@verbaly/compiler 0.49.0 → 0.51.0

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.
@@ -1 +1 @@
1
- {"version":3,"file":"config-DYlbHrPc.js","names":[],"sources":["../src/pseudo.ts","../src/config.ts"],"sourcesContent":["import type { Catalog, Catalogs } from './catalog';\nimport type { ResolvedConfig } from './config';\n\nexport const PSEUDO_LOCALE = 'en-XA';\n\nconst ACCENTS: Record<string, string> = {\n a: 'á',\n b: 'ƀ',\n c: 'ç',\n d: 'đ',\n e: 'é',\n f: 'ƒ',\n g: 'ğ',\n h: 'ĥ',\n i: 'í',\n j: 'ĵ',\n k: 'ķ',\n l: 'ĺ',\n m: 'ɱ',\n n: 'ñ',\n o: 'ó',\n p: 'þ',\n q: 'ǫ',\n r: 'ŕ',\n s: 'š',\n t: 'ţ',\n u: 'ú',\n v: 'ṽ',\n w: 'ŵ',\n x: 'ẋ',\n y: 'ý',\n z: 'ž',\n A: 'Á',\n B: 'Ɓ',\n C: 'Ç',\n D: 'Đ',\n E: 'É',\n F: 'Ƒ',\n G: 'Ğ',\n H: 'Ĥ',\n I: 'Í',\n J: 'Ĵ',\n K: 'Ķ',\n L: 'Ĺ',\n M: 'Ḿ',\n N: 'Ñ',\n O: 'Ó',\n P: 'Þ',\n Q: 'Ǫ',\n R: 'Ŕ',\n S: 'Š',\n T: 'Ţ',\n U: 'Ú',\n V: 'Ṽ',\n W: 'Ŵ',\n X: 'Ẍ',\n Y: 'Ý',\n Z: 'Ž',\n};\n\nconst TAG_AT = /<\\/?[a-zA-Z][\\w-]*\\/?>/y;\n\n// params, variant blocks, tags and escapes survive verbatim\nexport function pseudoLocalize(message: string): string {\n let out = '';\n let letters = 0;\n let i = 0;\n while (i < message.length) {\n const two = message.slice(i, i + 2);\n if (two === '{{' || two === '}}' || two === '||' || two === '##') {\n out += two;\n i += 2;\n continue;\n }\n const ch = message[i]!;\n if (ch === '{') {\n const end = matchBrace(message, i);\n out += message.slice(i, end);\n i = end;\n continue;\n }\n if (ch === '<') {\n TAG_AT.lastIndex = i;\n const m = TAG_AT.exec(message);\n if (m) {\n out += m[0];\n i += m[0].length;\n continue;\n }\n }\n const mapped = ACCENTS[ch];\n if (mapped) {\n out += mapped;\n letters += 1;\n } else {\n out += ch;\n }\n i += 1;\n }\n const pad = '~'.repeat(Math.ceil(letters / 3));\n return `⟦${out}${pad ? ' ' + pad : ''}⟧`;\n}\n\nfunction matchBrace(message: string, start: number): number {\n let depth = 0;\n for (let i = start; i < message.length; i++) {\n const two = message.slice(i, i + 2);\n if (two === '{{' || two === '}}') {\n i += 1;\n continue;\n }\n const ch = message[i];\n if (ch === '{') depth += 1;\n else if (ch === '}') {\n depth -= 1;\n if (depth === 0) return i + 1;\n }\n }\n return message.length; // unbalanced → verbatim\n}\n\n// regenerates the whole pseudo catalog from the source catalog\nexport function pseudoCatalogs(\n cfg: ResolvedConfig,\n catalogs: Catalogs,\n locale: string = PSEUDO_LOCALE,\n): string[] {\n const source = catalogs[cfg.sourceLocale] ?? {};\n const target: Catalog = {};\n for (const [key, msg] of Object.entries(source)) {\n target[key] = msg ? pseudoLocalize(msg) : '';\n }\n catalogs[locale] = target;\n return Object.keys(target).filter((key) => target[key]);\n}\n","import { existsSync, readFileSync, readdirSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport type { RichLink, Routing } from 'verbaly';\nimport { PSEUDO_LOCALE } from './pseudo';\nimport type { TranslateProvider } from './translate';\n\n// a term maps to how it must come out: one rendering for every locale, or one per locale\nexport type GlossaryEntry = string | Record<string, string>;\n\nexport interface TranslateConfig {\n provider?: 'claude' | TranslateProvider;\n model?: string;\n batchSize?: number;\n concurrency?: number;\n retries?: number;\n instructions?: string;\n glossary?: Record<string, GlossaryEntry>;\n}\n\nexport interface RedirectConfig {\n on?: 'root' | 'all';\n storageKey?: string | false;\n}\n\nexport interface BundleConfig {\n exclude?: string[];\n}\n\nexport interface RenderConfig {\n links?: Record<string, RichLink>;\n exclude?: string[];\n site?: string;\n attribute?: string;\n base?: string;\n baseUrl?: string;\n hreflang?: boolean;\n sitemap?: boolean | string;\n redirect?: boolean | RedirectConfig;\n clean?: boolean;\n}\n\nexport interface VerbalyConfig {\n root?: string;\n dir?: string;\n sourceLocale?: string;\n locales?: string[];\n routing?: Routing;\n icu?: boolean;\n relative?: boolean;\n include?: string[];\n exclude?: string[];\n dts?: string | false;\n translate?: TranslateConfig;\n render?: RenderConfig;\n bundle?: BundleConfig;\n}\n\nexport interface ResolvedConfig {\n root: string;\n dir: string;\n sourceLocale: string;\n locales: string[];\n localesDeclared: boolean;\n routing: Routing;\n icu: boolean | undefined;\n relative: boolean | undefined;\n include: string[];\n exclude: string[];\n dts: string | false | undefined;\n translate: TranslateConfig;\n render: RenderConfig;\n bundle: BundleConfig;\n}\n\nexport function resolveConfig(config: VerbalyConfig = {}): ResolvedConfig {\n const root = resolve(config.root ?? process.cwd());\n const dir = resolve(root, config.dir ?? 'locales');\n const sourceLocale = config.sourceLocale ?? 'en';\n\n const localesDeclared = config.locales !== undefined;\n const locales = new Set<string>([sourceLocale, ...(config.locales ?? [])]);\n // a declared list is the list: discovery is for a project that never wrote one down\n if (!localesDeclared && existsSync(dir)) {\n for (const file of readdirSync(dir)) {\n if (file.endsWith('.json') && !file.startsWith('.') && file !== `${PSEUDO_LOCALE}.json`) {\n locales.add(file.slice(0, -5));\n }\n }\n }\n\n return {\n root,\n dir,\n sourceLocale,\n localesDeclared,\n // the mode follows the surface: render is what builds a url tree per locale, so it is the tell\n routing: config.routing ?? (config.render ? 'prefix-except-source' : 'no-prefix'),\n // the catalogs decide on their own; these only force it for messages that land after the build\n icu: config.icu,\n relative: config.relative,\n locales: [...locales],\n include: config.include ?? ['{src,app}/**/*.{js,jsx,ts,tsx,mjs,mts,svelte,vue,astro}'],\n exclude: config.exclude ?? ['**/node_modules/**', '**/dist/**'],\n dts: typeof config.dts === 'string' ? resolve(root, config.dts) : config.dts,\n translate: config.translate ?? {},\n render: config.render ?? {},\n bundle: config.bundle ?? {},\n };\n}\n\nconst CONFIG_FILES = [\n 'verbaly.config.js',\n 'verbaly.config.mjs',\n 'verbaly.config.ts',\n 'verbaly.config.mts',\n 'verbaly.config.json',\n];\n\nexport function findConfigFile(root: string): string | undefined {\n return CONFIG_FILES.find((name) => existsSync(join(root, name)));\n}\n\nexport async function loadConfigFile(root: string): Promise<VerbalyConfig> {\n for (const name of ['verbaly.config.js', 'verbaly.config.mjs']) {\n const path = join(root, name);\n if (existsSync(path)) {\n const mod = (await import(pathToFileURL(path).href)) as { default?: VerbalyConfig };\n return mod.default ?? {};\n }\n }\n for (const name of ['verbaly.config.ts', 'verbaly.config.mts']) {\n const path = join(root, name);\n if (existsSync(path)) return loadTsConfig(path);\n }\n const jsonPath = join(root, 'verbaly.config.json');\n if (existsSync(jsonPath)) {\n return JSON.parse(readFileSync(jsonPath, 'utf8')) as VerbalyConfig;\n }\n return {};\n}\n\nasync function loadTsConfig(path: string): Promise<VerbalyConfig> {\n try {\n const { bundleRequire } = await import('bundle-require');\n const { mod } = await bundleRequire<{ default?: VerbalyConfig }>({ filepath: path });\n return mod.default ?? {};\n } catch (error) {\n if (isModuleNotFound(error, 'esbuild')) {\n throw new Error(`[verbaly] ${path} needs esbuild: install it with pnpm add -D esbuild`, {\n cause: error,\n });\n }\n throw error;\n }\n}\n\nexport function isModuleNotFound(error: unknown, name: string): boolean {\n return (\n error instanceof Error &&\n (error as { code?: string }).code === 'ERR_MODULE_NOT_FOUND' &&\n error.message.includes(name)\n );\n}\n\n// non-source locales a command may write to (optional CLI override, always config-bounded)\nexport function targetLocales(cfg: ResolvedConfig, override?: string[]): string[] {\n return (override ?? cfg.locales).filter(\n (locale) => locale !== cfg.sourceLocale && cfg.locales.includes(locale),\n );\n}\n\n// file config + inline overrides\nexport async function loadConfig(\n root: string,\n overrides: VerbalyConfig = {},\n): Promise<ResolvedConfig> {\n const fileConfig = await loadConfigFile(root);\n return resolveConfig({ ...fileConfig, ...definedOnly(overrides), root });\n}\n\nfunction definedOnly(config: VerbalyConfig): VerbalyConfig {\n return Object.fromEntries(\n Object.entries(config).filter(([, value]) => value !== undefined),\n ) as VerbalyConfig;\n}\n"],"mappings":"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"}
1
+ {"version":3,"file":"config-DYlbHrPc.js","names":[],"sources":["../src/pseudo.ts","../src/config.ts"],"sourcesContent":["import type { Catalog, Catalogs } from './catalog';\nimport type { ResolvedConfig } from './config';\n\nexport const PSEUDO_LOCALE = 'en-XA';\n\nconst ACCENTS: Record<string, string> = {\n a: 'á',\n b: 'ƀ',\n c: 'ç',\n d: 'đ',\n e: 'é',\n f: 'ƒ',\n g: 'ğ',\n h: 'ĥ',\n i: 'í',\n j: 'ĵ',\n k: 'ķ',\n l: 'ĺ',\n m: 'ɱ',\n n: 'ñ',\n o: 'ó',\n p: 'þ',\n q: 'ǫ',\n r: 'ŕ',\n s: 'š',\n t: 'ţ',\n u: 'ú',\n v: 'ṽ',\n w: 'ŵ',\n x: 'ẋ',\n y: 'ý',\n z: 'ž',\n A: 'Á',\n B: 'Ɓ',\n C: 'Ç',\n D: 'Đ',\n E: 'É',\n F: 'Ƒ',\n G: 'Ğ',\n H: 'Ĥ',\n I: 'Í',\n J: 'Ĵ',\n K: 'Ķ',\n L: 'Ĺ',\n M: 'Ḿ',\n N: 'Ñ',\n O: 'Ó',\n P: 'Þ',\n Q: 'Ǫ',\n R: 'Ŕ',\n S: 'Š',\n T: 'Ţ',\n U: 'Ú',\n V: 'Ṽ',\n W: 'Ŵ',\n X: 'Ẍ',\n Y: 'Ý',\n Z: 'Ž',\n};\n\nconst TAG_AT = /<\\/?[a-zA-Z][\\w-]*\\/?>/y;\n\n// params, variant blocks, tags and escapes survive verbatim\nexport function pseudoLocalize(message: string): string {\n let out = '';\n let letters = 0;\n let i = 0;\n while (i < message.length) {\n const two = message.slice(i, i + 2);\n if (two === '{{' || two === '}}' || two === '||' || two === '##') {\n out += two;\n i += 2;\n continue;\n }\n const ch = message[i]!;\n if (ch === '{') {\n const end = matchBrace(message, i);\n out += message.slice(i, end);\n i = end;\n continue;\n }\n if (ch === '<') {\n TAG_AT.lastIndex = i;\n const m = TAG_AT.exec(message);\n if (m) {\n out += m[0];\n i += m[0].length;\n continue;\n }\n }\n const mapped = ACCENTS[ch];\n if (mapped) {\n out += mapped;\n letters += 1;\n } else {\n out += ch;\n }\n i += 1;\n }\n const pad = '~'.repeat(Math.ceil(letters / 3));\n return `⟦${out}${pad ? ' ' + pad : ''}⟧`;\n}\n\nfunction matchBrace(message: string, start: number): number {\n let depth = 0;\n for (let i = start; i < message.length; i++) {\n const two = message.slice(i, i + 2);\n if (two === '{{' || two === '}}') {\n i += 1;\n continue;\n }\n const ch = message[i];\n if (ch === '{') depth += 1;\n else if (ch === '}') {\n depth -= 1;\n if (depth === 0) return i + 1;\n }\n }\n return message.length; // unbalanced → verbatim\n}\n\n// regenerates the whole pseudo catalog from the source catalog\nexport function pseudoCatalogs(\n cfg: ResolvedConfig,\n catalogs: Catalogs,\n locale: string = PSEUDO_LOCALE,\n): string[] {\n const source = catalogs[cfg.sourceLocale] ?? {};\n const target: Catalog = {};\n for (const [key, msg] of Object.entries(source)) {\n target[key] = msg ? pseudoLocalize(msg) : '';\n }\n catalogs[locale] = target;\n return Object.keys(target).filter((key) => target[key]);\n}\n","import { existsSync, readFileSync, readdirSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport type { RichLink, Routing } from 'verbaly';\nimport { PSEUDO_LOCALE } from './pseudo';\nimport type { TranslateProvider } from './translate';\n\n// a term maps to how it must come out: one rendering for every locale, or one per locale\nexport type GlossaryEntry = string | Record<string, string>;\n\nexport interface TranslateConfig {\n provider?: 'claude' | TranslateProvider;\n model?: string;\n batchSize?: number;\n concurrency?: number;\n retries?: number;\n instructions?: string;\n glossary?: Record<string, GlossaryEntry>;\n}\n\nexport interface RedirectConfig {\n on?: 'root' | 'all';\n storageKey?: string | false;\n}\n\nexport interface BundleConfig {\n exclude?: string[];\n}\n\nexport interface RenderConfig {\n links?: Record<string, RichLink>;\n exclude?: string[];\n site?: string;\n attribute?: string;\n base?: string;\n baseUrl?: string;\n hreflang?: boolean;\n sitemap?: boolean | string;\n redirect?: boolean | RedirectConfig;\n clean?: boolean;\n inlineCatalog?: boolean;\n}\n\nexport interface VerbalyConfig {\n root?: string;\n dir?: string;\n sourceLocale?: string;\n locales?: string[];\n routing?: Routing;\n icu?: boolean;\n relative?: boolean;\n include?: string[];\n exclude?: string[];\n dts?: string | false;\n translate?: TranslateConfig;\n render?: RenderConfig;\n bundle?: BundleConfig;\n}\n\nexport interface ResolvedConfig {\n root: string;\n dir: string;\n sourceLocale: string;\n locales: string[];\n localesDeclared: boolean;\n routing: Routing;\n icu: boolean | undefined;\n relative: boolean | undefined;\n include: string[];\n exclude: string[];\n dts: string | false | undefined;\n translate: TranslateConfig;\n render: RenderConfig;\n bundle: BundleConfig;\n}\n\nexport function resolveConfig(config: VerbalyConfig = {}): ResolvedConfig {\n const root = resolve(config.root ?? process.cwd());\n const dir = resolve(root, config.dir ?? 'locales');\n const sourceLocale = config.sourceLocale ?? 'en';\n\n const localesDeclared = config.locales !== undefined;\n const locales = new Set<string>([sourceLocale, ...(config.locales ?? [])]);\n // a declared list is the list: discovery is for a project that never wrote one down\n if (!localesDeclared && existsSync(dir)) {\n for (const file of readdirSync(dir)) {\n if (file.endsWith('.json') && !file.startsWith('.') && file !== `${PSEUDO_LOCALE}.json`) {\n locales.add(file.slice(0, -5));\n }\n }\n }\n\n return {\n root,\n dir,\n sourceLocale,\n localesDeclared,\n // the mode follows the surface: render is what builds a url tree per locale, so it is the tell\n routing: config.routing ?? (config.render ? 'prefix-except-source' : 'no-prefix'),\n // the catalogs decide on their own; these only force it for messages that land after the build\n icu: config.icu,\n relative: config.relative,\n locales: [...locales],\n include: config.include ?? ['{src,app}/**/*.{js,jsx,ts,tsx,mjs,mts,svelte,vue,astro}'],\n exclude: config.exclude ?? ['**/node_modules/**', '**/dist/**'],\n dts: typeof config.dts === 'string' ? resolve(root, config.dts) : config.dts,\n translate: config.translate ?? {},\n render: config.render ?? {},\n bundle: config.bundle ?? {},\n };\n}\n\nconst CONFIG_FILES = [\n 'verbaly.config.js',\n 'verbaly.config.mjs',\n 'verbaly.config.ts',\n 'verbaly.config.mts',\n 'verbaly.config.json',\n];\n\nexport function findConfigFile(root: string): string | undefined {\n return CONFIG_FILES.find((name) => existsSync(join(root, name)));\n}\n\nexport async function loadConfigFile(root: string): Promise<VerbalyConfig> {\n for (const name of ['verbaly.config.js', 'verbaly.config.mjs']) {\n const path = join(root, name);\n if (existsSync(path)) {\n const mod = (await import(pathToFileURL(path).href)) as { default?: VerbalyConfig };\n return mod.default ?? {};\n }\n }\n for (const name of ['verbaly.config.ts', 'verbaly.config.mts']) {\n const path = join(root, name);\n if (existsSync(path)) return loadTsConfig(path);\n }\n const jsonPath = join(root, 'verbaly.config.json');\n if (existsSync(jsonPath)) {\n return JSON.parse(readFileSync(jsonPath, 'utf8')) as VerbalyConfig;\n }\n return {};\n}\n\nasync function loadTsConfig(path: string): Promise<VerbalyConfig> {\n try {\n const { bundleRequire } = await import('bundle-require');\n const { mod } = await bundleRequire<{ default?: VerbalyConfig }>({ filepath: path });\n return mod.default ?? {};\n } catch (error) {\n if (isModuleNotFound(error, 'esbuild')) {\n throw new Error(`[verbaly] ${path} needs esbuild: install it with pnpm add -D esbuild`, {\n cause: error,\n });\n }\n throw error;\n }\n}\n\nexport function isModuleNotFound(error: unknown, name: string): boolean {\n return (\n error instanceof Error &&\n (error as { code?: string }).code === 'ERR_MODULE_NOT_FOUND' &&\n error.message.includes(name)\n );\n}\n\n// non-source locales a command may write to (optional CLI override, always config-bounded)\nexport function targetLocales(cfg: ResolvedConfig, override?: string[]): string[] {\n return (override ?? cfg.locales).filter(\n (locale) => locale !== cfg.sourceLocale && cfg.locales.includes(locale),\n );\n}\n\n// file config + inline overrides\nexport async function loadConfig(\n root: string,\n overrides: VerbalyConfig = {},\n): Promise<ResolvedConfig> {\n const fileConfig = await loadConfigFile(root);\n return resolveConfig({ ...fileConfig, ...definedOnly(overrides), root });\n}\n\nfunction definedOnly(config: VerbalyConfig): VerbalyConfig {\n return Object.fromEntries(\n Object.entries(config).filter(([, value]) => value !== undefined),\n ) as VerbalyConfig;\n}\n"],"mappings":"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"}
package/dist/index.d.ts CHANGED
@@ -3,10 +3,10 @@ import MagicString from "magic-string";
3
3
  //#region src/catalog.d.ts
