@menapo/vi18n 0.1.0 → 0.1.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.
Files changed (119) hide show
  1. package/README.md +14 -14
  2. package/dist/{apply-Bre-lY9J.js → apply-FAHl1R6T.js} +69 -89
  3. package/dist/{captured-Bj8bO6vd.js → captured-CTjjDF5o.js} +196 -217
  4. package/dist/{check-DyrAbv73.js → check-DwFwOB1d.js} +66 -84
  5. package/dist/cli.js +2 -3
  6. package/dist/{collect-Cx4_SKOe.js → collect-CYATDjdo.js} +1 -2
  7. package/dist/collisions-uMTuq36M.js +215 -0
  8. package/dist/compile-CEvH-6sY.js +240 -0
  9. package/dist/{compile-Cc97JaW2.js → compile-DqkofbiO.js} +376 -331
  10. package/dist/concurrency-BCY_4zcr.js +1 -0
  11. package/dist/concurrency-Dy2ny50V.js +107 -0
  12. package/dist/config.d.ts +1 -5
  13. package/dist/config.js +4 -5
  14. package/dist/{types-D3QGM8XO.js → diagnostics-1onDF6Ua.js} +26 -26
  15. package/dist/{dir-zw6bGMKQ.js → dir-TGLYuOZb.js} +34 -37
  16. package/dist/{duplicates-yuRljQ6h.js → duplicates-CsUXRX2J.js} +10 -27
  17. package/dist/engine-Bf7nVigL.js +556 -0
  18. package/dist/engine.d.ts +1 -5
  19. package/dist/engine.js +297 -168
  20. package/dist/exchange-DYG9RZoT.js +41 -0
  21. package/dist/{exclude-Du-Zd_qI.js → exclude-vMnm3lqU.js} +2 -3
  22. package/dist/{export-DGsMbcTZ.js → export-BYq0gfLd.js} +17 -38
  23. package/dist/{extract-Dujlsgnk.js → extract-CYtuEo8u.js} +114 -82
  24. package/dist/{formats-KPIg-08V.js → formats-ChV1LVH_.js} +352 -276
  25. package/dist/fs-ezCMZeDV.js +52 -0
  26. package/dist/i18next-1waHziMy.js +1 -0
  27. package/dist/i18next-D66Icz3L.js +1907 -0
  28. package/dist/{import-Cwdhcywt.js → import-BApbQlmm.js} +81 -75
  29. package/dist/index.d.ts +1 -13
  30. package/dist/index.js +14 -16
  31. package/dist/{init-BecCTvKi.js → init-J7AwwA5e.js} +466 -501
  32. package/dist/{library-D5CWvTQs.js → library-BfSOBeBd.js} +975 -451
  33. package/dist/lingui-Ee2farVo.js +902 -0
  34. package/dist/lint.d.ts +0 -4
  35. package/dist/lint.js +69 -82
  36. package/dist/{load-gW-oJt1Q.js → load-BFLLqY8x.js} +272 -147
  37. package/dist/{load-CQRz4PpM.js → load-CMwhukZ4.js} +1211 -1115
  38. package/dist/{locales-DX4MOBFE.js → locales-DxLDrx-h.js} +271 -237
  39. package/dist/{lsp-Cq1Nuu-Q.js → lsp-BC7xDGON.js} +4 -5
  40. package/dist/{match-BGr8EXB3.js → match-BLDcj610.js} +11 -4
  41. package/dist/{mcp-Cf0T7qPW.js → mcp-Cka8ywDF.js} +4 -5
  42. package/dist/{merge-driver-CpiiSVIc.js → merge-driver-B04Apm29.js} +138 -122
  43. package/dist/migrate-D7TNl6SD.js +2169 -0
  44. package/dist/migrate-khCY8TE0.js +1 -0
  45. package/dist/{openai-CTaMDcl-.js → openai-RWw0YlAx.js} +128 -87
  46. package/dist/{output-DsaHKHEt.js → output-CF9uvk_-.js} +15 -9
  47. package/dist/parse.d.ts +1 -3
  48. package/dist/parse.js +7 -8
  49. package/dist/{pipeline-wxS0SApG.js → pipeline-B30irGMD.js} +1 -1
  50. package/dist/{pipeline-C7g11THL.js → pipeline-sgl_q_op.js} +387 -359
  51. package/dist/project-DSzWKU3C.js +544 -0
  52. package/dist/{pseudo-DRv30iN5.js → pseudo-DNbNNVGP.js} +125 -3
  53. package/dist/{raw-C4Y6vyGY.js → raw-YsYZMS9n.js} +52 -29
  54. package/dist/react-intl-tzGIk6G3.js +634 -0
  55. package/dist/restore-BG_zMpSj.js +199 -0
  56. package/dist/rewrite-hAcRJwiZ.js +415 -0
  57. package/dist/{rich-DCUKl5HM.js → rich-ApY1Dm4S.js} +35 -28
  58. package/dist/rolldown-runtime-C1I3wEg2.js +43 -0
  59. package/dist/{rolldown-runtime-D7D4PA-g.js → rolldown-runtime-D8jQpDG7.js} +1 -2
  60. package/dist/run-CFzR3V93.js +647 -0
  61. package/dist/scan-worker.d.ts +2 -4
  62. package/dist/scan-worker.js +1 -1
  63. package/dist/{scoped-BMYpSthj.js → scoped-h3KE8XWW.js} +3 -4
  64. package/dist/{server-BDkykMjb.js → server-WlxZH0oX.js} +275 -330
  65. package/dist/{server-qv3mz70d.js → server-ceuzzkal.js} +292 -386
  66. package/dist/server.d.ts +1 -17
  67. package/dist/server.js +415 -381
  68. package/dist/{sitemap-DV3o8QD7.js → sitemap-796jJKUT.js} +21 -33
  69. package/dist/{sources-D19czDSA.js → sources-DuOdM02f.js} +712 -373
  70. package/dist/{status-DZArW5aE.js → status-CTH3qI-0.js} +30 -30
  71. package/dist/{stdio-FPOKQAgu.js → stdio-D9kTzyqB.js} +2 -4
  72. package/dist/{stdio-CVaJfxA7.js → stdio-FWIVU3P4.js} +1 -2
  73. package/dist/sync-CpL0Qsgw.js +1352 -0
  74. package/dist/{t-DC-c9zE5.js → t-gvEXx25s.js} +76 -53
  75. package/dist/test.d.ts +5 -16
  76. package/dist/test.js +77 -48
  77. package/dist/translate-BrfVRkjl.js +336 -0
  78. package/dist/{ts-BaU5yOf0.js → ts-BX6kwig5.js} +25 -14
  79. package/dist/{types-DtvQ7UdD.js → types-3kwyaCAm.js} +1 -2
  80. package/dist/{types-DsdWBG0b.d.ts → types-BaG1LboH.d.ts} +2 -6
  81. package/dist/{types-CgUCkFU1.d.ts → types-Cy2bPdSg.d.ts} +14 -20
  82. package/dist/types-Ds_vebja.js +41 -0
  83. package/dist/{units-CQ5Q99RC.js → units-VVLgQ7x7.js} +7 -16
  84. package/dist/{url-CRfCOhUI.js → url-Bpc6wLea.js} +24 -11
  85. package/dist/{url-CsBkRaJy.js → url-D2_VlEeH.js} +25 -12
  86. package/dist/{validate-D6DJepZv.js → validate-PGgMsasz.js} +3 -5
  87. package/dist/{validate-BxpupdAf.js → validate-zv4-IZyZ.js} +690 -377
  88. package/dist/{version-BlyLGlOa.js → version-BFs370Ce.js} +3 -5
  89. package/dist/{vite-scan-B_YW4X_a.js → vite-scan-DFKSGVE9.js} +87 -92
  90. package/dist/vite.d.ts +2 -6
  91. package/dist/vite.js +6482 -6018
  92. package/dist/vue-i18n-CBmZqHbG.js +806 -0
  93. package/dist/{which-C6PFI1Dm.js → which-BpyJyBkX.js} +44 -37
  94. package/dist/{worker-84U6uYB3.js → worker-BjzVqJVO.js} +454 -608
  95. package/package.json +8 -8
  96. package/dist/check-D34P-S--.js +0 -1
  97. package/dist/codec-DuvU2VQy.js +0 -207
  98. package/dist/collisions-CfpZU8e4.js +0 -217
  99. package/dist/compile-B5Mz6WJm.js +0 -245
  100. package/dist/concurrency-C9UUWuDC.js +0 -96
  101. package/dist/concurrency-DONL7t4V.js +0 -1
  102. package/dist/engine-B7p40M__.js +0 -531
  103. package/dist/i18next-CrUnKFfh.js +0 -1596
  104. package/dist/i18next-Rgo-v9l0.js +0 -1
  105. package/dist/lingui--PcOOYry.js +0 -833
  106. package/dist/messages-Cxa-5tR0.js +0 -166
  107. package/dist/migrate-CntqvrW4.js +0 -1
  108. package/dist/migrate-dPgq9uzy.js +0 -1484
  109. package/dist/project-Dwx7iPm6.js +0 -381
  110. package/dist/project-pXipT8iG.js +0 -1046
  111. package/dist/react-intl-CaBVwJ9u.js +0 -519
  112. package/dist/restore-Btq66Tid.js +0 -175
  113. package/dist/rewrite-CiTRAICl.js +0 -803
  114. package/dist/run-DYD_VXKy.js +0 -694
  115. package/dist/runtime-DTMmliT1.js +0 -64
  116. package/dist/sync-CcVzger_.js +0 -658
  117. package/dist/translate-DZR3MkSA.js +0 -299
  118. package/dist/types-wSh9fCBY.js +0 -11
  119. package/dist/vue-i18n-CEMnpv7k.js +0 -651
