@velastack/patterns 0.15.3 → 0.15.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/_page-CiazQY4O.js +5 -0
- package/dist/chunks/{_page-DkCd_o3E.js.map → _page-CiazQY4O.js.map} +1 -1
- package/dist/chunks/{auth-pages-mZeR1WIj.js → auth-pages-B8H3kQPW.js} +2 -2
- package/dist/chunks/{auth-pages-mZeR1WIj.js.map → auth-pages-B8H3kQPW.js.map} +1 -1
- package/dist/chunks/{collections-Daxlnbm0.js → collections-CFTIAty-.js} +2 -2
- package/dist/chunks/{collections-Daxlnbm0.js.map → collections-CFTIAty-.js.map} +1 -1
- package/dist/chunks/{env-vars-C3TSZc4f.js → env-vars--fyhY-ew.js} +3 -3
- package/dist/chunks/{env-vars-C3TSZc4f.js.map → env-vars--fyhY-ew.js.map} +1 -1
- package/dist/chunks/{generate-CbchamhA.js → generate-B2z0kA5C.js} +2 -2
- package/dist/chunks/{generate-CbchamhA.js.map → generate-B2z0kA5C.js.map} +1 -1
- package/dist/chunks/{generate-CAYM7OUF.js → generate-BSCDKlyL.js} +2 -2
- package/dist/chunks/{generate-CAYM7OUF.js.map → generate-BSCDKlyL.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CZMVPVjS.js → generate.runtime-2T2j6Cgc.js} +5 -5
- package/dist/chunks/{generate.runtime-CZMVPVjS.js.map → generate.runtime-2T2j6Cgc.js.map} +1 -1
- package/dist/chunks/{generate.runtime-_426A1Ij.js → generate.runtime-7rRHLyjy.js} +3 -3
- package/dist/chunks/{generate.runtime-_426A1Ij.js.map → generate.runtime-7rRHLyjy.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Bo_s7gYB.js → generate.runtime-9wfx5sJK.js} +2 -2
- package/dist/chunks/{generate.runtime-Bo_s7gYB.js.map → generate.runtime-9wfx5sJK.js.map} +1 -1
- package/dist/chunks/{generate.runtime-B7VubPTW.js → generate.runtime-B6Tce286.js} +3 -3
- package/dist/chunks/{generate.runtime-B7VubPTW.js.map → generate.runtime-B6Tce286.js.map} +1 -1
- package/dist/chunks/{generate.runtime-B11mOr45.js → generate.runtime-B9nqVvxO.js} +2 -2
- package/dist/chunks/{generate.runtime-B11mOr45.js.map → generate.runtime-B9nqVvxO.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BL6DpWFI.js → generate.runtime-BCa20dNN.js} +3 -3
- package/dist/chunks/{generate.runtime-BL6DpWFI.js.map → generate.runtime-BCa20dNN.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DP63Wwea.js → generate.runtime-BFyTIABc.js} +4 -4
- package/dist/chunks/{generate.runtime-DP63Wwea.js.map → generate.runtime-BFyTIABc.js.map} +1 -1
- package/dist/chunks/{generate.runtime-VZIxJWlr.js → generate.runtime-B_md4EZa.js} +15 -15
- package/dist/chunks/{generate.runtime-VZIxJWlr.js.map → generate.runtime-B_md4EZa.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BjTZ2Ls-.js → generate.runtime-BpXoagaq.js} +3 -3
- package/dist/chunks/{generate.runtime-BjTZ2Ls-.js.map → generate.runtime-BpXoagaq.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DW9bqOtC.js → generate.runtime-C1zb2WxI.js} +2 -2
- package/dist/chunks/{generate.runtime-DW9bqOtC.js.map → generate.runtime-C1zb2WxI.js.map} +1 -1
- package/dist/chunks/{generate.runtime-373mTxeo.js → generate.runtime-C4R919oE.js} +2 -2
- package/dist/chunks/{generate.runtime-373mTxeo.js.map → generate.runtime-C4R919oE.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BCv4F1Wm.js → generate.runtime-C4qZ7Q30.js} +4 -4
- package/dist/chunks/{generate.runtime-BCv4F1Wm.js.map → generate.runtime-C4qZ7Q30.js.map} +1 -1
- package/dist/chunks/{generate.runtime-C90_2L-8.js → generate.runtime-C8xFPEgP.js} +2 -2
- package/dist/chunks/{generate.runtime-C90_2L-8.js.map → generate.runtime-C8xFPEgP.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Cs73i6Zf.js → generate.runtime-CC4XoTnb.js} +2 -2
- package/dist/chunks/{generate.runtime-Cs73i6Zf.js.map → generate.runtime-CC4XoTnb.js.map} +1 -1
- package/dist/chunks/{generate.runtime-jIlQ2GMh.js → generate.runtime-CCL_doqr.js} +2 -2
- package/dist/chunks/{generate.runtime-jIlQ2GMh.js.map → generate.runtime-CCL_doqr.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BEWp57Y7.js → generate.runtime-CKyi82cZ.js} +2 -2
- package/dist/chunks/{generate.runtime-BEWp57Y7.js.map → generate.runtime-CKyi82cZ.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DgKiFemb.js → generate.runtime-CNHEuhx4.js} +3 -3
- package/dist/chunks/{generate.runtime-DgKiFemb.js.map → generate.runtime-CNHEuhx4.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DIIeK2w9.js → generate.runtime-CPF0TcjM.js} +3 -3
- package/dist/chunks/{generate.runtime-DIIeK2w9.js.map → generate.runtime-CPF0TcjM.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DmbDEjMA.js → generate.runtime-CWNIo1xQ.js} +3 -3
- package/dist/chunks/{generate.runtime-DmbDEjMA.js.map → generate.runtime-CWNIo1xQ.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CDY0Ot_t.js → generate.runtime-Cb2u0ft4.js} +5 -5
- package/dist/chunks/{generate.runtime-CDY0Ot_t.js.map → generate.runtime-Cb2u0ft4.js.map} +1 -1
- package/dist/chunks/{generate.runtime-ChSVP7cD.js → generate.runtime-CdpLsiqC.js} +4 -4
- package/dist/chunks/{generate.runtime-ChSVP7cD.js.map → generate.runtime-CdpLsiqC.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DVZUNxtv.js → generate.runtime-ChstrVRw.js} +4 -4
- package/dist/chunks/{generate.runtime-DVZUNxtv.js.map → generate.runtime-ChstrVRw.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Bhs7ttZS.js → generate.runtime-CpDUk3Ev.js} +2 -2
- package/dist/chunks/{generate.runtime-Bhs7ttZS.js.map → generate.runtime-CpDUk3Ev.js.map} +1 -1
- package/dist/chunks/{generate.runtime-xrxAElb3.js → generate.runtime-Ctd_522e.js} +3 -3
- package/dist/chunks/{generate.runtime-xrxAElb3.js.map → generate.runtime-Ctd_522e.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Bn17HK_S.js → generate.runtime-CviYhOWW.js} +198 -115
- package/dist/chunks/generate.runtime-CviYhOWW.js.map +1 -0
- package/dist/chunks/{generate.runtime-BRV9hIl5.js → generate.runtime-CxJaHusI.js} +2 -2
- package/dist/chunks/{generate.runtime-BRV9hIl5.js.map → generate.runtime-CxJaHusI.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DRPxOLnB.js → generate.runtime-D0acTMRF.js} +4 -4
- package/dist/chunks/{generate.runtime-DRPxOLnB.js.map → generate.runtime-D0acTMRF.js.map} +1 -1
- package/dist/chunks/{generate.runtime-fs6GEMx-.js → generate.runtime-D6vRzBoU.js} +4 -4
- package/dist/chunks/{generate.runtime-fs6GEMx-.js.map → generate.runtime-D6vRzBoU.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BRcP6sFt.js → generate.runtime-D7aGjoTD.js} +2 -2
- package/dist/chunks/{generate.runtime-BRcP6sFt.js.map → generate.runtime-D7aGjoTD.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DG9LRwbt.js → generate.runtime-DPtjvhGr.js} +2 -2
- package/dist/chunks/{generate.runtime-DG9LRwbt.js.map → generate.runtime-DPtjvhGr.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BjrtdoYE.js → generate.runtime-DmHZZz4Z.js} +2 -2
- package/dist/chunks/{generate.runtime-BjrtdoYE.js.map → generate.runtime-DmHZZz4Z.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DXqBku2y.js → generate.runtime-O5eQdhHV.js} +4 -4
- package/dist/chunks/{generate.runtime-DXqBku2y.js.map → generate.runtime-O5eQdhHV.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DKL7VAAd.js → generate.runtime-Uq_L7TtO.js} +5 -5
- package/dist/chunks/{generate.runtime-DKL7VAAd.js.map → generate.runtime-Uq_L7TtO.js.map} +1 -1
- package/dist/chunks/{generate.runtime-C_hrLPD4.js → generate.runtime-VWQfzXXv.js} +3 -3
- package/dist/chunks/{generate.runtime-C_hrLPD4.js.map → generate.runtime-VWQfzXXv.js.map} +1 -1
- package/dist/chunks/{generate.runtime-v3KCv1B6.js → generate.runtime-WL1mm8gp.js} +2 -2
- package/dist/chunks/{generate.runtime-v3KCv1B6.js.map → generate.runtime-WL1mm8gp.js.map} +1 -1
- package/dist/chunks/{generate.runtime-sey-wxXB.js → generate.runtime-vJFz9Q7V.js} +7 -7
- package/dist/chunks/{generate.runtime-sey-wxXB.js.map → generate.runtime-vJFz9Q7V.js.map} +1 -1
- package/dist/chunks/{gitignore-CBiWFRif.js → gitignore-DUzIQXIo.js} +2 -2
- package/dist/chunks/{gitignore-CBiWFRif.js.map → gitignore-DUzIQXIo.js.map} +1 -1
- package/dist/chunks/{i18n-Ho8H91Ze.js → i18n-BoYcqVBi.js} +2 -2
- package/dist/chunks/{i18n-Ho8H91Ze.js.map → i18n-BoYcqVBi.js.map} +1 -1
- package/dist/chunks/{modify-file-BOEKlIDw.js → modify-file-DRdmZIvW.js} +2 -2
- package/dist/chunks/{modify-file-BOEKlIDw.js.map → modify-file-DRdmZIvW.js.map} +1 -1
- package/dist/chunks/{pocketbase-CvsJYXj-.js → pocketbase-BrDs1_84.js} +23 -7
- package/dist/chunks/pocketbase-BrDs1_84.js.map +1 -0
- package/dist/chunks/{providers-BEjDonyG.js → providers-Dhr_mzm6.js} +2 -2
- package/dist/chunks/{providers-BEjDonyG.js.map → providers-Dhr_mzm6.js.map} +1 -1
- package/dist/chunks/{schema-DnMqw2Hn.js → schema-C16iVOAG.js} +2 -2
- package/dist/chunks/{schema-DnMqw2Hn.js.map → schema-C16iVOAG.js.map} +1 -1
- package/dist/chunks/{shared-CSwGWMcN.js → shared-D7-ZAoqr.js} +2 -2
- package/dist/chunks/{shared-CSwGWMcN.js.map → shared-D7-ZAoqr.js.map} +1 -1
- package/dist/chunks/{ui-CpjUq_lm.js → ui-BI9OQpuR.js} +2 -2
- package/dist/chunks/{ui-CpjUq_lm.js.map → ui-BI9OQpuR.js.map} +1 -1
- package/dist/chunks/{write-result-DlB-id5k.js → write-result-Do8AcYbL.js} +2 -2
- package/dist/chunks/{write-result-DlB-id5k.js.map → write-result-Do8AcYbL.js.map} +1 -1
- package/dist/index.js +2161 -2152
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunks/_page-DkCd_o3E.js +0 -5
- package/dist/chunks/generate.runtime-Bn17HK_S.js.map +0 -1
- package/dist/chunks/pocketbase-CvsJYXj-.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ui-CpjUq_lm.js","names":["RegistryUnavailableError","readComponentsConfig","installComponents","formatPaths","installedPackagesFromProject","getAllCustomComponents","isCustomComponent","executeCommand","path","loadPreset","resolved","createRequire","root","error","reason","pathToFileURL","STYLE_FONTS","presetFor","preset","config","current","encodePreset","overrides","applyPreset","code","only","runtime","COMPONENTS_JSON","listComponents","options","result","installedComponents","fetchRegistryIndex","assertOneOf","value","InvalidArgumentError","kind","choices","writeStyle","configPath","existsSync","text","readFileSync","style","indent","registryUiNames","index","item","switchStyle","logger","getLogger","unchanged","offered","reinstall","component","packagesBefore","filesModified","reinstalled","hints","font","applyStyleFont","packages","name","FONTSOURCE_IMPORT","fontsourceImports","css","match","fonts","cssPath","cssFile","wanted","stale","family","f","applyColors","applyBaseColor","applyTheme"],"sources":["../../src/runtime/shadcn-preset.ts","../../src/runtime/ui.ts"],"sourcesContent":["import { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport type { WriteResultRuntime } from \"../core/types\";\nimport { readComponentsConfig } from \"./registry\";\nimport { executeCommand, formatPaths } from \"./write-result\";\n\n/**\n * What a shadcn-svelte preset code carries. Mirrors `PresetConfig` from\n * `shadcn-svelte/preset` as plain strings, so this package's types do not\n * depend on a package its consumers may not have installed.\n */\nexport interface PresetConfig {\n style: string;\n baseColor: string;\n theme: string;\n chartColor?: string;\n iconLibrary: string;\n font: string;\n fontHeading: string;\n radius: string;\n menuAccent: string;\n menuColor: string;\n}\n\n/** The part of `shadcn-svelte/preset` this package uses. */\nexport interface ShadcnPreset {\n PRESET_STYLES: readonly string[];\n PRESET_BASE_COLOR_KEYS: readonly string[];\n PRESET_THEME_KEYS: readonly string[];\n PRESET_FONTS: readonly string[];\n PRESET_ICON_LIBRARIES: readonly string[];\n encodePreset(config: Partial<PresetConfig>): string;\n decodePreset(code: string): PresetConfig | null;\n}\n\nexport type PresetPart = \"theme\" | \"font\";\n\n/**\n * The encoder from the *project's* shadcn-svelte, so every preset code is\n * produced by the same version that consumes it and the value lists can\n * never drift from what `apply` accepts.\n */\nexport async function loadPreset(root: string): Promise<ShadcnPreset> {\n let resolved: string;\n try {\n resolved = createRequire(path.join(root, \"package.json\")).resolve(\n \"shadcn-svelte/preset\",\n );\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n throw new Error(\n `Could not load shadcn-svelte/preset from ${root}: ${reason}\\n` +\n \"Install the project's dependencies (shadcn-svelte >= 1.6) and try again.\",\n );\n }\n const module: unknown = await import(\n /* @vite-ignore */ pathToFileURL(resolved).href\n );\n return module as ShadcnPreset;\n}\n\n/**\n * The font each style is designed with. shadcn-svelte keeps this table inside\n * its bundle (the `create` presets) without exporting it, so it is vendored\n * here; `shadcn-preset.test.ts` checks it still covers every style the\n * installed shadcn-svelte knows.\n */\nexport const STYLE_FONTS: Record<\n string,\n { font: string; fontHeading?: string }\n> = {\n nova: { font: \"geist\" },\n vega: { font: \"inter\" },\n maia: { font: \"figtree\" },\n lyra: { font: \"jetbrains-mono\" },\n mira: { font: \"inter\" },\n luma: { font: \"inter\" },\n sera: { font: \"noto-sans\", fontHeading: \"playfair-display\" },\n rhea: { font: \"inter\" },\n};\n\n/**\n * A preset code for the project as it is, with `overrides` on top: the style,\n * base color, icon library and menu settings come from `components.json` so\n * an `apply --only theme` keeps everything it does not mean to change.\n * Values shadcn-svelte does not know (a `slate` from an older template) fall\n * back to its defaults inside `encodePreset`.\n */\nexport async function presetFor(\n root: string,\n overrides: Partial<PresetConfig>,\n preset?: ShadcnPreset,\n): Promise<string> {\n const { encodePreset } = preset ?? (await loadPreset(root));\n const config = readComponentsConfig(root);\n const current: Partial<PresetConfig> = { style: config.style };\n if (config.baseColor) current.baseColor = config.baseColor;\n if (config.iconLibrary) current.iconLibrary = config.iconLibrary;\n if (config.menuColor) current.menuColor = config.menuColor;\n if (config.menuAccent) current.menuAccent = config.menuAccent;\n return encodePreset({ ...current, ...overrides });\n}\n\n/**\n * `shadcn-svelte apply --preset <code> --only <parts> --yes` through the\n * project's package manager. `theme` rewrites the token values in `:root` /\n * `.dark` and records the base color in `components.json`; `font` adds the\n * fontsource import, dependency and `--font-sans`. Both leave the rest of the\n * stylesheet alone but write it in the registry's formatting, so the file is\n * run through the project's prettier afterwards.\n */\nexport async function applyPreset(\n root: string,\n code: string,\n only: PresetPart[],\n runtime?: WriteResultRuntime,\n): Promise<void> {\n await executeCommand(\n root,\n \"execute\",\n [\"shadcn-svelte\", \"apply\", \"--preset\", code, \"--only\", ...only, \"--yes\"],\n runtime,\n );\n await formatPaths(root, [readComponentsConfig(root).cssPath]);\n}\n","import { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport type {\n ApplyBaseColorOptions,\n ApplyColorsResult,\n ApplyThemeOptions,\n Component,\n ListComponentsOptions,\n ListComponentsResult,\n RegistryItem,\n SwitchStyleOptions,\n SwitchStyleResult,\n WriteResultRuntime,\n} from \"../core/types\";\nimport { InvalidArgumentError, RegistryUnavailableError } from \"../core/errors\";\nimport { getLogger } from \"../core/logger\";\nimport { fetchRegistryIndex, readComponentsConfig } from \"./registry\";\nimport {\n applyPreset,\n loadPreset,\n presetFor,\n STYLE_FONTS,\n type ShadcnPreset,\n} from \"./shadcn-preset\";\nimport {\n getAllCustomComponents,\n installComponents,\n installedComponents,\n installedPackagesFromProject,\n isCustomComponent,\n} from \"./write-result\";\n\nconst COMPONENTS_JSON = \"components.json\";\n\n/**\n * What a project has and what it could add: the ui directory, this package's\n * bundled components, and the registry index of the configured style. A\n * registry that cannot be read leaves the first two intact and says why.\n */\nexport async function listComponents(\n options: ListComponentsOptions,\n runtime?: WriteResultRuntime,\n): Promise<ListComponentsResult> {\n const { root } = options;\n const { style } = readComponentsConfig(root);\n const result: ListComponentsResult = {\n style,\n installed: installedComponents(root),\n custom: getAllCustomComponents(),\n registry: [],\n };\n try {\n result.registry = await fetchRegistryIndex(root, { runtime });\n } catch (error) {\n if (!(error instanceof RegistryUnavailableError)) throw error;\n result.registryUnavailable = error.message;\n }\n return result;\n}\n\nfunction assertOneOf(\n kind: string,\n value: string,\n choices: readonly string[],\n): void {\n if (choices.includes(value)) return;\n throw new InvalidArgumentError(\n `Unknown ${kind} \"${value}\". Choose one of: ${choices.join(\", \")}.`,\n );\n}\n\n/**\n * Rewrites `style` in `components.json` and nothing else, keeping the file's\n * indentation so the change reads as the one-line diff it is.\n */\nfunction writeStyle(root: string, style: string): void {\n const configPath = path.join(root, COMPONENTS_JSON);\n if (!existsSync(configPath)) {\n throw new Error(\n `${COMPONENTS_JSON} not found in ${root}; this does not look like a shadcn-svelte project.`,\n );\n }\n const text = readFileSync(configPath, \"utf8\");\n const config = JSON.parse(text) as Record<string, unknown>;\n config.style = style;\n const indent = text.includes(\"\\n\\t\") ? \"\\t\" : 2;\n writeFileSync(\n configPath,\n `${JSON.stringify(config, null, indent)}\\n`,\n \"utf8\",\n );\n}\n\nfunction registryUiNames(index: RegistryItem[]): Set<string> {\n return new Set(\n index\n .filter((item) => item.type === \"registry:ui\")\n .map((item) => item.name),\n );\n}\n\n/**\n * Moves a project to another shadcn-svelte style. Every installed component\n * the new style's registry also offers is re-added from there (their local\n * edits are lost, which is what `confirm` is for); this package's own\n * components and anything the registry does not know are left alone. The\n * style's preset font follows unless `font` is false.\n */\nexport async function switchStyle(\n options: SwitchStyleOptions,\n runtime?: WriteResultRuntime,\n): Promise<SwitchStyleResult> {\n const { root, style, font = true } = options;\n const logger = getLogger(options);\n const preset = await loadPreset(root);\n assertOneOf(\"style\", style, preset.PRESET_STYLES);\n\n const unchanged: SwitchStyleResult = {\n status: \"unchanged\",\n style,\n reinstalled: [],\n filesModified: [],\n packages: [],\n hints: [],\n };\n if (readComponentsConfig(root).style === style) {\n return unchanged;\n }\n\n const index = await fetchRegistryIndex(root, { style, runtime });\n const offered = registryUiNames(index);\n const reinstall = installedComponents(root).filter(\n (component) => offered.has(component) && !isCustomComponent(component),\n );\n\n if (options.confirm && !(await options.confirm(reinstall))) {\n return { ...unchanged, status: \"cancelled\" };\n }\n\n const packagesBefore = installedPackagesFromProject(root);\n writeStyle(root, style);\n const filesModified = [COMPONENTS_JSON];\n\n let reinstalled: Component[] = [];\n if (reinstall.length > 0) {\n const outcome = await installComponents(\n { root, components: reinstall, overwrite: true, logger },\n runtime,\n );\n reinstalled = outcome.installed;\n }\n\n const hints: string[] = [];\n if (font) {\n await applyStyleFont(\n root,\n style,\n preset,\n runtime,\n filesModified,\n hints,\n logger,\n );\n }\n\n const packages = [...installedPackagesFromProject(root)]\n .filter((name) => !packagesBefore.has(name))\n .sort();\n\n return {\n status: \"switched\",\n style,\n reinstalled,\n filesModified,\n packages,\n hints,\n };\n}\n\nconst FONTSOURCE_IMPORT =\n /@import\\s+[\"']@fontsource(?:-variable)?\\/([^\"']+)[\"']/g;\n\n/** The fontsource families a stylesheet imports, in order. */\nfunction fontsourceImports(css: string): string[] {\n return [...css.matchAll(FONTSOURCE_IMPORT)].map((match) => match[1]!);\n}\n\nasync function applyStyleFont(\n root: string,\n style: string,\n preset: ShadcnPreset,\n runtime: WriteResultRuntime | undefined,\n filesModified: string[],\n hints: string[],\n logger: ReturnType<typeof getLogger>,\n): Promise<void> {\n const fonts = STYLE_FONTS[style];\n if (!fonts) {\n logger.info(\n `No preset font is known for the ${style} style; leaving fonts unchanged.`,\n );\n return;\n }\n logger.info(`Applying the ${style} font (${fonts.font})`);\n const code = await presetFor(root, { style, ...fonts }, preset);\n await applyPreset(root, code, [\"font\"], runtime);\n\n const cssPath = readComponentsConfig(root).cssPath;\n filesModified.push(cssPath, \"package.json\");\n\n // `apply --only font` adds the new font beside whatever was imported before\n // and leaves it to the project to drop the old one; a font nobody uses\n // still ships to every visitor.\n const cssFile = path.join(root, cssPath);\n if (existsSync(cssFile)) {\n const wanted = new Set([fonts.font, fonts.fontHeading].filter(Boolean));\n const stale = fontsourceImports(readFileSync(cssFile, \"utf8\")).filter(\n (family) => !wanted.has(family),\n );\n if (stale.length > 0) {\n hints.push(\n `${cssPath} still imports ${stale.map((f) => `@fontsource-variable/${f}`).join(\", \")} from the previous style; remove the import and the package if nothing else uses them.`,\n );\n }\n }\n}\n\nasync function applyColors(\n root: string,\n overrides: { baseColor?: string; theme: string },\n runtime?: WriteResultRuntime,\n): Promise<ApplyColorsResult> {\n const preset = await loadPreset(root);\n if (overrides.baseColor) {\n assertOneOf(\n \"base color\",\n overrides.baseColor,\n preset.PRESET_BASE_COLOR_KEYS,\n );\n }\n assertOneOf(\"theme\", overrides.theme, preset.PRESET_THEME_KEYS);\n\n // Charts follow the accent, as shadcn-svelte's own presets do.\n const code = await presetFor(\n root,\n { ...overrides, chartColor: overrides.theme },\n preset,\n );\n await applyPreset(root, code, [\"theme\"], runtime);\n\n const config = readComponentsConfig(root);\n return {\n baseColor: config.baseColor ?? overrides.baseColor ?? \"\",\n theme: overrides.theme,\n filesModified: [config.cssPath, COMPONENTS_JSON],\n };\n}\n\n/**\n * Sets the base (gray) palette. The accent is reset to the base color as\n * well, since `components.json` records only the base color; `applyTheme`\n * puts an accent back on top.\n */\nexport async function applyBaseColor(\n options: ApplyBaseColorOptions,\n runtime?: WriteResultRuntime,\n): Promise<ApplyColorsResult> {\n return applyColors(\n options.root,\n { baseColor: options.color, theme: options.color },\n runtime,\n );\n}\n\n/** Sets the accent (primary, ring, charts) and keeps the base palette. */\nexport async function applyTheme(\n options: ApplyThemeOptions,\n runtime?: WriteResultRuntime,\n): Promise<ApplyColorsResult> {\n return applyColors(options.root, { theme: options.theme }, runtime);\n}\n"],"mappings":";;;;;;;;;AA2CA,eAAsBS,EAAW,GAAqC;CACpE,IAAIC;CACJ,IAAI;EACF,IAAWC,EAAcH,EAAK,KAAKI,GAAM,cAAc,CAAC,CAAC,CAAC,QACxD,sBACF;CACF,SAASC,GAAO;EACd,IAAMC,IAASD,aAAiB,QAAQA,EAAM,UAAU,OAAOA,CAAK;EACpE,MAAU,MACR,4CAA4CD,EAAK,IAAIE,EAAO,2EAE9D;CACF;CAIA,OAAO,MAHuB;;EACTC,EAAcL,CAAQ,CAAC,CAAC;;AAG/C;AAQA,IAAaM,IAGT;CACF,MAAM,EAAE,MAAM,QAAQ;CACtB,MAAM,EAAE,MAAM,QAAQ;CACtB,MAAM,EAAE,MAAM,UAAU;CACxB,MAAM,EAAE,MAAM,iBAAiB;CAC/B,MAAM,EAAE,MAAM,QAAQ;CACtB,MAAM,EAAE,MAAM,QAAQ;CACtB,MAAM;EAAE,MAAM;EAAa,aAAa;CAAmB;CAC3D,MAAM,EAAE,MAAM,QAAQ;AACxB;AASA,eAAsBC,EACpB,GACA,GACA,GACiB;CACjB,IAAM,EAAE,oBAAiBC,KAAW,MAAMT,EAAWG,CAAI,GACnDO,IAASlB,EAAqBW,CAAI,GAClCQ,IAAiC,EAAE,OAAOD,EAAO,MAAM;CAK7D,OAJIA,EAAO,cAAW,EAAQ,YAAYA,EAAO,YAC7CA,EAAO,gBAAa,EAAQ,cAAcA,EAAO,cACjDA,EAAO,cAAW,EAAQ,YAAYA,EAAO,YAC7CA,EAAO,eAAY,EAAQ,aAAaA,EAAO,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ACVJ,EAAO,sBACT,GAEFe,EAAY,SAASX,EAAU,OAAOJ,EAAO,iBAAiB,GAQ9D,MAAMK,EAAYX,GAAM,MALLK,EACjBL,GACA;EAAE,GAAGU;EAAW,YAAYA,EAAU;CAAM,GAC5CJ,CACF,GAC8B,CAAC,OAAO,GAAGQ,CAAO;CAEhD,IAAMP,IAASlB,EAAqBW,CAAI;CACxC,OAAO;EACL,WAAWO,EAAO,aAAaG,EAAU,aAAa;EACtD,OAAOA,EAAU;EACjB,eAAe,CAACH,EAAO,SAASQ,CAAe;CACjD;AACF;AAOA,eAAsBgD,EACpB,GACA,GAC4B;CAC5B,OAAOD,EACL7C,EAAQ,MACR;EAAE,WAAWA,EAAQ;EAAO,OAAOA,EAAQ;CAAM,GACjDH,CACF;AACF;AAGA,eAAsBkD,EACpB,GACA,GAC4B;CAC5B,OAAOF,EAAY7C,EAAQ,MAAM,EAAE,OAAOA,EAAQ,MAAM,GAAGH,CAAO;AACpE"}
|
|
1
|
+
{"version":3,"file":"ui-BI9OQpuR.js","names":["RegistryUnavailableError","readComponentsConfig","installComponents","formatPaths","installedPackagesFromProject","getAllCustomComponents","isCustomComponent","executeCommand","path","loadPreset","resolved","createRequire","root","error","reason","pathToFileURL","STYLE_FONTS","presetFor","preset","config","current","encodePreset","overrides","applyPreset","code","only","runtime","COMPONENTS_JSON","listComponents","options","result","installedComponents","fetchRegistryIndex","assertOneOf","value","InvalidArgumentError","kind","choices","writeStyle","configPath","existsSync","text","readFileSync","style","indent","registryUiNames","index","item","switchStyle","logger","getLogger","unchanged","offered","reinstall","component","packagesBefore","filesModified","reinstalled","hints","font","applyStyleFont","packages","name","FONTSOURCE_IMPORT","fontsourceImports","css","match","fonts","cssPath","cssFile","wanted","stale","family","f","applyColors","applyBaseColor","applyTheme"],"sources":["../../src/runtime/shadcn-preset.ts","../../src/runtime/ui.ts"],"sourcesContent":["import { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport type { WriteResultRuntime } from \"../core/types\";\nimport { readComponentsConfig } from \"./registry\";\nimport { executeCommand, formatPaths } from \"./write-result\";\n\n/**\n * What a shadcn-svelte preset code carries. Mirrors `PresetConfig` from\n * `shadcn-svelte/preset` as plain strings, so this package's types do not\n * depend on a package its consumers may not have installed.\n */\nexport interface PresetConfig {\n style: string;\n baseColor: string;\n theme: string;\n chartColor?: string;\n iconLibrary: string;\n font: string;\n fontHeading: string;\n radius: string;\n menuAccent: string;\n menuColor: string;\n}\n\n/** The part of `shadcn-svelte/preset` this package uses. */\nexport interface ShadcnPreset {\n PRESET_STYLES: readonly string[];\n PRESET_BASE_COLOR_KEYS: readonly string[];\n PRESET_THEME_KEYS: readonly string[];\n PRESET_FONTS: readonly string[];\n PRESET_ICON_LIBRARIES: readonly string[];\n encodePreset(config: Partial<PresetConfig>): string;\n decodePreset(code: string): PresetConfig | null;\n}\n\nexport type PresetPart = \"theme\" | \"font\";\n\n/**\n * The encoder from the *project's* shadcn-svelte, so every preset code is\n * produced by the same version that consumes it and the value lists can\n * never drift from what `apply` accepts.\n */\nexport async function loadPreset(root: string): Promise<ShadcnPreset> {\n let resolved: string;\n try {\n resolved = createRequire(path.join(root, \"package.json\")).resolve(\n \"shadcn-svelte/preset\",\n );\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n throw new Error(\n `Could not load shadcn-svelte/preset from ${root}: ${reason}\\n` +\n \"Install the project's dependencies (shadcn-svelte >= 1.6) and try again.\",\n );\n }\n const module: unknown = await import(\n /* @vite-ignore */ pathToFileURL(resolved).href\n );\n return module as ShadcnPreset;\n}\n\n/**\n * The font each style is designed with. shadcn-svelte keeps this table inside\n * its bundle (the `create` presets) without exporting it, so it is vendored\n * here; `shadcn-preset.test.ts` checks it still covers every style the\n * installed shadcn-svelte knows.\n */\nexport const STYLE_FONTS: Record<\n string,\n { font: string; fontHeading?: string }\n> = {\n nova: { font: \"geist\" },\n vega: { font: \"inter\" },\n maia: { font: \"figtree\" },\n lyra: { font: \"jetbrains-mono\" },\n mira: { font: \"inter\" },\n luma: { font: \"inter\" },\n sera: { font: \"noto-sans\", fontHeading: \"playfair-display\" },\n rhea: { font: \"inter\" },\n};\n\n/**\n * A preset code for the project as it is, with `overrides` on top: the style,\n * base color, icon library and menu settings come from `components.json` so\n * an `apply --only theme` keeps everything it does not mean to change.\n * Values shadcn-svelte does not know (a `slate` from an older template) fall\n * back to its defaults inside `encodePreset`.\n */\nexport async function presetFor(\n root: string,\n overrides: Partial<PresetConfig>,\n preset?: ShadcnPreset,\n): Promise<string> {\n const { encodePreset } = preset ?? (await loadPreset(root));\n const config = readComponentsConfig(root);\n const current: Partial<PresetConfig> = { style: config.style };\n if (config.baseColor) current.baseColor = config.baseColor;\n if (config.iconLibrary) current.iconLibrary = config.iconLibrary;\n if (config.menuColor) current.menuColor = config.menuColor;\n if (config.menuAccent) current.menuAccent = config.menuAccent;\n return encodePreset({ ...current, ...overrides });\n}\n\n/**\n * `shadcn-svelte apply --preset <code> --only <parts> --yes` through the\n * project's package manager. `theme` rewrites the token values in `:root` /\n * `.dark` and records the base color in `components.json`; `font` adds the\n * fontsource import, dependency and `--font-sans`. Both leave the rest of the\n * stylesheet alone but write it in the registry's formatting, so the file is\n * run through the project's prettier afterwards.\n */\nexport async function applyPreset(\n root: string,\n code: string,\n only: PresetPart[],\n runtime?: WriteResultRuntime,\n): Promise<void> {\n await executeCommand(\n root,\n \"execute\",\n [\"shadcn-svelte\", \"apply\", \"--preset\", code, \"--only\", ...only, \"--yes\"],\n runtime,\n );\n await formatPaths(root, [readComponentsConfig(root).cssPath]);\n}\n","import { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport type {\n ApplyBaseColorOptions,\n ApplyColorsResult,\n ApplyThemeOptions,\n Component,\n ListComponentsOptions,\n ListComponentsResult,\n RegistryItem,\n SwitchStyleOptions,\n SwitchStyleResult,\n WriteResultRuntime,\n} from \"../core/types\";\nimport { InvalidArgumentError, RegistryUnavailableError } from \"../core/errors\";\nimport { getLogger } from \"../core/logger\";\nimport { fetchRegistryIndex, readComponentsConfig } from \"./registry\";\nimport {\n applyPreset,\n loadPreset,\n presetFor,\n STYLE_FONTS,\n type ShadcnPreset,\n} from \"./shadcn-preset\";\nimport {\n getAllCustomComponents,\n installComponents,\n installedComponents,\n installedPackagesFromProject,\n isCustomComponent,\n} from \"./write-result\";\n\nconst COMPONENTS_JSON = \"components.json\";\n\n/**\n * What a project has and what it could add: the ui directory, this package's\n * bundled components, and the registry index of the configured style. A\n * registry that cannot be read leaves the first two intact and says why.\n */\nexport async function listComponents(\n options: ListComponentsOptions,\n runtime?: WriteResultRuntime,\n): Promise<ListComponentsResult> {\n const { root } = options;\n const { style } = readComponentsConfig(root);\n const result: ListComponentsResult = {\n style,\n installed: installedComponents(root),\n custom: getAllCustomComponents(),\n registry: [],\n };\n try {\n result.registry = await fetchRegistryIndex(root, { runtime });\n } catch (error) {\n if (!(error instanceof RegistryUnavailableError)) throw error;\n result.registryUnavailable = error.message;\n }\n return result;\n}\n\nfunction assertOneOf(\n kind: string,\n value: string,\n choices: readonly string[],\n): void {\n if (choices.includes(value)) return;\n throw new InvalidArgumentError(\n `Unknown ${kind} \"${value}\". Choose one of: ${choices.join(\", \")}.`,\n );\n}\n\n/**\n * Rewrites `style` in `components.json` and nothing else, keeping the file's\n * indentation so the change reads as the one-line diff it is.\n */\nfunction writeStyle(root: string, style: string): void {\n const configPath = path.join(root, COMPONENTS_JSON);\n if (!existsSync(configPath)) {\n throw new Error(\n `${COMPONENTS_JSON} not found in ${root}; this does not look like a shadcn-svelte project.`,\n );\n }\n const text = readFileSync(configPath, \"utf8\");\n const config = JSON.parse(text) as Record<string, unknown>;\n config.style = style;\n const indent = text.includes(\"\\n\\t\") ? \"\\t\" : 2;\n writeFileSync(\n configPath,\n `${JSON.stringify(config, null, indent)}\\n`,\n \"utf8\",\n );\n}\n\nfunction registryUiNames(index: RegistryItem[]): Set<string> {\n return new Set(\n index\n .filter((item) => item.type === \"registry:ui\")\n .map((item) => item.name),\n );\n}\n\n/**\n * Moves a project to another shadcn-svelte style. Every installed component\n * the new style's registry also offers is re-added from there (their local\n * edits are lost, which is what `confirm` is for); this package's own\n * components and anything the registry does not know are left alone. The\n * style's preset font follows unless `font` is false.\n */\nexport async function switchStyle(\n options: SwitchStyleOptions,\n runtime?: WriteResultRuntime,\n): Promise<SwitchStyleResult> {\n const { root, style, font = true } = options;\n const logger = getLogger(options);\n const preset = await loadPreset(root);\n assertOneOf(\"style\", style, preset.PRESET_STYLES);\n\n const unchanged: SwitchStyleResult = {\n status: \"unchanged\",\n style,\n reinstalled: [],\n filesModified: [],\n packages: [],\n hints: [],\n };\n if (readComponentsConfig(root).style === style) {\n return unchanged;\n }\n\n const index = await fetchRegistryIndex(root, { style, runtime });\n const offered = registryUiNames(index);\n const reinstall = installedComponents(root).filter(\n (component) => offered.has(component) && !isCustomComponent(component),\n );\n\n if (options.confirm && !(await options.confirm(reinstall))) {\n return { ...unchanged, status: \"cancelled\" };\n }\n\n const packagesBefore = installedPackagesFromProject(root);\n writeStyle(root, style);\n const filesModified = [COMPONENTS_JSON];\n\n let reinstalled: Component[] = [];\n if (reinstall.length > 0) {\n const outcome = await installComponents(\n { root, components: reinstall, overwrite: true, logger },\n runtime,\n );\n reinstalled = outcome.installed;\n }\n\n const hints: string[] = [];\n if (font) {\n await applyStyleFont(\n root,\n style,\n preset,\n runtime,\n filesModified,\n hints,\n logger,\n );\n }\n\n const packages = [...installedPackagesFromProject(root)]\n .filter((name) => !packagesBefore.has(name))\n .sort();\n\n return {\n status: \"switched\",\n style,\n reinstalled,\n filesModified,\n packages,\n hints,\n };\n}\n\nconst FONTSOURCE_IMPORT =\n /@import\\s+[\"']@fontsource(?:-variable)?\\/([^\"']+)[\"']/g;\n\n/** The fontsource families a stylesheet imports, in order. */\nfunction fontsourceImports(css: string): string[] {\n return [...css.matchAll(FONTSOURCE_IMPORT)].map((match) => match[1]!);\n}\n\nasync function applyStyleFont(\n root: string,\n style: string,\n preset: ShadcnPreset,\n runtime: WriteResultRuntime | undefined,\n filesModified: string[],\n hints: string[],\n logger: ReturnType<typeof getLogger>,\n): Promise<void> {\n const fonts = STYLE_FONTS[style];\n if (!fonts) {\n logger.info(\n `No preset font is known for the ${style} style; leaving fonts unchanged.`,\n );\n return;\n }\n logger.info(`Applying the ${style} font (${fonts.font})`);\n const code = await presetFor(root, { style, ...fonts }, preset);\n await applyPreset(root, code, [\"font\"], runtime);\n\n const cssPath = readComponentsConfig(root).cssPath;\n filesModified.push(cssPath, \"package.json\");\n\n // `apply --only font` adds the new font beside whatever was imported before\n // and leaves it to the project to drop the old one; a font nobody uses\n // still ships to every visitor.\n const cssFile = path.join(root, cssPath);\n if (existsSync(cssFile)) {\n const wanted = new Set([fonts.font, fonts.fontHeading].filter(Boolean));\n const stale = fontsourceImports(readFileSync(cssFile, \"utf8\")).filter(\n (family) => !wanted.has(family),\n );\n if (stale.length > 0) {\n hints.push(\n `${cssPath} still imports ${stale.map((f) => `@fontsource-variable/${f}`).join(\", \")} from the previous style; remove the import and the package if nothing else uses them.`,\n );\n }\n }\n}\n\nasync function applyColors(\n root: string,\n overrides: { baseColor?: string; theme: string },\n runtime?: WriteResultRuntime,\n): Promise<ApplyColorsResult> {\n const preset = await loadPreset(root);\n if (overrides.baseColor) {\n assertOneOf(\n \"base color\",\n overrides.baseColor,\n preset.PRESET_BASE_COLOR_KEYS,\n );\n }\n assertOneOf(\"theme\", overrides.theme, preset.PRESET_THEME_KEYS);\n\n // Charts follow the accent, as shadcn-svelte's own presets do.\n const code = await presetFor(\n root,\n { ...overrides, chartColor: overrides.theme },\n preset,\n );\n await applyPreset(root, code, [\"theme\"], runtime);\n\n const config = readComponentsConfig(root);\n return {\n baseColor: config.baseColor ?? overrides.baseColor ?? \"\",\n theme: overrides.theme,\n filesModified: [config.cssPath, COMPONENTS_JSON],\n };\n}\n\n/**\n * Sets the base (gray) palette. The accent is reset to the base color as\n * well, since `components.json` records only the base color; `applyTheme`\n * puts an accent back on top.\n */\nexport async function applyBaseColor(\n options: ApplyBaseColorOptions,\n runtime?: WriteResultRuntime,\n): Promise<ApplyColorsResult> {\n return applyColors(\n options.root,\n { baseColor: options.color, theme: options.color },\n runtime,\n );\n}\n\n/** Sets the accent (primary, ring, charts) and keeps the base palette. */\nexport async function applyTheme(\n options: ApplyThemeOptions,\n runtime?: WriteResultRuntime,\n): Promise<ApplyColorsResult> {\n return applyColors(options.root, { theme: options.theme }, runtime);\n}\n"],"mappings":";;;;;;;;;AA2CA,eAAsBS,EAAW,GAAqC;CACpE,IAAIC;CACJ,IAAI;EACF,IAAWC,EAAcH,EAAK,KAAKI,GAAM,cAAc,CAAC,CAAC,CAAC,QACxD,sBACF;CACF,SAASC,GAAO;EACd,IAAMC,IAASD,aAAiB,QAAQA,EAAM,UAAU,OAAOA,CAAK;EACpE,MAAU,MACR,4CAA4CD,EAAK,IAAIE,EAAO,2EAE9D;CACF;CAIA,OAAO,MAHuB;;EACTC,EAAcL,CAAQ,CAAC,CAAC;;AAG/C;AAQA,IAAaM,IAGT;CACF,MAAM,EAAE,MAAM,QAAQ;CACtB,MAAM,EAAE,MAAM,QAAQ;CACtB,MAAM,EAAE,MAAM,UAAU;CACxB,MAAM,EAAE,MAAM,iBAAiB;CAC/B,MAAM,EAAE,MAAM,QAAQ;CACtB,MAAM,EAAE,MAAM,QAAQ;CACtB,MAAM;EAAE,MAAM;EAAa,aAAa;CAAmB;CAC3D,MAAM,EAAE,MAAM,QAAQ;AACxB;AASA,eAAsBC,EACpB,GACA,GACA,GACiB;CACjB,IAAM,EAAE,oBAAiBC,KAAW,MAAMT,EAAWG,CAAI,GACnDO,IAASlB,EAAqBW,CAAI,GAClCQ,IAAiC,EAAE,OAAOD,EAAO,MAAM;CAK7D,OAJIA,EAAO,cAAW,EAAQ,YAAYA,EAAO,YAC7CA,EAAO,gBAAa,EAAQ,cAAcA,EAAO,cACjDA,EAAO,cAAW,EAAQ,YAAYA,EAAO,Y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C,AAfIU,EAAU,aACZW,EACE,cACAX,EAAU,WACVJ,EAAO,sBACT,GAEFe,EAAY,SAASX,EAAU,OAAOJ,EAAO,iBAAiB,GAQ9D,MAAMK,EAAYX,GAAM,MALLK,EACjBL,GACA;EAAE,GAAGU;EAAW,YAAYA,EAAU;CAAM,GAC5CJ,CACF,GAC8B,CAAC,OAAO,GAAGQ,CAAO;CAEhD,IAAMP,IAASlB,EAAqBW,CAAI;CACxC,OAAO;EACL,WAAWO,EAAO,aAAaG,EAAU,aAAa;EACtD,OAAOA,EAAU;EACjB,eAAe,CAACH,EAAO,SAASQ,CAAe;CACjD;AACF;AAOA,eAAsBgD,EACpB,GACA,GAC4B;CAC5B,OAAOD,EACL7C,EAAQ,MACR;EAAE,WAAWA,EAAQ;EAAO,OAAOA,EAAQ;CAAM,GACjDH,CACF;AACF;AAGA,eAAsBkD,EACpB,GACA,GAC4B;CAC5B,OAAOF,EAAY7C,EAAQ,MAAM,EAAE,OAAOA,EAAQ,MAAM,GAAGH,CAAO;AACpE"}
|
|
@@ -503,7 +503,7 @@ async function Lt(e, t, n) {
|
|
|
503
503
|
await Z(t.root, s, n, r);
|
|
504
504
|
let c = [];
|
|
505
505
|
if (e.collectionDrops.length > 0) {
|
|
506
|
-
let { dropCollections: n } = await import("./collections-
|
|
506
|
+
let { dropCollections: n } = await import("./collections-CFTIAty-.js").then((e) => e.r);
|
|
507
507
|
c = await Promise.all((await n(e.collectionDrops, t)).map(async (e) => ({
|
|
508
508
|
...e,
|
|
509
509
|
content: await o(e.content, e.path, t, { created: !0 })
|
|
@@ -560,4 +560,4 @@ async function Lt(e, t, n) {
|
|
|
560
560
|
}
|
|
561
561
|
export { Mt as a, I as c, Q as i, ht as l, K as n, F as o, k as r, W as s, P as t };
|
|
562
562
|
|
|
563
|
-
//# sourceMappingURL=write-result-
|
|
563
|
+
//# sourceMappingURL=write-result-Do8AcYbL.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"write-result-DlB-id5k.js","names":["__import_glob__0_0_","__import_glob__0_1_","__import_glob__0_2_","__import_glob__0_3_","__import_glob__0_4_","__import_glob__0_5_","__import_glob__0_6_","__import_glob__0_7_","__import_glob__0_8_","__import_glob__0_9_","__import_glob__0_10_","__import_glob__0_11_","__import_glob__0_12_","__import_glob__0_13_","__import_glob__0_14_","__import_glob__0_15_","__import_glob__0_16_","__import_glob__0_17_","__import_glob__0_18_","__import_glob__0_19_","__import_glob__0_20_","__import_glob__0_21_","__import_glob__0_22_","__import_glob__0_23_","__import_glob__0_24_","__import_glob__0_25_","__import_glob__0_26_","__import_glob__0_27_","__import_glob__0_28_","__import_glob__0_29_","__import_glob__0_30_","__import_glob__0_31_","__import_glob__0_32_","__import_glob__0_33_","__import_glob__0_34_","__import_glob__0_35_","__import_glob__0_36_","__import_glob__0_37_","__import_glob__0_38_","__import_glob__0_39_","__import_glob__0_40_","__import_glob__0_41_","__import_glob__0_42_","__import_glob__0_43_","__import_glob__0_44_","__import_glob__0_45_","__import_glob__0_46_","__import_glob__0_47_","__import_glob__0_48_","__import_glob__0_49_","__import_glob__0_50_","__import_glob__0_51_","__import_glob__0_52_","__import_glob__0_53_","__import_glob__0_54_","__import_glob__0_55_","__import_glob__0_56_","__import_glob__0_57_","__import_glob__0_58_","__import_glob__0_59_","__import_glob__0_60_","__import_glob__0_61_","__import_glob__0_62_","__import_glob__0_63_","__import_glob__0_64_","__exportAll","MissingShadcnError","RegistryUnavailableError","InvalidArgumentError","getLogger","NOOP_LOGGER","formatSource","TANSTACK_TABLE_CORE","SUPERFORMS_VERSION","FORMSNAP","SUPERFORMS","readComponentsConfig","fetchRegistryIndex","assertTableCorePackage","registryIndexUrl","resolveUiDir","assertRegistryPagination","path","spawn","os","auth_menu_content_default","auth_menu_group_default","auth_menu_item_default","auth_menu_label_default","auth_menu_separator_default","auth_menu_trigger_default","auth_menu_default$1","context_default","auth_menu_default","autodate_default","bool_default","date_default","editor_default","email_default","file_default","geoPoint_default","cells_default","json_default","number_default","password_default","relation_default","select_default","text_default","url_default","column_header_default$1","column_header_default","data_table_svelte_default","flex_render_default","data_table_default","render_helpers_default","data_table_pagination_default$1","data_table_pagination_default","faceted_filter_default$1","faceted_filter_default","file_field_default","file_input_default","file_multiple_default","file_single_default","file_thumb_default","file_form_default","shared_default","form_button_default","form_description_default","form_element_field_default","form_field_errors_default","form_field_default","form_fieldset_default","form_label_default","form_legend_default","form_default","coordinate_default","geopoint_default","input_default$1","toggle_map_default","leaflet_default$1","leaflet_default","chip_default","content_default","field_default","multiselect_default","input_default","item_default","trigger_default","row_actions_default$1","row_actions_default","write_result_exports","assertComponentsAvailable","installComponents","writeResult","customDependencies","customNpmPackages","customComponentAssets","getAllCustomComponents","componentNameFromAssetPath","parts","assetPath","componentRelativeAssetPath","index","toTargetPath","filePath","root","toRelativePath","writeFile","mkdirSync","writeFileSync","content","removeFile","existsSync","rmSync","pruneEmptyDirectories","stop","current","dir","readdirSync","EXACT_FLAG","executeWithDetectedPackageManager","packageManager","detect","resolved","resolveCommand","operation","args","commandArgs","exactFlag","options","child","reject","code","resolve","executeCommand","restoreTypes","preserveSvelteKitTypes","cwd","runtime","installedPackagesFromProject","packageJsonPath","packageJson","readFileSync","packageName","at","spec","isExactSpec","name","reconcileFormsnap","names","toInstall","formsnap","installed","touched","file","text","pkg","changed","formsnapRange","wantedFloor","rangeFloor","block","DEPENDENCY_BLOCKS","deps","floor","compareFloors","overrides","entry","_","rest","__","others","next","indent","logger","appDir","saved","mkdtempSync","cpSync","ensureSvelteKitSync","error","match","part","value","i","a","b","restoreDowngradedDependencies","after","restored","previous","before","entries","old","oldFloor","newFloor","readPackageJson","FLOOR_ENFORCED","isBelowFloor","wanted","have","installedManifest","version","manifest","range","installPackages","packages","exact","ranged","uninstallPackages","toRemove","isCustomComponent","component","customNpmPackagesFor","components","copyCustomComponent","targetDir","targetComponentsDir","relativePath","outputPath","FORMATTABLE_EXTENSIONS","filesUnder","target","statSync","formatPaths","context","paths","formatted","fileDigests","digests","dirs","createHash","filesWrittenSince","digest","installedComponents","uiDir","BARE_ITEM_NAME","REGISTRY_RETRY_MS","registryUnavailableAt","assertKnownRegistryItems","bare","config","url","fetchImpl","failedAt","known","item","failures","unknown","planComponentInstall","requested","componentsDir","isPresent","skipped","overwrite","customToInstall","publicToInstall","dependency","assertPlanInstallable","plan","applyComponentPlan","customList","publicList","shadcnDirs","beforeShadcn","formatWritten","recorded","had","writtenResult","componentPlan","result","dropMigrationCreates","n","dropCollections","isPackageJson","packageInstalls","componentInstalls","packageUninstalls","_written","reported"],"sources":["../../src/runtime/write-result.ts"],"sourcesContent":["import {\n cpSync,\n existsSync,\n mkdirSync,\n mkdtempSync,\n readdirSync,\n readFileSync,\n rmSync,\n statSync,\n writeFileSync,\n} from \"node:fs\";\nimport { createHash } from \"node:crypto\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { detect } from \"package-manager-detector\";\nimport { resolveCommand } from \"package-manager-detector/commands\";\nimport spawn from \"cross-spawn\";\nimport type {\n Component,\n ExecuteCommandOptions,\n InstallComponentsOptions,\n InstallComponentsResult,\n Options,\n PackageManagerOperation,\n Result,\n WriteResultRuntime,\n} from \"../core/types\";\nimport {\n InvalidArgumentError,\n MissingShadcnError,\n RegistryUnavailableError,\n} from \"../core/errors\";\nimport { getLogger, NOOP_LOGGER, type Logger } from \"../core/logger\";\nimport { formatSource } from \"../core/format-result\";\nimport {\n FORMSNAP,\n SUPERFORMS,\n SUPERFORMS_VERSION,\n TANSTACK_TABLE_CORE,\n} from \"../core/constants\";\nimport {\n fetchRegistryIndex,\n readComponentsConfig,\n registryIndexUrl,\n resolveUiDir,\n} from \"./registry\";\nimport { assertRegistryPagination, assertTableCorePackage } from \"./table-core\";\n\nexport { resolveUiDir };\n\ntype CustomNpmPackages = Record<string, string[]>;\n\n/**\n * The components under `src/ui/components` are copied into a project rather\n * than fetched from the shadcn-svelte registry, so their dependencies have to\n * be declared here: every shadcn-svelte component a bundled one imports\n * (`#lib/components/ui/<x>/index.js`) must appear in `customDependencies`, and\n * every npm package that no shadcn item installs for it must appear in\n * `customNpmPackages`.\n *\n * `form` is shadcn-svelte's own formsnap wrapper as it last shipped it: the\n * registry dropped the item from every style on 2026-11-24\n * (huntabyte/shadcn-svelte#2989), and the superforms pages the patterns\n * generate are built on it.\n */\nexport const customDependencies: Record<string, string[]> = {\n \"file-form\": [\"input\"],\n form: [\"label\", \"button\"],\n multiselect: [\"command\", \"popover\", \"button\"],\n geopoint: [\"button\", \"leaflet\"],\n cells: [\"badge\"],\n \"data-table\": [],\n \"column-header\": [\"dropdown-menu\", \"button\"],\n \"faceted-filter\": [\"command\", \"popover\", \"button\", \"separator\", \"badge\"],\n \"data-table-pagination\": [\"pagination\", \"select\"],\n \"row-actions\": [\"dropdown-menu\", \"button\"],\n leaflet: [],\n \"auth-menu\": [\"dropdown-menu\", \"button\"],\n};\n\nconst customNpmPackages: CustomNpmPackages = {\n \"file-form\": [FORMSNAP],\n // What the registry item used to record. Superforms is named because the\n // field components import its path types.\n form: [FORMSNAP, SUPERFORMS],\n multiselect: [FORMSNAP],\n geopoint: [],\n cells: [],\n // shadcn-svelte >= 1.2.0 resolves items from the style-scoped registry\n // (/registry/styles/<style>/), which has no `data-table` item, so the\n // TanStack helpers ship from here instead.\n \"data-table\": [TANSTACK_TABLE_CORE],\n \"column-header\": [TANSTACK_TABLE_CORE],\n \"faceted-filter\": [TANSTACK_TABLE_CORE],\n \"data-table-pagination\": [TANSTACK_TABLE_CORE],\n \"row-actions\": [],\n leaflet: [\"leaflet\", \"@types/leaflet\"],\n};\n\nconst customComponentAssets = import.meta.glob<string>(\"../ui/components/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n});\n\n/** The components this package ships, by directory name, sorted. */\nexport function getAllCustomComponents(): Component[] {\n return [\n ...new Set(\n Object.keys(customComponentAssets).map(componentNameFromAssetPath),\n ),\n ]\n .filter(Boolean)\n .sort();\n}\n\nfunction componentNameFromAssetPath(assetPath: string): string {\n const parts = assetPath.split(\"/\");\n const index = parts.indexOf(\"components\");\n return parts[index + 1] ?? \"\";\n}\n\nfunction componentRelativeAssetPath(assetPath: string): string {\n const parts = assetPath.split(\"/\");\n const index = parts.indexOf(\"components\");\n return parts.slice(index + 2).join(\"/\");\n}\n\nfunction toTargetPath(root: string, filePath: string): string {\n if (path.isAbsolute(filePath)) {\n return filePath;\n }\n return path.join(root, filePath);\n}\n\nfunction toRelativePath(root: string, filePath: string): string {\n if (path.isAbsolute(filePath)) {\n return path.relative(root, filePath);\n }\n return filePath;\n}\n\nfunction writeFile(filePath: string, content: string): void {\n mkdirSync(path.dirname(filePath), { recursive: true });\n writeFileSync(filePath, content, \"utf8\");\n}\n\nfunction removeFile(filePath: string, root: string): void {\n if (!existsSync(filePath)) {\n return;\n }\n\n rmSync(filePath, { force: true, recursive: true });\n pruneEmptyDirectories(path.dirname(filePath), root);\n}\n\n/**\n * Deleting a feature's files must also delete the directories it added, up\n * to the first one that still has content. The CLI detects features by\n * directory (`src/routes/(app)` means auth is on), so an empty leftover\n * directory keeps a disabled feature \"enabled\".\n */\nfunction pruneEmptyDirectories(dir: string, root: string): void {\n const stop = path.resolve(root);\n let current = path.resolve(dir);\n while (current !== stop && current.startsWith(stop)) {\n if (!existsSync(current) || readdirSync(current).length > 0) {\n return;\n }\n rmSync(current, { recursive: true, force: true });\n current = path.dirname(current);\n }\n}\n\n/** Each package manager's flag for saving the exact version instead of a range. */\nconst EXACT_FLAG: Record<string, string> = {\n npm: \"--save-exact\",\n pnpm: \"--save-exact\",\n yarn: \"--exact\",\n bun: \"--exact\",\n};\n\nasync function executeWithDetectedPackageManager(\n cwd: string,\n operation: PackageManagerOperation,\n args: string[],\n options: ExecuteCommandOptions = {},\n): Promise<void> {\n const packageManager = (await detect({ cwd }))?.name ?? \"npm\";\n // Adding named packages is `add` (`npm i`, `pnpm add`, `yarn add`):\n // `yarn install <pkg>` is an error.\n const resolved = resolveCommand(\n packageManager,\n operation === \"install\" && args.length > 0 ? \"add\" : operation,\n args,\n );\n if (!resolved) {\n throw new Error(\n `Unable to resolve ${operation} command for ${packageManager}`,\n );\n }\n\n const commandArgs = [...resolved.args];\n if (packageManager === \"npm\") {\n commandArgs.unshift(\"--yes\");\n }\n const exactFlag = EXACT_FLAG[packageManager];\n if (options.exact && exactFlag) {\n commandArgs.push(exactFlag);\n }\n\n await new Promise<void>((resolve, reject) => {\n const child = spawn(resolved.command, commandArgs, {\n cwd,\n stdio: \"inherit\",\n });\n child.on(\"error\", reject);\n child.on(\"exit\", (code) => {\n if (code === 0) {\n resolve();\n return;\n }\n reject(\n new Error(`${resolved.command} exited with code ${code ?? \"unknown\"}`),\n );\n });\n });\n}\n\nexport async function executeCommand(\n cwd: string,\n operation: PackageManagerOperation,\n args: string[],\n runtime?: WriteResultRuntime,\n options?: ExecuteCommandOptions,\n): Promise<void> {\n const restoreTypes =\n operation === \"execute\" ? null : preserveSvelteKitTypes(cwd);\n try {\n if (runtime?.executeCommand) {\n await (options\n ? runtime.executeCommand(cwd, operation, args, options)\n : runtime.executeCommand(cwd, operation, args));\n return;\n }\n\n await executeWithDetectedPackageManager(cwd, operation, args, options);\n } finally {\n restoreTypes?.();\n }\n}\n\n/** Package names `package.json` records, whichever dependency block they sit in. */\nexport function installedPackagesFromProject(root: string): Set<string> {\n const packageJsonPath = path.join(root, \"package.json\");\n if (!existsSync(packageJsonPath)) {\n return new Set();\n }\n\n const packageJson = JSON.parse(readFileSync(packageJsonPath, \"utf8\")) as {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n optionalDependencies?: Record<string, string>;\n peerDependencies?: Record<string, string>;\n };\n\n return new Set([\n ...Object.keys(packageJson.dependencies ?? {}),\n ...Object.keys(packageJson.devDependencies ?? {}),\n ...Object.keys(packageJson.optionalDependencies ?? {}),\n ...Object.keys(packageJson.peerDependencies ?? {}),\n ]);\n}\n\n/**\n * Splits an npm install spec into its package name, dropping any range.\n * `wuchale@^0.26.3` -> `wuchale`, `@wuchale/svelte@^0.21.1` -> `@wuchale/svelte`.\n *\n * The name is what `package.json` records, so it -- not the full spec -- is what\n * the already-installed check has to compare against.\n */\nexport function packageName(spec: string): string {\n const at = spec.indexOf(\"@\", spec.startsWith(\"@\") ? 1 : 0);\n return at === -1 ? spec : spec.slice(0, at);\n}\n\n/**\n * A spec naming one exact version (`sveltekit-superforms@3.0.0`),\n * which is saved as written. Package managers otherwise save a caret, and a\n * caret on a prerelease follows every later `next` build.\n */\nexport function isExactSpec(spec: string): boolean {\n const name = packageName(spec);\n return /^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?$/.test(\n spec.slice(name.length + 1),\n );\n}\n\n/**\n * formsnap 2.1 is the first release whose superforms peer admits 3.x, and\n * npm reads that `^3.0.0` peer as excluding `3.0.0-next.*`. Before an install\n * brings formsnap or superforms in next to the other, package.json is moved\n * to what resolves: a `3.0.0-next` superforms pin to the release, a formsnap\n * range below 2.1 to `FORMSNAP`, and the `overrides` entry earlier releases\n * wrote for formsnap 2.0 goes. Left as it is, `npm install` either stops with\n * ERESOLVE or keeps the formsnap 2.0 its lockfile holds, whose peer\n * superforms 3 does not meet.\n */\nfunction reconcileFormsnap(\n root: string,\n installed: Set<string>,\n toInstall: string[],\n logger: Logger,\n): void {\n const names = new Set(toInstall.map(packageName));\n const formsnap = names.has(\"formsnap\") || installed.has(\"formsnap\");\n const touched = names.has(\"formsnap\") || names.has(\"sveltekit-superforms\");\n if (!formsnap || !touched) {\n return;\n }\n const file = path.join(root, \"package.json\");\n if (!existsSync(file)) {\n return;\n }\n const text = readFileSync(file, \"utf8\");\n const pkg = JSON.parse(text) as Record<string, unknown>;\n const changed: string[] = [];\n\n const formsnapRange = FORMSNAP.slice(packageName(FORMSNAP).length + 1);\n const wantedFloor = rangeFloor(formsnapRange)!;\n for (const block of DEPENDENCY_BLOCKS) {\n const deps = pkg[block] as Record<string, string> | undefined;\n if (!deps) {\n continue;\n }\n if (deps[\"sveltekit-superforms\"]?.startsWith(\"3.0.0-\")) {\n deps[\"sveltekit-superforms\"] = SUPERFORMS_VERSION;\n changed.push(`sveltekit-superforms → ${SUPERFORMS_VERSION}`);\n }\n const floor =\n deps.formsnap === undefined ? null : rangeFloor(deps.formsnap);\n if (floor && compareFloors(floor, wantedFloor) < 0) {\n deps.formsnap = formsnapRange;\n changed.push(`formsnap → ${formsnapRange}`);\n }\n }\n\n const overrides = pkg.overrides as Record<string, unknown> | undefined;\n const entry = overrides?.formsnap;\n if (\n typeof entry === \"object\" &&\n entry !== null &&\n \"sveltekit-superforms\" in entry\n ) {\n const { \"sveltekit-superforms\": _, ...rest } = entry as Record<\n string,\n unknown\n >;\n const { formsnap: __, ...others } = overrides!;\n const next =\n Object.keys(rest).length > 0 ? { ...others, formsnap: rest } : others;\n if (Object.keys(next).length > 0) {\n pkg.overrides = next;\n } else {\n delete pkg.overrides;\n }\n changed.push(\"dropped the overrides entry formsnap 2.0 needed\");\n }\n\n if (changed.length === 0) {\n return;\n }\n const indent = text.match(/^[{]\\s*\\n([\\t ]+)/)?.[1] ?? \"\\t\";\n writeFileSync(file, `${JSON.stringify(pkg, null, indent)}\\n`, \"utf8\");\n logger.info(`formsnap 2.1 peers superforms 3: ${changed.join(\", \")}`);\n}\n\n/**\n * SvelteKit 3's tsconfig extends `$app/tsconfig`, which `svelte-kit sync`\n * writes to `node_modules/$app`. A package-manager install prunes that folder\n * (it is no package) and only an argument-less npm install's `prepare` writes\n * it back, so after `npm install <pkg>` every tool that reads the tsconfig\n * (shadcn-svelte, svelte-check without sync, the editor) fails on the missing\n * `extends`. Syncing again is no fix mid-pattern: it loads vite.config, which\n * may already name a plugin whose own config the pattern has not written yet.\n * So the folder is copied aside before an install and put back after.\n */\nfunction preserveSvelteKitTypes(root: string): (() => void) | null {\n const appDir = path.join(root, \"node_modules\", \"$app\");\n if (!existsSync(appDir)) {\n return null;\n }\n const saved = mkdtempSync(path.join(os.tmpdir(), \"vela-app-types-\"));\n cpSync(appDir, path.join(saved, \"$app\"), { recursive: true });\n return () => {\n try {\n if (!existsSync(appDir) && existsSync(path.join(root, \"node_modules\"))) {\n cpSync(path.join(saved, \"$app\"), appDir, { recursive: true });\n }\n } finally {\n rmSync(saved, { recursive: true, force: true });\n }\n };\n}\n\n/**\n * Run `svelte-kit sync` when SvelteKit is installed but `node_modules/$app`\n * is missing (a fresh copy of `node_modules`, or an install made outside\n * vela), so shadcn-svelte can read the tsconfig. Best effort: a sync that\n * fails is reported and left to shadcn-svelte to complain about.\n */\nexport async function ensureSvelteKitSync(\n root: string,\n runtime?: WriteResultRuntime,\n logger: Logger = NOOP_LOGGER,\n): Promise<boolean> {\n if (!existsSync(path.join(root, \"node_modules\", \"@sveltejs\", \"kit\"))) {\n return false;\n }\n if (existsSync(path.join(root, \"node_modules\", \"$app\", \"tsconfig.json\"))) {\n return false;\n }\n try {\n await executeCommand(root, \"execute\", [\"svelte-kit\", \"sync\"], runtime);\n return true;\n } catch (error) {\n logger.info(\n `svelte-kit sync failed (${error instanceof Error ? error.message : String(error)}); node_modules/$app is missing`,\n );\n return false;\n }\n}\n\ntype DependencyBlocks = Record<string, Record<string, string> | undefined>;\n\nconst DEPENDENCY_BLOCKS = [\n \"dependencies\",\n \"devDependencies\",\n \"optionalDependencies\",\n] as const;\n\n/** The lowest version a range names, as numbers, or null when it is no semver range. */\nfunction rangeFloor(spec: string): number[] | null {\n const match = spec\n .trim()\n .match(\n /^(?:[\\^~=v]|>=?)?\\s*(\\d+)(?:\\.(\\d+|[xX*]))?(?:\\.(\\d+|[xX*]))?(-[0-9A-Za-z.-]+)?$/,\n );\n if (!match) {\n return null;\n }\n const part = (value: string | undefined) =>\n value === undefined || /[xX*]/.test(value) ? 0 : Number(value);\n // A prerelease sorts below its release.\n return [part(match[1]), part(match[2]), part(match[3]), match[4] ? 0 : 1];\n}\n\nfunction compareFloors(a: number[], b: number[]): number {\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return a[i]! - b[i]!;\n }\n }\n return 0;\n}\n\n/**\n * The dependency entries `shadcn-svelte add` changed that have to go back:\n * shadcn replaces any range its registry item's own range does not cover,\n * downgrades included. The form item asked for `sveltekit-superforms` ^2,\n * which SvelteKit 3 cannot install, over the project's 3.x pin (the item is\n * gone from the registry and `form` ships from this package now, but any\n * item may do the same to another package). So an\n * entry the project already had is restored when shadcn moved it below\n * where it was, or when it is not a semver range at all (file:, git,\n * workspace:). A raised floor and every new entry are kept.\n */\nexport function restoreDowngradedDependencies(\n before: DependencyBlocks,\n after: DependencyBlocks,\n): { pkg: DependencyBlocks; restored: string[] } {\n const pkg: DependencyBlocks = { ...after };\n const restored: string[] = [];\n const previous = new Map<string, string>();\n for (const block of DEPENDENCY_BLOCKS) {\n for (const [name, spec] of Object.entries(before[block] ?? {})) {\n previous.set(name, spec);\n }\n }\n for (const block of DEPENDENCY_BLOCKS) {\n const entries = after[block];\n if (!entries) {\n continue;\n }\n for (const [name, spec] of Object.entries(entries)) {\n const old = previous.get(name);\n if (old === undefined || old === spec) {\n continue;\n }\n const oldFloor = rangeFloor(old);\n const newFloor = rangeFloor(spec);\n const keep =\n oldFloor !== null &&\n newFloor !== null &&\n compareFloors(newFloor, oldFloor) >= 0;\n if (keep) {\n continue;\n }\n pkg[block] = { ...(pkg[block] as Record<string, string>), [name]: old };\n restored.push(`${name}@${old}`);\n }\n }\n return { pkg, restored };\n}\n\nfunction readPackageJson(root: string): Record<string, unknown> | null {\n const file = path.join(root, \"package.json\");\n if (!existsSync(file)) {\n return null;\n }\n return JSON.parse(readFileSync(file, \"utf8\")) as Record<string, unknown>;\n}\n\n/**\n * Packages a project is brought up to, not just given when it has none: what\n * the generated code imports from them did not exist in earlier releases.\n * Any other package is left at whatever version the project has, since a\n * floor in `versions.json` rises every week and a generator should not move\n * a project's dependencies each time it runs.\n */\nconst FLOOR_ENFORCED = new Set<string>([\n // `requireUser` in `@velastack/pocketbase/auth` is new in 0.5.3.\n \"@velastack/pocketbase\",\n]);\n\n/**\n * Whether the project has `spec`'s package at a version below the one the\n * spec starts at, for the packages in `FLOOR_ENFORCED`. The version is the\n * installed one when there is a `node_modules`, since a range such as\n * `^0.5.1` says nothing about which release the lockfile holds; without one,\n * the floor of the range in `package.json`.\n */\nfunction isBelowFloor(root: string, spec: string): boolean {\n const name = packageName(spec);\n if (!FLOOR_ENFORCED.has(name)) return false;\n const wanted = rangeFloor(spec.slice(name.length + 1));\n if (!wanted) return false;\n\n let have: number[] | null = null;\n const installedManifest = path.join(\n root,\n \"node_modules\",\n ...name.split(\"/\"),\n \"package.json\",\n );\n if (existsSync(installedManifest)) {\n try {\n const { version } = JSON.parse(readFileSync(installedManifest, \"utf8\"));\n have = typeof version === \"string\" ? rangeFloor(version) : null;\n } catch {\n have = null;\n }\n } else {\n const manifest = JSON.parse(\n readFileSync(path.join(root, \"package.json\"), \"utf8\"),\n ) as Record<string, Record<string, string> | undefined>;\n const range = [\n \"dependencies\",\n \"devDependencies\",\n \"optionalDependencies\",\n \"peerDependencies\",\n ]\n .map((block) => manifest[block]?.[name])\n .find((value) => typeof value === \"string\");\n have = range ? rangeFloor(range) : null;\n }\n // Something that is not a plain version (a workspace or git dependency) is\n // the project's own business.\n return have !== null && compareFloors(have, wanted) < 0;\n}\n\nasync function installPackages(\n root: string,\n packages: string[],\n runtime?: WriteResultRuntime,\n logger: Logger = NOOP_LOGGER,\n): Promise<string[]> {\n if (packages.length === 0) {\n return [];\n }\n\n const installed = installedPackagesFromProject(root);\n const toInstall = [...new Set(packages)].filter(\n (pkg) => !installed.has(packageName(pkg)) || isBelowFloor(root, pkg),\n );\n if (toInstall.length === 0) {\n return [];\n }\n\n reconcileFormsnap(root, installed, toInstall, logger);\n\n logger.info(`Installing packages: ${toInstall.join(\", \")}`);\n // `--save-exact` applies to a whole command, so exact pins go in their own.\n const exact = toInstall.filter(isExactSpec);\n const ranged = toInstall.filter((spec) => !isExactSpec(spec));\n if (exact.length > 0) {\n await executeCommand(root, \"install\", exact, runtime, { exact: true });\n }\n if (ranged.length > 0) {\n await executeCommand(root, \"install\", ranged, runtime);\n }\n return toInstall;\n}\n\n/**\n * `npm uninstall` for the listed packages that `package.json` records. The\n * inverse of `installPackages`: names not present are skipped, so a disable\n * pattern can name everything its enable counterpart installed.\n */\nasync function uninstallPackages(\n root: string,\n packages: string[],\n runtime?: WriteResultRuntime,\n logger: Logger = NOOP_LOGGER,\n): Promise<string[]> {\n if (packages.length === 0) {\n return [];\n }\n\n const installed = installedPackagesFromProject(root);\n const toRemove = [...new Set(packages.map(packageName))].filter((pkg) =>\n installed.has(pkg),\n );\n if (toRemove.length === 0) {\n return [];\n }\n\n logger.info(`Removing packages: ${toRemove.join(\", \")}`);\n await executeCommand(root, \"uninstall\", toRemove, runtime);\n return toRemove;\n}\n\nexport function isCustomComponent(component: string): boolean {\n return getAllCustomComponents().includes(component);\n}\n\nfunction customNpmPackagesFor(components: string[]): string[] {\n return [\n ...new Set(\n components.flatMap((component) => customNpmPackages[component] ?? []),\n ),\n ];\n}\n\nfunction copyCustomComponent(\n component: string,\n targetComponentsDir: string,\n): void {\n const targetDir = path.join(targetComponentsDir, component);\n mkdirSync(targetDir, { recursive: true });\n\n for (const [assetPath, content] of Object.entries(customComponentAssets)) {\n if (componentNameFromAssetPath(assetPath) !== component) {\n continue;\n }\n const relativePath = componentRelativeAssetPath(assetPath);\n if (!relativePath) {\n continue;\n }\n\n const outputPath = path.join(targetDir, relativePath);\n mkdirSync(path.dirname(outputPath), { recursive: true });\n writeFileSync(outputPath, content, \"utf8\");\n }\n}\n\nconst FORMATTABLE_EXTENSIONS = new Set([\n \".ts\",\n \".js\",\n \".svelte\",\n \".json\",\n \".css\",\n]);\n\nfunction* filesUnder(target: string): Generator<string> {\n if (!existsSync(target)) {\n return;\n }\n if (statSync(target).isFile()) {\n yield target;\n return;\n }\n const entries = readdirSync(target, { recursive: true, withFileTypes: true });\n for (const entry of entries) {\n if (entry.isFile()) {\n yield path.join(entry.parentPath, entry.name);\n }\n }\n}\n\n/**\n * `shadcn-svelte add` and `apply` write files in the registry's style and the\n * bundled components carry this repo's; the project's `npm run lint` expects\n * its own. Runs the project's prettier over the given files and directories\n * (relative to the root or absolute) and returns the relative paths it\n * changed. Paths that do not exist are skipped.\n */\nexport async function formatPaths(\n root: string,\n paths: string[],\n): Promise<string[]> {\n const context = { env: \"runtime\" as const, root };\n const changed: string[] = [];\n for (const target of paths) {\n for (const filePath of filesUnder(toTargetPath(root, target))) {\n if (!FORMATTABLE_EXTENSIONS.has(path.extname(filePath))) {\n continue;\n }\n const content = readFileSync(filePath, \"utf8\");\n const formatted = await formatSource(content, filePath, context);\n if (formatted !== content) {\n writeFileSync(filePath, formatted, \"utf8\");\n changed.push(path.relative(root, filePath));\n }\n }\n }\n return changed;\n}\n\n/**\n * A digest of every file under the given directories. Content, not mtime: a\n * file rewritten within the filesystem's timestamp tick keeps its mtime.\n */\nfunction fileDigests(dirs: string[]): Map<string, string> {\n const digests = new Map<string, string>();\n for (const dir of dirs) {\n for (const filePath of filesUnder(dir)) {\n digests.set(\n filePath,\n createHash(\"sha1\").update(readFileSync(filePath)).digest(\"hex\"),\n );\n }\n }\n return digests;\n}\n\n/** The files under the directories that are new or changed since `before`. */\nfunction filesWrittenSince(\n before: Map<string, string>,\n dirs: string[],\n): string[] {\n return [...fileDigests(dirs)]\n .filter(([filePath, digest]) => before.get(filePath) !== digest)\n .map(([filePath]) => filePath);\n}\n\n/** The component directories a project has, sorted. */\nexport function installedComponents(root: string): Component[] {\n const uiDir = resolveUiDir(root);\n if (!existsSync(uiDir)) {\n return [];\n }\n return readdirSync(uiDir, { withFileTypes: true })\n .filter((entry) => entry.isDirectory())\n .map((entry) => entry.name)\n .sort();\n}\n\n/** Bare item names are checked against the index; URLs and `@scope/item` are shadcn's to resolve. */\nconst BARE_ITEM_NAME = /^[a-z0-9][a-z0-9-]*$/i;\n\n/**\n * How long an unreachable registry is left alone. One command checks the\n * names up to three times (a pattern's preflight, `writeResult`,\n * `installComponents`); offline, only the first should wait out the timeout\n * and say so. Short, so a long-lived caller asks again once it may be online.\n */\nconst REGISTRY_RETRY_MS = 30_000;\n\nconst registryUnavailableAt = new WeakMap<typeof fetch, Map<string, number>>();\n\n/**\n * A name the style's registry does not list would otherwise reach\n * `shadcn-svelte add`, which fails after a fetch with a message that never\n * mentions the style. Skipped when the registry cannot be read: shadcn will\n * report that itself.\n */\nasync function assertKnownRegistryItems(\n root: string,\n components: Component[],\n runtime: WriteResultRuntime | undefined,\n logger: Logger,\n): Promise<void> {\n const bare = components.filter((component) => BARE_ITEM_NAME.test(component));\n if (bare.length === 0) {\n return;\n }\n const config = readComponentsConfig(root);\n const url = registryIndexUrl(config.registry, config.style);\n const fetchImpl = runtime?.fetch ?? globalThis.fetch;\n const failedAt = registryUnavailableAt.get(fetchImpl)?.get(url);\n if (failedAt !== undefined && Date.now() - failedAt < REGISTRY_RETRY_MS) {\n return;\n }\n let known: Set<string>;\n try {\n const index = await fetchRegistryIndex(root, { runtime });\n known = new Set(index.map((item) => item.name));\n } catch (error) {\n if (!(error instanceof RegistryUnavailableError)) throw error;\n logger.info(`${error.message}; leaving component names to shadcn-svelte`);\n let failures = registryUnavailableAt.get(fetchImpl);\n if (!failures) {\n failures = new Map();\n registryUnavailableAt.set(fetchImpl, failures);\n }\n failures.set(url, Date.now());\n return;\n }\n const unknown = bare.filter((component) => !known.has(component));\n if (unknown.length === 0) {\n return;\n }\n const names = unknown.map((component) => `\"${component}\"`).join(\", \");\n throw new InvalidArgumentError(\n `Unknown component${unknown.length > 1 ? \"s\" : \"\"} ${names} for style ${config.style}. Run \\`vela ui list\\` to see what is available.`,\n );\n}\n\n/** What one `installComponents` call will do, worked out without touching the project. */\ninterface ComponentPlan {\n /** Requested but already in the project, and so left alone. */\n skipped: Component[];\n /** Copied from this package: the requested ones and the bundled components they build on, sorted. */\n custom: Component[];\n /** Handed to `shadcn-svelte add`: the requested ones and what the bundled components import, sorted. */\n registry: Component[];\n}\n\nfunction planComponentInstall(\n root: string,\n components: Component[],\n overwrite: boolean,\n): ComponentPlan {\n const requested = [...new Set(components)];\n if (requested.length === 0) {\n return { skipped: [], custom: [], registry: [] };\n }\n\n // `shadcn-svelte add` exits 1 without a `components.json`, after the custom\n // components and their packages are already in. Checked first, so a project\n // without shadcn-svelte is refused whole rather than left half-written.\n if (!existsSync(path.join(root, \"components.json\"))) {\n throw new MissingShadcnError(\n `Adding ${requested.length > 1 ? \"components\" : \"a component\"} (${requested.join(\", \")})`,\n );\n }\n\n const componentsDir = resolveUiDir(root);\n const isPresent = (component: string) =>\n existsSync(path.join(componentsDir, component));\n\n const skipped = overwrite ? [] : requested.filter(isPresent);\n const toInstall = requested.filter(\n (component) => !skipped.includes(component),\n );\n\n const customToInstall = new Set(toInstall.filter(isCustomComponent));\n const publicToInstall = new Set(\n toInstall.filter((component) => !isCustomComponent(component)),\n );\n\n // Dependencies are added only when missing, even under `overwrite`:\n // re-adding `button` because `pagination` was re-added would clobber edits\n // the user never asked to lose.\n for (const component of [...customToInstall]) {\n for (const dependency of customDependencies[component] ?? []) {\n if (isPresent(dependency)) {\n continue;\n }\n if (isCustomComponent(dependency)) {\n customToInstall.add(dependency);\n } else {\n publicToInstall.add(dependency);\n }\n }\n }\n\n return {\n skipped,\n custom: [...customToInstall].sort(),\n registry: [...publicToInstall].sort(),\n };\n}\n\n/**\n * Every reason an install would be refused, checked before it writes\n * anything: copying a bundled component, installing its packages and\n * spawning `shadcn-svelte add` all come after.\n */\nasync function assertPlanInstallable(\n root: string,\n plan: ComponentPlan,\n runtime: WriteResultRuntime | undefined,\n logger: Logger,\n): Promise<void> {\n // `installPackages` keeps an existing @tanstack/table-core whatever its range.\n assertTableCorePackage(root, plan.custom);\n if (plan.custom.includes(\"data-table-pagination\")) {\n assertRegistryPagination(root);\n }\n await assertKnownRegistryItems(root, plan.registry, runtime, logger);\n}\n\nexport interface AssertComponentsAvailableOptions {\n /** As for `installComponents`: also check the named components that are already present. */\n overwrite?: boolean;\n logger?: Logger;\n}\n\n/**\n * The preflight for `installComponents`: throws what it would throw for\n * these components, and changes nothing. `MissingShadcnError` without a\n * `components.json`, `InvalidArgumentError` for a name the style's registry\n * does not list (or a project whose table helpers are a major behind).\n * Components already in the project are not checked, as they are not\n * installed.\n *\n * For a caller with side effects of its own ahead of the install. A pattern\n * creates its collections first, and PocketBase writes each one's migration\n * file as it does, so a component the registry has dropped used to leave a\n * migration (and the bundled components, and their packages) behind a run\n * that then failed. `writeResult` and `installComponents` run the same\n * checks before their first write.\n *\n * A registry that cannot be read (offline, a timeout, an HTTP error) does not\n * fail the preflight: the names go unchecked, a line is logged, and\n * `shadcn-svelte add` reports the problem if it is still there at install\n * time, as it did before there was a preflight. The failure is remembered for\n * 30 seconds so the later checks of the same run neither wait nor repeat it.\n */\nexport async function assertComponentsAvailable(\n root: string,\n components: Component[],\n options: AssertComponentsAvailableOptions = {},\n runtime?: WriteResultRuntime,\n): Promise<void> {\n const plan = planComponentInstall(\n root,\n components,\n options.overwrite ?? false,\n );\n await assertPlanInstallable(root, plan, runtime, getLogger(options));\n}\n\nexport async function installComponents(\n options: InstallComponentsOptions,\n runtime?: WriteResultRuntime,\n): Promise<InstallComponentsResult> {\n const { root, components, overwrite = false } = options;\n const logger = getLogger(options);\n const plan = planComponentInstall(root, components, overwrite);\n await assertPlanInstallable(root, plan, runtime, logger);\n return applyComponentPlan(root, plan, runtime, logger);\n}\n\n/** Carries out a plan `assertPlanInstallable` has passed. */\nasync function applyComponentPlan(\n root: string,\n plan: ComponentPlan,\n runtime: WriteResultRuntime | undefined,\n logger: Logger,\n): Promise<InstallComponentsResult> {\n const { skipped, custom: customList, registry: publicList } = plan;\n if (skipped.length > 0) {\n logger.info(`Already present: ${skipped.join(\", \")}`);\n }\n if (customList.length === 0 && publicList.length === 0) {\n return { installed: [], skipped, packages: [] };\n }\n\n const componentsDir = resolveUiDir(root);\n mkdirSync(componentsDir, { recursive: true });\n\n const installed: string[] = [];\n let packages: string[] = [];\n const shadcnDirs = [path.join(root, \"src\", \"lib\"), componentsDir];\n let beforeShadcn: Map<string, string> | undefined;\n\n // The bundled components carry this repo's style and shadcn-svelte's files\n // the registry's. Whatever reached the project is formatted, whether or not\n // the install got to its end: a package install or `shadcn-svelte add` that\n // fails after the components were copied used to leave them as they came,\n // for the project's `prettier --check` to trip over.\n const formatWritten = () =>\n formatPaths(root, [\n ...new Set([\n ...installed.map((component) => path.join(componentsDir, component)),\n ...(beforeShadcn ? filesWrittenSince(beforeShadcn, shadcnDirs) : []),\n ]),\n ]);\n\n try {\n if (customList.length > 0) {\n logger.info(`Installing custom components: ${customList.join(\", \")}`);\n }\n for (const component of customList) {\n copyCustomComponent(component, componentsDir);\n installed.push(component);\n }\n\n packages = await installPackages(\n root,\n customNpmPackagesFor(customList),\n runtime,\n logger,\n );\n\n // `shadcn-svelte add` writes more than the items it is given: each one's\n // registry dependencies too (`command` brings `dialog` and `input-group`),\n // over a copy the project already has, and hooks and utils beside the\n // components. All of it arrives in the registry's style.\n beforeShadcn = publicList.length > 0 ? fileDigests(shadcnDirs) : undefined;\n\n if (publicList.length > 0) {\n logger.info(\n `Installing shadcn-svelte components: ${publicList.join(\", \")}`,\n );\n // shadcn-svelte reads the tsconfig, whose `extends` an install may have pruned.\n await ensureSvelteKitSync(root, runtime, logger);\n // shadcn only records its packages; they are installed below, once any\n // pin it moved backwards is put back.\n const before = readPackageJson(root);\n await executeCommand(\n root,\n \"execute\",\n [\n \"shadcn-svelte\",\n \"add\",\n \"--yes\",\n \"--overwrite\",\n \"--no-deps-install\",\n ...publicList,\n ],\n runtime,\n );\n installed.push(...publicList);\n const after = readPackageJson(root);\n if (before && after && JSON.stringify(before) !== JSON.stringify(after)) {\n const { pkg, restored } = restoreDowngradedDependencies(\n before as DependencyBlocks,\n after as DependencyBlocks,\n );\n if (restored.length > 0) {\n logger.info(\n `Kept ${restored.join(\", \")} (shadcn-svelte asked for an older range)`,\n );\n const file = path.join(root, \"package.json\");\n const indent =\n readFileSync(file, \"utf8\").match(/^[{]\\s*\\n([\\t ]+)/)?.[1] ?? \"\\t\";\n writeFileSync(file, `${JSON.stringify(pkg, null, indent)}\\n`, \"utf8\");\n }\n const recorded = (pkg: Record<string, unknown>) =>\n new Set(\n DEPENDENCY_BLOCKS.flatMap((block) =>\n Object.keys((pkg[block] as Record<string, string>) ?? {}),\n ),\n );\n const had = recorded(before);\n const added = [...recorded(after)].filter((name) => !had.has(name));\n reconcileFormsnap(root, had, added, logger);\n await executeCommand(root, \"install\", [], runtime);\n }\n }\n } catch (error) {\n // The install's error is the one to report.\n await formatWritten().catch(() => {});\n throw error;\n }\n await formatWritten();\n\n const installedList = [...new Set(installed)].sort();\n return { installed: installedList, skipped, packages };\n}\n\nexport async function writeResult(\n result: Result,\n options: Options,\n runtime?: WriteResultRuntime,\n): Promise<Result> {\n const logger = getLogger(options);\n\n const writtenResult: Result = {\n creates: [],\n modifies: [],\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n };\n\n // Before anything is dropped, written or installed: a component that\n // cannot be installed refuses the whole result.\n const componentPlan = planComponentInstall(\n options.root,\n result.components,\n false,\n );\n await assertPlanInstallable(options.root, componentPlan, runtime, logger);\n\n let dropMigrationCreates: Result[\"creates\"] = [];\n if (result.collectionDrops.length > 0) {\n const { dropCollections } = await import(\"./collections\");\n // PocketBase writes these while the collections drop, after the result\n // was formatted, so they still carry its own style.\n dropMigrationCreates = await Promise.all(\n (await dropCollections(result.collectionDrops, options)).map(\n async (file) => ({\n ...file,\n content: await formatSource(file.content, file.path, options, {\n created: true,\n }),\n }),\n ),\n );\n }\n\n // A package.json edit lands before the package manager runs, so the install\n // builds on it. Written after, its content (read before the install) would\n // take back every dependency the install just recorded.\n const packageJsonPath = path.resolve(options.root, \"package.json\");\n const isPackageJson = (file: Result[\"modifies\"][number]) =>\n file.status === \"success\" &&\n path.resolve(toTargetPath(options.root, file.path)) === packageJsonPath;\n for (const file of result.modifies.filter(isPackageJson)) {\n writeFile(packageJsonPath, file.content);\n }\n\n const packageInstalls = await installPackages(\n options.root,\n result.packages,\n runtime,\n logger,\n );\n\n const componentInstalls = await applyComponentPlan(\n options.root,\n componentPlan,\n runtime,\n logger,\n );\n\n const packageUninstalls = await uninstallPackages(\n options.root,\n result.uninstalls ?? [],\n runtime,\n logger,\n );\n\n for (const file of [...result.creates, ...dropMigrationCreates]) {\n if (file.status !== \"success\") {\n // A modifier that could not recognise the file it was asked to edit\n // reports `failed` / `not-found` with a paste-ready remediation snippet.\n // Nothing is written, but the entry has to survive into the result: this\n // loop used to `continue` before pushing, so the entry never reached the\n // caller at all and the snippet was lost. The pattern reported success\n // and simply said nothing about the file it had given up on.\n writtenResult.creates.push({\n ...file,\n path: toRelativePath(options.root, file.path),\n });\n continue;\n }\n const target = toTargetPath(options.root, file.path);\n if (!existsSync(target)) {\n writeFile(target, file.content);\n writtenResult.creates.push({\n ...file,\n path: toRelativePath(options.root, file.path),\n });\n continue;\n }\n // A `written` file is the run's own (a migration PocketBase wrote and\n // `readMigration` formatted), reported even when there is nothing left\n // to write: the CLI lists a new migration from this entry.\n const changed = readFileSync(target, \"utf8\") !== file.content;\n if (changed) {\n writeFile(target, file.content);\n }\n if (changed || file.written) {\n // The marker is this module's and `readMigration`'s; callers get the\n // entry in the shape it always had.\n const { written: _written, ...reported } = file;\n writtenResult.modifies.push({\n ...reported,\n path: toRelativePath(options.root, file.path),\n });\n }\n }\n\n for (const file of result.modifies) {\n if (isPackageJson(file)) {\n writtenResult.modifies.push({\n ...file,\n path: toRelativePath(options.root, file.path),\n });\n continue;\n }\n if (file.status !== \"success\") {\n // Carried through unwritten, so the caller can report the failure. See\n // the note in the creates loop above.\n writtenResult.modifies.push({\n ...file,\n path: toRelativePath(options.root, file.path),\n });\n continue;\n }\n writeFile(toTargetPath(options.root, file.path), file.content);\n writtenResult.modifies.push({\n ...file,\n path: toRelativePath(options.root, file.path),\n });\n }\n\n for (const file of result.deletes) {\n if (file.status !== \"success\") {\n writtenResult.deletes.push({\n ...file,\n path: toRelativePath(options.root, file.path),\n });\n continue;\n }\n if (existsSync(toTargetPath(options.root, file.path))) {\n removeFile(toTargetPath(options.root, file.path), options.root);\n writtenResult.deletes.push({\n ...file,\n path: toRelativePath(options.root, file.path),\n });\n }\n }\n\n return {\n ...result,\n creates: writtenResult.creates,\n modifies: writtenResult.modifies,\n deletes: writtenResult.deletes,\n components: componentInstalls.installed,\n packages: [...new Set([...packageInstalls, ...componentInstalls.packages])],\n ...(packageUninstalls.length > 0 ? { uninstalls: packageUninstalls } : {}),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;A,IAiEa0J,KAA+C;CAC1D,aAAa,CAAC,OAAO;CACrB,MAAM,CAAC,SAAS,QAAQ;CACxB,aAAa;EAAC;EAAW;EAAW;CAAQ;CAC5C,UAAU,CAAC,UAAU,SAAS;CAC9B,OAAO,CAAC,OAAO;CACf,cAAc,CAAC;CACf,iBAAiB,CAAC,iBAAiB,QAAQ;CAC3C,kBAAkB;EAAC;EAAW;EAAW;EAAU;EAAa;CAAO;CACvE,yBAAyB,CAAC,cAAc,QAAQ;CAChD,eAAe,CAAC,iBAAiB,QAAQ;CACzC,SAAS,CAAC;CACV,aAAa,CAAC,iBAAiB,QAAQ;AACzC,GAEMC,KAAuC;CAC3C,aAAa,CAACjF,CAAQ;CAGtB,MAAM,CAACA,GAAUC,CAAU;CAC3B,aAAa,CAACD,CAAQ;CACtB,UAAU,CAAC;CACX,OAAO,CAAC;CAIR,cAAc,CAACF,CAAmB;CAClC,iBAAiB,CAACA,CAAmB;CACrC,kBAAkB,CAACA,CAAmB;CACtC,yBAAyB,CAACA,CAAmB;CAC7C,eAAe,CAAC;CAChB,SAAS,CAAC,WAAW,gBAAgB;AACvC,GAEMoF,IAAwB,uBAAA,OAAA;CAAA,uDAAA5J;CAAA,qDAAAC;CAAA,oDAAAC;CAAA,qDAAAC;CAAA,yDAAAC;CAAA,uDAAAC;CAAA,+CAAAC;CAAA,yCAAAC;CAAA,uCAAAC;CAAA,0CAA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AO,UACxB,AAAII,EAAcxH,CAAI,KAOlBA,EAAK,WAAW,aASpB/C,EAAUJ,EAAa0B,EAAQ,MAAMyB,EAAK,IAAI,GAAGA,EAAK,OAAO,GAC7DkH,EAAc,SAAS,KAAK;EAC1B,GAAGlH;EACH,MAAMhD,EAAeuB,EAAQ,MAAMyB,EAAK,IAAI;CAC9C,CAAC;CAGH,KAAK,IAAMA,KAAQoH,EAAO,SACxB,AAAIpH,EAAK,WAAW,YAOhB1C,EAAWT,EAAa0B,EAAQ,MAAMyB,EAAK,IAAI,CAAC,MAClD3C,GAAWR,EAAa0B,EAAQ,MAAMyB,EAAK,IAAI,GAAGzB,EAAQ,IAAI,GAC9D2I,EAAc,QAAQ,KAAK;EACzB,GAAGlH;EACH,MAAMhD,EAAeuB,EAAQ,MAAMyB,EAAK,IAAI;CAC9C,CAAC,KAXDkH,EAAc,QAAQ,KAAK;EACzB,GAAGlH;EACH,MAAMhD,EAAeuB,EAAQ,MAAMyB,EAAK,IAAI;CAC9C,CAAC;CAYL,OAAO;EACL,GAAGoH;EACH,SAASF,EAAc;EACvB,UAAUA,EAAc;EACxB,SAASA,EAAc;EACvB,YAAYQ,EAAkB;EAC9B,UAAU,CAAC,mBAAG,IAAI,IAAI,CAAC,GAAGD,GAAiB,GAAGC,EAAkB,QAAQ,CAAC,CAAC;EAC1E,GAAIC,EAAkB,SAAS,IAAI,EAAE,YAAYA,EAAkB,IAAI,CAAC;CAC1E;AACF"}
|
|
1
|
+
{"version":3,"file":"write-result-Do8AcYbL.js","names":["__import_glob__0_0_","__import_glob__0_1_","__import_glob__0_2_","__import_glob__0_3_","__import_glob__0_4_","__import_glob__0_5_","__import_glob__0_6_","__import_glob__0_7_","__import_glob__0_8_","__import_glob__0_9_","__import_glob__0_10_","__import_glob__0_11_","__import_glob__0_12_","__import_glob__0_13_","__import_glob__0_14_","__import_glob__0_15_","__import_glob__0_16_","__import_glob__0_17_","__import_glob__0_18_","__import_glob__0_19_","__import_glob__0_20_","__import_glob__0_21_","__import_glob__0_22_","__import_glob__0_23_","__import_glob__0_24_","__import_glob__0_25_","__import_glob__0_26_","__import_glob__0_27_","__import_glob__0_28_","__import_glob__0_29_","__import_glob__0_30_","__import_glob__0_31_","__import_glob__0_32_","__import_glob__0_33_","__import_glob__0_34_","__import_glob__0_35_","__import_glob__0_36_","__import_glob__0_37_","__import_glob__0_38_","__import_glob__0_39_","__import_glob__0_40_","__import_glob__0_41_","__import_glob__0_42_","__import_glob__0_43_","__import_glob__0_44_","__import_glob__0_45_","__import_glob__0_46_","__import_glob__0_47_","__import_glob__0_48_","__import_glob__0_49_","__import_glob__0_50_","__import_glob__0_51_","__import_glob__0_52_","__import_glob__0_53_","__import_glob__0_54_","__import_glob__0_55_","__import_glob__0_56_","__import_glob__0_57_","__import_glob__0_58_","__import_glob__0_59_","__import_glob__0_60_","__import_glob__0_61_","__import_glob__0_62_","__import_glob__0_63_","__import_glob__0_64_","__exportAll","MissingShadcnError","RegistryUnavailableError","InvalidArgumentError","getLogger","NOOP_LOGGER","formatSource","TANSTACK_TABLE_CORE","SUPERFORMS_VERSION","FORMSNAP","SUPERFORMS","readComponentsConfig","fetchRegistryIndex","assertTableCorePackage","registryIndexUrl","resolveUiDir","assertRegistryPagination","path","spawn","os","auth_menu_content_default","auth_menu_group_default","auth_menu_item_default","auth_menu_label_default","auth_menu_separator_default","auth_menu_trigger_default","auth_menu_default$1","context_default","auth_menu_default","autodate_default","bool_default","date_default","editor_default","email_default","file_default","geoPoint_default","cells_default","json_default","number_default","password_default","relation_default","select_default","text_default","url_default","column_header_default$1","column_header_default","data_table_svelte_default","flex_render_default","data_table_default","render_helpers_default","data_table_pagination_default$1","data_table_pagination_default","faceted_filter_default$1","faceted_filter_default","file_field_default","file_input_default","file_multiple_default","file_single_default","file_thumb_default","file_form_default","shared_default","form_button_default","form_description_default","form_element_field_default","form_field_errors_default","form_field_default","form_fieldset_default","form_label_default","form_legend_default","form_default","coordinate_default","geopoint_default","input_default$1","toggle_map_default","leaflet_default$1","leaflet_default","chip_default","content_default","field_default","multiselect_default","input_default","item_default","trigger_default","row_actions_default$1","row_actions_default","write_result_exports","assertComponentsAvailable","installComponents","writeResult","customDependencies","customNpmPackages","customComponentAssets","getAllCustomComponents","componentNameFromAssetPath","parts","assetPath","componentRelativeAssetPath","index","toTargetPath","filePath","root","toRelativePath","writeFile","mkdirSync","writeFileSync","content","removeFile","existsSync","rmSync","pruneEmptyDirectories","stop","current","dir","readdirSync","EXACT_FLAG","executeWithDetectedPackageManager","packageManager","detect","resolved","resolveCommand","operation","args","commandArgs","exactFlag","options","child","reject","code","resolve","executeCommand","restoreTypes","preserveSvelteKitTypes","cwd","runtime","installedPackagesFromProject","packageJsonPath","packageJson","readFileSync","packageName","at","spec","isExactSpec","name","reconcileFormsnap","names","toInstall","formsnap","installed","touched","file","text","pkg","changed","formsnapRange","wantedFloor","rangeFloor","block","DEPENDENCY_BLOCKS","deps","floor","compareFloors","overrides","entry","_","rest","__","others","next","indent","logger","appDir","saved","mkdtempSync","cpSync","ensureSvelteKitSync","error","match","part","value","i","a","b","restoreDowngradedDependencies","after","restored","previous","before","entries","old","oldFloor","newFloor","readPackageJson","FLOOR_ENFORCED","isBelowFloor","wanted","have","installedManifest","version","manifest","range","installPackages","packages","exact","ranged","uninstallPackages","toRemove","isCustomComponent","component","customNpmPackagesFor","components","copyCustomComponent","targetDir","targetComponentsDir","relativePath","outputPath","FORMATTABLE_EXTENSIONS","filesUnder","target","statSync","formatPaths","context","paths","formatted","fileDigests","digests","dirs","createHash","filesWrittenSince","digest","installedComponents","uiDir","BARE_ITEM_NAME","REGISTRY_RETRY_MS","registryUnavailableAt","assertKnownRegistryItems","bare","config","url","fetchImpl","failedAt","known","item","failures","unknown","planComponentInstall","requested","componentsDir","isPresent","skipped","overwrite","customToInstall","publicToInstall","dependency","assertPlanInstallable","plan","applyComponentPlan","customList","publicList","shadcnDirs","beforeShadcn","formatWritten","recorded","had","writtenResult","componentPlan","result","dropMigrationCreates","n","dropCollections","isPackageJson","packageInstalls","componentInstalls","packageUninstalls","_written","reported"],"sources":["../../src/runtime/write-result.ts"],"sourcesContent":["import {\n cpSync,\n existsSync,\n mkdirSync,\n mkdtempSync,\n readdirSync,\n readFileSync,\n rmSync,\n statSync,\n writeFileSync,\n} from \"node:fs\";\nimport { createHash } from \"node:crypto\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { detect } from \"package-manager-detector\";\nimport { resolveCommand } from \"package-manager-detector/commands\";\nimport spawn from \"cross-spawn\";\nimport type {\n Component,\n ExecuteCommandOptions,\n InstallComponentsOptions,\n InstallComponentsResult,\n Options,\n PackageManagerOperation,\n Result,\n WriteResultRuntime,\n} from \"../core/types\";\nimport {\n InvalidArgumentError,\n MissingShadcnError,\n RegistryUnavailableError,\n} from \"../core/errors\";\nimport { getLogger, NOOP_LOGGER, type Logger } from \"../core/logger\";\nimport { formatSource } from \"../core/format-result\";\nimport {\n FORMSNAP,\n SUPERFORMS,\n SUPERFORMS_VERSION,\n TANSTACK_TABLE_CORE,\n} from \"../core/constants\";\nimport {\n fetchRegistryIndex,\n readComponentsConfig,\n registryIndexUrl,\n resolveUiDir,\n} from \"./registry\";\nimport { assertRegistryPagination, assertTableCorePackage } from \"./table-core\";\n\nexport { resolveUiDir };\n\ntype CustomNpmPackages = Record<string, string[]>;\n\n/**\n * The components under `src/ui/components` are copied into a project rather\n * than fetched from the shadcn-svelte registry, so their dependencies have to\n * be declared here: every shadcn-svelte component a bundled one imports\n * (`#lib/components/ui/<x>/index.js`) must appear in `customDependencies`, and\n * every npm package that no shadcn item installs for it must appear in\n * `customNpmPackages`.\n *\n * `form` is shadcn-svelte's own formsnap wrapper as it last shipped it: the\n * registry dropped the item from every style on 2026-11-24\n * (huntabyte/shadcn-svelte#2989), and the superforms pages the patterns\n * generate are built on it.\n */\nexport const customDependencies: Record<string, string[]> = {\n \"file-form\": [\"input\"],\n form: [\"label\", \"button\"],\n multiselect: [\"command\", \"popover\", \"button\"],\n geopoint: [\"button\", \"leaflet\"],\n cells: [\"badge\"],\n \"data-table\": [],\n \"column-header\": [\"dropdown-menu\", \"button\"],\n \"faceted-filter\": [\"command\", \"popover\", \"button\", \"separator\", \"badge\"],\n \"data-table-pagination\": [\"pagination\", \"select\"],\n \"row-actions\": [\"dropdown-menu\", \"button\"],\n leaflet: [],\n \"auth-menu\": [\"dropdown-menu\", \"button\"],\n};\n\nconst customNpmPackages: CustomNpmPackages = {\n \"file-form\": [FORMSNAP],\n // What the registry item used to record. Superforms is named because the\n // field components import its path types.\n form: [FORMSNAP, SUPERFORMS],\n multiselect: [FORMSNAP],\n geopoint: [],\n cells: [],\n // shadcn-svelte >= 1.2.0 resolves items from the style-scoped registry\n // (/registry/styles/<style>/), which has no `data-table` item, so the\n // TanStack helpers ship from here instead.\n \"data-table\": [TANSTACK_TABLE_CORE],\n \"column-header\": [TANSTACK_TABLE_CORE],\n \"faceted-filter\": [TANSTACK_TABLE_CORE],\n \"data-table-pagination\": [TANSTACK_TABLE_CORE],\n \"row-actions\": [],\n leaflet: [\"leaflet\", \"@types/leaflet\"],\n};\n\nconst customComponentAssets = import.meta.glob<string>(\"../ui/components/**\", {\n query: \"?raw\",\n import: \"default\",\n eager: true,\n});\n\n/** The components this package ships, by directory name, sorted. */\nexport function getAllCustomComponents(): Component[] {\n return [\n ...new Set(\n Object.keys(customComponentAssets).map(componentNameFromAssetPath),\n ),\n ]\n .filter(Boolean)\n .sort();\n}\n\nfunction componentNameFromAssetPath(assetPath: string): string {\n const parts = assetPath.split(\"/\");\n const index = parts.indexOf(\"components\");\n return parts[index + 1] ?? \"\";\n}\n\nfunction componentRelativeAssetPath(assetPath: string): string {\n const parts = assetPath.split(\"/\");\n const index = parts.indexOf(\"components\");\n return parts.slice(index + 2).join(\"/\");\n}\n\nfunction toTargetPath(root: string, filePath: string): string {\n if (path.isAbsolute(filePath)) {\n return filePath;\n }\n return path.join(root, filePath);\n}\n\nfunction toRelativePath(root: string, filePath: string): string {\n if (path.isAbsolute(filePath)) {\n return path.relative(root, filePath);\n }\n return filePath;\n}\n\nfunction writeFile(filePath: string, content: string): void {\n mkdirSync(path.dirname(filePath), { recursive: true });\n writeFileSync(filePath, content, \"utf8\");\n}\n\nfunction removeFile(filePath: string, root: string): void {\n if (!existsSync(filePath)) {\n return;\n }\n\n rmSync(filePath, { force: true, recursive: true });\n pruneEmptyDirectories(path.dirname(filePath), root);\n}\n\n/**\n * Deleting a feature's files must also delete the directories it added, up\n * to the first one that still has content. The CLI detects features by\n * directory (`src/routes/(app)` means auth is on), so an empty leftover\n * directory keeps a disabled feature \"enabled\".\n */\nfunction pruneEmptyDirectories(dir: string, root: string): void {\n const stop = path.resolve(root);\n let current = path.resolve(dir);\n while (current !== stop && current.startsWith(stop)) {\n if (!existsSync(current) || readdirSync(current).length > 0) {\n return;\n }\n rmSync(current, { recursive: true, force: true });\n current = path.dirname(current);\n }\n}\n\n/** Each package manager's flag for saving the exact version instead of a range. */\nconst EXACT_FLAG: Record<string, string> = {\n npm: \"--save-exact\",\n pnpm: \"--save-exact\",\n yarn: \"--exact\",\n bun: \"--exact\",\n};\n\nasync function executeWithDetectedPackageManager(\n cwd: string,\n operation: PackageManagerOperation,\n args: string[],\n options: ExecuteCommandOptions = {},\n): Promise<void> {\n const packageManager = (await detect({ cwd }))?.name ?? \"npm\";\n // Adding named packages is `add` (`npm i`, `pnpm add`, `yarn add`):\n // `yarn install <pkg>` is an error.\n const resolved = resolveCommand(\n packageManager,\n operation === \"install\" && args.length > 0 ? \"add\" : operation,\n args,\n );\n if (!resolved) {\n throw new Error(\n `Unable to resolve ${operation} command for ${packageManager}`,\n );\n }\n\n const commandArgs = [...resolved.args];\n if (packageManager === \"npm\") {\n commandArgs.unshift(\"--yes\");\n }\n const exactFlag = EXACT_FLAG[packageManager];\n if (options.exact && exactFlag) {\n commandArgs.push(exactFlag);\n }\n\n await new Promise<void>((resolve, reject) => {\n const child = spawn(resolved.command, commandArgs, {\n cwd,\n stdio: \"inherit\",\n });\n child.on(\"error\", reject);\n child.on(\"exit\", (code) => {\n if (code === 0) {\n resolve();\n return;\n }\n reject(\n new Error(`${resolved.command} exited with code ${code ?? \"unknown\"}`),\n );\n });\n });\n}\n\nexport async function executeCommand(\n cwd: string,\n operation: PackageManagerOperation,\n args: string[],\n runtime?: WriteResultRuntime,\n options?: ExecuteCommandOptions,\n): Promise<void> {\n const restoreTypes =\n operation === \"execute\" ? null : preserveSvelteKitTypes(cwd);\n try {\n if (runtime?.executeCommand) {\n await (options\n ? runtime.executeCommand(cwd, operation, args, options)\n : runtime.executeCommand(cwd, operation, args));\n return;\n }\n\n await executeWithDetectedPackageManager(cwd, operation, args, options);\n } finally {\n restoreTypes?.();\n }\n}\n\n/** Package names `package.json` records, whichever dependency block they sit in. */\nexport function installedPackagesFromProject(root: string): Set<string> {\n const packageJsonPath = path.join(root, \"package.json\");\n if (!existsSync(packageJsonPath)) {\n return new Set();\n }\n\n const packageJson = JSON.parse(readFileSync(packageJsonPath, \"utf8\")) as {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n optionalDependencies?: Record<string, string>;\n peerDependencies?: Record<string, string>;\n };\n\n return new Set([\n ...Object.keys(packageJson.dependencies ?? {}),\n ...Object.keys(packageJson.devDependencies ?? {}),\n ...Object.keys(packageJson.optionalDependencies ?? {}),\n ...Object.keys(packageJson.peerDependencies ?? {}),\n ]);\n}\n\n/**\n * Splits an npm install spec into its package name, dropping any range.\n * `wuchale@^0.26.3` -> `wuchale`, `@wuchale/svelte@^0.21.1` -> `@wuchale/svelte`.\n *\n * The name is what `package.json` records, so it -- not the full spec -- is what\n * the already-installed check has to compare against.\n */\nexport function packageName(spec: string): string {\n const at = spec.indexOf(\"@\", spec.startsWith(\"@\") ? 1 : 0);\n return at === -1 ? spec : spec.slice(0, at);\n}\n\n/**\n * A spec naming one exact version (`sveltekit-superforms@3.0.0`),\n * which is saved as written. Package managers otherwise save a caret, and a\n * caret on a prerelease follows every later `next` build.\n */\nexport function isExactSpec(spec: string): boolean {\n const name = packageName(spec);\n return /^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?$/.test(\n spec.slice(name.length + 1),\n );\n}\n\n/**\n * formsnap 2.1 is the first release whose superforms peer admits 3.x, and\n * npm reads that `^3.0.0` peer as excluding `3.0.0-next.*`. Before an install\n * brings formsnap or superforms in next to the other, package.json is moved\n * to what resolves: a `3.0.0-next` superforms pin to the release, a formsnap\n * range below 2.1 to `FORMSNAP`, and the `overrides` entry earlier releases\n * wrote for formsnap 2.0 goes. Left as it is, `npm install` either stops with\n * ERESOLVE or keeps the formsnap 2.0 its lockfile holds, whose peer\n * superforms 3 does not meet.\n */\nfunction reconcileFormsnap(\n root: string,\n installed: Set<string>,\n toInstall: string[],\n logger: Logger,\n): void {\n const names = new Set(toInstall.map(packageName));\n const formsnap = names.has(\"formsnap\") || installed.has(\"formsnap\");\n const touched = names.has(\"formsnap\") || names.has(\"sveltekit-superforms\");\n if (!formsnap || !touched) {\n return;\n }\n const file = path.join(root, \"package.json\");\n if (!existsSync(file)) {\n return;\n }\n const text = readFileSync(file, \"utf8\");\n const pkg = JSON.parse(text) as Record<string, unknown>;\n const changed: string[] = [];\n\n const formsnapRange = FORMSNAP.slice(packageName(FORMSNAP).length + 1);\n const wantedFloor = rangeFloor(formsnapRange)!;\n for (const block of DEPENDENCY_BLOCKS) {\n const deps = pkg[block] as Record<string, string> | undefined;\n if (!deps) {\n continue;\n }\n if (deps[\"sveltekit-superforms\"]?.startsWith(\"3.0.0-\")) {\n deps[\"sveltekit-superforms\"] = SUPERFORMS_VERSION;\n changed.push(`sveltekit-superforms → ${SUPERFORMS_VERSION}`);\n }\n const floor =\n deps.formsnap === undefined ? null : rangeFloor(deps.formsnap);\n if (floor && compareFloors(floor, wantedFloor) < 0) {\n deps.formsnap = formsnapRange;\n changed.push(`formsnap → ${formsnapRange}`);\n }\n }\n\n const overrides = pkg.overrides as Record<string, unknown> | undefined;\n const entry = overrides?.formsnap;\n if (\n typeof entry === \"object\" &&\n entry !== null &&\n \"sveltekit-superforms\" in entry\n ) {\n const { \"sveltekit-superforms\": _, ...rest } = entry as Record<\n string,\n unknown\n >;\n const { formsnap: __, ...others } = overrides!;\n const next =\n Object.keys(rest).length > 0 ? { ...others, formsnap: rest } : others;\n if (Object.keys(next).length > 0) {\n pkg.overrides = next;\n } else {\n delete pkg.overrides;\n }\n changed.push(\"dropped the overrides entry formsnap 2.0 needed\");\n }\n\n if (changed.length === 0) {\n return;\n }\n const indent = text.match(/^[{]\\s*\\n([\\t ]+)/)?.[1] ?? \"\\t\";\n writeFileSync(file, `${JSON.stringify(pkg, null, indent)}\\n`, \"utf8\");\n logger.info(`formsnap 2.1 peers superforms 3: ${changed.join(\", \")}`);\n}\n\n/**\n * SvelteKit 3's tsconfig extends `$app/tsconfig`, which `svelte-kit sync`\n * writes to `node_modules/$app`. A package-manager install prunes that folder\n * (it is no package) and only an argument-less npm install's `prepare` writes\n * it back, so after `npm install <pkg>` every tool that reads the tsconfig\n * (shadcn-svelte, svelte-check without sync, the editor) fails on the missing\n * `extends`. Syncing again is no fix mid-pattern: it loads vite.config, which\n * may already name a plugin whose own config the pattern has not written yet.\n * So the folder is copied aside before an install and put back after.\n */\nfunction preserveSvelteKitTypes(root: string): (() => void) | null {\n const appDir = path.join(root, \"node_modules\", \"$app\");\n if (!existsSync(appDir)) {\n return null;\n }\n const saved = mkdtempSync(path.join(os.tmpdir(), \"vela-app-types-\"));\n cpSync(appDir, path.join(saved, \"$app\"), { recursive: true });\n return () => {\n try {\n if (!existsSync(appDir) && existsSync(path.join(root, \"node_modules\"))) {\n cpSync(path.join(saved, \"$app\"), appDir, { recursive: true });\n }\n } finally {\n rmSync(saved, { recursive: true, force: true });\n }\n };\n}\n\n/**\n * Run `svelte-kit sync` when SvelteKit is installed but `node_modules/$app`\n * is missing (a fresh copy of `node_modules`, or an install made outside\n * vela), so shadcn-svelte can read the tsconfig. Best effort: a sync that\n * fails is reported and left to shadcn-svelte to complain about.\n */\nexport async function ensureSvelteKitSync(\n root: string,\n runtime?: WriteResultRuntime,\n logger: Logger = NOOP_LOGGER,\n): Promise<boolean> {\n if (!existsSync(path.join(root, \"node_modules\", \"@sveltejs\", \"kit\"))) {\n return false;\n }\n if (existsSync(path.join(root, \"node_modules\", \"$app\", \"tsconfig.json\"))) {\n return false;\n }\n try {\n await executeCommand(root, \"execute\", [\"svelte-kit\", \"sync\"], runtime);\n return true;\n } catch (error) {\n logger.info(\n `svelte-kit sync failed (${error instanceof Error ? error.message : String(error)}); node_modules/$app is missing`,\n );\n return false;\n }\n}\n\ntype DependencyBlocks = Record<string, Record<string, string> | undefined>;\n\nconst DEPENDENCY_BLOCKS = [\n \"dependencies\",\n \"devDependencies\",\n \"optionalDependencies\",\n] as const;\n\n/** The lowest version a range names, as numbers, or null when it is no semver range. */\nfunction rangeFloor(spec: string): number[] | null {\n const match = spec\n .trim()\n .match(\n /^(?:[\\^~=v]|>=?)?\\s*(\\d+)(?:\\.(\\d+|[xX*]))?(?:\\.(\\d+|[xX*]))?(-[0-9A-Za-z.-]+)?$/,\n );\n if (!match) {\n return null;\n }\n const part = (value: string | undefined) =>\n value === undefined || /[xX*]/.test(value) ? 0 : Number(value);\n // A prerelease sorts below its release.\n return [part(match[1]), part(match[2]), part(match[3]), match[4] ? 0 : 1];\n}\n\nfunction compareFloors(a: number[], b: number[]): number {\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return a[i]! - b[i]!;\n }\n }\n return 0;\n}\n\n/**\n * The dependency entries `shadcn-svelte add` changed that have to go back:\n * shadcn replaces any range its registry item's own range does not cover,\n * downgrades included. The form item asked for `sveltekit-superforms` ^2,\n * which SvelteKit 3 cannot install, over the project's 3.x pin (the item is\n * gone from the registry and `form` ships from this package now, but any\n * item may do the same to another package). So an\n * entry the project already had is restored when shadcn moved it below\n * where it was, or when it is not a semver range at all (file:, git,\n * workspace:). A raised floor and every new entry are kept.\n */\nexport function restoreDowngradedDependencies(\n before: DependencyBlocks,\n after: DependencyBlocks,\n): { pkg: DependencyBlocks; restored: string[] } {\n const pkg: DependencyBlocks = { ...after };\n const restored: string[] = [];\n const previous = new Map<string, string>();\n for (const block of DEPENDENCY_BLOCKS) {\n for (const [name, spec] of Object.entries(before[block] ?? {})) {\n previous.set(name, spec);\n }\n }\n for (const block of DEPENDENCY_BLOCKS) {\n const entries = after[block];\n if (!entries) {\n continue;\n }\n for (const [name, spec] of Object.entries(entries)) {\n const old = previous.get(name);\n if (old === undefined || old === spec) {\n continue;\n }\n const oldFloor = rangeFloor(old);\n const newFloor = rangeFloor(spec);\n const keep =\n oldFloor !== null &&\n newFloor !== null &&\n compareFloors(newFloor, oldFloor) >= 0;\n if (keep) {\n continue;\n }\n pkg[block] = { ...(pkg[block] as Record<string, string>), [name]: old };\n restored.push(`${name}@${old}`);\n }\n }\n return { pkg, restored };\n}\n\nfunction readPackageJson(root: string): Record<string, unknown> | null {\n const file = path.join(root, \"package.json\");\n if (!existsSync(file)) {\n return null;\n }\n return JSON.parse(readFileSync(file, \"utf8\")) as Record<string, unknown>;\n}\n\n/**\n * Packages a project is brought up to, not just given when it has none: what\n * the generated code imports from them did not exist in earlier releases.\n * Any other package is left at whatever version the project has, since a\n * floor in `versions.json` rises every week and a generator should not move\n * a project's dependencies each time it runs.\n */\nconst FLOOR_ENFORCED = new Set<string>([\n // `requireUser` in `@velastack/pocketbase/auth` is new in 0.5.3.\n \"@velastack/pocketbase\",\n]);\n\n/**\n * Whether the project has `spec`'s package at a version below the one the\n * spec starts at, for the packages in `FLOOR_ENFORCED`. The version is the\n * installed one when there is a `node_modules`, since a range such as\n * `^0.5.1` says nothing about which release the lockfile holds; without one,\n * the floor of the range in `package.json`.\n */\nfunction isBelowFloor(root: string, spec: string): boolean {\n const name = packageName(spec);\n if (!FLOOR_ENFORCED.has(name)) return false;\n const wanted = rangeFloor(spec.slice(name.length + 1));\n if (!wanted) return false;\n\n let have: number[] | null = null;\n const installedManifest = path.join(\n root,\n \"node_modules\",\n ...name.split(\"/\"),\n \"package.json\",\n );\n if (existsSync(installedManifest)) {\n try {\n const { version } = JSON.parse(readFileSync(installedManifest, \"utf8\"));\n have = typeof version === \"string\" ? rangeFloor(version) : null;\n } catch {\n have = null;\n }\n } else {\n const manifest = JSON.parse(\n readFileSync(path.join(root, \"package.json\"), \"utf8\"),\n ) as Record<string, Record<string, string> | undefined>;\n const range = [\n \"dependencies\",\n \"devDependencies\",\n \"optionalDependencies\",\n \"peerDependencies\",\n ]\n .map((block) => manifest[block]?.[name])\n .find((value) => typeof value === \"string\");\n have = range ? rangeFloor(range) : null;\n }\n // Something that is not a plain version (a workspace or git dependency) is\n // the project's own business.\n return have !== null && compareFloors(have, wanted) < 0;\n}\n\nasync function installPackages(\n root: string,\n packages: string[],\n runtime?: WriteResultRuntime,\n logger: Logger = NOOP_LOGGER,\n): Promise<string[]> {\n if (packages.length === 0) {\n return [];\n }\n\n const installed = installedPackagesFromProject(root);\n const toInstall = [...new Set(packages)].filter(\n (pkg) => !installed.has(packageName(pkg)) || isBelowFloor(root, pkg),\n );\n if (toInstall.length === 0) {\n return [];\n }\n\n reconcileFormsnap(root, installed, toInstall, logger);\n\n logger.info(`Installing packages: ${toInstall.join(\", \")}`);\n // `--save-exact` applies to a whole command, so exact pins go in their own.\n const exact = toInstall.filter(isExactSpec);\n const ranged = toInstall.filter((spec) => !isExactSpec(spec));\n if (exact.length > 0) {\n await executeCommand(root, \"install\", exact, runtime, { exact: true });\n }\n if (ranged.length > 0) {\n await executeCommand(root, \"install\", ranged, runtime);\n }\n return toInstall;\n}\n\n/**\n * `npm uninstall` for the listed packages that `package.json` records. The\n * inverse of `installPackages`: names not present are skipped, so a disable\n * pattern can name everything its enable counterpart installed.\n */\nasync function uninstallPackages(\n root: string,\n packages: string[],\n runtime?: WriteResultRuntime,\n logger: Logger = NOOP_LOGGER,\n): Promise<string[]> {\n if (packages.length === 0) {\n return [];\n }\n\n const installed = installedPackagesFromProject(root);\n const toRemove = [...new Set(packages.map(packageName))].filter((pkg) =>\n installed.has(pkg),\n );\n if (toRemove.length === 0) {\n return [];\n }\n\n logger.info(`Removing packages: ${toRemove.join(\", \")}`);\n await executeCommand(root, \"uninstall\", toRemove, runtime);\n return toRemove;\n}\n\nexport function isCustomComponent(component: string): boolean {\n return getAllCustomComponents().includes(component);\n}\n\nfunction customNpmPackagesFor(components: string[]): string[] {\n return [\n ...new Set(\n components.flatMap((component) => customNpmPackages[component] ?? []),\n ),\n ];\n}\n\nfunction copyCustomComponent(\n component: string,\n targetComponentsDir: string,\n): void {\n const targetDir = path.join(targetComponentsDir, component);\n mkdirSync(targetDir, { recursive: true });\n\n for (const [assetPath, content] of Object.entries(customComponentAssets)) {\n if (componentNameFromAssetPath(assetPath) !== component) {\n continue;\n }\n const relativePath = componentRelativeAssetPath(assetPath);\n if (!relativePath) {\n continue;\n }\n\n const outputPath = path.join(targetDir, relativePath);\n mkdirSync(path.dirname(outputPath), { recursive: true });\n writeFileSync(outputPath, content, \"utf8\");\n }\n}\n\nconst FORMATTABLE_EXTENSIONS = new Set([\n \".ts\",\n \".js\",\n \".svelte\",\n \".json\",\n \".css\",\n]);\n\nfunction* filesUnder(target: string): Generator<string> {\n if (!existsSync(target)) {\n return;\n }\n if (statSync(target).isFile()) {\n yield target;\n return;\n }\n const entries = readdirSync(target, { recursive: true, withFileTypes: true });\n for (const entry of entries) {\n if (entry.isFile()) {\n yield path.join(entry.parentPath, entry.name);\n }\n }\n}\n\n/**\n * `shadcn-svelte add` and `apply` write files in the registry's style and the\n * bundled components carry this repo's; the project's `npm run lint` expects\n * its own. Runs the project's prettier over the given files and directories\n * (relative to the root or absolute) and returns the relative paths it\n * changed. Paths that do not exist are skipped.\n */\nexport async function formatPaths(\n root: string,\n paths: string[],\n): Promise<string[]> {\n const context = { env: \"runtime\" as const, root };\n const changed: string[] = [];\n for (const target of paths) {\n for (const filePath of filesUnder(toTargetPath(root, target))) {\n if (!FORMATTABLE_EXTENSIONS.has(path.extname(filePath))) {\n continue;\n }\n const content = readFileSync(filePath, \"utf8\");\n const formatted = await formatSource(content, filePath, context);\n if (formatted !== content) {\n writeFileSync(filePath, formatted, \"utf8\");\n changed.push(path.relative(root, filePath));\n }\n }\n }\n return changed;\n}\n\n/**\n * A digest of every file under the given directories. Content, not mtime: a\n * file rewritten within the filesystem's timestamp tick keeps its mtime.\n */\nfunction fileDigests(dirs: string[]): Map<string, string> {\n const digests = new Map<string, string>();\n for (const dir of dirs) {\n for (const filePath of filesUnder(dir)) {\n digests.set(\n filePath,\n createHash(\"sha1\").update(readFileSync(filePath)).digest(\"hex\"),\n );\n }\n }\n return digests;\n}\n\n/** The files under the directories that are new or changed since `before`. */\nfunction filesWrittenSince(\n before: Map<string, string>,\n dirs: string[],\n): string[] {\n return [...fileDigests(dirs)]\n .filter(([filePath, digest]) => before.get(filePath) !== digest)\n .map(([filePath]) => filePath);\n}\n\n/** The component directories a project has, sorted. */\nexport function installedComponents(root: string): Component[] {\n const uiDir = resolveUiDir(root);\n if (!existsSync(uiDir)) {\n return [];\n }\n return readdirSync(uiDir, { withFileTypes: true })\n .filter((entry) => entry.isDirectory())\n .map((entry) => entry.name)\n .sort();\n}\n\n/** Bare item names are checked against the index; URLs and `@scope/item` are shadcn's to resolve. */\nconst BARE_ITEM_NAME = /^[a-z0-9][a-z0-9-]*$/i;\n\n/**\n * How long an unreachable registry is left alone. One command checks the\n * names up to three times (a pattern's preflight, `writeResult`,\n * `installComponents`); offline, only the first should wait out the timeout\n * and say so. Short, so a long-lived caller asks again once it may be online.\n */\nconst REGISTRY_RETRY_MS = 30_000;\n\nconst registryUnavailableAt = new WeakMap<typeof fetch, Map<string, number>>();\n\n/**\n * A name the style's registry does not list would otherwise reach\n * `shadcn-svelte add`, which fails after a fetch with a message that never\n * mentions the style. Skipped when the registry cannot be read: shadcn will\n * report that itself.\n */\nasync function assertKnownRegistryItems(\n root: string,\n components: Component[],\n runtime: WriteResultRuntime | undefined,\n logger: Logger,\n): Promise<void> {\n const bare = components.filter((component) => BARE_ITEM_NAME.test(component));\n if (bare.length === 0) {\n return;\n }\n const config = readComponentsConfig(root);\n const url = registryIndexUrl(config.registry, config.style);\n const fetchImpl = runtime?.fetch ?? globalThis.fetch;\n const failedAt = registryUnavailableAt.get(fetchImpl)?.get(url);\n if (failedAt !== undefined && Date.now() - failedAt < REGISTRY_RETRY_MS) {\n return;\n }\n let known: Set<string>;\n try {\n const index = await fetchRegistryIndex(root, { runtime });\n known = new Set(index.map((item) => item.name));\n } catch (error) {\n if (!(error instanceof RegistryUnavailableError)) throw error;\n logger.info(`${error.message}; leaving component names to shadcn-svelte`);\n let failures = registryUnavailableAt.get(fetchImpl);\n if (!failures) {\n failures = new Map();\n registryUnavailableAt.set(fetchImpl, failures);\n }\n failures.set(url, Date.now());\n return;\n }\n const unknown = bare.filter((component) => !known.has(component));\n if (unknown.length === 0) {\n return;\n }\n const names = unknown.map((component) => `\"${component}\"`).join(\", \");\n throw new InvalidArgumentError(\n `Unknown component${unknown.length > 1 ? \"s\" : \"\"} ${names} for style ${config.style}. Run \\`vela ui list\\` to see what is available.`,\n );\n}\n\n/** What one `installComponents` call will do, worked out without touching the project. */\ninterface ComponentPlan {\n /** Requested but already in the project, and so left alone. */\n skipped: Component[];\n /** Copied from this package: the requested ones and the bundled components they build on, sorted. */\n custom: Component[];\n /** Handed to `shadcn-svelte add`: the requested ones and what the bundled components import, sorted. */\n registry: Component[];\n}\n\nfunction planComponentInstall(\n root: string,\n components: Component[],\n overwrite: boolean,\n): ComponentPlan {\n const requested = [...new Set(components)];\n if (requested.length === 0) {\n return { skipped: [], custom: [], registry: [] };\n }\n\n // `shadcn-svelte add` exits 1 without a `components.json`, after the custom\n // components and their packages are already in. Checked first, so a project\n // without shadcn-svelte is refused whole rather than left half-written.\n if (!existsSync(path.join(root, \"components.json\"))) {\n throw new MissingShadcnError(\n `Adding ${requested.length > 1 ? \"components\" : \"a component\"} (${requested.join(\", \")})`,\n );\n }\n\n const componentsDir = resolveUiDir(root);\n const isPresent = (component: string) =>\n existsSync(path.join(componentsDir, component));\n\n const skipped = overwrite ? [] : requested.filter(isPresent);\n const toInstall = requested.filter(\n (component) => !skipped.includes(component),\n );\n\n const customToInstall = new Set(toInstall.filter(isCustomComponent));\n const publicToInstall = new Set(\n toInstall.filter((component) => !isCustomComponent(component)),\n );\n\n // Dependencies are added only when missing, even under `overwrite`:\n // re-adding `button` because `pagination` was re-added would clobber edits\n // the user never asked to lose.\n for (const component of [...customToInstall]) {\n for (const dependency of customDependencies[component] ?? []) {\n if (isPresent(dependency)) {\n continue;\n }\n if (isCustomComponent(dependency)) {\n customToInstall.add(dependency);\n } else {\n publicToInstall.add(dependency);\n }\n }\n }\n\n return {\n skipped,\n custom: [...customToInstall].sort(),\n registry: [...publicToInstall].sort(),\n };\n}\n\n/**\n * Every reason an install would be refused, checked before it writes\n * anything: copying a bundled component, installing its packages and\n * spawning `shadcn-svelte add` all come after.\n */\nasync function assertPlanInstallable(\n root: string,\n plan: ComponentPlan,\n runtime: WriteResultRuntime | undefined,\n logger: Logger,\n): Promise<void> {\n // `installPackages` keeps an existing @tanstack/table-core whatever its range.\n assertTableCorePackage(root, plan.custom);\n if (plan.custom.includes(\"data-table-pagination\")) {\n assertRegistryPagination(root);\n }\n await assertKnownRegistryItems(root, plan.registry, runtime, logger);\n}\n\nexport interface AssertComponentsAvailableOptions {\n /** As for `installComponents`: also check the named components that are already present. */\n overwrite?: boolean;\n logger?: Logger;\n}\n\n/**\n * The preflight for `installComponents`: throws what it would throw for\n * these components, and changes nothing. `MissingShadcnError` without a\n * `components.json`, `InvalidArgumentError` for a name the style's registry\n * does not list (or a project whose table helpers are a major behind).\n * Components already in the project are not checked, as they are not\n * installed.\n *\n * For a caller with side effects of its own ahead of the install. A pattern\n * creates its collections first, and PocketBase writes each one's migration\n * file as it does, so a component the registry has dropped used to leave a\n * migration (and the bundled components, and their packages) behind a run\n * that then failed. `writeResult` and `installComponents` run the same\n * checks before their first write.\n *\n * A registry that cannot be read (offline, a timeout, an HTTP error) does not\n * fail the preflight: the names go unchecked, a line is logged, and\n * `shadcn-svelte add` reports the problem if it is still there at install\n * time, as it did before there was a preflight. The failure is remembered for\n * 30 seconds so the later checks of the same run neither wait nor repeat it.\n */\nexport async function assertComponentsAvailable(\n root: string,\n components: Component[],\n options: AssertComponentsAvailableOptions = {},\n runtime?: WriteResultRuntime,\n): Promise<void> {\n const plan = planComponentInstall(\n root,\n components,\n options.overwrite ?? false,\n );\n await assertPlanInstallable(root, plan, runtime, getLogger(options));\n}\n\nexport async function installComponents(\n options: InstallComponentsOptions,\n runtime?: WriteResultRuntime,\n): Promise<InstallComponentsResult> {\n const { root, components, overwrite = false } = options;\n const logger = getLogger(options);\n const plan = planComponentInstall(root, components, overwrite);\n await assertPlanInstallable(root, plan, runtime, logger);\n return applyComponentPlan(root, plan, runtime, logger);\n}\n\n/** Carries out a plan `assertPlanInstallable` has passed. */\nasync function applyComponentPlan(\n root: string,\n plan: ComponentPlan,\n runtime: WriteResultRuntime | undefined,\n logger: Logger,\n): Promise<InstallComponentsResult> {\n const { skipped, custom: customList, registry: publicList } = plan;\n if (skipped.length > 0) {\n logger.info(`Already present: ${skipped.join(\", \")}`);\n }\n if (customList.length === 0 && publicList.length === 0) {\n return { installed: [], skipped, packages: [] };\n }\n\n const componentsDir = resolveUiDir(root);\n mkdirSync(componentsDir, { recursive: true });\n\n const installed: string[] = [];\n let packages: string[] = [];\n const shadcnDirs = [path.join(root, \"src\", \"lib\"), componentsDir];\n let beforeShadcn: Map<string, string> | undefined;\n\n // The bundled components carry this repo's style and shadcn-svelte's files\n // the registry's. Whatever reached the project is formatted, whether or not\n // the install got to its end: a package install or `shadcn-svelte add` that\n // fails after the components were copied used to leave them as they came,\n // for the project's `prettier --check` to trip over.\n const formatWritten = () =>\n formatPaths(root, [\n ...new Set([\n ...installed.map((component) => path.join(componentsDir, component)),\n ...(beforeShadcn ? filesWrittenSince(beforeShadcn, shadcnDirs) : []),\n ]),\n ]);\n\n try {\n if (customList.length > 0) {\n logger.info(`Installing custom components: ${customList.join(\", \")}`);\n }\n for (const component of customList) {\n copyCustomComponent(component, componentsDir);\n installed.push(component);\n }\n\n packages = await installPackages(\n root,\n customNpmPackagesFor(customList),\n runtime,\n logger,\n );\n\n // `shadcn-svelte add` writes more than the items it is given: each one's\n // registry dependencies too (`command` brings `dialog` and `input-group`),\n // over a copy the project already has, and hooks and utils beside the\n // components. All of it arrives in the registry's style.\n beforeShadcn = publicList.length > 0 ? fileDigests(shadcnDirs) : undefined;\n\n if (publicList.length > 0) {\n logger.info(\n `Installing shadcn-svelte components: ${publicList.join(\", \")}`,\n );\n // shadcn-svelte reads the tsconfig, whose `extends` an install may have pruned.\n await ensureSvelteKitSync(root, runtime, logger);\n // shadcn only records its packages; they are installed below, once any\n // pin it moved backwards is put back.\n const before = readPackageJson(root);\n await executeCommand(\n root,\n \"execute\",\n [\n \"shadcn-svelte\",\n \"add\",\n \"--yes\",\n \"--overwrite\",\n \"--no-deps-install\",\n ...publicList,\n ],\n runtime,\n );\n installed.push(...publicList);\n const after = readPackageJson(root);\n if (before && after && JSON.stringify(before) !== JSON.stringify(after)) {\n const { pkg, restored } = restoreDowngradedDependencies(\n before as DependencyBlocks,\n after as DependencyBlocks,\n );\n if (restored.length > 0) {\n logger.info(\n `Kept ${restored.join(\", \")} (shadcn-svelte asked for an older range)`,\n );\n const file = path.join(root, \"package.json\");\n const indent =\n readFileSync(file, \"utf8\").match(/^[{]\\s*\\n([\\t ]+)/)?.[1] ?? \"\\t\";\n writeFileSync(file, `${JSON.stringify(pkg, null, indent)}\\n`, \"utf8\");\n }\n const recorded = (pkg: Record<string, unknown>) =>\n new Set(\n DEPENDENCY_BLOCKS.flatMap((block) =>\n Object.keys((pkg[block] as Record<string, string>) ?? {}),\n ),\n );\n const had = recorded(before);\n const added = [...recorded(after)].filter((name) => !had.has(name));\n reconcileFormsnap(root, had, added, logger);\n await executeCommand(root, \"install\", [], runtime);\n }\n }\n } catch (error) {\n // The install's error is the one to report.\n await formatWritten().catch(() => {});\n throw error;\n }\n await formatWritten();\n\n const installedList = [...new Set(installed)].sort();\n return { installed: installedList, skipped, packages };\n}\n\nexport async function writeResult(\n result: Result,\n options: Options,\n runtime?: WriteResultRuntime,\n): Promise<Result> {\n const logger = getLogger(options);\n\n const writtenResult: Result = {\n creates: [],\n modifies: [],\n deletes: [],\n components: [],\n packages: [],\n collections: [],\n collectionPatches: [],\n collectionDrops: [],\n };\n\n // Before anything is dropped, written or installed: a component that\n // cannot be installed refuses the whole result.\n const componentPlan = planComponentInstall(\n options.root,\n result.components,\n false,\n );\n await assertPlanInstallable(options.root, componentPlan, runtime, logger);\n\n let dropMigrationCreates: Result[\"creates\"] = [];\n if (result.collectionDrops.length > 0) {\n const { dropCollections } = await import(\"./collections\");\n // PocketBase writes these while the collections drop, after the result\n // was formatted, so they still carry its own style.\n dropMigrationCreates = await Promise.all(\n (await dropCollections(result.collectionDrops, options)).map(\n async (file) => ({\n ...file,\n content: await formatSource(file.content, file.path, options, {\n created: true,\n }),\n }),\n ),\n );\n }\n\n // A package.json edit lands before the package manager runs, so the install\n // builds on it. Written after, its content (read before the install) would\n // take back every dependency the install just recorded.\n const packageJsonPath = path.resolve(options.root, \"package.json\");\n const isPackageJson = (file: Result[\"modifies\"][number]) =>\n file.status === \"success\" &&\n path.resolve(toTargetPath(options.root, file.path)) === packageJsonPath;\n for (const file of result.modifies.filter(isPackageJson)) {\n writeFile(packageJsonPath, file.content);\n }\n\n const packageInstalls = await installPackages(\n options.root,\n result.packages,\n runtime,\n logger,\n );\n\n const componentInstalls = await applyComponentPlan(\n options.root,\n componentPlan,\n runtime,\n logger,\n );\n\n const packageUninstalls = await uninstallPackages(\n options.root,\n result.uninstalls ?? [],\n runtime,\n logger,\n );\n\n for (const file of [...result.creates, ...dropMigrationCreates]) {\n if (file.status !== \"success\") {\n // A modifier that could not recognise the file it was asked to edit\n // reports `failed` / `not-found` with a paste-ready remediation snippet.\n // Nothing is written, but the entry has to survive into the result: this\n // loop used to `continue` before pushing, so the entry never reached the\n // caller at all and the snippet was lost. The pattern reported success\n // and simply said nothing about the file it had given up on.\n writtenResult.creates.push({\n ...file,\n path: toRelativePath(options.root, file.path),\n });\n continue;\n }\n const target = toTargetPath(options.root, file.path);\n if (!existsSync(target)) {\n writeFile(target, file.content);\n writtenResult.creates.push({\n ...file,\n path: toRelativePath(options.root, file.path),\n });\n continue;\n }\n // A `written` file is the run's own (a migration PocketBase wrote and\n // `readMigration` formatted), reported even when there is nothing left\n // to write: the CLI lists a new migration from this entry.\n const changed = readFileSync(target, \"utf8\") !== file.content;\n if (changed) {\n writeFile(target, file.content);\n }\n if (changed || file.written) {\n // The marker is this module's and `readMigration`'s; callers get the\n // entry in the shape it always had.\n const { written: _written, ...reported } = file;\n writtenResult.modifies.push({\n ...reported,\n path: toRelativePath(options.root, file.path),\n });\n }\n }\n\n for (const file of result.modifies) {\n if (isPackageJson(file)) {\n writtenResult.modifies.push({\n ...file,\n path: toRelativePath(options.root, file.path),\n });\n continue;\n }\n if (file.status !== \"success\") {\n // Carried through unwritten, so the caller can report the failure. See\n // the note in the creates loop above.\n writtenResult.modifies.push({\n ...file,\n path: toRelativePath(options.root, file.path),\n });\n continue;\n }\n writeFile(toTargetPath(options.root, file.path), file.content);\n writtenResult.modifies.push({\n ...file,\n path: toRelativePath(options.root, file.path),\n });\n }\n\n for (const file of result.deletes) {\n if (file.status !== \"success\") {\n writtenResult.deletes.push({\n ...file,\n path: toRelativePath(options.root, file.path),\n });\n continue;\n }\n if (existsSync(toTargetPath(options.root, file.path))) {\n removeFile(toTargetPath(options.root, file.path), options.root);\n writtenResult.deletes.push({\n ...file,\n path: toRelativePath(options.root, file.path),\n });\n }\n }\n\n return {\n ...result,\n creates: writtenResult.creates,\n modifies: writtenResult.modifies,\n deletes: writtenResult.deletes,\n components: componentInstalls.installed,\n packages: [...new Set([...packageInstalls, ...componentInstalls.packages])],\n ...(packageUninstalls.length > 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