@verbaly/compiler 0.48.0 → 0.50.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.
@@ -79,6 +79,6 @@ function definedOnly(config) {
79
79
  return Object.fromEntries(Object.entries(config).filter(([, value]) => value !== void 0));
80
80
  }
81
81
  //#endregion
82
- export { targetLocales as a, resolveConfig as i, isModuleNotFound as n, loadConfig as r, findConfigFile as t };
82
+ export { resolveConfig as a, loadConfigFile as i, isModuleNotFound as n, targetLocales as o, loadConfig as r, findConfigFile as t };
83
83
 
84
- //# sourceMappingURL=config-iLrfRYDB.js.map
84
+ //# sourceMappingURL=config-DYlbHrPc.js.map
@@ -0,0 +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 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,36 @@ 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
+ export declare function generateDts(catalog: Catalog): string;
200
+ export declare function writeDts(cfg: ResolvedConfig, catalog: Catalog, file?: string): void;
199
201
  //#endregion
200
202
  //#region src/transform.d.ts
201
203
  interface TransformResult {
202
204
  code: string;
203
205
  map: ReturnType<MagicString['generateMap']>;
204
206
  }
205
- declare function transformCode(code: string, file: string, analysis?: Analysis): TransformResult | null;
207
+ export declare function transformCode(code: string, file: string, analysis?: Analysis): TransformResult | null;
206
208
  //#endregion
207
209
  //#region src/plugin.d.ts