@@ -1,18 +1,18 @@
1
- import { o as isDiagnosticError, t as CONFIG_FILE } from "./types-D3QGM8XO.js";
2
- import { i as idScheme } from "./validate-BxpupdAf.js";
3
- import { b as emptyCatalog, o as catalogLayout, p as serializeCatalog, s as catalogPath } from "./library-D5CWvTQs.js";
4
- import { n as loadConfig, r as resolveConfig } from "./load-gW-oJt1Q.js";
5
- import { t as VERSION } from "./version-BlyLGlOa.js";
6
- import { l as langFromId, u as parseModule } from "./worker-84U6uYB3.js";
7
- import { a as writeGenFile, r as GEN_FILE } from "./sync-CcVzger_.js";
8
- import { t as EXIT } from "./types-wSh9fCBY.js";
9
- import { t as CliExit } from "./project-Dwx7iPm6.js";
1
+ import { n as isDiagnosticError, r as CONFIG_FILE } from "./diagnostics-1onDF6Ua.js";
2
+ import { C as emptyCatalog, o as catalogLayout, p as serializeCatalog, s as catalogPath } from "./library-BfSOBeBd.js";
3
+ import { i as resolveConfig, n as isWorkspaceRoot, r as loadConfig } from "./load-BFLLqY8x.js";
4
+ import { m as idScheme, u as toPosix } from "./validate-zv4-IZyZ.js";
5
+ import { t as VERSION } from "./version-BFs370Ce.js";
6
+ import { a as writeGenFile, r as GEN_FILE } from "./sync-CpL0Qsgw.js";
7
+ import { r as writeFileAtomic, t as findViteConfig } from "./fs-ezCMZeDV.js";
8
+ import { g as usageError, t as CliExit } from "./project-DSzWKU3C.js";
9
+ import { r as EXIT } from "./types-Ds_vebja.js";
10
+ import { C as langFromId, i as stripJsonc, w as parseModule, x as unwrap } from "./sources-DuOdM02f.js";
10
11
  import { createRequire } from "node:module";
11
- import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
12
- import { randomBytes } from "node:crypto";
12
+ import { basename, dirname, extname, isAbsolute, join, relative, resolve } from "node:path";
13
13
  import { existsSync, readFileSync } from "node:fs";
14
- import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
15
- //#region src/cli/scaffold.ts
14
+ import { readFile, stat } from "node:fs/promises";
15
+ // src/cli/scaffold.ts
16
16
  /**
17
17
  * The `<T>` components `vi18n init --rich` copies into a project (PLAN §4.1,
18
18
  * §5.16; INTERNALS §6 D213): Vue (one scoped slot per tag) and Svelte 5
@@ -105,268 +105,272 @@ ${SVELTE_IMPORTS}
105
105
 
106
106
  {@render render(richParts(message, values))}
107
107
  `;
108
- //#endregion
109
- //#region src/cli/commands/init.ts
110
- /**
111
- * `vi18n init [--yes] [--format po|json] [--locales a,b] [--source-locale a] [--rich]`
112
- * (INTERNALS §2.14, PLAN §5.19): the way into a project. Writes
113
- * `vi18n.config.ts` (never over an existing one), adds the plugin to the
114
- * exported config's `plugins` in `vite.config.*`, creates every locale's
115
- * empty catalog, writes `vi18n.gen.ts` and lists it in the tsconfig that
116
- * compiles the sources. `--rich` copies the `<T>` components for the
117
- * project's Vue and Svelte and lists them in `extraction.importSources`
118
- * (§6 D213); in a configured project it does only that. Each step
119
- * that cannot edit a file safely prints the snippet instead.
120
- */
121
- const VITE_CONFIGS = [
122
- "vite.config.ts",
123
- "vite.config.mts",
124
- "vite.config.js",
125
- "vite.config.mjs",
126
- "vite.config.cts",
127
- "vite.config.cjs"
128
- ];
129
- const PLUGIN_IMPORT = "import vi18n from \"@menapo/vi18n/vite\";";
108
+ // src/cli/commands/init/paths.ts
109
+ /** How `vi18n init` names the files it reports, and where it looks for sources. */
130
110
  /** Source directories of the supported frameworks, in the order `init` looks for them. */
131
111
  const SOURCE_DIRS = ["src", "app"];
