Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

openVsxThemes.ts

776 lines26.9 KB

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