@velastack/patterns 0.15.0 → 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-BFUn0CG1.js +5 -0
- package/dist/chunks/{_page-6d3DCr0p.js.map → _page-BFUn0CG1.js.map} +1 -1
- package/dist/chunks/auth-pages-D8n8gfCL.js +311 -0
- package/dist/chunks/auth-pages-D8n8gfCL.js.map +1 -0
- package/dist/chunks/{collections-FKsKGtaH.js → collections-Daxlnbm0.js} +2 -2
- package/dist/chunks/{collections-FKsKGtaH.js.map → collections-Daxlnbm0.js.map} +1 -1
- package/dist/chunks/{constants-BHuzzsKu.js → constants-E1I-__KI.js} +20 -20
- package/dist/chunks/{constants-BHuzzsKu.js.map → constants-E1I-__KI.js.map} +1 -1
- package/dist/chunks/{currency.server-DRuEFc6D.js → currency.server-BkzwY17R.js} +2 -2
- package/dist/chunks/{currency.server-DRuEFc6D.js.map → currency.server-BkzwY17R.js.map} +1 -1
- package/dist/chunks/{env-vars-BcHu8247.js → env-vars-C3TSZc4f.js} +3 -3
- package/dist/chunks/{env-vars-BcHu8247.js.map → env-vars-C3TSZc4f.js.map} +1 -1
- package/dist/chunks/{generate-CXAKf1Hh.js → generate-CAYM7OUF.js} +2 -2
- package/dist/chunks/{generate-CXAKf1Hh.js.map → generate-CAYM7OUF.js.map} +1 -1
- package/dist/chunks/{generate-rcDj36TD.js → generate-CL7wG0ZC.js} +3 -3
- package/dist/chunks/{generate-rcDj36TD.js.map → generate-CL7wG0ZC.js.map} +1 -1
- package/dist/chunks/{generate-CkfJrlEg.js → generate-CbchamhA.js} +3 -3
- package/dist/chunks/{generate-CkfJrlEg.js.map → generate-CbchamhA.js.map} +1 -1
- package/dist/chunks/{generate-9O0VdZOl.js → generate-DI58vuk1.js} +2 -2
- package/dist/chunks/{generate-9O0VdZOl.js.map → generate-DI58vuk1.js.map} +1 -1
- package/dist/chunks/{generate-a3U8uDzW.js → generate-DR2wkVPY.js} +2 -2
- package/dist/chunks/{generate-a3U8uDzW.js.map → generate-DR2wkVPY.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BmdO8oKV.js → generate.runtime-B11mOr45.js} +3 -3
- package/dist/chunks/{generate.runtime-BmdO8oKV.js.map → generate.runtime-B11mOr45.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BDVPJJbh.js → generate.runtime-B1Y2JrGW.js} +5 -5
- package/dist/chunks/{generate.runtime-BDVPJJbh.js.map → generate.runtime-B1Y2JrGW.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Cxa24AOd.js → generate.runtime-B7VubPTW.js} +3 -3
- package/dist/chunks/{generate.runtime-Cxa24AOd.js.map → generate.runtime-B7VubPTW.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DsW0Q5S5.js → generate.runtime-BCv4F1Wm.js} +5 -5
- package/dist/chunks/{generate.runtime-DsW0Q5S5.js.map → generate.runtime-BCv4F1Wm.js.map} +1 -1
- package/dist/chunks/{generate.runtime-COo85dGX.js → generate.runtime-BEWp57Y7.js} +2 -2
- package/dist/chunks/{generate.runtime-COo85dGX.js.map → generate.runtime-BEWp57Y7.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BKsrh3ZN.js → generate.runtime-BH6hHygm.js} +3 -3
- package/dist/chunks/{generate.runtime-BKsrh3ZN.js.map → generate.runtime-BH6hHygm.js.map} +1 -1
- package/dist/chunks/{generate.runtime-D7EETq9M.js → generate.runtime-BL6DpWFI.js} +3 -3
- package/dist/chunks/{generate.runtime-D7EETq9M.js.map → generate.runtime-BL6DpWFI.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Dp3x08St.js → generate.runtime-BRV9hIl5.js} +2 -2
- package/dist/chunks/{generate.runtime-Dp3x08St.js.map → generate.runtime-BRV9hIl5.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CGbSe_nd.js → generate.runtime-BRcP6sFt.js} +2 -2
- package/dist/chunks/{generate.runtime-CGbSe_nd.js.map → generate.runtime-BRcP6sFt.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DcBEbV-k.js → generate.runtime-Bhs7ttZS.js} +2 -2
- package/dist/chunks/{generate.runtime-DcBEbV-k.js.map → generate.runtime-Bhs7ttZS.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BGLekCHZ.js → generate.runtime-BjrtdoYE.js} +2 -2
- package/dist/chunks/{generate.runtime-BGLekCHZ.js.map → generate.runtime-BjrtdoYE.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CtV9Gn9T.js → generate.runtime-Bo_s7gYB.js} +2 -2
- package/dist/chunks/{generate.runtime-CtV9Gn9T.js.map → generate.runtime-Bo_s7gYB.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CnGVlvxN.js → generate.runtime-Bs77Oc8P.js} +3 -3
- package/dist/chunks/{generate.runtime-CnGVlvxN.js.map → generate.runtime-Bs77Oc8P.js.map} +1 -1
- package/dist/chunks/{generate.runtime-B5SP9iyN.js → generate.runtime-C3IswX7B.js} +2 -2
- package/dist/chunks/{generate.runtime-B5SP9iyN.js.map → generate.runtime-C3IswX7B.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DtcKbzOm.js → generate.runtime-C90_2L-8.js} +3 -3
- package/dist/chunks/{generate.runtime-DtcKbzOm.js.map → generate.runtime-C90_2L-8.js.map} +1 -1
- package/dist/chunks/{generate.runtime-As1It8o7.js → generate.runtime-CDY0Ot_t.js} +6 -6
- package/dist/chunks/{generate.runtime-As1It8o7.js.map → generate.runtime-CDY0Ot_t.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CI_rUVZo.js → generate.runtime-CZMVPVjS.js} +6 -6
- package/dist/chunks/{generate.runtime-CI_rUVZo.js.map → generate.runtime-CZMVPVjS.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BYhWm9JA.js → generate.runtime-C_hrLPD4.js} +3 -3
- package/dist/chunks/{generate.runtime-BYhWm9JA.js.map → generate.runtime-C_hrLPD4.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BKA41qV0.js → generate.runtime-CdZ3GzPS.js} +6 -6
- package/dist/chunks/{generate.runtime-BKA41qV0.js.map → generate.runtime-CdZ3GzPS.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Cqbsn5Ov.js → generate.runtime-ChSVP7cD.js} +6 -6
- package/dist/chunks/{generate.runtime-Cqbsn5Ov.js.map → generate.runtime-ChSVP7cD.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BL7O2fy8.js → generate.runtime-Cs73i6Zf.js} +2 -2
- package/dist/chunks/{generate.runtime-BL7O2fy8.js.map → generate.runtime-Cs73i6Zf.js.map} +1 -1
- package/dist/chunks/{generate.runtime-C7NexMXs.js → generate.runtime-D7KYlnvb.js} +3 -3
- package/dist/chunks/{generate.runtime-C7NexMXs.js.map → generate.runtime-D7KYlnvb.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CTQvLaU0.js → generate.runtime-DG9LRwbt.js} +3 -3
- package/dist/chunks/{generate.runtime-CTQvLaU0.js.map → generate.runtime-DG9LRwbt.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DiAnQ9MW.js → generate.runtime-DKL7VAAd.js} +6 -6
- package/dist/chunks/{generate.runtime-DiAnQ9MW.js.map → generate.runtime-DKL7VAAd.js.map} +1 -1
- package/dist/chunks/{generate.runtime-DaJ4gLPv.js → generate.runtime-DP63Wwea.js} +4 -4
- package/dist/chunks/{generate.runtime-DaJ4gLPv.js.map → generate.runtime-DP63Wwea.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CFSBH8yG.js → generate.runtime-DRPxOLnB.js} +4 -4
- package/dist/chunks/{generate.runtime-CFSBH8yG.js.map → generate.runtime-DRPxOLnB.js.map} +1 -1
- package/dist/chunks/{generate.runtime-SZInujfP.js → generate.runtime-DW9bqOtC.js} +2 -2
- package/dist/chunks/{generate.runtime-SZInujfP.js.map → generate.runtime-DW9bqOtC.js.map} +1 -1
- package/dist/chunks/{generate.runtime-Cc5Aw1zc.js → generate.runtime-DdY44Ulv.js} +6 -6
- package/dist/chunks/{generate.runtime-Cc5Aw1zc.js.map → generate.runtime-DdY44Ulv.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BOtYaNA5.js → generate.runtime-DjEj-n6m.js} +7 -7
- package/dist/chunks/{generate.runtime-BOtYaNA5.js.map → generate.runtime-DjEj-n6m.js.map} +1 -1
- package/dist/chunks/{generate.runtime-ICaKVEuW.js → generate.runtime-DlAJQ5Js.js} +4 -4
- package/dist/chunks/{generate.runtime-ICaKVEuW.js.map → generate.runtime-DlAJQ5Js.js.map} +1 -1
- package/dist/chunks/{generate.runtime-4gS2ZHpj.js → generate.runtime-JftBoKYS.js} +5 -5
- package/dist/chunks/{generate.runtime-4gS2ZHpj.js.map → generate.runtime-JftBoKYS.js.map} +1 -1
- package/dist/chunks/{generate.runtime-B8t8HtB6.js → generate.runtime-_426A1Ij.js} +3 -3
- package/dist/chunks/{generate.runtime-B8t8HtB6.js.map → generate.runtime-_426A1Ij.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CyteiEzT.js → generate.runtime-fs6GEMx-.js} +5 -5
- package/dist/chunks/{generate.runtime-CyteiEzT.js.map → generate.runtime-fs6GEMx-.js.map} +1 -1
- package/dist/chunks/{generate.runtime-B9U3kzHD.js → generate.runtime-jIlQ2GMh.js} +2 -2
- package/dist/chunks/{generate.runtime-B9U3kzHD.js.map → generate.runtime-jIlQ2GMh.js.map} +1 -1
- package/dist/chunks/{generate.runtime-BY5VmBG4.js → generate.runtime-v3KCv1B6.js} +2 -2
- package/dist/chunks/{generate.runtime-BY5VmBG4.js.map → generate.runtime-v3KCv1B6.js.map} +1 -1
- package/dist/chunks/{generate.runtime-CG3udLj8.js → generate.runtime-xrxAElb3.js} +3 -3
- package/dist/chunks/{generate.runtime-CG3udLj8.js.map → generate.runtime-xrxAElb3.js.map} +1 -1
- package/dist/chunks/{gitignore-CPardo4E.js → gitignore-CBiWFRif.js} +3 -3
- package/dist/chunks/{gitignore-CPardo4E.js.map → gitignore-CBiWFRif.js.map} +1 -1
- package/dist/chunks/{i18n-C8OfN_nr.js → i18n-Ho8H91Ze.js} +3 -3
- package/dist/chunks/{i18n-C8OfN_nr.js.map → i18n-Ho8H91Ze.js.map} +1 -1
- package/dist/chunks/{modify-file-DvIwtj4o.js → modify-file-BOEKlIDw.js} +2 -2
- package/dist/chunks/{modify-file-DvIwtj4o.js.map → modify-file-BOEKlIDw.js.map} +1 -1
- package/dist/chunks/{pocketbase-Ir-TPv7H.js → pocketbase-B2ksFrvH.js} +2 -2
- package/dist/chunks/{pocketbase-Ir-TPv7H.js.map → pocketbase-B2ksFrvH.js.map} +1 -1
- package/dist/chunks/{providers-B386TYCN.js → providers-BEjDonyG.js} +2 -2
- package/dist/chunks/{providers-B386TYCN.js.map → providers-BEjDonyG.js.map} +1 -1
- package/dist/chunks/{route-BJBV1DtX.js → route-9ZVJZkYu.js} +23 -19
- package/dist/chunks/route-9ZVJZkYu.js.map +1 -0
- package/dist/chunks/{schema-DSNYWlel.js → schema-DnMqw2Hn.js} +3 -3
- package/dist/chunks/{schema-DSNYWlel.js.map → schema-DnMqw2Hn.js.map} +1 -1
- package/dist/chunks/{shared-CZHopdly.js → shared-CSwGWMcN.js} +2 -2
- package/dist/chunks/{shared-CZHopdly.js.map → shared-CSwGWMcN.js.map} +1 -1
- package/dist/chunks/{shared-BofFBVmT.js → shared-Cdwm_-Nl.js} +40 -40
- package/dist/chunks/{shared-BofFBVmT.js.map → shared-Cdwm_-Nl.js.map} +1 -1
- package/dist/chunks/{site-B9-emR6D.js → site-B5zrFba9.js} +2 -2
- package/dist/chunks/{site-B9-emR6D.js.map → site-B5zrFba9.js.map} +1 -1
- package/dist/chunks/{table-core-CHsfbi-n.js → table-core-ux1xEJxN.js} +2 -2
- package/dist/chunks/{table-core-CHsfbi-n.js.map → table-core-ux1xEJxN.js.map} +1 -1
- package/dist/chunks/{translations-CiJnl574.js → translations-B5hX0Qq-.js} +5 -2
- package/dist/chunks/{translations-CiJnl574.js.map → translations-B5hX0Qq-.js.map} +1 -1
- package/dist/chunks/{ui-BUhkIHse.js → ui-CpjUq_lm.js} +3 -3
- package/dist/chunks/{ui-BUhkIHse.js.map → ui-CpjUq_lm.js.map} +1 -1
- package/dist/chunks/{whatsapp-DFZUsKWe.js → whatsapp-DOSZ_zwn.js} +2 -2
- package/dist/chunks/{whatsapp-DFZUsKWe.js.map → whatsapp-DOSZ_zwn.js.map} +1 -1
- package/dist/chunks/{write-result-Bkdkp7u2.js → write-result-DlB-id5k.js} +50 -26
- package/dist/chunks/write-result-DlB-id5k.js.map +1 -0
- package/dist/index.js +1864 -1842
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
- package/dist/chunks/_page-6d3DCr0p.js +0 -5
- package/dist/chunks/auth-pages-DHzh31mw.js +0 -285
- package/dist/chunks/auth-pages-DHzh31mw.js.map +0 -1
- package/dist/chunks/route-BJBV1DtX.js.map +0 -1
- package/dist/chunks/write-result-Bkdkp7u2.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"site-B9-emR6D.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,G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I,IAAkB,CAAC;CACzB,KAAK,IAAMzC,KAAOuC,GAAQ;EACxB,IAAIC,EAASxC,OAAS,KAAA,GAAW;EACjC,IAAM0C,IAAOtB,EAAiBE,GAAQtB,GAAKF,EAASE,EAAK;EACzD,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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AQtB,GAAKF,EAASE,EAAK;EACzD,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,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-CHsfbi-n.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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ArgumentError","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;CAC5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vC,EAAauC,GAAO,MAAM,CAAC,CAAC,SAAS,SAAS;AAC7E;AAYA,SAAgBT,EAAyB,GAAoB;CAC3D,IAAKiB,EAAoBlD,CAAI,GAE7B,MAAM,IAAIT,EACR,kmBAOF;AACF"}
|
|
@@ -121,7 +121,10 @@ var f = "src/routes/(public)/(auth)", p = "src/routes/(app)", m = `${f}/login/+p
|
|
|
121
121
|
"Remembered your password? <0>Log in</0>": "¿Recordaste tu contraseña? <0>Inicia sesión</0>"
|
|
122
122
|
}),
|
|
123
123
|
..._(`${f}/reset/+page.ts`, { "Reset password": "Restablecer contraseña" }),
|
|
124
|
-
..._(`${f}/reset/+page.server.ts`, {
|
|
124
|
+
..._(`${f}/reset/+page.server.ts`, {
|
|
125
|
+
"We sent a password reset link to your email.": "Te enviamos un enlace a tu correo para restablecer tu contraseña.",
|
|
126
|
+
"We could not send the reset link. Try again in a moment.": "No pudimos enviar el enlace. Inténtalo de nuevo en un momento."
|
|
127
|
+
}),
|
|
125
128
|
..._(`${f}/confirm-reset/[token]/+page.svelte`, { "Enter your new password": "Escribe tu nueva contraseña" }),
|
|
126
129
|
..._(`${f}/confirm-reset/[token]/+page.ts`, { "Confirm password reset": "Confirmar restablecimiento de contraseña" }),
|
|
127
130
|
..._(`${f}/confirm-reset/[token]/+page.server.ts`, { "Password reset successfully.": "Tu contraseña se restableció correctamente." }),
|
|
@@ -186,4 +189,4 @@ var f = "src/routes/(public)/(auth)", p = "src/routes/(app)", m = `${f}/login/+p
|
|
|
186
189
|
];
|
|
187
190
|
export { c as a, d as i, l as n, u as r, v as t };
|
|
188
191
|
|
|
189
|
-
//# sourceMappingURL=translations-
|
|
192
|
+
//# sourceMappingURL=translations-B5hX0Qq-.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"translations-CiJnl574.js","names":["fs","path","SPANISH_CATALOG","HEADER","quote","text","unquote","char","field","lines","block","at","line","keyword","parts","i","part","entryBlock","entry","withTranslations","blocks","source","byMsgid","msgid","index","changed","entries","entriesInProject","present","root","hasSpanish","configPath","locales","translateCatalog","none","catalogPath","result","AUTH","APP","LOGIN","SIGNUP","SETTINGS","messages","translations","msgstr","AUTH_TRANSLATIONS"],"sources":["../../src/runtime/wuchale-catalog.ts","../../src/patterns/enable/auth/translations.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File } from \"../core/types\";\n\n/**\n * `src/locales/es.po`: the Spanish a pattern ships for the pages it writes.\n *\n * enable-i18n sets a project up with English and Spanish, and wuchale leaves\n * a message it has no translation for in English without saying so. A pattern\n * whose pages a visitor reads keeps the Spanish for them as a list of\n * entries; whichever of the two patterns is enabled second merges that list\n * into the catalog: enable-i18n for the pages already in the project, the\n * other pattern for its own pages when the project already has i18n.\n *\n * Only what is missing is filled in. A translation the developer wrote, or\n * changed, is never replaced.\n */\nexport const SPANISH_CATALOG = \"src/locales/es.po\";\n\nexport interface CatalogEntry {\n /** The message as wuchale extracts it (`Don't have an account? <0>Sign up</0>`). */\n msgid: string;\n msgstr: string;\n /** A file the message is in, relative to the project root. */\n reference: string;\n}\n\n// What wuchale writes for `es`. It rewrites the file on the next extraction,\n// keeping the translations and adding the source locale's catalog.\nconst HEADER = [\n 'msgid \"\"',\n 'msgstr \"\"',\n '\"Source-Language: en\\\\n\"',\n '\"Language: es\\\\n\"',\n '\"MIME-Version: 1.0\\\\n\"',\n '\"Content-Type: text/plain; charset=utf-8\\\\n\"',\n '\"Content-Transfer-Encoding: 8bit\\\\n\"',\n '\"Plural-Forms: nplurals=3\\\\n\"',\n '\"X-Plurals-Order: one, many, other\\\\n\"',\n].join(\"\\n\");\n\nconst quote = (text: string) =>\n `\"${text.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"').replace(/\\n/g, \"\\\\n\")}\"`;\n\nconst unquote = (text: string) =>\n text.replace(/\\\\(.)/g, (_, char: string) => (char === \"n\" ? \"\\n\" : char));\n\n/** A `msgid` or `msgstr` value: the quoted string, and any continuation lines. */\nfunction field(block: string, keyword: \"msgid\" | \"msgstr\"): string | null {\n const lines = block.split(\"\\n\");\n const at = lines.findIndex((line) => line.startsWith(`${keyword} \"`));\n if (at === -1) return null;\n const parts = [lines[at].slice(keyword.length + 1)];\n for (let i = at + 1; i < lines.length && lines[i].startsWith('\"'); i++) {\n parts.push(lines[i]);\n }\n return parts.map((part) => unquote(part.trim().slice(1, -1))).join(\"\");\n}\n\nfunction entryBlock(entry: CatalogEntry): string {\n return [\n `#: ${entry.reference}`,\n `msgid ${quote(entry.msgid)}`,\n `msgstr ${quote(entry.msgstr)}`,\n ].join(\"\\n\");\n}\n\n/**\n * `source` (a `.po` catalog, or null for a project that has none yet) with\n * `entries` filled in: an entry the catalog lacks is added, one it holds\n * untranslated gets its translation, and one that is translated is left as\n * it is. Plural and context entries are not touched.\n */\nexport function withTranslations(\n source: string | null,\n entries: CatalogEntry[],\n): { source: string; changed: boolean } {\n const blocks = (source ?? HEADER).replace(/\\s+$/, \"\").split(/\\n{2,}/);\n const byMsgid = new Map<string, number>();\n blocks.forEach((block, index) => {\n if (block.includes(\"\\nmsgctxt \") || block.startsWith(\"msgctxt \")) return;\n if (block.includes(\"\\nmsgid_plural \")) return;\n const msgid = field(block, \"msgid\");\n if (msgid) byMsgid.set(msgid, index);\n });\n\n let changed = source === null;\n for (const entry of entries) {\n const index = byMsgid.get(entry.msgid);\n if (index === undefined) {\n byMsgid.set(entry.msgid, blocks.length);\n blocks.push(entryBlock(entry));\n changed = true;\n continue;\n }\n if (field(blocks[index], \"msgstr\") !== \"\") continue;\n // The untranslated `msgstr \"\"` is the last field of its block.\n blocks[index] = blocks[index].replace(\n /^msgstr \"\"$/m,\n `msgstr ${quote(entry.msgstr)}`,\n );\n changed = true;\n }\n\n return {\n source: changed ? blocks.join(\"\\n\\n\") + \"\\n\" : (source ?? \"\"),\n changed,\n };\n}\n\n/** The entries whose file is in the project. */\nexport function entriesInProject(\n root: string,\n entries: CatalogEntry[],\n): CatalogEntry[] {\n const present = new Map<string, boolean>();\n return entries.filter((entry) => {\n if (!present.has(entry.reference)) {\n present.set(\n entry.reference,\n fs.existsSync(path.join(root, entry.reference)),\n );\n }\n return present.get(entry.reference);\n });\n}\n\n/**\n * Whether the project's wuchale config still lists Spanish: `locales` is the\n * developer's to change, and a pattern does not bring a language back.\n */\nexport function hasSpanish(root: string): boolean {\n const configPath = path.join(root, \"wuchale.config.js\");\n if (!fs.existsSync(configPath)) return false;\n const locales = /\\blocales\\s*:\\s*\\[([^\\]]*)\\]/.exec(\n fs.readFileSync(configPath, \"utf8\"),\n );\n return locales !== null && /[\"']es[\"']/.test(locales[1]);\n}\n\n/**\n * Merge `entries` into the project's Spanish catalog. An existing catalog is\n * edited in place and returned as a modify; a project without one gets it as\n * a create, for the pattern's result to write. Both are empty when there is\n * nothing to add.\n */\nexport function translateCatalog(\n root: string,\n entries: CatalogEntry[],\n): { create: File | null; modify: File | null } {\n const none = { create: null, modify: null };\n if (entries.length === 0) return none;\n\n const catalogPath = path.join(root, SPANISH_CATALOG);\n if (!fs.existsSync(catalogPath)) {\n return {\n create: {\n path: SPANISH_CATALOG,\n language: \"text\",\n content: withTranslations(null, entries).source,\n status: \"success\",\n },\n modify: null,\n };\n }\n\n const result = withTranslations(\n fs.readFileSync(catalogPath, \"utf8\"),\n entries,\n );\n if (!result.changed) return none;\n fs.writeFileSync(catalogPath, result.source);\n return {\n create: null,\n modify: {\n path: catalogPath,\n language: \"text\",\n content: result.source,\n status: \"success\",\n },\n };\n}\n","import type { CatalogEntry } from \"../../../runtime/wuchale-catalog\";\n\nconst AUTH = \"src/routes/(public)/(auth)\";\nconst APP = \"src/routes/(app)\";\nconst LOGIN = `${AUTH}/login/+page.svelte`;\nconst SIGNUP = `${AUTH}/signup/+page.svelte`;\nconst SETTINGS = `${APP}/settings/+page.svelte`;\n\n/** The messages of one file, keyed by the text wuchale extracts. */\nconst messages = (\n reference: string,\n translations: Record<string, string>,\n): CatalogEntry[] =>\n Object.entries(translations).map(([msgid, msgstr]) => ({\n reference,\n msgid,\n msgstr,\n }));\n\n/**\n * Spanish for what enable-auth and enable-auth-remote write: the sign-in\n * pages, the signed-in shell and settings page, and the links they add to the\n * public navbar. Merged into `src/locales/es.po` by whichever of the auth\n * pattern and enable-i18n runs second (see `runtime/wuchale-catalog`).\n *\n * The keys are the messages as wuchale extracts them from the templates in\n * each pattern's `creates/`, so a template whose text changes needs its key\n * changed here: a\n * key that matches nothing is carried in the catalog and never shown. A\n * message used by several files is listed once, under the first.\n */\nexport const AUTH_TRANSLATIONS: CatalogEntry[] = [\n // The navbar links are in the root layout, which a project has with or\n // without auth, so they are filed under the page they lead to.\n ...messages(LOGIN, {\n Login: \"Iniciar sesión\",\n Logout: \"Cerrar sesión\",\n Settings: \"Configuración\",\n Dashboard: \"Panel\",\n\n \"Choose a login method\": \"Elige cómo iniciar sesión\",\n \"Use your email to login\": \"Usa tu correo para iniciar sesión\",\n \"Welcome back\": \"Qué gusto verte de nuevo\",\n \"Login is disabled\": \"El inicio de sesión está desactivado\",\n \"Check back later for login options\":\n \"Vuelve más tarde para ver las opciones de inicio de sesión\",\n \"<0/> Login with {0}\": \"<0/> Iniciar sesión con {0}\",\n \"Or continue with\": \"O continúa con\",\n Email: \"Correo electrónico\",\n Password: \"Contraseña\",\n \"Forgot your password?\": \"¿Olvidaste tu contraseña?\",\n \"Use one-time code instead\": \"Usar un código de un solo uso\",\n \"Continue with password\": \"Continuar con contraseña\",\n \"Send one-time code\": \"Enviar código de un solo uso\",\n \"Don't have an account? <0>Sign up</0>\":\n \"¿No tienes una cuenta? <0>Regístrate</0>\",\n \"By clicking continue, you agree to our <0>Terms of Service</0> and <1>Privacy Policy</1>.\":\n \"Al continuar, aceptas nuestros <0>Términos del servicio</0> y nuestra <1>Política de privacidad</1>.\",\n }),\n ...messages(`${AUTH}/login/+page.ts`, {\n \"Log in\": \"Iniciar sesión\",\n }),\n\n ...messages(SIGNUP, {\n \"Choose a sign up method\": \"Elige cómo registrarte\",\n \"Use your email to sign up\": \"Usa tu correo para registrarte\",\n \"Create an account\": \"Crea una cuenta\",\n \"Signups are disabled\": \"El registro está desactivado\",\n \"Check back later for signup options\":\n \"Vuelve más tarde para ver las opciones de registro\",\n \"<0/> Sign up with {0}\": \"<0/> Registrarte con {0}\",\n \"Confirm Password\": \"Confirmar contraseña\",\n \"Create account\": \"Crear cuenta\",\n \"Already have an account? <0>Log in</0>\":\n \"¿Ya tienes una cuenta? <0>Inicia sesión</0>\",\n }),\n ...messages(`${AUTH}/signup/+page.ts`, {\n \"Sign up\": \"Crear cuenta\",\n }),\n ...messages(`${AUTH}/signup/+page.server.ts`, {\n \"Failed to send the code.\": \"No pudimos enviar el código.\",\n \"We sent a confirmation link to your email.\":\n \"Te enviamos un enlace de confirmación a tu correo.\",\n }),\n\n ...messages(`${AUTH}/reset/+page.svelte`, {\n \"Reset your password\": \"Restablece tu contraseña\",\n \"Enter your email to reset your password\":\n \"Escribe tu correo para restablecer tu contraseña\",\n \"Send reset link\": \"Enviar enlace\",\n \"Remembered your password? <0>Log in</0>\":\n \"¿Recordaste tu contraseña? <0>Inicia sesión</0>\",\n }),\n ...messages(`${AUTH}/reset/+page.ts`, {\n \"Reset password\": \"Restablecer contraseña\",\n }),\n ...messages(`${AUTH}/reset/+page.server.ts`, {\n \"We sent a password reset link to your email.\":\n \"Te enviamos un enlace a tu correo para restablecer tu contraseña.\",\n }),\n\n ...messages(`${AUTH}/confirm-reset/[token]/+page.svelte`, {\n \"Enter your new password\": \"Escribe tu nueva contraseña\",\n }),\n ...messages(`${AUTH}/confirm-reset/[token]/+page.ts`, {\n \"Confirm password reset\": \"Confirmar restablecimiento de contraseña\",\n }),\n ...messages(`${AUTH}/confirm-reset/[token]/+page.server.ts`, {\n \"Password reset successfully.\":\n \"Tu contraseña se restableció correctamente.\",\n }),\n\n ...messages(`${AUTH}/confirm-email-change/[token]/+page.svelte`, {\n \"Confirm email change\": \"Confirmar cambio de correo\",\n \"Confirm your email change\": \"Confirma el cambio de correo\",\n \"Enter your password to confirm your email change\":\n \"Escribe tu contraseña para confirmar el cambio de correo\",\n }),\n ...messages(`${AUTH}/confirm-email-change/[token]/+page.server.ts`, {\n \"Email changed successfully.\": \"Tu correo se cambió correctamente.\",\n }),\n\n ...messages(`${AUTH}/otp/[token]/+page.svelte`, {\n \"Verify code\": \"Verificar código\",\n \"Enter your OTP code\": \"Escribe tu código\",\n \"Enter the code sent to your email\":\n \"Escribe el código que enviamos a tu correo\",\n \"OTP code\": \"Código de un solo uso\",\n }),\n\n ...messages(`${AUTH}/welcome/+page.svelte`, {\n \"Welcome!\": \"¡Te damos la bienvenida!\",\n \"What should we call you?\": \"¿Cómo quieres que te llamemos?\",\n Name: \"Nombre\",\n Continue: \"Continuar\",\n \"Skip for now\": \"Omitir por ahora\",\n }),\n ...messages(`${AUTH}/welcome/+page.ts`, {\n Welcome: \"Bienvenida\",\n }),\n\n ...messages(`${APP}/+layout.server.ts`, {\n Home: \"Inicio\",\n }),\n ...messages(\"src/lib/components/nav-user.svelte\", {\n \"<0/> Light mode\": \"<0/> Modo claro\",\n \"<0/> Dark mode\": \"<0/> Modo oscuro\",\n \"<0/> Log out\": \"<0/> Cerrar sesión\",\n }),\n\n ...messages(SETTINGS, {\n Profile: \"Perfil\",\n \"Your profile information.\": \"La información de tu perfil.\",\n Avatar: \"Avatar\",\n \"Upload a new avatar for your profile.\":\n \"Sube un nuevo avatar para tu perfil.\",\n \"Remove avatar\": \"Quitar avatar\",\n \"Upload new picture\": \"Subir nueva foto\",\n \"Display email publicly\": \"Mostrar mi correo públicamente\",\n \"By clicking this checkbox, your email will be displayed publicly.\":\n \"Al marcar esta casilla, tu correo se mostrará públicamente.\",\n \"Save changes\": \"Guardar cambios\",\n \"The email address associated with your account.\":\n \"El correo electrónico asociado a tu cuenta.\",\n Verified: \"Verificado\",\n Unverified: \"Sin verificar\",\n \"Resend verification email\": \"Reenviar correo de verificación\",\n \"Change email\": \"Cambiar correo\",\n \"Enter your new email address. You will receive a verification email.\":\n \"Escribe tu nuevo correo electrónico. Recibirás un correo de verificación.\",\n \"Your password is used to log in to your account.\":\n \"Tu contraseña se usa para iniciar sesión en tu cuenta.\",\n \"New password\": \"Nueva contraseña\",\n \"Confirm new password\": \"Confirmar nueva contraseña\",\n \"Update password\": \"Actualizar contraseña\",\n }),\n ...messages(`${APP}/settings/+page.server.ts`, {\n \"Profile updated successfully.\": \"Tu perfil se actualizó correctamente.\",\n \"We sent a confirmation link to your new email.\":\n \"Te enviamos un enlace de confirmación a tu nuevo correo.\",\n \"Password updated successfully.\":\n \"Tu contraseña se actualizó correctamente.\",\n \"Your account has no email.\": \"Tu cuenta no tiene correo.\",\n \"We sent a verification email to your email.\":\n \"Te enviamos un correo de verificación.\",\n }),\n\n // enable-auth-remote writes the same pages at the same paths, so everything\n // above covers it. These are the messages only it has, filed under its\n // remote functions so a project with the form-action pages is not handed\n // them.\n ...messages(`${AUTH}/login/form.remote.ts`, {\n \"Failed to authenticate.\": \"No pudimos iniciar tu sesión.\",\n }),\n ...messages(`${AUTH}/signup/form.remote.ts`, {\n \"Failed to create account.\": \"No pudimos crear tu cuenta.\",\n }),\n ...messages(`${AUTH}/otp/[token]/form.remote.ts`, {\n \"Failed to verify code.\": \"No pudimos verificar el código.\",\n }),\n ...messages(`${APP}/settings/form.remote.ts`, {\n \"Upload new picture <0/>\": \"Subir nueva foto <0/>\",\n }),\n];\n"],"mappings":";;;AAiBA,IAAaE,IAAkB,qBAYzBC,IAAS,yQAYTC,KAAS,MACb,IAAIC,EAAK,QAAQ,OAAO,MAAM,CAAC,CAAC,QAAQ,MAAM,MAAK,CAAC,CAAC,QAAQ,OAAO,KAAK,EAAE,IAEvEC,KAAW,MACfD,EAAK,QAAQ,WAAW,GAAG,MAAkBE,MAAS,MAAM,OAAOA,CAAK;AAG1E,SAASC,EAAM,GAAe,GAA4C;CACxE,IAAMC,IAAQC,EAAM,MAAM,IAAI,GACxBC,IAAKF,EAAM,WAAW,MAASG,EAAK,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B,EAC3C,6BAA6B,8BAC/B,CAAC;CACD,GAAGK,EAAS,GAAGL,EAAK,8BAA8B,EAChD,0BAA0B,kCAC5B,CAAC;CACD,GAAGK,EAAS,GAAGJ,EAAI,2BAA2B,EAC5C,2BAA2B,wBAC7B,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"translations-B5hX0Qq-.js","names":["fs","path","SPANISH_CATALOG","HEADER","quote","text","unquote","char","field","lines","block","at","line","keyword","parts","i","part","entryBlock","entry","withTranslations","blocks","source","byMsgid","msgid","index","changed","entries","entriesInProject","present","root","hasSpanish","configPath","locales","translateCatalog","none","catalogPath","result","AUTH","APP","LOGIN","SIGNUP","SETTINGS","messages","translations","msgstr","AUTH_TRANSLATIONS"],"sources":["../../src/runtime/wuchale-catalog.ts","../../src/patterns/enable/auth/translations.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { File } from \"../core/types\";\n\n/**\n * `src/locales/es.po`: the Spanish a pattern ships for the pages it writes.\n *\n * enable-i18n sets a project up with English and Spanish, and wuchale leaves\n * a message it has no translation for in English without saying so. A pattern\n * whose pages a visitor reads keeps the Spanish for them as a list of\n * entries; whichever of the two patterns is enabled second merges that list\n * into the catalog: enable-i18n for the pages already in the project, the\n * other pattern for its own pages when the project already has i18n.\n *\n * Only what is missing is filled in. A translation the developer wrote, or\n * changed, is never replaced.\n */\nexport const SPANISH_CATALOG = \"src/locales/es.po\";\n\nexport interface CatalogEntry {\n /** The message as wuchale extracts it (`Don't have an account? <0>Sign up</0>`). */\n msgid: string;\n msgstr: string;\n /** A file the message is in, relative to the project root. */\n reference: string;\n}\n\n// What wuchale writes for `es`. It rewrites the file on the next extraction,\n// keeping the translations and adding the source locale's catalog.\nconst HEADER = [\n 'msgid \"\"',\n 'msgstr \"\"',\n '\"Source-Language: en\\\\n\"',\n '\"Language: es\\\\n\"',\n '\"MIME-Version: 1.0\\\\n\"',\n '\"Content-Type: text/plain; charset=utf-8\\\\n\"',\n '\"Content-Transfer-Encoding: 8bit\\\\n\"',\n '\"Plural-Forms: nplurals=3\\\\n\"',\n '\"X-Plurals-Order: one, many, other\\\\n\"',\n].join(\"\\n\");\n\nconst quote = (text: string) =>\n `\"${text.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"').replace(/\\n/g, \"\\\\n\")}\"`;\n\nconst unquote = (text: string) =>\n text.replace(/\\\\(.)/g, (_, char: string) => (char === \"n\" ? \"\\n\" : char));\n\n/** A `msgid` or `msgstr` value: the quoted string, and any continuation lines. */\nfunction field(block: string, keyword: \"msgid\" | \"msgstr\"): string | null {\n const lines = block.split(\"\\n\");\n const at = lines.findIndex((line) => line.startsWith(`${keyword} \"`));\n if (at === -1) return null;\n const parts = [lines[at].slice(keyword.length + 1)];\n for (let i = at + 1; i < lines.length && lines[i].startsWith('\"'); i++) {\n parts.push(lines[i]);\n }\n return parts.map((part) => unquote(part.trim().slice(1, -1))).join(\"\");\n}\n\nfunction entryBlock(entry: CatalogEntry): string {\n return [\n `#: ${entry.reference}`,\n `msgid ${quote(entry.msgid)}`,\n `msgstr ${quote(entry.msgstr)}`,\n ].join(\"\\n\");\n}\n\n/**\n * `source` (a `.po` catalog, or null for a project that has none yet) with\n * `entries` filled in: an entry the catalog lacks is added, one it holds\n * untranslated gets its translation, and one that is translated is left as\n * it is. Plural and context entries are not touched.\n */\nexport function withTranslations(\n source: string | null,\n entries: CatalogEntry[],\n): { source: string; changed: boolean } {\n const blocks = (source ?? HEADER).replace(/\\s+$/, \"\").split(/\\n{2,}/);\n const byMsgid = new Map<string, number>();\n blocks.forEach((block, index) => {\n if (block.includes(\"\\nmsgctxt \") || block.startsWith(\"msgctxt \")) return;\n if (block.includes(\"\\nmsgid_plural \")) return;\n const msgid = field(block, \"msgid\");\n if (msgid) byMsgid.set(msgid, index);\n });\n\n let changed = source === null;\n for (const entry of entries) {\n const index = byMsgid.get(entry.msgid);\n if (index === undefined) {\n byMsgid.set(entry.msgid, blocks.length);\n blocks.push(entryBlock(entry));\n changed = true;\n continue;\n }\n if (field(blocks[index], \"msgstr\") !== \"\") continue;\n // The untranslated `msgstr \"\"` is the last field of its block.\n blocks[index] = blocks[index].replace(\n /^msgstr \"\"$/m,\n `msgstr ${quote(entry.msgstr)}`,\n );\n changed = true;\n }\n\n return {\n source: changed ? blocks.join(\"\\n\\n\") + \"\\n\" : (source ?? \"\"),\n changed,\n };\n}\n\n/** The entries whose file is in the project. */\nexport function entriesInProject(\n root: string,\n entries: CatalogEntry[],\n): CatalogEntry[] {\n const present = new Map<string, boolean>();\n return entries.filter((entry) => {\n if (!present.has(entry.reference)) {\n present.set(\n entry.reference,\n fs.existsSync(path.join(root, entry.reference)),\n );\n }\n return present.get(entry.reference);\n });\n}\n\n/**\n * Whether the project's wuchale config still lists Spanish: `locales` is the\n * developer's to change, and a pattern does not bring a language back.\n */\nexport function hasSpanish(root: string): boolean {\n const configPath = path.join(root, \"wuchale.config.js\");\n if (!fs.existsSync(configPath)) return false;\n const locales = /\\blocales\\s*:\\s*\\[([^\\]]*)\\]/.exec(\n fs.readFileSync(configPath, \"utf8\"),\n );\n return locales !== null && /[\"']es[\"']/.test(locales[1]);\n}\n\n/**\n * Merge `entries` into the project's Spanish catalog. An existing catalog is\n * edited in place and returned as a modify; a project without one gets it as\n * a create, for the pattern's result to write. Both are empty when there is\n * nothing to add.\n */\nexport function translateCatalog(\n root: string,\n entries: CatalogEntry[],\n): { create: File | null; modify: File | null } {\n const none = { create: null, modify: null };\n if (entries.length === 0) return none;\n\n const catalogPath = path.join(root, SPANISH_CATALOG);\n if (!fs.existsSync(catalogPath)) {\n return {\n create: {\n path: SPANISH_CATALOG,\n language: \"text\",\n content: withTranslations(null, entries).source,\n status: \"success\",\n },\n modify: null,\n };\n }\n\n const result = withTranslations(\n fs.readFileSync(catalogPath, \"utf8\"),\n entries,\n );\n if (!result.changed) return none;\n fs.writeFileSync(catalogPath, result.source);\n return {\n create: null,\n modify: {\n path: catalogPath,\n language: \"text\",\n content: result.source,\n status: \"success\",\n },\n };\n}\n","import type { CatalogEntry } from \"../../../runtime/wuchale-catalog\";\n\nconst AUTH = \"src/routes/(public)/(auth)\";\nconst APP = \"src/routes/(app)\";\nconst LOGIN = `${AUTH}/login/+page.svelte`;\nconst SIGNUP = `${AUTH}/signup/+page.svelte`;\nconst SETTINGS = `${APP}/settings/+page.svelte`;\n\n/** The messages of one file, keyed by the text wuchale extracts. */\nconst messages = (\n reference: string,\n translations: Record<string, string>,\n): CatalogEntry[] =>\n Object.entries(translations).map(([msgid, msgstr]) => ({\n reference,\n msgid,\n msgstr,\n }));\n\n/**\n * Spanish for what enable-auth and enable-auth-remote write: the sign-in\n * pages, the signed-in shell and settings page, and the links they add to the\n * public navbar. Merged into `src/locales/es.po` by whichever of the auth\n * pattern and enable-i18n runs second (see `runtime/wuchale-catalog`).\n *\n * The keys are the messages as wuchale extracts them from the templates in\n * each pattern's `creates/`, so a template whose text changes needs its key\n * changed here: a\n * key that matches nothing is carried in the catalog and never shown. A\n * message used by several files is listed once, under the first.\n */\nexport const AUTH_TRANSLATIONS: CatalogEntry[] = [\n // The navbar links are in the root layout, which a project has with or\n // without auth, so they are filed under the page they lead to.\n ...messages(LOGIN, {\n Login: \"Iniciar sesión\",\n Logout: \"Cerrar sesión\",\n Settings: \"Configuración\",\n Dashboard: \"Panel\",\n\n \"Choose a login method\": \"Elige cómo iniciar sesión\",\n \"Use your email to login\": \"Usa tu correo para iniciar sesión\",\n \"Welcome back\": \"Qué gusto verte de nuevo\",\n \"Login is disabled\": \"El inicio de sesión está desactivado\",\n \"Check back later for login options\":\n \"Vuelve más tarde para ver las opciones de inicio de sesión\",\n \"<0/> Login with {0}\": \"<0/> Iniciar sesión con {0}\",\n \"Or continue with\": \"O continúa con\",\n Email: \"Correo electrónico\",\n Password: \"Contraseña\",\n \"Forgot your password?\": \"¿Olvidaste tu contraseña?\",\n \"Use one-time code instead\": \"Usar un código de un solo uso\",\n \"Continue with password\": \"Continuar con contraseña\",\n \"Send one-time code\": \"Enviar código de un solo uso\",\n \"Don't have an account? <0>Sign up</0>\":\n \"¿No tienes una cuenta? <0>Regístrate</0>\",\n \"By clicking continue, you agree to our <0>Terms of Service</0> and <1>Privacy Policy</1>.\":\n \"Al continuar, aceptas nuestros <0>Términos del servicio</0> y nuestra <1>Política de privacidad</1>.\",\n }),\n ...messages(`${AUTH}/login/+page.ts`, {\n \"Log in\": \"Iniciar sesión\",\n }),\n\n ...messages(SIGNUP, {\n \"Choose a sign up method\": \"Elige cómo registrarte\",\n \"Use your email to sign up\": \"Usa tu correo para registrarte\",\n \"Create an account\": \"Crea una cuenta\",\n \"Signups are disabled\": \"El registro está desactivado\",\n \"Check back later for signup options\":\n \"Vuelve más tarde para ver las opciones de registro\",\n \"<0/> Sign up with {0}\": \"<0/> Registrarte con {0}\",\n \"Confirm Password\": \"Confirmar contraseña\",\n \"Create account\": \"Crear cuenta\",\n \"Already have an account? <0>Log in</0>\":\n \"¿Ya tienes una cuenta? <0>Inicia sesión</0>\",\n }),\n ...messages(`${AUTH}/signup/+page.ts`, {\n \"Sign up\": \"Crear cuenta\",\n }),\n ...messages(`${AUTH}/signup/+page.server.ts`, {\n \"Failed to send the code.\": \"No pudimos enviar el código.\",\n \"We sent a confirmation link to your email.\":\n \"Te enviamos un enlace de confirmación a tu correo.\",\n }),\n\n ...messages(`${AUTH}/reset/+page.svelte`, {\n \"Reset your password\": \"Restablece tu contraseña\",\n \"Enter your email to reset your password\":\n \"Escribe tu correo para restablecer tu contraseña\",\n \"Send reset link\": \"Enviar enlace\",\n \"Remembered your password? <0>Log in</0>\":\n \"¿Recordaste tu contraseña? <0>Inicia sesión</0>\",\n }),\n ...messages(`${AUTH}/reset/+page.ts`, {\n \"Reset password\": \"Restablecer contraseña\",\n }),\n ...messages(`${AUTH}/reset/+page.server.ts`, {\n \"We sent a password reset link to your email.\":\n \"Te enviamos un enlace a tu correo para restablecer tu contraseña.\",\n \"We could not send the reset link. Try again in a moment.\":\n \"No pudimos enviar el enlace. Inténtalo de nuevo en un momento.\",\n }),\n\n ...messages(`${AUTH}/confirm-reset/[token]/+page.svelte`, {\n \"Enter your new password\": \"Escribe tu nueva contraseña\",\n }),\n ...messages(`${AUTH}/confirm-reset/[token]/+page.ts`, {\n \"Confirm password reset\": \"Confirmar restablecimiento de contraseña\",\n }),\n ...messages(`${AUTH}/confirm-reset/[token]/+page.server.ts`, {\n \"Password reset successfully.\":\n \"Tu contraseña se restableció correctamente.\",\n }),\n\n ...messages(`${AUTH}/confirm-email-change/[token]/+page.svelte`, {\n \"Confirm email change\": \"Confirmar cambio de correo\",\n \"Confirm your email change\": \"Confirma el cambio de correo\",\n \"Enter your password to confirm your email change\":\n \"Escribe tu contraseña para confirmar el cambio de correo\",\n }),\n ...messages(`${AUTH}/confirm-email-change/[token]/+page.server.ts`, {\n \"Email changed successfully.\": \"Tu correo se cambió correctamente.\",\n }),\n\n ...messages(`${AUTH}/otp/[token]/+page.svelte`, {\n \"Verify code\": \"Verificar código\",\n \"Enter your OTP code\": \"Escribe tu código\",\n \"Enter the code sent to your email\":\n \"Escribe el código que enviamos a tu correo\",\n \"OTP code\": \"Código de un solo uso\",\n }),\n\n ...messages(`${AUTH}/welcome/+page.svelte`, {\n \"Welcome!\": \"¡Te damos la bienvenida!\",\n \"What should we call you?\": \"¿Cómo quieres que te llamemos?\",\n Name: \"Nombre\",\n Continue: \"Continuar\",\n \"Skip for now\": \"Omitir por ahora\",\n }),\n ...messages(`${AUTH}/welcome/+page.ts`, {\n Welcome: \"Bienvenida\",\n }),\n\n ...messages(`${APP}/+layout.server.ts`, {\n Home: \"Inicio\",\n }),\n ...messages(\"src/lib/components/nav-user.svelte\", {\n \"<0/> Light mode\": \"<0/> Modo claro\",\n \"<0/> Dark mode\": \"<0/> Modo oscuro\",\n \"<0/> Log out\": \"<0/> Cerrar sesión\",\n }),\n\n ...messages(SETTINGS, {\n Profile: \"Perfil\",\n \"Your profile information.\": \"La información de tu perfil.\",\n Avatar: \"Avatar\",\n \"Upload a new avatar for your profile.\":\n \"Sube un nuevo avatar para tu perfil.\",\n \"Remove avatar\": \"Quitar avatar\",\n \"Upload new picture\": \"Subir nueva foto\",\n \"Display email publicly\": \"Mostrar mi correo públicamente\",\n \"By clicking this checkbox, your email will be displayed publicly.\":\n \"Al marcar esta casilla, tu correo se mostrará públicamente.\",\n \"Save changes\": \"Guardar cambios\",\n \"The email address associated with your account.\":\n \"El correo electrónico asociado a tu cuenta.\",\n Verified: \"Verificado\",\n Unverified: \"Sin verificar\",\n \"Resend verification email\": \"Reenviar correo de verificación\",\n \"Change email\": \"Cambiar correo\",\n \"Enter your new email address. You will receive a verification email.\":\n \"Escribe tu nuevo correo electrónico. Recibirás un correo de verificación.\",\n \"Your password is used to log in to your account.\":\n \"Tu contraseña se usa para iniciar sesión en tu cuenta.\",\n \"New password\": \"Nueva contraseña\",\n \"Confirm new password\": \"Confirmar nueva contraseña\",\n \"Update password\": \"Actualizar contraseña\",\n }),\n ...messages(`${APP}/settings/+page.server.ts`, {\n \"Profile updated successfully.\": \"Tu perfil se actualizó correctamente.\",\n \"We sent a confirmation link to your new email.\":\n \"Te enviamos un enlace de confirmación a tu nuevo correo.\",\n \"Password updated successfully.\":\n \"Tu contraseña se actualizó correctamente.\",\n \"Your account has no email.\": \"Tu cuenta no tiene correo.\",\n \"We sent a verification email to your email.\":\n \"Te enviamos un correo de verificación.\",\n }),\n\n // enable-auth-remote writes the same pages at the same paths, so everything\n // above covers it. These are the messages only it has, filed under its\n // remote functions so a project with the form-action pages is not handed\n // them.\n ...messages(`${AUTH}/login/form.remote.ts`, {\n \"Failed to authenticate.\": \"No pudimos iniciar tu sesión.\",\n }),\n ...messages(`${AUTH}/signup/form.remote.ts`, {\n \"Failed to create account.\": \"No pudimos crear tu cuenta.\",\n }),\n ...messages(`${AUTH}/otp/[token]/form.remote.ts`, {\n \"Failed to verify code.\": \"No pudimos verificar el código.\",\n }),\n ...messages(`${APP}/settings/form.remote.ts`, {\n \"Upload new pic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ACtB,0BAA0B;EAC1B,qEACE;EACF,gBAAgB;EAChB,mDACE;EACF,UAAU;EACV,YAAY;EACZ,6BAA6B;EAC7B,gBAAgB;EAChB,wEACE;EACF,oDACE;EACF,gBAAgB;EAChB,wBAAwB;EACxB,mBAAmB;CACrB,CAAC;CACD,GAAGC,EAAS,GAAGJ,EAAI,4BAA4B;EAC7C,iCAAiC;EACjC,kDACE;EACF,kCACE;EACF,8BAA8B;EAC9B,+CACE;CACJ,CAAC;CAMD,GAAGI,EAAS,GAAGL,EAAK,wBAAwB,EAC1C,2BAA2B,gCAC7B,CAAC;CACD,GAAGK,EAAS,GAAGL,EAAK,yBAAyB,EAC3C,6BAA6B,8BAC/B,CAAC;CACD,GAAGK,EAAS,GAAGL,EAAK,8BAA8B,EAChD,0BAA0B,kCAC5B,CAAC;CACD,GAAGK,EAAS,GAAGJ,EAAI,2BAA2B,EAC5C,2BAA2B,wBAC7B,CAAC;AACH"}
|
|
@@ -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-BUhkIHse.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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,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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,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,EAAG,KAAK,6BAA6B,EAAE,QAAQ,MAAM,CAAC,GACrD;CACT,SAASC,GAAY;EACnB,IAAIA,GAAO,WAAW,KAAK,OAAO;EAClC,MAAMA;CACR;AACF;AAiBA,eAAsBC,EAAoB,GAAkC;CAC1E,IAAMC,IAAQ,MAAMH,EAAG,YAAY,OAAO,OAAO,GAC3CI,KAAO,MACXD,EAAM,OAAO,MAAM,MAAwBE,EAAE,SAASC,CAAI,GAExDC,IAAU,IACRC,IAAoCL,EAAM,OAAO,KACpD,MACKM,EAAM,SAAS,WAAWA,EAAM,YAClC,IAAU,IACH;EAAE,GAAGA;EAAO,UAAU;CAAM,KAE9BA,CAEX;CAUA,AATKL,EAAI,OAAO,MACd,IAAU,IACVI,EAAO,KAAK;EACV,MAAM;EACN,MAAM;EACN,SAASX;EACT,KAAK;CACP,CAAC,IAEEO,EAAI,eAAe,MACtB,IAAU,IACVI,EAAO,KAAK;EAAE,MAAM;EAAiB,MAAM;CAAO,CAAC;CAGrD,IAAME,IAAU,CAAC,GAAGP,EAAM,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