@funnelsgrove/cli 0.1.231 → 0.1.237

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 (35) hide show
  1. package/README.md +11 -0
  2. package/dist/cli.js +10 -0
  3. package/dist/localeContentSource.d.ts +13 -0
  4. package/dist/localeContentSource.js +117 -0
  5. package/dist/localeFilePlan.d.ts +4 -0
  6. package/dist/localeFilePlan.js +63 -0
  7. package/dist/localeModuleEdits.d.ts +19 -0
  8. package/dist/localeModuleEdits.js +97 -0
  9. package/dist/locales.d.ts +6 -0
  10. package/dist/locales.js +92 -0
  11. package/funnel-contract-compatibility.json +38 -38
  12. package/package.json +4 -4
  13. package/template_docs/.funnelsgrove-docs.json +5 -5
  14. package/template_docs/AGENTS.md +1 -0
  15. package/template_docs/docs/funnelsgrove/contracts/content-answers.md +69 -0
  16. package/template_docs/docs/funnelsgrove/migrations/step-contract-v3.md +1 -1
  17. package/template_docs/funnel-docs.config.json +1 -1
  18. package/template_scaffold/.funnelsgrove-docs.json +5 -5
  19. package/template_scaffold/.funnelsgrove-scaffold.json +35 -15
  20. package/template_scaffold/AGENTS.md +1 -0
  21. package/template_scaffold/docs/funnelsgrove/contracts/content-answers.md +69 -0
  22. package/template_scaffold/docs/funnelsgrove/migrations/step-contract-v3.md +1 -1
  23. package/template_scaffold/funnel-docs.config.json +1 -1
  24. package/template_scaffold/package-lock.json +15 -15
  25. package/template_scaffold/package.json +3 -3
  26. package/template_scaffold/src/app/subscription-dashboard/page.tsx +22 -19
  27. package/template_scaffold/src/components/FunnelFlow.tsx +11 -5
  28. package/template_scaffold/src/components/paywall/PaywallRenewalDisclaimer.tsx +23 -0
  29. package/template_scaffold/src/components/paywall/localize-paywall-plan-labels.ts +15 -0
  30. package/template_scaffold/src/config/billing.plans.ts +11 -10
  31. package/template_scaffold/src/config/billing.test.plans.ts +11 -10
  32. package/template_scaffold/src/steps/content/runtime.content.ts +22 -0
  33. package/template_scaffold/src/steps/content/step-32-paywall.content.ts +41 -1
  34. package/template_scaffold/src/steps/content/subscription-dashboard.content.ts +54 -0
  35. package/template_scaffold/src/steps/step-32-paywall.tsx +12 -22
package/README.md CHANGED
@@ -150,3 +150,14 @@ rows changed since the last pull. Pull again to resolve a concurrent edit.
150
150
 
151
151
  Use `--api-url` or `FUNNELSGROVE_API_URL` for non-production APIs.
152
152
  Use `--config` or `FUNNELSGROVE_CONFIG` to keep test credentials separate from the default `~/.funnelsgrove/config.json`.
153
+
154
+ ### Add a content locale
155
+
156
+ Run `fgrove locales add ru --dir ./my-funnel` to copy every default content
157
+ object into `src/localization/ru/`, preserving its path relative to `src/`.
158
+ Original content stays in place; translated files import its structural type.
159
+ Repeat runs preserve translations, add missing exports and repair registrations.
160
+ Translate the new content, run `npx tsc --noEmit`, review `?locale=ru` and the live builder Preview language
161
+ selector, then sync and publish through the normal workflow. Run `fgrove docs`
162
+ for the full localization guide. The funnel must use a runtime release supporting
163
+ URL locale selection; this command does not upgrade dependencies.
package/dist/cli.js CHANGED
@@ -7,6 +7,7 @@ import { createInterface } from 'node:readline/promises';
7
7
  import path from 'node:path';
8
8
  import { fileURLToPath } from 'node:url';
9
9
  import { Command } from 'commander';
