@dokebi/template-inertia 0.4.19 → 0.4.21
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 +59 -1
- package/README.md +4 -0
- package/dist/errors.d.ts +2 -2
- package/dist/errors.js +5 -1
- package/dist/index.d.ts +19 -0
- package/dist/index.js +107 -11
- package/dist/options.d.ts +9 -0
- package/dist/options.js +53 -0
- package/dist/pages.d.ts +33 -0
- package/dist/pages.js +82 -0
- package/dist/responder.d.ts +6 -0
- package/dist/responder.js +18 -8
- package/dist/template-build.d.ts +43 -0
- package/dist/template-build.js +365 -0
- package/dist/template-bundle.d.ts +102 -0
- package/dist/template-bundle.js +344 -0
- package/dist/template-runtime.d.ts +145 -0
- package/dist/template-runtime.js +723 -0
- package/dist/template-shared.d.ts +99 -0
- package/dist/template-shared.js +231 -0
- package/dist/template.d.ts +3 -0
- package/dist/template.js +5 -0
- package/dist/vite-plugin.d.ts +20 -2
- package/dist/vite-plugin.js +27 -0
- package/dist/vue-typescript.d.ts +9 -0
- package/dist/vue-typescript.js +68 -0
- package/options.schema.json +79 -1
- package/package.json +6 -2
- package/templates/shared.ts +4 -0
package/AI.md
CHANGED
|
@@ -31,12 +31,18 @@ npm run build # dist/ (browser) + dist/ssr
|
|
|
31
31
|
| `devHosts` | string[] | `[]` | development only (`DOKEBI_VITE_DEV=1`): host names, besides loopback names, IP addresses and @dokebi/app domains (with a domain provider, the domains of the moment, D-0252), that may load the Vite dev routes, for example a tunnel host. `.example.com` also allows its subdomains. At most 256 names; no `*`, no port ([D-0107](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0107-stream-and-render-bounds.md)) |
|
|
32
32
|
| `devDepsRepairIntervalMs` | integer 1000–3600000 | 10000 | development only (`dokebi dev`): the Vite dev host re-optimizes the pre-bundled dependencies (`node_modules/.vite/deps`) when they changed on disk under it, at most once per this many ms; a cache that keeps changing faster is reported (`INERTIA_VITE_DEPS_CHANGING`). Read by the host when `dokebi dev` starts (§5.1, [D-0128](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0128-vite-deps-cache-repair.md)) |
|
|
33
33
|
| `encryptHistory` | `true` · `false` · `'sealed'` | `'sealed'` | Inertia history encryption; `'sealed'` turns it on for sealed requests (D-0062) |
|
|
34
|
-
| `routeIds: { assets?, viteDev? }` | strings | `template-inertia.assets`, `template-inertia.viteDev` | the route ids of the routes this plugin adds ([D-0142](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0142-plugin-route-ids.md)): `assets` every built file of `vite.manifest` (one route per file, one id), `viteDev` the `<base>*` routes of the Vite dev server (development only). `request.routeOptions.config.id` and `dokebi describe` `routes[].id` show them (describe serves no build, so it lists neither). An id taken by another route of the same app fails the start (`DUPLICATE_ROUTE_ID`) |
|
|
34
|
+
| `routeIds: { assets?, viteDev?, templateFiles? }` | strings | `template-inertia.assets`, `template-inertia.viteDev`, `template-inertia.templateFiles` | the route ids of the routes this plugin adds ([D-0142](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0142-plugin-route-ids.md)): `assets` every built file of `vite.manifest` (one route per file, one id), `viteDev` the `<base>*` routes of the Vite dev server (development only). `request.routeOptions.config.id` and `dokebi describe` `routes[].id` show them (describe serves no build, so it lists neither). An id taken by another route of the same app fails the start (`DUPLICATE_ROUTE_ID`) |
|
|
35
35
|
| `errorPage` | string | none | page component of error answers (for example `Error`), rendered for Inertia visits and page loads (§3.3). Unset: JSON for visits, web's small HTML page for page loads |
|
|
36
36
|
| `bootFallback` | `{ enabled?, timeoutMs?, messages?, stylesheet?, logo? }` | `{ enabled: true, timeoutMs: 10000 }` | The root of the first HTML while the app loads (§3.4): a centered spinner, then "could not load" with a reload button. `enabled: false` leaves the root empty; `timeoutMs` 1000–120000; `messages` by language tag `{ loading?, failed?, reload? }` over the built-in Korean and English texts; `stylesheet` a local URL with the app's own look of the box; `logo` a local image above the spinner |
|
|
37
37
|
| `viteManifestMaxBytes` | integer 1024–67108864 | 4194304 | the largest Vite build manifest read at start; larger stops the start with `VITE_MANIFEST_INVALID`. Raise it for an app with thousands of chunks |
|
|
38
38
|
| `assetCacheMaxBytes` | integer 0–67108864 | 4194304 | built files up to this size are kept in memory after their first request; larger ones are streamed from disk every time (0: stream all). Memory is at most the sum of the served files at or below it |
|
|
39
39
|
| `logRepeatWindowMs` | integer 1000–3600000 | 10000 | window of the repeated per-request failure logs (`INERTIA_SSR_FAILED`, `INERTIA_PROP_RESCUED`, a failed shared-data or flash hook): the first is logged in full, the rest of the window are counted (`repeated`) |
|
|
40
|
+
| `templates` (reloadable) | `{ <app>: { <template>: { path } } }` | `{}` | (0.4.21, [D-0291](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0291-template-bundles-at-runtime.md)) the template bundles of each app (§4.3): `path` is the bundle folder (a read-only mount is fine). A key that is not an app stops the start and fails a reload (`TEMPLATE_APP_UNKNOWN`) |
|
|
41
|
+
| `templateCheckMs` (reloadable) | integer 0–3600000 | 5000 | how often each bundle folder's `dokebi-template.json` is looked at; a changed bundle is loaded beside the current one and replaces it for the next request. 0: only at start and reloads |
|
|
42
|
+
| `templateMaxBytes` (reloadable) | integer 1024–1073741824 | 52428800 | the largest bundle (its files) |
|
|
43
|
+
| `templateKeep` (reloadable) | integer 1–16 | 2 | generations of a template kept in the cache and served, so pages opened before a swap still load their files |
|
|
44
|
+
| `templateVerifyTimeoutMs` (reloadable) | integer 100–600000 | 10000 | how long the entry's `verifyTemplate` may take for one bundle; past it the bundle is refused |
|
|
45
|
+
| `templateCacheDir` | string | `.dokebi/cache/templates` | where the checked copies of the bundles go: a writable folder of the process (each worker of a cluster may share it) |
|
|
40
46
|
|
|
41
47
|
## 3. Rendering pages
|
|
42
48
|
|
|
@@ -247,6 +253,54 @@ A module keeps its Vue pages in its own views folder (@dokebi/module AI.md §4a)
|
|
|
247
253
|
- An app package without the sources (before @dokebi/app 0.4.9): no module pages, warn `INERTIA_MODULE_PAGES_UNSUPPORTED`. Failures are coded errors of the build: `MODULE_PAGES_APP_MISSING` (imported outside an app's views folder), `MODULE_PAGES_FAILED` (the app file cannot be imported, exports no definition, or a module folder cannot be read; the cause is kept).
|
|
248
254
|
- Debug logs: `Inertia module pages gathered` (app, page count per module, skipped sets, ms), `Inertia module pages changed; the browser reloads` (event, path), `Inertia dev file policy allows a module views folder`.
|
|
249
255
|
|
|
256
|
+
### 4.3 Template bundles (0.4.20, D-0291: the build side)
|
|
257
|
+
|
|
258
|
+
A template can live apart from the app: a `views/<template>/` folder (Layout.vue, `Pages/**`, its components and styles) built in another repository into a **bundle** that the app loads while it runs. 0.4.20 is the build side, 0.4.21 the loading side (below, "Using bundles"). Example: `examples/89-template-bundles`.
|
|
259
|
+
|
|
260
|
+
- **The app provides the shared modules.** In both vite configs of the app (`vite.config.ts` and `vite.ssr.config.ts`), give the same list:
|
|
261
|
+
```ts snippet
|
|
262
|
+
dokebiInertia({ templates: { shared: ['@shop/sdk', '@shop/sdk/components'] } })
|
|
263
|
+
```
|
|
264
|
+
Every `vite build` then adds one entry per shared module (`dokebi-shared/<module>`: every export of the module and its default) and writes `<outDir>/.vite/dokebi-shared.json` (`{ format: 1, ssr, base, modules: { <module>: { file, version } } }`). vue, vue/server-renderer (server build only), @inertiajs/vue3 and @dokebi/template-inertia/{i18n,pages} are always provided. Entries of one build share module instances, so a bundle page that imports `vue` or the SDK through them gets the app's own instance: one reactivity, one provide/inject, one `pageI18n`. Name the SDK as a package (a workspace package, or a package of the app), not a relative path: the bundle imports it by that name. Its `version` is read from `node_modules/<package>/package.json` (a workspace link counts); a module the build reaches through a `resolve.alias` takes the version of the nearest package.json of that name above the file it points to (0.4.21), else `null` (not compared). Without `templates` the build is as before.
|
|
265
|
+
- **The template repository builds the bundle:** `npx dokebi template build <dir> --shared @shop/sdk` (it needs `@dokebi/template-inertia`, `vite`, `@vitejs/plugin-vue`, `vue` and the SDK package installed; `--name` defaults to the folder name, `--version` to package.json). It runs a browser build and a server build with one entry per page, keeps every shared module an import, and writes `dist/template/<name>/`:
|
|
266
|
+
- `dokebi-template.json` (format 1): `name`, `version`, `builtWith`, `shared` (each shared module the pages import, with the version it was built with), `pages` (`Layout`, `Pages/<path>` → `browser`, `css`, `preload`, `ssr`, `meta`), `files` (every file's `bytes` and `sha256`).
|
|
267
|
+
- `browser/`, `ssr/`: the modules, chunks, stylesheets and assets (relative URLs, so the bundle can be served under any path).
|
|
268
|
+
- A page's contract goes in a plain `<script>` block beside `<script setup>`: `export const meta = { contract: 'checkout@2' }`. The build reads it from the server module and writes it into `pages.<page>.meta` (JSON data, at most 4 KiB). The framework never interprets it; the app's check will.
|
|
269
|
+
- The signature (`dokebi-template.sig`) is the template repository's next step: sign the manifest (its file hashes cover the rest).
|
|
270
|
+
- The same source builds the same bundle (`buildId` = the first 12 hex of the manifest's sha256).
|
|
271
|
+
- **`npx dokebi template check <dir>`** checks a bundle as the app will: the manifest's shape and format, every file's size and sha256, no file the manifest does not list, no link, the size limit; `--against <app>/dist/.vite/dokebi-shared.json` (repeatable: add `dist/ssr/.vite/dokebi-shared.json` for an app with server rendering) also checks that the app provides every shared module the bundle imports, in the same major version (0.x: minor). Without a server build `vue/server-renderer` is not asked for: only the bundle's server modules import it, and an app without server rendering never loads them.
|
|
272
|
+
- **`--config <vite config>`** merges a vite config of the template repository (aliases, more plugins); @vitejs/plugin-vue is added unless that config has its own `vue()`.
|
|
273
|
+
- **Props types from a package** (`defineProps<Props>()` with `import type { Props } from '@shop/sdk'`): the Vue compiler resolves them with TypeScript's JS API, which TypeScript 7 does not have (`ts2.findConfigFile is not a function`). `dokebiInertia()` (the app's builds and the `dokebi dev` Vite host) and `dokebi template build` register a TypeScript that has one with the compiler: the project's `typescript` when it is 6 or older, else **`@typescript/typescript6`** — `npm install --save-dev @typescript/typescript6` beside TypeScript 7 (debug `INERTIA_VUE_TYPESCRIPT` says which, or that none was found). Codes: `TEMPLATE_MANIFEST_MISSING`, `TEMPLATE_MANIFEST_INVALID`, `TEMPLATE_FORMAT_UNSUPPORTED`, `TEMPLATE_FILE_MISSING`, `TEMPLATE_FILE_CHANGED`, `TEMPLATE_FILE_EXTRA`, `TEMPLATE_FILE_LINK`, `TEMPLATE_TOO_LARGE`, `TEMPLATE_PAGE_FILE_UNKNOWN`, `TEMPLATE_SHARED_MISSING`, `TEMPLATE_SHARED_VERSION`. Run it in the template repository's CI after the build.
|
|
274
|
+
- The same API is `@dokebi/template-inertia/template`: `buildTemplateBundle(options)`, `checkTemplateBundle(dir, limits)`, `sharedProblems(bundle, provided)`.
|
|
275
|
+
|
|
276
|
+
**Using bundles (0.4.21).**
|
|
277
|
+
|
|
278
|
+
- **Name them:** `templates: { site: { luxe: { path: /tenant/templates/site-luxe } } }` under `dokebi-template-inertia` (reloadable). A host whose template (`domains.<host>.template` of @dokebi/app, a domain provider's row included) has a bundle gets its pages; @dokebi/app 0.4.19 takes such a template without a `views/<template>/` folder.
|
|
279
|
+
- **Lookup:** the bundle's page, then the app's `views/<template>`, `views/default`, then the module pages, as before. `views/app.js` and `views/ssr.js` hand the lookup to `templatePages({ files, modulePages, template })` of `@dokebi/template-inertia/pages`: `pages.page(name)` for Inertia's `resolve` (a Promise for a bundle page), `pages.layout()` for `layout`. `dokebi app add --inertia` writes them so; an existing app changes its two files the same way (a file that keeps its own `pick` serves no bundle page).
|
|
280
|
+
- **Loading:** at start (before the first request) and whenever the folder's `dokebi-template.json` changed (`templateCheckMs`) or the settings reload, the bundle is copied into `templateCacheDir/<app>/<template>/<buildId>/`, each file checked against the manifest's size and sha256 on the way. Then it is compared with what the app build provides (its `dist/.vite/dokebi-shared.json`, and `dist/ssr/.vite/dokebi-shared.json` with server rendering: every shared module the bundle imports, same major version). Then the entry's `verifyTemplate` judges it, and its server modules are imported. Only then is it the template's current generation: the next request uses it, a request under way keeps the one it started with. The mount may change or go away afterwards; the copy is what runs.
|
|
281
|
+
- **The app's judgement** (`src/infra/inertia/shared.ts` exports it beside `shared`):
|
|
282
|
+
```ts snippet
|
|
283
|
+
export async function verifyTemplate(bundle) {
|
|
284
|
+
// bundle: { app, template, path, buildId, manifest, signature (Buffer | undefined), read(file) }
|
|
285
|
+
if (!signatureMatches(await bundle.read('dokebi-template.json'), bundle.signature))
|
|
286
|
+
return { accept: false, reason: 'bad signature' };
|
|
287
|
+
const rejectPages = Object.entries(bundle.manifest.pages)
|
|
288
|
+
.filter(([, page]) => !supported(page.meta?.contract))
|
|
289
|
+
.map(([page]) => ({ page, reason: 'unknown contract' }));
|
|
290
|
+
return { accept: true, rejectPages };
|
|
291
|
+
}
|
|
292
|
+
```
|
|
293
|
+
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.
|
|
294
|
+
- **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: same origin (`'self'`), and the bundle's modules are imported by the app's own trusted script (`'strict-dynamic'`).
|
|
295
|
+
- **Asset version:** `<the app's version>+<template>@<buildId>`. A new bundle changes it, so an open page reloads at its next visit (409).
|
|
296
|
+
- **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.
|
|
297
|
+
- **Failures never stop the start:**
|
|
298
|
+
- a missing, unreadable, changed, too large or incompatible bundle, one `verifyTemplate` refused, or one that fails to import: the template keeps its previous generation, or the app's pages when there is none (error `INERTIA_TEMPLATE_UNAVAILABLE` / `INERTIA_TEMPLATE_REJECTED`, once per `logRepeatWindowMs` per cause).
|
|
299
|
+
- A bundle page whose server render throws or times out is set aside for this generation and the request renders again with the app's page (then the layout, if it still fails): error `INERTIA_TEMPLATE_PAGE_FAILED`. The next first HTMLs leave it out of the table, so the browser uses the app's page too; a new generation tries it again.
|
|
300
|
+
- In the browser, a bundle page that cannot load (network, syntax) falls back to the app's page with a console warning.
|
|
301
|
+
- **Logs:** info `INERTIA_TEMPLATE_LOADED` (app, template, name, version, buildId, previous, pages, rejectedPages, serverRendering, kept, ms), warn `INERTIA_TEMPLATE_PAGE_REJECTED`, info `INERTIA_TEMPLATE_REMOVED`, info `INERTIA_TEMPLATE_DEV_SKIPPED`.
|
|
302
|
+
- **Not under `dokebi dev`:** there the pages come from Vite, and bundles are not used (info `INERTIA_TEMPLATE_DEV_SKIPPED`); work on a template in the template repository.
|
|
303
|
+
|
|
250
304
|
## 5. SSR (D-0039)
|
|
251
305
|
|
|
252
306
|
- `ssr.bundle` is a build file that exports `render(page) → { head: string[]; body: string }`. In Inertia v3, calling `createInertiaApp({ resolve, layout })` on the server without a page returns a `(page, renderToString)` function (see the `views/ssr.js` that `--ssr` creates).
|
|
@@ -327,6 +381,10 @@ A module keeps its Vue pages in its own views folder (@dokebi/module AI.md §4a)
|
|
|
327
381
|
| `INVALID_URL` | `InertiaUsageError` | a redirect or asset that is not a local absolute URL; a location that is neither that nor an http(s) URL |
|
|
328
382
|
| `INVALID_PROP_HELPER` | `InertiaUsageError` | bad arguments to `defer`, `merge` or `once` |
|
|
329
383
|
| `SSR_INVALID_RESULT` | `InertiaUsageError` | the SSR `render` did not return `{ head, body }` or the body has no root element |
|
|
384
|
+
| `TEMPLATE_APP_UNKNOWN` | `InertiaError` | (D-0291) a key of `templates` is not an app of @dokebi/app (`data.apps`): stops the start, fails a reload (§4.3) |
|
|
385
|
+
| `TEMPLATE_BUILD_FAILED` | `InertiaError` | (`dokebi template build`, D-0291) the Vite build of a template failed, a page's server module could not be imported to read its `meta`, a `meta` is not JSON data or larger than 4 KiB, or the built bundle fails its own check; the original error is the `cause` (§4.3) |
|
|
386
|
+
| `INVALID_TEMPLATE_SHARED` | `InertiaUsageError` | (D-0291) `templates.shared` of `dokebiInertia()` or `--shared` names something that is not a package name with an optional subpath, more than 64, two names that make one entry, or a module that cannot be resolved or imported from the project (§4.3) |
|
|
387
|
+
| `INVALID_TEMPLATE_BUILD` | `InertiaUsageError` | (D-0291) `dokebi template build`: the folder is missing, outside the project or has no page, a page path is not a page name, the name or version is wrong, or `--out` is the project, the template folder, or a folder that holds files and no earlier bundle (§4.3) |
|
|
330
388
|
| `INVALID_PRUNE` | `InertiaUsageError` | `pruneBuildFiles` without a manifest path, or an `olderThanMs`, `maxManifestBytes` or `now` that is not a whole number from 0 |
|
|
331
389
|
|
|
332
390
|
## 7. Cautions
|
package/README.md
CHANGED
|
@@ -92,6 +92,10 @@ With `DOKEBI_VITE_DEV=1` (set by `dokebi dev`) the project's Vite starts in midd
|
|
|
92
92
|
|
|
93
93
|
The dev server serves only what the browser loads (D-0129): the views folders of the apps, the folders of the browser entries, `node_modules` and the files those modules import. `dokebi.yaml`, `.env`, `.dokebi/`, keys, compose files and the server code (`src/` outside `views/`, `tests/`, `scripts/`) answer 403 by every spelling (`?raw`, `/@fs/`, encoded, other letter cases, symlinks), and a remote host such as a `devHosts` tunnel gets a short 403 without paths. `dokebiInertia()` enforces this and the Vite host of `dokebi dev` adds it to a config without the plugin; the app may add to `server.fs.allow` and `deny` (or `dokebiInertia({ allow, deny })`) but never remove the framework's entries. Details: AI.md §5.2.
|
|
94
94
|
|
|
95
|
+
## Template bundles (0.4.20, [D-0291](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0291-template-bundles-at-runtime.md), build side)
|
|
96
|
+
|
|
97
|
+
A `views/<template>/` folder can be built in another repository into a bundle an app loads while it runs. `dokebiInertia({ templates: { shared: ['@shop/sdk'] } })` makes the app's builds provide the shared modules (vue, @inertiajs/vue3, the SDK) and list them in `dist/.vite/dokebi-shared.json`; `npx dokebi template build <dir> --shared @shop/sdk` builds the bundle (`dokebi-template.json`, `browser/`, `ssr/`, page `meta`, file hashes) and `npx dokebi template check <dir>` checks it. Since 0.4.21 the app uses them while it runs: `templates.<app>.<template>.path` names a bundle (reloadable); it is copied and checked, judged by the entry's `verifyTemplate` (required in production) and replaces the template's pages for the next request, rendered on the server with the app's own vue and SDK; `templatePages()` of `@dokebi/template-inertia/pages` is the lookup of `views/app.js` and `views/ssr.js`. Details in AI.md §4.3; example 89-template-bundles.
|
|
98
|
+
|
|
95
99
|
## Public pages (0.4.6, D-0195)
|
|
96
100
|
|
|
97
101
|
`render(request, reply, component, props, { public: true, head })` marks a page whose first HTML is the same for every visitor: it carries the render's props and the public shared props (view data a plugin calls public, such as @dokebi/i18n's, and `publicShared` of the entry and the scope), while the visitor's own (`auth`, `csrf`, the entry's `shared`) are named in the deferred group `dokebi-visitor` and fetched by the client right after it starts. On a seal host that HTML is plain and server rendered (with `<meta name="dokebi-seal" content="host">`, which tells `sealInertia` to seal everything after it), so crawlers read the page. `public: { cacheControl }` lets a shared cache keep it (an answer that sets a cookie stays `no-store`). `head` writes escaped title, description, canonical, robots, `hreflang` alternates and meta tags into the first HTML of any page, sealed ones included. Details: AI.md §3.5; example `examples/80-sealed-public-ssr`.
|
package/dist/errors.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { DokebiError, type DokebiErrorOptions } from '@dokebi/core';
|
|
2
2
|
/** Codes of `InertiaError` (failures of setup, files and the page flow). */
|
|
3
|
-
export type InertiaErrorCode = 'SSR_BUNDLE_MISSING' | 'SSR_BUNDLE_INVALID' | 'SSR_ENTRY_MISSING' | 'SSR_TIMEOUT' | 'VITE_MANIFEST_MISSING' | 'VITE_MANIFEST_INVALID' | 'VITE_DEV_MISSING' | 'VITE_DEV_UNAVAILABLE' | 'METHOD_NOT_ALLOWED' | 'CLOSED' | 'MODULE_PAGES_APP_MISSING' | 'MODULE_PAGES_FAILED';
|
|
3
|
+
export type InertiaErrorCode = 'SSR_BUNDLE_MISSING' | 'SSR_BUNDLE_INVALID' | 'SSR_ENTRY_MISSING' | 'SSR_TIMEOUT' | 'VITE_MANIFEST_MISSING' | 'VITE_MANIFEST_INVALID' | 'VITE_DEV_MISSING' | 'VITE_DEV_UNAVAILABLE' | 'METHOD_NOT_ALLOWED' | 'CLOSED' | 'MODULE_PAGES_APP_MISSING' | 'MODULE_PAGES_FAILED' | 'TEMPLATE_BUILD_FAILED' | 'TEMPLATE_APP_UNKNOWN';
|
|
4
4
|
/** Codes of `InertiaUsageError` (a wrong argument: a TypeError, as before 0.4.0). */
|
|
5
|
-
export type InertiaUsageErrorCode = 'INVALID_ENTRY' | 'INVALID_SCOPE' | 'INVALID_RENDER' | 'INVALID_PROPS' | 'INVALID_URL' | 'INVALID_PROP_HELPER' | 'SSR_INVALID_RESULT' | 'INVALID_PRUNE';
|
|
5
|
+
export type InertiaUsageErrorCode = 'INVALID_ENTRY' | 'INVALID_SCOPE' | 'INVALID_RENDER' | 'INVALID_PROPS' | 'INVALID_URL' | 'INVALID_PROP_HELPER' | 'SSR_INVALID_RESULT' | 'INVALID_PRUNE' | 'INVALID_TEMPLATE_SHARED' | 'INVALID_TEMPLATE_BUILD';
|
|
6
6
|
/** Failures of @dokebi/template-inertia; compare `code`, not the class. */
|
|
7
7
|
export declare class InertiaError extends DokebiError<InertiaErrorCode> {
|
|
8
8
|
constructor(code: InertiaErrorCode, message: string, options?: DokebiErrorOptions);
|
package/dist/errors.js
CHANGED
|
@@ -13,7 +13,9 @@ const FIX = {
|
|
|
13
13
|
CLOSED: 'Render only while the application runs.',
|
|
14
14
|
MODULE_PAGES_APP_MISSING: "Import 'virtual:dokebi/module-pages' only from an app's views/app.js or views/ssr.js: the app folder beside views/ must hold app.ts (defineApp), whose modules it reads.",
|
|
15
15
|
MODULE_PAGES_FAILED: "Fix the app file or the module folder the cause names: the Inertia build imports the app's app.ts (defineApp) and reads the views folders of the modules it mounts.",
|
|
16
|
-
|
|
16
|
+
TEMPLATE_BUILD_FAILED: 'Fix what the cause names (a page that does not compile, a module that is neither installed nor shared, a meta export that is not JSON data), then run npx dokebi template build again (D-0291).',
|
|
17
|
+
TEMPLATE_APP_UNKNOWN: 'Key dokebi-template-inertia templates by the apps dokebi-app defines (details.apps names the others; the folders of src/apps/<app>), or remove the key (D-0291).',
|
|
18
|
+
INVALID_ENTRY: 'The Inertia entry (src/infra/inertia/shared.ts) exports only shared: (request) => props, publicShared: (request) => props and verifyTemplate: (bundle) => verdict (D-0291).',
|
|
17
19
|
INVALID_SCOPE: 'Give scope() document settings (title, rootId, version, scripts, styles or vite, ssr, encryptHistory), shared and publicShared as functions and sealed as a boolean; vite replaces version, scripts and styles.',
|
|
18
20
|
INVALID_RENDER: 'render(request, reply, component, props?, { encryptHistory?, clearHistory?, public?, head? }): component is names of letters, digits, _ or - joined by /; public is true or { cacheControl }; head holds title, description, canonical, robots, alternates and meta as documented (AI.md §3.5).',
|
|
19
21
|
INVALID_PROPS: 'Page props must be JSON values: no undefined, functions, symbols, NaN or Infinity (use null, or leave the prop out).',
|
|
@@ -21,6 +23,8 @@ const FIX = {
|
|
|
21
23
|
INVALID_PROP_HELPER: 'defer(fn, { group? }), merge(value, { deep?, matchOn? }), once(value, { key? }): a JSON value or a function, with the documented options.',
|
|
22
24
|
SSR_INVALID_RESULT: 'The SSR render(page) must return { head: string[], body: string } whose body has the root element (rootId).',
|
|
23
25
|
INVALID_PRUNE: "pruneBuildFiles({ manifest: 'dist/.vite/manifest.json', olderThanMs?, dryRun?, maxManifestBytes?, now? }): a manifest path, and whole non-negative numbers.",
|
|
26
|
+
INVALID_TEMPLATE_SHARED: "Give dokebiInertia({ templates: { shared } }) (and dokebi template build --shared) installed package names with an optional subpath, at most 64, such as ['@shop/sdk', '@shop/sdk/components'] (D-0291).",
|
|
27
|
+
INVALID_TEMPLATE_BUILD: 'dokebi template build <dir>: a folder with Layout.vue and/or Pages/**/*.vue inside the project, a template name (^[a-z][a-z0-9-]{0,31}$), a version (letters, digits, . + -) and an --out folder that is neither the project nor the template folder (D-0291).',
|
|
24
28
|
};
|
|
25
29
|
/** Failures of @dokebi/template-inertia; compare `code`, not the class. */
|
|
26
30
|
export class InertiaError extends DokebiError {
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { type Awaitable } from '@dokebi/core';
|
|
2
2
|
import type { FastifyRequest } from 'fastify';
|
|
3
3
|
import { type InertiaApi, type Props } from './responder.js';
|
|
4
|
+
import { type VerifyTemplate } from './template-runtime.js';
|
|
4
5
|
export type { InertiaBootFallback, InertiaBootMessages } from './boot-fallback.js';
|
|
5
6
|
export { InertiaError, type InertiaErrorCode, InertiaUsageError, type InertiaUsageErrorCode, } from './errors.js';
|
|
6
7
|
export type { InertiaHead, InertiaHeadAlternate, InertiaHeadMeta, } from './head.js';
|
|
@@ -16,6 +17,12 @@ export interface InertiaEntry {
|
|
|
16
17
|
* its name): they go into the first HTML of public pages too.
|
|
17
18
|
*/
|
|
18
19
|
readonly publicShared?: InertiaShared;
|
|
20
|
+
/**
|
|
21
|
+
* D-0291: judges a template bundle before the app uses it (its signature, the pages'
|
|
22
|
+
* `meta.contract`): `{ accept: true, rejectPages? }` or `{ accept: false, reason }`. In
|
|
23
|
+
* production a bundle is not used without it.
|
|
24
|
+
*/
|
|
25
|
+
readonly verifyTemplate?: VerifyTemplate;
|
|
19
26
|
}
|
|
20
27
|
/**
|
|
21
28
|
* Server rendering of the first HTML of a page (D-0039), in this process: the SSR build output is
|
|
@@ -90,6 +97,11 @@ export interface InertiaViewEngine {
|
|
|
90
97
|
/** D-0195: `scope` takes `publicShared` and `render` takes `public` (dokebi-app checks it). */
|
|
91
98
|
readonly publicPages: true;
|
|
92
99
|
scope(input: InertiaScopeOptions): Promise<InertiaApi>;
|
|
100
|
+
/**
|
|
101
|
+
* D-0291: the templates of `app` that template bundles provide (`templates.<app>`, as the
|
|
102
|
+
* last reload left them): dokebi-app takes them as templates without a views/<template>/ folder.
|
|
103
|
+
*/
|
|
104
|
+
bundleTemplates(app: string): readonly string[];
|
|
93
105
|
}
|
|
94
106
|
export interface InertiaPluginApi extends InertiaApi {
|
|
95
107
|
/**
|
|
@@ -112,4 +124,11 @@ export interface InertiaViteOptions {
|
|
|
112
124
|
/** URL prefix the built files are served under. Default `/`. */
|
|
113
125
|
readonly base: string;
|
|
114
126
|
}
|
|
127
|
+
/**
|
|
128
|
+
* dokebi-web 0.4.3 or later: the validation redirect uses its form helpers (`formBackTarget`,
|
|
129
|
+
* `formOldInput`, D-0074 addendum 1), shared with @dokebi/app; 0.4.2 never answers a Referer
|
|
130
|
+
* path that reads as another host (ISSUE-0006 A02); 0.4.3 has the view data point (D-0076 §5). A local descriptor instead of
|
|
131
|
+
* '@dokebi/web/dependency' (whose range stays ^0.4.0 for the plugins that need nothing newer).
|
|
132
|
+
*/
|
|
133
|
+
export type { TemplateVerifyInput, TemplateVerifyResult, VerifyTemplate, } from './template-runtime.js';
|
|
115
134
|
export declare const createPlugin: import("@dokebi/core").PluginFactory<InertiaPluginApi>;
|
package/dist/index.js
CHANGED
|
@@ -14,6 +14,7 @@ import { builtFolderFile, HASHED } from './built-files.js';
|
|
|
14
14
|
import { InertiaError, InertiaUsageError } from './errors.js';
|
|
15
15
|
import { options } from './options.js';
|
|
16
16
|
import { cacheableReplies, InertiaResponder, normalizeInertiaOptions, vary, } from './responder.js';
|
|
17
|
+
import { TEMPLATE_FILES_PREFIX, TemplateBundles, } from './template-runtime.js';
|
|
17
18
|
import { isViteUpgrade, openViteDev, viteDevRequested } from './vite-dev.js';
|
|
18
19
|
import { DEV_CLIENT_HEADER, isLoopbackHost, isRemoteRequest } from './vite-files.js';
|
|
19
20
|
export { InertiaError, InertiaUsageError, } from './errors.js';
|
|
@@ -288,12 +289,6 @@ function hasCookie(header, name) {
|
|
|
288
289
|
return false;
|
|
289
290
|
return text.split(';').some((part) => part.slice(0, part.indexOf('=')).trim() === name);
|
|
290
291
|
}
|
|
291
|
-
/**
|
|
292
|
-
* dokebi-web 0.4.3 or later: the validation redirect uses its form helpers (`formBackTarget`,
|
|
293
|
-
* `formOldInput`, D-0074 addendum 1), shared with @dokebi/app; 0.4.2 never answers a Referer
|
|
294
|
-
* path that reads as another host (ISSUE-0006 A02); 0.4.3 has the view data point (D-0076 §5). A local descriptor instead of
|
|
295
|
-
* '@dokebi/web/dependency' (whose range stays ^0.4.0 for the plugins that need nothing newer).
|
|
296
|
-
*/
|
|
297
292
|
const web = providerDependency({
|
|
298
293
|
name: 'dokebi-web',
|
|
299
294
|
version: '^0.4.19',
|
|
@@ -311,15 +306,34 @@ function bootLog(options) {
|
|
|
311
306
|
? { timeoutMs: boot.timeoutMs, cspHashes: bootHashes(options.rootId, boot.timeoutMs) }
|
|
312
307
|
: false;
|
|
313
308
|
}
|
|
309
|
+
/** D-0291: the template part of the parsed options. */
|
|
310
|
+
function templateSettings(parsed) {
|
|
311
|
+
return Object.freeze({
|
|
312
|
+
templates: parsed.templates ?? {},
|
|
313
|
+
checkMs: parsed.templateCheckMs ?? 5000,
|
|
314
|
+
maxBytes: parsed.templateMaxBytes ?? 52_428_800,
|
|
315
|
+
keep: parsed.templateKeep ?? 2,
|
|
316
|
+
verifyTimeoutMs: parsed.templateVerifyTimeoutMs ?? 10_000,
|
|
317
|
+
cacheDir: parsed.templateCacheDir ?? '.dokebi/cache/templates',
|
|
318
|
+
});
|
|
319
|
+
}
|
|
314
320
|
/** Settings of the parsed options (the declaration checked them, D-0063 §3). */
|
|
315
321
|
function settings(parsed) {
|
|
316
322
|
const { vite, ssr, devHosts = [], viteManifestMaxBytes = 4_194_304, assetCacheMaxBytes = 4_194_304, logRepeatWindowMs = 10_000,
|
|
317
323
|
// Read by the Vite dev host of dokebi dev (vite-host.ts, D-0128), not by the app.
|
|
318
|
-
devDepsRepairIntervalMs: _devDepsRepairIntervalMs, routeIds, ...rest } = parsed;
|
|
324
|
+
devDepsRepairIntervalMs: _devDepsRepairIntervalMs, routeIds, templates, templateCheckMs, templateMaxBytes, templateKeep, templateVerifyTimeoutMs, templateCacheDir, ...rest } = parsed;
|
|
319
325
|
const document = normalizeInertiaOptions(rest);
|
|
320
326
|
return Object.freeze({
|
|
321
327
|
document,
|
|
322
|
-
routeIds: pluginRouteIds('dokebi-template-inertia', ['assets', 'viteDev'], routeIds),
|
|
328
|
+
routeIds: pluginRouteIds('dokebi-template-inertia', ['assets', 'viteDev', 'templateFiles'], routeIds),
|
|
329
|
+
templates: templateSettings({
|
|
330
|
+
templates,
|
|
331
|
+
templateCheckMs,
|
|
332
|
+
templateMaxBytes,
|
|
333
|
+
templateKeep,
|
|
334
|
+
templateVerifyTimeoutMs,
|
|
335
|
+
templateCacheDir,
|
|
336
|
+
}),
|
|
323
337
|
limits: Object.freeze({ viteManifestMaxBytes, assetCacheMaxBytes, logRepeatWindowMs }),
|
|
324
338
|
defaultVersion: vite === undefined && rest.version === undefined,
|
|
325
339
|
devHosts: Object.freeze([...devHosts]),
|
|
@@ -352,7 +366,9 @@ function parseEntry(input) {
|
|
|
352
366
|
if (typeof key !== 'string')
|
|
353
367
|
continue;
|
|
354
368
|
const descriptor = Object.getOwnPropertyDescriptor(input, key);
|
|
355
|
-
if ((key !== 'shared' && key !== 'publicShared'
|
|
369
|
+
if ((key !== 'shared' && key !== 'publicShared' && key !== 'verifyTemplate') ||
|
|
370
|
+
!descriptor ||
|
|
371
|
+
!('value' in descriptor))
|
|
356
372
|
throw new InertiaUsageError('INVALID_ENTRY', 'Invalid Inertia entry');
|
|
357
373
|
if (descriptor.value !== undefined && typeof descriptor.value !== 'function')
|
|
358
374
|
throw new InertiaUsageError('INVALID_ENTRY', `Inertia ${key} must be a function`);
|
|
@@ -368,6 +384,10 @@ class InertiaRuntime {
|
|
|
368
384
|
#devServer;
|
|
369
385
|
/** D-0288: set when the app drains; an HMR upgrade after it is not joined (503). */
|
|
370
386
|
#dev = { draining: false };
|
|
387
|
+
/** D-0291: the template bundles of a serving process (not under dokebi dev or describe). */
|
|
388
|
+
#templates;
|
|
389
|
+
/** D-0291: the template settings in use (the last reload's). */
|
|
390
|
+
#templateSettings;
|
|
371
391
|
constructor(settings, entry) {
|
|
372
392
|
this.settings = settings;
|
|
373
393
|
this.entry = entry;
|
|
@@ -403,6 +423,39 @@ class InertiaRuntime {
|
|
|
403
423
|
sockets,
|
|
404
424
|
});
|
|
405
425
|
}
|
|
426
|
+
/**
|
|
427
|
+
* D-0291: the configured bundles are loaded before the first request (a failure is logged,
|
|
428
|
+
* never thrown, but a `templates` key that is not an app stops the start).
|
|
429
|
+
*/
|
|
430
|
+
async start() {
|
|
431
|
+
const templates = this.#templates;
|
|
432
|
+
if (!templates)
|
|
433
|
+
return;
|
|
434
|
+
this.#checkTemplateApps(this.settings.templates, templates.server);
|
|
435
|
+
await templates.bundles.start();
|
|
436
|
+
}
|
|
437
|
+
/** D-0291: the template options are reloadable; anything else needs a restart. */
|
|
438
|
+
reload(input) {
|
|
439
|
+
const next = templateSettings(input.options);
|
|
440
|
+
const templates = this.#templates;
|
|
441
|
+
if (templates)
|
|
442
|
+
this.#checkTemplateApps(next, templates.server);
|
|
443
|
+
return {
|
|
444
|
+
apply: () => {
|
|
445
|
+
this.#templateSettings = next;
|
|
446
|
+
templates?.bundles.update(next);
|
|
447
|
+
input.context.logger.log('debug', 'Inertia template bundle settings reloaded', {
|
|
448
|
+
apps: Object.keys(next.templates),
|
|
449
|
+
checkMs: next.checkMs,
|
|
450
|
+
});
|
|
451
|
+
},
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
#checkTemplateApps(next, server) {
|
|
455
|
+
const unknown = TemplateBundles.unknownApps(next, server.apps?.names);
|
|
456
|
+
if (unknown.length)
|
|
457
|
+
throw new InertiaError('TEMPLATE_APP_UNKNOWN', `templates names ${unknown.join(', ')}, which ${unknown.length === 1 ? 'is' : 'are'} not an app (apps: ${server.apps?.names.join(', ') || 'none'})`, { data: { apps: unknown } });
|
|
458
|
+
}
|
|
406
459
|
async setup(context) {
|
|
407
460
|
const server = context.getDependency(web);
|
|
408
461
|
const logger = context.logger;
|
|
@@ -805,6 +858,35 @@ class InertiaRuntime {
|
|
|
805
858
|
const loaded = new Set();
|
|
806
859
|
// D-0077 B: `dokebi describe` never serves a page: the build is not needed (or read).
|
|
807
860
|
const describing = context.runtime.describing === true;
|
|
861
|
+
// D-0291: template bundles, for a process that serves built pages (not under dokebi dev:
|
|
862
|
+
// there the pages come from Vite, and template work has its own preview).
|
|
863
|
+
const templateApps = Object.keys(this.settings.templates.templates);
|
|
864
|
+
let templateRuntime;
|
|
865
|
+
if (serving && !describing && !develop) {
|
|
866
|
+
const loaded = new TemplateBundles({
|
|
867
|
+
logger,
|
|
868
|
+
settings: this.settings.templates,
|
|
869
|
+
verify: this.entry.verifyTemplate,
|
|
870
|
+
repeat: (key) => repeats.take(key),
|
|
871
|
+
});
|
|
872
|
+
templateRuntime = loaded;
|
|
873
|
+
this.#templates = { bundles: loaded, server };
|
|
874
|
+
context.defer(() => loaded.stop());
|
|
875
|
+
server.route({
|
|
876
|
+
method: 'GET',
|
|
877
|
+
url: `${TEMPLATE_FILES_PREFIX}*`,
|
|
878
|
+
config: publicAsset(routeIds, 'templateFiles'),
|
|
879
|
+
handler: (request, reply) => loaded.serve(request.params['*'], reply),
|
|
880
|
+
});
|
|
881
|
+
}
|
|
882
|
+
else if (develop && templateApps.length)
|
|
883
|
+
logger.log('info', 'Template bundles are not used under dokebi dev; the app pages answer', {
|
|
884
|
+
code: 'INERTIA_TEMPLATE_DEV_SKIPPED',
|
|
885
|
+
apps: templateApps,
|
|
886
|
+
});
|
|
887
|
+
const templateOf = (request) => typeof server.templateOf === 'function'
|
|
888
|
+
? server.templateOf(request)
|
|
889
|
+
: undefined;
|
|
808
890
|
const built = async (options) => {
|
|
809
891
|
if (describing)
|
|
810
892
|
return { scripts: [], styles: [], version: 'describe' };
|
|
@@ -1069,7 +1151,20 @@ class InertiaRuntime {
|
|
|
1069
1151
|
});
|
|
1070
1152
|
const merged = sharedSource(extraPublic, extra);
|
|
1071
1153
|
const scopedVite = vite === undefined ? this.settings.vite : parseVite(vite);
|
|
1072
|
-
|
|
1154
|
+
// D-0291: an app built with Vite can take template bundles.
|
|
1155
|
+
if (templateRuntime && appName !== undefined && scopedVite)
|
|
1156
|
+
templateRuntime.registerApp(appName, {
|
|
1157
|
+
base: scopedVite.base,
|
|
1158
|
+
manifest: scopedVite.manifest,
|
|
1159
|
+
...(ssr ? { ssrBundle: ssr.bundle } : {}),
|
|
1160
|
+
});
|
|
1161
|
+
const templateBundles = templateRuntime;
|
|
1162
|
+
const responder = new InertiaResponder(scoped, merged, await serverRendering(ssr, scopedVite), diagnostics, flash, templateBundles && appName !== undefined && scopedVite
|
|
1163
|
+
? Object.freeze({
|
|
1164
|
+
...hooks,
|
|
1165
|
+
template: (request, version) => templateBundles.use(appName, templateOf(request), version),
|
|
1166
|
+
})
|
|
1167
|
+
: hooks);
|
|
1073
1168
|
// Once the scope is valid: a scope refused above serves no page with the default version.
|
|
1074
1169
|
if (this.settings.defaultVersion && vite === undefined && fields.version === undefined)
|
|
1075
1170
|
logger.log('warn', 'Inertia asset version is not configured', {
|
|
@@ -1101,13 +1196,14 @@ class InertiaRuntime {
|
|
|
1101
1196
|
name: 'inertia',
|
|
1102
1197
|
publicPages: true,
|
|
1103
1198
|
scope: (input) => plugin.scope(input),
|
|
1199
|
+
bundleTemplates: (app) => Object.keys((this.#templateSettings ?? this.settings.templates).templates[app] ?? {}),
|
|
1104
1200
|
}));
|
|
1105
1201
|
return plugin;
|
|
1106
1202
|
}
|
|
1107
1203
|
}
|
|
1108
1204
|
export const createPlugin = definePlugin({
|
|
1109
1205
|
name: 'dokebi-template-inertia',
|
|
1110
|
-
version: '0.4.
|
|
1206
|
+
version: '0.4.21',
|
|
1111
1207
|
core: '^0.4.2',
|
|
1112
1208
|
options,
|
|
1113
1209
|
entry: parseEntry,
|
package/dist/options.d.ts
CHANGED
|
@@ -27,6 +27,7 @@ export declare const options: import("@dokebi/core").OptionsDeclaration<{
|
|
|
27
27
|
readonly rootId?: string;
|
|
28
28
|
readonly routeIds?: {
|
|
29
29
|
readonly assets?: string;
|
|
30
|
+
readonly templateFiles?: string;
|
|
30
31
|
readonly viteDev?: string;
|
|
31
32
|
};
|
|
32
33
|
readonly scripts?: readonly string[];
|
|
@@ -37,6 +38,14 @@ export declare const options: import("@dokebi/core").OptionsDeclaration<{
|
|
|
37
38
|
readonly timeoutMs: number;
|
|
38
39
|
};
|
|
39
40
|
readonly styles?: readonly string[];
|
|
41
|
+
readonly templateCacheDir: string;
|
|
42
|
+
readonly templateCheckMs: number;
|
|
43
|
+
readonly templateKeep: number;
|
|
44
|
+
readonly templateMaxBytes: number;
|
|
45
|
+
readonly templateVerifyTimeoutMs: number;
|
|
46
|
+
readonly templates: Readonly<Record<string, Readonly<Record<string, {
|
|
47
|
+
readonly path: string;
|
|
48
|
+
}>>>>;
|
|
40
49
|
readonly title?: string;
|
|
41
50
|
readonly version?: string;
|
|
42
51
|
readonly vite?: {
|
package/dist/options.js
CHANGED
|
@@ -165,6 +165,59 @@ export const options = defineOptions({
|
|
|
165
165
|
routeIds: routeIdsOption('dokebi-template-inertia', {
|
|
166
166
|
assets: 'the GET routes of the built files of vite.manifest (one per file)',
|
|
167
167
|
viteDev: 'the GET <vite base>* routes of the Vite dev server (dokebi dev, one per base)',
|
|
168
|
+
templateFiles: 'D-0291: the GET /_dokebi/templates/* route of the browser files of template bundles',
|
|
169
|
+
}),
|
|
170
|
+
templates: o.record(o.record(o.object({
|
|
171
|
+
path: o.string({
|
|
172
|
+
minLength: 1,
|
|
173
|
+
maxLength: 4096,
|
|
174
|
+
required: true,
|
|
175
|
+
description: 'The bundle folder (dokebi-template.json, browser/, ssr/), absolute or relative to the working directory: a read-only mount is fine',
|
|
176
|
+
}),
|
|
177
|
+
}), {
|
|
178
|
+
keys: { pattern: '^[a-z][a-z0-9-]{0,31}$' },
|
|
179
|
+
maxProperties: 64,
|
|
180
|
+
description: 'Template name (dokebi-app domains.<host>.template) → its bundle',
|
|
181
|
+
}), {
|
|
182
|
+
reloadable: true,
|
|
183
|
+
default: {},
|
|
184
|
+
keys: { pattern: '^[a-z][a-z0-9-]{0,31}$' },
|
|
185
|
+
maxProperties: 64,
|
|
186
|
+
description: 'D-0291: template bundles built apart from the app (npx dokebi template build), per app and template. A host whose template has a bundle gets its pages (then the app views/<template>, views/default and module pages, as before); a missing, broken or refused bundle leaves the template to the app pages and never stops the start. Not used under dokebi dev (Vite).',
|
|
187
|
+
}),
|
|
188
|
+
templateCheckMs: o.integer({
|
|
189
|
+
minimum: 0,
|
|
190
|
+
maximum: 3_600_000,
|
|
191
|
+
default: 5000,
|
|
192
|
+
reloadable: true,
|
|
193
|
+
description: "D-0291: how often each bundle folder's dokebi-template.json is looked at; a changed bundle is loaded beside the current one and replaces it for the next request. 0: only at start and reloads",
|
|
194
|
+
}),
|
|
195
|
+
templateMaxBytes: o.integer({
|
|
196
|
+
minimum: 1024,
|
|
197
|
+
maximum: 1_073_741_824,
|
|
198
|
+
default: 52_428_800,
|
|
199
|
+
reloadable: true,
|
|
200
|
+
description: 'D-0291: the largest template bundle (its files), 50 MiB by default',
|
|
201
|
+
}),
|
|
202
|
+
templateKeep: o.integer({
|
|
203
|
+
minimum: 1,
|
|
204
|
+
maximum: 16,
|
|
205
|
+
default: 2,
|
|
206
|
+
reloadable: true,
|
|
207
|
+
description: 'D-0291: generations of a template kept in the cache and served (the current one and those before it), so pages opened before a swap still load their files',
|
|
208
|
+
}),
|
|
209
|
+
templateVerifyTimeoutMs: o.integer({
|
|
210
|
+
minimum: 100,
|
|
211
|
+
maximum: 600_000,
|
|
212
|
+
default: 10_000,
|
|
213
|
+
reloadable: true,
|
|
214
|
+
description: "D-0291: how long the entry's verifyTemplate may take for one bundle; past it the bundle is refused",
|
|
215
|
+
}),
|
|
216
|
+
templateCacheDir: o.string({
|
|
217
|
+
minLength: 1,
|
|
218
|
+
maxLength: 4096,
|
|
219
|
+
default: '.dokebi/cache/templates',
|
|
220
|
+
description: 'D-0291: where checked copies of the bundles go (relative to the working directory); a writable folder of the process',
|
|
168
221
|
}),
|
|
169
222
|
}, {
|
|
170
223
|
checks: [
|
package/dist/pages.d.ts
CHANGED
|
@@ -13,3 +13,36 @@ export interface ModulePages {
|
|
|
13
13
|
}
|
|
14
14
|
/** The lookup over the table the virtual module writes. */
|
|
15
15
|
export declare function modulePages(table: ModulePageTable): ModulePages;
|
|
16
|
+
/** Options of {@link templatePages}. */
|
|
17
|
+
export interface TemplatePagesOptions {
|
|
18
|
+
/** The app's own pages: `import.meta.glob('./*\/{Layout,Pages/**\/*}.vue', { eager: true })` of views/. */
|
|
19
|
+
readonly files: Readonly<Record<string, PageModule>>;
|
|
20
|
+
/** The module pages (`virtual:dokebi/module-pages`), when the app has any. */
|
|
21
|
+
readonly modulePages?: ModulePages;
|
|
22
|
+
/** The template of this page (`page.props.app.template`, from dokebi-app); default `default`. */
|
|
23
|
+
readonly template?: string;
|
|
24
|
+
/** For tests: the document (default `globalThis.document`). */
|
|
25
|
+
readonly document?: unknown;
|
|
26
|
+
/** For tests: how a bundle module is imported (default `import(url)`). */
|
|
27
|
+
readonly load?: (url: string) => Promise<PageModule>;
|
|
28
|
+
}
|
|
29
|
+
/** The pages of one page load (browser) or one render (server). */
|
|
30
|
+
export interface TemplatePages {
|
|
31
|
+
readonly template: string;
|
|
32
|
+
/** The build of the template bundle in use, or undefined (the app's own pages). */
|
|
33
|
+
readonly bundle: string | undefined;
|
|
34
|
+
/** For Inertia's `resolve`: the bundle's page, else the app's, else a module's. */
|
|
35
|
+
page(name: string): PageModule | Promise<PageModule>;
|
|
36
|
+
/** For Inertia's `layout`: the bundle's Layout, else the app's of the template, else `default`. */
|
|
37
|
+
layout(): unknown;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* D-0291: the page lookup of views/app.js and views/ssr.js with template bundles. Without a
|
|
41
|
+
* bundle for this page's template it is the lookup of before: views/<template>, views/default,
|
|
42
|
+
* then the module pages. With one (the first HTML names it; on the server, the render's
|
|
43
|
+
* generation), the bundle's pages and Layout come first. In the browser a bundle page loads its
|
|
44
|
+
* stylesheets, then its module; one that cannot load falls back to the app's page (a console
|
|
45
|
+
* warning). Call it once per page load (browser) or per render (server), before
|
|
46
|
+
* createInertiaApp.
|
|
47
|
+
*/
|
|
48
|
+
export declare function templatePages(options: TemplatePagesOptions): Promise<TemplatePages>;
|
package/dist/pages.js
CHANGED
|
@@ -25,3 +25,85 @@ export function modulePages(table) {
|
|
|
25
25
|
},
|
|
26
26
|
});
|
|
27
27
|
}
|
|
28
|
+
const REGISTRY = Symbol.for('dokebi.inertia.template-bundles.v1');
|
|
29
|
+
/**
|
|
30
|
+
* D-0291: the page lookup of views/app.js and views/ssr.js with template bundles. Without a
|
|
31
|
+
* bundle for this page's template it is the lookup of before: views/<template>, views/default,
|
|
32
|
+
* then the module pages. With one (the first HTML names it; on the server, the render's
|
|
33
|
+
* generation), the bundle's pages and Layout come first. In the browser a bundle page loads its
|
|
34
|
+
* stylesheets, then its module; one that cannot load falls back to the app's page (a console
|
|
35
|
+
* warning). Call it once per page load (browser) or per render (server), before
|
|
36
|
+
* createInertiaApp.
|
|
37
|
+
*/
|
|
38
|
+
export async function templatePages(options) {
|
|
39
|
+
const { files, modulePages: modules } = options;
|
|
40
|
+
const template = options.template ?? 'default';
|
|
41
|
+
const own = (path) => files[`./${template}/${path}.vue`] ?? files[`./default/${path}.vue`];
|
|
42
|
+
const appPage = (name) => {
|
|
43
|
+
const found = own(`Pages/${name}`) ?? modules?.page(template, name);
|
|
44
|
+
if (!found)
|
|
45
|
+
throw new Error(`Unknown page: ${name}`);
|
|
46
|
+
return found;
|
|
47
|
+
};
|
|
48
|
+
const doc = (options.document ?? globalThis.document);
|
|
49
|
+
if (doc === undefined) {
|
|
50
|
+
// Server rendering: the registry template-inertia keeps for this render.
|
|
51
|
+
const registry = globalThis[REGISTRY];
|
|
52
|
+
const bundle = registry?.current();
|
|
53
|
+
const usable = bundle !== undefined && bundle.template === template ? bundle : undefined;
|
|
54
|
+
const layout = usable?.page('Layout');
|
|
55
|
+
return {
|
|
56
|
+
template,
|
|
57
|
+
bundle: usable ? 'server' : undefined,
|
|
58
|
+
page: (name) => usable?.page(`Pages/${name}`) ?? appPage(name),
|
|
59
|
+
layout: () => (layout ?? own('Layout'))?.default,
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
let table;
|
|
63
|
+
try {
|
|
64
|
+
const text = doc.getElementById('dokebi-template')?.textContent;
|
|
65
|
+
if (text) {
|
|
66
|
+
const parsed = JSON.parse(text);
|
|
67
|
+
if (parsed?.template === template && parsed.pages && typeof parsed.pages === 'object')
|
|
68
|
+
table = parsed;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
catch (error) {
|
|
72
|
+
console.warn('dokebi: the template bundle table could not be read; the app pages answer', error);
|
|
73
|
+
}
|
|
74
|
+
const load = options.load ?? ((url) => import(/* @vite-ignore */ url));
|
|
75
|
+
const styles = (urls) => Promise.all(urls.map((href) => new Promise((done) => {
|
|
76
|
+
// The server wrote the first page's stylesheets; bundle URLs hold no quote or backslash.
|
|
77
|
+
const quoted = href.replace(/["\\]/g, '\\$&');
|
|
78
|
+
if (doc.querySelector(`link[rel="stylesheet"][href="${quoted}"]`))
|
|
79
|
+
return done();
|
|
80
|
+
const link = doc.createElement('link');
|
|
81
|
+
link.rel = 'stylesheet';
|
|
82
|
+
link.href = href;
|
|
83
|
+
link.onload = () => done();
|
|
84
|
+
link.onerror = () => done();
|
|
85
|
+
doc.head.appendChild(link);
|
|
86
|
+
})));
|
|
87
|
+
const fromBundle = async (key) => {
|
|
88
|
+
const entry = table?.pages[key];
|
|
89
|
+
if (!entry)
|
|
90
|
+
return undefined;
|
|
91
|
+
try {
|
|
92
|
+
await styles(entry.css);
|
|
93
|
+
return await load(entry.js);
|
|
94
|
+
}
|
|
95
|
+
catch (error) {
|
|
96
|
+
console.warn(`dokebi: the template bundle page ${key} could not be loaded; the app page answers`, error);
|
|
97
|
+
return undefined;
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
const layout = await fromBundle('Layout');
|
|
101
|
+
return {
|
|
102
|
+
template,
|
|
103
|
+
bundle: table?.buildId,
|
|
104
|
+
page: (name) => table?.pages[`Pages/${name}`]
|
|
105
|
+
? fromBundle(`Pages/${name}`).then((module) => module ?? appPage(name))
|
|
106
|
+
: appPage(name),
|
|
107
|
+
layout: () => (layout ?? own('Layout'))?.default,
|
|
108
|
+
};
|
|
109
|
+
}
|
package/dist/responder.d.ts
CHANGED
|
@@ -5,6 +5,7 @@ import type { FastifyReply, FastifyRequest } from 'fastify';
|
|
|
5
5
|
import { type InertiaBootFallback, type NormalizedBootFallback } from './boot-fallback.js';
|
|
6
6
|
import { type InertiaHead } from './head.js';
|
|
7
7
|
import { type InertiaProp } from './props.js';
|
|
8
|
+
import type { TemplateUse } from './template-runtime.js';
|
|
8
9
|
export type Json = null | boolean | number | string | readonly Json[] | {
|
|
9
10
|
readonly [key: string]: Json;
|
|
10
11
|
};
|
|
@@ -99,6 +100,11 @@ export interface InertiaHooks {
|
|
|
99
100
|
* the session and answers 303 back; false when the request has no session or no way back.
|
|
100
101
|
*/
|
|
101
102
|
readonly validation?: (request: FastifyRequest, reply: FastifyReply, errors: Readonly<Record<string, string>>) => Promise<boolean>;
|
|
103
|
+
/**
|
|
104
|
+
* D-0291: the template bundle of this request's template, or undefined: its asset version,
|
|
105
|
+
* the head markup of its first HTML and the server render under it.
|
|
106
|
+
*/
|
|
107
|
+
readonly template?: (request: FastifyRequest, version: string) => TemplateUse | undefined;
|
|
102
108
|
}
|
|
103
109
|
/** The page object Inertia hands to the client and to the SSR bundle. */
|
|
104
110
|
export interface InertiaPage {
|