@dokebi/i18n 0.2.7 → 0.2.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/AI.md CHANGED
@@ -81,9 +81,10 @@ export const layers = await loadLayers(new URL('../../', import.meta.url));
81
81
 
82
82
  - **The server:** `request.i18n` translates in the scope of the request's app — its layer, the modules, the shared catalogs. The app comes from @dokebi/web's `appOf(request)`, which @dokebi/app answers from the host; an app without a layer (or no @dokebi/app) gets the modules and the shared catalogs. Outside a request, `i18n.forLocale(locale, { app: 'admin' })` (a job, a mail); `i18n.apps` lists the apps with a layer. With app layers and nothing that tells a request's app, the start warns `I18N_APP_LAYERS_UNUSED`.
83
83
  - **The page:** the `i18n` prop carries the bundles of the request's app scope only (another app's layer never reaches the page), merged per language, so `useI18n()` in the browser gives exactly what `request.i18n.t()` gives on the server. A namespace no app layer changed has the same bundle token in every app (the browser keeps it once).
84
+ - **The words of a domain template (0.2.9, [D-0282](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0282-i18n-template-layers.md)).** An @dokebi/app domain draws an app with a template (`domains.<host>.template`, the views folder). `src/apps/<app>/views/<template>/locales/<lang>/<ns>.json` and `src/shared/modules/<module>/views/<template>/locales/<lang>/<ns>.json` replace keys **in the page bundles of that template's domains only**: the same keys, other words (`common.money`: "Holdings" on the elite domains, "Money" elsewhere), so shared components keep their keys and need no template branch. `loadLayers` reads them as `layers.templates` (folders without `locales/` skipped; template names `^[a-z][a-z0-9-]{0,31}$`). Within one language: the app's template words, then the modules' template words (by name), then that app's scope (app > module > shared); the language still comes first (no Korean template words: the Korean page keeps its Korean wording). **Server `t()` never reads them** (errors, notices and mail keep the app's words). At start a template key that the catalogs under it do not have in that language (the app's scope for an app's template; the modules, the apps and the shared ones for a module's), or with other placeholders, fails with `INVALID_CATALOG` naming the file and the key: a template layer only replaces words, and a typo would otherwise stay silent. A template layer adds no language. Only the namespaces a template layer touches get bundles of their own (their own tokens), so a browser that goes between a default and an elite domain never takes one's bundle for the other's (claims, the pageCache cookie and the stored bundles of D-0126 all go by token); the version covers the template layers. The template of a request comes from @dokebi/web's `templateOf(request)` (web 0.4.25), which @dokebi/app 0.4.18 answers from the host; without it the start warns `I18N_TEMPLATE_LAYERS_UNUSED`. `dokebi describe` lists them (section `i18n`: `templates[]` with `kind`, `name`, `template`, `keys`), and `i18n.templates` (the plugin's provider) has the same.
84
85
  - **Intended overrides:** a namespace file of an app or module may start with `"$overrides": ["title", "nav.home"]` — the keys (inside the namespace) it overrides on purpose. The loader checks its shape and leaves it out of the messages; `dokebi check` stops reporting those keys (`i18n-layer-override`, @dokebi/cli AI.md).
85
86
 
