@dokebi/template-inertia 0.4.28 → 0.4.30

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
@@ -216,7 +216,7 @@ route.get('/notices/:id', async (request, reply, page) =>
216
216
 
217
217
  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
218
 
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`.
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 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
220
 
221
221
  ### 4.1 The Vite plugin (`@dokebi/template-inertia/vite`, D-0062 addendum 2026-10-20)
222
222
 
@@ -295,7 +295,7 @@ A template can live apart from the app: a `views/<template>/` folder (Layout.vue
295
295
  }
296
296
  ```
297
297
  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'`).
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); 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
299
  - **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
300
  - **Asset version:** `<the app's version>+<template>@<buildId>`. A new bundle changes it, so an open page reloads at its next visit (409).
301
301
  - **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.
@@ -322,6 +322,7 @@ A template can live apart from the app: a `views/<template>/` folder (Layout.vue
322
322
  - `preview.json` of the template folder: `{ "shared": { "app": { "name": "site", "template": "luxe" }, "auth": { … } } }`, under every case (the props the app's shared data gives in production).
323
323
  - The preview files are not in the bundle: `template build` builds the `.vue` pages only.
324
324
  - **Languages (0.4.28, D-0300):** the preview offers every language: `--locales ko,en` (else `preview.json`'s `locales`, else every locale folder of the template's `locales/` and of `--words`), the first shown being `--locale` (else `preview.json`'s `locale`, else the first). `--words <dir>` is a folder of the app's catalogs (`<locale>/<namespace>.json`, the shape of `src/shared/locales`) under the template's own words, so keys the template does not override show the app's words, not their keys. The `i18n` prop carries the settings of a language switch, so the app's language buttons (`useI18n().locales`) show, and `switchLocale('en')` draws the page again in that language in the same document (the preview answers in the language of its cookie `dokebi_preview_locale`). The default language is the fallback of the others.
325
+ - **The app's word rules and missing policy (0.4.29, D-0301):** with `--words`, the template's words are checked as the app's start checks a template layer (D-0282): every key of `locales/<locale>/` must be in the app's catalogs for that language, with the same placeholders, and be a valid message. Otherwise the preview does not start, and a page drawn after the words broke answers 500, with `INVALID_TEMPLATE_PREVIEW` naming every line (`locales/ko/common.json: common.elite.band is not in the app catalogs for ko`; the first 20, then `… and N more`). Without `--words` there is nothing to check against. `--missing <auto|error|key>` (else `preview.json`'s `missing`, else `key`) is the app's `i18n.missing`: `error` (and `auto`, as the app's start and production run it) breaks a page that asks for a word no catalog has (PageI18nError), as the app does, where `key` shows the key.
325
326
  - **Pages follow the folder (0.4.27, D-0299):** the list and the page URLs are read from the folder for every request, so a page added or removed while the preview runs is there at once; adding or removing a `Pages/**/*.vue` or `Layout.vue` reloads the open pages and the list (edits stay HMR). The preview starts without any page too (the list says so) — a template of styles alone can grow its first page.
326
327
  - **Stylesheets (0.4.27, D-0298):** `--style theme.css,style.css` links the template's stylesheets in every page, in order, as the app does with the bundle; Vite serves them, so an edit shows at once (HMR).
327
328
  - **CSP (0.4.27, D-0297):** every page is drawn under a `Content-Security-Policy` as the app would send it: web's default policy, or the app's own setting with `--csp <file>` (a JSON file shaped like `securityHeaders.contentSecurityPolicy`: `{ "directives": { … }, "nonce": true, "styleNonce": true }`), plus the template's `csp.json` sources and the preview's HMR socket; with `nonce` Vite and the preview write the nonce on their scripts. What the policy blocks is listed in a box at the bottom of the page (`connect-src blocked https://…`: declare the origin in `csp.json`) and warned in the console. A changed `csp.json` or setting file reloads the page.
@@ -356,6 +357,8 @@ A template can live apart from the app: a `views/<template>/` folder (Layout.vue
356
357
  - **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).
357
358
  - **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).
358
359
  - **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.
360
+ - **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.
361
+ - **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).
359
362
  - **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).
360
363
  - **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.
361
364
  - **Pre-bundled dependencies that load (D-0128, 0.4.4)**: Vite keeps what its dependency optimizer wrote (each dependency's file under `node_modules/.vite/deps` and the `?v=` hash pages get) in memory, and at start trusts `_metadata.json` whenever the lockfile and config hashes match; it never looks at the files again, and it answers a file that is gone with 504 "Outdated Optimize Dep". A folder changed under it (two Vite optimizers on one folder — two `dokebi dev` sessions, a host still closing while the next starts — or a reinstall) therefore left every page blank through app restarts and dev restarts, until `rm -rf node_modules/.vite`. The host now compares its optimizer's files and metadata hashes with the folder when it starts, whenever an app process connects (every app or worker start) and after it answered a 504; when they differ it removes the deps folder and restarts its Vite (warn `INERTIA_VITE_DEPS_STALE` with `trigger` `start`, `client` or `outdated`, `drift` `missing` or `rewritten`, and a sample of the missing files), and the app process is answered after the repair. Open pages reconnect HMR and reload; a new page load gets the new hashes. At most one repair per `devDepsRepairIntervalMs`; faster changes are reported with warn `INERTIA_VITE_DEPS_CHANGING`. The host records its pid in `<cacheDir>/.dokebi/vite-host.json` and warns `INERTIA_VITE_HOST_SHARED` when another live host recorded itself there (stop one of the two `dokebi dev`). App processes pass Vite's status text on (`504 Outdated Optimize Dep`).
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.28',
1255
+ version: '0.4.30',
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.28' };
18
+ const BUILDER = { name: 'dokebi-template-inertia', version: '0.4.30' };
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). */
@@ -32,6 +32,12 @@ export interface TemplatePreviewOptions {
32
32
  readonly locales?: readonly string[];
33
33
  /** D-0300: the language shown first (default: preview.json `locale`, else the first). */
34
34
  readonly defaultLocale?: string;
35
+ /**
36
+ * D-0301: the app's `i18n.missing` policy (default: preview.json `missing`, else `key`): `error`
37
+ * breaks a page that asks for a word no catalog has (PageI18nError), as the app does; `auto` is
38
+ * `error`, as the app's start and production run it.
39
+ */
40
+ readonly missing?: PreviewMissing;
35
41
  readonly logger?: Logger;
36
42
  }
37
43
  export interface TemplatePreviewPage {
@@ -48,6 +54,10 @@ export interface TemplatePreview {
48
54
  export declare function previewCases(file: string): Promise<Record<string, Record<string, unknown>>>;
49
55
  /** D-0300: the cookie the preview's language switch writes (the app's switchLocale). */
50
56
  export declare const PREVIEW_LOCALE_COOKIE = "dokebi_preview_locale";
57
+ /** D-0301: the app's `i18n.missing` setting. */
58
+ export type PreviewMissing = 'auto' | 'error' | 'key';
59
+ /** D-0301: the `missing` policies the preview takes (the app's `i18n.missing` values). */
60
+ export declare const PREVIEW_MISSING: readonly PreviewMissing[];
51
61
  /** D-0300: where the preview's languages and words come from. */
52
62
  export interface PreviewWordsOptions {
53
63
  /**
@@ -59,6 +69,8 @@ export interface PreviewWordsOptions {
59
69
  readonly locales?: readonly string[];
60
70
  /** The language shown first (default: the first of `locales`). */
61
71
  readonly defaultLocale?: string;
72
+ /** D-0301: the app's `i18n.missing` policy (default `key`; `auto` is `error`). */
73
+ readonly missing?: PreviewMissing;
62
74
  }
63
75
  /**
64
76
  * D-0291 stage 3b, D-0300: the `i18n` page prop of the preview: the words of `wanted` (or the
@@ -81,6 +81,11 @@ function flatten(input, prefix, out) {
81
81
  export const PREVIEW_LOCALE_COOKIE = 'dokebi_preview_locale';
82
82
  /** A locale folder name: a language tag. */
83
83
  const LOCALE = /^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8}){0,4}$/;
84
+ /** D-0301: the `missing` policies the preview takes (the app's `i18n.missing` values). */
85
+ export const PREVIEW_MISSING = Object.freeze(['auto', 'error', 'key']);
86
+ const MISSING = new Set(PREVIEW_MISSING);
87
+ /** D-0301: a template word problem lines listed in one error (the rest are counted). */
88
+ const WORD_PROBLEMS_SHOWN = 20;
84
89
  /** The locale folders of `root`, sorted (none when it is missing). */
85
90
  async function localeFolders(root) {
86
91
  if (root === undefined || !existsSync(root))
@@ -115,6 +120,75 @@ async function localeWords(root, locale, messages, namespaces) {
115
120
  flatten(parsed, namespace, messages);
116
121
  }
117
122
  }
123
+ /**
124
+ * D-0301: the placeholder names of a message as dokebi-i18n reads it (`{name}`, `{{`/`}}` escape a
125
+ * brace; a plural object is its branches), sorted, or a reason it is not a message.
126
+ */
127
+ function placeholdersOf(message) {
128
+ const branches = typeof message === 'string'
129
+ ? [message]
130
+ : message !== null &&
131
+ typeof message === 'object' &&
132
+ !Array.isArray(message) &&
133
+ typeof message.other === 'string' &&
134
+ Object.values(message).every((branch) => typeof branch === 'string')
135
+ ? Object.values(message)
136
+ : undefined;
137
+ if (!branches)
138
+ return 'a string or plural categories with other';
139
+ const names = new Set();
140
+ for (const text of branches)
141
+ for (let index = 0; index < text.length;) {
142
+ const char = text[index];
143
+ if ((char === '{' || char === '}') && text[index + 1] === char)
144
+ index += 2;
145
+ else if (char === '{') {
146
+ const end = text.indexOf('}', index + 1);
147
+ const name = text.slice(index + 1, end);
148
+ if (end < 0 || !/^[a-zA-Z_][a-zA-Z0-9_]{0,63}$/.test(name))
149
+ return 'an invalid named placeholder';
150
+ names.add(name);
151
+ index = end + 1;
152
+ }
153
+ else if (char === '}')
154
+ return 'an unescaped closing brace';
155
+ else
156
+ index++;
157
+ }
158
+ return [...names].sort();
159
+ }
160
+ /**
161
+ * D-0301: the template's words against the app's catalogs, as the app's start checks a template
162
+ * layer (D-0282): a layer only replaces words, so each key must be in the app's catalogs for that
163
+ * language, with the same placeholders. Every problem is one line; none means they fit.
164
+ */
165
+ async function templateWordProblems(own, app) {
166
+ const problems = [];
167
+ for (const locale of await localeFolders(own)) {
168
+ const theirs = {};
169
+ await localeWords(app, locale, theirs, new Set());
170
+ const mine = {};
171
+ await localeWords(own, locale, mine, new Set());
172
+ for (const [key, message] of Object.entries(mine)) {
173
+ const where = `locales/${locale}/${key.slice(0, key.indexOf('.'))}.json: ${key}`;
174
+ const names = placeholdersOf(message);
175
+ if (typeof names === 'string') {
176
+ problems.push(`${where} is not a valid message (${names})`);
177
+ continue;
178
+ }
179
+ if (!Object.hasOwn(theirs, key)) {
180
+ problems.push(`${where} is not in the app catalogs for ${locale}`);
181
+ continue;
182
+ }
183
+ const under = placeholdersOf(theirs[key]);
184
+ if (typeof under === 'string')
185
+ continue;
186
+ if (names.join(',') !== under.join(','))
187
+ problems.push(`${where} has other placeholders (${names.map((name) => `{${name}}`).join(' ') || 'none'} for ${under.map((name) => `{${name}}`).join(' ') || 'none'})`);
188
+ }
189
+ }
190
+ return problems;
191
+ }
118
192
  /**
119
193
  * D-0291 stage 3b, D-0300: the `i18n` page prop of the preview: the words of `wanted` (or the
120
194
  * default language) from the template's `locales/<locale>/<namespace>.json` over the app's
@@ -125,6 +199,18 @@ async function localeWords(root, locale, messages, namespaces) {
125
199
  export async function previewWords(folder, wanted, options = {}) {
126
200
  const own = join(folder, 'locales');
127
201
  const app = options.words;
202
+ if (options.missing !== undefined && !MISSING.has(options.missing))
203
+ throw new InertiaUsageError('INVALID_TEMPLATE_PREVIEW', `missing must be auto, error or key, not ${JSON.stringify(options.missing)}`);
204
+ // D-0301: the app refuses a template layer that adds words or changes placeholders (D-0282), so
205
+ // the preview does too; without the app's catalogs there is nothing to check against.
206
+ if (app !== undefined) {
207
+ const problems = await templateWordProblems(own, app);
208
+ if (problems.length)
209
+ throw new InertiaUsageError('INVALID_TEMPLATE_PREVIEW', `${problems.length} template words do not fit the app catalogs (${app}); the app refuses this template (a template only replaces words, with the same placeholders):\n${problems
210
+ .slice(0, WORD_PROBLEMS_SHOWN)
211
+ .map((line) => ` ${line}`)
212
+ .join('\n')}${problems.length > WORD_PROBLEMS_SHOWN ? `\n … and ${problems.length - WORD_PROBLEMS_SHOWN} more` : ''}`);
213
+ }
128
214
  const found = [...new Set([...(await localeFolders(own)), ...(await localeFolders(app))])].sort();
129
215
  const locales = options.locales?.length ? [...options.locales] : found;
130
216
  for (const locale of locales)
@@ -162,7 +248,7 @@ export async function previewWords(folder, wanted, options = {}) {
162
248
  settings: {
163
249
  locales,
164
250
  defaultLocale,
165
- missing: 'key',
251
+ missing: options.missing === undefined || options.missing === 'key' ? 'key' : 'error',
166
252
  timeZone: 'UTC',
167
253
  maxOutputLength: 65536,
168
254
  cookie: PREVIEW_LOCALE_COOKIE,
@@ -171,7 +257,7 @@ export async function previewWords(folder, wanted, options = {}) {
171
257
  },
172
258
  };
173
259
  }
174
- /** `preview.json` of the template folder: `{ shared, locale?, locales? }` (the languages). */
260
+ /** `preview.json` of the template folder: `{ shared, locale?, locales?, missing? }` (the words). */
175
261
  async function previewLocale(folder) {
176
262
  const file = join(folder, 'preview.json');
177
263
  if (!existsSync(file))
@@ -179,6 +265,7 @@ async function previewLocale(folder) {
179
265
  try {
180
266
  const parsed = JSON.parse(await readFile(file, 'utf8'));
181
267
  return {
268
+ ...(typeof parsed?.missing === 'string' ? { missing: parsed.missing } : {}),
182
269
  ...(typeof parsed?.locale === 'string' ? { locale: parsed.locale } : {}),
183
270
  ...(Array.isArray(parsed?.locales) && parsed.locales.every((item) => typeof item === 'string')
184
271
  ? { locales: parsed.locales }
@@ -357,6 +444,25 @@ export async function startTemplatePreview(options) {
357
444
  const currentNames = async () => [...(await templatePages(folder)).keys()]
358
445
  .filter((key) => key.startsWith('Pages/'))
359
446
  .map((key) => key.slice(6));
447
+ /**
448
+ * D-0300, D-0301: the i18n prop: every language (options, else preview.json, else the locale
449
+ * folders), the one the language switch chose (its cookie), the app's catalogs under the
450
+ * template's words (checked as the app checks them) and the app's missing policy.
451
+ */
452
+ const wordsOf = async (language) => {
453
+ const chosen = await previewLocale(folder);
454
+ const defaultLocale = options.defaultLocale ?? chosen.locale;
455
+ const locales = options.locales ?? chosen.locales;
456
+ const missing = options.missing ?? chosen.missing;
457
+ return previewWords(folder, language ?? defaultLocale, {
458
+ ...(appWords === undefined ? {} : { words: appWords }),
459
+ ...(locales === undefined ? {} : { locales }),
460
+ ...(defaultLocale === undefined ? {} : { defaultLocale }),
461
+ ...(missing === undefined ? {} : { missing }),
462
+ });
463
+ };
464
+ // D-0301: words the app would refuse stop the preview here, as they stop the app's start.
465
+ await wordsOf();
360
466
  /** The page object of one preview URL. */
361
467
  const pageObject = async (name, wanted, language) => {
362
468
  const cases = await previewCases(join(folder, 'Pages', `${name}.preview.json`));
@@ -368,16 +474,7 @@ export async function startTemplatePreview(options) {
368
474
  };
369
475
  // D-0291 stage 3b: the template's own words, unless the case gives its own i18n.
370
476
  if (props.i18n === undefined) {
371
- // D-0300: every language (options, else preview.json, else the locale folders), the one the
372
- // language switch chose (its cookie), the app's catalogs under the template's words.
373
- const chosenLanguages = await previewLocale(folder);
374
- const defaultLocale = options.defaultLocale ?? chosenLanguages.locale;
375
- const locales = options.locales ?? chosenLanguages.locales;
376
- const words = await previewWords(folder, language ?? defaultLocale, {
377
- ...(appWords === undefined ? {} : { words: appWords }),
378
- ...(locales === undefined ? {} : { locales }),
379
- ...(defaultLocale === undefined ? {} : { defaultLocale }),
380
- });
477
+ const words = await wordsOf(language);
381
478
  if (words) {
382
479
  props.i18n = words;
383
480
  props.locale ??= words.locale;
@@ -471,7 +568,7 @@ await createInertiaApp({
471
568
  logger.log('error', 'Template preview could not draw a page', {
472
569
  code: 'INERTIA_TEMPLATE_PREVIEW_FAILED',
473
570
  url: url.pathname,
474
- error: error.message,
571
+ error,
475
572
  });
476
573
  send(500, 'text/html; charset=utf-8', `<!doctype html><pre>${escapeHtml(error.message)}</pre>`);
477
574
  };
@@ -496,7 +593,8 @@ await createInertiaApp({
496
593
  const name = decodeURIComponent(url.pathname.slice(PREVIEW_PREFIX.length));
497
594
  if (!TEMPLATE_PAGE.test(`Pages/${name}`))
498
595
  return send(404, 'text/plain; charset=utf-8', `No page ${name} in ${options.dir}`);
499
- currentNames().then(async (names) => {
596
+ currentNames()
597
+ .then(async (names) => {
500
598
  if (!names.includes(name))
501
599
  return send(404, 'text/plain; charset=utf-8', `No page ${name} in ${options.dir}`);
502
600
  const { page } = await pageObject(name, url.searchParams.get('case'), cookieLocale(request.headers.cookie));
@@ -508,7 +606,8 @@ await createInertiaApp({
508
606
  const policy = await previewPolicy(folder, cspSetting, socketOrigin(), nonce);
509
607
  const html = await server.transformIndexHtml(url.pathname, `<!doctype html><html><head><meta charset="utf-8"><title>${escapeHtml(name)} · preview</title>${styles.map((file) => `<link rel="stylesheet" nonce="${nonce}" href="${escapeHtml(`${folderUrl}/${file}`)}">`).join('')}<script type="module" src="${ENTRY_URL}" nonce="${nonce}"></script></head><body><script data-page="app" type="application/json">${scriptJson(page)}</script><div id="app"></div></body></html>`);
510
608
  send(200, 'text/html; charset=utf-8', html, { 'content-security-policy': policy });
511
- }, fail);
609
+ })
610
+ .catch(fail);
512
611
  });
513
612
  // D-0299: a page added or removed (or the Layout) reloads the open pages and the list.
514
613
  const pagesFolder = join(folder, 'Pages') + sep;
@@ -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')
@@ -1,4 +1,4 @@
1
1
  export { buildTemplateBundle, packageEntry, TEMPLATE_CARRY_FOLDER, TEMPLATE_CSP_FILE, type TemplateBuildOptions, type TemplateBuildResult, templatePages, } from './template-build.js';
2
2
  export { checkTemplateBundle, compatibleLine, cspDeclarationProblem, type ProvidedShared, SERVER_ONLY_SHARED, SHARED_DEFAULTS, sharedProblems, TEMPLATE_CSP_DIRECTIVES, TEMPLATE_FORMAT, TEMPLATE_MANIFEST, TEMPLATE_MAX_BYTES, TEMPLATE_NAME, TEMPLATE_SIGNATURE, TEMPLATE_STYLES_MAX, type TemplateCheck, type TemplateCheckLimits, type TemplateManifest, type TemplatePage, type TemplateProblem, } from './template-bundle.js';
3
- export { PREVIEW_LOCALE_COOKIE, PREVIEW_PREFIX, type PreviewWordsOptions, previewCases, previewPolicy, previewWords, startTemplatePreview, type TemplatePreview, type TemplatePreviewOptions, type TemplatePreviewPage, } from './template-preview.js';
3
+ export { PREVIEW_LOCALE_COOKIE, PREVIEW_MISSING, PREVIEW_PREFIX, type PreviewMissing, type PreviewWordsOptions, previewCases, previewPolicy, previewWords, startTemplatePreview, type TemplatePreview, type TemplatePreviewOptions, type TemplatePreviewPage, } from './template-preview.js';
4
4
  export { type DokebiInertiaTemplateOptions, packageVersion, SHARED_FILE, type SharedFile, sharedEntryName, } from './template-shared.js';
package/dist/template.js CHANGED
@@ -2,5 +2,5 @@
2
2
  // the build that `dokebi template build` runs in a template repository.
3
3
  export { buildTemplateBundle, packageEntry, TEMPLATE_CARRY_FOLDER, TEMPLATE_CSP_FILE, templatePages, } from './template-build.js';
4
4
  export { checkTemplateBundle, compatibleLine, cspDeclarationProblem, SERVER_ONLY_SHARED, SHARED_DEFAULTS, sharedProblems, TEMPLATE_CSP_DIRECTIVES, TEMPLATE_FORMAT, TEMPLATE_MANIFEST, TEMPLATE_MAX_BYTES, TEMPLATE_NAME, TEMPLATE_SIGNATURE, TEMPLATE_STYLES_MAX, } from './template-bundle.js';
5
- export { PREVIEW_LOCALE_COOKIE, PREVIEW_PREFIX, previewCases, previewPolicy, previewWords, startTemplatePreview, } from './template-preview.js';
5
+ export { PREVIEW_LOCALE_COOKIE, PREVIEW_MISSING, PREVIEW_PREFIX, previewCases, previewPolicy, previewWords, startTemplatePreview, } from './template-preview.js';
6
6
  export { packageVersion, SHARED_FILE, sharedEntryName, } from './template-shared.js';
@@ -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.28",
3
+ "version": "0.4.30",
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",