@dokebi/template-inertia 0.4.29 → 0.4.31

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
@@ -148,7 +148,7 @@ const { t, n, d, locale, locales, switchLocale, localeName, timeZone } = useI18n
148
148
  </template>
149
149
  ```
150
150
 
151
- - `t(key, parameters?)`, `t(key, defaultValue, parameters?)`, `n(value, format?)`, `d(value, format?)`, `has(key)`: the server translator's rules — `{name}` placeholders, `{{`/`}}` literal braces, cardinal plurals chosen by `Intl.PluralRules` of the locale that gave the message, the lookup chain selected → registered parents → default, an explicit default that wins over the chain but not over the locale's own message, the `missing` policy in effect on the server (`error` throws `MISSING_MESSAGE` naming the namespace to send; `key` returns the key; dokebi-i18n's default `auto` is `key` under `npx dokebi dev` and `error` elsewhere), `maxOutputLength`, `maxKeyLength` and `maxBranchLength` of the server's settings (defaults 256 and 16384 when the server sends none), the named number/date formats and the application's time zone of the page's settings. A parity test runs the server translator and this runtime on one corpus.
151
+ - `t(key, parameters?)`, `t(key, defaultValue, parameters?)`, `n(value, format?)`, `d(value, format?)`, `has(key)`: the server translator's rules — `{name}` placeholders, `{{`/`}}` literal braces, cardinal plurals chosen by `Intl.PluralRules` of the locale that gave the message, the lookup chain selected → registered parents → default, an explicit default that wins over the chain but not over the locale's own message, the `missing` policy in effect on the server (`error` throws `MISSING_MESSAGE` naming the namespace to send; `key` returns the key; dokebi-i18n's default `auto` is `key` under `npx dokebi dev` and `error` elsewhere), the keys the app's pages never receive (0.4.31, D-0312: dokebi-i18n `http.apps.<app>.pageExclude` reaches the page as `settings.excluded`; a key under one throws `EXCLUDED_MESSAGE` naming the prefix with `missing: error`, and with `key` returns the key and warns `I18N_EXCLUDED_KEY` once per prefix — an explicit default still wins), `maxOutputLength`, `maxKeyLength` and `maxBranchLength` of the server's settings (defaults 256 and 16384 when the server sends none), the named number/date formats and the application's time zone of the page's settings. A parity test runs the server translator and this runtime on one corpus.
152
152
  - `timeZone()` is that zone: it follows `setTimeZone` on the server from the next page on (D-0178). Pass it to `@dokebi/i18n/calendar` so a page counts days as the server does (`dayOf(timeZone(), Date.now())` is the site's today; `presetRange(timeZone(), 'last7')` a filter's days).
153
153
  - `locale` and `locales` are read-only refs (destructure them; templates unwrap them). The functions are bound, so destructuring keeps them working. Templates also have `$t`, `$n`, `$d` and `$i18n`.
154
154
  - `switchLocale(locale)` writes the preference cookie of dokebi-i18n (`http.cookieName`) and reloads the page's props through Inertia's router (no document reload): every prop comes back translated by the server, plus the messages this browser does not hold. `<html lang>` follows. `localeName(code)` is the language's own name for a switch (`Intl.DisplayNames`). The generated `views/default/Layout.vue` shows such a switch when there are two or more locales.
@@ -157,7 +157,7 @@ const { t, n, d, locale, locales, switchLocale, localeName, timeZone } = useI18n
157
157
  - **Kept between page loads (D-0126).** In a browser, when the server allows it (`settings.cache`, dokebi-i18n `http.pageCache`), the bundles a page receives are written to localStorage when the page is idle (one item per bundle: `dokebi-i18n:1:<locale>:<namespace>:<token>:…`, one version per locale and namespace, within `maxBundles` and `maxStoreCharacters`, the oldest bundles of other locales evicted first, also when the quota is full) and the cookie `dokebi-i18n-held` names them (newest of the shown locale first, within `maxCookieBytes`). The next full page load leaves them out of the HTML (`held`) and the runtime reads them from the store before the first render; the kept bundles of the shown locale are loaded into memory when idle, so visits name them too, and `switchLocale` names the kept bundles of the target language. **When the store lacks a bundle the server left out** (storage cleared, a changed cookie, a full quota, another tab evicted it), the runtime rewrites the cookie from what is really kept and fetches the missing messages with an Inertia partial request for `i18n` **before `app.mount` runs** (pageI18n defers the app's `mount`, so neither a client render nor a hydration ever draws without them; an SSR page stays visible meanwhile). If that request gets no Inertia answer, the cookie is deleted and the document is loaded again (at most once a minute per tab; after that the page mounts and the failure is logged at `error` as `I18N_PAGE_RECOVERY_FAILED`). On the server, SSR takes the left-out bundles from the catalogs of @dokebi/i18n in the same process, so the first paint has them; a renderer in another process cannot, and `t()` throws `MISSING_MESSAGE` (the SSR failure policy applies). `storage: false` keeps nothing. No app code changes: the generated `views/app.js` and `views/ssr.js` are unchanged.
158
158
  - A project made before this entry existed: `views/app.js` and `views/ssr.js` are yours, so add the two lines by hand — `import { pageI18n } from '@dokebi/template-inertia/i18n'`, then `.use(pageI18n(props.initialPage, { router }))` after `.use(plugin)` in `setup` (`router` from `@inertiajs/vue3`), and `withApp: (vue) => vue.use(pageI18n(page))` in the `createInertiaApp` options of `views/ssr.js`.
159
159
  - `createI18n({ locale, messages, defaultLocale?, fallback?, missing?, timeZone?, maxOutputLength?, maxKeyLength?, maxBranchLength?, numberFormats?, dateFormats?, logger? })` makes an instance from given messages (flat dot keys or nested namespace objects), for plain Vue apps and unit tests: `app.use(createI18n(...))`.
160
- - Debug logs (D-0047) go to the optional `logger` (`{ isEnabled?, log(level, message, fields) }`): `Missing translation returned as key` (`I18N_MISSING_KEY`), `Page translations are off` (`I18N_PAGE_OFF`), `Page translations reloaded` (`I18N_PAGE_RELOAD`), `Page language switch` (`I18N_PAGE_SWITCH`); D-0126: `I18N_PAGE_INCOMPLETE` (a page lacks bundles), `I18N_PAGE_RECOVER`, `I18N_PAGE_RECOVERED`, `I18N_PAGE_RECOVERY_RELOAD`, `I18N_STORE_COOKIE`, `I18N_STORE_LOADED`, `I18N_STORE_FULL`, `I18N_STORE_TRIMMED`, `I18N_STORE_SKIPPED`, `I18N_STORE_INVALID` (an item that is not the server's shape is removed), `I18N_STORE_UNAVAILABLE` (storage refused: nothing is kept and the cookie is deleted), `I18N_STORE_OFF`.
160
+ - Debug logs (D-0047) go to the optional `logger` (`{ isEnabled?, log(level, message, fields) }`): `Missing translation returned as key` (`I18N_MISSING_KEY`), `Excluded translation returned as key` (`I18N_EXCLUDED_KEY`, `prefix`; the first one per prefix at `warn`), `Page translations are off` (`I18N_PAGE_OFF`), `Page translations reloaded` (`I18N_PAGE_RELOAD`), `Page language switch` (`I18N_PAGE_SWITCH`); D-0126: `I18N_PAGE_INCOMPLETE` (a page lacks bundles), `I18N_PAGE_RECOVER`, `I18N_PAGE_RECOVERED`, `I18N_PAGE_RECOVERY_RELOAD`, `I18N_STORE_COOKIE`, `I18N_STORE_LOADED`, `I18N_STORE_FULL`, `I18N_STORE_TRIMMED`, `I18N_STORE_SKIPPED`, `I18N_STORE_INVALID` (an item that is not the server's shape is removed), `I18N_STORE_UNAVAILABLE` (storage refused: nothing is kept and the cookie is deleted), `I18N_STORE_OFF`.
161
161
  - Types: `page.d.ts` of the scaffold types `$page.props.i18n` (`PageI18nPayload`) and `locale`; importing the module also types `$t`, `$n`, `$d` and `$i18n` for vue-tsc. Vue is an optional peer dependency (`^3.5.0`), used only by this entry.
162
162
  - Do not add `vue-i18n` or another translation runtime, import the catalogs into the browser bundle, cache messages yourself or build a route that serves them: the prop already carries what the page needs, once per browser and bundle version.
163
163
 
@@ -169,6 +169,7 @@ const { t, n, d, locale, locales, switchLocale, localeName, timeZone } = useI18n
169
169
  | `INVALID_LOCALE` | an invalid BCP 47 tag; `switchLocale` without a router to a locale without messages |
170
170
  | `INVALID_FORMAT` | an unknown or invalid named number/date format |
171
171
  | `MISSING_MESSAGE` | an invalid key, or no message in the lookup chain with `missing: error` |
172
+ | `EXCLUDED_MESSAGE` | a key under the app's `pageExclude` (`settings.excluded`) with `missing: error`: the server leaves it out of this app's pages on purpose (D-0312) |
172
173
  | `INVALID_PARAMETER` | a missing parameter, a non-finite number, an invalid date or plural count |
173
174
  | `OUTPUT_LIMIT` | the rendered message (or a returned missing key) exceeds `maxOutputLength` |
174
175
  | `RECOVERY_FAILED` | the fetch of a first page's missing bundles got no Inertia answer, or one without them (handled: the document is loaded again without the cookie; it is the `error` of `I18N_PAGE_RECOVERY_FAILED`) |
@@ -216,7 +217,7 @@ route.get('/notices/:id', async (request, reply, page) =>
216
217
 
217
218
  With `vite`, the manifest (at most `viteManifestMaxBytes`, 4 MiB) is read once in setup, and the files reachable from the entry (static and dynamic chunks, CSS, assets) are served at the exact path `<base><file>` (`cache-control: public, max-age=31536000, immutable`). Each file is read on its first request and kept in memory (files above `assetCacheMaxBytes`, 4 MiB, are streamed per request), so rebuild with new hashed names and restart instead of changing a served file in place. A missing manifest fails the start (`Vite manifest not found: … Build the views first (npm run build).`), and so does a missing entry.
218
219
 
219
- **Rolling deploys (two builds at once).** During `rollingRestart` (or any deploy that replaces workers one by one) old and new workers answer side by side: a page of the new build loads its chunks from workers that read the old manifest, and the other way round. So every worker also serves **the other files of the folders its manifest's files sit in** (`<base>assets/*` for Vite's default `assets/`), streamed from disk: regular files only, inside that folder (no `..`, no hidden name, no symbolic link out of it), never a source map (`*.map`: the manifest names none, and `build.sourcemap: 'hidden'` writes them there for error tracking only); a content-hashed name (`app-3fa8c1d2.js`) gets the immutable header, any other `no-cache`; a name that is not there is 404. The manifest, `.vite/`, `dist/ssr/` and files directly in `outDir` are never served. For this to work the deploy must **keep the chunks of the previous build**: build with `build.emptyOutDir: false` (Vite's default `true` deletes them, and pages of the old build then miss their chunks on every worker). Remove the old chunks with `pruneBuildFiles` of `@dokebi/template-inertia/prune`, after a deploy or daily, on every host that has its own `dist/`: `node -e "import('@dokebi/template-inertia/prune').then(async (m) => console.log(await m.pruneBuildFiles({ manifest: 'dist/.vite/manifest.json' })))"` (also as a `prune:build` script in package.json). The current manifest decides, not the age alone: every file it names (and the source map of one) stays however old it is; a content-hashed file of the manifest's folders that it does not name goes once it is unchanged for `olderThanMs` (default 7 days, the time a page of an earlier build may stay open; 0 removes them all). Unhashed names (`robots.txt`), hidden names, links and the files directly in `outDir` (`.vite/`, `dist/ssr/`) are never touched. A manifest that is missing (`VITE_MANIFEST_MISSING`), not an object of chunks, larger than `maxManifestBytes` (4 MiB) or naming no file (`VITE_MANIFEST_INVALID`) removes nothing. `dryRun: true` lists what would go; the result is `{ folders, removed, kept }`. Do not use an age-only cleanup such as `find dist/assets -type f -mtime +7 -delete`: when no deploy comes for a week it removes the current build's files too (a page then misses its chunks: 404). Server rendering stays on the manifest and bundle a worker read at start: an old worker renders the old build until it is replaced. Its SSR bundle may still import chunks of its own lazily (a dynamic `import()`, a non-eager `import.meta.glob`) at its first render of a page, so build the SSR side with `emptyOutDir: false` too; an emptied `dist/ssr/` makes that render fail (`INERTIA_SSR_FAILED`, the client-rendered fallback). Debug logs: `Vite build folder served` (url, folder), per request `Vite built file served from its folder`.
220
+ **Rolling deploys (two builds at once).** During `rollingRestart` (or any deploy that replaces workers one by one) old and new workers answer side by side: a page of the new build loads its chunks from workers that read the old manifest, and the other way round. So every worker also serves **the other files of the folders its manifest's files sit in** (`<base>assets/*` for Vite's default `assets/`), streamed from disk: regular files only, inside that folder (no `..`, no hidden name, no symbolic link out of it), never a source map (`*.map`: the manifest names none, and `build.sourcemap: 'hidden'` writes them there for error tracking only); a content-hashed name (`app-3fa8c1d2.js`) gets the immutable header, any other `no-cache`; a name that is not there is web's 404 with `Cache-Control: no-store` (0.4.30, [D-0302](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0302-missing-files-never-cached.md)), so a CDN or the browser never keeps the miss of a chunk a worker of the other build has: the next try gets it. The manifest, `.vite/`, `dist/ssr/` and files directly in `outDir` are never served. For this to work the deploy must **keep the chunks of the previous build**: build with `build.emptyOutDir: false` (Vite's default `true` deletes them, and pages of the old build then miss their chunks on every worker). Remove the old chunks with `pruneBuildFiles` of `@dokebi/template-inertia/prune`, after a deploy or daily, on every host that has its own `dist/`: `node -e "import('@dokebi/template-inertia/prune').then(async (m) => console.log(await m.pruneBuildFiles({ manifest: 'dist/.vite/manifest.json' })))"` (also as a `prune:build` script in package.json). The current manifest decides, not the age alone: every file it names (and the source map of one) stays however old it is; a content-hashed file of the manifest's folders that it does not name goes once it is unchanged for `olderThanMs` (default 7 days, the time a page of an earlier build may stay open; 0 removes them all). Unhashed names (`robots.txt`), hidden names, links and the files directly in `outDir` (`.vite/`, `dist/ssr/`) are never touched. A manifest that is missing (`VITE_MANIFEST_MISSING`), not an object of chunks, larger than `maxManifestBytes` (4 MiB) or naming no file (`VITE_MANIFEST_INVALID`) removes nothing. `dryRun: true` lists what would go; the result is `{ folders, removed, kept }`. Do not use an age-only cleanup such as `find dist/assets -type f -mtime +7 -delete`: when no deploy comes for a week it removes the current build's files too (a page then misses its chunks: 404). Server rendering stays on the manifest and bundle a worker read at start: an old worker renders the old build until it is replaced. Its SSR bundle may still import chunks of its own lazily (a dynamic `import()`, a non-eager `import.meta.glob`) at its first render of a page, so build the SSR side with `emptyOutDir: false` too; an emptied `dist/ssr/` makes that render fail (`INERTIA_SSR_FAILED`, the client-rendered fallback). Debug logs: `Vite build folder served` (url, folder), per request `Vite built file served from its folder`.
220
221
 
221
222
  ### 4.1 The Vite plugin (`@dokebi/template-inertia/vite`, D-0062 addendum 2026-10-20)
222
223
 
@@ -295,7 +296,7 @@ A template can live apart from the app: a `views/<template>/` folder (Layout.vue
295
296
  }
296
297
  ```
297
298
  A refused page answers with the app's page; a refused bundle leaves the template to the app. It may take `templateVerifyTimeoutMs`. **In production (`NODE_ENV=production`) a bundle without `verifyTemplate` is not used** (error `INERTIA_TEMPLATE_UNVERIFIED`): its server modules run in the app's process. In development it is used with a warning.
298
- - **The first HTML** of such a host carries an import map (with the CSP nonce) from the shared modules to the app build's files of them, so the bundle's `import 'vue'` is the app's vue in the browser too; the bundle's page table (`<script type="application/json" id="dokebi-template">`); the stylesheets and `modulepreload` links of the layout and the page. The bundle's browser files are served at `/_dokebi/templates/<app>/<template>/<buildId>/…` (immutable; the `templateKeep` generations). No CSP change is needed for the bundle itself: same origin (`'self'`), and the bundle's modules are imported by the app's own trusted script (`'strict-dynamic'`).
299
+ - **The first HTML** of such a host carries an import map (with the CSP nonce) from the shared modules to the app build's files of them, so the bundle's `import 'vue'` is the app's vue in the browser too; the bundle's page table (`<script type="application/json" id="dokebi-template">`); the stylesheets and `modulepreload` links of the layout and the page. The bundle's browser files are served at `/_dokebi/templates/<app>/<template>/<buildId>/…` (immutable; the `templateKeep` generations); any other path there is web's 404 with `Cache-Control: no-store` (0.4.30, D-0302). No CSP change is needed for the bundle itself: same origin (`'self'`), and the bundle's modules are imported by the app's own trusted script (`'strict-dynamic'`).
299
300
  - **Other origins a template uses (0.4.27, D-0297, web 0.4.28):** a template folder's **`csp.json`** declares them: `{ "connect-src": ["https://api.widget.example"], "font-src": ["https://fonts.example"], "frame-src": ["https://player.example"] }`. Directives: `script-src`, `style-src`, `connect-src`, `font-src`, `img-src`, `frame-src`; at most 32 sources each; each an `https://` origin (host with an optional `*.` in front, optional port and path; `wss://` in `connect-src`) — no keyword, nonce, bare scheme (`https:`, `data:`), `*` or `http://`. `template build` checks it (`INVALID_TEMPLATE_BUILD`; not JSON: `TEMPLATE_BUILD_FAILED`) and writes it, sorted, into the manifest as `csp` (covered by the signature; `template build` and `template check` show it). When the app loads the bundle, `verifyTemplate` sees `bundle.manifest.csp` and may answer `{ accept: true, csp: { … } }`: only the declared sources it lists are used (the rest: warn `INERTIA_TEMPLATE_CSP_REFUSED` with `refused`); without `csp` in the answer (and in development without `verifyTemplate`) every declared source is used. The first HTML of a host whose template has that bundle gets them added to its `Content-Security-Policy` (`web.addCsp`); other hosts and Inertia visits (JSON) do not change, and a new bundle changes them with no restart (its 409 reloads open pages). `templateState` gives `csp` (what is used) and `cspRefused`; `INERTIA_TEMPLATE_LOADED` has `csp`. Under a nonce policy browsers ignore host sources in `script-src` beside `'strict-dynamic'`; a script the page's code loads runs anyway, so declare `script-src` for apps without a nonce. With a web before 0.4.28 the sources are not used (warn `INERTIA_TEMPLATE_CSP_UNSUPPORTED`). Apps before 0.4.27 ignore `csp`.
300
301
  - **Asset version:** `<the app's version>+<template>@<buildId>`. A new bundle changes it, so an open page reloads at its next visit (409).
301
302
  - **Server rendering** uses the same generation (an AsyncLocalStorage store; `templatePages()` reads it through a global registry, no imports). The bundle's server modules import the shared modules through a resolve hook that answers only importers inside the cache folder: the app build's server entries of them, the same instances as the app's own pages.
@@ -357,6 +358,7 @@ A template can live apart from the app: a `views/<template>/` folder (Layout.vue
357
358
  - **A template declares the other origins it uses (0.4.27, [D-0297](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0297-template-csp-sources.md), web 0.4.28)**: the template folder's `csp.json` goes into the bundle's manifest; the app's `verifyTemplate` may narrow it; the first HTML drawn with the bundle adds those sources to its Content-Security-Policy, and only that host's pages do. `template preview --csp <app setting>` draws the pages under the same policy and lists what it blocks (§4.3).
358
359
  - **The template's look is in the first HTML; a template may have no page (0.4.27, [D-0298](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0298-template-styles-and-pageless-bundles.md))**: `dokebi template build --style theme.css` lists the template's stylesheets in the manifest (`styles`), and the app links them, in order and with the nonce, in the head of every first HTML of that template, where a template's stylesheet used to arrive after the first paint. A folder of stylesheets and carried files alone builds into a bundle without pages (§4.3).
359
360
  - **The preview follows the folder's pages (0.4.27, [D-0299](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0299-preview-follows-pages.md))**: a page added or removed while `dokebi template preview` runs is listed and drawn at once (the open pages reload), where the preview fixed its pages at start; it also starts without any page.
361
+ - **A missing file is never cached (0.4.30, [D-0302](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0302-missing-files-never-cached.md))**: the 404 of the build folder route (`<base>assets/*`) and of the bundle route (`/_dokebi/templates/…`) is web's 404 with `Cache-Control: no-store` (it was `{ error: 'NOT_FOUND' }` without the header, and a CDN kept it: during a rolling deploy a page waited on a chunk the edge remembered as missing, for up to 4 hours). The dev Vite fallthrough's 404 and 500 carry `no-store` too.
360
362
  - **The preview checks the template's words as the app does (0.4.29, [D-0301](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0301-preview-checks-template-words.md))**: `template preview --words <app catalogs>` refuses words the app would refuse (a key the app does not have in that language, other placeholders), naming every line, and `--missing error` draws with the app's missing policy; a template that GAON's app refused (PageI18nError) passed the preview before. A page request that failed in the preview (a broken `<Page>.preview.json`) now answers 500 instead of no answer (§4.3).
361
363
  - **The preview offers every language (0.4.28, [D-0300](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0300-preview-languages.md))**: `template preview --locales ko,en --locale ko [--words <app catalogs>]`: the app's language buttons show in the preview and switch the page, where the preview sent one language without the switch's settings (§4.3).
362
364
  - **A module URL the host answers 404 says why (0.4.23, [D-0292](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0292-vite-host-explains-module-404.md))**: Vite turns `ERR_LOAD_URL` ("Failed to load url … (resolved id: …) in <importer>") into `next()` without the error, so a module it could not load answered an empty 404 and nothing was logged. Now, when a module request (`GET`/`HEAD` under the base with a module or style extension, `?import`, or `Sec-Fetch-Dest: script`) ends that way, the host asks Vite again in the same process and logs warn `INERTIA_VITE_NOT_LOADED` with `url`, `module` (the module URL without `t` and `import`), `root`, `file`, `exists` (with `missing`: `ENOENT`, `directory`, …), `readable`, `real` (when it is a link), `allowed` (Vite's `isFileLoadingAllowed`), `graph` (the module graph's entry for the URL: `id`, `file`, `stale` when its id names another file, `transformed`, `invalidatedAt`), `cause` (the error of one more `transformRequest`: the message Vite dropped, with its `code`) and `loadsNow`. Once per URL until it is served again; repeats are debug with `repeats`. Vite's static middleware serves a file that is there and allowed even when its transform fails, so an empty 404 means that this process saw the file missing or not allowed; when the diagnosis finds it there, readable and allowed after all (`retry: true`), the host invalidates the module, drops a URL entry whose id names another file and runs the request through Vite once more: the warning then says it was served after invalidating it, and `retried` is the status of that second answer. A page, a folder and a virtual `/@id/` URL keep the plain 404.
package/dist/i18n.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { type App, type ComputedRef } from 'vue';
2
2
  import { BundleStore, type StoreHost } from './i18n-store.js';
3
- export type PageI18nErrorCode = 'UNAVAILABLE' | 'INVALID_CATALOG' | 'INVALID_LOCALE' | 'INVALID_FORMAT' | 'MISSING_MESSAGE' | 'INVALID_PARAMETER' | 'OUTPUT_LIMIT' | 'RECOVERY_FAILED';
3
+ export type PageI18nErrorCode = 'UNAVAILABLE' | 'INVALID_CATALOG' | 'INVALID_LOCALE' | 'INVALID_FORMAT' | 'MISSING_MESSAGE' | 'EXCLUDED_MESSAGE' | 'INVALID_PARAMETER' | 'OUTPUT_LIMIT' | 'RECOVERY_FAILED';
4
4
  /** A coded error of the browser runtime; the codes are the server translator's. */