10
+ import { addFunnelLocale } from './locales.js';
10
11
  import { CURRENT_STEP_CONTRACT_VERSION, FUNNEL_CONTRACT_DIAGNOSTIC_CODES, PREVIOUS_STEP_CONTRACT_VERSION, createFunnelContractDiagnostic, } from '@funnelsgrove/runtime';
11
12
  import { abortFunnelSourceCandidate, applyFunnelDraftPatch, beginFunnelSourceCandidate, callTrpcProcedure, createFunnelExperimentFromSpec, finalizeFunnelDirectAssetUpload, finalizeFunnelSourceCandidate, prepareFunnelDirectAssetUpload, stageFunnelSourceCandidate, } from './apiClient.js';
12
13
  import { cliReleaseIdentity } from './cliIdentity.js';
@@ -2980,6 +2981,15 @@ addExamples(githubCommand
2980
2981
  });
2981
2982
  printValueRows(formatGitHubJobRows(result));
2982
2983
  });
2984
+ program.command('locales')
2985
+ .description('Manage local funnel content languages')
2986
+ .command('add <locale>')
2987
+ .description('Create or complete typed localization files without translating')
2988
+ .option('--dir <path>', 'Local funnel directory', '.')
2989
+ .action(async (locale, options) => {
2990
+ const result = await addFunnelLocale(path.resolve(options.dir), locale);
2991
+ console.log(`${result.locale}\t${result.added.length} added\t${result.existing.length} already present`);
2992
+ });
2983
2993
  addExamples(program
2984
2994
  .command('validate')
2985
2995
  .description('Validate a local funnel against the current authoring contract')
@@ -0,0 +1,13 @@
1
+ import ts from 'typescript';
2
+ export declare const modulePath: (from: string, to: string) => string;
3
+ export declare function property(object: ts.ObjectLiteralExpression, name: string): ts.PropertyAssignment | undefined;
4
+ export type ContentDefinition = {
5
+ name: string;
6
+ type: string;
7
+ defaultLocale: string;
8
+ map: ts.ObjectLiteralExpression;
9
+ };
10
+ export declare function readContentDefinitions(parsed: ts.SourceFile): ContentDefinition[];
11
+ /** Copies authored expressions, redirecting same-file inheritance to the translated export. */
12
+ export declare function translatedExpression(value: ts.Expression, parsed: ts.SourceFile, definitions: ContentDefinition[], locale: string, existingBindings?: ReadonlyMap<string, string | null>): string;
13
+ export declare function contentImports(parsed: ts.SourceFile, destination: string, payload: string): string[];
@@ -0,0 +1,117 @@
1
+ import path from 'node:path';
2
+ import ts from 'typescript';
3
+ import { selectImport } from './localeModuleEdits.js';
4
+ export const modulePath = (from, to) => {
5
+ const relative = path.relative(path.dirname(from), to).split(path.sep).join('/').replace(/\.ts$/, '');
6
+ return relative.startsWith('.') ? relative : `./${relative}`;
7
+ };
8
+ export function property(object, name) {
9
+ return object.properties.find((node) => ts.isPropertyAssignment(node) && (ts.isIdentifier(node.name) || ts.isStringLiteral(node.name)) && node.name.text === name);
10
+ }
11
+ export function readContentDefinitions(parsed) {
12
+ const definitions = [];
13
+ for (const statement of parsed.statements) {
14
+ if (!ts.isVariableStatement(statement))
15
+ continue;
16
+ for (const declaration of statement.declarationList.declarations) {
17
+ let expression = declaration.initializer;
18
+ let type = declaration.type;
19
+ while (expression && (ts.isAsExpression(expression) || ts.isSatisfiesExpression(expression) || ts.isParenthesizedExpression(expression))) {
20
+ if (!ts.isParenthesizedExpression(expression) && ts.isTypeReferenceNode(expression.type) && expression.type.typeArguments?.length)
21
+ type = expression.type;
22
+ expression = expression.expression;
23
+ }
24
+ if (!expression || !ts.isObjectLiteralExpression(expression))
25
+ continue;
26
+ const base = property(expression, 'defaultLocale');
27
+ const locales = property(expression, 'locales');
28
+ if (!base || !locales)
29
+ continue;
30
+ if (!ts.isStringLiteral(base.initializer) || !ts.isObjectLiteralExpression(locales.initializer))
31
+ throw new Error('defaultLocale and locales must be literals.');
32
+ if (locales.initializer.properties.some((item) => !ts.isPropertyAssignment(item) || !(ts.isIdentifier(item.name) || ts.isStringLiteral(item.name))))
33
+ throw new Error('locale entries must be explicit properties, without spreads or computed names.');
34
+ const contentType = type && ts.isTypeReferenceNode(type) && type.typeArguments?.[0];
35
+ if (!ts.isIdentifier(declaration.name) || !contentType || !ts.isTypeReferenceNode(contentType) || !ts.isIdentifier(contentType.typeName))
36
+ throw new Error('Declare a named content type and use satisfies LocalizedStepContent<YourContentType>.');
37
+ if (contentType.typeArguments?.length)
38
+ throw new Error('Use a named non-generic content type; generic content types are not supported by locale copying.');
39
+ const typeName = contentType.typeName.text;
40
+ const owner = parsed.statements.find((item) => (ts.isTypeAliasDeclaration(item) || ts.isInterfaceDeclaration(item)) && item.name.text === typeName);
41
+ if (!owner)
42
+ throw new Error(`Declare ${typeName} in this original content file so translations can import its structure.`);
43
+ definitions.push({ name: declaration.name.text, type: typeName, defaultLocale: base.initializer.text, map: locales.initializer });
44
+ }
45
+ }
46
+ if (!definitions.length)
47
+ throw new Error('No localized content definition found.');
48
+ return definitions;
49
+ }
50
+ /** Copies authored expressions, redirecting same-file inheritance to the translated export. */
51
+ export function translatedExpression(value, parsed, definitions, locale, existingBindings = new Map()) {
52
+ const edits = [];
53
+ const options = { noLib: true, noResolve: true };
54
+ const host = ts.createCompilerHost(options);
55
+ host.getSourceFile = (name) => path.resolve(name) === path.resolve(parsed.fileName) ? parsed : undefined;
56
+ const checker = ts.createProgram([parsed.fileName], options, host).getTypeChecker();
57
+ const visit = (node) => {
58
+ if (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) {
59
+ const map = node.expression;
60
+ const key = ts.isPropertyAccessExpression(node) ? node.name.text : ts.isStringLiteral(node.argumentExpression) ? node.argumentExpression.text : null;
61
+ if (ts.isPropertyAccessExpression(map) && map.name.text === 'locales' && ts.isIdentifier(map.expression)) {
62
+ const definition = definitions.find((item) => item.name === map.expression.getText(parsed));
63
+ if (definition && key) {
64
+ if (key !== definition.defaultLocale && key !== locale) {
65
+ throw new Error(`Cannot copy ${node.getText(parsed)}: inheritance must use the default or requested locale. Make this copy explicit before retrying.`);
66
+ }
67
+ const binding = existingBindings.get(definition.name);
68
+ if (binding === null)
69
+ throw new Error(`Import the re-exported ${definition.name} into the translation before adding inherited content.`);
70
+ edits.push({ start: node.getStart(parsed), end: node.end, text: binding ?? definition.name });
71
+ return;
72
+ }
73
+ }
74
+ }
75
+ if (ts.isIdentifier(node)
76
+ && !(ts.isPropertyAssignment(node.parent) && node.parent.name === node)
77
+ && !(ts.isPropertyAccessExpression(node.parent) && node.parent.name === node)) {
78
+ const symbol = ts.isShorthandPropertyAssignment(node.parent)
79
+ ? checker.getShorthandAssignmentValueSymbol(node.parent)
80
+ : checker.getSymbolAtLocation(node);
81
+ const uncopied = symbol?.declarations?.some((declaration) => {
82
+ if (declaration.getSourceFile() !== parsed || declaration.pos >= value.pos && declaration.end <= value.end)
83
+ return false;
84
+ let parent = declaration;
85
+ while (parent && parent !== parsed) {
86
+ if (ts.isImportDeclaration(parent))
87
+ return false;
88
+ parent = parent.parent;
89
+ }
90
+ return true;
91
+ });
92
+ if (uncopied)
93
+ throw new Error(`Content references local helper ${node.text}. Inline it in the content object or move it into an independent imported module before adding a locale.`);
94
+ }
95
+ ts.forEachChild(node, visit);
96
+ };
97
+ visit(value);
98
+ let result = value.getText(parsed);
99
+ const offset = value.getStart(parsed);
100
+ for (const edit of edits.sort((a, b) => b.start - a.start))
101
+ result = result.slice(0, edit.start - offset) + edit.text + result.slice(edit.end - offset);
102
+ return result;
103
+ }
104
+ export function contentImports(parsed, destination, payload) {
105
+ const identifiers = new Set();
106
+ const visit = (node) => { if (ts.isIdentifier(node))
107
+ identifiers.add(node.text); ts.forEachChild(node, visit); };
108
+ visit(ts.createSourceFile('content.ts', payload, ts.ScriptTarget.Latest, true));
109
+ return parsed.statements.flatMap((statement) => {
110
+ if (!ts.isImportDeclaration(statement) || !statement.importClause || !ts.isStringLiteral(statement.moduleSpecifier))
111
+ return [];
112
+ const specifier = statement.moduleSpecifier.text;
113
+ const target = specifier.startsWith('.') ? modulePath(destination, path.resolve(path.dirname(parsed.fileName), specifier)) : specifier;
114
+ const selected = selectImport(statement, parsed, (name) => identifiers.has(name), ts.factory.createStringLiteral(target));
115
+ return selected ? [selected] : [];
116
+ });
117
+ }
@@ -0,0 +1,4 @@
1
+ export declare function planLocaleFile(file: string, source: string, destination: string, translated: string | null, locale: string): {
2
+ source: string;
3
+ translated: string | null;
4
+ };
@@ -0,0 +1,63 @@
1
+ import ts from 'typescript';
2
+ import { contentImports, modulePath, property, readContentDefinitions, translatedExpression } from './localeContentSource.js';
3
+ import { appendTranslation, applySourceEdits, exportedBindings, importedNames, insertImports } from './localeModuleEdits.js';
4
+ export function planLocaleFile(file, source, destination, translated, locale) {
5
+ const parsed = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true);
6
+ const definitions = readContentDefinitions(parsed);
7
+ const canonical = (tag) => Intl.getCanonicalLocales(tag)[0];
8
+ if (new Set(definitions.map((item) => canonical(item.defaultLocale))).size !== 1) {
9
+ throw new Error('Definitions in one content file must use the same defaultLocale.');
10
+ }
11
+ if (canonical(definitions[0].defaultLocale) === locale)
12
+ return { source, translated };
13
+ const translatedModule = ts.createSourceFile(destination, translated ?? '', ts.ScriptTarget.Latest, true);
14
+ const present = exportedBindings(translatedModule);
15
+ const sourceImports = importedNames(parsed);
16
+ const registrationPath = modulePath(file, destination);
17
+ const edits = [];
18
+ const exports = [];
19
+ const imports = [];
20
+ const newTypes = new Set();
21
+ const typeNames = new Set(definitions.map((item) => item.type));
22
+ for (const definition of definitions) {
23
+ const previous = definition.map.properties.find((item) => ts.isPropertyAssignment(item)
24
+ && canonical(item.name.text) === locale);
25
+ if (!present.has(definition.name)) {
26
+ const value = (previous ?? property(definition.map, definition.defaultLocale))?.initializer;
27
+ if (!value || !ts.isObjectLiteralExpression(value)) {
28
+ throw new Error(`Restore the missing translation for ${definition.name} or provide inline object content before retrying.`);
29
+ }
30
+ exports.push(`export const ${definition.name}: ${definition.type} = ${translatedExpression(value, parsed, definitions, locale, present)};`);
31
+ newTypes.add(definition.type);
32
+ }
33
+ const registered = [...sourceImports].find(([, value]) => value.module === registrationPath && value.name === definition.name && !value.typeOnly)?.[0];
34
+ if (registered && previous && ts.isIdentifier(previous.initializer) && previous.initializer.text === registered)
35
+ continue;
36
+ let alias = registered ?? `${definition.name}_${locale.replace(/-/g, '_')}`;
37
+ if (!registered) {
38
+ const initial = alias;
39
+ let suffix = 1;
40
+ while (source.includes(alias))
41
+ alias = `${initial}_${suffix++}`;
42
+ imports.push(`import { ${definition.name} as ${alias} } from ${JSON.stringify(registrationPath)};`);
43
+ }
44
+ if (previous)
45
+ edits.push({ start: previous.initializer.getStart(parsed), end: previous.initializer.end, text: alias });
46
+ else
47
+ edits.push({ start: definition.map.end - 1, end: definition.map.end - 1, text: `${definition.map.properties.hasTrailingComma ? '' : ','}\n ${JSON.stringify(locale)}: ${alias},\n ` });
48
+ }
49
+ for (const statement of parsed.statements) {
50
+ if ((ts.isTypeAliasDeclaration(statement) || ts.isInterfaceDeclaration(statement)) && typeNames.has(statement.name.text)
51
+ && !statement.modifiers?.some((item) => item.kind === ts.SyntaxKind.ExportKeyword)) {
52
+ edits.push({ start: statement.getStart(parsed), end: statement.getStart(parsed), text: 'export ' });
53
+ }
54
+ }
55
+ const payload = exports.join('\n\n');
56
+ const dependencies = exports.length ? contentImports(parsed, destination, payload) : [];
57
+ if (newTypes.size)
58
+ dependencies.unshift(`import type { ${[...newTypes].join(', ')} } from ${JSON.stringify(modulePath(destination, file))};`);
59
+ return {
60
+ source: insertImports(applySourceEdits(source, edits), imports),
61
+ translated: appendTranslation(translated ?? '', dependencies, exports),
62
+ };
63
+ }
@@ -0,0 +1,19 @@
1
+ import ts from 'typescript';
2
+ export type SourceEdit = {
3
+ start: number;
4
+ end: number;
5
+ text: string;
6
+ };
7
+ export declare function applySourceEdits(source: string, edits: SourceEdit[]): string;
8
+ /** Keep module directives and leading comments before generated imports. */
9
+ export declare function insertImports(source: string, imports: string[]): string;
10
+ export declare function importedNames(parsed: ts.SourceFile): Map<string, {
11
+ module: string;
12
+ name: string;
13
+ typeOnly: boolean;
14
+ }>;
15
+ export declare function exportedBindings(parsed: ts.SourceFile): Map<string, string | null>;
16
+ /** Print the selected bindings, preserving import kinds and attributes. */
17
+ export declare function selectImport(statement: ts.ImportDeclaration, parsed: ts.SourceFile, keep: (name: string) => boolean, module?: ts.Expression): string | null;
18
+ /** Reuse matching imports when adding definitions to an already translated module. */
19
+ export declare function appendTranslation(source: string, imports: string[], definitions: string[]): string;
@@ -0,0 +1,97 @@
1
+ import ts from 'typescript';
2
+ export function applySourceEdits(source, edits) {
3
+ return [...edits].sort((a, b) => b.start - a.start).reduce((result, edit) => result.slice(0, edit.start) + edit.text + result.slice(edit.end), source);
4
+ }
5
+ /** Keep module directives and leading comments before generated imports. */
6
+ export function insertImports(source, imports) {
7
+ if (!imports.length)
8
+ return source;
9
+ const parsed = ts.createSourceFile('content.ts', source, ts.ScriptTarget.Latest, true);
10
+ const first = parsed.statements.find((statement) => !ts.isExpressionStatement(statement) || !ts.isStringLiteral(statement.expression));
11
+ const offset = first?.getStart(parsed) ?? source.length;
12
+ return source.slice(0, offset) + imports.join('\n') + '\n' + source.slice(offset);
13
+ }
14
+ export function importedNames(parsed) {
15
+ const names = new Map();
16
+ for (const statement of parsed.statements) {
17
+ if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier))
18
+ continue;
19
+ const clause = statement.importClause;
20
+ if (!clause)
21
+ continue;
22
+ const module = statement.moduleSpecifier.text;
23
+ if (clause.name)
24
+ names.set(clause.name.text, { module, name: 'default', typeOnly: clause.isTypeOnly });
25
+ const bindings = clause.namedBindings;
26
+ if (bindings && ts.isNamespaceImport(bindings))
27
+ names.set(bindings.name.text, { module, name: '*', typeOnly: clause.isTypeOnly });
28
+ if (bindings && ts.isNamedImports(bindings)) {
29
+ for (const item of bindings.elements)
30
+ names.set(item.name.text, { module, name: (item.propertyName ?? item.name).text, typeOnly: clause.isTypeOnly || item.isTypeOnly });
31
+ }
32
+ }
33
+ return names;
34
+ }
35
+ export function exportedBindings(parsed) {
36
+ const names = new Map();
37
+ for (const statement of parsed.statements) {
38
+ if (ts.isVariableStatement(statement)
39
+ && statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)) {
40
+ for (const declaration of statement.declarationList.declarations) {
41
+ if (ts.isIdentifier(declaration.name))
42
+ names.set(declaration.name.text, declaration.name.text);
43
+ }
44
+ }
45
+ if (ts.isExportDeclaration(statement) && !statement.isTypeOnly
46
+ && statement.exportClause && ts.isNamedExports(statement.exportClause)) {
47
+ for (const item of statement.exportClause.elements) {
48
+ if (!item.isTypeOnly)
49
+ names.set(item.name.text, statement.moduleSpecifier ? null : (item.propertyName ?? item.name).text);
50
+ }
51
+ }
52
+ }
53
+ return names;
54
+ }
55
+ /** Print the selected bindings, preserving import kinds and attributes. */
56
+ export function selectImport(statement, parsed, keep, module = statement.moduleSpecifier) {
57
+ const clause = statement.importClause;
58
+ if (!clause)
59
+ return null;
60
+ const name = clause.name && keep(clause.name.text) ? clause.name : undefined;
61
+ const bindings = clause.namedBindings;
62
+ const named = bindings && (ts.isNamespaceImport(bindings)
63
+ ? keep(bindings.name.text) ? bindings : undefined
64
+ : ts.factory.createNamedImports(bindings.elements.filter((item) => keep(item.name.text))));
65
+ if (!name && (!named || ts.isNamedImports(named) && !named.elements.length))
66
+ return null;
67
+ const updated = ts.factory.updateImportDeclaration(statement, statement.modifiers, ts.factory.updateImportClause(clause, clause.isTypeOnly, name, named), module, statement.attributes);
68
+ return ts.createPrinter().printNode(ts.EmitHint.Unspecified, updated, parsed);
69
+ }
70
+ /** Reuse matching imports when adding definitions to an already translated module. */
71
+ export function appendTranslation(source, imports, definitions) {
72
+ const parsed = ts.createSourceFile('content.ts', source, ts.ScriptTarget.Latest, true);
73
+ const existing = importedNames(parsed);
74
+ const additions = [];
75
+ for (const text of imports) {
76
+ const imported = ts.createSourceFile('import.ts', text, ts.ScriptTarget.Latest, true);
77
+ const statement = imported.statements[0];
78
+ const names = importedNames(imported);
79
+ const needed = (name) => {
80
+ const previous = existing.get(name);
81
+ const next = names.get(name);
82
+ if (!previous) {
83
+ existing.set(name, next);
84
+ return true;
85
+ }
86
+ if (previous.module !== next.module || previous.name !== next.name || previous.typeOnly !== next.typeOnly) {
87
+ throw new Error(`Translation import ${name} conflicts with an existing import. Resolve the import before retrying.`);
88
+ }
89
+ return false;
90
+ };
91
+ const addition = selectImport(statement, imported, needed);
92
+ if (addition)
93
+ additions.push(addition);
94
+ }
95
+ const updated = insertImports(source, additions);
96
+ return definitions.length ? `${updated}${updated.endsWith('\n') || !updated ? '' : '\n'}\n${definitions.join('\n\n')}\n` : updated;
97
+ }
@@ -0,0 +1,6 @@
1
+ /** Plan every source change before writing; original content keeps its existing location. */
2
+ export declare function addFunnelLocale(directory: string, requestedLocale: string): Promise<{
3
+ locale: string;
4
+ added: string[];
5
+ existing: string[];
6
+ }>;
@@ -0,0 +1,92 @@
1
+ import { lstat, mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { planLocaleFile } from './localeFilePlan.js';
4
+ function canonicalLocale(value) {
5
+ try {
6
+ const [locale] = Intl.getCanonicalLocales(value);
7
+ if (locale)
8
+ return locale;
9
+ }
10
+ catch { /* Invalid tag. */ }
11
+ throw new Error(`Invalid locale: ${value}. Use a language tag such as ru or pt-BR.`);
12
+ }
13
+ async function contentFiles(directory, localizationRoot) {
14
+ const files = [];
15
+ for (const entry of (await readdir(directory, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
16
+ const file = path.join(directory, entry.name);
17
+ if (file === localizationRoot)
18
+ continue;
19
+ if (entry.isDirectory())
20
+ files.push(...await contentFiles(file, localizationRoot));
21
+ else if (entry.isFile() && entry.name.endsWith('.content.ts'))
22
+ files.push(file);
23
+ }
24
+ return files;
25
+ }
26
+ async function exists(file) {
27
+ try {
28
+ await lstat(file);
29
+ return true;
30
+ }
31
+ catch (error) {
32
+ if (error.code === 'ENOENT')
33
+ return false;
34
+ throw error;
35
+ }
36
+ }
37
+ async function assertDestinationPath(root, file) {
38
+ let current = root;
39
+ for (const part of path.relative(root, file).split(path.sep)) {
40
+ current = path.join(current, part);
41
+ try {
42
+ if ((await lstat(current)).isSymbolicLink())
43
+ throw new Error(`Localization destination contains a symbolic link: ${current}`);
44
+ }
45
+ catch (error) {
46
+ if (error.code !== 'ENOENT')
47
+ throw error;
48
+ }
49
+ }
50
+ }
51
+ /** Plan every source change before writing; original content keeps its existing location. */
52
+ export async function addFunnelLocale(directory, requestedLocale) {
53
+ directory = path.resolve(directory);
54
+ const locale = canonicalLocale(requestedLocale);
55
+ const sourceRoot = path.join(directory, 'src');
56
+ const localizationRoot = path.join(sourceRoot, 'localization');
57
+ const files = await contentFiles(sourceRoot, localizationRoot);
58
+ if (!files.length)
59
+ throw new Error('No src/**/*.content.ts files found. Move translatable copy into content definitions first.');
60
+ const edits = [];
61
+ const added = [];
62
+ const existing = [];
63
+ for (const file of files) {
64
+ const relative = path.relative(directory, file).split(path.sep).join('/');
65
+ try {
66
+ const source = await readFile(file, 'utf8');
67
+ const destination = path.join(localizationRoot, locale, path.relative(sourceRoot, file));
68
+ const localizedPath = path.relative(directory, destination).split(path.sep).join('/');
69
+ await assertDestinationPath(sourceRoot, destination);
70
+ const translated = await exists(destination) ? await readFile(destination, 'utf8') : null;
71
+ const plan = planLocaleFile(file, source, destination, translated, locale);
72
+ if (plan.source === source && plan.translated === translated) {
73
+ existing.push(translated === null ? relative : localizedPath);
74
+ continue;
75
+ }
76
+ if (plan.translated !== translated && plan.translated !== null) {
77
+ edits.push({ file: destination, source: plan.translated, create: translated === null });
78
+ }
79
+ if (plan.source !== source)
80
+ edits.push({ file, source: plan.source });
81
+ added.push(localizedPath);
82
+ }
83
+ catch (error) {
84
+ throw new Error(`${relative}: ${error.message}`);
85
+ }
86
+ }
87
+ for (const edit of edits) {
88
+ await mkdir(path.dirname(edit.file), { recursive: true });
89
+ await writeFile(edit.file, edit.source, edit.create ? { flag: 'wx' } : undefined);
90
+ }
91
+ return { locale, added, existing };
92
+ }