208
210
  interface PluginOptions extends VerbalyConfig {
209
211
  failOnMissing?: boolean;
210
212
  }
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): {
213
+ export declare const RESOLVED_VIRTUAL_ID: string;
214
+ export declare const LOCALE_MODULE_PREFIX = "\0virtual:verbaly/locale/";
215
+ export declare const SOURCE_FILE_RE: RegExp;
216
+ export declare function resolveVirtualId(id: string): string | undefined;
217
+ export declare function loadVirtualModule(id: string, cfg: ResolvedConfig, catalogs: Catalogs): string | undefined;
218
+ export declare function isTransformTarget(id: string): boolean;
219
+ export declare function createSourceFilter(cfg: ResolvedConfig): (id: string) => boolean;
220
+ export declare function transformSource(code: string, id: string, registry: MessageRegistry): {
219
221
  messages: Catalog;
220
222
  result: TransformResult | null;
221
223
  };
222
- declare function runBuildGate(cfg: ResolvedConfig, registry: MessageRegistry, failOnMissing?: boolean): void;
224
+ export declare function runBuildGate(cfg: ResolvedConfig, registry: MessageRegistry, failOnMissing?: boolean): void;
223
225
  //#endregion
224
226
  //#region src/validate.d.ts
225
227
  type IssueSeverity = 'error' | 'warning';
@@ -246,16 +248,16 @@ interface CheckResult {
246
248
  unknown: UnknownEntry[];
247
249
  broken: BrokenEntry[];
248
250
  }
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;
251
+ export declare function check(cfg: ResolvedConfig, catalogs: Catalogs, registry: MessageRegistry): CheckResult;
252
+ export declare function formatCheckResult(result: CheckResult, root?: string): string;
253
+ export declare function formatCheckWarnings(result: CheckResult): string;
252
254
  //#endregion
253
255
  //#region src/drafts.d.ts
254
256
  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;
257
+ export declare function loadDrafts(cfg: ResolvedConfig): Drafts;
258
+ export declare function saveDrafts(cfg: ResolvedConfig, drafts: Drafts): void;
259
+ export declare function markDrafts(drafts: Drafts, locale: string, keys: string[]): void;
260
+ export declare function effectiveDrafts(drafts: Drafts, catalogs: Catalogs): Drafts;
259
261
  //#endregion
260
262
  //#region src/status.d.ts
261
263
  interface LocaleStatus {
@@ -270,11 +272,11 @@ interface StatusResult {
270
272
  source: string;
271
273
  locales: LocaleStatus[];
272
274
  }
273
- declare function status(cfg: ResolvedConfig, catalogs: Catalogs, registry: MessageRegistry, drafts?: Drafts): StatusResult;
274
- declare function formatStatusResult(result: StatusResult): string;
275
+ export declare function status(cfg: ResolvedConfig, catalogs: Catalogs, registry: MessageRegistry, drafts?: Drafts): StatusResult;
276
+ export declare function formatStatusResult(result: StatusResult): string;
275
277
  //#endregion
276
278
  //#region src/text.d.ts
277
- declare function counted(count: number, noun: string, many?: string): string;
279
+ export declare function counted(count: number, noun: string, many?: string): string;
278
280
  //#endregion
279
281
  //#region src/doctor.d.ts
280
282
  interface DoctorEntry {
@@ -287,8 +289,25 @@ interface DoctorResult {
287
289
  ok: boolean;
288
290
  entries: DoctorEntry[];
289
291
  }
290
- declare function formatDoctorEntry(entry: DoctorEntry): string;
291
- declare function doctor(cfg: ResolvedConfig): Promise<DoctorResult>;
292
+ export declare function formatDoctorEntry(entry: DoctorEntry): string;
293
+ export declare function doctor(cfg: ResolvedConfig): Promise<DoctorResult>;
294
+ //#endregion
295
+ //#region src/init.d.ts
296
+ interface InitOptions {
297
+ root?: string;
298
+ dir?: string;
299
+ sourceLocale?: string;
300
+ locales?: string[];
301
+ }
302
+ interface InitResult {
303
+ created: string[];
304
+ skipped: string[];
305
+ host: Host | undefined;
306
+ configFile: string;
307
+ next: string[];
308
+ }
309
+ type Host = 'nuxt' | 'next' | 'sveltekit' | 'astro' | 'vite' | 'webpack' | 'rspack' | 'rollup' | 'esbuild';
310
+ export declare function init(options?: InitOptions): Promise<InitResult>;
292
311
  //#endregion
293
312
  //#region src/wrap.d.ts
294
313
  interface WrapEntry {
@@ -319,7 +338,7 @@ interface WrapResult {
319
338
  interface WrapOptions {
320
339
  write?: boolean;
321
340
  }
322
- declare function wrapProject(cfg: ResolvedConfig, options?: WrapOptions): Promise<WrapResult>;
341
+ export declare function wrapProject(cfg: ResolvedConfig, options?: WrapOptions): Promise<WrapResult>;
323
342
  //#endregion
324
343
  //#region src/render.d.ts
325
344
  interface RenderSiteOptions {
@@ -342,8 +361,8 @@ interface RenderSiteResult {
342
361
  missing: Record<string, string[]>;
343
362
  untranslatedHead: string[];
344
363
  }
345
- declare function renderSite(cfg: ResolvedConfig, options?: RenderSiteOptions): Promise<RenderSiteResult>;
346
- declare function formatRenderWarnings(result: RenderSiteResult, sourceLocale: string): string[];
364
+ export declare function renderSite(cfg: ResolvedConfig, options?: RenderSiteOptions): Promise<RenderSiteResult>;
365
+ export declare function formatRenderWarnings(result: RenderSiteResult, sourceLocale: string): string[];
347
366
  //#endregion
348
- export { type BrokenEntry, type BundleConfig, type Catalog, type Catalogs, type CheckResult, type DoctorEntry, type DoctorResult, type Drafts, type GlossaryEntry, 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, isTransformTarget, loadCatalogs, loadConfig, loadDrafts, loadVirtualModule, markDrafts, needsIcu, needsRelative, pruneCatalogs, renderSite, resolveConfig, resolveProvider, resolveVirtualId, runBuildGate, saveDrafts, stableKey, status, syncCatalogs, transformCode, transformSource, translateCatalogs, wrapProject, writeCatalog, writeDts };
367
+ export type { BrokenEntry, BundleConfig, Catalog, Catalogs, CheckResult, DoctorEntry, DoctorResult, Drafts, 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 };
349
368
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
- import { a as targetLocales, i as resolveConfig, r as loadConfig, t as findConfigFile } from "./config-iLrfRYDB.js";
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";
@@ -952,7 +952,7 @@ function generateRuntimeModule(cfg, options = {}) {
952
952
  createVerbaly,
953
953
  localeFromPath as readPath,
954
954
  localePath as writePath,
955
- switchLocale as runSwitch${options.icu ? ",\n parseIcu" : ""}${options.relative ? ",\n relativeFormatter" : ""},
955
+ switchLocale as runSwitch${options.icu ? ",\n parseIcu" : ""}${options.relative ? ",\n relativeFormatter" : ""}${options.inlineCatalog ? ",\n inlineMessages" : ""},
956
956
  } from 'verbaly';
957
957
  import source from '${importPath(cfg.sourceLocale)}';
958
958
 
@@ -990,13 +990,13 @@ export async function loadMessages(locale) {
990
990
  return loader ? (await loader()).default : {};
991
991
  }
992
992
 
993
- // per-request/per-instance factory (SSR): the singleton below is browser/SPA-only
994
- export function createInstance(options) {
993
+ ${options.inlineCatalog ? "// the slice `verbaly render` inlined here: enough for what this page shows, so nothing is fetched\nfunction pageSlice() {\n const locale = readPath({ supported: locales });\n if (!locale || locale === sourceLocale) return undefined;\n const messages = inlineMessages();\n return messages ? { locale, messages } : undefined;\n}\n\n" : ""}// per-request/per-instance factory (SSR): the singleton below is browser/SPA-only
994
+ export function createInstance(options) {${options.inlineCatalog ? "\n const page = pageSlice();" : ""}
995
995
  return createVerbaly({
996
- locale: ${src},
996
+ locale: ${options.inlineCatalog ? `page ? page.locale : ${src}` : src},
997
997
  fallback: ${src},
998
- messages: { [${src}]: source },
999
- loaders: localeLoaders,${options.icu ? "\n icu: parseIcu," : ""}
998
+ messages: ${options.inlineCatalog ? `page ? { [${src}]: source, [page.locale]: page.messages } : { [${src}]: source }` : `{ [${src}]: source }`},
999
+ loaders: localeLoaders,${options.inlineCatalog ? "\n partial: page ? [page.locale] : undefined," : ""}${options.icu ? "\n icu: parseIcu," : ""}
1000
1000
  ...options,${options.relative ? "\n // merged, not spread over: passing your own formatters must not drop this one\n formatters: { relative: relativeFormatter, ...options?.formatters }," : ""}
1001
1001
  });
1002
1002
  }
@@ -1190,6 +1190,53 @@ function detectHost(root) {
1190
1190
  const deps = readDependencies(root);
1191
1191
  return HOSTS.find((host) => deps[host.dep]);
1192
1192
  }
1193
+ function configSource(options, typescript) {
1194
+ const fields = [` sourceLocale: '${options.sourceLocale ?? "en"}',`];
1195
+ if (options.locales?.length) fields.push(` locales: [${options.locales.map((l) => `'${l}'`).join(", ")}],`);
1196
+ if (options.dir) fields.push(` dir: '${options.dir}',`);
1197
+ const body = `export default {\n${fields.join("\n")}\n}`;
1198
+ if (typescript) return `import type { VerbalyConfig } from '@verbaly/compiler';\n\n${body} satisfies VerbalyConfig;\n`;
1199
+ return `/** @type {import('@verbaly/compiler').VerbalyConfig} */\n${body};\n`;
1200
+ }
1201
+ async function init(options = {}) {
1202
+ const root = options.root ?? process.cwd();
1203
+ const created = [];
1204
+ const skipped = [];
1205
+ const existing = findConfigFile(root);
1206
+ const typescript = existsSync(join(root, "tsconfig.json"));
1207
+ const configFile = existing ?? (typescript ? "verbaly.config.ts" : "verbaly.config.mjs");
1208
+ if (existing) skipped.push(existing);
1209
+ else {
1210
+ writeFileSync(join(root, configFile), configSource(options, typescript));
1211
+ created.push(configFile);
1212
+ }
1213
+ const fromFile = existing ? await loadConfigFile(root) : {};
1214
+ const scaffold = {
1215
+ dir: options.dir ?? fromFile.dir,
1216
+ sourceLocale: options.sourceLocale ?? fromFile.sourceLocale,
1217
+ locales: options.locales ?? fromFile.locales
1218
+ };
1219
+ const dir = join(root, scaffold.dir ?? "locales");
1220
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
1221
+ for (const locale of /* @__PURE__ */ new Set([scaffold.sourceLocale ?? "en", ...scaffold.locales ?? []])) {
1222
+ const file = join(dir, `${locale}.json`);
1223
+ const label = relative(root, file).replaceAll("\\", "/");
1224
+ if (existsSync(file)) skipped.push(label);
1225
+ else {
1226
+ writeFileSync(file, "{}\n");
1227
+ created.push(label);
1228
+ }
1229
+ }
1230
+ const host = detectHost(root);
1231
+ const next = host ? [`pnpm add -D ${host.pkg}`, host.wire] : ["run \"verbaly extract\" after writing your first t`…` message"];
1232
+ return {
1233
+ created,
1234
+ skipped,
1235
+ host: host?.name,
1236
+ configFile,
1237
+ next
1238
+ };
1239
+ }
1193
1240
  //#endregion
1194
1241
  //#region src/check.ts
1195
1242
  function gatePasses(result) {
@@ -1330,7 +1377,8 @@ function loadVirtualModule(id, cfg, catalogs) {
1330
1377
  const client = clientCatalogs(cfg, catalogs);
1331
1378
  if (id === RESOLVED_VIRTUAL_ID) return generateRuntimeModule(cfg, {
1332
1379
  icu: cfg.icu ?? needsIcu(client),
1333
- relative: cfg.relative ?? needsRelative(client)
1380
+ relative: cfg.relative ?? needsRelative(client),
1381
+ inlineCatalog: cfg.render.inlineCatalog === true
1334
1382
  });
1335
1383
  if (id.startsWith(LOCALE_MODULE_PREFIX)) return generateLocaleModule(client[id.slice(LOCALE_MODULE_PREFIX.length)] ?? {});
1336
1384
  }
@@ -1598,7 +1646,7 @@ function formatTranslateFailures(failed) {
1598
1646
  async function resolveProvider(cfg, model) {
1599
1647
  const configured = cfg.translate.provider;
1600
1648
  if (typeof configured === "function") return configured;
1601
- const { claudeProvider } = await import("./claude-B-vethK9.js");
1649
+ const { claudeProvider } = await import("./claude-CbKynSMc.js");
1602
1650
  return claudeProvider({ model: model ?? cfg.translate.model });
1603
1651
  }
1604
1652
  function structureMatches(source, translated) {
@@ -2073,6 +2121,8 @@ function localeInstance(catalogs, locale, sourceLocale) {
2073
2121
  }
2074
2122
  const HREFLANG_OPEN = "<!--verbaly:hreflang-->";
2075
2123
  const HREFLANG_CLOSE = "<!--/verbaly:hreflang-->";
2124
+ const CATALOG_OPEN = "<!--verbaly:catalog-->";
2125
+ const CATALOG_CLOSE = "<!--/verbaly:catalog-->";
2076
2126
  const REDIRECT_OPEN = "<!--verbaly:redirect-->";
2077
2127
  const REDIRECT_CLOSE = "<!--/verbaly:redirect-->";
2078
2128
  const VOID = new Set(VOID_TAGS);
@@ -2091,6 +2141,7 @@ function renderHtml(html, options) {
2091
2141
  const t = v.t;
2092
2142
  const ms = new MagicString(html);
2093
2143
  const missing = /* @__PURE__ */ new Set();
2144
+ const used = /* @__PURE__ */ new Set();
2094
2145
  const skip = protectedRanges(html);
2095
2146
  const inSkip = (index) => skip.some(([from, to]) => index >= from && index < to);
2096
2147
  const filled = [];
@@ -2133,6 +2184,7 @@ function renderHtml(html, options) {
2133
2184
  if (key) {
2134
2185
  if (!v.has(key)) missing.add(key);
2135
2186
  else if (!VOID.has(tagName) && !attrChunk.trimEnd().endsWith("/")) {
2187
+ used.add(key);
2136
2188
  const close = findClose(html, tagName, openEnd, inSkip);
2137
2189
  if (close) {
2138
2190
  const text = t(key, args);
@@ -2158,6 +2210,7 @@ function renderHtml(html, options) {
2158
2210
  missing.add(attrKey);
2159
2211
  continue;
2160
2212
  }
2213
+ used.add(attrKey);
2161
2214
  const value = safeAttribute(name, t(attrKey, args));
2162
2215
  if (value !== void 0) setAttribute(ms, html, chunkStart, openEnd, attrChunk, name, value);
2163
2216
  }
@@ -2165,11 +2218,24 @@ function renderHtml(html, options) {
2165
2218
  }
2166
2219
  if (options.alternates?.length) injectAlternates(ms, html, options.alternates);
2167
2220
  if (options.redirect) injectRedirect(ms, html, options.redirect);
2221
+ if (options.inlineCatalog && options.locale !== sourceLocale) {
2222
+ const slice = pageSlice(v, options.locale, used);
2223
+ if (Object.keys(slice).length > 0) injectCatalog(ms, html, slice);
2224
+ }
2168
2225
  return {
2169
2226
  html: ms.toString(),
2170
- missing: [...missing]
2227
+ missing: [...missing],
2228
+ used: [...used]
2171
2229
  };
2172
2230
  }
2231
+ function pageSlice(v, locale, used) {
2232
+ const slice = {};
2233
+ for (const key of used) {
2234
+ const found = v.inspect(key);
2235
+ if (found?.from === locale) slice[key] = found.source;
2236
+ }
2237
+ return slice;
2238
+ }
2173
2239
  function publicPath(rel) {
2174
2240
  const path = `/${rel.replace(/(^|\/)index\.html$/, "$1")}`;
2175
2241
  return path.length > 1 ? path.replace(/\/+$/, "") : path;
@@ -2237,6 +2303,22 @@ function injectAlternates(ms, html, alternates) {
2237
2303
  const head = /<\/head\s*>/i.exec(html);
2238
2304
  if (head) ms.appendLeft(head.index, block);
2239
2305
  }
2306
+ function injectCatalog(ms, html, messages) {
2307
+ const json = JSON.stringify(messages).replace(/<\//g, "<\\/");
2308
+ const tag = `<script ${CATALOG_SCRIPT} type="application/json">${json}<\/script>`;
2309
+ const block = `${CATALOG_OPEN}${tag}${CATALOG_CLOSE}`;
2310
+ const from = html.indexOf(CATALOG_OPEN);
2311
+ if (from !== -1) {
2312
+ const to = html.indexOf(CATALOG_CLOSE, from);
2313
+ if (to !== -1) {
2314
+ const end = to + 23;
2315
+ if (html.slice(from, end) !== block) ms.overwrite(from, end, block);
2316
+ return;
2317
+ }
2318
+ }
2319
+ const head = /<\/head\s*>/i.exec(html);
2320
+ if (head) ms.appendLeft(head.index, block);
2321
+ }
2240
2322
  const TITLE_TAG = /<title\b([^>]*)>/i;
2241
2323
  const REFRESH_META = /<meta\b[^>]*http-equiv\s*=\s*["']?refresh/i;
2242
2324
  const NOINDEX_META = /<meta\b[^>]*name\s*=\s*["']?robots["']?[^>]*content\s*=\s*["'][^"']*noindex/i;
@@ -2309,7 +2391,8 @@ async function renderSite(cfg, options = {}) {
2309
2391
  base,
2310
2392
  pages
2311
2393
  },
2312
- redirect: routed && locale === cfg.sourceLocale ? script : void 0
2394
+ redirect: routed && locale === cfg.sourceLocale ? script : void 0,
2395
+ inlineCatalog: cfg.render.inlineCatalog === true
2313
2396
  });
2314
2397
  for (const key of result.missing) {
2315
2398
  const list = missing[locale] ??= [];
@@ -2428,6 +2511,6 @@ function decodeEntities(text) {
2428
2511
  return text.replace(/&quot;/g, "\"").replace(/&#39;/g, "'").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
2429
2512
  }
2430
2513
  //#endregion
2431
- export { LOCALE_MODULE_PREFIX, MessageRegistry, RESOLVED_VIRTUAL_ID, SOURCE_FILE_RE, check, clientCatalogs, collectOrigins, counted, createSourceFilter, doctor, effectiveDrafts, extractProject, formatCheckResult, formatCheckWarnings, formatDoctorEntry, formatRenderWarnings, formatStatusResult, formatTranslateFailures, generateDts, generateLocaleModule, generateRuntimeModule, isTransformTarget, loadCatalogs, loadConfig, loadDrafts, loadVirtualModule, markDrafts, needsIcu, needsRelative, pruneCatalogs, renderSite, resolveConfig, resolveProvider, resolveVirtualId, runBuildGate, saveDrafts, stableKey, status, syncCatalogs, transformCode, transformSource, translateCatalogs, wrapProject, writeCatalog, writeDts };
2514
+ export { LOCALE_MODULE_PREFIX, MessageRegistry, RESOLVED_VIRTUAL_ID, SOURCE_FILE_RE, 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 };
2432
2515
 
2433
2516
  //# sourceMappingURL=index.js.map