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

openVsxThemes.test.ts

526 lines17.6 KB

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 };
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 zip.file(
297 "extension/themes/base.jsonc",
298 `{
299 // inherited workbench colors
300 "colors": {
301 "editor.foreground": "#eeeeee",
302 "focusBorder": "#8b5cf6",
303 },
304 }`,
305 );
306 zip.file(
307 "extension/themes/demo-dark.json",
308 `{
309 "include": "./base.jsonc",
310 "colors": { "editor.background": "#111111" }
311 }`,
312 );
313 zip.file(
314 "extension/themes/demo-light.json",
315 `{
316 "colors": {
317 "editor.background": "#fafafa",
318 "editor.foreground": "#222222",
319 "focusBorder": "#8b5cf6"
320 }
321 }`,
322 );
323 zip.file(
324 "extension/themes/demo.json",
325 `{
326 "colors": {
327 "editor.background": "#181818",
328 "editor.foreground": "#eeeeee"
329 }
330 }`,
331 );
332 const packagedManifest = {
333 publisher: "demo",
334 name: "theme",
335 version: "1.0.0",
336 license: "MIT",
337 contributes: {
338 themes: [
339 { label: "Demo Dark", uiTheme: "vs-dark", path: "./themes/demo-dark.json" },
340 { label: "Demo Light", uiTheme: "vs", path: "./themes/demo-light.json" },
341 { label: "Demo", uiTheme: "vs-dark", path: "./themes/demo.json" },
342 ],
343 },
344 };
345 let packageBytes = new ArrayBuffer(0);
346 let checksum = "";
347 const rebuildPackage = async () => {
348 zip.file("extension/package.json", JSON.stringify(packagedManifest));
349 packageBytes = await zip.generateAsync({
350 type: "arraybuffer",
351 comment: `PK\u0005\u0006${"x".repeat(26)}`,
352 });
353 checksum = [...sha256(new Uint8Array(packageBytes))]
354 .map((byte) => byte.toString(16).padStart(2, "0"))
355 .join("");
356 };
357 await rebuildPackage();
358 // The public manifest is only a preflight hint. Imports must use the manifest
359 // inside the checksummed VSIX rather than this inconsistent contribution.
360 const manifest = {
361 contributes: { themes: [{ label: "Wrong", path: "./themes/missing.json" }] },
362 };
363 const extension: OpenVsxThemeExtension = {
364 collectionId: "open-vsx:demo.theme",
365 id: "demo.theme",
366 name: "Demo Theme",
367 publisher: "demo",
368 description: "",
369 downloadCount: 1,
370 iconUrl: null,
371 sourceUrl: null,
372 license: "MIT",
373 manifestUrl: `${ASSET_ROOT}/package.json`,
374 sha256Url: `${ASSET_ROOT}/demo.theme-1.0.0.sha256`,
375 version: "1.0.0",
376 vsixUrl: `${ASSET_ROOT}/demo.theme-1.0.0.vsix`,
377 };
378 vi.stubGlobal(
379 "fetch",
380 vi.fn(async (input: string | URL | Request) => {
381 const url = String(input);
382 if (url === extension.manifestUrl) {
383 return new Response(JSON.stringify(manifest), { status: 200 });
384 }
385 if (url === extension.sha256Url) return new Response(`${checksum} demo.vsix`);
386 return new Response(packageBytes, {
387 status: 200,
388 headers: { "Content-Length": String(packageBytes.byteLength) },
389 });
390 }),
391 );
392​
393 const themes = await importOpenVsxThemeExtension(extension);
394​
395 expect(themes).toHaveLength(2);
396 expect(new Set(themes.map((theme) => theme.id)).size).toBe(2);
397 expect(themes.every((theme) => /^ovx-[a-z0-9-]+-[0-9a-f]{12}$/.test(theme.id))).toBe(true);
398 expect(themes.every((theme) => theme.collection?.id === "open-vsx:demo.theme")).toBe(true);
399 const paired = themes.find(
400 (theme) =>
401 getThemeColorsForMode(theme, "light") !== null &&
402 getThemeColorsForMode(theme, "dark") !== null,
403 )!;
404 expect(paired.label).toBe("Demo");
405 expect(themeColorToHex(paired.colors.canvas)).toBe("#fafafa");
406 expect(themeColorToHex(getThemeColorsForMode(paired, "dark")!.canvas)).toBe("#111111");
407 expect(themeColorToHex(getThemeColorsForMode(paired, "dark")!.text)).toBe("#eeeeee");
408​
409 packagedManifest.contributes.themes[0]!.label = "Renamed Dark";
410 packagedManifest.contributes.themes[1]!.label = "Renamed Light";
411 packagedManifest.contributes.themes[2]!.label = "Renamed Solo";
412 await rebuildPackage();
413 const renamedThemes = await importOpenVsxThemeExtension(extension);
414 expect(renamedThemes.map((theme) => theme.id)).toEqual(themes.map((theme) => theme.id));
415​
416 packagedManifest.contributes.themes.push({
417 label: "Duplicate Demo",
418 uiTheme: "vs-dark",
419 path: "./themes/demo.json",
420 });
421 await rebuildPackage();
422 const duplicatePathThemes = await importOpenVsxThemeExtension(extension);
423 expect(new Set(duplicatePathThemes.map((theme) => theme.id)).size).toBe(
424 duplicatePathThemes.length,
425 );
426 expect(themes.every(({ id }) => duplicatePathThemes.some((theme) => theme.id === id))).toBe(
427 true,
428 );
429 packagedManifest.contributes.themes.pop();
430​
431 packagedManifest.contributes.themes[2]!.path = "./themes/missing.json";
432 await rebuildPackage();
433 await expect(importOpenVsxThemeExtension(extension)).rejects.toThrow(
434 "could not be imported safely",
435 );
436 packagedManifest.contributes.themes[2]!.path = "./themes/demo.json";
437​
438 packagedManifest.license = "Proprietary";
439 await rebuildPackage();
440 await expect(importOpenVsxThemeExtension(extension)).rejects.toThrow(
441 "does not match its advertised license",
442 );
443​
444 Reflect.deleteProperty(packagedManifest, "license");
445 await rebuildPackage();
446 await expect(importOpenVsxThemeExtension(extension)).rejects.toThrow(
447 "does not match its advertised license",
448 );
449 });
450​
451 it("stops import work when the request is cancelled", async () => {
452 const packageBytes = new Uint8Array([1, 2, 3]);
453 const checksum = [...sha256(packageBytes)]
454 .map((byte) => byte.toString(16).padStart(2, "0"))
455 .join("");
456 const controller = new AbortController();
457 const extension: OpenVsxThemeExtension = {
458 collectionId: "open-vsx:demo.theme",
459 id: "demo.theme",
460 name: "Demo Theme",
461 publisher: "demo",
462 description: "",
463 downloadCount: 1,
464 iconUrl: null,
465 sourceUrl: null,
466 license: "MIT",
467 manifestUrl: `${ASSET_ROOT}/package.json`,
468 sha256Url: `${ASSET_ROOT}/demo.theme-1.0.0.sha256`,
469 version: "1.0.0",
470 vsixUrl: `${ASSET_ROOT}/demo.theme-1.0.0.vsix`,
471 };
472 vi.stubGlobal(
473 "fetch",
474 vi.fn(async (input: string | URL | Request) => {
475 const url = String(input);
476 if (url === extension.manifestUrl) {
477 return new Response(
478 JSON.stringify({ contributes: { themes: [{ path: "./theme.json" }] } }),
479 );
480 }
481 if (url === extension.sha256Url) {
482 controller.abort();
483 return new Response(checksum);
484 }
485 return new Response(packageBytes);
486 }),
487 );
488​
489 await expect(importOpenVsxThemeExtension(extension, controller.signal)).rejects.toMatchObject({
490 name: "AbortError",
491 });
492 });
493​
494 it("rejects a package whose Open VSX checksum does not match", async () => {
495 const extension: OpenVsxThemeExtension = {
496 collectionId: "open-vsx:demo.theme",
497 id: "demo.theme",
498 name: "Demo Theme",
499 publisher: "demo",
500 description: "",
501 downloadCount: 1,
502 iconUrl: null,
503 sourceUrl: null,
504 license: "MIT",
505 manifestUrl: `${ASSET_ROOT}/package.json`,
506 sha256Url: `${ASSET_ROOT}/demo.theme-1.0.0.sha256`,
507 version: "1.0.0",
508 vsixUrl: `${ASSET_ROOT}/demo.theme-1.0.0.vsix`,
509 };
510 vi.stubGlobal(
511 "fetch",
512 vi.fn(async (input: string | URL | Request) => {
513 const url = String(input);
514 if (url === extension.manifestUrl) {
515 return new Response(
516 JSON.stringify({ contributes: { themes: [{ path: "./theme.json" }] } }),
517 );
518 }
519 if (url === extension.sha256Url) return new Response("0".repeat(64));
520 return new Response(new Uint8Array([1, 2, 3]));
521 }),
522 );
523​
524 await expect(importOpenVsxThemeExtension(extension)).rejects.toThrow("integrity check");
525 });
526});