Open History to see the last commit
1import { sha256 } from "@noble/hashes/sha2";
2import JSZip from "jszip";
3import { afterEach, describe, expect, it, vi } from "vite-plus/test";
4
5import {
6 importOpenVsxThemeExtension,
7 searchOpenVsxThemes,
8 type OpenVsxThemeExtension,
9} from "./openVsxThemes";
10import { getThemeColorsForMode, themeColorToHex } from "./themePalette";
11
12const ASSET_ROOT = "https://open-vsx.org/api/demo/theme/1.0.0/file";
13
14function extensionDetail(overrides: Record<string, unknown> = {}) {
15 return {
16 namespace: "demo",
17 name: "theme",
18 displayName: "Demo Theme",
19 description: "A nice theme",
20 version: "1.0.0",
21 downloadCount: 123456,
22 license: "MIT",
23 repository: "https://github.com/demo/theme",
24 files: {
25 icon: `${ASSET_ROOT}/icon.png`,
26 manifest: `${ASSET_ROOT}/package.json`,
27 sha256: `${ASSET_ROOT}/demo.theme-1.0.0.sha256`,
28 download: `${ASSET_ROOT}/demo.theme-1.0.0.vsix`,
29 },
30 ...overrides,
31 };
32}
33
34afterEach(() => {
35 vi.useRealTimers();
36 vi.unstubAllGlobals();
37});
38
39describe("Open VSX themes", () => {
40 it("searches theme extensions and keeps only supported open-source licenses", async () => {
41 const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
42 const url = String(input);
43 if (url.includes("/-/search?")) {
44 return new Response(
45 JSON.stringify({
46 extensions: [
47 { namespace: "demo", name: "theme" },
48 { namespace: "icons", name: "theme" },
49 { namespace: "oversized", name: "theme" },
50 { namespace: "unlicensed", name: "theme" },
51 { namespace: "unavailable", name: "theme" },
52 { namespace: "closed", name: "theme" },
53 { namespace: "huge", name: "theme" },
54 ],
55 }),
56 { status: 200 },
57 );
58 }
59 if (url.endsWith("/icons/theme")) {
60 return new Response(
61 JSON.stringify(
62 extensionDetail({
63 namespace: "icons",
64 files: {
65 ...extensionDetail().files,
66 manifest: `${ASSET_ROOT.replace("demo/theme", "icons/theme")}/package.json`,
67 },
68 }),
69 ),
70 { status: 200 },
71 );
72 }
73 if (url.endsWith("/oversized/theme")) {
74 return new Response(
75 JSON.stringify(
76 extensionDetail({
77 namespace: "oversized",
78 files: {
79 ...extensionDetail().files,
80 download: `${ASSET_ROOT.replace("demo/theme", "oversized/theme")}/oversized.vsix`,
81 },
82 }),
83 ),
84 { status: 200 },
85 );
86 }
87 if (url.endsWith("/unlicensed/theme")) {
88 return new Response(
89 JSON.stringify(
90 extensionDetail({
91 namespace: "unlicensed",
92 files: {
93 ...extensionDetail().files,
94 manifest: `${ASSET_ROOT.replace("demo/theme", "unlicensed/theme")}/package.json`,
95 },
96 }),
97 ),
98 { status: 200 },
99 );
100 }
101 if (url.endsWith("/unavailable/theme")) {
102 return new Response(
103 JSON.stringify(
104 extensionDetail({
105 namespace: "unavailable",
106 files: {
107 ...extensionDetail().files,
108 download: `${ASSET_ROOT.replace("demo/theme", "unavailable/theme")}/unavailable.vsix`,
109 manifest: `${ASSET_ROOT.replace("demo/theme", "unavailable/theme")}/package.json`,
110 },
111 }),
112 ),
113 { status: 200 },
114 );
115 }
116 if (url.endsWith("/closed/theme")) {
117 return new Response(
118 JSON.stringify(extensionDetail({ namespace: "closed", license: "All Rights Reserved" })),
119 { status: 200 },
120 );
121 }
122 if (url.endsWith("/huge/theme")) {
123 return new Response(JSON.stringify({ padding: "x".repeat(256 * 1024) }), { status: 200 });
124 }
125 if (url.endsWith("/oversized/theme/1.0.0/file/oversized.vsix")) {
126 return new Response(null, {
127 headers: { "content-length": String(20 * 1024 * 1024 + 1) },
128 status: 200,
129 });
130 }
131 if (url.endsWith("/unavailable/theme/1.0.0/file/unavailable.vsix")) {
132 return new Response(null, { status: 404 });
133 }
134 if (url.endsWith(".vsix")) {
135 return new Response(null, { headers: { "content-length": "1024" }, status: 200 });
136 }
137 if (url.endsWith("/icons/theme/1.0.0/file/package.json")) {
138 return new Response(JSON.stringify({ contributes: { iconThemes: [{}] } }), { status: 200 });
139 }
140 if (url.endsWith("/unlicensed/theme/1.0.0/file/package.json")) {
141 return new Response(
142 JSON.stringify({ contributes: { themes: [{ path: "./theme.json" }] } }),
143 { status: 200 },
144 );
145 }
146 if (url.endsWith("/unavailable/theme/1.0.0/file/package.json")) {
147 return new Response(
148 JSON.stringify({ license: "MIT", contributes: { themes: [{ path: "./theme.json" }] } }),
149 { status: 200 },
150 );
151 }
152 if (url.endsWith("/demo/theme/1.0.0/file/package.json")) {
153 return new Response(
154 JSON.stringify({ license: "MIT", contributes: { themes: [{ path: "./theme.json" }] } }),
155 { status: 200 },
156 );
157 }
158 return new Response(JSON.stringify(extensionDetail()), { status: 200 });
159 });
160 vi.stubGlobal("fetch", fetchMock);
161
162 const results = await searchOpenVsxThemes(" dracula ");
163
164 expect(results).toEqual([
165 expect.objectContaining({
166 id: "demo.theme",
167 name: "Demo Theme",
168 publisher: "demo",
169 downloadCount: 123456,
170 iconUrl: `${ASSET_ROOT}/icon.png`,
171 sourceUrl: "https://github.com/demo/theme",
172 license: "MIT",
173 }),
174 ]);
175 const searchUrl = new URL(String(fetchMock.mock.calls[0]![0]));
176 expect(searchUrl.searchParams.get("query")).toBe("dracula");
177 expect(searchUrl.searchParams.get("category")).toBe("Themes");
178 expect(searchUrl.searchParams.get("sortBy")).toBe("downloadCount");
179 expect(searchUrl.searchParams.get("sortOrder")).toBe("desc");
180 expect(searchUrl.searchParams.get("size")).toBe("16");
181 });
182
183 it("supports sorting theme searches", async () => {
184 const fetchMock = vi.fn(
185 async (..._args: unknown[]) =>
186 new Response(JSON.stringify({ extensions: [] }), { status: 200 }),
187 );
188 vi.stubGlobal("fetch", fetchMock);
189
190 await searchOpenVsxThemes("nord", { sortBy: "rating" });
191
192 const searchUrl = new URL(String(fetchMock.mock.calls[0]![0]));
193 expect(searchUrl.searchParams.get("sortBy")).toBe("rating");
194 expect(searchUrl.searchParams.get("sortOrder")).toBe("desc");
195 });
196
197 it("rejects malformed search responses", async () => {
198 vi.stubGlobal(
199 "fetch",
200 vi.fn(async () => new Response(JSON.stringify({ error: "unavailable" }), { status: 200 })),
201 );
202
203 await expect(searchOpenVsxThemes("nord")).rejects.toThrow(
204 "Open VSX returned an unreadable search response.",
205 );
206 });
207
208 it("reports an unavailable search when every detail request fails", async () => {
209 vi.stubGlobal(
210 "fetch",
211 vi.fn(async (input: RequestInfo | URL) => {
212 if (String(input).includes("/-/search?")) {
213 return new Response(
214 JSON.stringify({ extensions: [{ namespace: "demo", name: "theme" }] }),
215 { status: 200 },
216 );
217 }
218 return new Response(null, { status: 429 });
219 }),
220 );
221
222 await expect(searchOpenVsxThemes("dracula")).rejects.toThrow(
223 "Open VSX theme details are unavailable",
224 );
225 });
226
227 it("reports an unavailable search when every detail response is malformed", async () => {
228 vi.stubGlobal(
229 "fetch",
230 vi.fn(async (input: RequestInfo | URL) => {
231 if (String(input).includes("/-/search?")) {
232 return new Response(
233 JSON.stringify({ extensions: [{ namespace: "demo", name: "theme" }] }),
234 { status: 200 },
235 );
236 }
237 return new Response("{}", { status: 200 });
238 }),
239 );
240
241 await expect(searchOpenVsxThemes("dracula")).rejects.toThrow(
242 "Open VSX theme details are unavailable",
243 );
244 });
245
246 it("returns no results when every theme package is unavailable", async () => {
247 vi.stubGlobal(
248 "fetch",
249 vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
250 const url = String(input);
251 if (url.includes("/-/search?")) {
252 return new Response(
253 JSON.stringify({ extensions: [{ namespace: "demo", name: "theme" }] }),
254 { status: 200 },
255 );
256 }
257 if (url.endsWith("/demo/theme")) {
258 return new Response(JSON.stringify(extensionDetail()), { status: 200 });
259 }
260 if (init?.method === "HEAD") return new Response(null, { status: 404 });
261 return new Response(
262 JSON.stringify({ license: "MIT", contributes: { themes: [{ path: "./theme.json" }] } }),
263 { status: 200 },
264 );
265 }),
266 );
267
268 await expect(searchOpenVsxThemes("dracula")).resolves.toEqual([]);
269 });
270
271 it("times out a stalled search request", async () => {
272 vi.useFakeTimers();
273 vi.stubGlobal(
274 "fetch",
275 vi.fn(
276 (_input: RequestInfo | URL, init?: RequestInit) =>
277 new Promise<Response>((_resolve, reject) => {
278 init?.signal?.addEventListener("abort", () => {
279 reject(new DOMException("The operation was aborted.", "AbortError"));
280 });
281 }),
282 ),
283 );
284
285 const search = expect(searchOpenVsxThemes("dracula")).rejects.toThrow(
286 "Open VSX took too long to respond",
287 );
288 await vi.advanceTimersByTimeAsync(10_000);
289
290 await search;
291 });
292
293 it("downloads a verified VSIX, reads JSONC includes, and pairs contributed variants", async () => {
294 const zip = new JSZip();
295 zip.file("extension/.gitkeep", "");
296 for (let index = 0; index < 3_000; index += 1) {
297 zip.file(`extension/node_modules/package-${index}.js`, "");
298 }
299 zip.file(
300 "extension/themes/base.jsonc",
301 `{
302 // inherited workbench colors
303 "colors": {
304 "editor.foreground": "#eeeeee",
305 "focusBorder": "#8b5cf6",
306 "editor.findMatchBackground": "#663399",
307 "editor.findMatchForeground": "#ffffff",
308 "editor.findMatchHighlightBackground": "#445566",
309 "editor.findMatchHighlightForeground": "#ffffff",
310 },
311 }`,
312 );
313 zip.file(
314 "extension/themes/demo-dark.json",
315 `{
316 "include": "./base.jsonc",
317 "colors": {
318 "editor.background": "#111111",
319 "editor.findMatchHighlightBackground": "#ffffff20"
320 }
321 }`,
322 );
323 zip.file(
324 "extension/themes/demo-light.json",
325 `{
326 "colors": {
327 "editor.background": "#fafafa",
328 "editor.foreground": "#222222",
329 "focusBorder": "#8b5cf6",
330 "editor.findMatchBackground": "#335577",
331 "editor.findMatchForeground": "#ffffff",
332 "editor.findMatchHighlightBackground": "#bbddff",
333 "editor.findMatchHighlightForeground": "#112233"
334 }
335 }`,
336 );
337 zip.file(
338 "extension/themes/demo.json",
339 `{
340 "colors": {
341 "editor.background": "#181818",
342 "editor.foreground": "#eeeeee"
343 }
344 }`,
345 );
346 const packagedManifest = {
347 publisher: "demo",
348 name: "theme",
349 version: "1.0.0",
350 license: "MIT",
351 contributes: {
352 themes: [
353 { label: "Demo Dark", uiTheme: "vs-dark", path: "./themes/demo-dark.json" },
354 { label: "Demo Light", uiTheme: "vs", path: "./themes/demo-light.json" },
355 { label: "Demo", uiTheme: "vs-dark", path: "./themes/demo.json" },
356 ],
357 },
358 };
359 let packageBytes = new ArrayBuffer(0);
360 let checksum = "";
361 const rebuildPackage = async () => {
362 zip.file("extension/package.json", JSON.stringify(packagedManifest));
363 packageBytes = await zip.generateAsync({
364 type: "arraybuffer",
365 comment: `PK\u0005\u0006${"x".repeat(26)}`,
366 });
367 checksum = [...sha256(new Uint8Array(packageBytes))]
368 .map((byte) => byte.toString(16).padStart(2, "0"))
369 .join("");
370 };
371 await rebuildPackage();
372 const manifest = {
373 contributes: { themes: [{ label: "Wrong", path: "./themes/missing.json" }] },
374 };
375 const extension: OpenVsxThemeExtension = {
376 collectionId: "open-vsx:demo.theme",
377 id: "demo.theme",
378 name: "Demo Theme",
379 publisher: "demo",
380 description: "",
381 downloadCount: 1,
382 iconUrl: null,
383 sourceUrl: null,
384 license: "MIT",
385 manifestUrl: `${ASSET_ROOT}/package.json`,
386 sha256Url: `${ASSET_ROOT}/demo.theme-1.0.0.sha256`,
387 version: "1.0.0",
388 vsixUrl: `${ASSET_ROOT}/demo.theme-1.0.0.vsix`,
389 };
390 vi.stubGlobal(
391 "fetch",
392 vi.fn(async (input: string | URL | Request) => {
393 const url = String(input);
394 if (url === extension.manifestUrl) {
395 return new Response(JSON.stringify(manifest), { status: 200 });
396 }
397 if (url === extension.sha256Url) return new Response(`${checksum} demo.vsix`);
398 return new Response(packageBytes, {
399 status: 200,
400 headers: { "Content-Length": String(packageBytes.byteLength) },
401 });
402 }),
403 );
404
405 const themes = await importOpenVsxThemeExtension(extension);
406
407 expect(themes).toHaveLength(2);
408 expect(new Set(themes.map((theme) => theme.id)).size).toBe(2);
409 expect(themes.every((theme) => /^ovx-[a-z0-9-]+-[0-9a-f]{12}$/.test(theme.id))).toBe(true);
410 expect(themes.every((theme) => theme.collection?.id === "open-vsx:demo.theme")).toBe(true);
411 const paired = themes.find(
412 (theme) =>
413 getThemeColorsForMode(theme, "light") !== null &&
414 getThemeColorsForMode(theme, "dark") !== null,
415 )!;
416 expect(paired.label).toBe("Demo");
417 expect(themeColorToHex(paired.colors.canvas)).toBe("#fafafa");
418 expect(themeColorToHex(getThemeColorsForMode(paired, "dark")!.canvas)).toBe("#111111");
419 expect(themeColorToHex(getThemeColorsForMode(paired, "dark")!.text)).toBe("#eeeeee");
420 const darkColors = getThemeColorsForMode(paired, "dark")!;
421 expect(themeColorToHex(darkColors.searchMatchActiveBackground)).toBe("#663399");
422 expect(themeColorToHex(darkColors.searchMatchActiveForeground)).toBe("#ffffff");
423 expect(themeColorToHex(darkColors.searchMatchBackground)).toBe("#2f2f2f");
424 expect(themeColorToHex(darkColors.searchMatchForeground)).toBe("#ffffff");
425 expect(themeColorToHex(paired.colors.searchMatchActiveBackground)).toBe("#335577");
426 expect(themeColorToHex(paired.colors.searchMatchActiveForeground)).toBe("#ffffff");
427 expect(themeColorToHex(paired.colors.searchMatchBackground)).toBe("#bbddff");
428 expect(themeColorToHex(paired.colors.searchMatchForeground)).toBe("#112233");
429
430 packagedManifest.contributes.themes[0]!.label = "Renamed Dark";
431 packagedManifest.contributes.themes[1]!.label = "Renamed Light";
432 packagedManifest.contributes.themes[2]!.label = "Renamed Solo";
433 await rebuildPackage();
434 const renamedThemes = await importOpenVsxThemeExtension(extension);
435 expect(renamedThemes.map((theme) => theme.id)).toEqual(themes.map((theme) => theme.id));
436
437 packagedManifest.contributes.themes.push({
438 label: "Duplicate Demo",
439 uiTheme: "vs-dark",
440 path: "./themes/demo.json",
441 });
442 await rebuildPackage();
443 const duplicatePathThemes = await importOpenVsxThemeExtension(extension);
444 expect(new Set(duplicatePathThemes.map((theme) => theme.id)).size).toBe(
445 duplicatePathThemes.length,
446 );
447 expect(themes.every(({ id }) => duplicatePathThemes.some((theme) => theme.id === id))).toBe(
448 true,
449 );
450 packagedManifest.contributes.themes.pop();
451
452 packagedManifest.contributes.themes[2]!.path = "./themes/missing.json";
453 await rebuildPackage();
454 await expect(importOpenVsxThemeExtension(extension)).rejects.toThrow(
455 "could not be imported safely",
456 );
457 packagedManifest.contributes.themes[2]!.path = "./themes/demo.json";
458
459 packagedManifest.license = "Proprietary";
460 await rebuildPackage();
461 await expect(importOpenVsxThemeExtension(extension)).rejects.toThrow(
462 "does not match its advertised license",
463 );
464
465 Reflect.deleteProperty(packagedManifest, "license");
466 await rebuildPackage();
467 await expect(importOpenVsxThemeExtension(extension)).rejects.toThrow(
468 "does not match its advertised license",
469 );
470 });
471
472 it("stops import work when the request is cancelled", async () => {
473 const packageBytes = new Uint8Array([1, 2, 3]);
474 const checksum = [...sha256(packageBytes)]
475 .map((byte) => byte.toString(16).padStart(2, "0"))
476 .join("");
477 const controller = new AbortController();
478 const extension: OpenVsxThemeExtension = {
479 collectionId: "open-vsx:demo.theme",
480 id: "demo.theme",
481 name: "Demo Theme",
482 publisher: "demo",
483 description: "",
484 downloadCount: 1,
485 iconUrl: null,
486 sourceUrl: null,
487 license: "MIT",
488 manifestUrl: `${ASSET_ROOT}/package.json`,
489 sha256Url: `${ASSET_ROOT}/demo.theme-1.0.0.sha256`,
490 version: "1.0.0",
491 vsixUrl: `${ASSET_ROOT}/demo.theme-1.0.0.vsix`,
492 };
493 vi.stubGlobal(
494 "fetch",
495 vi.fn(async (input: string | URL | Request) => {
496 const url = String(input);
497 if (url === extension.manifestUrl) {
498 return new Response(
499 JSON.stringify({ contributes: { themes: [{ path: "./theme.json" }] } }),
500 );
501 }
502 if (url === extension.sha256Url) {
503 controller.abort();
504 return new Response(checksum);
505 }
506 return new Response(packageBytes);
507 }),
508 );
509
510 await expect(importOpenVsxThemeExtension(extension, controller.signal)).rejects.toMatchObject({
511 name: "AbortError",
512 });
513 });
514
515 it("rejects a package whose Open VSX checksum does not match", async () => {
516 const extension: OpenVsxThemeExtension = {
517 collectionId: "open-vsx:demo.theme",
518 id: "demo.theme",
519 name: "Demo Theme",
520 publisher: "demo",
521 description: "",
522 downloadCount: 1,
523 iconUrl: null,
524 sourceUrl: null,
525 license: "MIT",
526 manifestUrl: `${ASSET_ROOT}/package.json`,
527 sha256Url: `${ASSET_ROOT}/demo.theme-1.0.0.sha256`,
528 version: "1.0.0",
529 vsixUrl: `${ASSET_ROOT}/demo.theme-1.0.0.vsix`,
530 };
531 vi.stubGlobal(
532 "fetch",
533 vi.fn(async (input: string | URL | Request) => {
534 const url = String(input);
535 if (url === extension.manifestUrl) {
536 return new Response(
537 JSON.stringify({ contributes: { themes: [{ path: "./theme.json" }] } }),
538 );
539 }
540 if (url === extension.sha256Url) return new Response("0".repeat(64));
541 return new Response(new Uint8Array([1, 2, 3]));
542 }),
543 );
544
545 await expect(importOpenVsxThemeExtension(extension)).rejects.toThrow("integrity check");
546 });
547});