4
4
  type Catalog = Record<string, string>;
5
5
  type Catalogs = Record<string, Catalog>;
6
- declare function loadCatalogs(cfg: ResolvedConfig): Catalogs;
7
- declare function writeCatalog(cfg: ResolvedConfig, locale: string, catalog: Catalog): string;
8
- declare function needsIcu(catalogs: Catalogs): boolean;
9
- declare function needsRelative(catalogs: Catalogs): boolean;
6
+ export declare function loadCatalogs(cfg: ResolvedConfig): Catalogs;
7
+ export declare function writeCatalog(cfg: ResolvedConfig, locale: string, catalog: Catalog): string;
8
+ export declare function needsIcu(catalogs: Catalogs): boolean;
9
+ export declare function needsRelative(catalogs: Catalogs): boolean;
10
10
  //#endregion
11
11
  //#region src/translate.d.ts
12
12
  interface TranslateRequest {
@@ -46,9 +46,9 @@ interface TranslateResult {
46
46
  pending: Record<string, string[]>;
47
47
  failed: TranslateFailure[];
48
48
  }
49
- declare function translateCatalogs(cfg: ResolvedConfig, catalogs: Catalogs, provider: TranslateProvider, options?: TranslateOptions): Promise<TranslateResult>;
50
- declare function formatTranslateFailures(failed: TranslateFailure[]): string[];
51
- declare function resolveProvider(cfg: ResolvedConfig, model?: string): Promise<TranslateProvider>;
49
+ export declare function translateCatalogs(cfg: ResolvedConfig, catalogs: Catalogs, provider: TranslateProvider, options?: TranslateOptions): Promise<TranslateResult>;
50
+ export declare function formatTranslateFailures(failed: TranslateFailure[]): string[];
51
+ export declare function resolveProvider(cfg: ResolvedConfig, model?: string): Promise<TranslateProvider>;
52
52
  //#endregion
53
53
  //#region src/config.d.ts
54
54
  type GlossaryEntry = string | Record<string, string>;
@@ -79,6 +79,7 @@ interface RenderConfig {
79
79
  sitemap?: boolean | string;
80
80
  redirect?: boolean | RedirectConfig;
81
81
  clean?: boolean;
82
+ inlineCatalog?: boolean;
82
83
  }
83
84
  interface VerbalyConfig {
84
85
  root?: string;
@@ -111,8 +112,8 @@ interface ResolvedConfig {
111
112
  render: RenderConfig;
112
113
  bundle: BundleConfig;
113
114
  }
114
- declare function resolveConfig(config?: VerbalyConfig): ResolvedConfig;
115
- declare function loadConfig(root: string, overrides?: VerbalyConfig): Promise<ResolvedConfig>;
115
+ export declare function resolveConfig(config?: VerbalyConfig): ResolvedConfig;
116
+ export declare function loadConfig(root: string, overrides?: VerbalyConfig): Promise<ResolvedConfig>;
116
117
  //#endregion
117
118
  //#region src/analyze.d.ts
118
119
  interface TaggedParam {
@@ -156,7 +157,7 @@ interface Analysis {
156
157
  }
157
158
  //#endregion
158
159
  //#region src/registry.d.ts
159
- declare class MessageRegistry {
160
+ export declare class MessageRegistry {
160
161
  private files;
161
162
  update(file: string, analysis: Analysis): void;
162
163
  remove(file: string): void;
@@ -171,19 +172,19 @@ declare class MessageRegistry {
171
172
  }
172
173
  //#endregion
173
174
  //#region src/bundle.d.ts
174
- declare function clientCatalogs(cfg: ResolvedConfig, catalogs: Catalogs): Catalogs;
175
+ export declare function clientCatalogs(cfg: ResolvedConfig, catalogs: Catalogs): Catalogs;
175
176
  //#endregion
176
177
  //#region src/extract.d.ts
177
- declare function extractProject(cfg: ResolvedConfig): Promise<MessageRegistry>;
178
- declare function collectOrigins(cfg: ResolvedConfig): Promise<Record<string, string[]>>;
178
+ export declare function extractProject(cfg: ResolvedConfig): Promise<MessageRegistry>;
179
+ export declare function collectOrigins(cfg: ResolvedConfig): Promise<Record<string, string[]>>;
179
180
  interface SyncResult {
180
181
  added: Record<string, string[]>;
181
182
  }
182
- declare function syncCatalogs(cfg: ResolvedConfig, catalogs: Catalogs, registry: MessageRegistry): SyncResult;
183
- declare function pruneCatalogs(cfg: ResolvedConfig, catalogs: Catalogs, registry: MessageRegistry): Record<string, string[]>;
183
+ export declare function syncCatalogs(cfg: ResolvedConfig, catalogs: Catalogs, registry: MessageRegistry): SyncResult;
184
+ export declare function pruneCatalogs(cfg: ResolvedConfig, catalogs: Catalogs, registry: MessageRegistry): Record<string, string[]>;
184
185
  //#endregion
185
186
  //#region src/key.d.ts
186
- declare function stableKey(message: string): string;
187
+ export declare function stableKey(message: string): string;
187
188
  //#endregion
188
189
  //#region src/codegen.d.ts
189
190
  interface RuntimeModuleOptions {
@@ -191,35 +192,39 @@ interface RuntimeModuleOptions {
191
192
  extraExports?: string;
192
193
  icu?: boolean;
193
194
  relative?: boolean;
195
+ inlineCatalog?: boolean;
194
196
  }
195
- declare function generateRuntimeModule(cfg: ResolvedConfig, options?: RuntimeModuleOptions): string;
196
- declare function generateLocaleModule(catalog: Catalog): string;
197
- declare function generateDts(catalog: Catalog): string;
198
- declare function writeDts(cfg: ResolvedConfig, catalog: Catalog, file?: string): void;
197
+ export declare function generateRuntimeModule(cfg: ResolvedConfig, options?: RuntimeModuleOptions): string;
198
+ export declare function generateLocaleModule(catalog: Catalog): string;
199
+ interface DtsOptions {
200
+ inlineCatalog?: boolean;
201
+ }
202
+ export declare function generateDts(catalog: Catalog, options?: DtsOptions): string;
203
+ export declare function writeDts(cfg: ResolvedConfig, catalog: Catalog, file?: string): void;
199
204
  //#endregion
200
205
  //#region src/transform.d.ts
201
206
  interface TransformResult {
202
207
  code: string;
203
208
  map: ReturnType<MagicString['generateMap']>;
204
209
  }
205
- declare function transformCode(code: string, file: string, analysis?: Analysis): TransformResult | null;
210
+ export declare function transformCode(code: string, file: string, analysis?: Analysis): TransformResult | null;
206
211
  //#endregion
207
212
  //#region src/plugin.d.ts
208
213
  interface PluginOptions extends VerbalyConfig {
209
214
  failOnMissing?: boolean;
210
215
  }
211
- declare const RESOLVED_VIRTUAL_ID: string;
212
- declare const LOCALE_MODULE_PREFIX = "\0virtual:verbaly/locale/";
213
- declare const SOURCE_FILE_RE: RegExp;
214
- declare function resolveVirtualId(id: string): string | undefined;
215
- declare function loadVirtualModule(id: string, cfg: ResolvedConfig, catalogs: Catalogs): string | undefined;
216
- declare function isTransformTarget(id: string): boolean;
217
- declare function createSourceFilter(cfg: ResolvedConfig): (id: string) => boolean;
218
- declare function transformSource(code: string, id: string, registry: MessageRegistry): {
216
+ export declare const RESOLVED_VIRTUAL_ID: string;
217
+ export declare const LOCALE_MODULE_PREFIX = "\0virtual:verbaly/locale/";
218
+ export declare const SOURCE_FILE_RE: RegExp;
219
+ export declare function resolveVirtualId(id: string): string | undefined;
220
+ export declare function loadVirtualModule(id: string, cfg: ResolvedConfig, catalogs: Catalogs): string | undefined;
221
+ export declare function isTransformTarget(id: string): boolean;
222
+ export declare function createSourceFilter(cfg: ResolvedConfig): (id: string) => boolean;
223
+ export declare function transformSource(code: string, id: string, registry: MessageRegistry): {
219
224
  messages: Catalog;
220
225
  result: TransformResult | null;
221
226
  };
222
- declare function runBuildGate(cfg: ResolvedConfig, registry: MessageRegistry, failOnMissing?: boolean): void;
227
+ export declare function runBuildGate(cfg: ResolvedConfig, registry: MessageRegistry, failOnMissing?: boolean): void;
223
228
  //#endregion
224
229
  //#region src/validate.d.ts
225
230
  type IssueSeverity = 'error' | 'warning';
@@ -246,16 +251,16 @@ interface CheckResult {
246
251
  unknown: UnknownEntry[];
247
252
  broken: BrokenEntry[];
248
253
  }
249
- declare function check(cfg: ResolvedConfig, catalogs: Catalogs, registry: MessageRegistry): CheckResult;
250
- declare function formatCheckResult(result: CheckResult, root?: string): string;
251
- declare function formatCheckWarnings(result: CheckResult): string;
254
+ export declare function check(cfg: ResolvedConfig, catalogs: Catalogs, registry: MessageRegistry): CheckResult;
255
+ export declare function formatCheckResult(result: CheckResult, root?: string): string;
256
+ export declare function formatCheckWarnings(result: CheckResult): string;
252
257
  //#endregion
253
258
  //#region src/drafts.d.ts
254
259
  type Drafts = Record<string, string[]>;
255
- declare function loadDrafts(cfg: ResolvedConfig): Drafts;
256
- declare function saveDrafts(cfg: ResolvedConfig, drafts: Drafts): void;
257
- declare function markDrafts(drafts: Drafts, locale: string, keys: string[]): void;
258
- declare function effectiveDrafts(drafts: Drafts, catalogs: Catalogs): Drafts;
260
+ export declare function loadDrafts(cfg: ResolvedConfig): Drafts;
261
+ export declare function saveDrafts(cfg: ResolvedConfig, drafts: Drafts): void;
262
+ export declare function markDrafts(drafts: Drafts, locale: string, keys: string[]): void;
263
+ export declare function effectiveDrafts(drafts: Drafts, catalogs: Catalogs): Drafts;
259
264
  //#endregion
260
265
  //#region src/status.d.ts
261
266
  interface LocaleStatus {
@@ -270,11 +275,11 @@ interface StatusResult {
270
275
  source: string;
271
276
  locales: LocaleStatus[];
272
277
  }
273
- declare function status(cfg: ResolvedConfig, catalogs: Catalogs, registry: MessageRegistry, drafts?: Drafts): StatusResult;
274
- declare function formatStatusResult(result: StatusResult): string;
278
+ export declare function status(cfg: ResolvedConfig, catalogs: Catalogs, registry: MessageRegistry, drafts?: Drafts): StatusResult;
279
+ export declare function formatStatusResult(result: StatusResult): string;
275
280
  //#endregion
276
281
  //#region src/text.d.ts
277
- declare function counted(count: number, noun: string, many?: string): string;
282
+ export declare function counted(count: number, noun: string, many?: string): string;
278
283
  //#endregion
279
284
  //#region src/doctor.d.ts
280
285
  interface DoctorEntry {
@@ -287,8 +292,8 @@ interface DoctorResult {
287
292
  ok: boolean;
288
293
  entries: DoctorEntry[];
289
294
  }
290
- declare function formatDoctorEntry(entry: DoctorEntry): string;
291
- declare function doctor(cfg: ResolvedConfig): Promise<DoctorResult>;
295
+ export declare function formatDoctorEntry(entry: DoctorEntry): string;
296
+ export declare function doctor(cfg: ResolvedConfig): Promise<DoctorResult>;
292
297
  //#endregion
293
298
  //#region src/init.d.ts
294
299
  interface InitOptions {
@@ -305,7 +310,7 @@ interface InitResult {
305
310
  next: string[];
306
311
  }
307
312
  type Host = 'nuxt' | 'next' | 'sveltekit' | 'astro' | 'vite' | 'webpack' | 'rspack' | 'rollup' | 'esbuild';
308
- declare function init(options?: InitOptions): Promise<InitResult>;
313
+ export declare function init(options?: InitOptions): Promise<InitResult>;
309
314
  //#endregion
310
315
  //#region src/wrap.d.ts
311
316
  interface WrapEntry {
@@ -336,7 +341,7 @@ interface WrapResult {
336
341
  interface WrapOptions {
337
342
  write?: boolean;
338
343
  }
339
- declare function wrapProject(cfg: ResolvedConfig, options?: WrapOptions): Promise<WrapResult>;
344
+ export declare function wrapProject(cfg: ResolvedConfig, options?: WrapOptions): Promise<WrapResult>;
340
345
  //#endregion
341
346
  //#region src/render.d.ts
342
347
  interface RenderSiteOptions {
@@ -359,8 +364,8 @@ interface RenderSiteResult {
359
364
  missing: Record<string, string[]>;
360
365
  untranslatedHead: string[];
361
366
  }
362
- declare function renderSite(cfg: ResolvedConfig, options?: RenderSiteOptions): Promise<RenderSiteResult>;
363
- declare function formatRenderWarnings(result: RenderSiteResult, sourceLocale: string): string[];
367
+ export declare function renderSite(cfg: ResolvedConfig, options?: RenderSiteOptions): Promise<RenderSiteResult>;
368
+ export declare function formatRenderWarnings(result: RenderSiteResult, sourceLocale: string): string[];
364
369
  //#endregion
365
- export { type BrokenEntry, type BundleConfig, type Catalog, type Catalogs, type CheckResult, type DoctorEntry, type DoctorResult, type Drafts, type GlossaryEntry, type Host, type InitOptions, type InitResult, type IssueSeverity, LOCALE_MODULE_PREFIX, type LocaleStatus, MessageRegistry, type MissingEntry, type PluginOptions, RESOLVED_VIRTUAL_ID, type RedirectConfig, type RenderConfig, type RenderSiteOptions, type RenderSiteResult, type ResolvedConfig, type RuntimeModuleOptions, SOURCE_FILE_RE, type StatusResult, type SyncResult, type TransformResult, type TranslateConfig, type TranslateFailure, type TranslateOptions, type TranslateProgress, type TranslateProvider, type TranslateRequest, type TranslateResult, type UnknownEntry, type VerbalyConfig, type WrapBlocked, type WrapEntry, type WrapOptions, type WrapResult, type WrapSkip, check, clientCatalogs, collectOrigins, counted, createSourceFilter, doctor, effectiveDrafts, extractProject, formatCheckResult, formatCheckWarnings, formatDoctorEntry, formatRenderWarnings, formatStatusResult, formatTranslateFailures, generateDts, generateLocaleModule, generateRuntimeModule, init, isTransformTarget, loadCatalogs, loadConfig, loadDrafts, loadVirtualModule, markDrafts, needsIcu, needsRelative, pruneCatalogs, renderSite, resolveConfig, resolveProvider, resolveVirtualId, runBuildGate, saveDrafts, stableKey, status, syncCatalogs, transformCode, transformSource, translateCatalogs, wrapProject, writeCatalog, writeDts };
370
+ export type { BrokenEntry, BundleConfig, Catalog, Catalogs, CheckResult, DoctorEntry, DoctorResult, Drafts, DtsOptions, GlossaryEntry, Host, InitOptions, InitResult, IssueSeverity, LocaleStatus, MissingEntry, PluginOptions, RedirectConfig, RenderConfig, RenderSiteOptions, RenderSiteResult, ResolvedConfig, RuntimeModuleOptions, StatusResult, SyncResult, TransformResult, TranslateConfig, TranslateFailure, TranslateOptions, TranslateProgress, TranslateProvider, TranslateRequest, TranslateResult, UnknownEntry, VerbalyConfig, WrapBlocked, WrapEntry, WrapOptions, WrapResult, WrapSkip };
366
371
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { a as resolveConfig, i as loadConfigFile, o as targetLocales, r as loadConfig, t as findConfigFile } from "./config-DYlbHrPc.js";
2
2
  import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
3
  import { dirname, join, relative } from "node:path";
4
- import { LOCALE_STORAGE_KEY, RICH_TAGS, VOID_TAGS, alternateLinks, createVerbaly, flatten, localeDirection, normalizeLink, parse, parseTags, safeAttribute } from "verbaly";
4
+ import { CATALOG_SCRIPT, LOCALE_STORAGE_KEY, RICH_TAGS, VOID_TAGS, alternateLinks, createVerbaly, flatten, localeDirection, normalizeLink, parse, parseTags, safeAttribute } from "verbaly";
5
5
  import { glob } from "tinyglobby";
6
6
  import { parse as parse$1 } from "@babel/parser";
7
7
  import { createHash } from "node:crypto";
@@ -943,16 +943,34 @@ function renderParamType(types) {
943
943
  ]) members.add(m);
944
944
  return [...members].join(" | ");
945
945
  }
946
+ const SLICE_HELPERS = `function readSlice(root, path) {
947
+ const locale = readPath({ supported: locales, path });
948
+ if (!locale || locale === sourceLocale) return undefined;
949
+ const messages = inlineMessages(root);
950
+ return messages ? { locale, messages } : undefined;
951
+ }
952
+
953
+ export function adoptPage(options) {
954
+ const slice = readSlice(options?.root, options?.path);
955
+ if (slice) v.addMessages(slice.locale, slice.messages, { partial: true });
956
+ return slice ? slice.locale : undefined;
957
+ }
958
+
959
+ `;
946
960
  function generateRuntimeModule(cfg, options = {}) {
947
961
  const importPath = options.localeImport ?? ((locale) => `virtual:verbaly/locale/${locale}`);
948
962
  const others = cfg.locales.filter((locale) => locale !== cfg.sourceLocale);
949
963
  const src = JSON.stringify(cfg.sourceLocale);
950
964
  const loaders = others.map((locale) => ` ${JSON.stringify(locale)}: () => import('${importPath(locale)}'),`).join("\n");
965
+ const icu = options.icu ? ",\n parseIcu" : "";
966
+ const rel = options.relative ? ",\n relativeFormatter" : "";
967
+ const slice = options.inlineCatalog ? ",\n inlineMessages" : "";
968
+ const slices = options.inlineCatalog ? SLICE_HELPERS : "";
951
969
  return `import {
952
970
  createVerbaly,
953
971
  localeFromPath as readPath,
954
972
  localePath as writePath,
955
- switchLocale as runSwitch${options.icu ? ",\n parseIcu" : ""}${options.relative ? ",\n relativeFormatter" : ""},
973
+ switchLocale as runSwitch${icu}${rel}${slice},
956
974
  } from 'verbaly';
957
975
  import source from '${importPath(cfg.sourceLocale)}';
958
976
 
@@ -990,13 +1008,13 @@ export async function loadMessages(locale) {
990
1008
  return loader ? (await loader()).default : {};
991
1009
  }
992
1010
 
993
- // per-request/per-instance factory (SSR): the singleton below is browser/SPA-only
994
- export function createInstance(options) {
1011
+ ${slices}// per-request/per-instance factory (SSR): the singleton below is browser/SPA-only
1012
+ export function createInstance(options) {${options.inlineCatalog ? "\n const page = readSlice();" : ""}
995
1013
  return createVerbaly({
996
- locale: ${src},
1014
+ locale: ${options.inlineCatalog ? `page ? page.locale : ${src}` : src},
997
1015
  fallback: ${src},
998
- messages: { [${src}]: source },
999
- loaders: localeLoaders,${options.icu ? "\n icu: parseIcu," : ""}
1016
+ messages: ${options.inlineCatalog ? `page ? { [${src}]: source, [page.locale]: page.messages } : { [${src}]: source }` : `{ [${src}]: source }`},
1017
+ loaders: localeLoaders,${options.inlineCatalog ? "\n partial: page ? [page.locale] : undefined," : ""}${options.icu ? "\n icu: parseIcu," : ""}
1000
1018
  ...options,${options.relative ? "\n // merged, not spread over: passing your own formatters must not drop this one\n formatters: { relative: relativeFormatter, ...options?.formatters }," : ""}
1001
1019
  });
1002
1020
  }
@@ -1030,7 +1048,7 @@ ${options.extraExports ?? ""}`;
1030
1048
  function generateLocaleModule(catalog) {
1031
1049
  return `export default ${JSON.stringify(catalog)};\n`;
1032
1050
  }
1033
- function generateDts(catalog) {
1051
+ function generateDts(catalog, options = {}) {
1034
1052
  const lines = [];
1035
1053
  for (const [key, message] of Object.entries(catalog).sort(([a], [b]) => a.localeCompare(b))) {
1036
1054
  const params = collectParams(message);
@@ -1063,7 +1081,7 @@ ${lines.join("\n")}
1063
1081
  path?: string;
1064
1082
  base?: string;
1065
1083
  }): string | undefined;
1066
- export function loadMessages(locale: string): Promise<Record<string, string>>;
1084
+ export function loadMessages(locale: string): Promise<Record<string, string>>;${options.inlineCatalog ? "\n export function adoptPage(options?: {\n root?: ParentNode;\n path?: string;\n }): string | undefined;" : ""}
1067
1085
  export function createInstance(
1068
1086
  options?: import('verbaly').VerbalyOptions<VerbalyKey>,
1069
1087
  ): import('verbaly').Verbaly<VerbalyKey>;
@@ -1102,7 +1120,7 @@ declare module 'virtual:verbaly/locale/*' {
1102
1120
  }
1103
1121
  function writeDts(cfg, catalog, file) {
1104
1122
  file ??= join(cfg.root, "verbaly.d.ts");
1105
- const content = generateDts(catalog);
1123
+ const content = generateDts(catalog, { inlineCatalog: cfg.render.inlineCatalog === true });
1106
1124
  try {
1107
1125
  if (readFileSync(file, "utf8") === content) return;
1108
1126
  } catch {}
@@ -1377,7 +1395,8 @@ function loadVirtualModule(id, cfg, catalogs) {
1377
1395
  const client = clientCatalogs(cfg, catalogs);
1378
1396
  if (id === RESOLVED_VIRTUAL_ID) return generateRuntimeModule(cfg, {
1379
1397
  icu: cfg.icu ?? needsIcu(client),
1380
- relative: cfg.relative ?? needsRelative(client)
1398
+ relative: cfg.relative ?? needsRelative(client),
1399
+ inlineCatalog: cfg.render.inlineCatalog === true
1381
1400
  });
1382
1401
  if (id.startsWith(LOCALE_MODULE_PREFIX)) return generateLocaleModule(client[id.slice(LOCALE_MODULE_PREFIX.length)] ?? {});
1383
1402
  }
@@ -1774,7 +1793,7 @@ async function doctor(cfg) {
1774
1793
  if (source && scanning && cfg.dts !== false) {
1775
1794
  const dtsPath = cfg.dts ?? join(cfg.root, "verbaly.d.ts");
1776
1795
  if (!existsSync(dtsPath)) warn("types", "verbaly.d.ts has not been generated", "run `npx verbaly extract`");
1777
- else if (readFileSync(dtsPath, "utf8") !== generateDts(source)) warn("types", "verbaly.d.ts is stale", "run `npx verbaly extract`");
1796
+ else if (readFileSync(dtsPath, "utf8") !== generateDts(source, { inlineCatalog: cfg.render.inlineCatalog === true })) warn("types", "verbaly.d.ts is stale", "run `npx verbaly extract`");
1778
1797
  else ok("types", "verbaly.d.ts is up to date");
1779
1798
  }
1780
1799
  const registry = await extractProject(cfg);
@@ -2120,6 +2139,8 @@ function localeInstance(catalogs, locale, sourceLocale) {
2120
2139
  }
2121
2140
  const HREFLANG_OPEN = "<!--verbaly:hreflang-->";
2122
2141
  const HREFLANG_CLOSE = "<!--/verbaly:hreflang-->";
2142
+ const CATALOG_OPEN = "<!--verbaly:catalog-->";
2143
+ const CATALOG_CLOSE = "<!--/verbaly:catalog-->";
2123
2144
  const REDIRECT_OPEN = "<!--verbaly:redirect-->";
2124
2145
  const REDIRECT_CLOSE = "<!--/verbaly:redirect-->";
2125
2146
  const VOID = new Set(VOID_TAGS);
@@ -2138,6 +2159,7 @@ function renderHtml(html, options) {
2138
2159
  const t = v.t;
2139
2160
  const ms = new MagicString(html);
2140
2161
  const missing = /* @__PURE__ */ new Set();
2162
+ const used = /* @__PURE__ */ new Set();
2141
2163
  const skip = protectedRanges(html);
2142
2164
  const inSkip = (index) => skip.some(([from, to]) => index >= from && index < to);
2143
2165
  const filled = [];
@@ -2180,6 +2202,7 @@ function renderHtml(html, options) {
2180
2202
  if (key) {
2181
2203
  if (!v.has(key)) missing.add(key);
2182
2204
  else if (!VOID.has(tagName) && !attrChunk.trimEnd().endsWith("/")) {
2205
+ used.add(key);
2183
2206
  const close = findClose(html, tagName, openEnd, inSkip);
2184
2207
  if (close) {
2185
2208
  const text = t(key, args);
@@ -2205,6 +2228,7 @@ function renderHtml(html, options) {
2205
2228
  missing.add(attrKey);
2206
2229
  continue;
2207
2230
  }
2231
+ used.add(attrKey);
2208
2232
  const value = safeAttribute(name, t(attrKey, args));
2209
2233
  if (value !== void 0) setAttribute(ms, html, chunkStart, openEnd, attrChunk, name, value);
2210
2234
  }
@@ -2212,11 +2236,24 @@ function renderHtml(html, options) {
2212
2236
  }
2213
2237
  if (options.alternates?.length) injectAlternates(ms, html, options.alternates);
2214
2238
  if (options.redirect) injectRedirect(ms, html, options.redirect);
2239
+ if (options.inlineCatalog && options.locale !== sourceLocale) {
2240
+ const slice = pageSlice(v, options.locale, used);
2241
+ if (Object.keys(slice).length > 0) injectCatalog(ms, html, slice);
2242
+ }
2215
2243
  return {
2216
2244
  html: ms.toString(),
2217
- missing: [...missing]
2245
+ missing: [...missing],
2246
+ used: [...used]
2218
2247
  };
2219
2248
  }
2249
+ function pageSlice(v, locale, used) {
2250
+ const slice = {};
2251
+ for (const key of used) {
2252
+ const found = v.inspect(key);
2253
+ slice[key] = found?.from === locale ? found.source : "";
2254
+ }
2255
+ return slice;
2256
+ }
2220
2257
  function publicPath(rel) {
2221
2258
  const path = `/${rel.replace(/(^|\/)index\.html$/, "$1")}`;
2222
2259
  return path.length > 1 ? path.replace(/\/+$/, "") : path;
@@ -2284,6 +2321,22 @@ function injectAlternates(ms, html, alternates) {
2284
2321
  const head = /<\/head\s*>/i.exec(html);
2285
2322
  if (head) ms.appendLeft(head.index, block);
2286
2323
  }
2324
+ function injectCatalog(ms, html, messages) {
2325
+ const json = JSON.stringify(messages).replace(/<\//g, "<\\/");
2326
+ const tag = `<script ${CATALOG_SCRIPT} type="application/json">${json}<\/script>`;
2327
+ const block = `${CATALOG_OPEN}${tag}${CATALOG_CLOSE}`;
2328
+ const from = html.indexOf(CATALOG_OPEN);
2329
+ if (from !== -1) {
2330
+ const to = html.indexOf(CATALOG_CLOSE, from);
2331
+ if (to !== -1) {
2332
+ const end = to + 23;
2333
+ if (html.slice(from, end) !== block) ms.overwrite(from, end, block);
2334
+ return;
2335
+ }
2336
+ }
2337
+ const head = /<\/head\s*>/i.exec(html);
2338
+ if (head) ms.appendLeft(head.index, block);
2339
+ }
2287
2340
  const TITLE_TAG = /<title\b([^>]*)>/i;
2288
2341
  const REFRESH_META = /<meta\b[^>]*http-equiv\s*=\s*["']?refresh/i;
2289
2342
  const NOINDEX_META = /<meta\b[^>]*name\s*=\s*["']?robots["']?[^>]*content\s*=\s*["'][^"']*noindex/i;
@@ -2356,7 +2409,8 @@ async function renderSite(cfg, options = {}) {
2356
2409
  base,
2357
2410
  pages
2358
2411
  },
2359
- redirect: routed && locale === cfg.sourceLocale ? script : void 0
2412
+ redirect: routed && locale === cfg.sourceLocale ? script : void 0,
2413
+ inlineCatalog: cfg.render.inlineCatalog === true
2360
2414
  });
2361
2415
  for (const key of result.missing) {
2362
2416
  const list = missing[locale] ??= [];