Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.
feat(web): add Open VSX theme search (#5654)
t3-code[bot]f0b57ca2313b
diff --git a/apps/web/package.json b/apps/web/package.jsonindex 0fce19b28..598feaec0 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -23,6 +23,7 @@"@formkit/auto-animate": "^0.9.0","@legendapp/list": "catalog:","@lexical/react": "^0.41.0",+ "@noble/hashes": "catalog:","@pierre/diffs": "catalog:","@pierre/trees": "1.0.0-beta.4","@t3tools/client-runtime": "workspace:*",@@ -34,6 +35,8 @@"culori": "^4.0.2","effect": "catalog:","jose": "catalog:",+ "jsonc-parser": "3.3.1",+ "jszip": "3.10.1","lexical": "^0.41.0","lucide-react": "^0.564.0","react": "19.2.6",diff --git a/apps/web/src/components/settings/ThemeEditorPanel.tsx b/apps/web/src/components/settings/ThemeEditorPanel.tsxindex b2a87c019..4d7300d1f 100644--- a/apps/web/src/components/settings/ThemeEditorPanel.tsx+++ b/apps/web/src/components/settings/ThemeEditorPanel.tsx@@ -610,7 +610,7 @@ export function ThemeEditorPanel({[activeAppearance, editingTheme, selectedRole],);- const handleSubmit = useCallback(() => {+ const handleSubmit = () => {if (!name.trim()) {setError("Name your theme first.");return;@@ -645,8 +645,8 @@ export function ThemeEditorPanel({return;}mergedAppearance = editedModes[0] ?? null;- savedTheme = updateCustomTheme(- parseThemeFile({+ savedTheme = updateCustomTheme({+ ...parseThemeFile({version: THEME_FILE_VERSION,id: mergeTarget.id,name: mergeTarget.label,@@ -658,7 +658,8 @@ export function ThemeEditorPanel({},...(mergeTarget.managed === true && !isAdvanced ? { managed: true } : {}),}),- );+ ...(mergeTarget.collection ? { collection: mergeTarget.collection } : {}),+ });retiredTheme = editingTheme;try {removeCustomTheme(editingTheme.id);@@ -676,8 +677,8 @@ export function ThemeEditorPanel({} else if (editingTheme) {const baseAppearance = editingTheme.appearance;const variantAppearance = baseAppearance === "light" ? "dark" : "light";- savedTheme = updateCustomTheme(- parseThemeFile({+ savedTheme = updateCustomTheme({+ ...parseThemeFile({version: THEME_FILE_VERSION,id: editingTheme.id,name,@@ -688,7 +689,8 @@ export function ThemeEditorPanel({: {}),...(isAdvanced ? {} : { managed: true }),}),- );+ ...(editingTheme.collection ? { collection: editingTheme.collection } : {}),+ });} else if (mergeTarget) {if (takenAppearances.includes(activeAppearance)) {setError(@@ -701,8 +703,8 @@ export function ThemeEditorPanel({// survives when every palette in the theme came from the guided// editor.mergedAppearance = activeAppearance;- savedTheme = updateCustomTheme(- parseThemeFile({+ savedTheme = updateCustomTheme({+ ...parseThemeFile({version: THEME_FILE_VERSION,id: mergeTarget.id,name: mergeTarget.label,@@ -714,7 +716,8 @@ export function ThemeEditorPanel({},...(mergeTarget.managed === true && !isAdvanced ? { managed: true } : {}),}),- );+ ...(mergeTarget.collection ? { collection: mergeTarget.collection } : {}),+ });} else {savedTheme = installCustomTheme(parseThemeFile({@@ -762,19 +765,7 @@ export function ThemeEditorPanel({: "Could not create the theme.",);}- }, [- activeAppearance,- colorsByAppearance,- editingTheme,- isAdvanced,- isEditing,- mergeTarget,- name,- onOpenChange,- onSaved,- simpleColorsDirtyByAppearance,- takenAppearances,- ]);+ };const renderNameField = () => (<label className="grid grid-cols-[minmax(0,1fr)_minmax(0,2fr)] items-center gap-3">diff --git a/apps/web/src/components/settings/ThemeImportDialog.tsx b/apps/web/src/components/settings/ThemeImportDialog.tsxindex be0de13c6..46915954e 100644--- a/apps/web/src/components/settings/ThemeImportDialog.tsx+++ b/apps/web/src/components/settings/ThemeImportDialog.tsx@@ -28,6 +28,7 @@ import {DialogPopup,DialogTitle,} from "../ui/dialog";+import { ThemeSearchSection } from "./ThemeSearchSection";/*** A full theme export is a few KB, so anything past this is not a theme file.@@ -360,9 +361,16 @@ export function ThemeImportDialog({: null;for (const theme of conflicts) {try {+ const existingTheme =+ mode === "update"+ ? getCustomThemes().find((candidate) => candidate.id === theme.id)+ : undefined;+ const themeToUpdate = existingTheme?.collection+ ? { ...theme, collection: existingTheme.collection }+ : theme;resolved.push(mode === "update"- ? updateCustomTheme(theme)+ ? updateCustomTheme(themeToUpdate): installCustomTheme(versionedCopy(theme, preferredName)),);} catch (cause) {@@ -426,7 +434,23 @@ export function ThemeImportDialog({<DialogHeader><DialogTitle>Add a theme</DialogTitle></DialogHeader>- <DialogPanel className="space-y-4">+ <DialogPanel className="space-y-5">+ <ThemeSearchSection+ onInstalled={(themes, context) => {+ onImportedMany(themes, context);+ onOpenChange(false);+ }}+ open={open}+ />++ <div className="flex items-center gap-3" aria-hidden>+ <div className="h-px flex-1 bg-border" />+ <span className="text-muted-foreground text-[11px] uppercase tracking-wider">+ or import a file+ </span>+ <div className="h-px flex-1 bg-border" />+ </div>+{(() => {const dropHandlers = {onDragEnter: (event: DragEvent<HTMLDivElement>) => {diff --git a/apps/web/src/components/settings/ThemeSearchSection.tsx b/apps/web/src/components/settings/ThemeSearchSection.tsxnew file mode 100644index 000000000..6085c593a--- /dev/null+++ b/apps/web/src/components/settings/ThemeSearchSection.tsx@@ -0,0 +1,389 @@+import {+ ExternalLinkIcon,+ PaletteIcon,+ PlusIcon,+ RefreshCwIcon,+ SearchIcon,+ ShieldCheckIcon,+} from "lucide-react";+import type { FormEvent } from "react";+import { useCallback, useEffect, useRef, useState } from "react";+import {+ importOpenVsxThemeExtension,+ searchOpenVsxThemes,+ type OpenVsxThemeExtension,+ type OpenVsxThemeSort,+} from "../../openVsxThemes";+import {+ getCustomThemes,+ getStoredCustomThemeCollection,+ replaceCustomThemeCollection,+ type ThemeDefinition,+} from "../../themePalette";+import {+ AlertDialog,+ AlertDialogClose,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogPopup,+ AlertDialogTitle,+} from "../ui/alert-dialog";+import { Button } from "../ui/button";+import { Input } from "../ui/input";+import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";+import { Spinner } from "../ui/spinner";++const DOWNLOAD_FORMAT = new Intl.NumberFormat(undefined, {+ notation: "compact",+ maximumFractionDigits: 1,+});+const SUGGESTED_SEARCHES = ["Dracula", "Catppuccin", "Nord", "Tokyo Night"];+const SORT_OPTIONS: ReadonlyArray<{ value: OpenVsxThemeSort; label: string }> = [+ { value: "downloadCount", label: "Most downloaded" },+ { value: "rating", label: "Best rated" },+ { value: "timestamp", label: "Newest" },+ { value: "relevance", label: "Most relevant" },+];++function ThemeExtensionIcon({ extension }: { extension: OpenVsxThemeExtension }) {+ const [failed, setFailed] = useState(false);++ return (+ <div className="flex size-10 shrink-0 items-center justify-center overflow-hidden rounded-lg bg-muted text-muted-foreground">+ {extension.iconUrl && !failed ? (+ <img+ alt=""+ className="size-full object-cover"+ loading="lazy"+ referrerPolicy="no-referrer"+ src={extension.iconUrl}+ onError={() => setFailed(true)}+ />+ ) : (+ <PaletteIcon className="size-4" />+ )}+ </div>+ );+}++export function ThemeSearchSection({+ open,+ onInstalled,+}: {+ open: boolean;+ onInstalled: (themes: ReadonlyArray<ThemeDefinition>, context: { updated: boolean }) => void;+}) {+ const [query, setQuery] = useState("");+ const [sortBy, setSortBy] = useState<OpenVsxThemeSort>("downloadCount");+ const [results, setResults] = useState<ReadonlyArray<OpenVsxThemeExtension> | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [isSearching, setIsSearching] = useState(false);+ const [installingId, setInstallingId] = useState<string | null>(null);+ const [pendingUpdate, setPendingUpdate] = useState<OpenVsxThemeExtension | null>(null);+ const requestRef = useRef<AbortController | null>(null);++ useEffect(() => {+ requestRef.current?.abort();+ requestRef.current = null;+ if (open) {+ setQuery("");+ setSortBy("downloadCount");+ setResults(null);+ setError(null);+ setIsSearching(false);+ setInstallingId(null);+ setPendingUpdate(null);+ }+ return () => {+ requestRef.current?.abort();+ requestRef.current = null;+ };+ }, [open]);++ const runSearch = useCallback(+ async (searchText: string, nextSort = sortBy) => {+ const trimmed = searchText.trim();+ if (!trimmed) return;+ requestRef.current?.abort();+ const controller = new AbortController();+ requestRef.current = controller;+ setQuery(trimmed);+ setIsSearching(true);+ setError(null);+ setResults(null);+ try {+ const nextResults = await searchOpenVsxThemes(trimmed, {+ signal: controller.signal,+ sortBy: nextSort,+ });+ if (!controller.signal.aborted) setResults(nextResults);+ } catch (cause) {+ if (!controller.signal.aborted) {+ setError(cause instanceof Error ? cause.message : "Open VSX search failed.");+ }+ }+ if (requestRef.current === controller) {+ requestRef.current = null;+ setIsSearching(false);+ }+ },+ [sortBy],+ );++ const handleSearch = useCallback(+ (event: FormEvent<HTMLFormElement>) => {+ event.preventDefault();+ void runSearch(query);+ },+ [query, runSearch],+ );++ const handleSortChange = useCallback(+ (value: OpenVsxThemeSort | null) => {+ const nextSort = SORT_OPTIONS.find((option) => option.value === value)?.value;+ if (!nextSort) return;+ setSortBy(nextSort);+ if ((results !== null || isSearching) && query.trim()) {+ void runSearch(query, nextSort);+ }+ },+ [isSearching, query, results, runSearch],+ );++ const handleInstall = useCallback(+ async (extension: OpenVsxThemeExtension, allowUpdate: boolean) => {+ setError(null);+ let installedCollection: ReadonlyArray<ThemeDefinition>;+ try {+ installedCollection = getStoredCustomThemeCollection(extension.collectionId);+ } catch (cause) {+ setError(cause instanceof Error ? cause.message : "Installed themes could not be read.");+ return;+ }+ const updated = installedCollection.length > 0;+ if (updated && !allowUpdate) {+ setPendingUpdate(extension);+ return;+ }++ requestRef.current?.abort();+ const controller = new AbortController();+ requestRef.current = controller;+ setInstallingId(extension.id);+ try {+ const themes = await importOpenVsxThemeExtension(extension, controller.signal);+ if (!controller.signal.aborted) {+ const imported = replaceCustomThemeCollection(extension.collectionId, themes, {+ expectedCollection: installedCollection,+ });+ onInstalled(imported, { updated });+ }+ } catch (cause) {+ if (!controller.signal.aborted) {+ setError(cause instanceof Error ? cause.message : "That theme could not be added.");+ }+ }+ if (requestRef.current === controller) {+ requestRef.current = null;+ setInstallingId(null);+ }+ },+ [onInstalled],+ );++ return (+ <section className="space-y-3" aria-labelledby="theme-search-heading">+ <div>+ <h3 className="text-sm font-medium" id="theme-search-heading">+ Search community themes+ </h3>+ <p className="mt-0.5 text-muted-foreground text-xs">+ Find open-source themes from Open VSX.+ </p>+ </div>+ <form className="relative flex gap-2" onSubmit={handleSearch}>+ <SearchIcon className="pointer-events-none absolute left-3 top-1/2 z-10 size-4 -translate-y-1/2 text-muted-foreground" />+ <Input+ aria-label="Search Open VSX themes"+ className="rounded-xl [&_input]:pl-9"+ autoFocus+ onChange={(event) => setQuery(event.currentTarget.value)}+ placeholder="try dracula, nord, catppuccin..."+ size="lg"+ type="search"+ value={query}+ />+ <Button+ disabled={!query.trim() || isSearching || installingId !== null}+ type="submit"+ variant="outline"+ >+ {isSearching ? <Spinner /> : <SearchIcon />}+ Search+ </Button>+ </form>++ {!isSearching ? (+ <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">+ <div className="flex min-w-0 flex-wrap items-center gap-1.5">+ <p className="text-muted-foreground text-xs">Popular</p>+ {SUGGESTED_SEARCHES.map((suggestion) => (+ <Button+ key={suggestion}+ size="xs"+ variant="ghost"+ onClick={() => void runSearch(suggestion)}+ >+ {suggestion}+ </Button>+ ))}+ </div>+ {results && results.length > 0 ? (+ <div className="flex shrink-0 items-center justify-end gap-2">+ <p className="text-muted-foreground text-xs">Sort</p>+ <Select+ disabled={installingId !== null}+ value={sortBy}+ onValueChange={handleSortChange}+ >+ <SelectTrigger size="sm" className="w-40" aria-label="Sort themes">+ <SelectValue>+ {SORT_OPTIONS.find((option) => option.value === sortBy)?.label}+ </SelectValue>+ </SelectTrigger>+ <SelectPopup align="end" alignItemWithTrigger={false}>+ {SORT_OPTIONS.map((option) => (+ <SelectItem key={option.value} hideIndicator value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectPopup>+ </Select>+ </div>+ ) : null}+ </div>+ ) : null}++ <div className="sr-only" role="status">+ {isSearching+ ? "Finding themes..."+ : results+ ? `${results.length} supported ${results.length === 1 ? "theme" : "themes"} found.`+ : ""}+ </div>++ {error ? (+ <div+ aria-live="polite"+ className="rounded-xl border border-destructive/30 bg-destructive/5 px-3 py-2 text-destructive text-sm"+ >+ {error}+ </div>+ ) : null}++ {isSearching ? (+ <div className="flex min-h-20 items-center justify-center gap-2 text-muted-foreground text-sm">+ <Spinner /> Finding themes...+ </div>+ ) : null}++ {results ? (+ results.length === 0 ? (+ <div className="flex min-h-40 flex-col items-center justify-center rounded-2xl border border-dashed text-center">+ <p className="text-sm font-medium">No supported open-source themes found</p>+ <p className="mt-1 text-muted-foreground text-xs">Try a broader search.</p>+ </div>+ ) : (+ <div className="grid gap-2 sm:grid-cols-2">+ {results.map((extension) => {+ const isInstalling = installingId === extension.id;+ const isInstalled = getCustomThemes().some(+ (theme) => theme.collection?.id === extension.collectionId,+ );+ const action = isInstalled ? "Update" : "Add";+ const progressAction = isInstalled ? "Updating" : "Adding";+ return (+ <article+ className="group flex min-w-0 flex-col gap-3 rounded-xl border border-border/70 bg-card/60 p-3 transition-colors hover:bg-accent/20"+ key={extension.id}+ >+ <div className="flex min-w-0 gap-3">+ <ThemeExtensionIcon key={extension.iconUrl} extension={extension} />+ <div className="min-w-0 flex-1">+ <h4 className="truncate text-sm font-medium">{extension.name}</h4>+ <p className="truncate text-muted-foreground text-xs">+ {extension.publisher} · {DOWNLOAD_FORMAT.format(extension.downloadCount)}{" "}+ downloads+ </p>+ </div>+ </div>+ <p className="line-clamp-2 min-h-8 text-muted-foreground text-xs leading-4">+ {extension.description || "A community color theme for your editor."}+ </p>+ <div className="mt-auto flex items-center justify-between gap-2">+ <div className="flex min-w-0 items-center gap-2">+ <span className="inline-flex items-center gap-1 text-muted-foreground text-[11px]">+ <ShieldCheckIcon className="size-3" /> {extension.license}+ </span>+ {extension.sourceUrl ? (+ <a+ aria-label={`View source for ${extension.name}`}+ className="inline-flex items-center gap-1 text-muted-foreground text-[11px] hover:text-foreground"+ href={extension.sourceUrl}+ rel="noreferrer"+ target="_blank"+ >+ Source <ExternalLinkIcon className="size-3" />+ </a>+ ) : null}+ </div>+ <Button+ aria-label={`${isInstalling ? progressAction : action} ${extension.name}`}+ disabled={installingId !== null}+ size="xs"+ variant="outline"+ onClick={() => void handleInstall(extension, false)}+ >+ {isInstalling ? <Spinner /> : isInstalled ? <RefreshCwIcon /> : <PlusIcon />}+ {isInstalling ? `${progressAction}...` : action}+ </Button>+ </div>+ </article>+ );+ })}+ </div>+ )+ ) : null}++ <AlertDialog+ open={pendingUpdate !== null}+ onOpenChange={(nextOpen) => {+ if (!nextOpen) setPendingUpdate(null);+ }}+ >+ <AlertDialogPopup>+ <AlertDialogHeader>+ <AlertDialogTitle>Update “{pendingUpdate?.name}”?</AlertDialogTitle>+ <AlertDialogDescription>+ This replaces its installed variants, including any local edits. Variants no longer in+ the extension will be removed.+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>+ <Button+ onClick={() => {+ const extension = pendingUpdate;+ setPendingUpdate(null);+ if (extension) void handleInstall(extension, true);+ }}+ >+ Update theme+ </Button>+ </AlertDialogFooter>+ </AlertDialogPopup>+ </AlertDialog>+ </section>+ );+}diff --git a/apps/web/src/components/settings/ThemeSettings.tsx b/apps/web/src/components/settings/ThemeSettings.tsxindex a2261e91f..7e4b80d19 100644--- a/apps/web/src/components/settings/ThemeSettings.tsx+++ b/apps/web/src/components/settings/ThemeSettings.tsx@@ -1,17 +1,20 @@import {+ CheckIcon,CopyIcon,DownloadIcon,+ MoonIcon,PenLineIcon,PlusIcon,+ SunIcon,Trash2Icon,UploadIcon,} from "lucide-react";-import { useCallback, useEffect, useRef, useState } from "react";+import { useCallback, useEffect, useState, type ReactElement } from "react";import { cn } from "../../lib/utils";import {getThemeDefinition,getThemeModes,- removeCustomTheme,+ removeCustomThemes,serializeThemeFile,type ThemeAppearance,type ThemeDefinition,@@ -41,6 +44,7 @@ import {getThemeCardDefinition,previewColorsOf,ThemePreviewCircles,+ ThemePreviewCircle,type ThemeCardDefinition,type ThemeMode,} from "./ThemePreviewCircles";@@ -54,6 +58,21 @@ const MAINTAINER_THEMES: ReadonlyArray<ThemeDefinition> = [IRIS_THEME,];+function collectionVariantLabels(themes: ReadonlyArray<ThemeDefinition>): ReadonlyArray<string> {+ if (themes.length === 0) return [];+ const words = themes.map((theme) => theme.label.trim().split(/\s+/));+ const firstWords = words[0]!;+ const sharedWordCount = firstWords.findIndex((word, index) =>+ words.some((labelWords) => labelWords[index]?.toLocaleLowerCase() !== word.toLocaleLowerCase()),+ );+ const prefixLength = sharedWordCount === -1 ? firstWords.length - 1 : sharedWordCount;++ return themes.map((theme, index) => {+ const shortLabel = words[index]?.slice(Math.max(0, prefixLength)).join(" ").trim();+ return shortLabel || theme.label;+ });+}+function downloadThemeFile(filename: string, contents: string): void {const url = URL.createObjectURL(new Blob([contents], { type: "application/json" }));const anchor = document.createElement("a");@@ -65,6 +84,15 @@ function downloadThemeFile(filename: string, contents: string): void {setTimeout(() => URL.revokeObjectURL(url), 30_000);}+function ThemeVariantTooltip({ label, children }: { label: string; children: ReactElement }) {+ return (+ <Tooltip>+ <TooltipTrigger render={children} />+ <TooltipPopup>{label}</TooltipPopup>+ </Tooltip>+ );+}+function ThemeLibraryCard({theme,isActive,@@ -75,6 +103,7 @@ function ThemeLibraryCard({onDuplicate,onDownload,onRemove,+ variantNavigation,}: {theme: ThemeCardDefinition;isActive: boolean;@@ -85,10 +114,33 @@ function ThemeLibraryCard({onDuplicate?: () => void;onDownload?: () => void;onRemove?: () => void;+ variantNavigation?: {+ collectionLabel: string;+ options: ReadonlyArray<{+ themeIndex: number;+ label: string;+ activeModes: ReadonlyArray<ThemeMode>;+ preview: ThemeCardDefinition["previews"][number];+ }>;+ onSelectAndUse: (themeIndex: number, mode: ThemeAppearance) => void;+ };}) {// A one-appearance theme can only take its own side of the mix, so the card// tooltip promises exactly what clicking it does.const cardModes = theme.previews.map((preview) => preview.mode);+ const [radialModeOpen, setRadialModeOpen] = useState<ThemeAppearance | null>(null);+ const radialModeGroups = (["light", "dark"] as const).map((mode) => {+ const options =+ variantNavigation?.options.flatMap((option) => {+ const preview = option.preview;+ return preview.mode === mode ? [{ option, preview }] : [];+ }) ?? [];+ return {+ mode,+ options,+ selected: options.find(({ option }) => option.activeModes.includes(mode)) ?? options[0],+ };+ });return (// The card surface stays a plain div (buttons cannot nest inside a button// role); the title button and mode circles carry the accessible actions,@@ -105,17 +157,147 @@ function ThemeLibraryCard({onClick={onUse}style={isActive ? { boxShadow: "inset 0 0 0 1px var(--ring)" } : undefined}>- <ThemePreviewCircles- label={theme.label}- activeModes={activeModes}- onSelectMode={onUseMode}- previews={theme.previews}- />+ <div className="relative">+ {variantNavigation ? (+ <div+ aria-label="Light and dark theme variants"+ className="relative h-20"+ role="group"+ onBlurCapture={(event) => {+ const nextTarget = event.relatedTarget;+ if (+ !(nextTarget instanceof Node) ||+ !event.currentTarget.contains(nextTarget)+ ) {+ setRadialModeOpen(null);+ }+ }}+ onKeyDown={(event) => {+ if (event.key === "Escape") setRadialModeOpen(null);+ }}+ onMouseLeave={() => setRadialModeOpen(null)}+ >+ {radialModeGroups.map(({ mode, options, selected }) => {+ if (!selected) return null;+ const rootOffsetX = mode === "light" ? -52 : 52;+ const isOpen = radialModeOpen === mode;+ const isActive = selected.option.activeModes.includes(mode);+ const modeLabel = mode === "light" ? "Light" : "Dark";+ return (+ <div className="contents" key={mode}>+ <ThemeVariantTooltip label={`${modeLabel}: ${selected.option.label}`}>+ <button+ aria-label={+ options.length > 1+ ? `Choose ${mode} variant, ${options.length} options, currently ${selected.option.label}`+ : `Use ${mode} variant, currently ${selected.option.label}`+ }+ aria-pressed={isActive}+ className="absolute left-1/2 top-2 z-20 flex size-14 items-center justify-center rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ring"+ style={{+ transform: `translateX(calc(-50% + ${rootOffsetX}px))`,+ }}+ type="button"+ onClick={(event) => {+ event.stopPropagation();+ variantNavigation.onSelectAndUse(selected.option.themeIndex, mode);+ }}+ onFocus={() => setRadialModeOpen(mode)}+ onMouseEnter={() => setRadialModeOpen(mode)}+ >+ <ThemePreviewCircle+ colors={selected.preview.colors}+ mode={selected.preview.mode}+ />+ {isActive ? (+ <span+ aria-hidden+ className="pointer-events-none absolute inset-0 rounded-full ring-2 ring-ring"+ />+ ) : null}+ {isActive ? (+ <span className="pointer-events-none absolute -bottom-0.5 -right-0.5 flex size-4 items-center justify-center rounded-full border border-border/70 bg-background text-foreground shadow-sm">+ {mode === "light" ? (+ <SunIcon className="size-2.5" />+ ) : (+ <MoonIcon className="size-2.5" />+ )}+ </span>+ ) : null}+ </button>+ </ThemeVariantTooltip>+ <span+ className="pointer-events-none absolute bottom-0 left-1/2 inline-flex max-w-24 -translate-x-1/2 items-center gap-1 text-[11px] font-medium text-foreground"+ style={{ marginLeft: rootOffsetX }}+ >+ <span className="truncate">{selected.option.label}</span>+ {options.length > 1 ? (+ <span className="shrink-0 rounded-full bg-muted px-1 text-[9px] text-muted-foreground">+ +{options.length - 1}+ </span>+ ) : null}+ </span>+ {options.length > 1+ ? options.map(({ option, preview }, optionIndex) => {+ const progress = optionIndex / (options.length - 1) - 0.5;+ const childOffsetX = rootOffsetX + progress * 68;+ const childOffsetY = Math.abs(progress) * 10;+ const optionIsActive = option.activeModes.includes(mode);+ return (+ <ThemeVariantTooltip+ key={option.label}+ label={`Use ${option.label} for ${mode} mode`}+ >+ <button+ aria-label={`Use ${option.label} for ${mode} mode${optionIsActive ? ", currently active" : ""}`}+ aria-pressed={optionIsActive}+ className={cn(+ "absolute left-1/2 top-1 z-30 flex size-7 items-center justify-center rounded-full bg-background shadow-sm outline-none transition-[transform,opacity] duration-200 ease-out motion-reduce:transition-none focus-visible:ring-2 focus-visible:ring-ring",+ optionIsActive ? "ring-2 ring-ring" : "ring-1 ring-border/70",+ )}+ style={{+ opacity: isOpen ? 1 : 0,+ pointerEvents: isOpen ? "auto" : "none",+ transform: `translate(calc(-50% + ${isOpen ? childOffsetX : rootOffsetX}px), ${isOpen ? childOffsetY : 28}px) scale(${isOpen ? 1 : 0.55})`,+ transitionDelay: isOpen ? `${optionIndex * 35}ms` : "0ms",+ }}+ type="button"+ onClick={(event) => {+ event.stopPropagation();+ variantNavigation.onSelectAndUse(option.themeIndex, mode);+ }}+ onFocus={() => setRadialModeOpen(mode)}+ onMouseEnter={() => setRadialModeOpen(mode)}+ >+ <span className="pointer-events-none scale-[0.43]">+ <ThemePreviewCircle+ colors={preview.colors}+ mode={preview.mode}+ />+ </span>+ </button>+ </ThemeVariantTooltip>+ );+ })+ : null}+ </div>+ );+ })}+ </div>+ ) : (+ <ThemePreviewCircles+ label={theme.label}+ activeModes={activeModes}+ onSelectMode={onUseMode}+ previews={theme.previews}+ />+ )}+ </div><div className="flex items-center gap-2 px-3 pb-3 pt-2"><div className="min-w-0 flex-1"><div className="flex items-center gap-1.5"><button- aria-label={`Use ${theme.label} theme${isActive ? ", currently active" : ""}`}+ aria-label={`Use ${variantNavigation ? `${variantNavigation.collectionLabel}, ${theme.label} variant` : `${theme.label} theme`}${isActive ? ", currently active" : ""}`}aria-pressed={isActive}className="min-w-0 cursor-pointer truncate rounded-sm text-left text-sm font-medium text-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-card"type="button"@@ -124,7 +306,7 @@ function ThemeLibraryCard({onUse();}}>- {theme.label}+ {variantNavigation?.collectionLabel ?? theme.label}</button></div></div>@@ -195,7 +377,11 @@ function ThemeLibraryCard({<TooltipTriggerrender={<Button- aria-label={`Remove ${theme.label}`}+ aria-label={+ variantNavigation+ ? `Remove themes from ${variantNavigation.collectionLabel}`+ : `Remove ${theme.label}`+ }size="icon-xs"variant="ghost"className="text-muted-foreground hover:text-destructive"@@ -208,7 +394,9 @@ function ThemeLibraryCard({</Button>}/>- <TooltipPopup>Remove theme</TooltipPopup>+ <TooltipPopup>+ {variantNavigation ? "Remove themes" : "Remove theme"}+ </TooltipPopup></Tooltip>) : null}</div>@@ -218,12 +406,97 @@ function ThemeLibraryCard({}/><TooltipPopup>- {cardModes.length > 1 ? "Use for both light and dark" : `Use for ${cardModes[0]} mode only`}+ {variantNavigation+ ? "Use the first variants for light and dark"+ : cardModes.length > 1+ ? "Use for both light and dark"+ : `Use for ${cardModes[0]} mode only`}</TooltipPopup></Tooltip>);}+function CustomThemeCollectionCard({+ themes,+ activeModesFor,+ onUse,+ onUseMode,+ onDuplicate,+ onEdit,+ onDownload,+ onRemove,+}: {+ themes: ReadonlyArray<ThemeDefinition>;+ activeModesFor: (themeId: string) => ReadonlyArray<ThemeMode>;+ onUse: (theme: ThemeDefinition) => void;+ onUseMode: (theme: ThemeDefinition, mode: ThemeMode) => void;+ onDuplicate: (theme: ThemeDefinition) => void;+ onEdit: (theme: ThemeDefinition) => void;+ onDownload: (theme: ThemeDefinition) => void;+ onRemove: (theme: ThemeDefinition) => void;+}) {+ const [variantIndex, setVariantIndex] = useState(() => {+ const activeIndex = themes.findIndex((theme) => activeModesFor(theme.id).length > 0);+ return activeIndex < 0 ? 0 : activeIndex;+ });+ const safeIndex = Math.min(variantIndex, themes.length - 1);+ const theme = themes[safeIndex];++ useEffect(() => {+ if (variantIndex !== safeIndex) setVariantIndex(safeIndex);+ }, [safeIndex, variantIndex]);++ if (!theme) return null;+ const collectionLabel = theme.collection?.label ?? theme.label;+ const variantLabels = collectionVariantLabels(themes);+ const defaultLightTheme = themes.find((candidate) => getThemeModes(candidate).includes("light"));+ const defaultDarkTheme = themes.find((candidate) => getThemeModes(candidate).includes("dark"));+ const selectCollectionDefaults = () => {+ if (themes.length === 1) {+ onUse(theme);+ return;+ }+ if (defaultLightTheme) onUseMode(defaultLightTheme, "light");+ if (defaultDarkTheme) onUseMode(defaultDarkTheme, "dark");+ setVariantIndex(0);+ };++ return (+ <ThemeLibraryCard+ activeModes={activeModesFor(theme.id)}+ isActive={false}+ onDownload={() => onDownload(theme)}+ onDuplicate={() => onDuplicate(theme)}+ onEdit={() => onEdit(theme)}+ onRemove={() => onRemove(theme)}+ onUse={selectCollectionDefaults}+ onUseMode={(mode) => onUseMode(theme, mode)}+ theme={getThemeCardDefinition(theme)}+ {...(themes.length > 1+ ? {+ variantNavigation: {+ collectionLabel,+ options: themes.flatMap((variant, themeIndex) =>+ getThemeCardDefinition(variant).previews.map((preview) => ({+ themeIndex,+ label: variantLabels[themeIndex] ?? variant.label,+ activeModes: activeModesFor(variant.id),+ preview,+ })),+ ),+ onSelectAndUse: (themeIndex, mode) => {+ const selectedTheme = themes[themeIndex];+ if (!selectedTheme) return;+ setVariantIndex(themeIndex);+ onUseMode(selectedTheme, mode);+ },+ },+ }+ : {})}+ />+ );+}+export function ThemeLibrary({theme,setTheme,@@ -250,14 +523,20 @@ export function ThemeLibrary({setThemeHalf: (appearance: ThemeAppearance, themeId: string | null) => boolean;}) {const openThemeEditor = useThemeEditorStore((store) => store.openThemeEditor);- const [themeToRemove, setThemeToRemove] = useState<ThemeDefinition | null>(null);- // Keep the last removal target so the dialog title stays populated while the- // close animation plays after confirming.- const lastThemeToRemoveRef = useRef<ThemeDefinition | null>(null);- useEffect(() => {- if (themeToRemove) lastThemeToRemoveRef.current = themeToRemove;- }, [themeToRemove]);- const removeDialogTheme = themeToRemove ?? lastThemeToRemoveRef.current;+ const [themeRemovalTarget, setThemeRemovalTarget] = useState<{+ theme: ThemeDefinition;+ collectionThemes: ReadonlyArray<ThemeDefinition>;+ } | null>(null);+ // Keep the target after closing so the dialog text remains populated during+ // its exit animation. The next trash action replaces it before reopening.+ const [isThemeRemovalOpen, setIsThemeRemovalOpen] = useState(false);+ const [themeIdsToRemove, setThemeIdsToRemove] = useState<ReadonlyArray<string>>([]);+ const themeIdsToRemoveSet = new Set(themeIdsToRemove);+ const removeDialogTheme = themeRemovalTarget?.theme;+ const removeDialogCollectionThemes = themeRemovalTarget?.collectionThemes ?? [];+ const canRemoveCollection = removeDialogCollectionThemes.length > 1;+ const removeDialogCollectionLabel =+ removeDialogTheme?.collection?.label ?? removeDialogTheme?.label;const notifyThemeSaveFailure = useCallback(() => {toastManager.add(@@ -288,37 +567,43 @@ export function ThemeLibrary({[notifyThemeSaveFailure, setTheme],);- const handleRemoveTheme = useCallback((customTheme: ThemeDefinition) => {- setThemeToRemove(customTheme);- }, []);+ const handleRemoveTheme = useCallback(+ (customTheme: ThemeDefinition, collectionThemes: ReadonlyArray<ThemeDefinition>) => {+ setThemeRemovalTarget({ theme: customTheme, collectionThemes });+ setThemeIdsToRemove(collectionThemes.length > 1 ? [] : [customTheme.id]);+ setIsThemeRemovalOpen(true);+ },+ [],+ );const handleConfirmRemoveTheme = useCallback(() => {- if (!themeToRemove) return;- const removesBase = getThemeDefinition(theme)?.id === themeToRemove.id;- // Keep the theme installed if we cannot move the selection off it; the- // dialog stays open so the user can retry or cancel.+ if (!themeRemovalTarget) return;+ const removedIds = new Set(themeIdsToRemove);+ if (removedIds.size === 0) return;+ const removesBase = removedIds.has(getThemeDefinition(theme)?.id ?? "");+ // Keep the themes installed if we cannot move the selection off one of+ // them; the dialog stays open so the user can retry or cancel.if (removesBase && !persistTheme(appearanceMode === "system" ? "system" : appearanceMode)) {return;}for (const appearance of ["light", "dark"] as const) {const half = themeHalves?.[appearance];if (half === undefined) continue;- // Writing a base preference clears the whole mix, so halves that name a- // surviving theme are written back; halves on the removed theme fall- // back to the base.- const next = half === themeToRemove.id ? null : removesBase ? half : undefined;+ // Writing a base preference clears the whole mix, so halves that name+ // a surviving theme are written back; removed halves fall back to base.+ const next = half && removedIds.has(half) ? null : removesBase ? half : undefined;if (next !== undefined && !setThemeHalf(appearance, next)) {notifyThemeRemovalFailure();return;}}try {- removeCustomTheme(themeToRemove.id);+ removeCustomThemes([...removedIds]);} catch {notifyThemeRemovalFailure();return;}- setThemeToRemove(null);+ setIsThemeRemovalOpen(false);}, [appearanceMode,notifyThemeRemovalFailure,@@ -326,7 +611,8 @@ export function ThemeLibrary({setThemeHalf,theme,themeHalves,- themeToRemove,+ themeIdsToRemove,+ themeRemovalTarget,]);// ----- Automatic-mode mixing -------------------------------------------@@ -460,6 +746,20 @@ export function ThemeLibrary({</div>);+ const customThemeCollections = [+ ...customThemes+ .reduce((groups, customTheme) => {+ const groupId = customTheme.collection+ ? `collection:${customTheme.collection.id}`+ : `theme:${customTheme.id}`;+ const group = groups.get(groupId);+ if (group) group.push(customTheme);+ else groups.set(groupId, [customTheme]);+ return groups;+ }, new Map<string, ThemeDefinition[]>())+ .entries(),+ ];+const renderPairGrid = () => (// One shared provider so every tooltip in the grid hands off instantly to// the next hovered trigger instead of stacking on top of it. The card@@ -509,43 +809,39 @@ export function ThemeLibrary({/>);})}- {customThemes.map((customTheme) => {- const card = getThemeCardDefinition(customTheme);- return (- <ThemeLibraryCard- activeModes={pickedModesFor(customTheme.id)}- isActive={false}- key={customTheme.id}- onDuplicate={() =>- openThemeEditor({- editingThemeId: null,- seedThemeId: customTheme.id,- seedName: `${customTheme.label} copy`,- initialAppearance,- })- }- onEdit={() =>- openThemeEditor({- editingThemeId: customTheme.id,- seedThemeId: null,- seedName: null,- initialAppearance,- })- }- onDownload={() =>- downloadThemeFile(`${customTheme.id}.json`, serializeThemeFile(customTheme))- }- onRemove={() => handleRemoveTheme(customTheme)}- onUse={() => {- const modes = getThemeModes(customTheme);- if (modes.length === 1) assignHalf(modes[0]!, customTheme.id);- else persistTheme(customTheme.id);- }}- onUseMode={handlePairPick(customTheme.id)}- theme={card}- />- );- })}+ {customThemeCollections.map(([collectionId, themes]) => (+ <CustomThemeCollectionCard+ activeModesFor={pickedModesFor}+ key={collectionId}+ onDownload={(customTheme) =>+ downloadThemeFile(`${customTheme.id}.json`, serializeThemeFile(customTheme))+ }+ onDuplicate={(customTheme) =>+ openThemeEditor({+ editingThemeId: null,+ seedThemeId: customTheme.id,+ seedName: `${customTheme.label} copy`,+ initialAppearance,+ })+ }+ onEdit={(customTheme) =>+ openThemeEditor({+ editingThemeId: customTheme.id,+ seedThemeId: null,+ seedName: null,+ initialAppearance,+ })+ }+ onRemove={(customTheme) => handleRemoveTheme(customTheme, themes)}+ onUse={(customTheme) => {+ const modes = getThemeModes(customTheme);+ if (modes.length === 1) assignHalf(modes[0]!, customTheme.id);+ else persistTheme(customTheme.id);+ }}+ onUseMode={(customTheme, mode) => handlePairPick(customTheme.id)(mode)}+ themes={themes}+ />+ ))}</div></TooltipProvider>);@@ -561,7 +857,7 @@ export function ThemeLibrary({{renderModeTiles()}<div className="flex min-h-8 flex-wrap items-center justify-between gap-3 px-3 pt-2 sm:px-4"><h3 className="text-sm font-medium tracking-[-0.005em] text-foreground">Themes</h3>- <div className="flex flex-wrap items-center justify-end gap-3">+ <div className="flex flex-wrap items-center justify-end gap-2"><Buttonsize="xs"variant="outline"@@ -586,19 +882,9 @@ export function ThemeLibrary({{renderPairGrid()}<ThemeImportDialogonImportedMany={(importedThemes, { updated }) => {- // An updated theme that is showing (as the base or either half)- // needs its palette re-applied.- if (- updated &&- importedThemes.some(- (imported) =>- getThemeDefinition(theme)?.id === imported.id ||- themeHalves?.light === imported.id ||- themeHalves?.dark === imported.id,- )- ) {- refreshTheme();- }+ // Re-apply after collection updates. The update may remove the+ // selected variant, in which case the theme hook falls back safely.+ if (updated) refreshTheme();const verb = updated ? "updated" : "added";toastManager.add(stackedThreadToast({@@ -639,23 +925,80 @@ export function ThemeLibrary({onOpenChange={onImportOpenChange}open={isImportOpen}/>- <AlertDialog- open={themeToRemove !== null}- onOpenChange={(open) => {- if (!open) setThemeToRemove(null);- }}- >+ <AlertDialog open={isThemeRemovalOpen} onOpenChange={setIsThemeRemovalOpen}><AlertDialogPopup><AlertDialogHeader>- <AlertDialogTitle>Remove “{removeDialogTheme?.label}”?</AlertDialogTitle>+ <AlertDialogTitle>+ {canRemoveCollection+ ? `Remove themes from “${removeDialogCollectionLabel}”?`+ : `Remove “${removeDialogTheme?.label}”?`}+ </AlertDialogTitle><AlertDialogDescription>- You can bring it back anytime by importing its JSON file.+ {canRemoveCollection+ ? "Select the variants you want to remove. You can restore them by importing the extension again."+ : "You can bring it back anytime by importing its JSON file."}</AlertDialogDescription></AlertDialogHeader>+ {canRemoveCollection ? (+ <div className="grid max-h-72 grid-cols-1 gap-2 overflow-y-auto px-6 pb-6 sm:grid-cols-2">+ {removeDialogCollectionThemes.map((customTheme) => {+ const checked = themeIdsToRemoveSet.has(customTheme.id);+ const card = getThemeCardDefinition(customTheme);+ const checkboxId = `remove-theme-${customTheme.id}`;+ return (+ <label+ className="group relative flex min-h-28 cursor-pointer flex-col items-center justify-center gap-2 rounded-lg border border-border/70 bg-muted/25 p-3 has-checked:border-ring has-checked:bg-accent/20 hover:bg-muted/40"+ htmlFor={checkboxId}+ key={customTheme.id}+ >+ <span className="absolute right-2 top-2 inline-grid size-5 grid-cols-1 sm:size-4">+ <input+ checked={checked}+ className="col-start-1 row-start-1 size-full appearance-none rounded-sm border border-input bg-background outline-none checked:border-primary checked:bg-primary focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring dark:not-checked:bg-input/32 forced-colors:appearance-auto"+ id={checkboxId}+ name="themes-to-remove"+ type="checkbox"+ onChange={(event) => {+ const shouldRemove = event.currentTarget.checked;+ setThemeIdsToRemove((current) =>+ shouldRemove+ ? [...current, customTheme.id]+ : current.filter((themeId) => themeId !== customTheme.id),+ );+ }}+ />+ <CheckIcon className="pointer-events-none col-start-1 row-start-1 size-3.5 shrink-0 self-center justify-self-center stroke-primary-foreground opacity-0 group-has-checked:opacity-100 sm:size-3" />+ </span>+ <span className="flex min-h-12 items-center justify-center gap-1">+ {card.previews.map((preview) => (+ <span+ className="flex size-11 shrink-0 items-center justify-center"+ key={preview.mode}+ >+ <span className="flex scale-75">+ <ThemePreviewCircle colors={preview.colors} mode={preview.mode} />+ </span>+ </span>+ ))}+ </span>+ <p className="max-w-full truncate text-center text-base font-medium text-foreground sm:text-sm">+ {customTheme.label}+ </p>+ </label>+ );+ })}+ </div>+ ) : null}<AlertDialogFooter><AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>- <Button variant="destructive" onClick={handleConfirmRemoveTheme}>- Remove theme+ <Button+ disabled={themeIdsToRemove.length === 0}+ variant="destructive"+ onClick={handleConfirmRemoveTheme}+ >+ {canRemoveCollection+ ? `Remove selected${themeIdsToRemove.length > 0 ? ` (${themeIdsToRemove.length})` : ""}`+ : "Remove theme"}</Button></AlertDialogFooter></AlertDialogPopup>diff --git a/apps/web/src/openVsxThemes.test.ts b/apps/web/src/openVsxThemes.test.tsnew file mode 100644index 000000000..4775a0188--- /dev/null+++ b/apps/web/src/openVsxThemes.test.ts@@ -0,0 +1,526 @@+import { sha256 } from "@noble/hashes/sha2";+import JSZip from "jszip";+import { afterEach, describe, expect, it, vi } from "vite-plus/test";++import {+ importOpenVsxThemeExtension,+ searchOpenVsxThemes,+ type OpenVsxThemeExtension,+} from "./openVsxThemes";+import { getThemeColorsForMode, themeColorToHex } from "./themePalette";++const ASSET_ROOT = "https://open-vsx.org/api/demo/theme/1.0.0/file";++function extensionDetail(overrides: Record<string, unknown> = {}) {+ return {+ namespace: "demo",+ name: "theme",+ displayName: "Demo Theme",+ description: "A nice theme",+ version: "1.0.0",+ downloadCount: 123456,+ license: "MIT",+ repository: "https://github.com/demo/theme",+ files: {+ icon: `${ASSET_ROOT}/icon.png`,+ manifest: `${ASSET_ROOT}/package.json`,+ sha256: `${ASSET_ROOT}/demo.theme-1.0.0.sha256`,+ download: `${ASSET_ROOT}/demo.theme-1.0.0.vsix`,+ },+ ...overrides,+ };+}++afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+});++describe("Open VSX themes", () => {+ it("searches theme extensions and keeps only supported open-source licenses", async () => {+ const fetchMock = vi.fn(async (input: RequestInfo | URL) => {+ const url = String(input);+ if (url.includes("/-/search?")) {+ return new Response(+ JSON.stringify({+ extensions: [+ { namespace: "demo", name: "theme" },+ { namespace: "icons", name: "theme" },+ { namespace: "oversized", name: "theme" },+ { namespace: "unlicensed", name: "theme" },+ { namespace: "unavailable", name: "theme" },+ { namespace: "closed", name: "theme" },+ { namespace: "huge", name: "theme" },+ ],+ }),+ { status: 200 },+ );+ }+ if (url.endsWith("/icons/theme")) {+ return new Response(+ JSON.stringify(+ extensionDetail({+ namespace: "icons",+ files: {+ ...extensionDetail().files,+ manifest: `${ASSET_ROOT.replace("demo/theme", "icons/theme")}/package.json`,+ },+ }),+ ),+ { status: 200 },+ );+ }+ if (url.endsWith("/oversized/theme")) {+ return new Response(+ JSON.stringify(+ extensionDetail({+ namespace: "oversized",+ files: {+ ...extensionDetail().files,+ download: `${ASSET_ROOT.replace("demo/theme", "oversized/theme")}/oversized.vsix`,+ },+ }),+ ),+ { status: 200 },+ );+ }+ if (url.endsWith("/unlicensed/theme")) {+ return new Response(+ JSON.stringify(+ extensionDetail({+ namespace: "unlicensed",+ files: {+ ...extensionDetail().files,+ manifest: `${ASSET_ROOT.replace("demo/theme", "unlicensed/theme")}/package.json`,+ },+ }),+ ),+ { status: 200 },+ );+ }+ if (url.endsWith("/unavailable/theme")) {+ return new Response(+ JSON.stringify(+ extensionDetail({+ namespace: "unavailable",+ files: {+ ...extensionDetail().files,+ download: `${ASSET_ROOT.replace("demo/theme", "unavailable/theme")}/unavailable.vsix`,+ manifest: `${ASSET_ROOT.replace("demo/theme", "unavailable/theme")}/package.json`,+ },+ }),+ ),+ { status: 200 },+ );+ }+ if (url.endsWith("/closed/theme")) {+ return new Response(+ JSON.stringify(extensionDetail({ namespace: "closed", license: "All Rights Reserved" })),+ { status: 200 },+ );+ }+ if (url.endsWith("/huge/theme")) {+ return new Response(JSON.stringify({ padding: "x".repeat(256 * 1024) }), { status: 200 });+ }+ if (url.endsWith("/oversized/theme/1.0.0/file/oversized.vsix")) {+ return new Response(null, {+ headers: { "content-length": String(20 * 1024 * 1024 + 1) },+ status: 200,+ });+ }+ if (url.endsWith("/unavailable/theme/1.0.0/file/unavailable.vsix")) {+ return new Response(null, { status: 404 });+ }+ if (url.endsWith(".vsix")) {+ return new Response(null, { headers: { "content-length": "1024" }, status: 200 });+ }+ if (url.endsWith("/icons/theme/1.0.0/file/package.json")) {+ return new Response(JSON.stringify({ contributes: { iconThemes: [{}] } }), { status: 200 });+ }+ if (url.endsWith("/unlicensed/theme/1.0.0/file/package.json")) {+ return new Response(+ JSON.stringify({ contributes: { themes: [{ path: "./theme.json" }] } }),+ { status: 200 },+ );+ }+ if (url.endsWith("/unavailable/theme/1.0.0/file/package.json")) {+ return new Response(+ JSON.stringify({ license: "MIT", contributes: { themes: [{ path: "./theme.json" }] } }),+ { status: 200 },+ );+ }+ if (url.endsWith("/demo/theme/1.0.0/file/package.json")) {+ return new Response(+ JSON.stringify({ license: "MIT", contributes: { themes: [{ path: "./theme.json" }] } }),+ { status: 200 },+ );+ }+ return new Response(JSON.stringify(extensionDetail()), { status: 200 });+ });+ vi.stubGlobal("fetch", fetchMock);++ const results = await searchOpenVsxThemes(" dracula ");++ expect(results).toEqual([+ expect.objectContaining({+ id: "demo.theme",+ name: "Demo Theme",+ publisher: "demo",+ downloadCount: 123456,+ iconUrl: `${ASSET_ROOT}/icon.png`,+ sourceUrl: "https://github.com/demo/theme",+ license: "MIT",+ }),+ ]);+ const searchUrl = new URL(String(fetchMock.mock.calls[0]![0]));+ expect(searchUrl.searchParams.get("query")).toBe("dracula");+ expect(searchUrl.searchParams.get("category")).toBe("Themes");+ expect(searchUrl.searchParams.get("sortBy")).toBe("downloadCount");+ expect(searchUrl.searchParams.get("sortOrder")).toBe("desc");+ expect(searchUrl.searchParams.get("size")).toBe("16");+ });++ it("supports sorting theme searches", async () => {+ const fetchMock = vi.fn(+ async (..._args: unknown[]) =>+ new Response(JSON.stringify({ extensions: [] }), { status: 200 }),+ );+ vi.stubGlobal("fetch", fetchMock);++ await searchOpenVsxThemes("nord", { sortBy: "rating" });++ const searchUrl = new URL(String(fetchMock.mock.calls[0]![0]));+ expect(searchUrl.searchParams.get("sortBy")).toBe("rating");+ expect(searchUrl.searchParams.get("sortOrder")).toBe("desc");+ });++ it("rejects malformed search responses", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn(async () => new Response(JSON.stringify({ error: "unavailable" }), { status: 200 })),+ );++ await expect(searchOpenVsxThemes("nord")).rejects.toThrow(+ "Open VSX returned an unreadable search response.",+ );+ });++ it("reports an unavailable search when every detail request fails", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn(async (input: RequestInfo | URL) => {+ if (String(input).includes("/-/search?")) {+ return new Response(+ JSON.stringify({ extensions: [{ namespace: "demo", name: "theme" }] }),+ { status: 200 },+ );+ }+ return new Response(null, { status: 429 });+ }),+ );++ await expect(searchOpenVsxThemes("dracula")).rejects.toThrow(+ "Open VSX theme details are unavailable",+ );+ });++ it("reports an unavailable search when every detail response is malformed", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn(async (input: RequestInfo | URL) => {+ if (String(input).includes("/-/search?")) {+ return new Response(+ JSON.stringify({ extensions: [{ namespace: "demo", name: "theme" }] }),+ { status: 200 },+ );+ }+ return new Response("{}", { status: 200 });+ }),+ );++ await expect(searchOpenVsxThemes("dracula")).rejects.toThrow(+ "Open VSX theme details are unavailable",+ );+ });++ it("returns no results when every theme package is unavailable", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input);+ if (url.includes("/-/search?")) {+ return new Response(+ JSON.stringify({ extensions: [{ namespace: "demo", name: "theme" }] }),+ { status: 200 },+ );+ }+ if (url.endsWith("/demo/theme")) {+ return new Response(JSON.stringify(extensionDetail()), { status: 200 });+ }+ if (init?.method === "HEAD") return new Response(null, { status: 404 });+ return new Response(+ JSON.stringify({ license: "MIT", contributes: { themes: [{ path: "./theme.json" }] } }),+ { status: 200 },+ );+ }),+ );++ await expect(searchOpenVsxThemes("dracula")).resolves.toEqual([]);+ });++ it("times out a stalled search request", async () => {+ vi.useFakeTimers();+ vi.stubGlobal(+ "fetch",+ vi.fn(+ (_input: RequestInfo | URL, init?: RequestInit) =>+ new Promise<Response>((_resolve, reject) => {+ init?.signal?.addEventListener("abort", () => {+ reject(new DOMException("The operation was aborted.", "AbortError"));+ });+ }),+ ),+ );++ const search = expect(searchOpenVsxThemes("dracula")).rejects.toThrow(+ "Open VSX took too long to respond",+ );+ await vi.advanceTimersByTimeAsync(10_000);++ await search;+ });++ it("downloads a verified VSIX, reads JSONC includes, and pairs contributed variants", async () => {+ const zip = new JSZip();+ zip.file("extension/.gitkeep", "");+ zip.file(+ "extension/themes/base.jsonc",+ `{+ // inherited workbench colors+ "colors": {+ "editor.foreground": "#eeeeee",+ "focusBorder": "#8b5cf6",+ },+ }`,+ );+ zip.file(+ "extension/themes/demo-dark.json",+ `{+ "include": "./base.jsonc",+ "colors": { "editor.background": "#111111" }+ }`,+ );+ zip.file(+ "extension/themes/demo-light.json",+ `{+ "colors": {+ "editor.background": "#fafafa",+ "editor.foreground": "#222222",+ "focusBorder": "#8b5cf6"+ }+ }`,+ );+ zip.file(+ "extension/themes/demo.json",+ `{+ "colors": {+ "editor.background": "#181818",+ "editor.foreground": "#eeeeee"+ }+ }`,+ );+ const packagedManifest = {+ publisher: "demo",+ name: "theme",+ version: "1.0.0",+ license: "MIT",+ contributes: {+ themes: [+ { label: "Demo Dark", uiTheme: "vs-dark", path: "./themes/demo-dark.json" },+ { label: "Demo Light", uiTheme: "vs", path: "./themes/demo-light.json" },+ { label: "Demo", uiTheme: "vs-dark", path: "./themes/demo.json" },+ ],+ },+ };+ let packageBytes = new ArrayBuffer(0);+ let checksum = "";+ const rebuildPackage = async () => {+ zip.file("extension/package.json", JSON.stringify(packagedManifest));+ packageBytes = await zip.generateAsync({+ type: "arraybuffer",+ comment: `PK\u0005\u0006${"x".repeat(26)}`,+ });+ checksum = [...sha256(new Uint8Array(packageBytes))]+ .map((byte) => byte.toString(16).padStart(2, "0"))+ .join("");+ };+ await rebuildPackage();+ // The public manifest is only a preflight hint. Imports must use the manifest+ // inside the checksummed VSIX rather than this inconsistent contribution.+ const manifest = {+ contributes: { themes: [{ label: "Wrong", path: "./themes/missing.json" }] },+ };+ const extension: OpenVsxThemeExtension = {+ collectionId: "open-vsx:demo.theme",+ id: "demo.theme",+ name: "Demo Theme",+ publisher: "demo",+ description: "",+ downloadCount: 1,+ iconUrl: null,+ sourceUrl: null,+ license: "MIT",+ manifestUrl: `${ASSET_ROOT}/package.json`,+ sha256Url: `${ASSET_ROOT}/demo.theme-1.0.0.sha256`,+ version: "1.0.0",+ vsixUrl: `${ASSET_ROOT}/demo.theme-1.0.0.vsix`,+ };+ vi.stubGlobal(+ "fetch",+ vi.fn(async (input: string | URL | Request) => {+ const url = String(input);+ if (url === extension.manifestUrl) {+ return new Response(JSON.stringify(manifest), { status: 200 });+ }+ if (url === extension.sha256Url) return new Response(`${checksum} demo.vsix`);+ return new Response(packageBytes, {+ status: 200,+ headers: { "Content-Length": String(packageBytes.byteLength) },+ });+ }),+ );++ const themes = await importOpenVsxThemeExtension(extension);++ expect(themes).toHaveLength(2);+ expect(new Set(themes.map((theme) => theme.id)).size).toBe(2);+ expect(themes.every((theme) => /^ovx-[a-z0-9-]+-[0-9a-f]{12}$/.test(theme.id))).toBe(true);+ expect(themes.every((theme) => theme.collection?.id === "open-vsx:demo.theme")).toBe(true);+ const paired = themes.find(+ (theme) =>+ getThemeColorsForMode(theme, "light") !== null &&+ getThemeColorsForMode(theme, "dark") !== null,+ )!;+ expect(paired.label).toBe("Demo");+ expect(themeColorToHex(paired.colors.canvas)).toBe("#fafafa");+ expect(themeColorToHex(getThemeColorsForMode(paired, "dark")!.canvas)).toBe("#111111");+ expect(themeColorToHex(getThemeColorsForMode(paired, "dark")!.text)).toBe("#eeeeee");++ packagedManifest.contributes.themes[0]!.label = "Renamed Dark";+ packagedManifest.contributes.themes[1]!.label = "Renamed Light";+ packagedManifest.contributes.themes[2]!.label = "Renamed Solo";+ await rebuildPackage();+ const renamedThemes = await importOpenVsxThemeExtension(extension);+ expect(renamedThemes.map((theme) => theme.id)).toEqual(themes.map((theme) => theme.id));++ packagedManifest.contributes.themes.push({+ label: "Duplicate Demo",+ uiTheme: "vs-dark",+ path: "./themes/demo.json",+ });+ await rebuildPackage();+ const duplicatePathThemes = await importOpenVsxThemeExtension(extension);+ expect(new Set(duplicatePathThemes.map((theme) => theme.id)).size).toBe(+ duplicatePathThemes.length,+ );+ expect(themes.every(({ id }) => duplicatePathThemes.some((theme) => theme.id === id))).toBe(+ true,+ );+ packagedManifest.contributes.themes.pop();++ packagedManifest.contributes.themes[2]!.path = "./themes/missing.json";+ await rebuildPackage();+ await expect(importOpenVsxThemeExtension(extension)).rejects.toThrow(+ "could not be imported safely",+ );+ packagedManifest.contributes.themes[2]!.path = "./themes/demo.json";++ packagedManifest.license = "Proprietary";+ await rebuildPackage();+ await expect(importOpenVsxThemeExtension(extension)).rejects.toThrow(+ "does not match its advertised license",+ );++ Reflect.deleteProperty(packagedManifest, "license");+ await rebuildPackage();+ await expect(importOpenVsxThemeExtension(extension)).rejects.toThrow(+ "does not match its advertised license",+ );+ });++ it("stops import work when the request is cancelled", async () => {+ const packageBytes = new Uint8Array([1, 2, 3]);+ const checksum = [...sha256(packageBytes)]+ .map((byte) => byte.toString(16).padStart(2, "0"))+ .join("");+ const controller = new AbortController();+ const extension: OpenVsxThemeExtension = {+ collectionId: "open-vsx:demo.theme",+ id: "demo.theme",+ name: "Demo Theme",+ publisher: "demo",+ description: "",+ downloadCount: 1,+ iconUrl: null,+ sourceUrl: null,+ license: "MIT",+ manifestUrl: `${ASSET_ROOT}/package.json`,+ sha256Url: `${ASSET_ROOT}/demo.theme-1.0.0.sha256`,+ version: "1.0.0",+ vsixUrl: `${ASSET_ROOT}/demo.theme-1.0.0.vsix`,+ };+ vi.stubGlobal(+ "fetch",+ vi.fn(async (input: string | URL | Request) => {+ const url = String(input);+ if (url === extension.manifestUrl) {+ return new Response(+ JSON.stringify({ contributes: { themes: [{ path: "./theme.json" }] } }),+ );+ }+ if (url === extension.sha256Url) {+ controller.abort();+ return new Response(checksum);+ }+ return new Response(packageBytes);+ }),+ );++ await expect(importOpenVsxThemeExtension(extension, controller.signal)).rejects.toMatchObject({+ name: "AbortError",+ });+ });++ it("rejects a package whose Open VSX checksum does not match", async () => {+ const extension: OpenVsxThemeExtension = {+ collectionId: "open-vsx:demo.theme",+ id: "demo.theme",+ name: "Demo Theme",+ publisher: "demo",+ description: "",+ downloadCount: 1,+ iconUrl: null,+ sourceUrl: null,+ license: "MIT",+ manifestUrl: `${ASSET_ROOT}/package.json`,+ sha256Url: `${ASSET_ROOT}/demo.theme-1.0.0.sha256`,+ version: "1.0.0",+ vsixUrl: `${ASSET_ROOT}/demo.theme-1.0.0.vsix`,+ };+ vi.stubGlobal(+ "fetch",+ vi.fn(async (input: string | URL | Request) => {+ const url = String(input);+ if (url === extension.manifestUrl) {+ return new Response(+ JSON.stringify({ contributes: { themes: [{ path: "./theme.json" }] } }),+ );+ }+ if (url === extension.sha256Url) return new Response("0".repeat(64));+ return new Response(new Uint8Array([1, 2, 3]));+ }),+ );++ await expect(importOpenVsxThemeExtension(extension)).rejects.toThrow("integrity check");+ });+});diff --git a/apps/web/src/openVsxThemes.ts b/apps/web/src/openVsxThemes.tsnew file mode 100644index 000000000..90d0d62ce--- /dev/null+++ b/apps/web/src/openVsxThemes.ts@@ -0,0 +1,776 @@+import { sha256 } from "@noble/hashes/sha2";+import JSZip from "jszip";+import { parse, type ParseError } from "jsonc-parser";++import type { ThemeDefinition } from "./themePalette";+import {+ isVsCodeThemeFile,+ pairVsCodeThemes,+ parseVsCodeThemeFile,+ resolveThemeLabelCollisions,+} from "./vscodeThemeImport";++const OPEN_VSX_SEARCH_URL = "https://open-vsx.org/api/-/search";+const MAX_VSIX_BYTES = 20 * 1024 * 1024;+const MAX_SEARCH_BYTES = 512 * 1024;+const MAX_DETAIL_BYTES = 256 * 1024;+const MAX_MANIFEST_BYTES = 256 * 1024;+const SEARCH_REQUEST_TIMEOUT_MS = 10_000;+const MAX_THEME_BYTES = 256 * 1024;+const MAX_ZIP_ENTRIES = 2_000;+const MAX_UNCOMPRESSED_BYTES = 50 * 1024 * 1024;+const MAX_COMPRESSION_RATIO = 200;+const MAX_THEMES_PER_EXTENSION = 40;+const MAX_INCLUDE_DEPTH = 8;+const MAX_PACKAGE_PATH_LENGTH = 1_024;+const MAX_COLOR_VALUE_LENGTH = 128;+const MAX_RESOLVED_THEME_FILES = MAX_THEMES_PER_EXTENSION * MAX_INCLUDE_DEPTH;+const SUPPORTED_LICENSES = new Set([+ "0BSD",+ "Apache-2.0",+ "BSD-2-Clause",+ "BSD-3-Clause",+ "CC0-1.0",+ "ISC",+ "MIT",+ "MPL-2.0",+ "Unlicense",+]);+const USED_WORKBENCH_COLORS = new Set([+ "activityBar.background",+ "activityBarBadge.background",+ "badge.background",+ "button.background",+ "button.foreground",+ "contrastBorder",+ "descriptionForeground",+ "disabledForeground",+ "dropdown.background",+ "dropdown.border",+ "editor.background",+ "editor.foreground",+ "editor.selectionBackground",+ "editorCursor.foreground",+ "editorError.foreground",+ "editorGroup.border",+ "editorPane.background",+ "editorWarning.foreground",+ "editorWidget.background",+ "errorForeground",+ "focusBorder",+ "foreground",+ "input.border",+ "input.placeholderForeground",+ "list.activeSelectionBackground",+ "list.hoverBackground",+ "list.inactiveSelectionBackground",+ "menu.background",+ "panel.background",+ "panel.border",+ "progressBar.background",+ "quickInput.background",+ "scrollbarSlider.background",+ "sideBar.background",+ "sideBar.border",+ "sideBar.foreground",+ "terminal.background",+ "terminal.foreground",+ "terminal.selectionBackground",+ "terminalCursor.foreground",+ "textCodeBlock.background",+ "textLink.foreground",+]);++export type OpenVsxThemeSort = "downloadCount" | "rating" | "timestamp" | "relevance";++export type OpenVsxThemeExtension = {+ id: string;+ collectionId: string;+ name: string;+ publisher: string;+ description: string;+ downloadCount: number;+ iconUrl: string | null;+ sourceUrl: string | null;+ manifestUrl: string;+ sha256Url: string;+ vsixUrl: string;+ version: string;+ license: string;+};++export type OpenVsxThemeSearchOptions = {+ signal?: AbortSignal;+ sortBy?: OpenVsxThemeSort;+};++type ThemeContribution = { label?: unknown; uiTheme?: unknown; path?: unknown };++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++function shortHash(value: string): string {+ return [...sha256(new TextEncoder().encode(value))]+ .slice(0, 6)+ .map((byte) => byte.toString(16).padStart(2, "0"))+ .join("");+}++function openVsxThemeId(extensionId: string, source: string): string {+ return `ovx-theme-${shortHash(`${extensionId}:${source}`)}`;+}++function openVsxCollectionId(extensionId: string): string {+ const normalized = `open-vsx:${extensionId.toLowerCase()}`;+ return /^[a-z0-9][a-z0-9.:-]{0,127}$/.test(normalized)+ ? normalized+ : `open-vsx:${shortHash(extensionId)}`;+}++function trustedOpenVsxUrl(value: unknown): string | null {+ if (typeof value !== "string") return null;+ try {+ const url = new URL(value);+ return url.protocol === "https:" && url.hostname.toLowerCase() === "open-vsx.org"+ ? url.toString()+ : null;+ } catch {+ return null;+ }+}++function publicSourceUrl(value: unknown): string | null {+ const rawValue =+ typeof value === "string"+ ? value+ : isRecord(value) && typeof value.url === "string"+ ? value.url+ : null;+ if (!rawValue) return null;+ try {+ const url = new URL(rawValue);+ return url.protocol === "https:" && !url.username && !url.password ? url.toString() : null;+ } catch {+ return null;+ }+}++function themeContributions(manifest: Record<string, unknown>): ThemeContribution[] {+ const contributes = isRecord(manifest.contributes) ? manifest.contributes : null;+ return Array.isArray(contributes?.themes)+ ? (contributes.themes.filter(isRecord) as ThemeContribution[])+ : [];+}++function manifestLicenseMatches(manifest: Record<string, unknown>, license: string): boolean {+ return (+ typeof manifest.license === "string" &&+ manifest.license.trim().toLowerCase() === license.toLowerCase()+ );+}++function extensionFromDetail(value: unknown): OpenVsxThemeExtension | null {+ if (!isRecord(value) || !isRecord(value.files)) {+ throw new Error("Open VSX returned malformed theme details.");+ }+ const namespace = typeof value.namespace === "string" ? value.namespace.trim() : "";+ const extensionName = typeof value.name === "string" ? value.name.trim() : "";+ const displayName =+ (typeof value.displayName === "string" ? value.displayName.trim() : "") || extensionName;+ const version = typeof value.version === "string" ? value.version.trim() : "";+ const license = typeof value.license === "string" ? value.license.trim() : "";+ const manifestUrl = trustedOpenVsxUrl(value.files.manifest);+ const sha256Url = trustedOpenVsxUrl(value.files.sha256);+ const vsixUrl = trustedOpenVsxUrl(value.files.download);+ if (!namespace || !extensionName || !version || !manifestUrl || !sha256Url || !vsixUrl) {+ throw new Error("Open VSX returned malformed theme details.");+ }+ if (!SUPPORTED_LICENSES.has(license)) return null;+ const id = `${namespace}.${extensionName}`;+ return {+ id,+ collectionId: openVsxCollectionId(id),+ name: displayName,+ publisher: namespace,+ description: typeof value.description === "string" ? value.description : "",+ downloadCount:+ typeof value.downloadCount === "number" && Number.isFinite(value.downloadCount)+ ? value.downloadCount+ : 0,+ iconUrl: trustedOpenVsxUrl(value.files.icon),+ sourceUrl:+ publicSourceUrl(value.repository) ??+ publicSourceUrl(value.homepage) ??+ publicSourceUrl(value.url),+ manifestUrl,+ sha256Url,+ vsixUrl,+ version,+ license,+ };+}++async function withSearchTimeout<T>(+ operation: (signal: AbortSignal) => Promise<T>,+ parentSignal?: AbortSignal,+): Promise<T> {+ const controller = new AbortController();+ const abort = () => controller.abort();+ if (parentSignal?.aborted) abort();+ else parentSignal?.addEventListener("abort", abort, { once: true });+ const timeout = setTimeout(abort, SEARCH_REQUEST_TIMEOUT_MS);+ try {+ return await operation(controller.signal);+ } catch (cause) {+ if (controller.signal.aborted && !parentSignal?.aborted) {+ throw new Error("Open VSX took too long to respond.", { cause });+ }+ throw cause;+ } finally {+ clearTimeout(timeout);+ parentSignal?.removeEventListener("abort", abort);+ }+}++export async function searchOpenVsxThemes(+ query: string,+ { signal, sortBy = "downloadCount" }: OpenVsxThemeSearchOptions = {},+): Promise<OpenVsxThemeExtension[]> {+ const searchText = query.trim();+ if (!searchText) return [];+ const url = new URL(OPEN_VSX_SEARCH_URL);+ url.searchParams.set("query", searchText);+ url.searchParams.set("category", "Themes");+ url.searchParams.set("sortBy", sortBy);+ url.searchParams.set("sortOrder", "desc");+ // Ask for a few extras because results without a supported SPDX license+ // are intentionally omitted.+ url.searchParams.set("size", "16");+ const value = await withSearchTimeout(async (requestSignal) => {+ const response = await fetch(url, { signal: requestSignal });+ if (!response.ok) throw new Error("Open VSX search is unavailable right now.");+ const searchBytes = await readCappedResponse(+ response,+ MAX_SEARCH_BYTES,+ "Open VSX returned an unexpectedly large response.",+ );+ try {+ return JSON.parse(new TextDecoder().decode(searchBytes)) as unknown;+ } catch {+ throw new Error("Open VSX returned an unreadable response.");+ }+ }, signal);+ if (!isRecord(value) || !Array.isArray(value.extensions)) {+ throw new Error("Open VSX returned an unreadable search response.");+ }+ const identities = value.extensions.flatMap((candidate): Array<[string, string]> => {+ if (!isRecord(candidate)) return [];+ const namespace = typeof candidate.namespace === "string" ? candidate.namespace : "";+ const name = typeof candidate.name === "string" ? candidate.name : "";+ return namespace && name ? [[namespace, name]] : [];+ });+ const details = await Promise.allSettled(+ identities.slice(0, 16).map(([namespace, name]) =>+ withSearchTimeout(async (requestSignal) => {+ const detailUrl = `https://open-vsx.org/api/${encodeURIComponent(namespace)}/${encodeURIComponent(name)}`;+ const detailResponse = await fetch(detailUrl, { signal: requestSignal });+ if (!detailResponse.ok) throw new Error("Open VSX theme details are unavailable.");+ const detailBytes = await readCappedResponse(+ detailResponse,+ MAX_DETAIL_BYTES,+ "Open VSX returned an unexpectedly large detail response.",+ );+ try {+ const extension = extensionFromDetail(JSON.parse(new TextDecoder().decode(detailBytes)));+ if (!extension) return null;+ const [manifestResponse, packageResponse] = await Promise.all([+ fetch(extension.manifestUrl, { signal: requestSignal }),+ fetch(extension.vsixUrl, { method: "HEAD", signal: requestSignal }),+ ]);+ if (!manifestResponse.ok) throw new Error("manifest unavailable");+ if (!packageResponse.ok) return null;+ const packageLength = Number(packageResponse.headers.get("content-length"));+ if (Number.isFinite(packageLength) && packageLength > MAX_VSIX_BYTES) {+ return null;+ }+ const manifestBytes = await readCappedResponse(+ manifestResponse,+ MAX_MANIFEST_BYTES,+ "Open VSX returned an unexpectedly large manifest.",+ );+ const manifest = parseJsoncObject(+ new TextDecoder().decode(manifestBytes),+ "Extension manifest",+ );+ return themeContributions(manifest).length > 0 &&+ manifestLicenseMatches(manifest, extension.license)+ ? extension+ : null;+ } catch {+ throw new Error("Open VSX returned unreadable theme details.");+ }+ }, signal),+ ),+ );+ if (signal?.aborted) throw new DOMException("The operation was aborted.", "AbortError");+ const completedDetails = details.filter((result) => result.status === "fulfilled");+ if (identities.length > 0 && completedDetails.length === 0) {+ throw new Error("Open VSX theme details are unavailable right now.");+ }+ return completedDetails.flatMap((result) => (result.value ? [result.value] : [])).slice(0, 8);+}++function parseJsoncObject(source: string, description: string): Record<string, unknown> {+ const errors: ParseError[] = [];+ const value: unknown = parse(source, errors, { allowTrailingComma: true });+ if (errors.length > 0 || !isRecord(value)) throw new Error(`${description} is not valid JSON.`);+ return value;+}++function sanitizeThemeObject(value: Record<string, unknown>): Record<string, unknown> {+ const colors: Record<string, string> = {};+ if (isRecord(value.colors)) {+ for (const [key, color] of Object.entries(value.colors)) {+ if (+ USED_WORKBENCH_COLORS.has(key) &&+ typeof color === "string" &&+ color.length <= MAX_COLOR_VALUE_LENGTH+ ) {+ colors[key] = color;+ }+ }+ }+ return {+ ...(typeof value.include === "string" ? { include: value.include } : {}),+ colors,+ };+}++function normalizePackagePath(path: string, relativeTo = "extension/"): string {+ if (+ path.length > MAX_PACKAGE_PATH_LENGTH ||+ path.includes("\0") ||+ path.startsWith("/") ||+ /^[a-zA-Z]:/.test(path)+ ) {+ throw new Error("Theme path is not a safe relative package path.");+ }+ const normalizedInput = path.replaceAll("\\", "/");+ const baseSegments = relativeTo.split("/").slice(0, -1);+ const segments = baseSegments;+ for (const segment of normalizedInput.split("/")) {+ if (!segment || segment === ".") continue;+ if (segment === "..") {+ if (segments.length <= 1) throw new Error("Theme path escapes the extension package.");+ segments.pop();+ continue;+ }+ segments.push(segment);+ }+ if (segments[0] !== "extension") segments.unshift("extension");+ return segments.join("/");+}++function contributionType(uiTheme: unknown): string | null {+ if (uiTheme === "vs") return "light";+ if (uiTheme === "vs-dark") return "dark";+ if (uiTheme === "hc-black" || uiTheme === "hc-light") return uiTheme;+ return null;+}++type ZipEntrySizes = {+ uncompressedSize?: unknown;+};++type InspectableZipObject = JSZip.JSZipObject & {+ _data?: ZipEntrySizes;+ unsafeOriginalName?: string;+ internalStream?: (type: "uint8array") => JSZip.JSZipStreamHelper<Uint8Array>;+};++function inspectZipDirectory(bytes: Uint8Array): Uint8Array {+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);+ const minimumOffset = Math.max(0, bytes.byteLength - 65_557);+ let endOffset = bytes.byteLength - 22;+ while (+ endOffset >= minimumOffset &&+ (view.getUint32(endOffset, true) !== 0x06054b50 ||+ endOffset + 22 + view.getUint16(endOffset + 20, true) !== bytes.byteLength)+ ) {+ endOffset -= 1;+ }+ if (endOffset < minimumOffset) throw new Error("That extension package has no ZIP directory.");++ const directorySize = view.getUint32(endOffset + 12, true);+ const directoryOffset = view.getUint32(endOffset + 16, true);+ const directoryEnd = directoryOffset + directorySize;+ if (directoryEnd !== endOffset || directoryEnd > bytes.byteLength) {+ throw new Error("That extension package has an invalid ZIP directory.");+ }++ let entryCount = 0;+ let totalUncompressed = 0;+ let offset = directoryOffset;+ while (offset < directoryEnd) {+ if (offset + 46 > directoryEnd || view.getUint32(offset, true) !== 0x02014b50) {+ throw new Error("That extension package has an invalid ZIP directory.");+ }+ entryCount += 1;+ if (entryCount > MAX_ZIP_ENTRIES) {+ throw new Error("That extension package has too many files.");+ }+ const compressed = view.getUint32(offset + 20, true);+ const uncompressed = view.getUint32(offset + 24, true);+ if (compressed === 0xffffffff || uncompressed === 0xffffffff) {+ throw new Error("That extension package has unsupported ZIP64 metadata.");+ }+ totalUncompressed += uncompressed;+ if (totalUncompressed > MAX_UNCOMPRESSED_BYTES) {+ throw new Error("That extension package expands beyond the safe import limit.");+ }+ if (+ uncompressed > 0 &&+ (compressed === 0 || uncompressed / compressed > MAX_COMPRESSION_RATIO)+ ) {+ throw new Error("That extension package has an unsafe compression ratio.");+ }+ const nameLength = view.getUint16(offset + 28, true);+ const extraLength = view.getUint16(offset + 30, true);+ const commentLength = view.getUint16(offset + 32, true);+ offset += 46 + nameLength + extraLength + commentLength;+ }+ if (offset !== directoryEnd)+ throw new Error("That extension package has an invalid ZIP directory.");++ const commentLength = view.getUint16(endOffset + 20, true);+ if (commentLength === 0) return bytes;++ // JSZip mistakes EOCD-like bytes inside an archive comment for the real EOCD.+ // The comment is not needed for theme import, so remove it before parsing.+ const withoutComment = bytes.slice(0, endOffset + 22);+ withoutComment[endOffset + 20] = 0;+ withoutComment[endOffset + 21] = 0;+ return withoutComment;+}++function inspectZip(zip: JSZip): void {+ const entries = Object.values(zip.files) as InspectableZipObject[];+ if (entries.length > MAX_ZIP_ENTRIES)+ throw new Error("That extension package has too many files.");++ for (const entry of entries) {+ if (entry.unsafeOriginalName) normalizePackagePath(entry.unsafeOriginalName);+ }+}++async function readZipText(+ zip: JSZip,+ path: string,+ description: string,+ signal?: AbortSignal,+): Promise<string> {+ signal?.throwIfAborted();+ const file = zip.file(path) as InspectableZipObject | null;+ if (!file) throw new Error(`${description} is missing from the extension package.`);+ if (typeof file._data?.uncompressedSize !== "number" || !file.internalStream) {+ throw new Error(`${description} has unreadable size metadata.`);+ }+ if (file._data.uncompressedSize > MAX_THEME_BYTES) {+ throw new Error(`${description} is too large.`);+ }++ return new Promise((resolve, reject) => {+ const chunks: Uint8Array[] = [];+ let byteLength = 0;+ let settled = false;+ const stream = file.internalStream!("uint8array");+ const cleanup = () => signal?.removeEventListener("abort", handleAbort);+ const handleAbort = () => {+ if (settled) return;+ settled = true;+ stream.pause();+ cleanup();+ reject(signal?.reason);+ };+ signal?.addEventListener("abort", handleAbort, { once: true });+ stream+ .on("data", (chunk) => {+ if (settled) return;+ byteLength += chunk.byteLength;+ if (byteLength > MAX_THEME_BYTES) {+ settled = true;+ stream.pause();+ cleanup();+ reject(new Error(`${description} is too large.`));+ return;+ }+ chunks.push(chunk);+ })+ .on("error", (cause) => {+ if (settled) return;+ settled = true;+ cleanup();+ reject(cause);+ })+ .on("end", () => {+ if (settled) return;+ settled = true;+ cleanup();+ const bytes = new Uint8Array(byteLength);+ let offset = 0;+ for (const chunk of chunks) {+ bytes.set(chunk, offset);+ offset += chunk.byteLength;+ }+ resolve(new TextDecoder().decode(bytes));+ })+ .resume();+ });+}++async function loadThemeObject(+ zip: JSZip,+ path: string,+ cache: Map<string, Record<string, unknown>>,+ budget: { files: number },+ ancestors: ReadonlySet<string> = new Set(),+ signal?: AbortSignal,+): Promise<Record<string, unknown>> {+ signal?.throwIfAborted();+ if (ancestors.size >= MAX_INCLUDE_DEPTH) throw new Error("Theme includes are nested too deeply.");+ if (ancestors.has(path)) throw new Error("Theme includes contain a cycle.");+ const cached = cache.get(path);+ if (cached) return cached;+ budget.files += 1;+ if (budget.files > MAX_RESOLVED_THEME_FILES) {+ throw new Error("That extension references too many theme files.");+ }++ const value = sanitizeThemeObject(+ parseJsoncObject(await readZipText(zip, path, path, signal), path),+ );+ if (typeof value.include !== "string") {+ cache.set(path, value);+ return value;+ }++ const includePath = normalizePackagePath(value.include, path);+ const nextAncestors = new Set(ancestors);+ nextAncestors.add(path);+ const base = await loadThemeObject(zip, includePath, cache, budget, nextAncestors, signal);+ const resolved = {+ ...base,+ ...value,+ colors: {+ ...(isRecord(base.colors) ? base.colors : {}),+ ...(isRecord(value.colors) ? value.colors : {}),+ },+ };+ cache.set(path, resolved);+ return resolved;+}++async function readCappedResponse(+ response: Response,+ limit: number,+ tooLargeMessage: string,+): Promise<Uint8Array> {+ const contentLength = response.headers.get("content-length");+ if (contentLength && Number(contentLength) > limit) throw new Error(tooLargeMessage);+ if (!response.body) {+ const bytes = new Uint8Array(await response.arrayBuffer());+ if (bytes.byteLength > limit) throw new Error(tooLargeMessage);+ return bytes;+ }++ const reader = response.body.getReader();+ const chunks: Uint8Array[] = [];+ let byteLength = 0;+ try {+ while (true) {+ const { done, value } = await reader.read();+ if (done) break;+ byteLength += value.byteLength;+ if (byteLength > limit) {+ await reader.cancel();+ throw new Error(tooLargeMessage);+ }+ chunks.push(value);+ }+ } finally {+ reader.releaseLock();+ }++ const result = new Uint8Array(byteLength);+ let offset = 0;+ for (const chunk of chunks) {+ result.set(chunk, offset);+ offset += chunk.byteLength;+ }+ return result;+}++async function fetchPackage(url: string, signal?: AbortSignal): Promise<Uint8Array> {+ const response = await fetch(url, signal ? { signal } : {});+ if (!response.ok) throw new Error("That Open VSX theme could not be downloaded.");+ return readCappedResponse(+ response,+ MAX_VSIX_BYTES,+ "That theme extension is too large to import safely.",+ );+}++export async function importOpenVsxThemeExtension(+ extension: OpenVsxThemeExtension,+ signal?: AbortSignal,+): Promise<ReadonlyArray<ThemeDefinition>> {+ const manifestResponse = await fetch(extension.manifestUrl, signal ? { signal } : {});+ if (!manifestResponse.ok) throw new Error("That Open VSX extension has no readable manifest.");+ const manifestBytes = await readCappedResponse(+ manifestResponse,+ MAX_MANIFEST_BYTES,+ "That Open VSX extension manifest is too large.",+ );+ const manifest = parseJsoncObject(new TextDecoder().decode(manifestBytes), "Extension manifest");+ const advertisedContributions = themeContributions(manifest);+ if (advertisedContributions.length === 0) {+ throw new Error("That extension does not contain color themes.");+ }+ if (advertisedContributions.length > MAX_THEMES_PER_EXTENSION) {+ throw new Error("That extension contains too many color themes to import safely.");+ }++ const packageBytes = await fetchPackage(extension.vsixUrl, signal);+ signal?.throwIfAborted();+ const checksumResponse = await fetch(extension.sha256Url, signal ? { signal } : {});+ if (!checksumResponse.ok) throw new Error("That Open VSX theme has no readable checksum.");+ const expectedChecksum = new TextDecoder()+ .decode(+ await readCappedResponse(+ checksumResponse,+ 256,+ "That Open VSX checksum response is invalid.",+ ),+ )+ .trim()+ .split(/\s+/)[0];+ if (!expectedChecksum || !/^[a-f\d]{64}$/i.test(expectedChecksum)) {+ throw new Error("That Open VSX theme has an invalid checksum.");+ }+ signal?.throwIfAborted();+ const actualChecksum = [...sha256(packageBytes)]+ .map((byte) => byte.toString(16).padStart(2, "0"))+ .join("");+ if (actualChecksum.toLowerCase() !== expectedChecksum.toLowerCase()) {+ throw new Error("That Open VSX theme failed its integrity check.");+ }+ signal?.throwIfAborted();+ let zip: JSZip;+ try {+ const inspectedPackageBytes = inspectZipDirectory(packageBytes);+ zip = await JSZip.loadAsync(inspectedPackageBytes);+ signal?.throwIfAborted();+ inspectZip(zip);+ } catch (cause) {+ if (signal?.aborted) signal.throwIfAborted();+ if (cause instanceof Error && cause.message.startsWith("That extension package")) throw cause;+ throw new Error("That Open VSX extension package could not be opened.", { cause });+ }++ const packagedManifest = parseJsoncObject(+ await readZipText(zip, "extension/package.json", "Extension manifest", signal),+ "Extension manifest",+ );+ if (+ typeof packagedManifest.publisher !== "string" ||+ packagedManifest.publisher.toLowerCase() !== extension.publisher.toLowerCase() ||+ typeof packagedManifest.name !== "string" ||+ `${packagedManifest.publisher}.${packagedManifest.name}`.toLowerCase() !==+ extension.id.toLowerCase() ||+ packagedManifest.version !== extension.version+ ) {+ throw new Error("That extension package does not match the selected Open VSX theme.");+ }+ if (!manifestLicenseMatches(packagedManifest, extension.license)) {+ throw new Error("That extension package does not match its advertised license.");+ }+ const contributions = themeContributions(packagedManifest);+ if (contributions.length === 0) throw new Error("That extension does not contain color themes.");+ if (contributions.length > MAX_THEMES_PER_EXTENSION) {+ throw new Error("That extension contains too many color themes to import safely.");+ }++ const parsed: Array<{ theme: ThemeDefinition; sourceName: string; sourcePath: string }> = [];+ const failures: string[] = [];+ const themeCache = new Map<string, Record<string, unknown>>();+ const themeBudget = { files: 0 };+ for (const contribution of contributions) {+ signal?.throwIfAborted();+ if (typeof contribution.path !== "string") {+ failures.push("theme path is missing");+ continue;+ }+ try {+ const path = normalizePackagePath(contribution.path);+ const themeValue = await loadThemeObject(+ zip,+ path,+ themeCache,+ themeBudget,+ new Set(),+ signal,+ );+ const type = contributionType(contribution.uiTheme);+ const label =+ typeof contribution.label === "string" && contribution.label.trim()+ ? contribution.label.trim()+ : extension.name;+ const decorated = {+ ...themeValue,+ displayName: label,+ ...(type ? { type } : {}),+ };+ if (!isVsCodeThemeFile(decorated)) throw new Error("not a VS Code color theme");+ parsed.push({+ theme: parseVsCodeThemeFile(decorated),+ sourceName: path.split("/").at(-1)!,+ sourcePath: path,+ });+ } catch (cause) {+ signal?.throwIfAborted();+ failures.push(cause instanceof Error ? cause.message : "theme could not be read");+ }+ }+ if (failures.length > 0) {+ throw new Error("One or more color themes in that extension could not be imported safely.");+ }+ if (parsed.length === 0) {+ throw new Error("That extension has no compatible color themes.");+ }+ const extensionId = extension.id.toLowerCase();+ const sourcePathCounts = new Map<string, number>();+ for (const { sourcePath } of parsed) {+ sourcePathCounts.set(sourcePath, (sourcePathCounts.get(sourcePath) ?? 0) + 1);+ }+ const sourcePathOccurrences = new Map<string, number>();+ const sourceIdentities = parsed.map(({ sourcePath }) => {+ if (sourcePathCounts.get(sourcePath) === 1) return sourcePath;+ const occurrence = sourcePathOccurrences.get(sourcePath) ?? 0;+ sourcePathOccurrences.set(sourcePath, occurrence + 1);+ return occurrence === 0 ? sourcePath : `${sourcePath}\0${occurrence}`;+ });+ const resolved = resolveThemeLabelCollisions(parsed).map((theme, index) => ({+ ...theme,+ id: openVsxThemeId(extensionId, sourceIdentities[index]!),+ }));+ const paired = pairVsCodeThemes(resolved, {+ pairedId: (light, dark) => openVsxThemeId(extensionId, [light.id, dark.id].sort().join(":")),+ });+ const themes = resolveThemeLabelCollisions(paired.map((theme) => ({ theme })));+ const collection = {+ id: extension.collectionId,+ label: extension.name.slice(0, 48),+ };+ return themes.map((theme) => ({ ...theme, collection }));+}diff --git a/apps/web/src/themePalette.test.ts b/apps/web/src/themePalette.test.tsindex c19652088..95ce10af9 100644--- a/apps/web/src/themePalette.test.ts+++ b/apps/web/src/themePalette.test.ts@@ -10,12 +10,15 @@ import {getThemePreferenceMode,isKnownThemePreference,getCustomThemes,+ getStoredCustomThemeCollection,invalidateCustomThemes,installCustomTheme,canonicalThemePreference,parseThemeFile,parseThemeHalves,removeCustomTheme,+ removeCustomThemes,+ replaceCustomThemeCollection,resolveDesktopTheme,resolveThemeAppearance,serializeThemeFile,@@ -277,6 +280,28 @@ describe("theme files", () => {});});+ it("serializes a theme back into the importable file shape", () => {+ const theme = {+ ...parseThemeFile({+ version: THEME_FILE_VERSION,+ id: "community-demo",+ name: "Community Demo",+ appearance: "dark",+ colors: { canvas: "#111111" },+ }),+ collection: { id: "open-vsx:demo.theme", label: "Demo Theme" },+ };+ const serialized = serializeThemeFile(theme);+ expect(JSON.parse(serialized)).toMatchObject({+ version: THEME_FILE_VERSION,+ id: theme.id,+ name: theme.label,+ appearance: "dark",+ collection: theme.collection,+ });+ expect(parseThemeFile(JSON.parse(serialized)).collection).toEqual(theme.collection);+ });+it("keeps sidebar artwork disabled for custom theme files", () => {const theme = parseThemeFile({version: THEME_FILE_VERSION,@@ -491,6 +516,178 @@ describe("theme files", () => {vi.unstubAllGlobals();});+ it("preserves valid imported-theme collections and drops malformed metadata", () => {+ vi.stubGlobal("window", {+ localStorage: {+ getItem: (key: string) =>+ key === CUSTOM_THEMES_STORAGE_KEY+ ? JSON.stringify([+ {+ id: "github-dark",+ label: "GitHub Dark",+ appearance: "dark",+ colors: { canvas: "#0d1117" },+ collection: { id: "open-vsx:github.github-vscode-theme", label: "GitHub Theme" },+ },+ {+ id: "github-light",+ label: "GitHub Light",+ appearance: "light",+ colors: { canvas: "#ffffff" },+ collection: { id: "bad collection id", label: "GitHub Theme" },+ },+ ])+ : null,+ },+ });++ invalidateCustomThemes();+ expect(getCustomThemes()).toMatchObject([+ { collection: { id: "open-vsx:github.github-vscode-theme", label: "GitHub Theme" } },+ { id: "github-light" },+ ]);+ expect(getCustomThemes()[1]).not.toHaveProperty("collection");++ vi.unstubAllGlobals();+ invalidateCustomThemes();+ });++ it("atomically replaces an imported collection and removes stale variants", () => {+ const collection = { id: "open-vsx:demo.theme", label: "Demo Theme" };+ const personalTheme = {+ id: "personal",+ label: "Personal",+ appearance: "dark",+ colors: { canvas: "#111111", futureRole: "hsl(10 20% 30%)" },+ futureMetadata: { version: 2 },+ };+ const stored = new Map<string, string>([+ [+ CUSTOM_THEMES_STORAGE_KEY,+ JSON.stringify([+ personalTheme,+ {+ id: "old-light",+ label: "Old Light",+ appearance: "light",+ colors: { canvas: "#ffffff" },+ collection,+ },+ {+ id: "removed-dark",+ label: "Removed Dark",+ appearance: "dark",+ colors: { canvas: "#000000" },+ collection,+ },+ ]),+ ],+ ]);+ const setItem = vi.fn((key: string, value: string) => stored.set(key, value));+ vi.stubGlobal("window", {+ localStorage: {+ getItem: (key: string) => stored.get(key) ?? null,+ setItem,+ },+ });++ invalidateCustomThemes();+ const expectedCollection = getStoredCustomThemeCollection(collection.id);+ getCustomThemes();+ const concurrentlyAddedTheme = {+ id: "other-tab",+ label: "Other Tab",+ appearance: "dark",+ colors: { canvas: "#222222" },+ };+ stored.set(+ CUSTOM_THEMES_STORAGE_KEY,+ JSON.stringify([+ ...JSON.parse(stored.get(CUSTOM_THEMES_STORAGE_KEY) ?? "[]"),+ concurrentlyAddedTheme,+ ]),+ );+ const replacement = [+ {+ ...parseThemeFile({+ version: THEME_FILE_VERSION,+ id: "old-light",+ name: "New Light",+ appearance: "light",+ colors: { canvas: "#fafafa" },+ }),+ collection,+ },+ {+ ...parseThemeFile({+ version: THEME_FILE_VERSION,+ id: "new-dark",+ name: "New Dark",+ appearance: "dark",+ colors: { canvas: "#101010" },+ }),+ collection,+ },+ ];++ expect(+ replaceCustomThemeCollection(collection.id, replacement, { expectedCollection }),+ ).toEqual(replacement);+ expect(getCustomThemes().map((theme) => theme.id)).toEqual([+ "personal",+ "old-light",+ "new-dark",+ "other-tab",+ ]);+ expect(setItem).toHaveBeenCalledTimes(1);+ expect(JSON.parse(stored.get(CUSTOM_THEMES_STORAGE_KEY) ?? "[]")[0]).toEqual(personalTheme);++ vi.unstubAllGlobals();+ invalidateCustomThemes();+ });++ it("replaces collection entries even when their stored collection label is malformed", () => {+ const collection = { id: "open-vsx:demo.theme", label: "Demo Theme" };+ const stored = new Map<string, string>([+ [+ CUSTOM_THEMES_STORAGE_KEY,+ JSON.stringify([+ {+ id: "old-light",+ label: "Old Light",+ appearance: "light",+ colors: { canvas: "#ffffff" },+ collection: { id: collection.id, label: 42 },+ },+ ]),+ ],+ ]);+ vi.stubGlobal("window", {+ localStorage: {+ getItem: (key: string) => stored.get(key) ?? null,+ setItem: (key: string, value: string) => stored.set(key, value),+ },+ });++ invalidateCustomThemes();+ const replacement = {+ ...parseThemeFile({+ version: THEME_FILE_VERSION,+ id: "old-light",+ name: "New Light",+ appearance: "light",+ colors: { canvas: "#fafafa" },+ }),+ collection,+ };++ expect(replaceCustomThemeCollection(collection.id, [replacement])).toEqual([replacement]);+ expect(getCustomThemes()).toEqual([replacement]);++ vi.unstubAllGlobals();+ invalidateCustomThemes();+ });+it("canonicalizes explicit writes without migrating untouched themes", () => {const stored = new Map<string, string>();const untouchedTheme = {@@ -551,6 +748,56 @@ describe("theme files", () => {invalidateCustomThemes();});+ it("removes multiple custom themes atomically while preserving unrelated entries", () => {+ const collection = { id: "open-vsx:demo.theme", label: "Demo Theme" };+ const personalTheme = {+ id: "personal",+ label: "Personal",+ appearance: "dark",+ colors: { canvas: "#111111", futureRole: "hsl(10 20% 30%)" },+ futureMetadata: { version: 2 },+ };+ const stored = new Map<string, string>([+ [+ CUSTOM_THEMES_STORAGE_KEY,+ JSON.stringify([+ personalTheme,+ {+ id: "demo-light",+ label: "Demo Light",+ appearance: "light",+ colors: { canvas: "#ffffff" },+ collection,+ },+ {+ id: "demo-dark",+ label: "Demo Dark",+ appearance: "dark",+ colors: { canvas: "#000000" },+ collection,+ },+ ]),+ ],+ ]);+ const setItem = vi.fn((key: string, value: string) => stored.set(key, value));+ vi.stubGlobal("window", {+ localStorage: {+ getItem: (key: string) => stored.get(key) ?? null,+ setItem,+ },+ });++ invalidateCustomThemes();+ removeCustomThemes(["demo-light", "demo-dark"]);++ expect(setItem).toHaveBeenCalledOnce();+ expect(getCustomThemes()).toEqual([expect.objectContaining({ id: "personal" })]);+ expect(JSON.parse(stored.get(CUSTOM_THEMES_STORAGE_KEY) ?? "[]")).toEqual([personalTheme]);++ vi.unstubAllGlobals();+ invalidateCustomThemes();+ });+it("writes from the cached raw snapshot without risking a destructive reread", () => {const legacyTheme = {id: "legacy",diff --git a/apps/web/src/themePalette.ts b/apps/web/src/themePalette.tsindex 05838f5f5..00b29dce8 100644--- a/apps/web/src/themePalette.ts+++ b/apps/web/src/themePalette.ts@@ -92,12 +92,15 @@ export type ThemeColorOverrides = Readonly<Partial<Record<ThemeColorRole, stringexport type ThemeVariants = Readonly<Partial<Record<ThemeAppearance, ThemeColors>>>;export type ThemeVariantOverrides = Readonly<Partial<Record<ThemeAppearance, ThemeColorOverrides>>>;export type ThemePreferenceMode = ThemeAppearance | "system";+export type ThemeCollection = Readonly<{ id: string; label: string }>;export type ThemeDefinition = Readonly<{id: string;label: string;appearance: ThemeAppearance;colors: ThemeColors;variants?: ThemeVariants;+ /** Groups related imported variants into one library card. */+ collection?: ThemeCollection;/** Allows Dev/Nightly artwork to render over a maintainer-controlled sidebar. */sidebarArtwork?: boolean;/** True when the palette was generated by the guided editor from its@@ -111,6 +114,7 @@ export type ThemeFile = Readonly<{appearance: ThemeAppearance;colors: ThemeColorOverrides;variants?: ThemeVariantOverrides;+ collection?: ThemeCollection;managed?: boolean;}>;@@ -179,6 +183,15 @@ function isThemeLabel(value: unknown): value is string {return typeof value === "string" && value.trim().length > 0 && value.trim().length <= 48;}+function parseThemeCollection(value: unknown): ThemeCollection | undefined {+ return isRecord(value) &&+ typeof value.id === "string" &&+ /^[a-z0-9][a-z0-9.:-]{0,127}$/i.test(value.id) &&+ isThemeLabel(value.label)+ ? { id: value.id, label: value.label.trim() }+ : undefined;+}+function parseStoredThemeColors(value: unknown, appearance: ThemeAppearance): ThemeColors | null {if (!isRecord(value)) return null;@@ -224,6 +237,7 @@ function parseStoredTheme(value: unknown): ThemeDefinition | null {if (!colors) return null;const variants = parseStoredThemeVariants(value.variants, value.appearance);if (value.variants !== undefined && variants === null) return null;+ const collection = parseThemeCollection(value.collection);return {id: value.id,@@ -231,10 +245,22 @@ function parseStoredTheme(value: unknown): ThemeDefinition | null {appearance: value.appearance,colors,...(variants ? { variants } : {}),+ ...(collection ? { collection } : {}),...(value.managed === true ? { managed: true } : {}),};}+function parseStoredThemes(storedThemes: ReadonlyArray<unknown>): ReadonlyArray<ThemeDefinition> {+ const themes: ThemeDefinition[] = [];+ for (const value of storedThemes) {+ const theme = parseStoredTheme(value);+ if (theme && !themes.some((existing) => existing.id === theme.id)) {+ themes.push(theme);+ }+ }+ return themes;+}+function readCustomThemeLibrarySnapshot(): CustomThemeLibrarySnapshot {if (typeof window === "undefined") {return { status: "ready", storedThemes: [], themes: [] };@@ -256,15 +282,7 @@ function readCustomThemeLibrarySnapshot(): CustomThemeLibrarySnapshot {}if (!Array.isArray(parsed)) return { status: "unavailable", reason: "malformed" };- const themes: ThemeDefinition[] = [];- for (const value of parsed) {- const theme = parseStoredTheme(value);- if (theme && !themes.some((existing) => existing.id === theme.id)) {- themes.push(theme);- }- }-- return { status: "ready", storedThemes: parsed, themes };+ return { status: "ready", storedThemes: parsed, themes: parseStoredThemes(parsed) };}function getCustomThemeLibrarySnapshot(): CustomThemeLibrarySnapshot {@@ -288,6 +306,14 @@ export function getCustomThemes(): ReadonlyArray<ThemeDefinition> {return snapshot.status === "ready" ? snapshot.themes : [];}+export function getStoredCustomThemeCollection(+ collectionId: string,+): ReadonlyArray<ThemeDefinition> {+ return readWritableCustomThemeLibrary().themes.filter(+ (theme) => theme.collection?.id === collectionId,+ );+}+export function subscribeToCustomThemes(listener: () => void): () => void {customThemeListeners.add(listener);if (typeof window === "undefined") {@@ -1598,8 +1624,9 @@ function saveCustomThemes(notifyCustomThemeListeners();}-function getWritableCustomThemeLibrary(): Extract<CustomThemeLibrarySnapshot, { status: "ready" }> {- const snapshot = getCustomThemeLibrarySnapshot();+function requireWritableCustomThemeLibrary(+ snapshot: CustomThemeLibrarySnapshot,+): Extract<CustomThemeLibrarySnapshot, { status: "ready" }> {if (snapshot.status === "unavailable") {throw new ThemeLibraryStorageError({storageKey: CUSTOM_THEMES_STORAGE_KEY,@@ -1611,10 +1638,29 @@ function getWritableCustomThemeLibrary(): Extract<CustomThemeLibrarySnapshot, {return snapshot;}+function getWritableCustomThemeLibrary(): Extract<CustomThemeLibrarySnapshot, { status: "ready" }> {+ return requireWritableCustomThemeLibrary(getCustomThemeLibrarySnapshot());+}++function readWritableCustomThemeLibrary(): Extract<+ CustomThemeLibrarySnapshot,+ { status: "ready" }+> {+ return requireWritableCustomThemeLibrary(readCustomThemeLibrarySnapshot());+}+function storedThemeHasId(storedTheme: unknown, themeId: string): boolean {return isRecord(storedTheme) && storedTheme.id === themeId;}+function storedThemeHasCollectionId(storedTheme: unknown, collectionId: string): boolean {+ return (+ isRecord(storedTheme) &&+ isRecord(storedTheme.collection) &&+ storedTheme.collection.id === collectionId+ );+}+export function installCustomTheme(theme: ThemeDefinition): ThemeDefinition {if (RESERVED_THEME_IDS.has(theme.id)) {throw new Error(`The theme id "${theme.id}" is reserved.`);@@ -1662,12 +1708,80 @@ export function updateCustomTheme(theme: ThemeDefinition): ThemeDefinition {return canonicalTheme;}+export function replaceCustomThemeCollection(+ collectionId: string,+ themes: ReadonlyArray<ThemeDefinition>,+ options?: { expectedCollection?: ReadonlyArray<ThemeDefinition> },+): ReadonlyArray<ThemeDefinition> {+ if (themes.length === 0) throw new Error("A theme collection cannot be empty.");++ const validated = themes.map((theme) => parseStoredTheme(theme));+ if (+ validated.some((theme) => theme === null || theme.collection?.id !== collectionId) ||+ new Set(validated.map((theme) => theme?.id)).size !== validated.length+ ) {+ throw new Error("That theme collection is invalid.");+ }+ const replacement = validated as ThemeDefinition[];+ const library = readWritableCustomThemeLibrary();+ const current = library.themes;+ const currentCollection = current.filter((theme) => theme.collection?.id === collectionId);+ if (+ options?.expectedCollection &&+ JSON.stringify(currentCollection) !== JSON.stringify(options.expectedCollection)+ ) {+ throw new Error("Your installed themes changed while this package was downloading. Try again.");+ }+ const occupiedIds = new Set(BUILT_IN_THEME_DEFINITIONS.map((theme) => theme.id));+ for (const storedTheme of library.storedThemes) {+ if (+ !storedThemeHasCollectionId(storedTheme, collectionId) &&+ isRecord(storedTheme) &&+ typeof storedTheme.id === "string"+ ) {+ occupiedIds.add(storedTheme.id);+ }+ }+ const conflictingTheme = replacement.find(+ (theme) => RESERVED_THEME_IDS.has(theme.id) || occupiedIds.has(theme.id),+ );+ if (conflictingTheme) {+ throw new Error(`A theme named "${conflictingTheme.label}" is already installed.`);+ }++ const nextStoredThemes: unknown[] = [];+ let insertedReplacement = false;+ for (const storedTheme of library.storedThemes) {+ if (!storedThemeHasCollectionId(storedTheme, collectionId)) {+ nextStoredThemes.push(storedTheme);+ } else if (!insertedReplacement) {+ nextStoredThemes.push(...replacement);+ insertedReplacement = true;+ }+ }+ if (!insertedReplacement) nextStoredThemes.push(...replacement);++ saveCustomThemes(nextStoredThemes, parseStoredThemes(nextStoredThemes));+ return replacement;+}+export function removeCustomTheme(themeId: string): void {+ removeCustomThemes([themeId]);+}++export function removeCustomThemes(themeIds: ReadonlyArray<string>): void {+ const removedIds = new Set(themeIds);+ if (removedIds.size === 0) return;const library = getWritableCustomThemeLibrary();- const nextThemes = library.themes.filter((theme) => theme.id !== themeId);+ const nextThemes = library.themes.filter((theme) => !removedIds.has(theme.id));if (nextThemes.length === library.themes.length) return;saveCustomThemes(- library.storedThemes.filter((storedTheme) => !storedThemeHasId(storedTheme, themeId)),+ library.storedThemes.filter(+ (storedTheme) =>+ !isRecord(storedTheme) ||+ typeof storedTheme.id !== "string" ||+ !removedIds.has(storedTheme.id),+ ),nextThemes,);}@@ -1720,6 +1834,10 @@ export function parseThemeFile(value: unknown): ThemeDefinition {}const overrides = parseThemeColorOverrides(rawColors);+ const collection = parseThemeCollection(value.collection);+ if (value.collection !== undefined && !collection) {+ throw new Error("Theme collections need a valid id and label.");+ }const fallback = getDefaultThemeColors(appearance);const variants: Partial<Record<ThemeAppearance, ThemeColors>> = {};@@ -1746,6 +1864,7 @@ export function parseThemeFile(value: unknown): ThemeDefinition {appearance,colors: { ...fallback, ...overrides },...(Object.keys(variants).length > 0 ? { variants } : {}),+ ...(collection ? { collection } : {}),...(value.managed === true ? { managed: true } : {}),};}@@ -1759,6 +1878,7 @@ export function serializeThemeFile(theme: ThemeDefinition): string {appearance: canonicalTheme.appearance,colors: canonicalTheme.colors,...(canonicalTheme.variants ? { variants: canonicalTheme.variants } : {}),+ ...(canonicalTheme.collection ? { collection: canonicalTheme.collection } : {}),...(canonicalTheme.managed ? { managed: true } : {}),};return `${JSON.stringify(file, null, 2)}\n`;diff --git a/apps/web/src/vscodeThemeImport.ts b/apps/web/src/vscodeThemeImport.tsindex 0ba19306a..186e03fb6 100644--- a/apps/web/src/vscodeThemeImport.ts+++ b/apps/web/src/vscodeThemeImport.ts@@ -337,6 +337,9 @@ export function parseVsCodeThemeFile(value: unknown): ThemeDefinition {*/export function pairVsCodeThemes(themes: ReadonlyArray<ThemeDefinition>,+ options?: {+ pairedId?: (light: ThemeDefinition, dark: ThemeDefinition) => string;+ },): ReadonlyArray<ThemeDefinition> {const stripAppearance = (label: string) =>label@@ -372,6 +375,7 @@ export function pairVsCodeThemes(order: group.order,theme: parseThemeFile({version: THEME_FILE_VERSION,+ ...(options?.pairedId ? { id: options.pairedId(group.light[0]!, group.dark[0]!) } : {}),name: key,appearance: "light",colors: group.light[0]!.colors,diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 78b2c686b..9abd0dc45 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -546,6 +546,9 @@ importers:'@lexical/react':specifier: ^0.41.0+ '@noble/hashes':+ specifier: 'catalog:'+ version: 1.8.0'@pierre/diffs':specifier: 'catalog:'version: 1.3.0-beta.10(patch_hash=7ef7cb0cbabb17c15cdb137554068b36f15f6f5265e73fb51452aa3380db91aa)(@shikijs/[email protected])([email protected]([email protected]))([email protected])@@ -579,6 +582,12 @@ importers:jose:specifier: 'catalog:'version: 6.2.2+ jsonc-parser:+ specifier: 3.3.1+ version: 3.3.1+ jszip:+ specifier: 3.10.1+ version: 3.10.1lexical:specifier: ^0.41.0version: 0.41.0