@velastack/patterns 0.15.1 → 0.15.2
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-Cg7LjaOE.js → _page-BFUn0CG1.js} +2 -2
- package/dist/chunks/{_page-Cg7LjaOE.js.map → _page-BFUn0CG1.js.map} +1 -1
- package/dist/chunks/{auth-pages-DSBqKjO0.js → auth-pages-D8n8gfCL.js} +2 -2
- package/dist/chunks/{auth-pages-DSBqKjO0.js.map → auth-pages-D8n8gfCL.js.map} +1 -1
- package/dist/chunks/{collections-D2_2cxWD.js → collections-Daxlnbm0.js} +2 -2
- package/dist/chunks/{collections-D2_2cxWD.js.map → collections-Daxlnbm0.js.map} +1 -1
- package/dist/chunks/{constants-DbpctM1D.js → constants-E1I-__KI.js} +18 -18
- package/dist/chunks/{constants-DbpctM1D.js.map → constants-E1I-__KI.js.map} +1 -1
- package/dist/chunks/{currency.server-CFrwmYra.js → currency.server-BkzwY17R.js} +2 -2
- package/dist/chunks/{currency.server-CFrwmYra.js.map → currency.server-BkzwY17R.js.map} +1 -1
- package/dist/chunks/{env-vars-Dm3Xy4rl.js → env-vars-C3TSZc4f.js} +3 -3
- package/dist/chunks/{env-vars-Dm3Xy4rl.js.map → env-vars-C3TSZc4f.js.map} +1 -1
- package/dist/chunks/{generate-BMWoD9E2.js → generate-CAYM7OUF.js} +2 -2
- package/dist/chunks/{generate-BMWoD9E2.js.map → generate-CAYM7OUF.js.map} +1 -1
- package/dist/chunks/{generate-DZ9kT3iC.js → generate-CL7wG0ZC.js} +3 -3
- package/dist/chunks/{generate-DZ9kT3iC.js.map → generate-CL7wG0ZC.js.map} +1 -1
- package/dist/chunks/{generate-BRTIGlqT.js → generate-CbchamhA.js} +3 -3
- package/dist/chunks/{generate-BRTIGlqT.js.map → generate-CbchamhA.js.map} +1 -1
- package/dist/chunks/{generate-Cs_fdfD7.js → generate-DI58vuk1.js} +2 -2
- package/dist/chunks/{generate-Cs_fdfD7.js.map → generate-DI58vuk1.js.map} +1 -1
- package/dist/chunks/{generate-BvQ6VwYH.js → generate-DR2wkVPY.js} +2 -2
- package/dist/chunks/{generate-BvQ6VwYH.js.map → generate-DR2wkVPY.js.map} +1 -1
- package/dist/chunks/{generate.runtime-1eTnPFmA.js → generate.runtime-B11mOr45.js} +2 -2
- package/dist/chunks/{generate.runtime-1eTnPFmA.js.map → generate.runtime-B11mOr45.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CjLath7N.js → generate.runtime-B1Y2JrGW.js} +5 -5
- package/dist/chunks/{generate.runtime-CjLath7N.js.map → generate.runtime-B1Y2JrGW.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CnNtG_x5.js → generate.runtime-B7VubPTW.js} +3 -3
- package/dist/chunks/{generate.runtime-CnNtG_x5.js.map → generate.runtime-B7VubPTW.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BvHK8IN-.js → generate.runtime-BCv4F1Wm.js} +5 -5
- package/dist/chunks/{generate.runtime-BvHK8IN-.js.map → generate.runtime-BCv4F1Wm.js.map} +1 -1
- package/dist/chunks/{generate.runtime-D8G8cwCr.js → generate.runtime-BEWp57Y7.js} +2 -2
- package/dist/chunks/{generate.runtime-D8G8cwCr.js.map → generate.runtime-BEWp57Y7.js.map} +1 -1
- package/dist/chunks/{generate.runtime-B4mQEW54.js → generate.runtime-BH6hHygm.js} +3 -3
- package/dist/chunks/{generate.runtime-B4mQEW54.js.map → generate.runtime-BH6hHygm.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CfCDLJ6Y.js → generate.runtime-BL6DpWFI.js} +3 -3
- package/dist/chunks/{generate.runtime-CfCDLJ6Y.js.map → generate.runtime-BL6DpWFI.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BJwSyslL.js → generate.runtime-BRV9hIl5.js} +2 -2
- package/dist/chunks/{generate.runtime-BJwSyslL.js.map → generate.runtime-BRV9hIl5.js.map} +1 -1
- package/dist/chunks/{generate.runtime-B9nVU5iO.js → generate.runtime-BRcP6sFt.js} +2 -2
- package/dist/chunks/{generate.runtime-B9nVU5iO.js.map → generate.runtime-BRcP6sFt.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BC1GJUXE.js → generate.runtime-Bhs7ttZS.js} +2 -2
- package/dist/chunks/{generate.runtime-BC1GJUXE.js.map → generate.runtime-Bhs7ttZS.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Bda2_WK7.js → generate.runtime-BjrtdoYE.js} +2 -2
- package/dist/chunks/{generate.runtime-Bda2_WK7.js.map → generate.runtime-BjrtdoYE.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DBQvnQmR.js → generate.runtime-Bo_s7gYB.js} +2 -2
- package/dist/chunks/{generate.runtime-DBQvnQmR.js.map → generate.runtime-Bo_s7gYB.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DQUZRJH8.js → generate.runtime-Bs77Oc8P.js} +3 -3
- package/dist/chunks/{generate.runtime-DQUZRJH8.js.map → generate.runtime-Bs77Oc8P.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Cd742Yqf.js → generate.runtime-C3IswX7B.js} +2 -2
- package/dist/chunks/{generate.runtime-Cd742Yqf.js.map → generate.runtime-C3IswX7B.js.map} +1 -1
- package/dist/chunks/{generate.runtime-B-H2F-sH.js → generate.runtime-C90_2L-8.js} +3 -3
- package/dist/chunks/{generate.runtime-B-H2F-sH.js.map → generate.runtime-C90_2L-8.js.map} +1 -1
- package/dist/chunks/{generate.runtime-B4rG6gSK.js → generate.runtime-CDY0Ot_t.js} +6 -6
- package/dist/chunks/{generate.runtime-B4rG6gSK.js.map → generate.runtime-CDY0Ot_t.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Doumu0TL.js → generate.runtime-CZMVPVjS.js} +6 -6
- package/dist/chunks/{generate.runtime-Doumu0TL.js.map → generate.runtime-CZMVPVjS.js.map} +1 -1
- package/dist/chunks/{generate.runtime-liAz2TOE.js → generate.runtime-C_hrLPD4.js} +3 -3
- package/dist/chunks/{generate.runtime-liAz2TOE.js.map → generate.runtime-C_hrLPD4.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DE-vPcn4.js → generate.runtime-CdZ3GzPS.js} +6 -6
- package/dist/chunks/{generate.runtime-DE-vPcn4.js.map → generate.runtime-CdZ3GzPS.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BkQPchHe.js → generate.runtime-ChSVP7cD.js} +6 -6
- package/dist/chunks/{generate.runtime-BkQPchHe.js.map → generate.runtime-ChSVP7cD.js.map} +1 -1
- package/dist/chunks/{generate.runtime-C1HlZnLC.js → generate.runtime-Cs73i6Zf.js} +2 -2
- package/dist/chunks/{generate.runtime-C1HlZnLC.js.map → generate.runtime-Cs73i6Zf.js.map} +1 -1
- package/dist/chunks/{generate.runtime-GmsldrGj.js → generate.runtime-D7KYlnvb.js} +3 -3
- package/dist/chunks/{generate.runtime-GmsldrGj.js.map → generate.runtime-D7KYlnvb.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DFSsgOmB.js → generate.runtime-DG9LRwbt.js} +3 -3
- package/dist/chunks/{generate.runtime-DFSsgOmB.js.map → generate.runtime-DG9LRwbt.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CIOi-XSm.js → generate.runtime-DKL7VAAd.js} +6 -6
- package/dist/chunks/{generate.runtime-CIOi-XSm.js.map → generate.runtime-DKL7VAAd.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CQ_U4YTJ.js → generate.runtime-DP63Wwea.js} +4 -4
- package/dist/chunks/{generate.runtime-CQ_U4YTJ.js.map → generate.runtime-DP63Wwea.js.map} +1 -1
- package/dist/chunks/{generate.runtime-C62ChKGg.js → generate.runtime-DRPxOLnB.js} +4 -4
- package/dist/chunks/{generate.runtime-C62ChKGg.js.map → generate.runtime-DRPxOLnB.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DQI69jkX.js → generate.runtime-DW9bqOtC.js} +2 -2
- package/dist/chunks/{generate.runtime-DQI69jkX.js.map → generate.runtime-DW9bqOtC.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Dtum580c.js → generate.runtime-DdY44Ulv.js} +6 -6
- package/dist/chunks/{generate.runtime-Dtum580c.js.map → generate.runtime-DdY44Ulv.js.map} +1 -1
- package/dist/chunks/{generate.runtime-ufoTIUXA.js → generate.runtime-DjEj-n6m.js} +7 -7
- package/dist/chunks/{generate.runtime-ufoTIUXA.js.map → generate.runtime-DjEj-n6m.js.map} +1 -1
- package/dist/chunks/{generate.runtime-rxzMCECc.js → generate.runtime-DlAJQ5Js.js} +4 -4
- package/dist/chunks/{generate.runtime-rxzMCECc.js.map → generate.runtime-DlAJQ5Js.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CZA46Ghe.js → generate.runtime-JftBoKYS.js} +5 -5
- package/dist/chunks/{generate.runtime-CZA46Ghe.js.map → generate.runtime-JftBoKYS.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DNjyaFml.js → generate.runtime-_426A1Ij.js} +3 -3
- package/dist/chunks/{generate.runtime-DNjyaFml.js.map → generate.runtime-_426A1Ij.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DR8z6DyZ.js → generate.runtime-fs6GEMx-.js} +5 -5
- package/dist/chunks/{generate.runtime-DR8z6DyZ.js.map → generate.runtime-fs6GEMx-.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Diix70x4.js → generate.runtime-jIlQ2GMh.js} +2 -2
- package/dist/chunks/{generate.runtime-Diix70x4.js.map → generate.runtime-jIlQ2GMh.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BuQASx9Y.js → generate.runtime-v3KCv1B6.js} +2 -2
- package/dist/chunks/{generate.runtime-BuQASx9Y.js.map → generate.runtime-v3KCv1B6.js.map} +1 -1
- package/dist/chunks/{generate.runtime-lP4eoera.js → generate.runtime-xrxAElb3.js} +3 -3
- package/dist/chunks/{generate.runtime-lP4eoera.js.map → generate.runtime-xrxAElb3.js.map} +1 -1
- package/dist/chunks/{gitignore-2XpeEFmr.js → gitignore-CBiWFRif.js} +3 -3
- package/dist/chunks/{gitignore-2XpeEFmr.js.map → gitignore-CBiWFRif.js.map} +1 -1
- package/dist/chunks/{i18n-CxT1kz8Y.js → i18n-Ho8H91Ze.js} +2 -2
- package/dist/chunks/{i18n-CxT1kz8Y.js.map → i18n-Ho8H91Ze.js.map} +1 -1
- package/dist/chunks/{modify-file-BX9-aZD1.js → modify-file-BOEKlIDw.js} +2 -2
- package/dist/chunks/{modify-file-BX9-aZD1.js.map → modify-file-BOEKlIDw.js.map} +1 -1
- package/dist/chunks/{pocketbase-Dq9UdK_j.js → pocketbase-B2ksFrvH.js} +2 -2
- package/dist/chunks/{pocketbase-Dq9UdK_j.js.map → pocketbase-B2ksFrvH.js.map} +1 -1
- package/dist/chunks/{providers-2UgxXRJW.js → providers-BEjDonyG.js} +2 -2
- package/dist/chunks/{providers-2UgxXRJW.js.map → providers-BEjDonyG.js.map} +1 -1
- package/dist/chunks/{route-BDhlro0V.js → route-9ZVJZkYu.js} +23 -19
- package/dist/chunks/route-9ZVJZkYu.js.map +1 -0
- package/dist/chunks/{schema-2frI_BS2.js → schema-DnMqw2Hn.js} +3 -3
- package/dist/chunks/{schema-2frI_BS2.js.map → schema-DnMqw2Hn.js.map} +1 -1
- package/dist/chunks/{shared-BOFCKWJs.js → shared-CSwGWMcN.js} +2 -2
- package/dist/chunks/{shared-BOFCKWJs.js.map → shared-CSwGWMcN.js.map} +1 -1
- package/dist/chunks/{shared-DJ4KvhTb.js → shared-Cdwm_-Nl.js} +40 -40
- package/dist/chunks/{shared-DJ4KvhTb.js.map → shared-Cdwm_-Nl.js.map} +1 -1
- package/dist/chunks/{site-qASrdyUt.js → site-B5zrFba9.js} +2 -2
- package/dist/chunks/{site-qASrdyUt.js.map → site-B5zrFba9.js.map} +1 -1
- package/dist/chunks/{table-core-s2xjYgRD.js → table-core-ux1xEJxN.js} +2 -2
- package/dist/chunks/{table-core-s2xjYgRD.js.map → table-core-ux1xEJxN.js.map} +1 -1
- package/dist/chunks/{ui-DZuwcswv.js → ui-CpjUq_lm.js} +3 -3
- package/dist/chunks/{ui-DZuwcswv.js.map → ui-CpjUq_lm.js.map} +1 -1
- package/dist/chunks/{whatsapp-BytvTPlS.js → whatsapp-DOSZ_zwn.js} +2 -2
- package/dist/chunks/{whatsapp-BytvTPlS.js.map → whatsapp-DOSZ_zwn.js.map} +1 -1
- package/dist/chunks/{write-result-BhfLWAXf.js → write-result-DlB-id5k.js} +50 -26
- package/dist/chunks/write-result-DlB-id5k.js.map +1 -0
- package/dist/index.js +1863 -1841
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunks/route-BDhlro0V.js.map +0 -1
- package/dist/chunks/write-result-BhfLWAXf.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"site-qASrdyUt.js","names":["getLogger","languageFromPath","withPocketbase","fs","path","sitePath","root","BUSINESS_KEYS","siteModule","declared","business","lines","key","propertyLines","properties","quote","name","url","entry","i","ensureComma","value","SUPPORTED_CURRENCIES","normalizeCurrency","raw","code","normalizeCountry","normalizeCurrencies","entries","codes","home","SITE_OBJECT","withSiteProperty","match","source","body","siteBusiness","text","shape","list","currency","country","m","existingName","options","appName","pb","pkg","ensureSiteFile","file","ensureSiteBusiness","wanted","existing","added","next"],"sources":["../../src/runtime/site.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, Options } from \"../core/types\";\nimport { getLogger } from \"../core/logger\";\nimport { languageFromPath } from \"../core/util\";\nimport { withPocketbase } from \"./pocketbase\";\n\n/** Where every VelaStack app keeps its name and public URL. */\nexport function sitePath(root: string): string {\n return path.join(root, \"src\", \"lib\", \"site.ts\");\n}\n\n/**\n * What a business declares about itself in `src/lib/site.ts`, next to the\n * app's name: the currency it prices in and is paid in, the country it is in\n * (prices format for it: `es-MX`, not `es`) and the other currencies it shows\n * prices in, as estimates. Every property is optional; a payments provider\n * asks for what it needs.\n */\nexport interface SiteBusiness {\n /** ISO 4217, e.g. `MXN`. */\n currency?: string;\n /** ISO 3166-1 alpha-2, e.g. `MX`. */\n country?: string;\n /** ISO 4217 codes the site also shows prices in; empty means the home currency only. */\n currencies?: string[];\n}\n\ntype BusinessKey = keyof SiteBusiness;\n\nconst BUSINESS_KEYS: BusinessKey[] = [\"currency\", \"country\", \"currencies\"];\n\n/**\n * `src/lib/site.ts` as the CLI templates ship it (`site.template.ts`), with\n * the placeholders filled in, plus whatever the business declares.\n */\nexport function siteModule(\n name: string,\n url = \"http://localhost:5173\",\n business: SiteBusiness | string = {},\n): string {\n // The old third argument was the currency alone.\n const declared: SiteBusiness =\n typeof business === \"string\" ? { currency: business } : business;\n const lines = BUSINESS_KEYS.filter((key) => declared[key] !== undefined).map(\n (key) => propertyLines(key, declared[key]!),\n );\n const properties = [\n `\\tname: ${quote(name)},`,\n `\\turl: ${quote(url)}`,\n ...lines.map((entry) => entry.join(\"\\n\")),\n ];\n return [\n \"/**\",\n \" * Site-wide metadata, and the one place the app's name and public URL live.\",\n \" *\",\n \" * Set `url` to where the site is deployed: canonical links, Open Graph images\",\n \" * and feeds are built from it, including in prerendered pages. With a backend,\",\n \" * `vela dev` and `vela deploy` copy `name` into PocketBase's application name\",\n \" * for the emails it sends, so change it here rather than in the admin panel.\",\n \" */\",\n \"export const site = {\",\n // Every property but the last ends in a comma.\n ...properties.map((entry, i) =>\n i < properties.length - 1 ? ensureComma(entry) : entry,\n ),\n \"};\",\n \"\",\n ].join(\"\\n\");\n}\n\nfunction ensureComma(entry: string): string {\n return entry.endsWith(\",\") ? entry : `${entry},`;\n}\n\n/** A property's lines: its doc comment, then `key: value` with no trailing comma. */\nfunction propertyLines(key: BusinessKey, value: string | string[]): string[] {\n switch (key) {\n case \"currency\":\n return [\n \"\\t/** ISO 4217: the currency the business prices in and is paid in. */\",\n `\\tcurrency: ${quote(value as string)}`,\n ];\n case \"country\":\n return [\n \"\\t/** ISO 3166-1: the country the business is in; prices format for it. */\",\n `\\tcountry: ${quote(value as string)}`,\n ];\n case \"currencies\":\n return [\n \"\\t/** Other currencies prices are shown in, as estimates at the day's rate. */\",\n `\\tcurrencies: [${(value as string[]).map(quote).join(\", \")}]`,\n ];\n }\n}\n\nconst SUPPORTED_CURRENCIES = (\n Intl as unknown as {\n supportedValuesOf: (key: \"currency\") => string[];\n }\n).supportedValuesOf(\"currency\");\n\n/** A three-letter code `Intl` knows, upper-cased; anything else is refused. */\nexport function normalizeCurrency(raw: unknown): string | null {\n if (typeof raw !== \"string\") return null;\n const code = raw.trim().toUpperCase();\n if (!/^[A-Z]{3}$/.test(code)) return null;\n // Any well-formed code formats, so ask for the list of real ones. Node has\n // had it since 18; the repo's ES2020 lib types just don't declare it.\n return SUPPORTED_CURRENCIES.includes(code) ? code : null;\n}\n\n/** A two-letter ISO 3166-1 code, upper-cased; anything else is refused. */\nexport function normalizeCountry(raw: unknown): string | null {\n if (typeof raw !== \"string\") return null;\n const code = raw.trim().toUpperCase();\n if (!/^[A-Z]{2}$/.test(code)) return null;\n // `Intl.DisplayNames` knows every region; an unknown one comes back as is.\n const names = new Intl.DisplayNames([\"en\"], { type: \"region\" });\n return names.of(code) !== code ? code : null;\n}\n\n/**\n * A list of currency codes, from an array or a comma-separated string,\n * upper-cased and deduplicated; `null` when any entry is not a currency.\n * `home` is left out: the business's own currency is never a display one.\n */\nexport function normalizeCurrencies(\n raw: unknown,\n home?: string,\n): string[] | null {\n const entries = Array.isArray(raw)\n ? raw\n : typeof raw === \"string\"\n ? raw.split(/[,\\s]+/)\n : null;\n if (!entries) return null;\n const codes: string[] = [];\n for (const entry of entries) {\n if (entry === \"\" || entry === undefined) continue;\n const code = normalizeCurrency(entry);\n if (!code) return null;\n if (code !== home && !codes.includes(code)) codes.push(code);\n }\n return codes;\n}\n\nconst SITE_OBJECT = /export const site = \\{\\n([\\s\\S]*?)\\n\\};/;\n\n/**\n * `src/lib/site.ts` with `key` added as the object's last property, or\n * `null` when it already has one (a project's declaration is never changed\n * behind its back) or has no `export const site = { ... };` to add it to.\n */\nexport function withSiteProperty(\n source: string,\n key: BusinessKey,\n value: string | string[],\n): string | null {\n const match = SITE_OBJECT.exec(source);\n if (!match || new RegExp(`^\\\\s*${key}\\\\s*:`, \"m\").test(match[1])) return null;\n const body = match[1].replace(/,?\\s*$/, \",\");\n return source.replace(\n match[0],\n `export const site = {\\n${body}\\n${propertyLines(key, value).join(\"\\n\")}\\n};`,\n );\n}\n\n/** `withSiteProperty` for the currency, as the Phase 1.5 code called it. */\nexport function withSiteCurrency(\n source: string,\n currency: string,\n): string | null {\n return withSiteProperty(source, \"currency\", currency);\n}\n\n/** What `src/lib/site.ts` declares about the business, if anything. */\nexport function siteBusiness(root: string): SiteBusiness {\n let source: string;\n try {\n source = fs.readFileSync(sitePath(root), \"utf8\");\n } catch {\n return {};\n }\n const text = (key: string, shape: string) =>\n new RegExp(`^\\\\s*${key}\\\\s*:\\\\s*['\"](${shape})['\"]`, \"m\").exec(source)?.[1];\n const list = /^\\s*currencies\\s*:\\s*\\[([^\\]]*)\\]/m.exec(source)?.[1];\n const business: SiteBusiness = {};\n const currency = text(\"currency\", \"[A-Za-z]{3}\");\n if (currency) business.currency = currency;\n const country = text(\"country\", \"[A-Za-z]{2}\");\n if (country) business.country = country;\n if (list !== undefined) {\n business.currencies = [...list.matchAll(/['\"]([A-Za-z]{3})['\"]/g)].map(\n (m) => m[1],\n );\n }\n return business;\n}\n\n/** The currency `src/lib/site.ts` declares, if any. */\nexport function siteCurrency(root: string): string | null {\n return siteBusiness(root).currency ?? null;\n}\n\n/** Single-quoted, as the templates write their strings. */\nfunction quote(value: string): string {\n return `'${value.replace(/\\\\/g, \"\\\\\\\\\").replace(/'/g, \"\\\\'\")}'`;\n}\n\n/**\n * The name a project created before `site.ts` existed already goes by.\n *\n * Those projects kept it in PocketBase's settings, so that is asked first; the\n * package name is the fallback for a project without a backend, or one whose\n * database can't be reached.\n */\nasync function existingName(options: Options): Promise<string> {\n if (options.features.backend) {\n try {\n let appName: unknown;\n await withPocketbase(options.root, async (pb) => {\n const settings = (await pb.settings.getAll()) as {\n meta?: { appName?: unknown };\n };\n appName = settings.meta?.appName;\n });\n if (typeof appName === \"string\" && appName.trim()) return appName;\n } catch {\n // No database to ask; fall through to package.json.\n }\n }\n\n try {\n const pkg = JSON.parse(\n fs.readFileSync(path.join(options.root, \"package.json\"), \"utf8\"),\n ) as { name?: unknown };\n if (typeof pkg.name === \"string\" && pkg.name.trim()) return pkg.name;\n } catch {\n // No package.json to name the site after; the placeholder stands.\n }\n return \"My App\";\n}\n\n/**\n * Create `src/lib/site.ts` for a pattern whose files import `#lib/site.js`, when\n * the project doesn't have one yet. Every template ships it; projects created\n * before that read the app name from `locals.meta` instead.\n *\n * Returns null when the file exists, so an existing one is never overwritten.\n */\nexport async function ensureSiteFile(options: Options): Promise<File | null> {\n const file = sitePath(options.root);\n if (fs.existsSync(file)) return null;\n\n getLogger(options).info(\"Creating src/lib/site.ts\");\n return {\n path: file,\n language: languageFromPath(file),\n content: siteModule(await existingName(options)),\n status: \"success\",\n };\n}\n\n/**\n * Make `src/lib/site.ts` declare what the business says about itself: create\n * the file with it, or add the properties an existing one lacks. A property\n * already there is kept, whatever `business` says; the result says what the\n * file declares after the call, and the file to write, if anything changed.\n */\nexport async function ensureSiteBusiness(\n options: Options,\n business: SiteBusiness,\n): Promise<{ file: File | null; business: SiteBusiness }> {\n const file = sitePath(options.root);\n const wanted = BUSINESS_KEYS.filter((key) => business[key] !== undefined);\n if (!fs.existsSync(file)) {\n if (wanted.length === 0) return { file: null, business: {} };\n getLogger(options).info(\"Creating src/lib/site.ts\");\n return {\n file: {\n path: file,\n language: languageFromPath(file),\n content: siteModule(await existingName(options), undefined, business),\n status: \"success\",\n },\n business,\n };\n }\n\n const existing = siteBusiness(options.root);\n let source = fs.readFileSync(file, \"utf8\");\n const added: string[] = [];\n for (const key of wanted) {\n if (existing[key] !== undefined) continue;\n const next = withSiteProperty(source, key, business[key]!);\n if (next === null) continue;\n source = next;\n added.push(key);\n (existing as Record<string, unknown>)[key] = business[key];\n }\n if (added.length === 0) return { file: null, business: existing };\n getLogger(options).info(`Adding ${added.join(\", \")} to src/lib/site.ts`);\n return {\n file: {\n path: file,\n language: languageFromPath(file),\n content: source,\n status: \"success\",\n },\n business: existing,\n };\n}\n\n/** `ensureSiteBusiness` for the currency alone, as the Phase 1.5 code called it. */\nexport async function ensureSiteCurrency(\n options: Options,\n currency: string,\n): Promise<{ file: File | null; currency: string }> {\n const { file, business } = await ensureSiteBusiness(options, { currency });\n return { file, currency: business.currency ?? currency };\n}\n"],"mappings":";;;;;;AAQA,SAAgBK,EAAS,GAAsB;CAC7C,OAAOD,EAAK,KAAKE,GAAM,OAAO,OAAO,SAAS;AAChD;AAoBA,IAAMC,IAA+B;CAAC;CAAY;CAAW;AAAY;AAMzE,SAAgBC,EACd,GACA,IAAM,yBACN,IAAkC,CAAC,GAC3B;CAER,IAAMC,IACJ,OAAOC,KAAa,WAAW,EAAE,UAAUA,EAAS,IAAIA,GACpDC,IAAQJ,EAAc,QAAQ,MAAQE,EAASG,OAAS,KAAA,CAAS,CAAC,CAAC,KACtE,MAAQC,EAAcD,GAAKH,EAASG,EAAK,CAC5C,GACME,IAAa;EACjB,WAAWC,EAAMC,CAAI,EAAE;EACvB,UAAUD,EAAME,CAAG;EACnB,GAAGN,EAAM,KAAK,MAAUO,EAAM,KAAK,IAAI,CAAC;CAC1C;CACA,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EAEA,GAAGJ,EAAW,KAAK,GAAO,MACxBK,IAAIL,EAAW,SAAS,IAAIM,EAAYF,CAAK,IAAIA,CACnD;EACA;EACA;CACF,CAAC,CAAC,KAAK,IAAI;AACb;AAEA,SAASE,EAAY,GAAuB;CAC1C,OAAOF,EAAM,SAAS,GAAG,IAAIA,IAAQ,GAAGA,EAAM;AAChD;AAGA,SAASL,EAAc,GAAkB,GAAoC;CAC3E,QAAQD,GAAR;EACE,KAAK,YACH,OAAO,CACL,y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D,AAAI0C,MAAS,SACb,IAASA,GACTD,EAAM,KAAKzC,CAAG,GACd,EAAsCA,KAAOF,EAASE;CACxD;CAGA,OAFIyC,EAAM,WAAW,IAAU;EAAE,MAAM;EAAM,UAAUD;CAAS,KAChEpD,EAAU4C,CAAO,CAAC,CAAC,KAAK,UAAUS,EAAM,KAAK,IAAI,EAAE,oBAAoB,GAChE;EACL,MAAM;GACJ,MAAMJ;GACN,UAAUhD,EAAiBgD,CAAI;GAC/B,SAASf;GACT,QAAQ;EACV;EACA,UAAUkB;CACZ;AACF"}
|
|
1
|
+
{"version":3,"file":"site-B5zrFba9.js","names":["getLogger","languageFromPath","withPocketbase","fs","path","sitePath","root","BUSINESS_KEYS","siteModule","declared","business","lines","key","propertyLines","properties","quote","name","url","entry","i","ensureComma","value","SUPPORTED_CURRENCIES","normalizeCurrency","raw","code","normalizeCountry","normalizeCurrencies","entries","codes","home","SITE_OBJECT","withSiteProperty","match","source","body","siteBusiness","text","shape","list","currency","country","m","existingName","options","appName","pb","pkg","ensureSiteFile","file","ensureSiteBusiness","wanted","existing","added","next"],"sources":["../../src/runtime/site.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File, Options } from \"../core/types\";\nimport { getLogger } from \"../core/logger\";\nimport { languageFromPath } from \"../core/util\";\nimport { withPocketbase } from \"./pocketbase\";\n\n/** Where every VelaStack app keeps its name and public URL. */\nexport function sitePath(root: string): string {\n return path.join(root, \"src\", \"lib\", \"site.ts\");\n}\n\n/**\n * What a business declares about itself in `src/lib/site.ts`, next to the\n * app's name: the currency it prices in and is paid in, the country it is in\n * (prices format for it: `es-MX`, not `es`) and the other currencies it shows\n * prices in, as estimates. Every property is optional; a payments provider\n * asks for what it needs.\n */\nexport interface SiteBusiness {\n /** ISO 4217, e.g. `MXN`. */\n currency?: string;\n /** ISO 3166-1 alpha-2, e.g. `MX`. */\n country?: string;\n /** ISO 4217 codes the site also shows prices in; empty means the home currency only. */\n currencies?: string[];\n}\n\ntype BusinessKey = keyof SiteBusiness;\n\nconst BUSINESS_KEYS: BusinessKey[] = [\"currency\", \"country\", \"currencies\"];\n\n/**\n * `src/lib/site.ts` as the CLI templates ship it (`site.template.ts`), with\n * the placeholders filled in, plus whatever the business declares.\n */\nexport function siteModule(\n name: string,\n url = \"http://localhost:5173\",\n business: SiteBusiness | string = {},\n): string {\n // The old third argument was the currency alone.\n const declared: SiteBusiness =\n typeof business === \"string\" ? { currency: business } : business;\n const lines = BUSINESS_KEYS.filter((key) => declared[key] !== undefined).map(\n (key) => propertyLines(key, declared[key]!),\n );\n const properties = [\n `\\tname: ${quote(name)},`,\n `\\turl: ${quote(url)}`,\n ...lines.map((entry) => entry.join(\"\\n\")),\n ];\n return [\n \"/**\",\n \" * Site-wide metadata, and the one place the app's name and public URL live.\",\n \" *\",\n \" * Set `url` to where the site is deployed: canonical links, Open Graph images\",\n \" * and feeds are built from it, including in prerendered pages. With a backend,\",\n \" * `vela dev` and `vela deploy` copy `name` into PocketBase's application name\",\n \" * for the emails it sends, so change it here rather than in the admin panel.\",\n \" */\",\n \"export const site = {\",\n // Every property but the last ends in a comma.\n ...properties.map((entry, i) =>\n i < properties.length - 1 ? ensureComma(entry) : entry,\n ),\n \"};\",\n \"\",\n ].join(\"\\n\");\n}\n\nfunction ensureComma(entry: string): string {\n return entry.endsWith(\",\") ? entry : `${entry},`;\n}\n\n/** A property's lines: its doc comment, then `key: value` with no trailing comma. */\nfunction propertyLines(key: BusinessKey, value: string | string[]): string[] {\n switch (key) {\n case \"currency\":\n return [\n \"\\t/** ISO 4217: the currency the business prices in and is paid in. */\",\n `\\tcurrency: ${quote(value as string)}`,\n ];\n case \"country\":\n return [\n \"\\t/** ISO 3166-1: the country the business is in; prices format for it. */\",\n `\\tcountry: ${quote(value as string)}`,\n ];\n case \"currencies\":\n return [\n \"\\t/** Other currencies prices are shown in, as estimates at the day's rate. */\",\n `\\tcurrencies: [${(value as string[]).map(quote).join(\", \")}]`,\n ];\n }\n}\n\nconst SUPPORTED_CURRENCIES = (\n Intl as unknown as {\n supportedValuesOf: (key: \"currency\") => string[];\n }\n).supportedValuesOf(\"currency\");\n\n/** A three-letter code `Intl` knows, upper-cased; anything else is refused. */\nexport function normalizeCurrency(raw: unknown): string | null {\n if (typeof raw !== \"string\") return null;\n const code = raw.trim().toUpperCase();\n if (!/^[A-Z]{3}$/.test(code)) return null;\n // Any well-formed code formats, so ask for the list of real ones. Node has\n // had it since 18; the repo's ES2020 lib types just don't declare it.\n return SUPPORTED_CURRENCIES.includes(code) ? code : null;\n}\n\n/** A two-letter ISO 3166-1 code, upper-cased; anything else is refused. */\nexport function normalizeCountry(raw: unknown): string | null {\n if (typeof raw !== \"string\") return null;\n const code = raw.trim().toUpperCase();\n if (!/^[A-Z]{2}$/.test(code)) return null;\n // `Intl.DisplayNames` knows every region; an unknown one comes back as is.\n const names = new Intl.DisplayNames([\"en\"], { type: \"region\" });\n return names.of(code) !== code ? code : null;\n}\n\n/**\n * A list of currency codes, from an array or a comma-separated string,\n * upper-cased and deduplicated; `null` when any entry is not a currency.\n * `home` is left out: the business's own currency is never a display one.\n */\nexport function normalizeCurrencies(\n raw: unknown,\n home?: string,\n): string[] | null {\n const entries = Array.isArray(raw)\n ? raw\n : typeof raw === \"string\"\n ? raw.split(/[,\\s]+/)\n : null;\n if (!entries) return null;\n const codes: string[] = [];\n for (const entry of entries) {\n if (entry === \"\" || entry === undefined) continue;\n const code = normalizeCurrency(entry);\n if (!code) return null;\n if (code !== home && !codes.includes(code)) codes.push(code);\n }\n return codes;\n}\n\nconst SITE_OBJECT = /export const site = \\{\\n([\\s\\S]*?)\\n\\};/;\n\n/**\n * `src/lib/site.ts` with `key` added as the object's last property, or\n * `null` when it already has one (a project's declaration is never changed\n * behind its back) or has no `export const site = { ... };` to add it to.\n */\nexport function withSiteProperty(\n source: string,\n key: BusinessKey,\n value: string | string[],\n): string | null {\n const match = SITE_OBJECT.exec(source);\n if (!match || new RegExp(`^\\\\s*${key}\\\\s*:`, \"m\").test(match[1])) return null;\n const body = match[1].replace(/,?\\s*$/, \",\");\n return source.replace(\n match[0],\n `export const site = {\\n${body}\\n${propertyLines(key, value).join(\"\\n\")}\\n};`,\n );\n}\n\n/** `withSiteProperty` for the currency, as the Phase 1.5 code called it. */\nexport function withSiteCurrency(\n source: string,\n currency: string,\n): string | null {\n return withSiteProperty(source, \"currency\", currency);\n}\n\n/** What `src/lib/site.ts` declares about the business, if anything. */\nexport function siteBusiness(root: string): SiteBusiness {\n let source: string;\n try {\n source = fs.readFileSync(sitePath(root), \"utf8\");\n } catch {\n return {};\n }\n const text = (key: string, shape: string) =>\n new RegExp(`^\\\\s*${key}\\\\s*:\\\\s*['\"](${shape})['\"]`, \"m\").exec(source)?.[1];\n const list = /^\\s*currencies\\s*:\\s*\\[([^\\]]*)\\]/m.exec(source)?.[1];\n const business: SiteBusiness = {};\n const currency = text(\"currency\", \"[A-Za-z]{3}\");\n if (currency) business.currency = currency;\n const country = text(\"country\", \"[A-Za-z]{2}\");\n if (country) business.country = country;\n if (list !== undefined) {\n business.currencies = [...list.matchAll(/['\"]([A-Za-z]{3})['\"]/g)].map(\n (m) => m[1],\n );\n }\n return business;\n}\n\n/** The currency `src/lib/site.ts` declares, if any. */\nexport function siteCurrency(root: string): string | null {\n return siteBusiness(root).currency ?? null;\n}\n\n/** Single-quoted, as the templates write their strings. */\nfunction quote(value: string): string {\n return `'${value.replace(/\\\\/g, \"\\\\\\\\\").replace(/'/g, \"\\\\'\")}'`;\n}\n\n/**\n * The name a project created before `site.ts` existed already goes by.\n *\n * Those projects kept it in PocketBase's settings, so that is asked first; the\n * package name is the fallback for a project without a backend, or one whose\n * database can't be reached.\n */\nasync function existingName(options: Options): Promise<string> {\n if (options.features.backend) {\n try {\n let appName: unknown;\n await withPocketbase(options.root, async (pb) => {\n const settings = (await pb.settings.getAll()) as {\n meta?: { appName?: unknown };\n };\n appName = settings.meta?.appName;\n });\n if (typeof appName === \"string\" && appName.trim()) return appName;\n } catch {\n // No database to ask; fall through to package.json.\n }\n }\n\n try {\n const pkg = JSON.parse(\n fs.readFileSync(path.join(options.root, \"package.json\"), \"utf8\"),\n ) as { name?: unknown };\n if (typeof pkg.name === \"string\" && pkg.name.trim()) return pkg.name;\n } catch {\n // No package.json to name the site after; the placeholder stands.\n }\n return \"My App\";\n}\n\n/**\n * Create `src/lib/site.ts` for a pattern whose files import `#lib/site.js`, when\n * the project doesn't have one yet. Every template ships it; projects created\n * before that read the app name from `locals.meta` instead.\n *\n * Returns null when the file exists, so an existing one is never overwritten.\n */\nexport async function ensureSiteFile(options: Options): Promise<File | null> {\n const file = sitePath(options.root);\n if (fs.existsSync(file)) return null;\n\n getLogger(options).info(\"Creating src/lib/site.ts\");\n return {\n path: file,\n language: languageFromPath(file),\n content: siteModule(await existingName(options)),\n status: \"success\",\n };\n}\n\n/**\n * Make `src/lib/site.ts` declare what the business says about itself: create\n * the file with it, or add the properties an existing one lacks. A property\n * already there is kept, whatever `business` says; the result says what the\n * file declares after the call, and the file to write, if anything changed.\n */\nexport async function ensureSiteBusiness(\n options: Options,\n business: SiteBusiness,\n): Promise<{ file: File | null; business: SiteBusiness }> {\n const file = sitePath(options.root);\n const wanted = BUSINESS_KEYS.filter((key) => business[key] !== undefined);\n if (!fs.existsSync(file)) {\n if (wanted.length === 0) return { file: null, business: {} };\n getLogger(options).info(\"Creating src/lib/site.ts\");\n return {\n file: {\n path: file,\n language: languageFromPath(file),\n content: siteModule(await existingName(options), undefined, business),\n status: \"success\",\n },\n business,\n };\n }\n\n const existing = siteBusiness(options.root);\n let source = fs.readFileSync(file, \"utf8\");\n const added: string[] = [];\n for (const key of wanted) {\n if (existing[key] !== undefined) continue;\n const next = withSiteProperty(source, key, business[key]!);\n if (next === null) continue;\n source = next;\n added.push(key);\n (existing as Record<string, unknown>)[key] = business[key];\n }\n if (added.length === 0) return { file: null, business: existing };\n getLogger(options).info(`Adding ${added.join(\", \")} to src/lib/site.ts`);\n return {\n file: {\n path: file,\n language: languageFromPath(file),\n content: source,\n status: \"success\",\n },\n business: existing,\n };\n}\n\n/** `ensureSiteBusiness` for the currency alone, as the Phase 1.5 code called it. */\nexport async function ensureSiteCurrency(\n options: Options,\n currency: string,\n): Promise<{ file: File | null; currency: string }> {\n const { file, business } = await ensureSiteBusiness(options, { currency });\n return { file, currency: business.currency ?? currency };\n}\n"],"mappings":";;;;;;AAQA,SAAgBK,EAAS,GAAsB;CAC7C,OAAOD,EAAK,KAAKE,GAAM,OAAO,OAAO,SAAS;AAChD;AAoBA,IAAMC,IAA+B;CAAC;CAAY;CAAW;AAAY;AAMzE,SAAgBC,EACd,GACA,IAAM,yBACN,IAAkC,CAAC,GAC3B;CAER,IAAMC,IACJ,OAAOC,KAAa,WAAW,EAAE,UAAUA,EAAS,IAAIA,GACpDC,IAAQJ,EAAc,QAAQ,MAAQE,EAASG,OAAS,KAAA,CAAS,CAAC,CAAC,KACtE,MAAQC,EAAcD,GAAKH,EAASG,EAAK,CAC5C,GACME,IAAa;EACjB,WAAWC,EAAMC,CAAI,EAAE;EACvB,UAAUD,EAAME,CAAG;EACnB,GAAGN,EAAM,KAAK,MAAUO,EAAM,KAAK,IAAI,CAAC;CAC1C;CACA,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EAEA,GAAGJ,EAAW,KAAK,GAAO,MACxBK,IAAIL,EAAW,SAAS,IAAIM,EAAYF,CAAK,IAAIA,CACnD;EACA;EACA;CACF,CAAC,CAAC,KAAK,IAAI;AACb;AAEA,SAASE,EAAY,GAAuB;CAC1C,OAAOF,EAAM,SAAS,GAAG,IAAIA,IAAQ,GAAGA,EAAM;AAChD;AAGA,SAASL,EAAc,GAAkB,GAAoC;CAC3E,QAAQD,GAAR;EACE,KAAK,YACH,OAAO,CACL,yEACA,eAAeG,EAAMM,CAAe,GACtC;EACF,KAAK,WACH,OAAO,CACL,6EACA,cAAcN,EAAMM,CAAe,GACrC;EACF,KAAK,cACH,OAAO,CACL,iFACA,k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,MAAM;EAAM,UAAUD;CAAS,KAChEpD,EAAU4C,CAAO,CAAC,CAAC,KAAK,UAAUS,EAAM,KAAK,IAAI,EAAE,oBAAoB,GAChE;EACL,MAAM;GACJ,MAAMJ;GACN,UAAUhD,EAAiBgD,CAAI;GAC/B,SAASf;GACT,QAAQ;EACV;EACA,UAAUkB;CACZ;AACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { n as e } from "./rolldown-runtime-CwxnZyOB.js";
|
|
2
|
-
import { _ as t, g as n } from "./constants-
|
|
2
|
+
import { _ as t, g as n } from "./constants-E1I-__KI.js";
|
|
3
3
|
import { r, t as i } from "./errors-DdSUZI8f.js";
|
|
4
4
|
import { n as a } from "./lib-specifier-C3M0WTev.js";
|
|
5
5
|
import { existsSync as o, readFileSync as s } from "node:fs";
|
|
@@ -127,4 +127,4 @@ function O(e) {
|
|
|
127
127
|
}
|
|
128
128
|
export { d as a, v as i, E as n, m as o, y as r, p as s, O as t };
|
|
129
129
|
|
|
130
|
-
//# sourceMappingURL=table-core-
|
|
130
|
+
//# sourceMappingURL=table-core-ux1xEJxN.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"table-core-s2xjYgRD.js","names":["__exportAll","TANSTACK_TABLE_CORE_MAJOR","TANSTACK_TABLE_CORE","InvalidArgumentError","libAliasPath","path","REGISTRY_TIMEOUT_MS","optionalString","value","readComponentsConfig","raw","configPath","root","existsSync","parsed","readFileSync","aliases","key","alias","DEFAULT_UI_DIR","resolveUiDir","rel","registryIndexUrl","registry","style","indexCache","parseIndex","body","items","entry","name","type","requestIndex","response","fetchImpl","url","error","reason","RegistryUnavailableError","fetchRegistryIndex","config","options","cache","pending","table_core_exports","assertRegistryPagination","assertTableCoreV9","TABLE_CORE_COMPONENTS","MIGRATION_GUIDE","declaredTableCoreMajor","packageJsonPath","pkg","major","hasV8DataTable","index","upgradeSteps","outdatedPackage","found","assertTableCorePackage","tableComponents","components","component","hasLegacyPagination"],"sources":["../../src/runtime/registry.ts","../../src/runtime/table-core.ts"],"sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport type { RegistryItem, WriteResultRuntime } from \"../core/types\";\nimport { RegistryUnavailableError } from \"../core/errors\";\nimport { libAliasPath } from \"./lib-specifier\";\n\n/**\n * shadcn-svelte's schema defaults. A `components.json` that names no `style`\n * resolves to `nova` (not `vega`, whatever `getRegistryUrl`'s fallback says),\n * which is why the CLI's templates write the key explicitly.\n */\nexport const DEFAULT_STYLE = \"nova\";\nexport const DEFAULT_REGISTRY = \"https://shadcn-svelte.com/registry\";\nexport const DEFAULT_CSS_PATH = \"src/app.css\";\n\nconst REGISTRY_TIMEOUT_MS = 10_000;\n\nexport interface ComponentsConfig {\n style: string;\n registry: string;\n baseColor?: string;\n iconLibrary?: string;\n menuColor?: string;\n menuAccent?: string;\n aliases: Record<string, string>;\n /** `tailwind.css`: the global stylesheet, relative to the root. */\n cssPath: string;\n}\n\ninterface RawComponentsConfig {\n style?: unknown;\n registry?: unknown;\n iconLibrary?: unknown;\n menuColor?: unknown;\n menuAccent?: unknown;\n tailwind?: { css?: unknown; baseColor?: unknown };\n aliases?: Record<string, unknown>;\n}\n\nfunction optionalString(value: unknown): string | undefined {\n return typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\n/**\n * The project's `components.json` with the schema defaults filled in. A\n * missing or unreadable file behaves like an empty one, so callers can still\n * compute paths and the existence checks here agree with shadcn's own.\n */\nexport function readComponentsConfig(root: string): ComponentsConfig {\n let raw: RawComponentsConfig = {};\n const configPath = path.join(root, \"components.json\");\n if (existsSync(configPath)) {\n try {\n const parsed: unknown = JSON.parse(readFileSync(configPath, \"utf8\"));\n if (parsed && typeof parsed === \"object\") {\n raw = parsed as RawComponentsConfig;\n }\n } catch {\n raw = {};\n }\n }\n\n const aliases: Record<string, string> = {};\n for (const [key, value] of Object.entries(raw.aliases ?? {})) {\n const alias = optionalString(value);\n if (alias) aliases[key] = alias;\n }\n\n return {\n style: optionalString(raw.style) ?? DEFAULT_STYLE,\n registry: optionalString(raw.registry) ?? DEFAULT_REGISTRY,\n baseColor: optionalString(raw.tailwind?.baseColor),\n iconLibrary: optionalString(raw.iconLibrary),\n menuColor: optionalString(raw.menuColor),\n menuAccent: optionalString(raw.menuAccent),\n aliases,\n cssPath: optionalString(raw.tailwind?.css) ?? DEFAULT_CSS_PATH,\n };\n}\n\nconst DEFAULT_UI_DIR = [\"src\", \"lib\", \"components\", \"ui\"];\n\n/**\n * Where shadcn-svelte writes items: `components.json` `aliases.ui`, resolved\n * under `src/lib` for `#lib/...`, or the alias a project from before\n * SvelteKit 3 still has.\n * Anything else (a custom alias, a missing or unreadable config) falls back\n * to the default so the existence check here and shadcn's own target agree\n * for every project the CLI creates.\n */\nexport function resolveUiDir(root: string): string {\n const alias = readComponentsConfig(root).aliases.ui;\n const rel = alias === undefined ? null : libAliasPath(alias);\n if (rel === null) {\n return path.join(root, ...DEFAULT_UI_DIR);\n }\n return path.join(root, \"src\", \"lib\", ...rel.split(\"/\").filter(Boolean));\n}\n\n/** `${registry}/styles/${style}/index.json`: the items one style offers. */\nexport function registryIndexUrl(registry: string, style: string): string {\n return `${registry.replace(/\\/+$/, \"\")}/styles/${encodeURIComponent(style)}/index.json`;\n}\n\n/**\n * One request per registry URL per process, keyed on the fetch implementation\n * so an injected test double never sees another test's answer and the real\n * `fetch` shares its answer across a style switch and the installs it runs.\n */\nconst indexCache = new WeakMap<\n typeof fetch,\n Map<string, Promise<RegistryItem[]>>\n>();\n\nfunction parseIndex(body: unknown): RegistryItem[] {\n if (!Array.isArray(body)) {\n throw new Error(\"the index is not a list\");\n }\n const items: RegistryItem[] = [];\n for (const entry of body) {\n if (!entry || typeof entry !== \"object\") continue;\n const { name, type } = entry as { name?: unknown; type?: unknown };\n if (typeof name === \"string\" && typeof type === \"string\") {\n items.push({ name, type });\n }\n }\n return items;\n}\n\nasync function requestIndex(\n url: string,\n fetchImpl: typeof fetch,\n): Promise<RegistryItem[]> {\n let response: Response;\n try {\n response = await fetchImpl(url, {\n signal: AbortSignal.timeout(REGISTRY_TIMEOUT_MS),\n });\n } catch (error) {\n const reason =\n error instanceof Error && error.name === \"TimeoutError\"\n ? `no answer within ${REGISTRY_TIMEOUT_MS / 1000}s`\n : error instanceof Error\n ? error.message\n : String(error);\n throw new RegistryUnavailableError(url, reason);\n }\n if (!response.ok) {\n throw new RegistryUnavailableError(url, `HTTP ${response.status}`);\n }\n try {\n return parseIndex(await response.json());\n } catch (error) {\n throw new RegistryUnavailableError(\n url,\n error instanceof Error ? error.message : String(error),\n );\n }\n}\n\n/**\n * The items the project's registry offers for a style: the configured one by\n * default, or `options.style` to look at the style a project is about to\n * switch to. Throws `RegistryUnavailableError` when the index cannot be read.\n */\nexport async function fetchRegistryIndex(\n root: string,\n options: { style?: string; runtime?: WriteResultRuntime } = {},\n): Promise<RegistryItem[]> {\n const config = readComponentsConfig(root);\n const url = registryIndexUrl(config.registry, options.style ?? config.style);\n const fetchImpl = options.runtime?.fetch ?? globalThis.fetch;\n\n let cache = indexCache.get(fetchImpl);\n if (!cache) {\n cache = new Map();\n indexCache.set(fetchImpl, cache);\n }\n let pending = cache.get(url);\n if (!pending) {\n pending = requestIndex(url, fetchImpl).catch((error: unknown) => {\n // A failed read is not worth remembering: the next command may be online.\n cache.delete(url);\n throw error;\n });\n cache.set(url, pending);\n }\n return pending;\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport {\n TANSTACK_TABLE_CORE,\n TANSTACK_TABLE_CORE_MAJOR,\n} from \"../core/constants\";\nimport { InvalidArgumentError } from \"../core/errors\";\nimport { resolveUiDir } from \"./registry\";\n\n/** The components this package ships that are built on `@tanstack/table-core`. */\nexport const TABLE_CORE_COMPONENTS = [\n \"data-table\",\n \"column-header\",\n \"faceted-filter\",\n \"data-table-pagination\",\n];\n\nconst MIGRATION_GUIDE =\n \"https://tanstack.com/table/latest/docs/framework/svelte/guide/migrating\";\n\n/**\n * The major of the `@tanstack/table-core` range `package.json` declares, when\n * it names one (`^8.21.3` is 8; `latest` or `workspace:*` is undefined).\n */\nexport function declaredTableCoreMajor(root: string): number | undefined {\n const packageJsonPath = path.join(root, \"package.json\");\n if (!existsSync(packageJsonPath)) return undefined;\n const pkg = JSON.parse(readFileSync(packageJsonPath, \"utf8\")) as {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n };\n const range =\n pkg.dependencies?.[\"@tanstack/table-core\"] ??\n pkg.devDependencies?.[\"@tanstack/table-core\"];\n const major = range?.match(/^[\\^~>=v\\s]*(\\d+)/)?.[1];\n return major === undefined ? undefined : Number(major);\n}\n\n/** Whether the project's `data-table` helper is the v8 one (`createSvelteTable`). */\nfunction hasV8DataTable(root: string): boolean {\n const index = path.join(resolveUiDir(root), \"data-table\", \"index.ts\");\n return (\n existsSync(index) &&\n readFileSync(index, \"utf8\").includes(\"createSvelteTable\")\n );\n}\n\nfunction upgradeSteps(): string {\n return (\n \"Nothing was changed. To upgrade:\\n\" +\n ` 1. Install ${TANSTACK_TABLE_CORE}: npm install ${TANSTACK_TABLE_CORE}\\n` +\n ` 2. Replace the table helpers: vela ui add ${TABLE_CORE_COMPONENTS.join(\" \")} --overwrite\\n` +\n ` 3. Move existing list pages to the v9 API (createTable, tableFeatures): ${MIGRATION_GUIDE}\\n` +\n \"Then run this again.\"\n );\n}\n\n/**\n * Refuses a project still on TanStack Table v8, before anything is written.\n *\n * The scaffold list pages and the table helpers target v9. A project set up\n * before that has `@tanstack/table-core@^8` and v8 helpers; the package is\n * never upgraded by `installPackages` (it is already present) and the helpers\n * are never replaced (they already exist), so a new page would not compile,\n * and upgrading in place would break the list pages already there.\n */\nexport function assertTableCoreV9(root: string): void {\n const major = declaredTableCoreMajor(root);\n const outdatedPackage =\n major !== undefined && major < TANSTACK_TABLE_CORE_MAJOR;\n if (!outdatedPackage && !hasV8DataTable(root)) return;\n\n const found = outdatedPackage\n ? `package.json pins @tanstack/table-core ${major}.x`\n : \"its data-table helper is the v8 one (createSvelteTable)\";\n throw new InvalidArgumentError(\n `This project uses TanStack Table v8 (${found}), and scaffold list pages now need v${TANSTACK_TABLE_CORE_MAJOR}.\\n\\n` +\n upgradeSteps(),\n );\n}\n\n/**\n * Refuses to add v9 table helpers next to a v8 `@tanstack/table-core`, which\n * `installPackages` would leave in place.\n */\nexport function assertTableCorePackage(\n root: string,\n components: string[],\n): void {\n const tableComponents = components.filter((component) =>\n TABLE_CORE_COMPONENTS.includes(component),\n );\n if (tableComponents.length === 0) return;\n const major = declaredTableCoreMajor(root);\n if (major === undefined || major >= TANSTACK_TABLE_CORE_MAJOR) return;\n\n throw new InvalidArgumentError(\n `${tableComponents.join(\", \")} target${tableComponents.length === 1 ? \"s\" : \"\"} TanStack Table v${TANSTACK_TABLE_CORE_MAJOR}, and package.json pins @tanstack/table-core ${major}.x.\\n\\n` +\n `Nothing was changed. Install ${TANSTACK_TABLE_CORE} first (npm install ${TANSTACK_TABLE_CORE}), then run this again.`,\n );\n}\n\n/**\n * Whether `ui/pagination` is the table footer this package shipped under that\n * name (one `Pagination` taking a `table`), not shadcn-svelte's pagination,\n * whose index exports the parts (`Content`, `Item`, `Link`, ...).\n */\nfunction hasLegacyPagination(root: string): boolean {\n const index = path.join(resolveUiDir(root), \"pagination\", \"index.ts\");\n return existsSync(index) && !readFileSync(index, \"utf8\").includes(\"Content\");\n}\n\n/**\n * Refuses a project whose `ui/pagination` is still the old table footer,\n * before anything is written.\n *\n * The footer is `data-table-pagination` now, built on shadcn-svelte's\n * `pagination`, which installs to that same directory. A component that is\n * present is never replaced, so the new footer would import parts the old\n * file does not export; and replacing it in place would break the list pages\n * that render the old one.\n */\nexport function assertRegistryPagination(root: string): void {\n if (!hasLegacyPagination(root)) return;\n\n throw new InvalidArgumentError(\n \"This project's ui/pagination is the table footer older scaffolds used. The footer is now data-table-pagination, built on shadcn-svelte's pagination, which belongs in that directory.\\n\\n\" +\n \"Nothing was changed. To upgrade:\\n\" +\n \" 1. Replace ui/pagination with shadcn-svelte's: vela ui add pagination --overwrite\\n\" +\n \" 2. Add the new footer: vela ui add data-table-pagination\\n\" +\n ' 3. In existing list pages, import { DataTablePagination } from \"#lib/components/ui/data-table-pagination/index.js\"\\n' +\n \" in place of { Pagination }, and render <DataTablePagination {table} />.\\n\" +\n \"Then run this again.\",\n );\n}\n"],"mappings":";;;;;;AAeA,IAAMM,IAAsB;AAwB5B,SAASC,EAAe,GAAoC;CAC1D,OAAO,OAAOC,KAAU,YAAYA,EAAM,SAAS,IAAIA,IAAQ,KAAA;AACjE;AAOA,SAAgBC,EAAqB,GAAgC;CACnE,IAAIC,IAA2B,CAAC,GAC1BC,IAAaN,EAAK,KAAKO,GAAM,iBAAiB;CACpD,IAAIC,EAAWF,CAAU,GACvB,IAAI;EACF,IAAMG,IAAkB,KAAK,MAAMC,EAAaJ,GAAY,MAAM,CAAC;EACnE,AAAIG,KAAU,OAAOA,KAAW,aAC9B,IAAMA;CAEV,QAAQ;EACN,IAAM,CAAC;CACT;CAGF,IAAME,IAAkC,CAAC;CACzC,KAAK,IAAM,CAACC,GAAKT,MAAU,OAAO,QAAQE,EAAI,WAAW,CAAC,CAAC,GAAG;EAC5D,IAAMQ,IAAQX,EAAeC,CAAK;EAClC,AAAIU,MAAO,EAAQD,KAAOC;CAC5B;CAEA,OAAO;EACL,OAAOX,EAAeG,EAAI,KAAK,KAAA;EAC/B,UAAUH,EAAeG,EAAI,QAAQ,KAAA;EACrC,WAAWH,EAAeG,EAAI,UAAU,SAAS;EACjD,aAAaH,EAAeG,EAAI,WAAW;EAC3C,WAAWH,EAAeG,EAAI,SAAS;EACvC,YAAYH,EAAeG,EAAI,UAAU;EACzC;EACA,SAASH,EAAeG,EAAI,UAAU,GAAG,KAAA;CAC3C;AACF;AAEA,IAAMS,IAAiB;CAAC;CAAO;CAAO;CAAc;AAAI;AAUxD,SAAgBC,EAAa,GAAsB;CACjD,IAAMF,IAAQT,EAAqBG,CAAI,CAAC,C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gB;AAGjG;AAWA,SAAgBF,EAAkB,GAAoB;CACpD,IAAMM,IAAQH,EAAuBrC,CAAI,GACnC4C,IACJJ,MAAU,KAAA,KAAaA,IAAQnD;CACjC,IAAI,CAACuD,KAAmB,CAACH,EAAezC,CAAI,GAAG;CAE/C,IAAM6C,IAAQD,IACV,0CAA0CJ,EAAM,MAChD;CACJ,MAAM,IAAIjD,EACR,wCAAwCsD,EAAM,uCAAuCxD,EAA0B,SAC7GsD,EAAa,CACjB;AACF;AAMA,SAAgBG,EACd,GACA,GACM;CACN,IAAMC,IAAkBC,EAAW,QAAQ,MACzCb,EAAsB,SAASc,CAAS,CAC1C;CACA,IAAIF,EAAgB,WAAW,GAAG;CAClC,IAAMP,IAAQH,EAAuBrC,CAAI;CACzC,IAAI,QAAU,KAAA,KAAawC,KAASnD,IAEpC,MAAM,IAAIE,EACR,GAAGwD,EAAgB,KAAK,IAAI,EAAE,SAASA,EAAgB,WAAW,IAAI,MAAM,GAAG,mBAAmB1D,EAA0B,+CAA+CmD,EAAM,sCAC/IlD,EAAoB,sBAAsBA,EAAoB,wBAClG;AACF;AAOA,SAAS4D,EAAoB,GAAuB;CAClD,IAAMR,IAAQjD,EAAK,KAAKe,EAAaR,CAAI,GAAG,cAAc,UAAU;CACpE,OAAOC,EAAWyC,CAAK,KAAK,CAACvC,EAAauC,GAAO,MAAM,CAAC,CAAC,SAAS,SAAS;AAC7E;AAYA,SAAgBT,EAAyB,GAAoB;CAC3D,IAAKiB,EAAoBlD,CAAI,GAE7B,MAAM,IAAIT,EACR,kmBAOF;AACF"}
|
|
1
|
+
{"version":3,"file":"table-core-ux1xEJxN.js","names":["__exportAll","TANSTACK_TABLE_CORE_MAJOR","TANSTACK_TABLE_CORE","InvalidArgumentError","libAliasPath","path","REGISTRY_TIMEOUT_MS","optionalString","value","readComponentsConfig","raw","configPath","root","existsSync","parsed","readFileSync","aliases","key","alias","DEFAULT_UI_DIR","resolveUiDir","rel","registryIndexUrl","registry","style","indexCache","parseIndex","body","items","entry","name","type","requestIndex","response","fetchImpl","url","error","reason","RegistryUnavailableError","fetchRegistryIndex","config","options","cache","pending","table_core_exports","assertRegistryPagination","assertTableCoreV9","TABLE_CORE_COMPONENTS","MIGRATION_GUIDE","declaredTableCoreMajor","packageJsonPath","pkg","major","hasV8DataTable","index","upgradeSteps","outdatedPackage","found","assertTableCorePackage","tableComponents","components","component","hasLegacyPagination"],"sources":["../../src/runtime/registry.ts","../../src/runtime/table-core.ts"],"sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport type { RegistryItem, WriteResultRuntime } from \"../core/types\";\nimport { RegistryUnavailableError } from \"../core/errors\";\nimport { libAliasPath } from \"./lib-specifier\";\n\n/**\n * shadcn-svelte's schema defaults. A `components.json` that names no `style`\n * resolves to `nova` (not `vega`, whatever `getRegistryUrl`'s fallback says),\n * which is why the CLI's templates write the key explicitly.\n */\nexport const DEFAULT_STYLE = \"nova\";\nexport const DEFAULT_REGISTRY = \"https://shadcn-svelte.com/registry\";\nexport const DEFAULT_CSS_PATH = \"src/app.css\";\n\nconst REGISTRY_TIMEOUT_MS = 10_000;\n\nexport interface ComponentsConfig {\n style: string;\n registry: string;\n baseColor?: string;\n iconLibrary?: string;\n menuColor?: string;\n menuAccent?: string;\n aliases: Record<string, string>;\n /** `tailwind.css`: the global stylesheet, relative to the root. */\n cssPath: string;\n}\n\ninterface RawComponentsConfig {\n style?: unknown;\n registry?: unknown;\n iconLibrary?: unknown;\n menuColor?: unknown;\n menuAccent?: unknown;\n tailwind?: { css?: unknown; baseColor?: unknown };\n aliases?: Record<string, unknown>;\n}\n\nfunction optionalString(value: unknown): string | undefined {\n return typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\n/**\n * The project's `components.json` with the schema defaults filled in. A\n * missing or unreadable file behaves like an empty one, so callers can still\n * compute paths and the existence checks here agree with shadcn's own.\n */\nexport function readComponentsConfig(root: string): ComponentsConfig {\n let raw: RawComponentsConfig = {};\n const configPath = path.join(root, \"components.json\");\n if (existsSync(configPath)) {\n try {\n const parsed: unknown = JSON.parse(readFileSync(configPath, \"utf8\"));\n if (parsed && typeof parsed === \"object\") {\n raw = parsed as RawComponentsConfig;\n }\n } catch {\n raw = {};\n }\n }\n\n const aliases: Record<string, string> = {};\n for (const [key, value] of Object.entries(raw.aliases ?? {})) {\n const alias = optionalString(value);\n if (alias) aliases[key] = alias;\n }\n\n return {\n style: optionalString(raw.style) ?? DEFAULT_STYLE,\n registry: optionalString(raw.registry) ?? DEFAULT_REGISTRY,\n baseColor: optionalString(raw.tailwind?.baseColor),\n iconLibrary: optionalString(raw.iconLibrary),\n menuColor: optionalString(raw.menuColor),\n menuAccent: optionalString(raw.menuAccent),\n aliases,\n cssPath: optionalString(raw.tailwind?.css) ?? DEFAULT_CSS_PATH,\n };\n}\n\nconst DEFAULT_UI_DIR = [\"src\", \"lib\", \"components\", \"ui\"];\n\n/**\n * Where shadcn-svelte writes items: `components.json` `aliases.ui`, resolved\n * under `src/lib` for `#lib/...`, or the alias a project from before\n * SvelteKit 3 still has.\n * Anything else (a custom alias, a missing or unreadable config) falls back\n * to the default so the existence check here and shadcn's own target agree\n * for every project the CLI creates.\n */\nexport function resolveUiDir(root: string): string {\n const alias = readComponentsConfig(root).aliases.ui;\n const rel = alias === undefined ? null : libAliasPath(alias);\n if (rel === null) {\n return path.join(root, ...DEFAULT_UI_DIR);\n }\n return path.join(root, \"src\", \"lib\", ...rel.split(\"/\").filter(Boolean));\n}\n\n/** `${registry}/styles/${style}/index.json`: the items one style offers. */\nexport function registryIndexUrl(registry: string, style: string): string {\n return `${registry.replace(/\\/+$/, \"\")}/styles/${encodeURIComponent(style)}/index.json`;\n}\n\n/**\n * One request per registry URL per process, keyed on the fetch implementation\n * so an injected test double never sees another test's answer and the real\n * `fetch` shares its answer across a style switch and the installs it runs.\n */\nconst indexCache = new WeakMap<\n typeof fetch,\n Map<string, Promise<RegistryItem[]>>\n>();\n\nfunction parseIndex(body: unknown): RegistryItem[] {\n if (!Array.isArray(body)) {\n throw new Error(\"the index is not a list\");\n }\n const items: RegistryItem[] = [];\n for (const entry of body) {\n if (!entry || typeof entry !== \"object\") continue;\n const { name, type } = entry as { name?: unknown; type?: unknown };\n if (typeof name === \"string\" && typeof type === \"string\") {\n items.push({ name, type });\n }\n }\n return items;\n}\n\nasync function requestIndex(\n url: string,\n fetchImpl: typeof fetch,\n): Promise<RegistryItem[]> {\n let response: Response;\n try {\n response = await fetchImpl(url, {\n signal: AbortSignal.timeout(REGISTRY_TIMEOUT_MS),\n });\n } catch (error) {\n const reason =\n error instanceof Error && error.name === \"TimeoutError\"\n ? `no answer within ${REGISTRY_TIMEOUT_MS / 1000}s`\n : error instanceof Error\n ? error.message\n : String(error);\n throw new RegistryUnavailableError(url, reason);\n }\n if (!response.ok) {\n throw new RegistryUnavailableError(url, `HTTP ${response.status}`);\n }\n try {\n return parseIndex(await response.json());\n } catch (error) {\n throw new RegistryUnavailableError(\n url,\n error instanceof Error ? error.message : String(error),\n );\n }\n}\n\n/**\n * The items the project's registry offers for a style: the configured one by\n * default, or `options.style` to look at the style a project is about to\n * switch to. Throws `RegistryUnavailableError` when the index cannot be read.\n */\nexport async function fetchRegistryIndex(\n root: string,\n options: { style?: string; runtime?: WriteResultRuntime } = {},\n): Promise<RegistryItem[]> {\n const config = readComponentsConfig(root);\n const url = registryIndexUrl(config.registry, options.style ?? config.style);\n const fetchImpl = options.runtime?.fetch ?? globalThis.fetch;\n\n let cache = indexCache.get(fetchImpl);\n if (!cache) {\n cache = new Map();\n indexCache.set(fetchImpl, cache);\n }\n let pending = cache.get(url);\n if (!pending) {\n pending = requestIndex(url, fetchImpl).catch((error: unknown) => {\n // A failed read is not worth remembering: the next command may be online.\n cache.delete(url);\n throw error;\n });\n cache.set(url, pending);\n }\n return pending;\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport {\n TANSTACK_TABLE_CORE,\n TANSTACK_TABLE_CORE_MAJOR,\n} from \"../core/constants\";\nimport { InvalidArgumentError } from \"../core/errors\";\nimport { resolveUiDir } from \"./registry\";\n\n/** The components this package ships that are built on `@tanstack/table-core`. */\nexport const TABLE_CORE_COMPONENTS = [\n \"data-table\",\n \"column-header\",\n \"faceted-filter\",\n \"data-table-pagination\",\n];\n\nconst MIGRATION_GUIDE =\n \"https://tanstack.com/table/latest/docs/framework/svelte/guide/migrating\";\n\n/**\n * The major of the `@tanstack/table-core` range `package.json` declares, when\n * it names one (`^8.21.3` is 8; `latest` or `workspace:*` is undefined).\n */\nexport function declaredTableCoreMajor(root: string): number | undefined {\n const packageJsonPath = path.join(root, \"package.json\");\n if (!existsSync(packageJsonPath)) return undefined;\n const pkg = JSON.parse(readFileSync(packageJsonPath, \"utf8\")) as {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n };\n const range =\n pkg.dependencies?.[\"@tanstack/table-core\"] ??\n pkg.devDependencies?.[\"@tanstack/table-core\"];\n const major = range?.match(/^[\\^~>=v\\s]*(\\d+)/)?.[1];\n return major === undefined ? undefined : Number(major);\n}\n\n/** Whether the project's `data-table` helper is the v8 one (`createSvelteTable`). */\nfunction hasV8DataTable(root: string): boolean {\n const index = path.join(resolveUiDir(root), \"data-table\", \"index.ts\");\n return (\n existsSync(index) &&\n readFileSync(index, \"utf8\").includes(\"createSvelteTable\")\n );\n}\n\nfunction upgradeSteps(): string {\n return (\n \"Nothing was changed. To upgrade:\\n\" +\n ` 1. Install ${TANSTACK_TABLE_CORE}: npm install ${TANSTACK_TABLE_CORE}\\n` +\n ` 2. Replace the table helpers: vela ui add ${TABLE_CORE_COMPONENTS.join(\" \")} --overwrite\\n` +\n ` 3. Move existing list pages to the v9 API (createTable, tableFeatures): ${MIGRATION_GUIDE}\\n` +\n \"Then run this again.\"\n );\n}\n\n/**\n * Refuses a project still on TanStack Table v8, before anything is written.\n *\n * The scaffold list pages and the table helpers target v9. A project set up\n * before that has `@tanstack/table-core@^8` and v8 helpers; the package is\n * never upgraded by `installPackages` (it is already present) and the helpers\n * are never replaced (they already exist), so a new page would not compile,\n * and upgrading in place would break the list pages already there.\n */\nexport function assertTableCoreV9(root: string): void {\n const major = declaredTableCoreMajor(root);\n const outdatedPackage =\n major !== undefined && major < TANSTACK_TABLE_CORE_MAJOR;\n if (!outdatedPackage && !hasV8DataTable(root)) return;\n\n const found = outdatedPackage\n ? `package.json pins @tanstack/table-core ${major}.x`\n : \"its data-table helper is the v8 one (createSvelteTable)\";\n throw new InvalidArgumentError(\n `This project uses TanStack Table v8 (${found}), and scaffold list pages now need v${TANSTACK_TABLE_CORE_MAJOR}.\\n\\n` +\n upgradeSteps(),\n );\n}\n\n/**\n * Refuses to add v9 table helpers next to a v8 `@tanstack/table-core`, which\n * `installPackages` would leave in place.\n */\nexport function assertTableCorePackage(\n root: string,\n components: string[],\n): void {\n const tableComponents = components.filter((component) =>\n TABLE_CORE_COMPONENTS.includes(component),\n );\n if (tableComponents.length === 0) return;\n const major = declaredTableCoreMajor(root);\n if (major === undefined || major >= TANSTACK_TABLE_CORE_MAJOR) return;\n\n throw new InvalidArgumentError(\n `${tableComponents.join(\", \")} target${tableComponents.length === 1 ? \"s\" : \"\"} TanStack Table v${TANSTACK_TABLE_CORE_MAJOR}, and package.json pins @tanstack/table-core ${major}.x.\\n\\n` +\n `Nothing was changed. Install ${TANSTACK_TABLE_CORE} first (npm install ${TANSTACK_TABLE_CORE}), then run this again.`,\n );\n}\n\n/**\n * Whether `ui/pagination` is the table footer this package shipped under that\n * name (one `Pagination` taking a `table`), not shadcn-svelte's pagination,\n * whose index exports the parts (`Content`, `Item`, `Link`, ...).\n */\nfunction hasLegacyPagination(root: string): boolean {\n const index = path.join(resolveUiDir(root), \"pagination\", \"index.ts\");\n return existsSync(index) && !readFileSync(index, \"utf8\").includes(\"Content\");\n}\n\n/**\n * Refuses a project whose `ui/pagination` is still the old table footer,\n * before anything is written.\n *\n * The footer is `data-table-pagination` now, built on shadcn-svelte's\n * `pagination`, which installs to that same directory. A component that is\n * present is never replaced, so the new footer would import parts the old\n * file does not export; and replacing it in place would break the list pages\n * that render the old one.\n */\nexport function assertRegistryPagination(root: string): void {\n if (!hasLegacyPagination(root)) return;\n\n throw new InvalidArgumentError(\n \"This project's ui/pagination is the table footer older scaffolds used. The footer is now data-table-pagination, built on shadcn-svelte's pagination, which belongs in that directory.\\n\\n\" +\n \"Nothing was changed. To upgrade:\\n\" +\n \" 1. Replace ui/pagination with shadcn-svelte's: vela ui add pagination --overwrite\\n\" +\n \" 2. Add the new footer: vela ui add data-table-pagination\\n\" +\n ' 3. In existing list pages, import { DataTablePagination } from \"#lib/components/ui/data-table-pagination/index.js\"\\n' +\n \" in place of { Pagination }, and render <DataTablePagination {table} />.\\n\" +\n \"Then run this again.\",\n );\n}\n"],"mappings":";;;;;;AAeA,IAAMM,IAAsB;AAwB5B,SAASC,EAAe,GAAoC;CAC1D,OAAO,OAAOC,KAAU,YAAYA,EAAM,SAAS,IAAIA,IAAQ,KAAA;AACjE;AAOA,SAAgBC,EAAqB,GAAgC;CACnE,IAAIC,IAA2B,CAAC,GAC1BC,IAAaN,EAAK,KAAKO,GAAM,iBAAiB;CACpD,IAAIC,EAAWF,CAAU,GACvB,IAAI;EACF,IAAMG,IAAkB,KAAK,MAAMC,EAAaJ,GAAY,MAAM,CAAC;EACnE,AAAIG,KAAU,OAAOA,KAAW,aAC9B,IAAMA;CAEV,QAAQ;EACN,IAAM,CAAC;CACT;CAGF,IAAME,IAAkC,CAAC;CACzC,KAAK,IAAM,CAACC,GAAKT,MAAU,OAAO,QAAQE,EAAI,WAAW,CAAC,CAAC,GAAG;EAC5D,IAAMQ,IAAQX,EAAeC,CAAK;EAClC,AAAIU,MAAO,EAAQD,KAAOC;CAC5B;CAEA,OAAO;EACL,OAAOX,EAAeG,EAAI,KAAK,KAAA;EAC/B,UAAUH,EAAeG,EAAI,QAAQ,KAAA;EACrC,WAAWH,EAAeG,EAAI,UAAU,SAAS;EACjD,aAAaH,EAAeG,E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}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { r as e, t } from "./errors-DdSUZI8f.js";
|
|
2
2
|
import { n } from "./logger-t1HxmpG2.js";
|
|
3
|
-
import { a as r, i } from "./table-core-
|
|
4
|
-
import { a, i as o, n as s, o as c, r as l, s as u, t as d } from "./write-result-
|
|
3
|
+
import { a as r, i } from "./table-core-ux1xEJxN.js";
|
|
4
|
+
import { a, i as o, n as s, o as c, r as l, s as u, t as d } from "./write-result-DlB-id5k.js";
|
|
5
5
|
import { existsSync as f, readFileSync as p, writeFileSync as m } from "node:fs";
|
|
6
6
|
import h from "node:path";
|
|
7
7
|
import { createRequire as g } from "node:module";
|
|
@@ -169,4 +169,4 @@ async function N(e, t) {
|
|
|
169
169
|
}
|
|
170
170
|
export { M as applyBaseColor, N as applyTheme, C as listComponents, D as switchStyle };
|
|
171
171
|
|
|
172
|
-
//# sourceMappingURL=ui-
|
|
172
|
+
//# sourceMappingURL=ui-CpjUq_lm.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ui-DZuwcswv.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,EAA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AS,MAAMT,EAAWG,CAAI;CAgBpC,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"}
|
|
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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EACb,GACA,GACA,GAC4B;CAC5B,IAAMxD,IAAS,MAAMT,EAAWG,CAAI;CAgBpC,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"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { c as e } from "./constants-
|
|
1
|
+
import { c as e } from "./constants-E1I-__KI.js";
|
|
2
2
|
import t from "node:fs";
|
|
3
3
|
import n from "node:path";
|
|
4
4
|
// src/patterns/enable/whatsapp/runtime/whatsapp.ts
|
|
@@ -101,4 +101,4 @@ migrate(
|
|
|
101
101
|
}
|
|
102
102
|
export { o as a, a as i, c as n, u as o, s as r, i as t };
|
|
103
103
|
|
|
104
|
-
//# sourceMappingURL=whatsapp-
|
|
104
|
+
//# sourceMappingURL=whatsapp-DOSZ_zwn.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"whatsapp-
|
|
1
|
+
{"version":3,"file":"whatsapp-DOSZ_zwn.js","names":["MIGRATIONS_DIR","fs","path","PHONE_PATTERN","MIN_POCKETBASE_SERVER","hasWhatsAppPlugin","pb","error","setupWhatsAppFields","users","has","f","name","changed","fields","field","indexes","index","enableWhatsAppAuth","disableWhatsAppAuth","CONFIG_MIGRATION","writeWhatsAppConfigMigration","dir","options","file","enabled","config","whatsappConfigMigration"],"sources":["../../src/patterns/enable/whatsapp/runtime/whatsapp.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type PocketBase from \"pocketbase\";\nimport type { Options } from \"../../../../core/types\";\nimport { MIGRATIONS_DIR } from \"../../../../core/constants\";\n\n/** pocketbase-whatsapp's `PhonePattern`: E.164. */\nconst PHONE_PATTERN = \"^\\\\+[1-9][0-9]{7,14}$\";\n\n/** The first pocketbase-server with the plugin and its env-only sender. */\nexport const MIN_POCKETBASE_SERVER = \"0.40.5-beta.5\";\n\n/**\n * Whether the server has the pocketbase-whatsapp plugin that velabase ships.\n * Vanilla PocketBase and older pocketbase-server answer 404.\n */\nexport async function hasWhatsAppPlugin(pb: PocketBase): Promise<boolean> {\n try {\n await pb.send(\"/api/whatsapp/collections\", { method: \"GET\" });\n return true;\n } catch (error: any) {\n if (error?.status === 404) return false;\n throw error;\n }\n}\n\n/**\n * Gets `users` ready for WhatsApp sign-in:\n *\n * - `phone`: E.164 text with a unique index, the number users sign in with;\n * - `phoneVerified`: set once a code proves the number (`verified` is about\n * the email);\n * - `email` optional, since a WhatsApp signup has none.\n *\n * Through the collections API, not the plugin's \"Create phone field\"\n * endpoint: automigrate only writes a migration for collection changes made\n * over the API, so a save from inside the plugin would never reach\n * production.\n *\n * Returns whether `users` changed (and so wrote a migration).\n */\nexport async function setupWhatsAppFields(pb: PocketBase): Promise<boolean> {\n const users = await pb.collections.getOne(\"users\");\n const has = (name: string) =>\n users.fields.some((f: { name: string }) => f.name === name);\n\n let changed = false;\n const fields: Record<string, unknown>[] = users.fields.map(\n (field: Record<string, unknown>) => {\n if (field.name === \"email\" && field.required) {\n changed = true;\n return { ...field, required: false };\n }\n return field;\n },\n );\n if (!has(\"phone\")) {\n changed = true;\n fields.push({\n name: \"phone\",\n type: \"text\",\n pattern: PHONE_PATTERN,\n max: 16,\n });\n }\n if (!has(\"phoneVerified\")) {\n changed = true;\n fields.push({ name: \"phoneVerified\", type: \"bool\" });\n }\n\n const indexes = [...users.indexes];\n if (!indexes.some((index) => /\\(\\s*`?phone`?\\s*\\)/.test(index))) {\n changed = true;\n // Unique among the numbers that are set: email-only users have none.\n indexes.push(\n \"CREATE UNIQUE INDEX `idx_users_phone` ON `users` (`phone`) WHERE `phone` != ''\",\n );\n }\n\n if (changed) {\n await pb.collections.update(\"users\", { fields, indexes });\n }\n return changed;\n}\n\n/**\n * Turns WhatsApp sign-in and signup on for `users` in this PocketBase. The\n * plugin keeps that in its own store, which automigrate does not see, so\n * deployments get it from `writeWhatsAppConfigMigration` instead.\n *\n * With no sender configured yet, the sender is `dev`: codes go to the\n * PocketBase log. A deployment's env credentials take precedence over it.\n */\nexport async function enableWhatsAppAuth(pb: PocketBase): Promise<void> {\n await pb.send(\"/api/whatsapp/collections/users\", {\n method: \"PATCH\",\n body: {\n enabled: true,\n allowSignup: true,\n phoneField: \"phone\",\n phoneVerifiedField: \"phoneVerified\",\n },\n });\n\n const response = await pb.send(\"/api/whatsapp/settings\", { method: \"GET\" });\n if (!response?.settings?.mode) {\n await pb.send(\"/api/whatsapp/settings\", {\n method: \"PATCH\",\n body: { mode: \"dev\" },\n });\n }\n}\n\n/** Turns WhatsApp sign-in off for `users` in this PocketBase. */\nexport async function disableWhatsAppAuth(pb: PocketBase): Promise<void> {\n await pb.send(\"/api/whatsapp/collections/users\", {\n method: \"PATCH\",\n body: { enabled: false },\n });\n}\n\nconst CONFIG_MIGRATION = /^\\d+_(enabled|disabled)_whatsapp_users\\.js$/;\n\n/**\n * A migration that sets the plugin's `users` config (`_whatsapp`, key\n * `collection:<id>`) on every PocketBase it runs on. The plugin's own system\n * migration creates `_whatsapp` before any app migration runs.\n *\n * Returns `null`, writing nothing, when the latest such migration already\n * leaves WhatsApp in that state, so a re-run adds no migration.\n */\nexport function writeWhatsAppConfigMigration(\n options: Options,\n enabled: boolean,\n): string | null {\n const dir = path.join(options.root, MIGRATIONS_DIR);\n const latest = fs\n .readdirSync(dir)\n .filter((file) => CONFIG_MIGRATION.test(file))\n .sort()\n .pop();\n if (latest?.includes(enabled ? \"_enabled_\" : \"_disabled_\")) return null;\n\n const config = enabled\n ? {\n enabled: true,\n allowSignup: true,\n phoneField: \"phone\",\n phoneVerifiedField: \"phoneVerified\",\n }\n : { enabled: false };\n const name = `${Math.floor(Date.now() / 1000)}_${enabled ? \"enabled\" : \"disabled\"}_whatsapp_users.js`;\n const file = path.join(dir, name);\n fs.writeFileSync(file, whatsappConfigMigration(config), \"utf8\");\n return file;\n}\n\nfunction whatsappConfigMigration(config: Record<string, unknown>): string {\n return `/// <reference path=\"../pb_data/types.d.ts\" />\n\n// WhatsApp sign-in for users (pocketbase-whatsapp). The plugin keeps this in\n// \\`_whatsapp\\`, which automigrate does not see, so this migration carries it\n// to every deployment. The sender comes from the env (VELASTACK_API_KEY, or\n// WHATSAPP_ACCESS_TOKEN and co.), or Settings > WhatsApp.\nconst CONFIG = ${JSON.stringify(config)};\n\nfunction setConfig(app, values) {\n const users = app.findCollectionByNameOrId(\"users\");\n const key = \"collection:\" + users.id;\n\n let record;\n try {\n record = app.findFirstRecordByData(\"_whatsapp\", \"key\", key);\n } catch {\n record = new Record(app.findCollectionByNameOrId(\"_whatsapp\"));\n record.set(\"key\", key);\n }\n\n let current = {};\n try {\n current = JSON.parse(record.getString(\"value\") || \"{}\");\n } catch {}\n\n record.set(\"value\", JSON.stringify(Object.assign(current, values)));\n app.save(record);\n}\n\nmigrate(\n (app) => setConfig(app, CONFIG),\n (app) => setConfig(app, { enabled: !CONFIG.enabled }),\n);\n`;\n}\n"],"mappings":";;;;AAOA,IAAMG,IAAgB,yBAGTC,IAAwB;AAMrC,eAAsBC,EAAkB,GAAkC;CACxE,IAAI;EAEF,OADA,MAAMC,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