5
5
  export declare class PageI18nError extends Error {
6
6
  readonly code: PageI18nErrorCode;
@@ -38,6 +38,11 @@ export interface PageI18nSettings {
38
38
  /** Longest X-Dokebi-I18n header the server reads (http.maxPageHeaderBytes). Default 4096. */
39
39
  readonly maxHeaderBytes?: number;
40
40
  readonly cache?: PageI18nCache;
41
+ /**
42
+ * D-0312: key prefixes this app's pages never receive (dokebi-i18n http.apps.<app>.pageExclude).
43
+ * A call of one is EXCLUDED_MESSAGE, not MISSING_MESSAGE.
44
+ */
45
+ readonly excluded?: readonly string[];
41
46
  }
42
47
  /** The shared page prop `i18n` of dokebi-i18n (D-0099, D-0126). */
43
48
  export interface PageI18nPayload {
package/dist/i18n.js CHANGED
@@ -129,6 +129,19 @@ function chainOf(locale, known, defaultLocale) {
129
129
  chain.push(defaultLocale);
130
130
  return chain;
131
131
  }
132
+ /**
133
+ * D-0312: the shortest pageExclude prefix that covers `key` (the key itself, or a part of it that
134
+ * ends at a dot), if any: one set lookup per dot, however long the list is.
135
+ */
136
+ function excludedBy(key, prefixes) {
137
+ for (let dot = key.indexOf('.');; dot = key.indexOf('.', dot + 1)) {
138
+ const part = dot < 0 ? key : key.slice(0, dot);
139
+ if (prefixes.has(part))
140
+ return part;
141
+ if (dot < 0)
142
+ return undefined;
143
+ }
144
+ }
132
145
  function namespaceOf(key) {
133
146
  const dot = key.indexOf('.');
134
147
  return dot < 0 ? key : key.slice(0, dot);
@@ -168,6 +181,10 @@ export class I18n {
168
181
  #formats = new Map();
169
182
  #defaults = new Map();
170
183
  #defaultCharacters = 0;
184
+ /** D-0312: the pageExclude prefixes already warned about (bounded by the settings' list). */
185
+ #warnedExcluded = new Set();
186
+ /** D-0312: `settings.excluded` as a set (the page's settings). */
187
+ #excludedSet;
171
188
  #settings;
172
189
  #logger;
173
190
  #feed;
@@ -248,6 +265,28 @@ export class I18n {
248
265
  this.#debug('Translation pending, key shown', { code: 'I18N_PAGE_PENDING', locale });
249
266
  return key;
250
267
  }
268
+ // D-0312: a key the server leaves out of this app's pages on purpose says so.
269
+ const excluded = this.#excludedSet && excludedBy(key, this.#excludedSet);
270
+ if (excluded) {
271
+ if (this.#settings.missing === 'error')
272
+ throw new PageI18nError('EXCLUDED_MESSAGE', `Message ${JSON.stringify(key)} is left out of this app's pages (pageExclude ${JSON.stringify(excluded)})`, `This app's pages do not receive keys under ${JSON.stringify(excluded)} (options.dokebi-i18n.http.apps.<app>.pageExclude): use another key on this page, or take the prefix out of pageExclude.`);
273
+ if (key.length > this.#settings.maxOutputLength)
274
+ throw new PageI18nError('OUTPUT_LIMIT', 'Missing key exceeds maxOutputLength');
275
+ // A page that calls a key it can never receive is a defect: warned once per prefix (an
276
+ // I18n lives as long as the document), then at debug like a missing key.
277
+ const fields = { code: 'I18N_EXCLUDED_KEY', locale, prefix: excluded };
278
+ if (!this.#warnedExcluded.has(excluded)) {
279
+ this.#warnedExcluded.add(excluded);
280
+ if (this.#logger && (this.#logger.isEnabled?.('warn') ?? true))
281
+ this.#logger.log('warn', 'Excluded translation returned as key', {
282
+ ...fields,
283
+ fix: `This app's pages do not receive keys under ${JSON.stringify(excluded)} (options.dokebi-i18n.http.apps.<app>.pageExclude).`,
284
+ });
285
+ }
286
+ else
287
+ this.#debug('Excluded translation returned as key', fields);
288
+ return key;
289
+ }
251
290
  if (this.#settings.missing === 'error')
252
291
  throw new PageI18nError('MISSING_MESSAGE', `No message ${JSON.stringify(key)} in the locale fallback chain of ${locale}`, `Add the key to src/shared/locales/<locale>/${key.split('.', 1)[0]}.json, or send that namespace to the page (options.dokebi-i18n.http.pageMessages, or pageMessages(request, '${key.split('.', 1)[0]}') in the route).`);
253
292
  if (key.length > this.#settings.maxOutputLength)
@@ -512,6 +551,10 @@ export class I18n {
512
551
  ...(settings.cache ? { cache: settings.cache } : {}),
513
552
  };
514
553
  this.#locales = Object.freeze([...settings.locales]);
554
+ this.#excludedSet =
555
+ Array.isArray(settings.excluded) && settings.excluded.length
556
+ ? new Set(settings.excluded.filter((prefix) => typeof prefix === 'string'))
557
+ : undefined;
515
558
  // Formats and the time zone may have changed with the version.
516
559
  this.#formats.clear();
517
560
  const cache = settings.cache;
package/dist/index.js CHANGED
@@ -984,8 +984,12 @@ class InertiaRuntime {
984
984
  config: publicAsset(routeIds, 'assets'),
985
985
  handler: async (request, reply) => {
986
986
  const file = await builtFolderFile(folder, request.params['*']);
987
- if (!file)
988
- return reply.code(404).send({ error: 'NOT_FOUND' });
987
+ // D-0302: web's 404 (Cache-Control: no-store): a chunk of a build this worker has not
988
+ // yet (a rolling deploy) must not be kept by a CDN or the browser.
989
+ if (!file) {
990
+ reply.callNotFound();
991
+ return reply;
992
+ }
989
993
  if (logger.isEnabled('debug'))
990
994
  logger.log('debug', 'Vite built file served from its folder', {
991
995
  url: request.url.split('?', 1)[0]?.slice(0, 200),
@@ -1248,7 +1252,7 @@ class InertiaRuntime {
1248
1252
  }
1249
1253
  export const createPlugin = definePlugin({
1250
1254
  name: 'dokebi-template-inertia',
1251
- version: '0.4.29',
1255
+ version: '0.4.31',
1252
1256
  core: '^0.4.2',
1253
1257
  options,
1254
1258
  entry: parseEntry,
@@ -15,7 +15,7 @@ import { checkTemplateBundle, cspDeclarationProblem, jsonValue, PAGE_META_MAX_BY
15
15
  import { packageVersion } from './template-shared.js';
16
16
  import { registerVueTypeScript } from './vue-typescript.js';
17
17
  /** The builder written into `builtWith` (scripts/testing/check-metadata.mjs keeps it the package version). */
18
- const BUILDER = { name: 'dokebi-template-inertia', version: '0.4.29' };
18
+ const BUILDER = { name: 'dokebi-template-inertia', version: '0.4.31' };
19
19
  /** D-0296: carried files go under this folder of the bundle (served like the pages' files). */
20
20
  export const TEMPLATE_CARRY_FOLDER = 'browser';
21
21
  /** The folders Vite writes under browser/: a carried file never takes them (any case). */
@@ -236,7 +236,10 @@ export declare class TemplateBundles {
236
236
  current(app: string, template: string | undefined): TemplateGeneration | undefined;
237
237
  /** The use of one request: undefined when its template has no bundle. */
238
238
  use(app: string, template: string | undefined, baseVersion: string): TemplateUse | undefined;
239
- /** `GET /_dokebi/templates/<app>/<template>/<buildId>/browser/…` of a kept generation. */
239
+ /**
240
+ * `GET /_dokebi/templates/<app>/<template>/<buildId>/browser/…` of a kept generation. Anything
241
+ * else is web's 404 (D-0302: `Cache-Control: no-store`, so a CDN or browser never keeps it).
242
+ */
240
243
  serve(path: string, reply: FastifyReply): Promise<FastifyReply>;
241
244
  /** For tests and describe: the loaded generations. */
242
245
  generations(): ReadonlyArray<{
@@ -923,8 +923,15 @@ export class TemplateBundles {
923
923
  },
924
924
  };
925
925
  }
926
- /** `GET /_dokebi/templates/<app>/<template>/<buildId>/browser/…` of a kept generation. */
926
+ /**
927
+ * `GET /_dokebi/templates/<app>/<template>/<buildId>/browser/…` of a kept generation. Anything
928
+ * else is web's 404 (D-0302: `Cache-Control: no-store`, so a CDN or browser never keeps it).
929
+ */
927
930
  async serve(path, reply) {
931
+ const notFound = () => {
932
+ reply.callNotFound();
933
+ return reply;
934
+ };
928
935
  const parts = path.split('/');
929
936
  const [app, template, buildId, ...rest] = parts;
930
937
  const file = rest.join('/');
@@ -933,10 +940,10 @@ export class TemplateBundles {
933
940
  if (!generation ||
934
941
  !file.startsWith('browser/') ||
935
942
  !Object.hasOwn(generation.manifest.files, file))
936
- return reply.code(404).send({ error: 'NOT_FOUND' });
943
+ return notFound();
937
944
  const absolute = join(generation.dir, ...file.split('/'));
938
945
  if (!absolute.startsWith(generation.dir + sep) || isAbsolute(file))
939
- return reply.code(404).send({ error: 'NOT_FOUND' });
946
+ return notFound();
940
947
  return reply
941
948
  .type(CONTENT_TYPES[extname(file).toLowerCase()] ?? 'application/octet-stream')
942
949
  .header('cache-control', 'public, max-age=31536000, immutable')
@@ -6,6 +6,7 @@ export declare const viteDevRequested: () => boolean;
6
6
  export interface DevResponse {
7
7
  statusCode: number;
8
8
  readonly headersSent: boolean;
9
+ setHeader(name: string, value: string): unknown;
9
10
  end(): unknown;
10
11
  }
11
12
  /**
package/dist/vite-dev.js CHANGED
@@ -33,13 +33,13 @@ export const viteDevRequested = () => process.env.DOKEBI_VITE_DEV === '1';
33
33
  * reported (logged by the caller) and answered 500, never dropped (D-0047).
34
34
  */
35
35
  export function viteFallthrough(response, error, report) {
36
- if (error !== undefined && error !== null) {
36
+ if (error !== undefined && error !== null)
37
37
  report(error);
38
- if (!response.headersSent)
39
- response.statusCode = 500;
38
+ if (!response.headersSent) {
39
+ response.statusCode = error !== undefined && error !== null ? 500 : 404;
40
+ // D-0302: never kept by a CDN in front of a dev tunnel, or by the browser.
41
+ response.setHeader('cache-control', 'no-store');
40
42
  }
41
- else if (!response.headersSent)
42
- response.statusCode = 404;
43
43
  response.end();
44
44
  }
45
45
  /** Header that carries the host key; the host answers no HTTP request without it. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dokebi/template-inertia",
3
- "version": "0.4.29",
3
+ "version": "0.4.31",
4
4
  "description": "Inertia v3 server adapter for Dokebi: page JSON, Vite manifest assets and optional server-side rendering.",
5
5
  "keywords": [
6
6
  "dokebi",
@@ -152,7 +152,7 @@
152
152
  ]
153
153
  },
154
154
  "devDependencies": {
155
- "@dokebi/i18n": "0.2.10",
155
+ "@dokebi/i18n": "0.2.11",
156
156
  "@dokebi/session": "0.4.11",
157
157
  "@dokebi/web": "0.4.28",
158
158
  "@dokebi/websocket": "0.4.10",