The best way to control Claude Code, Codex and more from any computer or phone

main
ts 806 lines 27.8 KB
Raw
1 import { sha256 } from "@noble/hashes/sha2";
2 import JSZip from "jszip";
3 import { parse, type ParseError } from "jsonc-parser";
4 import { msg } from "gt-react";
5
6 import { m } from "./i18n/messages";
7 import type { ThemeDefinition } from "./themePalette";
8 import {
9 isVsCodeThemeFile,
10 pairVsCodeThemes,
11 parseVsCodeThemeFile,
12 resolveThemeLabelCollisions,
13 } from "./vscodeThemeImport";
14
15 const OPEN_VSX_SEARCH_URL = "https://open-vsx.org/api/-/search";
16 const MAX_VSIX_BYTES = 20 * 1024 * 1024;
17 const MAX_SEARCH_BYTES = 512 * 1024;
18 const MAX_DETAIL_BYTES = 256 * 1024;
19 const MAX_MANIFEST_BYTES = 256 * 1024;
20 const SEARCH_REQUEST_TIMEOUT_MS = 10_000;
21 const MAX_THEME_BYTES = 256 * 1024;
22 const MAX_ZIP_ENTRIES = 5_000;
23 const MAX_UNCOMPRESSED_BYTES = 100 * 1024 * 1024;
24 const MAX_COMPRESSION_RATIO = 200;
25 const MAX_THEMES_PER_EXTENSION = 40;
26 const MAX_INCLUDE_DEPTH = 8;
27 const MAX_PACKAGE_PATH_LENGTH = 1_024;
28 const MAX_COLOR_VALUE_LENGTH = 128;
29 const MAX_RESOLVED_THEME_FILES = MAX_THEMES_PER_EXTENSION * MAX_INCLUDE_DEPTH;
30 const SUPPORTED_LICENSES = new Set([
31 "0BSD",
32 "Apache-2.0",
33 "BSD-2-Clause",
34 "BSD-3-Clause",
35 "CC0-1.0",
36 "ISC",
37 "MIT",
38 "MPL-2.0",
39 "Unlicense",
40 ]);
41 const USED_WORKBENCH_COLORS = new Set([
42 "activityBar.background",
43 "activityBarBadge.background",
44 "badge.background",
45 "button.background",
46 "button.foreground",
47 "contrastBorder",
48 "descriptionForeground",
49 "disabledForeground",
50 "dropdown.background",
51 "dropdown.border",
52 "editor.background",
53 "editor.foreground",
54 "editor.findMatchBackground",
55 "editor.findMatchForeground",
56 "editor.findMatchHighlightBackground",
57 "editor.findMatchHighlightForeground",
58 "editor.selectionBackground",
59 "editorCursor.foreground",
60 "editorError.foreground",
61 "editorGroup.border",
62 "editorPane.background",
63 "editorWarning.foreground",
64 "editorWidget.background",
65 "errorForeground",
66 "focusBorder",
67 "foreground",
68 "input.border",
69 "input.placeholderForeground",
70 "list.activeSelectionBackground",
71 "list.hoverBackground",
72 "list.inactiveSelectionBackground",
73 "menu.background",
74 "panel.background",
75 "panel.border",
76 "progressBar.background",
77 "quickInput.background",
78 "scrollbarSlider.background",
79 "sideBar.background",
80 "sideBar.border",
81 "sideBar.foreground",
82 "terminal.background",
83 "terminal.foreground",
84 "terminal.selectionBackground",
85 "terminalCursor.foreground",
86 "textCodeBlock.background",
87 "textLink.foreground",
88 ]);
89
90 export type OpenVsxThemeSort = "downloadCount" | "rating" | "timestamp" | "relevance";
91
92 export type OpenVsxThemeExtension = {
93 id: string;
94 collectionId: string;
95 name: string;
96 publisher: string;
97 description: string;
98 downloadCount: number;
99 iconUrl: string | null;
100 sourceUrl: string | null;
101 manifestUrl: string;
102 sha256Url: string;
103 vsixUrl: string;
104 version: string;
105 license: string;
106 };
107
108 export type OpenVsxThemeSearchOptions = {
109 signal?: AbortSignal;
110 sortBy?: OpenVsxThemeSort;
111 };
112
113 type ThemeContribution = { label?: unknown; uiTheme?: unknown; path?: unknown };
114
115 function isRecord(value: unknown): value is Record<string, unknown> {
116 return typeof value === "object" && value !== null && !Array.isArray(value);
117 }
118
119 function shortHash(value: string): string {
120 return [...sha256(new TextEncoder().encode(value))]
121 .slice(0, 6)
122 .map((byte) => byte.toString(16).padStart(2, "0"))
123 .join("");
124 }
125
126 function openVsxThemeId(extensionId: string, source: string): string {
127 return `ovx-theme-${shortHash(`${extensionId}:${source}`)}`;
128 }
129
130 function openVsxCollectionId(extensionId: string): string {
131 const normalized = `open-vsx:${extensionId.toLowerCase()}`;
132 return /^[a-z0-9][a-z0-9.:-]{0,127}$/.test(normalized)
133 ? normalized
134 : `open-vsx:${shortHash(extensionId)}`;
135 }
136
137 function trustedOpenVsxUrl(value: unknown): string | null {
138 if (typeof value !== "string") return null;
139 try {
140 const url = new URL(value);
141 return url.protocol === "https:" && url.hostname.toLowerCase() === "open-vsx.org"
142 ? url.toString()
143 : null;
144 } catch {
145 return null;
146 }
147 }
148
149 function publicSourceUrl(value: unknown): string | null {
150 const rawValue =
151 typeof value === "string"
152 ? value
153 : isRecord(value) && typeof value.url === "string"
154 ? value.url
155 : null;
156 if (!rawValue) return null;
157 try {
158 const url = new URL(rawValue);
159 return url.protocol === "https:" && !url.username && !url.password ? url.toString() : null;
160 } catch {
161 return null;
162 }
163 }
164
165 function themeContributions(manifest: Record<string, unknown>): ThemeContribution[] {
166 const contributes = isRecord(manifest.contributes) ? manifest.contributes : null;
167 return Array.isArray(contributes?.themes)
168 ? (contributes.themes.filter(isRecord) as ThemeContribution[])
169 : [];
170 }
171
172 function manifestLicenseMatches(manifest: Record<string, unknown>, license: string): boolean {
173 return (
174 typeof manifest.license === "string" &&
175 manifest.license.trim().toLowerCase() === license.toLowerCase()
176 );
177 }
178
179 function extensionFromDetail(value: unknown): OpenVsxThemeExtension | null {
180 if (!isRecord(value) || !isRecord(value.files)) {
181 throw new Error(m(msg("Open VSX returned malformed theme details.")));
182 }
183 const namespace = typeof value.namespace === "string" ? value.namespace.trim() : "";
184 const extensionName = typeof value.name === "string" ? value.name.trim() : "";
185 const displayName =
186 (typeof value.displayName === "string" ? value.displayName.trim() : "") || extensionName;
187 const version = typeof value.version === "string" ? value.version.trim() : "";
188 const license = typeof value.license === "string" ? value.license.trim() : "";
189 const manifestUrl = trustedOpenVsxUrl(value.files.manifest);
190 const sha256Url = trustedOpenVsxUrl(value.files.sha256);
191 const vsixUrl = trustedOpenVsxUrl(value.files.download);
192 if (!namespace || !extensionName || !version || !manifestUrl || !sha256Url || !vsixUrl) {
193 throw new Error(m(msg("Open VSX returned malformed theme details.")));
194 }
195 if (!SUPPORTED_LICENSES.has(license)) return null;
196 const id = `${namespace}.${extensionName}`;
197 return {
198 id,
199 collectionId: openVsxCollectionId(id),
200 name: displayName,
201 publisher: namespace,
202 description: typeof value.description === "string" ? value.description : "",
203 downloadCount:
204 typeof value.downloadCount === "number" && Number.isFinite(value.downloadCount)
205 ? value.downloadCount
206 : 0,
207 iconUrl: trustedOpenVsxUrl(value.files.icon),
208 sourceUrl:
209 publicSourceUrl(value.repository) ??
210 publicSourceUrl(value.homepage) ??
211 publicSourceUrl(value.url),
212 manifestUrl,
213 sha256Url,
214 vsixUrl,
215 version,
216 license,
217 };
218 }
219
220 async function withSearchTimeout<T>(
221 operation: (signal: AbortSignal) => Promise<T>,
222 parentSignal?: AbortSignal,
223 ): Promise<T> {
224 const controller = new AbortController();
225 const abort = () => controller.abort();
226 if (parentSignal?.aborted) abort();
227 else parentSignal?.addEventListener("abort", abort, { once: true });
228 const timeout = setTimeout(abort, SEARCH_REQUEST_TIMEOUT_MS);
229 try {
230 return await operation(controller.signal);
231 } catch (cause) {
232 if (controller.signal.aborted && !parentSignal?.aborted) {
233 throw new Error(m(msg("Open VSX took too long to respond.")), { cause });
234 }
235 throw cause;
236 } finally {
237 clearTimeout(timeout);
238 parentSignal?.removeEventListener("abort", abort);
239 }
240 }
241
242 export async function searchOpenVsxThemes(
243 query: string,
244 { signal, sortBy = "downloadCount" }: OpenVsxThemeSearchOptions = {},
245 ): Promise<OpenVsxThemeExtension[]> {
246 const searchText = query.trim();
247 if (!searchText) return [];
248 const url = new URL(OPEN_VSX_SEARCH_URL);
249 url.searchParams.set("query", searchText);
250 url.searchParams.set("category", "Themes");
251 url.searchParams.set("sortBy", sortBy);
252 url.searchParams.set("sortOrder", "desc");
253 url.searchParams.set("size", "16");
254 const value = await withSearchTimeout(async (requestSignal) => {
255 const response = await fetch(url, { signal: requestSignal });
256 if (!response.ok) throw new Error(m(msg("Open VSX search is unavailable right now.")));
257 const searchBytes = await readCappedResponse(
258 response,
259 MAX_SEARCH_BYTES,
260 m(msg("Open VSX returned an unexpectedly large response.")),
261 );
262 try {
263 return JSON.parse(new TextDecoder().decode(searchBytes)) as unknown;
264 } catch {
265 throw new Error(m(msg("Open VSX returned an unreadable response.")));
266 }
267 }, signal);
268 if (!isRecord(value) || !Array.isArray(value.extensions)) {
269 throw new Error(m(msg("Open VSX returned an unreadable search response.")));
270 }
271 const identities = value.extensions.flatMap((candidate): Array<[string, string]> => {
272 if (!isRecord(candidate)) return [];
273 const namespace = typeof candidate.namespace === "string" ? candidate.namespace : "";
274 const name = typeof candidate.name === "string" ? candidate.name : "";
275 return namespace && name ? [[namespace, name]] : [];
276 });
277 const details = await Promise.allSettled(
278 identities.slice(0, 16).map(([namespace, name]) =>
279 withSearchTimeout(async (requestSignal) => {
280 const detailUrl = `https://open-vsx.org/api/${encodeURIComponent(namespace)}/${encodeURIComponent(name)}`;
281 const detailResponse = await fetch(detailUrl, { signal: requestSignal });
282 if (!detailResponse.ok) throw new Error(m(msg("Open VSX theme details are unavailable.")));
283 const detailBytes = await readCappedResponse(
284 detailResponse,
285 MAX_DETAIL_BYTES,
286 m(msg("Open VSX returned an unexpectedly large detail response.")),
287 );
288 try {
289 const extension = extensionFromDetail(JSON.parse(new TextDecoder().decode(detailBytes)));
290 if (!extension) return null;
291 const [manifestResponse, packageResponse] = await Promise.all([
292 fetch(extension.manifestUrl, { signal: requestSignal }),
293 fetch(extension.vsixUrl, { method: "HEAD", signal: requestSignal }),
294 ]);
295 if (!manifestResponse.ok) throw new Error("manifest unavailable");
296 if (!packageResponse.ok) return null;
297 const packageLength = Number(packageResponse.headers.get("content-length"));
298 if (Number.isFinite(packageLength) && packageLength > MAX_VSIX_BYTES) {
299 return null;
300 }
301 const manifestBytes = await readCappedResponse(
302 manifestResponse,
303 MAX_MANIFEST_BYTES,
304 m(msg("Open VSX returned an unexpectedly large manifest.")),
305 );
306 const manifest = parseJsoncObject(
307 new TextDecoder().decode(manifestBytes),
308 m(msg("Extension manifest")),
309 );
310 return themeContributions(manifest).length > 0 &&
311 manifestLicenseMatches(manifest, extension.license)
312 ? extension
313 : null;
314 } catch {
315 throw new Error(m(msg("Open VSX returned unreadable theme details.")));
316 }
317 }, signal),
318 ),
319 );
320 if (signal?.aborted) throw new DOMException("The operation was aborted.", "AbortError");
321 const completedDetails = details.filter((result) => result.status === "fulfilled");
322 if (identities.length > 0 && completedDetails.length === 0) {
323 throw new Error(m(msg("Open VSX theme details are unavailable right now.")));
324 }
325 return completedDetails.flatMap((result) => (result.value ? [result.value] : [])).slice(0, 8);
326 }
327
328 function parseJsoncObject(source: string, description: string): Record<string, unknown> {
329 const errors: ParseError[] = [];
330 const value: unknown = parse(source, errors, { allowTrailingComma: true });
331 if (errors.length > 0 || !isRecord(value))
332 throw new Error(m(msg("{description} is not valid JSON.", { description })));
333 return value;
334 }
335
336 function sanitizeThemeObject(value: Record<string, unknown>): Record<string, unknown> {
337 const colors: Record<string, string> = {};
338 if (isRecord(value.colors)) {
339 for (const [key, color] of Object.entries(value.colors)) {
340 if (
341 USED_WORKBENCH_COLORS.has(key) &&
342 typeof color === "string" &&
343 color.length <= MAX_COLOR_VALUE_LENGTH
344 ) {
345 colors[key] = color;
346 }
347 }
348 }
349 return {
350 ...(typeof value.include === "string" ? { include: value.include } : {}),
351 colors,
352 };
353 }
354
355 function normalizePackagePath(path: string, relativeTo = "extension/"): string {
356 if (
357 path.length > MAX_PACKAGE_PATH_LENGTH ||
358 path.includes("\0") ||
359 path.startsWith("/") ||
360 /^[a-zA-Z]:/.test(path)
361 ) {
362 throw new Error(m(msg("Theme path is not a safe relative package path.")));
363 }
364 const normalizedInput = path.replaceAll("\\", "/");
365 const baseSegments = relativeTo.split("/").slice(0, -1);
366 const segments = baseSegments;
367 for (const segment of normalizedInput.split("/")) {
368 if (!segment || segment === ".") continue;
369 if (segment === "..") {
370 if (segments.length <= 1)
371 throw new Error(m(msg("Theme path escapes the extension package.")));
372 segments.pop();
373 continue;
374 }
375 segments.push(segment);
376 }
377 if (segments[0] !== "extension") segments.unshift("extension");
378 return segments.join("/");
379 }
380
381 function contributionType(uiTheme: unknown): string | null {
382 if (uiTheme === "vs") return "light";
383 if (uiTheme === "vs-dark") return "dark";
384 if (uiTheme === "hc-black" || uiTheme === "hc-light") return uiTheme;
385 return null;
386 }
387
388 type ZipEntrySizes = {
389 uncompressedSize?: unknown;
390 };
391
392 type InspectableZipObject = JSZip.JSZipObject & {
393 _data?: ZipEntrySizes;
394 unsafeOriginalName?: string;
395 internalStream?: (type: "uint8array") => JSZip.JSZipStreamHelper<Uint8Array>;
396 };
397
398 const extensionPackageErrors = new WeakSet<Error>();
399
400 function extensionPackageError(message: string): Error {
401 const error = new Error(message);
402 extensionPackageErrors.add(error);
403 return error;
404 }
405
406 function inspectZipDirectory(bytes: Uint8Array): Uint8Array {
407 const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
408 const minimumOffset = Math.max(0, bytes.byteLength - 65_557);
409 let endOffset = bytes.byteLength - 22;
410 while (
411 endOffset >= minimumOffset &&
412 (view.getUint32(endOffset, true) !== 0x06054b50 ||
413 endOffset + 22 + view.getUint16(endOffset + 20, true) !== bytes.byteLength)
414 ) {
415 endOffset -= 1;
416 }
417 if (endOffset < minimumOffset)
418 throw extensionPackageError(m(msg("That extension package has no ZIP directory.")));
419
420 const directorySize = view.getUint32(endOffset + 12, true);
421 const directoryOffset = view.getUint32(endOffset + 16, true);
422 const directoryEnd = directoryOffset + directorySize;
423 if (directoryEnd !== endOffset || directoryEnd > bytes.byteLength) {
424 throw extensionPackageError(m(msg("That extension package has an invalid ZIP directory.")));
425 }
426
427 let entryCount = 0;
428 let totalUncompressed = 0;
429 let offset = directoryOffset;
430 while (offset < directoryEnd) {
431 if (offset + 46 > directoryEnd || view.getUint32(offset, true) !== 0x02014b50) {
432 throw extensionPackageError(m(msg("That extension package has an invalid ZIP directory.")));
433 }
434 entryCount += 1;
435 if (entryCount > MAX_ZIP_ENTRIES) {
436 throw extensionPackageError(m(msg("That extension package has too many files.")));
437 }
438 const compressed = view.getUint32(offset + 20, true);
439 const uncompressed = view.getUint32(offset + 24, true);
440 if (compressed === 0xffffffff || uncompressed === 0xffffffff) {
441 throw extensionPackageError(m(msg("That extension package has unsupported ZIP64 metadata.")));
442 }
443 totalUncompressed += uncompressed;
444 if (totalUncompressed > MAX_UNCOMPRESSED_BYTES) {
445 throw extensionPackageError(
446 m(msg("That extension package expands beyond the safe import limit.")),
447 );
448 }
449 if (
450 uncompressed > 0 &&
451 (compressed === 0 || uncompressed / compressed > MAX_COMPRESSION_RATIO)
452 ) {
453 throw extensionPackageError(
454 m(msg("That extension package has an unsafe compression ratio.")),
455 );
456 }
457 const nameLength = view.getUint16(offset + 28, true);
458 const extraLength = view.getUint16(offset + 30, true);
459 const commentLength = view.getUint16(offset + 32, true);
460 offset += 46 + nameLength + extraLength + commentLength;
461 }
462 if (offset !== directoryEnd)
463 throw extensionPackageError(m(msg("That extension package has an invalid ZIP directory.")));
464
465 const commentLength = view.getUint16(endOffset + 20, true);
466 if (commentLength === 0) return bytes;
467
468 // Strip ZIP comments; JSZip can mistake EOCD-like comment bytes for the real record.
469 const withoutComment = bytes.slice(0, endOffset + 22);
470 withoutComment[endOffset + 20] = 0;
471 withoutComment[endOffset + 21] = 0;
472 return withoutComment;
473 }
474
475 function inspectZip(zip: JSZip): void {
476 const entries = Object.values(zip.files) as InspectableZipObject[];
477 if (entries.length > MAX_ZIP_ENTRIES)
478 throw extensionPackageError(m(msg("That extension package has too many files.")));
479
480 for (const entry of entries) {
481 if (entry.unsafeOriginalName) normalizePackagePath(entry.unsafeOriginalName);
482 }
483 }
484
485 async function readZipText(
486 zip: JSZip,
487 path: string,
488 description: string,
489 signal?: AbortSignal,
490 ): Promise<string> {
491 signal?.throwIfAborted();
492 const file = zip.file(path) as InspectableZipObject | null;
493 if (!file)
494 throw new Error(
495 m(msg("{description} is missing from the extension package.", { description })),
496 );
497 if (typeof file._data?.uncompressedSize !== "number" || !file.internalStream) {
498 throw new Error(m(msg("{description} has unreadable size metadata.", { description })));
499 }
500 if (file._data.uncompressedSize > MAX_THEME_BYTES) {
501 throw new Error(m(msg("{description} is too large.", { description })));
502 }
503
504 return new Promise((resolve, reject) => {
505 const chunks: Uint8Array[] = [];
506 let byteLength = 0;
507 let settled = false;
508 const stream = file.internalStream!("uint8array");
509 const cleanup = () => signal?.removeEventListener("abort", handleAbort);
510 const handleAbort = () => {
511 if (settled) return;
512 settled = true;
513 stream.pause();
514 cleanup();
515 reject(signal?.reason);
516 };
517 signal?.addEventListener("abort", handleAbort, { once: true });
518 stream
519 .on("data", (chunk) => {
520 if (settled) return;
521 byteLength += chunk.byteLength;
522 if (byteLength > MAX_THEME_BYTES) {
523 settled = true;
524 stream.pause();
525 cleanup();
526 reject(new Error(m(msg("{description} is too large.", { description }))));
527 return;
528 }
529 chunks.push(chunk);
530 })
531 .on("error", (cause) => {
532 if (settled) return;
533 settled = true;
534 cleanup();
535 reject(cause);
536 })
537 .on("end", () => {
538 if (settled) return;
539 settled = true;
540 cleanup();
541 const bytes = new Uint8Array(byteLength);
542 let offset = 0;
543 for (const chunk of chunks) {
544 bytes.set(chunk, offset);
545 offset += chunk.byteLength;
546 }
547 resolve(new TextDecoder().decode(bytes));
548 })
549 .resume();
550 });
551 }
552
553 async function loadThemeObject(
554 zip: JSZip,
555 path: string,
556 cache: Map<string, Record<string, unknown>>,
557 budget: { files: number },
558 ancestors: ReadonlySet<string> = new Set(),
559 signal?: AbortSignal,
560 ): Promise<Record<string, unknown>> {
561 signal?.throwIfAborted();
562 if (ancestors.size >= MAX_INCLUDE_DEPTH)
563 throw new Error(m(msg("Theme includes are nested too deeply.")));
564 if (ancestors.has(path)) throw new Error(m(msg("Theme includes contain a cycle.")));
565 const cached = cache.get(path);
566 if (cached) return cached;
567 budget.files += 1;
568 if (budget.files > MAX_RESOLVED_THEME_FILES) {
569 throw new Error(m(msg("That extension references too many theme files.")));
570 }
571
572 const value = sanitizeThemeObject(
573 parseJsoncObject(await readZipText(zip, path, path, signal), path),
574 );
575 if (typeof value.include !== "string") {
576 cache.set(path, value);
577 return value;
578 }
579
580 const includePath = normalizePackagePath(value.include, path);
581 const nextAncestors = new Set(ancestors);
582 nextAncestors.add(path);
583 const base = await loadThemeObject(zip, includePath, cache, budget, nextAncestors, signal);
584 const resolved = {
585 ...base,
586 ...value,
587 colors: {
588 ...(isRecord(base.colors) ? base.colors : {}),
589 ...(isRecord(value.colors) ? value.colors : {}),
590 },
591 };
592 cache.set(path, resolved);
593 return resolved;
594 }
595
596 async function readCappedResponse(
597 response: Response,
598 limit: number,
599 tooLargeMessage: string,
600 ): Promise<Uint8Array> {
601 const contentLength = response.headers.get("content-length");
602 if (contentLength && Number(contentLength) > limit) throw new Error(tooLargeMessage);
603 if (!response.body) {
604 const bytes = new Uint8Array(await response.arrayBuffer());
605 if (bytes.byteLength > limit) throw new Error(tooLargeMessage);
606 return bytes;
607 }
608
609 const reader = response.body.getReader();
610 const chunks: Uint8Array[] = [];
611 let byteLength = 0;
612 try {
613 while (true) {
614 const { done, value } = await reader.read();
615 if (done) break;
616 byteLength += value.byteLength;
617 if (byteLength > limit) {
618 await reader.cancel();
619 throw new Error(tooLargeMessage);
620 }
621 chunks.push(value);
622 }
623 } finally {
624 reader.releaseLock();
625 }
626
627 const result = new Uint8Array(byteLength);
628 let offset = 0;
629 for (const chunk of chunks) {
630 result.set(chunk, offset);
631 offset += chunk.byteLength;
632 }
633 return result;
634 }
635
636 async function fetchPackage(url: string, signal?: AbortSignal): Promise<Uint8Array> {
637 const response = await fetch(url, signal ? { signal } : {});
638 if (!response.ok) throw new Error(m(msg("That Open VSX theme could not be downloaded.")));
639 return readCappedResponse(
640 response,
641 MAX_VSIX_BYTES,
642 m(msg("That theme extension is too large to import safely.")),
643 );
644 }
645
646 export async function importOpenVsxThemeExtension(
647 extension: OpenVsxThemeExtension,
648 signal?: AbortSignal,
649 ): Promise<ReadonlyArray<ThemeDefinition>> {
650 const manifestResponse = await fetch(extension.manifestUrl, signal ? { signal } : {});
651 if (!manifestResponse.ok)
652 throw new Error(m(msg("That Open VSX extension has no readable manifest.")));
653 const manifestBytes = await readCappedResponse(
654 manifestResponse,
655 MAX_MANIFEST_BYTES,
656 m(msg("That Open VSX extension manifest is too large.")),
657 );
658 const manifest = parseJsoncObject(
659 new TextDecoder().decode(manifestBytes),
660 m(msg("Extension manifest")),
661 );
662 const advertisedContributions = themeContributions(manifest);
663 if (advertisedContributions.length === 0) {
664 throw new Error(m(msg("That extension does not contain color themes.")));
665 }
666 if (advertisedContributions.length > MAX_THEMES_PER_EXTENSION) {
667 throw new Error(m(msg("That extension contains too many color themes to import safely.")));
668 }
669
670 const packageBytes = await fetchPackage(extension.vsixUrl, signal);
671 signal?.throwIfAborted();
672 const checksumResponse = await fetch(extension.sha256Url, signal ? { signal } : {});
673 if (!checksumResponse.ok)
674 throw new Error(m(msg("That Open VSX theme has no readable checksum.")));
675 const expectedChecksum = new TextDecoder()
676 .decode(
677 await readCappedResponse(
678 checksumResponse,
679 256,
680 m(msg("That Open VSX checksum response is invalid.")),
681 ),
682 )
683 .trim()
684 .split(/\s+/)[0];
685 if (!expectedChecksum || !/^[a-f\d]{64}$/i.test(expectedChecksum)) {
686 throw new Error(m(msg("That Open VSX theme has an invalid checksum.")));
687 }
688 signal?.throwIfAborted();
689 const actualChecksum = [...sha256(packageBytes)]
690 .map((byte) => byte.toString(16).padStart(2, "0"))
691 .join("");
692 if (actualChecksum.toLowerCase() !== expectedChecksum.toLowerCase()) {
693 throw new Error(m(msg("That Open VSX theme failed its integrity check.")));
694 }
695 signal?.throwIfAborted();
696 let zip: JSZip;
697 try {
698 const inspectedPackageBytes = inspectZipDirectory(packageBytes);
699 zip = await JSZip.loadAsync(inspectedPackageBytes);
700 signal?.throwIfAborted();
701 inspectZip(zip);
702 } catch (cause) {
703 if (signal?.aborted) signal.throwIfAborted();
704 if (cause instanceof Error && extensionPackageErrors.has(cause)) throw cause;
705 throw new Error(m(msg("That Open VSX extension package could not be opened.")), { cause });
706 }
707
708 const packagedManifest = parseJsoncObject(
709 await readZipText(zip, "extension/package.json", m(msg("Extension manifest")), signal),
710 m(msg("Extension manifest")),
711 );
712 if (
713 typeof packagedManifest.publisher !== "string" ||
714 packagedManifest.publisher.toLowerCase() !== extension.publisher.toLowerCase() ||
715 typeof packagedManifest.name !== "string" ||
716 `${packagedManifest.publisher}.${packagedManifest.name}`.toLowerCase() !==
717 extension.id.toLowerCase() ||
718 packagedManifest.version !== extension.version
719 ) {
720 throw new Error(m(msg("That extension package does not match the selected Open VSX theme.")));
721 }
722 if (!manifestLicenseMatches(packagedManifest, extension.license)) {
723 throw new Error(m(msg("That extension package does not match its advertised license.")));
724 }
725 const contributions = themeContributions(packagedManifest);
726 if (contributions.length === 0)
727 throw new Error(m(msg("That extension does not contain color themes.")));
728 if (contributions.length > MAX_THEMES_PER_EXTENSION) {
729 throw new Error(m(msg("That extension contains too many color themes to import safely.")));
730 }
731
732 const parsed: Array<{ theme: ThemeDefinition; sourceName: string; sourcePath: string }> = [];
733 const failures: string[] = [];
734 const themeCache = new Map<string, Record<string, unknown>>();
735 const themeBudget = { files: 0 };
736 for (const contribution of contributions) {
737 signal?.throwIfAborted();
738 if (typeof contribution.path !== "string") {
739 failures.push("theme path is missing");
740 continue;
741 }
742 try {
743 const path = normalizePackagePath(contribution.path);
744 const themeValue = await loadThemeObject(
745 zip,
746 path,
747 themeCache,
748 themeBudget,
749 new Set(),
750 signal,
751 );
752 const type = contributionType(contribution.uiTheme);
753 const label =
754 typeof contribution.label === "string" && contribution.label.trim()
755 ? contribution.label.trim()
756 : extension.name;
757 const decorated = {
758 ...themeValue,
759 displayName: label,
760 ...(type ? { type } : {}),
761 };
762 if (!isVsCodeThemeFile(decorated)) throw new Error("not a VS Code color theme");
763 parsed.push({
764 theme: parseVsCodeThemeFile(decorated),
765 sourceName: path.split("/").at(-1)!,
766 sourcePath: path,
767 });
768 } catch (cause) {
769 signal?.throwIfAborted();
770 failures.push(cause instanceof Error ? cause.message : "theme could not be read");
771 }
772 }
773 if (failures.length > 0) {
774 throw new Error(
775 m(msg("One or more color themes in that extension could not be imported safely.")),
776 );
777 }
778 if (parsed.length === 0) {
779 throw new Error(m(msg("That extension has no compatible color themes.")));
780 }
781 const extensionId = extension.id.toLowerCase();
782 const sourcePathCounts = new Map<string, number>();
783 for (const { sourcePath } of parsed) {
784 sourcePathCounts.set(sourcePath, (sourcePathCounts.get(sourcePath) ?? 0) + 1);
785 }
786 const sourcePathOccurrences = new Map<string, number>();
787 const sourceIdentities = parsed.map(({ sourcePath }) => {
788 if (sourcePathCounts.get(sourcePath) === 1) return sourcePath;
789 const occurrence = sourcePathOccurrences.get(sourcePath) ?? 0;
790 sourcePathOccurrences.set(sourcePath, occurrence + 1);
791 return occurrence === 0 ? sourcePath : `${sourcePath}\0${occurrence}`;
792 });
793 const resolved = resolveThemeLabelCollisions(parsed).map((theme, index) => ({
794 ...theme,
795 id: openVsxThemeId(extensionId, sourceIdentities[index]!),
796 }));
797 const paired = pairVsCodeThemes(resolved, {
798 pairedId: (light, dark) => openVsxThemeId(extensionId, [light.id, dark.id].sort().join(":")),
799 });
800 const themes = resolveThemeLabelCollisions(paired.map((theme) => ({ theme })));
801 const collection = {
802 id: extension.collectionId,
803 label: extension.name.slice(0, 48),
804 };
805 return themes.map((theme) => ({ ...theme, collection }));
806 }