132
- /** Markers `findConfigFile` stops at; `init` does not look for a tsconfig above them either. */
133
- const WORKSPACE_MARKERS = ["pnpm-workspace.yaml", ".git"];
134
- async function init(ctx, flags) {
135
- const dir = resolve(ctx.global.cwd);
136
- const configFile = ctx.global.config === null ? join(dir, CONFIG_FILE) : resolve(dir, ctx.global.config);
137
- const root = dirname(configFile);
138
- if (flags.rich && existsSync(configFile)) return scaffoldOnly(ctx, root, configFile);
139
- const input = configInput(await ask(ctx, flags), root);
140
- const components = flags.rich ? richComponents(root) : [];
141
- if (flags.rich && components.length === 0) throw noRichFramework();
142
- if (components.length > 0) input.extraction = { importSources: components.map((c) => c.specifier) };
143
- let config;
144
- try {
145
- config = resolveConfig(input, root, configFile);
146
- } catch (error) {
147
- if (isDiagnosticError(error)) throw new CliExit(EXIT.usage, [error.diagnostic]);
148
- throw error;
112
+ function relativeTo(root) {
113
+ return (file) => toPosix(relative(root, file)) || ".";
114
+ }
115
+ // src/cli/commands/init/tsconfig.ts
116
+ /**
117
+ * `vi18n init`'s tsconfig edit: `vi18n.gen.ts` in the `include` of the
118
+ * config that compiles the sources, or the snippet to add by hand.
119
+ */
120
+ /**
121
+ * Lists `vi18n.gen.ts` in the `include` of the tsconfig that compiles the
122
+ * sources, when that file is plain JSON (a JSONC file with comments is left
123
+ * alone: rewriting it would drop them). Without `include` or `files` of its
124
+ * own or through `extends`, TypeScript already sees every file; with only
125
+ * inherited ones, the snippet to add is printed. A config that has `files` but no
126
+ * `include` never gets an `include` added (the snippet is printed), and a
127
+ * solution-style config (`references` and nothing of its own to compile, as
128
+ * create-vite's) is never edited: adding `include` there would make it a
129
+ * project of its own, which breaks `tsc -b`. Its reference whose `include`
130
+ * covers the source directory is the one edited instead.
131
+ */
132
+ async function addToTsconfig(root, gen, data, rel) {
133
+ const file = await nearestTsconfig(root);
134
+ if (file === null) return;
135
+ const read = await readTsconfig(file);
136
+ if (read === null) return;
137
+ const json = read.json;
138
+ if (json === null) {
139
+ data.manual.push(includeSnippet(file, gen, rel));
140
+ return;
149
141
  }
150
- const data = {
151
- wrote: [],
152
- skipped: [],
153
- manual: [],
154
- sourceLocale: config.sourceLocale,
155
- locales: config.locales,
156
- format: config.catalogs.format
157
- };
158
- const rel = (file) => relative(root, file).split(sep).join("/") || ".";
159
- if (existsSync(configFile)) {
160
- ctx.out.report([{
161
- code: "config-invalid",
162
- severity: "error",
163
- message: `${rel(configFile)} already exists; vi18n init never overwrites it (edit it, or run vi18n extract)`,
164
- file: configFile
165
- }]);
166
- return {
167
- exitCode: EXIT.failure,
168
- data
169
- };
142
+ if (typeof json !== "object" || Array.isArray(json)) return;
143
+ if (!isSolutionConfig(json)) {
144
+ await listGenFile(file, read, gen, data, rel);
145
+ return;
170
146
  }
171
- await atomicWrite(configFile, configSource(input));
172
- data.wrote.push(rel(configFile));
173
- if (flags.rich) await writeComponents(root, components, data, rel);
174
- await addPlugin(root, data, rel);
175
- const layout = catalogLayout(config);
176
- const header = {
177
- idScheme: idScheme(config.ids.length),
178
- sourceLocale: config.sourceLocale
179
- };
180
- for (const locale of config.locales) {
181
- const path = catalogPath(config, locale);
182
- if (existsSync(path)) {
183
- data.skipped.push(rel(path));
184
- continue;
147
+ const sourceDir = SOURCE_DIRS.map((name) => join(root, name)).find((dir) => existsSync(dir)) ?? root;
148
+ let first = null;
149
+ for (const reference of json.references) {
150
+ const found = await readReference(file, reference);
151
+ if (found === null) continue;
152
+ first ??= found.file;
153
+ const include = found.read.json?.include;
154
+ if (Array.isArray(include) && covers(include, dirname(found.file), sourceDir)) {
155
+ await listGenFile(found.file, found.read, gen, data, rel);
156
+ return;
185
157
  }
186
- const isSourceLocale = locale === config.sourceLocale;
187
- const text = serializeCatalog(emptyCatalog(locale, layout, header), {
188
- isSourceLocale,
189
- version: VERSION
190
- });
191
- await mkdir(dirname(path), { recursive: true });
192
- await atomicWrite(path, text);
193
- data.wrote.push(rel(path));
194
158
  }
195
- const gen = join(root, GEN_FILE);
196
- if (await writeGenFile(config)) data.wrote.push(rel(gen));
197
- await addToTsconfig(root, gen, data, rel);
198
- printSummary(ctx, data);
199
- ctx.out.result(`\nNext: wrap strings in t("…") and run vi18n extract.`);
159
+ data.manual.push(includeSnippet(first ?? file, gen, rel));
160
+ }
161
+ /** A solution-style config: `references`, and no `include` or `files` of its own. */
162
+ function isSolutionConfig(json) {
163
+ const references = Array.isArray(json.references) ? json.references : [];
164
+ const ownFiles = Array.isArray(json.files) ? json.files : null;
165
+ return references.length > 0 && json.include === void 0 && (json.files === void 0 || ownFiles?.length === 0);
166
+ }
167
+ /** The tsconfig a `references` entry names (a directory means its `tsconfig.json`); null when it cannot be read. */
168
+ async function readReference(file, reference) {
169
+ const path = reference?.path;
170
+ if (typeof path !== "string") return null;
171
+ let target = resolve(dirname(file), path);
172
+ try {
173
+ if ((await stat(target)).isDirectory()) target = join(target, "tsconfig.json");
174
+ } catch {
175
+ return null;
176
+ }
177
+ const read = await readTsconfig(target);
178
+ return read === null ? null : {
179
+ file: target,
180
+ read
181
+ };
182
+ }
183
+ /** The `include` snippet that lists the generated file in `file`. */
184
+ function includeSnippet(file, gen, rel) {
185
+ const entry = toPosix(relative(dirname(file), gen));
200
186
  return {
201
- exitCode: EXIT.ok,
202
- data
187
+ file: rel(file),
188
+ snippet: `"include": [/* … */ ${JSON.stringify(entry)}]`
203
189
  };
204
190
  }
205
- function printSummary(ctx, data) {
206
- for (const file of data.wrote) ctx.out.result(`created ${file}`);
207
- for (const file of data.skipped) ctx.out.result(`kept ${file}`);
208
- for (const { file, snippet } of data.manual) ctx.out.result(`\nAdd to ${file} by hand:\n${snippet}`);
191
+ /** Adds the entry to one config's `include`, or prints the snippet when that cannot be done safely. */
192
+ async function listGenFile(file, read, gen, data, rel) {
193
+ const entry = toPosix(relative(dirname(file), gen));
194
+ const json = read.json;
195
+ if (typeof json !== "object" || json === null || Array.isArray(json)) return;
196
+ if (json.include === void 0 && json.files === void 0) {
197
+ const snippet = await inheritedSnippet(file, json, gen, entry);
198
+ if (snippet !== null) data.manual.push({
199
+ file: rel(file),
200
+ snippet
201
+ });
202
+ return;
203
+ }
204
+ if (json.include === void 0) {
205
+ data.manual.push({
206
+ file: rel(file),
207
+ snippet: `"files": [/* … */ ${JSON.stringify(entry)}]`
208
+ });
209
+ return;
210
+ }
211
+ const include = Array.isArray(json.include) ? json.include : [];
212
+ if (include.includes(entry) || include.includes("./" + entry)) {
213
+ data.skipped.push(rel(file));
214
+ return;
215
+ }
216
+ if (!read.plain) {
217
+ data.manual.push(includeSnippet(file, gen, rel));
218
+ return;
219
+ }
220
+ json.include = [...include, entry];
221
+ const text = read.text;
222
+ const indent = /\n([ \t]+)\S/.exec(text.slice(text.indexOf("{") + 1))?.[1] ?? " ";
223
+ await writeFileAtomic(file, JSON.stringify(json, null, indent) + (text.endsWith("\n") ? "\n" : ""));
224
+ data.wrote.push(rel(file));
209
225
  }
210
226
  /**
211
- * One component per framework the root `package.json` depends on, beside
212
- * the project's other shared components: `<src>/lib` (SvelteKit's `$lib`)
213
- * when it exists, else `<src>/components`. React, Preact and Solid get
214
- * none: `rich()` returns what JSX renders, and the `<T>` macro is compiled
215
- * away (§6 D213).
227
+ * The `include` snippet for a tsconfig with no `include` or `files` of its
228
+ * own, or null when TypeScript already compiles the generated file. Such a
229
+ * config takes both from `extends` (SvelteKit's `.svelte-kit/tsconfig.json`
230
+ * lists globs under `../src` and a few files), and an `include` written here
231
+ * replaces the inherited one, so the snippet repeats its entries, rebased to
232
+ * this file. Inherited `files` stay: TypeScript adds an own `include` to them.
216
233
  */
217
- function richComponents(root) {
218
- let deps = {};
219
- try {
220
- const pkg = JSON.parse(readFileSyncSafe(join(root, "package.json")));
221
- deps = {
222
- ...pkg.dependencies,
223
- ...pkg.devDependencies
224
- };
225
- } catch {}
226
- const sourceDir = SOURCE_DIRS.find((name) => existsSync(join(root, name)));
227
- const base = sourceDir === void 0 ? "" : sourceDir + "/";
228
- const dir = existsSync(join(root, base + "lib")) ? base + "lib" : base + "components";
229
- const out = [];
230
- if ("vue" in deps) out.push({
231
- file: `${dir}/T.vue`,
232
- specifier: `./${dir}/T.vue`,
233
- source: T_VUE
234
- });
235
- if ("svelte" in deps) out.push({
236
- file: `${dir}/T.svelte`,
237
- specifier: `./${dir}/T.svelte`,
238
- source: T_SVELTE
239
- });
240
- return out;
234
+ async function inheritedSnippet(file, json, gen, entry) {
235
+ if (json.extends === void 0) return null;
236
+ const include = await inherited(file, json, "include", /* @__PURE__ */ new Set([file]));
237
+ const files = await inherited(file, json, "files", /* @__PURE__ */ new Set([file]));
238
+ if (include === void 0 || files === void 0) return `"include": [/* every entry "extends" gives it (none given: nothing to add) */ ${JSON.stringify(entry)}]`;
239
+ if (include === null && files === null) return null;
240
+ const target = toPosix(gen);
241
+ if (files !== null && files.list.some((f) => toPosix(resolve(files.base, f)) === target)) return null;
242
+ if (include !== null && include.list.some((p) => matchesInclude(p, include.base, target))) return null;
243
+ return `"include": [${[...include === null ? [] : include.list.map((p) => toPosix(relative(dirname(file), resolve(include.base, p))) || "."), entry].map((p) => JSON.stringify(p)).join(", ")}]`;
241
244
  }
242
- function noRichFramework() {
243
- return usage("--rich copies a <T> component for Vue and Svelte, and package.json depends on neither; in JSX, rich() and the <T> macro need no component");
245
+ /**
246
+ * `key` as `file` inherits it through `extends` (later bases override
247
+ * earlier ones, as in TypeScript), with the directory its paths are relative
248
+ * to; null when no base has it; undefined when a base cannot be read.
249
+ */
250
+ async function inherited(file, json, key, seen) {
251
+ let found = null;
252
+ for (const spec of extendsList(json)) {
253
+ const target = typeof spec === "string" ? resolveExtends(file, spec) : null;
254
+ if (target === null || seen.has(target)) return void 0;
255
+ const base = (await readTsconfig(target))?.json;
256
+ if (typeof base !== "object" || base === null || Array.isArray(base)) return void 0;
257
+ const value = base[key];
258
+ let result;
259
+ if (value === void 0) result = await inherited(target, base, key, /* @__PURE__ */ new Set([...seen, target]));
260
+ else if (Array.isArray(value) && value.every((v) => typeof v === "string")) result = {
261
+ list: value,
262
+ base: dirname(target)
263
+ };
264
+ else return void 0;
265
+ if (result === void 0) return void 0;
266
+ if (result !== null) found = result;
267
+ }
268
+ return found;
244
269
  }
245
- function readFileSyncSafe(file) {
246
- return existsSync(file) ? readFileSync(file, "utf8") : "";
270
+ /** `extends` as a list: TypeScript accepts one string or an array. */
271
+ function extendsList(json) {
272
+ if (typeof json.extends === "string") return [json.extends];
273
+ return Array.isArray(json.extends) ? json.extends : [];
247
274
  }
248
- /** Copies the components, never over a file that exists. */
249
- async function writeComponents(root, components, data, rel) {
250
- for (const component of components) {
251
- const path = join(root, component.file);
252
- if (existsSync(path)) {
253
- data.skipped.push(rel(path));
254
- continue;
255
- }
256
- await mkdir(dirname(path), { recursive: true });
257
- await atomicWrite(path, component.source);
258
- data.wrote.push(rel(path));
275
+ /** The file an `extends` entry names, as TypeScript finds it; null when it cannot be found. */
276
+ function resolveExtends(file, spec) {
277
+ if (spec.startsWith("./") || spec.startsWith("../") || isAbsolute(spec)) {
278
+ const path = resolve(dirname(file), spec);
279
+ if (existsSync(path)) return path;
280
+ return !path.endsWith(".json") && existsSync(path + ".json") ? path + ".json" : null;
259
281
  }
282
+ const require = createRequire(file);
283
+ const candidates = spec.endsWith(".json") ? [spec] : [`${spec}.json`, `${spec}/tsconfig.json`];
284
+ for (const candidate of candidates) try {
285
+ return require.resolve(candidate);
286
+ } catch {}
287
+ return null;
260
288
  }
261
289
  /**
262
- * `--rich` in a configured project: copy the components and, unless the
263
- * config already names them, print the `importSources` entry to add (the
264
- * config is the user's code, and `init` edits only what it can parse safely).
290
+ * Whether a tsconfig `include` pattern (relative to `base`) takes `file`
291
+ * (absolute, `/`-separated): `*` and `?` within a segment, `**` across
292
+ * directories, and a pattern without wildcards as a file or a directory.
265
293
  */
266
- async function scaffoldOnly(ctx, root, configFile) {
267
- const rel = (file) => relative(root, file).split(sep).join("/") || ".";
268
- let config;
269
- try {
270
- config = await loadConfig({
271
- cwd: root,
272
- configFile
273
- });
274
- } catch (error) {
275
- if (isDiagnosticError(error)) throw new CliExit(EXIT.usage, [error.diagnostic]);
276
- throw error;
277
- }
278
- const data = {
279
- wrote: [],
280
- skipped: [],
281
- manual: [],
282
- sourceLocale: config.sourceLocale,
283
- locales: config.locales,
284
- format: config.catalogs.format
285
- };
286
- const components = richComponents(root);
287
- if (components.length === 0) throw noRichFramework();
288
- await writeComponents(root, components, data, rel);
289
- const text = readFileSyncSafe(configFile);
290
- const missing = components.filter((c) => !text.includes(c.specifier.slice(2)));
291
- if (missing.length > 0) data.manual.push({
292
- file: rel(configFile),
293
- snippet: `extraction: { importSources: [${missing.map((c) => JSON.stringify(c.specifier)).join(", ")}] },`
294
- });
295
- printSummary(ctx, data);
296
- return {
297
- exitCode: EXIT.ok,
298
- data
299
- };
294
+ function matchesInclude(pattern, base, file) {
295
+ const absolute = toPosix(resolve(base, pattern));
296
+ if (!/[*?]/.test(pattern)) return file === absolute || file.startsWith(absolute + "/");
297
+ let regex = "";
298
+ for (let i = 0; i < absolute.length; i++) {
299
+ const c = absolute[i];
300
+ if (c === "*" && absolute[i + 1] === "*") {
301
+ const slash = absolute[i + 2] === "/";
302
+ regex += slash ? "(?:[^/]*/)*" : ".*";
303
+ i += slash ? 2 : 1;
304
+ } else if (c === "*") regex += "[^/]*";
305
+ else if (c === "?") regex += "[^/]";
306
+ else regex += /[\\^$.+()[\]{}|]/.test(c) ? "\\" + c : c;
307
+ }
308
+ return new RegExp(`^${regex}$`).test(file);
300
309
  }
301
310
  /**
302
- * Flags first; questions only for what they leave open, only on a terminal,
303
- * and never with `--yes` or `--json` (an agent or CI must not hang).
311
+ * A tsconfig as JSON when it is plain JSON (`plain`: safe to rewrite), else
312
+ * read leniently past comments and trailing commas (only to look at it);
313
+ * null when it cannot be read at all.
304
314
  */
305
- async function ask(ctx, flags) {
306
- const prompt = flags.yes || ctx.global.json ? void 0 : ctx.io.prompt;
307
- let locales = flags.locales;
308
- let sourceLocale = flags.sourceLocale;
309
- let format = flags.format;
310
- if (prompt !== void 0) {
311
- if (sourceLocale === null) sourceLocale = (await prompt("Source locale (the language of the strings in your code)", locales[0] ?? "en")).trim();
312
- if (locales.length === 0) locales = (await prompt("Locales, comma-separated", sourceLocale || "en")).split(",").map((l) => l.trim()).filter((l) => l !== "");
313
- if (format === null) {
314
- const answer = (await prompt("Catalog format (po or json)", "po")).trim().toLowerCase();
315
- if (answer !== "po" && answer !== "json") throw usage(`catalog format must be po or json, not "${answer}"`);
316
- format = answer;
317
- }
315
+ async function readTsconfig(file) {
316
+ let text;
317
+ try {
318
+ text = await readFile(file, "utf8");
319
+ } catch {
320
+ return null;
318
321
  }
319
- sourceLocale = sourceLocale || locales[0] || "en";
320
- if (!locales.includes(sourceLocale)) locales = [sourceLocale, ...locales];
321
- for (const locale of locales) {
322
- let canonical;
323
- try {
324
- canonical = Intl.getCanonicalLocales(locale)[0];
325
- } catch {
326
- canonical = void 0;
327
- }
328
- if (canonical !== locale) throw usage(canonical === void 0 ? `"${locale}" is not a BCP 47 locale` : `"${locale}" is not in canonical form; use "${canonical}"`);
322
+ try {
323
+ return {
324
+ json: JSON.parse(text),
325
+ text,
326
+ plain: true
327
+ };
328
+ } catch {}
329
+ try {
330
+ return {
331
+ json: JSON.parse(stripJsonc(text)),
332
+ text,
333
+ plain: false
334
+ };
335
+ } catch {
336
+ return {
337
+ json: null,
338
+ text,
339
+ plain: false
340
+ };
329
341
  }
330
- return {
331
- sourceLocale,
332
- locales: [...new Set(locales)],
333
- format: format ?? "po"
334
- };
335
- }
336
- function usage(message) {
337
- return new CliExit(EXIT.usage, [{
338
- code: "config-invalid",
339
- severity: "error",
340
- message
341
- }]);
342
342
  }
343
- /** Only what differs from the defaults, so the file stays a short starting point. */
344
- function configInput(answers, root) {
345
- const input = {
346
- sourceLocale: answers.sourceLocale,
347
- locales: answers.locales
348
- };
349
- if (answers.format === "json") input.catalogs = { format: "json" };
350
- const sourceDir = SOURCE_DIRS.find((name) => existsSync(join(root, name)));
351
- if (sourceDir === void 0) input.project = { include: ["."] };
352
- else if (sourceDir !== "src") input.project = { include: [sourceDir] };
353
- return input;
343
+ /** Whether an `include` list reaches `dir`: a pattern's static prefix contains it. */
344
+ function covers(include, base, dir) {
345
+ for (const pattern of include) {
346
+ if (typeof pattern !== "string") continue;
347
+ const segments = [];
348
+ for (const segment of pattern.split("/")) {
349
+ if (/[*?[{]/.test(segment)) break;
350
+ segments.push(segment);
351
+ }
352
+ const prefix = resolve(base, ...segments);
353
+ const rel = relative(prefix, dir);
354
+ if (rel === "" || !rel.startsWith("..") && !isAbsolute(rel)) return true;
355
+ }
356
+ return false;
354
357
  }
355
- function configSource(input) {
356
- const lines = [
357
- "import { defineConfig } from \"@menapo/vi18n/config\";",
358
- "",
359
- "export default defineConfig({",
360
- ` sourceLocale: ${JSON.stringify(input.sourceLocale)},`,
361
- ` locales: [${(input.locales ?? []).map((l) => JSON.stringify(l)).join(", ")}],`
362
- ];
363
- if (input.catalogs?.format === "json") lines.push(" catalogs: { format: \"json\" },");
364
- if (input.project?.include !== void 0) lines.push(` project: { include: [${input.project.include.map((p) => JSON.stringify(p)).join(", ")}] },`);
365
- const sources = input.extraction?.importSources;
366
- if (sources !== void 0) lines.push(` extraction: { importSources: [${sources.map((p) => JSON.stringify(p)).join(", ")}] },`);
367
- lines.push("});", "");
368
- return lines.join("\n");
358
+ async function nearestTsconfig(from) {
359
+ for (let dir = from;; dir = dirname(dir)) {
360
+ const file = join(dir, "tsconfig.json");
361
+ try {
362
+ if ((await stat(file)).isFile()) return file;
363
+ } catch {}
364
+ if (await isWorkspaceRoot(dir)) return null;
365
+ if (dirname(dir) === dir) return null;
366
+ }
369
367
  }
368
+ // src/cli/commands/init/vite-config.ts
369
+ /**
370
+ * `vi18n init`'s `vite.config.*` edit: the plugin import and `vi18n()` in
371
+ * the exported config's `plugins`, through the AST.
372
+ */
373
+ const PLUGIN_IMPORT = "import vi18n from \"@menapo/vi18n/vite\";";
370
374
  /**
371
375
  * Adds the import after the last top-level import and `vi18n()` as the first
372
376
  * element of the exported config's `plugins` array. Anything less certain
@@ -374,9 +378,9 @@ function configSource(input) {
374
378
  * instead of guessing.
375
379
  */
376
380
  async function addPlugin(root, data, rel) {
377
- const file = VITE_CONFIGS.map((name) => join(root, name)).find((path) => existsSync(path));
381
+ const file = findViteConfig(root);
378
382
  const snippet = `${PLUGIN_IMPORT}\n\n// in defineConfig({ … }):\nplugins: [vi18n(), /* … */],`;
379
- if (file === void 0) {
383
+ if (file === null) {
380
384
  data.manual.push({
381
385
  file: "vite.config.ts",
382
386
  snippet
@@ -396,14 +400,9 @@ async function addPlugin(root, data, rel) {
396
400
  });
397
401
  return;
398
402
  }
399
- await atomicWrite(file, edited);
403
+ await writeFileAtomic(file, edited);
400
404
  data.wrote.push(rel(file));
401
405
  }
402
- function unwrap(node) {
403
- let current = node;
404
- while (current.type === "TSAsExpression" || current.type === "TSSatisfiesExpression" || current.type === "TSNonNullExpression" || current.type === "ParenthesizedExpression") current = current.expression;
405
- return current;
406
- }
407
406
  /**
408
407
  * The object literal a config module exports: `export default {…}`,
409
408
  * `defineConfig({…})`, `defineConfig(() => ({…}))`, a function returning
@@ -520,273 +519,239 @@ function withPlugin(text, file = "vite.config.ts") {
520
519
  const insertAt = leadingEnd(text);
521
520
  return `${out.slice(0, insertAt)}${PLUGIN_IMPORT}\n${out.slice(insertAt)}`;
522
521
  }
522
+ // src/cli/commands/init.ts
523
523
  /**
524
- * Lists `vi18n.gen.ts` in the `include` of the tsconfig that compiles the
525
- * sources, when that file is plain JSON (a JSONC file with comments is left
526
- * alone: rewriting it would drop them). Without `include` or `files` of its
527
- * own or through `extends`, TypeScript already sees every file; with only
528
- * inherited ones, the snippet to add is printed. A config that has `files` but no
529
- * `include` never gets an `include` added (the snippet is printed), and a
530
- * solution-style config (`references` and nothing of its own to compile, as
531
- * create-vite's) is never edited: adding `include` there would make it a
532
- * project of its own, which breaks `tsc -b`. Its reference whose `include`
533
- * covers the source directory is the one edited instead.
524
+ * `vi18n init [--yes] [--format po|json] [--locales a,b] [--source-locale a] [--rich]`
525
+ * (INTERNALS §2.14, PLAN §5.19): the way into a project. Writes
526
+ * `vi18n.config.ts` (never over an existing one), adds the plugin to the
527
+ * exported config's `plugins` in `vite.config.*`, creates every locale's
528
+ * empty catalog, writes `vi18n.gen.ts` and lists it in the tsconfig that
529
+ * compiles the sources. `--rich` copies the `<T>` components for the
530
+ * project's Vue and Svelte and lists them in `extraction.importSources`
531
+ * (§6 D213); in a configured project it does only that. Each step
532
+ * that cannot edit a file safely prints the snippet instead.
534
533
  */
535
- async function addToTsconfig(root, gen, data, rel) {
536
- const file = await nearestTsconfig(root);
537
- if (file === null) return;
538
- const read = await readTsconfig(file);
539
- if (read === null) return;
540
- const sourceDir = SOURCE_DIRS.map((name) => join(root, name)).find((dir) => existsSync(dir)) ?? root;
541
- const json = read.json;
542
- if (json === null) {
543
- const entry = relative(dirname(file), gen).split(sep).join("/");
544
- data.manual.push({
545
- file: rel(file),
546
- snippet: `"include": [/* … */ ${JSON.stringify(entry)}]`
547
- });
548
- return;
549
- }
550
- if (typeof json !== "object" || Array.isArray(json)) return;
551
- const references = Array.isArray(json.references) ? json.references : [];
552
- const ownFiles = Array.isArray(json.files) ? json.files : null;
553
- if (!(references.length > 0 && json.include === void 0 && (json.files === void 0 || ownFiles?.length === 0))) {
554
- await listGenFile(file, read, gen, data, rel);
555
- return;
556
- }
557
- let first = null;
558
- for (const reference of references) {
559
- const path = reference?.path;
560
- if (typeof path !== "string") continue;
561
- let target = resolve(dirname(file), path);
562
- try {
563
- if ((await stat(target)).isDirectory()) target = join(target, "tsconfig.json");
564
- } catch {
565
- continue;
566
- }
567
- const referenced = await readTsconfig(target);
568
- if (referenced === null) continue;
569
- first ??= target;
570
- const include = referenced.json?.include;
571
- if (Array.isArray(include) && covers(include, dirname(target), sourceDir)) {
572
- await listGenFile(target, referenced, gen, data, rel);
573
- return;
574
- }
575
- }
576
- const entry = relative(dirname(first ?? file), gen).split(sep).join("/");
577
- data.manual.push({
578
- file: rel(first ?? file),
579
- snippet: `"include": [/* … */ ${JSON.stringify(entry)}]`
580
- });
581
- }
582
- /** Adds the entry to one config's `include`, or prints the snippet when that cannot be done safely. */
583
- async function listGenFile(file, read, gen, data, rel) {
584
- const entry = relative(dirname(file), gen).split(sep).join("/");
585
- const json = read.json;
586
- if (typeof json !== "object" || json === null || Array.isArray(json)) return;
587
- if (json.include === void 0 && json.files === void 0) {
588
- const snippet = await inheritedSnippet(file, json, gen, entry);
589
- if (snippet !== null) data.manual.push({
590
- file: rel(file),
591
- snippet
592
- });
593
- return;
594
- }
595
- if (json.include === void 0) {
596
- data.manual.push({
597
- file: rel(file),
598
- snippet: `"files": [/* … */ ${JSON.stringify(entry)}]`
599
- });
600
- return;
601
- }
602
- const include = Array.isArray(json.include) ? json.include : [];
603
- if (include.includes(entry) || include.includes("./" + entry)) {
604
- data.skipped.push(rel(file));
605
- return;
606
- }
607
- if (!read.plain) {
608
- data.manual.push({
609
- file: rel(file),
610
- snippet: `"include": [/* … */ ${JSON.stringify(entry)}]`
611
- });
612
- return;
534
+ async function init(ctx, flags) {
535
+ const dir = resolve(ctx.global.cwd);
536
+ const configFile = ctx.global.config === null ? join(dir, CONFIG_FILE) : resolve(dir, ctx.global.config);
537
+ const root = dirname(configFile);
538
+ if (flags.rich && existsSync(configFile)) return scaffoldOnly(ctx, root, configFile);
539
+ const input = configInput(await ask(ctx, flags), root);
540
+ const components = flags.rich ? richComponents(root) : [];
541
+ if (flags.rich && components.length === 0) throw noRichFramework();
542
+ if (components.length > 0) input.extraction = { importSources: components.map((c) => c.specifier) };
543
+ let config;
544
+ try {
545
+ config = resolveConfig(input, root, configFile);
546
+ } catch (error) {
547
+ if (isDiagnosticError(error)) throw new CliExit(EXIT.usage, [error.diagnostic]);
548
+ throw error;
613
549
  }
614
- json.include = [...include, entry];
615
- const text = read.text;
616
- const indent = /\n([ \t]+)\S/.exec(text.slice(text.indexOf("{") + 1))?.[1] ?? " ";
617
- await atomicWrite(file, JSON.stringify(json, null, indent) + (text.endsWith("\n") ? "\n" : ""));
618
- data.wrote.push(rel(file));
619
- }
620
- /**
621
- * The `include` snippet for a tsconfig with no `include` or `files` of its
622
- * own, or null when TypeScript already compiles the generated file. Such a
623
- * config takes both from `extends` (SvelteKit's `.svelte-kit/tsconfig.json`
624
- * lists globs under `../src` and a few files), and an `include` written here
625
- * replaces the inherited one, so the snippet repeats its entries, rebased to
626
- * this file. Inherited `files` stay: TypeScript adds an own `include` to them.
627
- */
628
- async function inheritedSnippet(file, json, gen, entry) {
629
- if (json.extends === void 0) return null;
630
- const include = await inherited(file, json, "include", /* @__PURE__ */ new Set([file]));
631
- const files = await inherited(file, json, "files", /* @__PURE__ */ new Set([file]));
632
- if (include === void 0 || files === void 0) return `"include": [/* every entry "extends" gives it (none given: nothing to add) */ ${JSON.stringify(entry)}]`;
633
- if (include === null && files === null) return null;
634
- const target = toSlash(gen);
635
- if (files !== null && files.list.some((f) => toSlash(resolve(files.base, f)) === target)) return null;
636
- if (include !== null && include.list.some((p) => matchesInclude(p, include.base, target))) return null;
637
- return `"include": [${[...include === null ? [] : include.list.map((p) => toSlash(relative(dirname(file), resolve(include.base, p))) || "."), entry].map((p) => JSON.stringify(p)).join(", ")}]`;
638
- }
639
- /**
640
- * `key` as `file` inherits it through `extends` (later bases override
641
- * earlier ones, as in TypeScript), with the directory its paths are relative
642
- * to; null when no base has it; undefined when a base cannot be read.
643
- */
644
- async function inherited(file, json, key, seen) {
645
- const bases = typeof json.extends === "string" ? [json.extends] : Array.isArray(json.extends) ? json.extends : [];
646
- let found = null;
647
- for (const spec of bases) {
648
- const target = typeof spec === "string" ? resolveExtends(file, spec) : null;
649
- if (target === null || seen.has(target)) return void 0;
650
- const base = (await readTsconfig(target))?.json;
651
- if (typeof base !== "object" || base === null || Array.isArray(base)) return void 0;
652
- const value = base[key];
653
- let result;
654
- if (value === void 0) result = await inherited(target, base, key, /* @__PURE__ */ new Set([...seen, target]));
655
- else if (Array.isArray(value) && value.every((v) => typeof v === "string")) result = {
656
- list: value,
657
- base: dirname(target)
550
+ const data = emptyInitData(config);
551
+ const rel = relativeTo(root);
552
+ if (existsSync(configFile)) {
553
+ ctx.out.report([{
554
+ code: "config-invalid",
555
+ severity: "error",
556
+ message: `${rel(configFile)} already exists; vi18n init never overwrites it (edit it, or run vi18n extract)`,
557
+ file: configFile
558
+ }]);
559
+ return {
560
+ exitCode: EXIT.failure,
561
+ data
658
562
  };
659
- else return void 0;
660
- if (result === void 0) return void 0;
661
- if (result !== null) found = result;
662
563
  }
663
- return found;
664
- }
665
- /** The file an `extends` entry names, as TypeScript finds it; null when it cannot be found. */
666
- function resolveExtends(file, spec) {
667
- if (spec.startsWith("./") || spec.startsWith("../") || isAbsolute(spec)) {
668
- const path = resolve(dirname(file), spec);
669
- if (existsSync(path)) return path;
670
- return !path.endsWith(".json") && existsSync(path + ".json") ? path + ".json" : null;
564
+ await writeFileAtomic(configFile, configSource(input));
565
+ data.wrote.push(rel(configFile));
566
+ if (flags.rich) await writeComponents(root, components, data, rel);
567
+ await addPlugin(root, data, rel);
568
+ const layout = catalogLayout(config);
569
+ const header = {
570
+ idScheme: idScheme(config.ids.length),
571
+ sourceLocale: config.sourceLocale
572
+ };
573
+ for (const locale of config.locales) {
574
+ const path = catalogPath(config, locale);
575
+ if (existsSync(path)) {
576
+ data.skipped.push(rel(path));
577
+ continue;
578
+ }
579
+ const isSourceLocale = locale === config.sourceLocale;
580
+ const text = serializeCatalog(emptyCatalog(locale, layout, header), {
581
+ isSourceLocale,
582
+ version: VERSION
583
+ });
584
+ await writeFileAtomic(path, text);
585
+ data.wrote.push(rel(path));
671
586
  }
672
- const require = createRequire(file);
673
- const candidates = spec.endsWith(".json") ? [spec] : [`${spec}.json`, `${spec}/tsconfig.json`];
674
- for (const candidate of candidates) try {
675
- return require.resolve(candidate);
676
- } catch {}
677
- return null;
587
+ const gen = join(root, GEN_FILE);
588
+ if (await writeGenFile(config)) data.wrote.push(rel(gen));
589
+ await addToTsconfig(root, gen, data, rel);
590
+ printSummary(ctx, data);
591
+ ctx.out.result(`\nNext: wrap strings in t("…") and run vi18n extract.`);
592
+ return {
593
+ exitCode: EXIT.ok,
594
+ data
595
+ };
678
596
  }
679
- function toSlash(path) {
680
- return path.split(sep).join("/");
597
+ function emptyInitData(config) {
598
+ return {
599
+ wrote: [],
600
+ skipped: [],
601
+ manual: [],
602
+ sourceLocale: config.sourceLocale,
603
+ locales: config.locales,
604
+ format: config.catalogs.format
605
+ };
681
606
  }
682
- /**
683
- * Whether a tsconfig `include` pattern (relative to `base`) takes `file`
684
- * (absolute, `/`-separated): `*` and `?` within a segment, `**` across
685
- * directories, and a pattern without wildcards as a file or a directory.
686
- */
687
- function matchesInclude(pattern, base, file) {
688
- const absolute = toSlash(resolve(base, pattern));
689
- if (!/[*?]/.test(pattern)) return file === absolute || file.startsWith(absolute + "/");
690
- let regex = "";
691
- for (let i = 0; i < absolute.length; i++) {
692
- const c = absolute[i];
693
- if (c === "*" && absolute[i + 1] === "*") {
694
- const slash = absolute[i + 2] === "/";
695
- regex += slash ? "(?:[^/]*/)*" : ".*";
696
- i += slash ? 2 : 1;
697
- } else if (c === "*") regex += "[^/]*";
698
- else if (c === "?") regex += "[^/]";
699
- else regex += /[\\^$.+()[\]{}|]/.test(c) ? "\\" + c : c;
700
- }
701
- return new RegExp(`^${regex}$`).test(file);
607
+ function printSummary(ctx, data) {
608
+ for (const file of data.wrote) ctx.out.result(`created ${file}`);
609
+ for (const file of data.skipped) ctx.out.result(`kept ${file}`);
610
+ for (const { file, snippet } of data.manual) ctx.out.result(`\nAdd to ${file} by hand:\n${snippet}`);
702
611
  }
703
612
  /**
704
- * A tsconfig as JSON when it is plain JSON (`plain`: safe to rewrite), else
705
- * read leniently past comments and trailing commas (only to look at it);
706
- * null when it cannot be read at all.
613
+ * One component per framework the root `package.json` depends on, beside
614
+ * the project's other shared components: `<src>/lib` (SvelteKit's `$lib`)
615
+ * when it exists, else `<src>/components`. React, Preact and Solid get
616
+ * none: `rich()` returns what JSX renders, and the `<T>` macro is compiled
617
+ * away (§6 D213).
707
618
  */
708
- async function readTsconfig(file) {
709
- let text;
710
- try {
711
- text = await readFile(file, "utf8");
712
- } catch {
713
- return null;
714
- }
619
+ function richComponents(root) {
620
+ let deps = {};
715
621
  try {
716
- return {
717
- json: JSON.parse(text),
718
- text,
719
- plain: true
622
+ const pkg = JSON.parse(readFileSyncSafe(join(root, "package.json")));
623
+ deps = {
624
+ ...pkg.dependencies,
625
+ ...pkg.devDependencies
720
626
  };
721
627
  } catch {}
722
- try {
723
- return {
724
- json: JSON.parse(stripJsonc(text)),
725
- text,
726
- plain: false
727
- };
728
- } catch {
729
- return {
730
- json: null,
731
- text,
732
- plain: false
733
- };
734
- }
628
+ const sourceDir = SOURCE_DIRS.find((name) => existsSync(join(root, name)));
629
+ const base = sourceDir === void 0 ? "" : sourceDir + "/";
630
+ const dir = existsSync(join(root, base + "lib")) ? base + "lib" : base + "components";
631
+ const out = [];
632
+ if ("vue" in deps) out.push({
633
+ file: `${dir}/T.vue`,
634
+ specifier: `./${dir}/T.vue`,
635
+ source: T_VUE
636
+ });
637
+ if ("svelte" in deps) out.push({
638
+ file: `${dir}/T.svelte`,
639
+ specifier: `./${dir}/T.svelte`,
640
+ source: T_SVELTE
641
+ });
642
+ return out;
735
643
  }
736
- /** JSONC → JSON: comments and trailing commas outside strings removed. */
737
- function stripJsonc(text) {
738
- let out = "";
739
- for (let i = 0; i < text.length; i++) {
740
- const c = text[i];
741
- if (c === "\"") {
742
- let j = i + 1;
743
- while (j < text.length && text[j] !== "\"") j += text[j] === "\\" ? 2 : 1;
744
- out += text.slice(i, j + 1);
745
- i = j;
746
- } else if (c === "/" && text[i + 1] === "/") {
747
- while (i < text.length && text[i] !== "\n") i++;
748
- out += "\n";
749
- } else if (c === "/" && text[i + 1] === "*") {
750
- const end = text.indexOf("*/", i + 2);
751
- i = end === -1 ? text.length : end + 1;
752
- } else out += c;
753
- }
754
- return out.replace(/,(\s*[}\]])/g, "$1");
644
+ function noRichFramework() {
645
+ return usageError("--rich copies a <T> component for Vue and Svelte, and package.json depends on neither; in JSX, rich() and the <T> macro need no component");
755
646
  }
756
- /** Whether an `include` list reaches `dir`: a pattern's static prefix contains it. */
757
- function covers(include, base, dir) {
758
- for (const pattern of include) {
759
- if (typeof pattern !== "string") continue;
760
- const segments = [];
761
- for (const segment of pattern.split("/")) {
762
- if (/[*?[{]/.test(segment)) break;
763
- segments.push(segment);
764
- }
765
- const prefix = resolve(base, ...segments);
766
- const rel = relative(prefix, dir);
767
- if (rel === "" || !rel.startsWith("..") && !isAbsolute(rel)) return true;
768
- }
769
- return false;
647
+ function readFileSyncSafe(file) {
648
+ return existsSync(file) ? readFileSync(file, "utf8") : "";
770
649
  }
771
- async function nearestTsconfig(from) {
772
- for (let dir = from;; dir = dirname(dir)) {
773
- const file = join(dir, "tsconfig.json");
774
- try {
775
- if ((await stat(file)).isFile()) return file;
776
- } catch {}
777
- if (WORKSPACE_MARKERS.some((marker) => existsSync(join(dir, marker)))) return null;
778
- if (dirname(dir) === dir) return null;
650
+ /** Copies the components, never over a file that exists. */
651
+ async function writeComponents(root, components, data, rel) {
652
+ for (const component of components) {
653
+ const path = join(root, component.file);
654
+ if (existsSync(path)) {
655
+ data.skipped.push(rel(path));
656
+ continue;
657
+ }
658
+ await writeFileAtomic(path, component.source);
659
+ data.wrote.push(rel(path));
779
660
  }
780
661
  }
781
- async function atomicWrite(path, content) {
782
- const temp = `${path}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
662
+ /**
663
+ * `--rich` in a configured project: copy the components and, unless the
664
+ * config already names them, print the `importSources` entry to add (the
665
+ * config is the user's code, and `init` edits only what it can parse safely).
666
+ */
667
+ async function scaffoldOnly(ctx, root, configFile) {
668
+ const rel = relativeTo(root);
669
+ let config;
783
670
  try {
784
- await writeFile(temp, content);
785
- await rename(temp, path);
671
+ config = await loadConfig({
672
+ cwd: root,
673
+ configFile
674
+ });
786
675
  } catch (error) {
787
- await rm(temp, { force: true });
676
+ if (isDiagnosticError(error)) throw new CliExit(EXIT.usage, [error.diagnostic]);
788
677
  throw error;
789
678
  }
679
+ const data = emptyInitData(config);
680
+ const components = richComponents(root);
681
+ if (components.length === 0) throw noRichFramework();
682
+ await writeComponents(root, components, data, rel);
683
+ const text = readFileSyncSafe(configFile);
684
+ const missing = components.filter((c) => !text.includes(c.specifier.slice(2)));
685
+ if (missing.length > 0) data.manual.push({
686
+ file: rel(configFile),
687
+ snippet: `extraction: { importSources: [${missing.map((c) => JSON.stringify(c.specifier)).join(", ")}] },`
688
+ });
689
+ printSummary(ctx, data);
690
+ return {
691
+ exitCode: EXIT.ok,
692
+ data
693
+ };
694
+ }
695
+ /**
696
+ * Flags first; questions only for what they leave open, only on a terminal,
697
+ * and never with `--yes` or `--json` (an agent or CI must not hang).
698
+ */
699
+ async function ask(ctx, flags) {
700
+ const prompt = flags.yes || ctx.global.json ? void 0 : ctx.io.prompt;
701
+ let locales = flags.locales;
702
+ let sourceLocale = flags.sourceLocale;
703
+ let format = flags.format;
704
+ if (prompt !== void 0) {
705
+ if (sourceLocale === null) sourceLocale = (await prompt("Source locale (the language of the strings in your code)", locales[0] ?? "en")).trim();
706
+ if (locales.length === 0) locales = (await prompt("Locales, comma-separated", sourceLocale || "en")).split(",").map((l) => l.trim()).filter((l) => l !== "");
707
+ if (format === null) {
708
+ const answer = (await prompt("Catalog format (po or json)", "po")).trim().toLowerCase();
709
+ if (answer !== "po" && answer !== "json") throw usageError(`catalog format must be po or json, not "${answer}"`);
710
+ format = answer;
711
+ }
712
+ }
713
+ sourceLocale = sourceLocale || locales[0] || "en";
714
+ if (!locales.includes(sourceLocale)) locales = [sourceLocale, ...locales];
715
+ for (const locale of locales) {
716
+ let canonical;
717
+ try {
718
+ canonical = Intl.getCanonicalLocales(locale)[0];
719
+ } catch {
720
+ canonical = void 0;
721
+ }
722
+ if (canonical !== locale) throw usageError(canonical === void 0 ? `"${locale}" is not a BCP 47 locale` : `"${locale}" is not in canonical form; use "${canonical}"`);
723
+ }
724
+ return {
725
+ sourceLocale,
726
+ locales: [...new Set(locales)],
727
+ format: format ?? "po"
728
+ };
729
+ }
730
+ /** Only what differs from the defaults, so the file stays a short starting point. */
731
+ function configInput(answers, root) {
732
+ const input = {
733
+ sourceLocale: answers.sourceLocale,
734
+ locales: answers.locales
735
+ };
736
+ if (answers.format === "json") input.catalogs = { format: "json" };
737
+ const sourceDir = SOURCE_DIRS.find((name) => existsSync(join(root, name)));
738
+ if (sourceDir === void 0) input.project = { include: ["."] };
739
+ else if (sourceDir !== "src") input.project = { include: [sourceDir] };
740
+ return input;
741
+ }
742
+ function configSource(input) {
743
+ const lines = [
744
+ "import { defineConfig } from \"@menapo/vi18n/config\";",
745
+ "",
746
+ "export default defineConfig({",
747
+ ` sourceLocale: ${JSON.stringify(input.sourceLocale)},`,
748
+ ` locales: [${(input.locales ?? []).map((l) => JSON.stringify(l)).join(", ")}],`
749
+ ];
750
+ if (input.catalogs?.format === "json") lines.push(" catalogs: { format: \"json\" },");
751
+ if (input.project?.include !== void 0) lines.push(` project: { include: [${input.project.include.map((p) => JSON.stringify(p)).join(", ")}] },`);
752
+ const sources = input.extraction?.importSources;
753
+ if (sources !== void 0) lines.push(` extraction: { importSources: [${sources.map((p) => JSON.stringify(p)).join(", ")}] },`);
754
+ lines.push("});", "");
755
+ return lines.join("\n");
790
756
  }
791
- //#endregion
792
757
  export { init };