86
- Use one folder per locale and one JSON file per namespace: `locales/en/auth.json`, `locales/ko/auth.json`, `locales/en/posts.json`, etc. A nested value `{"password":{"minimum":"At least {count} characters"}}` in `auth.json` becomes `auth.password.minimum`. Adding a namespace needs no import list. Files are discovered once when loading the entry, never per request. Restart after changes. `loadCatalogs(directory: string | URL)` is a Node-only subpath export; it accepts regular JSON files, safe ASCII path segments and at most 16 nested levels (`maxDepth`, which bounds the loader's own recursion), and only reads: the counts and sizes (`maxLocales`, `maxMessages`, `maxCatalogBytes`, `maxCatalogCharacters`, `maxKeyLength`) are the plugin options, checked at setup where dokebi.yaml is known (D-0118), so an entry file needs no limits. `loadCatalogs(directory, { maxMessages, maxLocales, maxBytes, maxKeyLength, maxDepth })` refuses earlier, while loading, when a caller asks (a test that loads catalogs by itself). An object is a plural message only when its keys are `other` and other cardinal categories (`zero`, `one`, `two`, `few`, `many`) and every value is a string; an object with any other key is nested, so `{"regions":{"kr":"Korea","other":"Other"}}` gives `regions.kr` and `regions.other`. It returns flat catalogs for constant-time lookup; inline catalogs remain supported. Invalid files throw `INVALID_CATALOG` with the original cause.
87
+ Use one folder per locale and one JSON file per namespace: `locales/en/auth.json`, `locales/ko/auth.json`, `locales/en/posts.json`, etc. A nested value `{"password":{"minimum":"At least {count} characters"}}` in `auth.json` becomes `auth.password.minimum`. Adding a namespace needs no import list. Files are discovered once when loading the entry, never per request. Restart after changes. `loadCatalogs(directory: string | URL)` is a Node-only subpath export; it accepts regular JSON files, safe ASCII path segments and at most 16 nested levels (`maxDepth`, which bounds the loader's own recursion), and only reads: the counts and sizes (`maxLocales`, `maxMessages`, `maxCatalogBytes`, `maxCatalogCharacters`, `maxKeyLength`) are the plugin options, checked at setup where dokebi.yaml is known (D-0118), so an entry file needs no limits. `loadCatalogs(directory, { maxMessages, maxLocales, maxBytes, maxKeyLength, maxDepth })` refuses earlier, while loading, when a caller asks (a test that loads catalogs by itself). An object is a plural message only when its keys are `other` and other cardinal categories (`zero`, `one`, `two`, `few`, `many`) and every value is a string; an object with any other key is nested, so `{"regions":{"kr":"Korea","other":"Other"}}` gives `regions.kr` and `regions.other`. It returns flat catalogs for constant-time lookup; inline catalogs remain supported. Invalid files throw `INVALID_CATALOG` with the original cause. Entries whose name starts with a dot (`.claude/`, `.DS_Store`, `.draft.json`) are never locales, namespaces, apps or modules: `loadCatalogs` and `loadLayers` skip them at every level (0.2.8; before, a `.claude/` folder an editor tool left in a `locales/` folder failed the start with `Invalid BCP 47 locale`), `catalogSource(catalogs).skipped` names them (paths relative to the folder read, at most 100), and the plugin logs them once at start at `debug` (`I18N_ENTRIES_SKIPPED`).
87
88
 
88
89
  Catalogs can also be imported from application-owned modules. Setup snapshots them, validates all messages and precompiles placeholders. Restart to change translations. Entry exports are only `catalogs`, `layers`, `numberFormats`, `dateFormats`; no default class is required. Plain objects/ESM namespace data only; getters and proxies are refused.
89
90
 
@@ -19,6 +19,12 @@ export interface CatalogSource {
19
19
  /** Bytes of every namespace file together. */
20
20
  readonly bytes: number;
21
21
  readonly files: number;
22
+ /**
23
+ * Entries left out because their name starts with a dot (`.claude/`, `.DS_Store`): folders and
24
+ * files that tools leave behind, never locales, apps, modules or namespaces. Paths are relative
25
+ * to the folder handed to the loader; the plugin logs them at debug when it starts.
26
+ */
27
+ readonly skipped: readonly string[];
22
28
  }
23
29
  /** The files behind catalogs made by `loadCatalogs` (undefined for inline catalogs). */
24
30
  export declare function catalogSource(catalogs: unknown): CatalogSource | undefined;
@@ -26,7 +32,8 @@ export declare function catalogSource(catalogs: unknown): CatalogSource | undefi
26
32
  * D-0181: the app and module layers under `src` (`src/apps/<app>/locales/` and
27
33
  * `src/shared/modules/<module>/locales/`, each read like `loadCatalogs`). An entry exports it as
28
34
  * `layers` next to `catalogs` (the shared layer, `src/shared/locales/`). Folders without a
29
- * `locales` folder are skipped.
35
+ * `locales` folder are skipped. D-0282: also the template layers, `views/<template>/locales/` of
36
+ * each app and module (`layers.templates`, only when there is one).
30
37
  */
31
38
  export declare function loadLayers(src: string | URL, limits?: CatalogLimits): Promise<CatalogLayers>;
32
39
  /** Load once in an entry: locales/<locale>/<namespace>.json -> namespace.nested.key. */
package/dist/catalogs.js CHANGED
@@ -3,6 +3,10 @@ import { join } from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
4
  import { I18nError } from './errors.js';
5
5
  import { canonical, record } from './values.js';
6
+ /** Skipped entries kept for the debug log; more are counted, not named. */
7
+ const MAX_SKIPPED = 100;
8
+ /** A dot entry (`.claude`, `.git`, `.DS_Store`): never part of a catalog tree. */
9
+ const hidden = (name) => name.startsWith('.');
6
10
  const SOURCES = new WeakMap();
7
11
  /** A key path inside a namespace (`title`, `nav.home`): the `$overrides` entries (D-0181). */
8
12
  const KEY_PATH = /^[a-zA-Z][a-zA-Z0-9_-]*(?:\.[a-zA-Z][a-zA-Z0-9_-]*)*$/;
@@ -23,66 +27,113 @@ export function catalogSource(catalogs) {
23
27
  }
24
28
  /** App and module names: the folders of src/apps and src/shared/modules (D-0181). */
25
29
  const LAYER_NAME = /^[a-z][a-z0-9-]{0,63}$/;
30
+ /** D-0282: template names, as @dokebi/app's `domains.<host>.template` takes them. */
31
+ const TEMPLATE_NAME = /^[a-z][a-z0-9-]{0,31}$/;
26
32
  /**
27
33
  * D-0181: the app and module layers under `src` (`src/apps/<app>/locales/` and
28
34
  * `src/shared/modules/<module>/locales/`, each read like `loadCatalogs`). An entry exports it as
29
35
  * `layers` next to `catalogs` (the shared layer, `src/shared/locales/`). Folders without a
30
- * `locales` folder are skipped.
36
+ * `locales` folder are skipped. D-0282: also the template layers, `views/<template>/locales/` of
37
+ * each app and module (`layers.templates`, only when there is one).
31
38
  */
32
39
  export async function loadLayers(src, limits = {}) {
33
40
  const root = src instanceof URL ? fileURLToPath(src) : src;
34
41
  let bytes = 0;
35
42
  let files = 0;
36
- const read = async (parent, kind) => {
37
- const out = Object.create(null);
43
+ const skipped = [];
44
+ /** Whether `path` (under root) is a folder; a missing one is not. */
45
+ const folderAt = async (path) => {
46
+ try {
47
+ return (await stat(join(root, path))).isDirectory();
48
+ }
49
+ catch (error) {
50
+ if (error.code === 'ENOENT')
51
+ return false;
52
+ throw new I18nError('INVALID_CATALOG', `Cannot read ${path}`, error);
53
+ }
54
+ };
55
+ /** The sub-folders of `path` (under root), sorted, dot entries left out (and noted). */
56
+ const folders = async (path) => {
38
57
  let entries;
39
58
  try {
40
- entries = await readdir(join(root, parent), { withFileTypes: true });
59
+ entries = await readdir(join(root, path), { withFileTypes: true });
41
60
  }
42
61
  catch (error) {
43
- // No apps or modules folder: that layer is empty.
62
+ // No apps, modules or views folder: nothing there.
44
63
  if (error.code === 'ENOENT')
45
- return out;
46
- throw new I18nError('INVALID_CATALOG', `Cannot read ${parent}`, error);
64
+ return [];
65
+ throw new I18nError('INVALID_CATALOG', `Cannot read ${path}`, error);
47
66
  }
67
+ const out = [];
48
68
  for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
49
69
  if (!entry.isDirectory())
50
70
  continue;
51
- const folder = join(root, parent, entry.name, 'locales');
52
- try {
53
- if (!(await stat(folder)).isDirectory())
54
- continue;
71
+ if (hidden(entry.name)) {
72
+ if (skipped.length < MAX_SKIPPED)
73
+ skipped.push(`${path}/${entry.name}`);
74
+ continue;
55
75
  }
56
- catch (error) {
57
- // This app or module has no translations of its own.
58
- if (error.code === 'ENOENT')
76
+ out.push(entry.name);
77
+ }
78
+ return out;
79
+ };
80
+ /** One `locales` folder, read like `loadCatalogs` within what the others left of maxBytes. */
81
+ const load = async (path, what) => {
82
+ let catalogs;
83
+ try {
84
+ catalogs = await loadCatalogs(join(root, path), {
85
+ ...limits,
86
+ ...(limits.maxBytes === undefined ? {} : { maxBytes: limits.maxBytes - bytes }),
87
+ });
88
+ }
89
+ catch (error) {
90
+ throw new I18nError('INVALID_CATALOG', `Cannot load the ${what} ${path}`, error);
91
+ }
92
+ const source = SOURCES.get(catalogs);
93
+ bytes += source.bytes;
94
+ files += source.files;
95
+ for (const skippedPath of source.skipped)
96
+ if (skipped.length < MAX_SKIPPED)
97
+ skipped.push(`${path}/${skippedPath}`);
98
+ return catalogs;
99
+ };
100
+ const read = async (parent, kind) => {
101
+ const layers = Object.create(null);
102
+ const templates = Object.create(null);
103
+ for (const name of await folders(parent)) {
104
+ const own = await folderAt(`${parent}/${name}/locales`);
105
+ // D-0282: views/<template>/locales of the app or module, the words of a domain template.
106
+ const byTemplate = Object.create(null);
107
+ for (const template of await folders(`${parent}/${name}/views`)) {
108
+ const path = `${parent}/${name}/views/${template}/locales`;
109
+ if (!(await folderAt(path)))
59
110
  continue;
60
- throw new I18nError('INVALID_CATALOG', `Cannot read ${parent}/${entry.name}/locales`, error);
61
- }
62
- if (!LAYER_NAME.test(entry.name))
63
- throw new I18nError('INVALID_CATALOG', `The ${kind} folder ${JSON.stringify(entry.name)} is not a ${kind} name`);
64
- let catalogs;
65
- try {
66
- catalogs = await loadCatalogs(folder, {
67
- ...limits,
68
- ...(limits.maxBytes === undefined ? {} : { maxBytes: limits.maxBytes - bytes }),
69
- });
111
+ if (!TEMPLATE_NAME.test(template))
112
+ throw new I18nError('INVALID_CATALOG', `The template folder ${JSON.stringify(template)} of ${parent}/${name}/views is not a template name (a-z, 0-9, -, at most 32)`);
113
+ byTemplate[template] = await load(path, `template layer`);
70
114
  }
71
- catch (error) {
72
- throw new I18nError('INVALID_CATALOG', `Cannot load the ${kind} layer ${parent}/${entry.name}/locales`, error);
73
- }
74
- const source = SOURCES.get(catalogs);
75
- bytes += source.bytes;
76
- files += source.files;
77
- out[entry.name] = catalogs;
115
+ const hasTemplates = Object.keys(byTemplate).length > 0;
116
+ if (!own && !hasTemplates)
117
+ continue;
118
+ if (!LAYER_NAME.test(name))
119
+ throw new I18nError('INVALID_CATALOG', `The ${kind} folder ${JSON.stringify(name)} is not a ${kind} name`);
120
+ if (own)
121
+ layers[name] = await load(`${parent}/${name}/locales`, `${kind} layer`);
122
+ if (hasTemplates)
123
+ templates[name] = Object.freeze(byTemplate);
78
124
  }
79
- return Object.freeze(out);
125
+ return { layers: Object.freeze(layers), templates: Object.freeze(templates) };
80
126
  };
127
+ const apps = await read('apps', 'app');
128
+ const modules = await read('shared/modules', 'module');
81
129
  const layers = Object.freeze({
82
- apps: await read('apps', 'app'),
83
- modules: await read('shared/modules', 'module'),
130
+ apps: apps.layers,
131
+ modules: modules.layers,
132
+ ...(Object.keys(apps.templates).length || Object.keys(modules.templates).length
133
+ ? { templates: Object.freeze({ apps: apps.templates, modules: modules.templates }) }
134
+ : {}),
84
135
  });
85
- SOURCES.set(layers, Object.freeze({ bytes, files }));
136
+ SOURCES.set(layers, Object.freeze({ bytes, files, skipped: Object.freeze(skipped) }));
86
137
  return layers;
87
138
  }
88
139
  /** Load once in an entry: locales/<locale>/<namespace>.json -> namespace.nested.key. */
@@ -93,6 +144,11 @@ export async function loadCatalogs(directory, limits = {}) {
93
144
  const maxKeyLength = limits.maxKeyLength ?? Number.POSITIVE_INFINITY;
94
145
  const maxDepth = limits.maxDepth ?? 16;
95
146
  let files = 0;
147
+ const skipped = [];
148
+ const skip = (path) => {
149
+ if (skipped.length < MAX_SKIPPED)
150
+ skipped.push(path);
151
+ };
96
152
  const root = directory instanceof URL ? fileURLToPath(directory) : directory;
97
153
  const catalogs = Object.create(null);
98
154
  let bytes = 0;
@@ -128,6 +184,10 @@ export async function loadCatalogs(directory, limits = {}) {
128
184
  try {
129
185
  const locales = await readdir(root, { withFileTypes: true });
130
186
  for (const locale of locales.sort((a, b) => a.name.localeCompare(b.name))) {
187
+ if (hidden(locale.name)) {
188
+ skip(locale.name);
189
+ continue;
190
+ }
131
191
  if (!locale.isDirectory())
132
192
  continue;
133
193
  current = locale.name;
@@ -138,6 +198,10 @@ export async function loadCatalogs(directory, limits = {}) {
138
198
  catalogs[name] = target;
139
199
  const folder = join(root, locale.name);
140
200
  for (const file of (await readdir(folder, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
201
+ if (hidden(file.name)) {
202
+ skip(`${locale.name}/${file.name}`);
203
+ continue;
204
+ }
141
205
  if (!file.name.endsWith('.json'))
142
206
  continue;
143
207
  current = `${locale.name}/${file.name}`;
@@ -154,7 +218,7 @@ export async function loadCatalogs(directory, limits = {}) {
154
218
  Object.freeze(target);
155
219
  }
156
220
  const loaded = Object.freeze(catalogs);
157
- SOURCES.set(loaded, Object.freeze({ bytes, files }));
221
+ SOURCES.set(loaded, Object.freeze({ bytes, files, skipped: Object.freeze(skipped) }));
158
222
  return loaded;
159
223
  }
160
224
  catch (cause) {
@@ -7,6 +7,15 @@ export type Catalogs = Readonly<Record<string, Readonly<Record<string, Message>>
7
7
  export interface CatalogLayers {
8
8
  readonly apps?: Readonly<Record<string, Catalogs>>;
9
9
  readonly modules?: Readonly<Record<string, Catalogs>>;
10
+ /**
11
+ * D-0282: the screen words of a domain template (`views/<template>/locales/` of an app or a
12
+ * module), by app or module, then by template. They replace keys of that app's page bundles on
13
+ * the domains of that template only; server `t()` never reads them.
14
+ */
15
+ readonly templates?: {
16
+ readonly apps?: Readonly<Record<string, Readonly<Record<string, Catalogs>>>>;
17
+ readonly modules?: Readonly<Record<string, Readonly<Record<string, Catalogs>>>>;
18
+ };
10
19
  }
11
20
  export interface I18nEntry {
12
21
  readonly catalogs: Catalogs;
package/dist/layers.d.ts CHANGED
@@ -5,6 +5,16 @@ export interface Layer<T> {
5
5
  readonly name: string;
6
6
  readonly catalogs: ReadonlyMap<string, ReadonlyMap<string, T>>;
7
7
  }
8
+ /**
9
+ * D-0282: the screen words of a domain template: an app's or a module's
10
+ * `views/<template>/locales/`. They replace keys in the page bundles of that template's domains.
11
+ */
12
+ export interface TemplateLayer<T> {
13
+ readonly kind: 'app' | 'module';
14
+ readonly name: string;
15
+ readonly template: string;
16
+ readonly catalogs: ReadonlyMap<string, ReadonlyMap<string, T>>;
17
+ }
8
18
  /** The base scope (no app). */
9
19
  export declare const BASE = "";
10
20
  /** The raw messages of an entry: the shared layer, the module layers and the app layers. */
@@ -12,6 +22,7 @@ export declare function entryLayers(entry: Record<string, unknown>): {
12
22
  shared: Layer<Message>;
13
23
  modules: Layer<Message>[];
14
24
  apps: Layer<Message>[];
25
+ templates: TemplateLayer<Message>[];
15
26
  };
16
27
  /** Every locale any layer has. */
17
28
  export declare function localesOf<T>(layers: Iterable<Layer<T>>): string[];
package/dist/layers.js CHANGED
@@ -3,6 +3,7 @@ import { canonical, record } from './values.js';
3
3
  /** The base scope (no app). */
4
4
  export const BASE = '';
5
5
  const LAYER_NAME = /^[a-z][a-z0-9-]{0,63}$/;
6
+ const TEMPLATE_NAME = /^[a-z][a-z0-9-]{0,31}$/;
6
7
  /** The raw messages of an entry: the shared layer, the module layers and the app layers. */
7
8
  export function entryLayers(entry) {
8
9
  const catalogsOf = (input) => {
@@ -19,8 +20,8 @@ export function entryLayers(entry) {
19
20
  return out;
20
21
  };
21
22
  const layers = entry.layers === undefined ? {} : record(entry.layers);
22
- if (Object.keys(layers).some((key) => key !== 'apps' && key !== 'modules'))
23
- throw new I18nError('INVALID_CATALOG', 'layers holds apps and modules (loadLayers)');
23
+ if (Object.keys(layers).some((key) => key !== 'apps' && key !== 'modules' && key !== 'templates'))
24
+ throw new I18nError('INVALID_CATALOG', 'layers holds apps, modules and templates (loadLayers)');
24
25
  const named = (kind, input) => Object.entries(input === undefined ? {} : record(input))
25
26
  .map(([name, catalogs]) => {
26
27
  if (!LAYER_NAME.test(name))
@@ -28,10 +29,35 @@ export function entryLayers(entry) {
28
29
  return { kind, name, catalogs: catalogsOf(catalogs) };
29
30
  })
30
31
  .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
32
+ // D-0282: { apps: { <app>: { <template>: catalogs } }, modules: { … } }, apps first, by name.
33
+ const templatesIn = layers.templates === undefined ? {} : record(layers.templates);
34
+ if (Object.keys(templatesIn).some((key) => key !== 'apps' && key !== 'modules'))
35
+ throw new I18nError('INVALID_CATALOG', 'layers.templates holds apps and modules (loadLayers)');
36
+ const templates = [];
37
+ for (const kind of ['app', 'module']) {
38
+ const owners = templatesIn[kind === 'app' ? 'apps' : 'modules'];
39
+ for (const [name, value] of Object.entries(owners === undefined ? {} : record(owners)).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) {
40
+ if (!LAYER_NAME.test(name))
41
+ throw new I18nError('INVALID_CATALOG', `The ${kind} of a template layer ${JSON.stringify(name)} is not a ${kind} name`);
42
+ const owner = { name };
43
+ const byTemplate = record(value);
44
+ for (const template of Object.keys(byTemplate).sort()) {
45
+ if (!TEMPLATE_NAME.test(template))
46
+ throw new I18nError('INVALID_CATALOG', `The template ${JSON.stringify(template)} of the ${kind} ${owner.name} is not a template name`);
47
+ templates.push({
48
+ kind,
49
+ name: owner.name,
50
+ template,
51
+ catalogs: catalogsOf(byTemplate[template]),
52
+ });
53
+ }
54
+ }
55
+ }
31
56
  return {
32
57
  shared: { kind: 'shared', name: 'shared', catalogs: catalogsOf(entry.catalogs) },
33
58
  modules: named('module', layers.modules),
34
59
  apps: named('app', layers.apps),
60
+ templates,
35
61
  };
36
62
  }
37
63
  /** Every locale any layer has. */
package/dist/page.d.ts CHANGED
@@ -73,6 +73,8 @@ export declare class PageMessages {
73
73
  #private;
74
74
  /** Changes with the time zone (D-0178): the browser then takes the new settings. */
75
75
  version: string;
76
+ /** D-0282: whether any template layer exists (the plugin then asks a request's template). */
77
+ readonly templates: boolean;
76
78
  constructor(options: I18nOptions, input: unknown, logger: Logger, apps?: ReadonlyMap<string, AppLocales>);
77
79
  /**
78
80
  * D-0178: the application's time zone changed. The settings carry it and the version changes,
@@ -95,5 +97,7 @@ export declare class PageMessages {
95
97
  * D-0195: the first HTML of a public page, the same for every visitor: the claim cookie is
96
98
  * not read, so every bundle is sent.
97
99
  */
98
- publicPage?: boolean): PageI18nPayload;
100
+ publicPage?: boolean,
101
+ /** D-0282: the domain template of the request (@dokebi/app), whose words replace keys. */
102
+ template?: string): PageI18nPayload;
99
103
  }
package/dist/page.js CHANGED
@@ -84,6 +84,13 @@ export class PageMessages {
84
84
  #catalogHash;
85
85
  /** D-0181: the scopes with bundles (BASE and the apps with a layer); the maps below are by slot. */
86
86
  #scopes;
87
+ /**
88
+ * D-0282: the template scopes (`<app or BASE>\u0001<template>`): a scope with the template
89
+ * layers of that template over it. Only the namespaces they touch have bundles of their own.
90
+ */
91
+ #templateScopes = new Set();
92
+ /** D-0282: whether any template layer exists (the plugin then asks a request's template). */
93
+ templates;
87
94
  #chains = new Map();
88
95
  /** locale → namespace → { chain locale → { key → message } } (each key under its source). */
89
96
  #fragments = new Map();
@@ -239,6 +246,56 @@ export class PageMessages {
239
246
  }
240
247
  store(at, fragments, tokens, this.#baseNamespaces.some((namespace) => touched.has(namespace)) ? undefined : base);
241
248
  }
249
+ // D-0282: per template, a scope for each app scope (BASE, the apps with a layer, the apps
250
+ // with that template's own words): the app's template layer, then the modules' template
251
+ // layers (name order), then the scope it sits on. Only the namespaces they touch differ.
252
+ const appSplitOf = new Map(appSplits);
253
+ const templateNames = [...new Set(layers.templates.map((layer) => layer.template))].sort();
254
+ for (const template of templateNames) {
255
+ const moduleSplits = layers.templates
256
+ .filter((layer) => layer.kind === 'module' && layer.template === template)
257
+ .map((layer) => byNamespace(layer.catalogs));
258
+ const appTemplateSplits = new Map(layers.templates
259
+ .filter((layer) => layer.kind === 'app' && layer.template === template)
260
+ .map((layer) => [layer.name, byNamespace(layer.catalogs)]));
261
+ const owners = new Set([BASE, ...appSplitOf.keys(), ...appTemplateSplits.keys()]);
262
+ for (const owner of owners) {
263
+ const own = appTemplateSplits.get(owner);
264
+ const over = [...(own ? [own] : []), ...moduleSplits];
265
+ if (!over.length)
266
+ continue;
267
+ const under = appSplitOf.get(owner);
268
+ const scope = templateScope(owner, template);
269
+ this.#templateScopes.add(scope);
270
+ for (const locale of baseCatalogs.keys()) {
271
+ const below = slot(under ? owner : BASE, locale);
272
+ const at = slot(scope, locale);
273
+ const chain = this.#chains.get(below);
274
+ this.#chains.set(at, chain);
275
+ const touched = new Set();
276
+ for (const source of chain)
277
+ for (const split of over)
278
+ for (const namespace of split.get(source)?.keys() ?? [])
279
+ touched.add(namespace);
280
+ const belowFragments = this.#fragments.get(below);
281
+ const belowTokens = this.#tokens.get(below);
282
+ if (!touched.size) {
283
+ store(at, belowFragments, belowTokens, below);
284
+ continue;
285
+ }
286
+ const fragments = new Map(belowFragments);
287
+ const tokens = new Map(belowTokens);
288
+ const splits = [...over, ...(under ? [under] : []), baseSplit];
289
+ for (const namespace of touched) {
290
+ const fragment = fragmentOf(chain, namespace, splits);
291
+ fragments.set(namespace, fragment);
292
+ tokens.set(namespace, tokenOf(locale, namespace, fragment));
293
+ }
294
+ store(at, fragments, tokens, this.#baseNamespaces.some((namespace) => touched.has(namespace)) ? undefined : below);
295
+ }
296
+ }
297
+ }
298
+ this.templates = this.#templateScopes.size > 0;
242
299
  // A token two bundles share (48 bits: not expected in practice) is never honored in a claim.
243
300
  const byTokens = new Map();
244
301
  for (const [at, tokens] of this.#tokens) {
@@ -291,11 +348,25 @@ export class PageMessages {
291
348
  .map(([locale, messages]) => [locale, [...messages].sort(([a], [b]) => (a < b ? -1 : 1))]);
292
349
  // Without layers the version is what it was (one catalog); with them the base scope and
293
350
  // each app's own layer (which, over the base, is that app's scope).
294
- const canonicalJson = JSON.stringify(!layers.apps.length && !layers.modules.length
351
+ // D-0282: template layers join the version only when there are some (it stays otherwise).
352
+ const canonicalJson = JSON.stringify(!layers.apps.length && !layers.modules.length && !layers.templates.length
295
353
  ? sortedCatalogs(baseCatalogs)
296
354
  : [
297
355
  [BASE, sortedCatalogs(baseCatalogs)],
298
356
  ...layers.apps.map((app) => [app.name, sortedCatalogs(app.catalogs)]),
357
+ ...(layers.templates.length
358
+ ? [
359
+ [
360
+ 'templates',
361
+ layers.templates.map((layer) => [
362
+ layer.kind,
363
+ layer.name,
364
+ layer.template,
365
+ sortedCatalogs(layer.catalogs),
366
+ ]),
367
+ ],
368
+ ]
369
+ : []),
299
370
  ]);
300
371
  this.#catalogHash = createHash('sha256').update(canonicalJson);
301
372
  this.version = this.#versionOf(this.#settings);
@@ -387,8 +458,20 @@ export class PageMessages {
387
458
  * D-0195: the first HTML of a public page, the same for every visitor: the claim cookie is
388
459
  * not read, so every bundle is sent.
389
460
  */
390
- publicPage = false) {
391
- const at = slot(app !== undefined && this.#scopes.has(app) ? app : BASE, locale);
461
+ publicPage = false,
462
+ /** D-0282: the domain template of the request (@dokebi/app), whose words replace keys. */
463
+ template) {
464
+ const owner = app !== undefined && this.#scopes.has(app) ? app : BASE;
465
+ let scope = owner;
466
+ if (template !== undefined && this.#templateScopes.size) {
467
+ // The app's own template words (it may have no layer of its own), else its scope's.
468
+ const own = app !== undefined ? templateScope(app, template) : undefined;
469
+ if (own !== undefined && this.#templateScopes.has(own))
470
+ scope = own;
471
+ else if (this.#templateScopes.has(templateScope(owner, template)))
472
+ scope = templateScope(owner, template);
473
+ }
474
+ const at = slot(scope, locale);
392
475
  const fragments = this.#fragments.get(at);
393
476
  const chain = this.#chains.get(at);
394
477
  const tokens = this.#tokens.get(at);
@@ -572,6 +655,8 @@ export class PageMessages {
572
655
  /** The key of one scope's locale in the maps of PageMessages. */
573
656
  const SLOT = '\u0000';
574
657
  const slot = (scope, locale) => `${scope}${SLOT}${locale}`;
658
+ /** D-0282: the scope of an app scope (or BASE) under one domain template. */
659
+ const templateScope = (owner, template) => `${owner}\u0001${template}`;
575
660
  function pick(tokens, namespaces) {
576
661
  const result = object();
577
662
  for (const name of namespaces) {
package/dist/plugin.d.ts CHANGED
@@ -5,6 +5,11 @@ import type { I18nApi } from './contract.js';
5
5
  import { type I18nOptions } from './options.js';
6
6
  export declare const web: import("@dokebi/core").PluginDependency<WebApi>;
7
7
  export declare const localeData: import("@dokebi/core").ContributionPoint<WebViewData>;
8
+ /** The `core:describe` point (core 0.4.2), declared by name. */
9
+ export declare const describePoint: import("@dokebi/core").ContributionPoint<{
10
+ readonly section: string;
11
+ describe(): unknown;
12
+ }>;
8
13
  export declare class I18nRuntime implements PluginRuntime<I18nApi> {
9
14
  #private;
10
15
  constructor(options: I18nOptions, entry: unknown);
package/dist/plugin.js CHANGED
@@ -9,12 +9,16 @@ import { I18n, negotiationLimits } from './service.js';
9
9
  // Optional by name: server-only translators do not import or install the web runtime.
10
10
  export const web = optionalDependency({ name: 'dokebi-web', version: '^0.4.3' });
11
11
  export const localeData = definePoint('dokebi-web:view-data');
12
+ /** The `core:describe` point (core 0.4.2), declared by name. */
13
+ export const describePoint = definePoint('core:describe');
12
14
  export class I18nRuntime {
13
15
  #options;
14
16
  #entry;
15
17
  #web;
16
18
  #apps = [];
17
19
  #pageApps = [];
20
+ /** D-0282: the template layers whose words the page bundles use (unused without templateOf). */
21
+ #templates = [];
18
22
  constructor(options, entry) {
19
23
  this.#options = options;
20
24
  this.#entry = entry;
@@ -24,6 +28,16 @@ export class I18nRuntime {
24
28
  try {
25
29
  const api = new I18n(this.#options, this.#entry, context.logger);
26
30
  this.#apps = api.apps;
31
+ // D-0282: what `dokebi describe` shows of the layers: the template layers and their keys.
32
+ context.contribute(describePoint, {
33
+ section: 'i18n',
34
+ describe: () => ({
35
+ locales: api.locales,
36
+ defaultLocale: api.defaultLocale,
37
+ apps: api.apps,
38
+ templates: api.templates,
39
+ }),
40
+ });
27
41
  if (this.#options.http.enabled) {
28
42
  const server = context.getOptionalDependency(web);
29
43
  if (!server)
@@ -43,6 +57,13 @@ export class I18nRuntime {
43
57
  const pageAppOf = appOf ??
44
58
  (this.#pageApps.length ? (request) => server.appOf(request) : undefined);
45
59
  this.#web = server;
60
+ // D-0282: the template of a page's domain (dokebi-app tells web), asked only when a
61
+ // template layer exists; web before 0.4.25 has no templateOf (the layers then go unused).
62
+ const templateOf = page.templates
63
+ ? server.templateOf
64
+ : undefined;
65
+ if (page.templates)
66
+ this.#templates = api.templates.map((layer) => `${layer.kind}:${layer.name}@${layer.template}`);
46
67
  // D-0178: a time zone set at run time reaches the page settings and their version.
47
68
  api.onTimeZone((zone) => page.setTimeZone(zone));
48
69
  server.register(translationHttp(api, this.#options.http.cookieName, context.logger, {
@@ -65,7 +86,7 @@ export class I18nRuntime {
65
86
  // D-0126: a sealed answer's browser keeps no bundles (the page leaves through the seal).
66
87
  // D-0195: a public page's first HTML sends every bundle (the claim cookie of this
67
88
  // browser is not read), so one HTML serves every visitor of the URL and language.
68
- value: (request, view) => page.value(request, request.i18n?.locale ?? api.defaultLocale, server.sealOf(request) !== undefined, pageAppOf?.(request), view?.public === true),
89
+ value: (request, view) => page.value(request, request.i18n?.locale ?? api.defaultLocale, server.sealOf(request) !== undefined, pageAppOf?.(request), view?.public === true, templateOf?.(request)),
69
90
  });
70
91
  context.defer(() => page.close());
71
92
  context.logger.log('debug', 'Translation HTTP integration registered', {
@@ -90,6 +111,14 @@ export class I18nRuntime {
90
111
  * tells a request's app are unused.
91
112
  */
92
113
  start(context) {
114
+ if (this.#templates.length &&
115
+ this.#web &&
116
+ (!this.#web.templateOf || !this.#web.resolvesApps))
117
+ context.logger.log('warn', 'Translation template layers are not used: dokebi-web tells no template', {
118
+ code: 'I18N_TEMPLATE_LAYERS_UNUSED',
119
+ templates: this.#templates,
120
+ fix: 'Upgrade @dokebi/web to 0.4.25 or later and @dokebi/app to 0.4.18 or later (it tells web the template of each host)',
121
+ });
93
122
  if (this.#apps.length && this.#web && !this.#web.resolvesApps)
94
123
  context.logger.log('warn', 'Translation app layers are not used: nothing tells the app of a request', {
95
124
  code: 'I18N_APP_LAYERS_UNUSED',
@@ -106,10 +135,10 @@ export class I18nRuntime {
106
135
  }
107
136
  export const createPlugin = definePlugin({
108
137
  name: 'dokebi-i18n',
109
- version: '0.2.7',
138
+ version: '0.2.9',
110
139
  core: '^0.4.0',
111
140
  options,
112
- contributes: [localeData],
141
+ contributes: [localeData, describePoint],
113
142
  dependencies: ({ options }) => (options.http.enabled ? [web] : []),
114
143
  entry: (input) => input,
115
144
  instance: ({ options, entry }) => new I18nRuntime(options, entry),
package/dist/service.d.ts CHANGED
@@ -15,6 +15,16 @@ export declare class I18n implements I18nApi {
15
15
  readonly defaultLocale: string;
16
16
  /** D-0181: the apps with a layer of their own. */
17
17
  readonly apps: readonly string[];
18
+ /**
19
+ * D-0282: the template layers (the screen words of a domain template) and how many keys each
20
+ * replaces; checked here at start, used by the page bundles only.
21
+ */
22
+ readonly templates: readonly {
23
+ readonly kind: 'app' | 'module';
24
+ readonly name: string;
25
+ readonly template: string;
26
+ readonly keys: number;
27
+ }[];
18
28
  constructor(options: I18nOptions, input: unknown, logger: Logger);
19
29
  forLocale(locale?: string, options?: {
20
30
  readonly app?: string;
package/dist/service.js CHANGED
@@ -186,6 +186,11 @@ export class I18n {
186
186
  defaultLocale;
187
187
  /** D-0181: the apps with a layer of their own. */
188
188
  apps;
189
+ /**
190
+ * D-0282: the template layers (the screen words of a domain template) and how many keys each
191
+ * replaces; checked here at start, used by the page bundles only.
192
+ */
193
+ templates;
189
194
  /** Translators by scope (BASE, or an app with a layer), then by locale. */
190
195
  #translators = new Map();
191
196
  #negotiator;
@@ -203,12 +208,23 @@ export class I18n {
203
208
  throw new I18nError('INVALID_CATALOG', 'The i18n entry exports no catalogs: create src/infra/i18n/extension.ts with export const catalogs (npx dokebi add @dokebi/i18n writes it) and pass it as the plugin entry');
204
209
  // D-0118: the files loadCatalogs and loadLayers read are bounded here, where dokebi.yaml is known.
205
210
  const bytes = (catalogSource(entry.catalogs)?.bytes ?? 0) + (catalogSource(entry.layers)?.bytes ?? 0);
211
+ // Dot entries (`.claude/` a tool left in a locales folder) were left out while loading.
212
+ const skipped = [
213
+ ...(catalogSource(entry.catalogs)?.skipped ?? []),
214
+ ...(catalogSource(entry.layers)?.skipped ?? []),
215
+ ];
216
+ if (skipped.length && logger.isEnabled('debug'))
217
+ logger.log('debug', 'Translation catalog dot entries skipped', {
218
+ code: 'I18N_ENTRIES_SKIPPED',
219
+ skipped,
220
+ });
206
221
  if (bytes > options.maxCatalogBytes)
207
222
  throw new I18nError('INVALID_CATALOG', options.maxCatalogBytes === 4194304
208
223
  ? 'Catalog files exceed 4 MiB'
209
224
  : `Catalog files exceed ${options.maxCatalogBytes} bytes (maxCatalogBytes)`);
210
225
  // D-0181: the shared catalogs, the module layers and the app layers, each compiled once.
211
226
  const raw = entryLayers(entry);
227
+ // D-0282: template layers add no locale (a locale only they have fails their check below).
212
228
  const all = [raw.shared, ...raw.modules, ...raw.apps];
213
229
  const locales = localesOf(all);
214
230
  if (raw.shared.catalogs.size === 0 || locales.length > options.maxLocales)
@@ -251,6 +267,15 @@ export class I18n {
251
267
  }
252
268
  return { kind: layer.kind, name: layer.name, catalogs };
253
269
  };
270
+ // D-0282: template layers count toward the same bounds; their words are checked below.
271
+ const templateLayers = raw.templates.map((layer) => ({
272
+ layer,
273
+ compiled: compile({
274
+ kind: layer.kind,
275
+ name: `${layer.name} (template ${layer.template})`,
276
+ catalogs: layer.catalogs,
277
+ }),
278
+ }));
254
279
  const shared = compile(raw.shared);
255
280
  const modules = raw.modules.map(compile);
256
281
  const apps = raw.apps.map(compile);
@@ -282,6 +307,40 @@ export class I18n {
282
307
  baseTranslators.set(locale, translator(locale, messages, own));
283
308
  }
284
309
  this.#translators.set(BASE, baseTranslators);
310
+ // D-0282: a template layer only replaces words. A key the catalogs under it do not have in
311
+ // that locale is a typo, and other placeholders would break the page: both fail the start.
312
+ const placeholders = (resolved) => {
313
+ const names = new Set();
314
+ for (const parts of resolved.message.branches.values())
315
+ for (const part of parts)
316
+ if (typeof part !== 'string')
317
+ names.add(part.name);
318
+ return [...names].sort();
319
+ };
320
+ for (const { layer, compiled } of templateLayers)
321
+ for (const [locale, entries] of compiled.catalogs)
322
+ for (const [key, resolved] of entries) {
323
+ const under = (layer.kind === 'app'
324
+ ? apps
325
+ .find((app) => app.name === layer.name)
326
+ ?.catalogs.get(locale)
327
+ ?.get(key)
328
+ : apps.map((app) => app.catalogs.get(locale)?.get(key)).find(Boolean)) ??
329
+ base.get(locale)?.get(key);
330
+ const where = `${layer.kind === 'app' ? 'src/apps' : 'src/shared/modules'}/${layer.name}/views/${layer.template}/locales/${locale}`;
331
+ if (!under)
332
+ throw new I18nError('INVALID_CATALOG', `${where} replaces ${JSON.stringify(key)}, which the catalogs under it (${layer.kind === 'app' ? 'the app, the modules and the shared ones' : 'the modules, the apps and the shared ones'}) do not have in ${locale}: a template layer only replaces words`);
333
+ const own = placeholders(resolved);
334
+ const theirs = placeholders(under);
335
+ if (own.join(',') !== theirs.join(','))
336
+ throw new I18nError('INVALID_CATALOG', `${where} replaces ${JSON.stringify(key)} with other placeholders (${own.map((name) => `{${name}}`).join(' ') || 'none'} for ${theirs.map((name) => `{${name}}`).join(' ') || 'none'})`);
337
+ }
338
+ this.templates = Object.freeze(raw.templates.map((layer) => Object.freeze({
339
+ kind: layer.kind,
340
+ name: layer.name,
341
+ template: layer.template,
342
+ keys: [...layer.catalogs.values()].reduce((sum, entries) => sum + entries.size, 0),
343
+ })));
285
344
  // An app scope is its layer over the base: only the keys the layer has are resolved again
286
345
  // (per chain locale, the app's message before the base's: a locale still comes before a
287
346
  // layer); every other key is the base's, so an app costs its own messages, not a copy.
@@ -312,6 +371,11 @@ export class I18n {
312
371
  messages: messageCount,
313
372
  modules: modules.length,
314
373
  apps: this.apps,
374
+ ...(this.templates.length
375
+ ? {
376
+ templates: this.templates.map((layer) => `${layer.kind}:${layer.name}@${layer.template}=${layer.keys}`),
377
+ }
378
+ : {}),
315
379
  });
316
380
  Object.freeze(this);
317
381
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dokebi/i18n",
3
- "version": "0.2.7",
3
+ "version": "0.2.9",
4
4
  "description": "Compiled translation catalogs, locale negotiation, cardinal plurals and named Intl formats.",
5
5
  "keywords": [
6
6
  "dokebi",
@@ -66,6 +66,7 @@
66
66
  }
67
67
  ],
68
68
  "contributes": [
69
+ "core:describe",
69
70
  "dokebi-web:view-data"
70
71
  ],
71
72
  "installModule": "dist/install.js"
@@ -97,6 +98,6 @@
97
98
  }
98
99
  },
99
100
  "devDependencies": {
100
- "@dokebi/web": "0.4.12"
101
+ "@dokebi/web": "0.4.25"
101
102
  }
102
103
  }