@dokebi/template-inertia 0.4.18 → 0.4.20

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
@@ -247,6 +247,24 @@ A module keeps its Vue pages in its own views folder (@dokebi/module AI.md §4a)
247
247
  - 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
248
  - 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
249
 
250
+ ### 4.3 Template bundles (0.4.20, D-0291: the build side)
251
+
252
+ 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. The loading side (options `templates.<app>.<template>.path`, the import map, server rendering, swapping without downtime, `verifyTemplate`) comes in the next stage; until then a bundle is built and checked, not served.
253
+
254
+ - **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:
255
+ ```ts snippet
256
+ dokebiInertia({ templates: { shared: ['@shop/sdk', '@shop/sdk/components'] } })
257
+ ```
258
+ 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. Without `templates` the build is as before.
259
+ - **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>/`:
260
+ - `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`).
261
+ - `browser/`, `ssr/`: the modules, chunks, stylesheets and assets (relative URLs, so the bundle can be served under any path).
262
+ - 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.
263
+ - The signature (`dokebi-template.sig`) is the template repository's next step: sign the manifest (its file hashes cover the rest).
264
+ - The same source builds the same bundle (`buildId` = the first 12 hex of the manifest's sha256).
265
+ - **`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` also checks that the app provides every shared module the bundle imports, in the same major version (0.x: minor). 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.
266
+ - The same API is `@dokebi/template-inertia/template`: `buildTemplateBundle(options)`, `checkTemplateBundle(dir, limits)`, `sharedProblems(bundle, provided)`.
267
+
250
268
  ## 5. SSR (D-0039)
251
269
 
252
270
  - `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).
@@ -266,6 +284,7 @@ A module keeps its Vue pages in its own views folder (@dokebi/module AI.md §4a)
266
284
  - Vite's token check (protection against cross-site WebSocket hijacking) stays. Upgrades that are not Vite's subprotocols are cut. Closing the host closes its port and connections, and a host whose Vite fails to start closes its port.
267
285
  - **Late file events are no edits (D-0045 addendum 4, 0.4.3)**: on macOS, FSEvents also delivers events for writes made before the watch started (`dokebi init`, `dokebi add`, `npm install`, a checkout), minutes late when fseventsd is busy. The host records each module file's state (device, inode, size, modification time) when Vite first loads it in an environment (before Vite reads it) and the `vite.config.*` files before Vite starts, and drops a watcher `change`, `add` or `unlink` whose file state equals every recorded one, so such an event invalidates nothing, sends no reload or update (a reload was buffered for the first page that connected) and restarts nothing. Any other event goes on at once. Files Vite never loaded through its plugin pipeline are not filtered. A save that changes nothing but the modification time is still an edit.
268
286
  - **The drain ends the open HMR sockets (0.4.18, [D-0288](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0288-dev-kills-after-the-apps-stop-deadlines.md))**: the Vite host outlives a `dokebi dev` restart, so nothing else closes a socket the app joined to it; next to @dokebi/websocket each one is a hijacked request web's drain waits for, and an open page held every restart to the drain deadline (center dev: `Web drain started pending: 2` for one tab, then the process was killed). On drain they end (debug `INERTIA_VITE_HMR_ENDED` with the count) and an HMR upgrade after that is answered 503; the page's Vite client reconnects to the next app and reloads, as it did when the process ended.
287
+ - **The host compares with the disk on a timer too (0.4.19, [D-0289](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0289-vite-host-rescans-and-env-records.md))**: FSEvents delivers edits seconds late (measured: 2.8 s median, 6 s at worst on an idle Mac; far more under load), so the comparison below also runs every `DOKEBI_DEV_RESCAN_MS` (the variable `dokebi dev` uses for src/, default 2000, `0` off, 250–600000; `.env` works, dev passes it on): an open page gets its HMR update within that time without a page load (info `INERTIA_VITE_WATCH_MISSED` with `trigger: 'timer'` when it found something; an empty pass says nothing). The module page tables follow the disk the same way: the files the worker read for a table (the app file, the module list, the definitions) and the `.vue` listing of its folders are compared and a difference reloads the browser (info `INERTIA_MODULE_PAGES_MISSED`). The filter of unchanged files also records the env files Vite restarts for (`.env`, `.env.local`, `.env.<mode>`, `.env.<mode>.local`, and the config's dependencies): a late event for one written before the start no longer restarts Vite (a request then under way got 504).
269
288
  - **Edits the watcher missed are read anyway (D-0283, 0.4.17)**: FSEvents can report an edit a minute late, or not before the next page load (a `git pull` that restarted the app while the host kept serving the old `.vue`, and the page broke on its new locales). The same records serve a comparison: when an app process connects (`trigger` `client`), before a server render (`ssr`) and when a page loads `<base>@vite/client` (`page`), the host compares every file Vite read with its state on disk. A file that changed is invalidated in every module graph at once and handed to Vite as the watcher's `change` (`unlink` when it is gone), so plugins, HMR updates and reloads run as for the watcher's own event, and the request that follows gets the file as it is; the watcher's late event then changes nothing and is dropped. Each find is info `INERTIA_VITE_WATCH_MISSED` (`trigger`, `files`, `sample` of at most 5, `compared`, `ms`). Open pages still get their immediate HMR from the watcher; the comparison guarantees that a reloaded page or a restarted app gets the files on disk.
270
289
  - **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`).
271
290
  - SSR: the host runs `ssrLoadModule(<source entry>)` and `render(page)` per request. The app process asks on connections of its own (a render that waits never holds the connections module requests are forwarded on) and cuts the request at `ssr.timeoutMs`, so renders that never finish do not pile up on the host. The source entry is `ssr.entry` (for example `src/apps/admin/views/ssr.js`), otherwise `ssr.js` in the folder of `vite.entry`. When neither exists the start fails (`SSR_ENTRY_MISSING`).
@@ -326,6 +345,9 @@ A module keeps its Vue pages in its own views folder (@dokebi/module AI.md §4a)
326
345
  | `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 |
327
346
  | `INVALID_PROP_HELPER` | `InertiaUsageError` | bad arguments to `defer`, `merge` or `once` |
328
347
  | `SSR_INVALID_RESULT` | `InertiaUsageError` | the SSR `render` did not return `{ head, body }` or the body has no root element |
348
+ | `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) |
349
+ | `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) |
350
+ | `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) |
329
351
  | `INVALID_PRUNE` | `InertiaUsageError` | `pruneBuildFiles` without a manifest path, or an `olderThanMs`, `maxManifestBytes` or `now` that is not a whole number from 0 |
330
352
 
331
353
  ## 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. Loading bundles in the app is the next stage. Details in AI.md §4.3.
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`.
@@ -0,0 +1,12 @@
1
+ /** The variable `dokebi dev` reads for its own comparison of the watched paths (D-0264). */
2
+ export declare const RESCAN_VARIABLE = "DOKEBI_DEV_RESCAN_MS";
3
+ export declare const RESCAN_DEFAULT_MS = 2000;
4
+ /**
5
+ * The interval DOKEBI_DEV_RESCAN_MS asks for, as dokebi dev reads it: 0 turns the comparison off,
6
+ * a whole number of milliseconds from 250 to 600000 sets it, nothing is the default (2000).
7
+ * Anything else keeps the default and is answered as `problem` for the caller to log.
8
+ */
9
+ export declare function rescanInterval(value: string | undefined): {
10
+ ms: number;
11
+ problem?: string;
12
+ };
@@ -0,0 +1,28 @@
1
+ // D-0289: how often the Vite dev host compares what it read with the disk, besides its watcher.
2
+ // FSEvents can deliver an edit seconds late, or a minute late when fseventsd is busy (measured on
3
+ // a developer Mac, 2026-11-27: median 2.8 s, up to 6.2 s, on an idle machine), so HMR and the
4
+ // module page table waited for it. The host takes the same knob as `dokebi dev`'s own comparison
5
+ // of src/ (D-0264): DOKEBI_DEV_RESCAN_MS in the environment or .env (dokebi dev passes .env on).
6
+ /** The variable `dokebi dev` reads for its own comparison of the watched paths (D-0264). */
7
+ export const RESCAN_VARIABLE = 'DOKEBI_DEV_RESCAN_MS';
8
+ export const RESCAN_DEFAULT_MS = 2000;
9
+ const RESCAN_MIN_MS = 250;
10
+ const RESCAN_MAX_MS = 600_000;
11
+ /**
12
+ * The interval DOKEBI_DEV_RESCAN_MS asks for, as dokebi dev reads it: 0 turns the comparison off,
13
+ * a whole number of milliseconds from 250 to 600000 sets it, nothing is the default (2000).
14
+ * Anything else keeps the default and is answered as `problem` for the caller to log.
15
+ */
16
+ export function rescanInterval(value) {
17
+ if (value === undefined || value.trim() === '')
18
+ return { ms: RESCAN_DEFAULT_MS };
19
+ const ms = Number(value);
20
+ if (ms === 0)
21
+ return { ms: 0 };
22
+ if (Number.isSafeInteger(ms) && ms >= RESCAN_MIN_MS && ms <= RESCAN_MAX_MS)
23
+ return { ms };
24
+ return {
25
+ ms: RESCAN_DEFAULT_MS,
26
+ problem: `${RESCAN_VARIABLE}=${value.slice(0, 40)} is not 0 (off) or whole milliseconds from ${RESCAN_MIN_MS} to ${RESCAN_MAX_MS}; using ${RESCAN_DEFAULT_MS}`,
27
+ };
28
+ }
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';
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,6 +13,7 @@ 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
+ 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).',
16
17
  INVALID_ENTRY: 'The Inertia entry (src/infra/inertia/shared.ts) exports only shared: (request) => props and publicShared: (request) => props.',
17
18
  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
19
  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).',
@@ -21,6 +22,8 @@ const FIX = {
21
22
  INVALID_PROP_HELPER: 'defer(fn, { group? }), merge(value, { deep?, matchOn? }), once(value, { key? }): a JSON value or a function, with the documented options.',
22
23
  SSR_INVALID_RESULT: 'The SSR render(page) must return { head: string[], body: string } whose body has the root element (rootId).',
23
24
  INVALID_PRUNE: "pruneBuildFiles({ manifest: 'dist/.vite/manifest.json', olderThanMs?, dryRun?, maxManifestBytes?, now? }): a manifest path, and whole non-negative numbers.",
25
+ 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).",
26
+ 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
27
  };
25
28
  /** Failures of @dokebi/template-inertia; compare `code`, not the class. */
26
29
  export class InertiaError extends DokebiError {
package/dist/index.js CHANGED
@@ -1107,7 +1107,7 @@ class InertiaRuntime {
1107
1107
  }
1108
1108
  export const createPlugin = definePlugin({
1109
1109
  name: 'dokebi-template-inertia',
1110
- version: '0.4.18',
1110
+ version: '0.4.20',
1111
1111
  core: '^0.4.2',
1112
1112
  options,
1113
1113
  entry: parseEntry,
@@ -2,6 +2,7 @@
2
2
  export type ModulePagesAnswer = {
3
3
  readonly kind: 'sources';
4
4
  readonly sources: unknown;
5
+ readonly files?: readonly string[];
5
6
  } | {
6
7
  readonly kind: 'unsupported';
7
8
  } | {
@@ -3,9 +3,26 @@
3
3
  // writes, the modules' own definitions) are loaded as they are now; the Vite host lives for the
4
4
  // whole `dokebi dev` session, and its own cache would keep the modules of its first read (a module
5
5
  // added while it ran stayed out of the page table and its folder answered 403).
6
+ //
7
+ // D-0289: the worker also answers which project files it read (the app file, the module list, the
8
+ // definitions), so the dev server compares them with the disk besides its watcher.
9
+ import nodeModule from 'node:module';
10
+ import { fileURLToPath } from 'node:url';
6
11
  import { parentPort, workerData } from 'node:worker_threads';
7
12
  import { diagnostics } from '@dokebi/core/libraries';
8
13
  const PAGES_KEY = Symbol.for('dokebi.app.modulePages');
14
+ /** Project files this worker loaded (file: URLs outside node_modules), when Node can say. */
15
+ const loaded = new Set();
16
+ const registerHooks = nodeModule.registerHooks;
17
+ // Node 22.15 / 23.5 and later; without it the dev server keeps its watcher alone for these files.
18
+ registerHooks?.({
19
+ resolve(specifier, context, next) {
20
+ const resolved = next(specifier, context);
21
+ if (resolved.url.startsWith('file:') && !resolved.url.includes('/node_modules/'))
22
+ loaded.add(resolved.url);
23
+ return resolved;
24
+ },
25
+ });
9
26
  async function read(url) {
10
27
  try {
11
28
  const definition = (await import(url)).default;
@@ -15,7 +32,14 @@ async function read(url) {
15
32
  if (typeof list !== 'function')
16
33
  return { kind: 'unsupported' };
17
34
  // Plain data (module names, folders, set names): it crosses to the main thread as it is.
18
- return { kind: 'sources', sources: list() };
35
+ const sources = list();
36
+ return {
37
+ kind: 'sources',
38
+ sources,
39
+ files: [url, ...loaded]
40
+ .filter((item, at, all) => all.indexOf(item) === at)
41
+ .map((item) => fileURLToPath(item)),
42
+ };
19
43
  }
20
44
  catch (error) {
21
45
  return { kind: 'error', error: diagnostics.describeError(error) };
@@ -37,5 +37,7 @@ export declare class ModulePagesSource {
37
37
  load(id: string): Promise<string | null>;
38
38
  /** The dev server: page files added or removed in a module folder reload the browser. */
39
39
  configureServer(server: PagesDevServer): void;
40
+ /** Ends the comparison (the dev server closed or configures again). */
41
+ stop(): void;
40
42
  }
41
43
  export {};
@@ -6,12 +6,15 @@
6
6
  // `Symbol.for('dokebi.app.modulePages')`, @dokebi/app 0.4.9) and writes one static import per page
7
7
  // file. Pages of sets the app did not choose (`Pages/<set>/**`) are left out. In the dev server it
8
8
  // watches the module folders and the app file: a page added or removed reloads the browser.
9
- import { existsSync } from 'node:fs';
9
+ import { existsSync, readdirSync, statSync } from 'node:fs';
10
10
  import { readdir } from 'node:fs/promises';
11
11
  import { basename, dirname, join, relative, sep } from 'node:path';
12
12
  import { pathToFileURL } from 'node:url';
13
13
  import { Worker } from 'node:worker_threads';
14
+ import { diagnostics } from '@dokebi/core/libraries';
15
+ import { RESCAN_VARIABLE, rescanInterval } from './dev-rescan.js';
14
16
  import { InertiaError } from './errors.js';
17
+ const { describeError } = diagnostics;
15
18
  /** The specifier views/app.js and views/ssr.js import. */
16
19
  export const MODULE_PAGES_ID = 'virtual:dokebi/module-pages';
17
20
  /** Vite's mark of a virtual module, then the app file the module is for. */
@@ -70,6 +73,35 @@ async function pageFiles(source, appViews) {
70
73
  }
71
74
  return found;
72
75
  }
76
+ /** A file's state for the comparison (D-0289): inode, size and time, or absent. */
77
+ function fileState(path) {
78
+ try {
79
+ const stats = statSync(path);
80
+ return `${stats.ino}:${stats.size}:${stats.mtimeMs}`;
81
+ }
82
+ catch (error) {
83
+ const code = error.code;
84
+ return code === 'ENOENT' || code === 'ENOTDIR' ? 'absent' : `unreadable:${code ?? '?'}`;
85
+ }
86
+ }
87
+ /** The .vue files below the folders, sorted (a page added or removed changes it). */
88
+ function pageListing(folders) {
89
+ const lines = [];
90
+ for (const folder of folders) {
91
+ let names;
92
+ try {
93
+ names = readdirSync(folder, { recursive: true, encoding: 'utf8' });
94
+ }
95
+ catch (error) {
96
+ lines.push(`${folder}:${error.code ?? '?'}`);
97
+ continue;
98
+ }
99
+ for (const name of names)
100
+ if (name.endsWith('.vue'))
101
+ lines.push(join(folder, name));
102
+ }
103
+ return lines.sort().join('\n');
104
+ }
73
105
  /** The build: the app file in this process (one read per build). */
74
106
  async function readHere(app) {
75
107
  let definition;
@@ -132,6 +164,13 @@ export class ModulePagesSource {
132
164
  /** Virtual id → the folders and the app file a change of which reloads it. */
133
165
  #watched = new Map();
134
166
  #allow;
167
+ /**
168
+ * D-0289: per virtual id, the state of every file its table was read from (the app file, the
169
+ * module list, the definitions: what the worker loaded) and the page listing of its folders,
170
+ * compared every DOKEBI_DEV_RESCAN_MS besides the watcher (whose events can come late).
171
+ */
172
+ #tracked = new Map();
173
+ #rescanTimer;
135
174
  /** `allow` hands each module views folder to the dev file policy (D-0129). */
136
175
  constructor(logger, allow) {
137
176
  this.#logger = logger;
@@ -217,6 +256,8 @@ export class ModulePagesSource {
217
256
  limit: MAX_FILES,
218
257
  });
219
258
  this.#watch(id, app, sources);
259
+ if (this.#serve)
260
+ this.#track(id, read.kind === 'sources' ? (read.files ?? []) : []);
220
261
  this.#logger.log('debug', 'Inertia module pages gathered', {
221
262
  app,
222
263
  modules: counts,
@@ -235,6 +276,13 @@ export class ModulePagesSource {
235
276
  /** The dev server: page files added or removed in a module folder reload the browser. */
236
277
  configureServer(server) {
237
278
  this.#server = server;
279
+ // D-0289: the comparison besides the watcher (one per source: a restart configures again).
280
+ this.stop();
281
+ const rescan = rescanInterval(process.env[RESCAN_VARIABLE]);
282
+ if (rescan.ms > 0) {
283
+ this.#rescanTimer = setInterval(() => this.#rescan(), rescan.ms);
284
+ this.#rescanTimer.unref();
285
+ }
238
286
  const changed = (event) => (path) => {
239
287
  for (const [id, watched] of this.#watched) {
240
288
  const page = event !== 'change' &&
@@ -246,6 +294,11 @@ export class ModulePagesSource {
246
294
  const definition = DEFINITION.test(basename(path)) && within(path, watched.sources);
247
295
  if (!page && !definition && path !== watched.app && !watched.files.includes(path))
248
296
  continue;
297
+ // A file or page the comparison follows, already at the state it took (or no change):
298
+ // nothing to do. Any other file (a definition no table was read from) goes on as before.
299
+ const followed = page || this.#tracked.get(id)?.states.has(path) === true;
300
+ if (followed && this.#current(id, watched.folders))
301
+ continue;
249
302
  this.#invalidate(id, event, path);
250
303
  }
251
304
  };
@@ -253,6 +306,72 @@ export class ModulePagesSource {
253
306
  server.watcher?.on('unlink', changed('unlink'));
254
307
  server.watcher?.on('change', changed('change'));
255
308
  }
309
+ /** Ends the comparison (the dev server closed or configures again). */
310
+ stop() {
311
+ clearInterval(this.#rescanTimer);
312
+ this.#rescanTimer = undefined;
313
+ }
314
+ /** Records what the table of `id` was read from (D-0289). */
315
+ #track(id, loaded) {
316
+ const watched = this.#watched.get(id);
317
+ if (!watched)
318
+ return;
319
+ const states = new Map();
320
+ for (const path of new Set([watched.app, ...watched.files, ...loaded]))
321
+ states.set(path, fileState(path));
322
+ this.#tracked.set(id, { states, listing: pageListing(watched.folders) });
323
+ }
324
+ /**
325
+ * Whether every recorded file and the page listing of `id` are as they are now; when not, the
326
+ * records take the state now (so the change is handled once, by whoever sees it first) and the
327
+ * first path that differs is answered. Undefined: nothing recorded (the watcher decides).
328
+ */
329
+ #current(id, folders) {
330
+ const tracked = this.#tracked.get(id);
331
+ if (!tracked)
332
+ return undefined;
333
+ return this.#differs(tracked, folders) === undefined;
334
+ }
335
+ #differs(tracked, folders) {
336
+ let first;
337
+ for (const [path, state] of tracked.states) {
338
+ const now = fileState(path);
339
+ if (now === state)
340
+ continue;
341
+ tracked.states.set(path, now);
342
+ first ??= path;
343
+ }
344
+ const listing = pageListing(folders);
345
+ if (listing !== tracked.listing) {
346
+ tracked.listing = listing;
347
+ first ??= folders[0] ?? 'views';
348
+ }
349
+ return first;
350
+ }
351
+ /** D-0289: what the watcher has not reported yet reloads the table now. */
352
+ #rescan() {
353
+ for (const [id, tracked] of this.#tracked) {
354
+ const watched = this.#watched.get(id);
355
+ if (!watched)
356
+ continue;
357
+ let path;
358
+ try {
359
+ path = this.#differs(tracked, watched.folders);
360
+ }
361
+ catch (error) {
362
+ this.#logger.log('warn', 'Inertia module pages could not be compared with the disk', {
363
+ code: 'INERTIA_MODULE_PAGES_RESCAN_FAILED',
364
+ app: watched.app,
365
+ error: describeError(error),
366
+ });
367
+ continue;
368
+ }
369
+ if (path === undefined)
370
+ continue;
371
+ this.#logger.log('info', 'Inertia module pages found a change on disk its watcher had not reported; the browser reloads', { code: 'INERTIA_MODULE_PAGES_MISSED', app: watched.app, path });
372
+ this.#invalidate(id, 'rescan', path);
373
+ }
374
+ }
256
375
  #watch(id, app, sources) {
257
376
  // The app's own views too: a page added or removed there changes which module pages it hides.
258
377
  const folders = [join(dirname(app), 'views'), ...sources.map((source) => source.folder)];
@@ -0,0 +1,43 @@
1
+ import { type Logger } from '@dokebi/core';
2
+ export interface TemplateBuildOptions {
3
+ /** The project (template repository) root: its node_modules has vite and @vitejs/plugin-vue. Default: the working directory. */
4
+ readonly root?: string;
5
+ /** The template folder, relative to root (Layout.vue, Pages/**). */
6
+ readonly dir: string;
7
+ /** Where the bundle goes, inside root. Default: dist/template/<name>. Emptied first. */
8
+ readonly out?: string;
9
+ /** The template name. Default: the folder name. */
10
+ readonly name?: string;
11
+ /** The template version. Default: the version of root's package.json. */
12
+ readonly version?: string;
13
+ /** The app's modules the pages import and the app provides (its SDK), besides the defaults. */
14
+ readonly shared?: readonly string[];
15
+ /** The largest bundle allowed (default 50 MiB, like the app's default limit). */
16
+ readonly maxBytes?: number;
17
+ /** A vite config file of the project to merge (aliases, more plugins). Default: none. */
18
+ readonly config?: string;
19
+ readonly logger?: Logger;
20
+ }
21
+ export interface TemplateBuildResult {
22
+ /** The bundle folder (absolute). */
23
+ readonly out: string;
24
+ readonly name: string;
25
+ readonly version: string;
26
+ readonly buildId: string;
27
+ readonly pages: readonly string[];
28
+ /** The shared modules the pages import → their versions in this project. */
29
+ readonly shared: Readonly<Record<string, string | null>>;
30
+ readonly files: number;
31
+ readonly bytes: number;
32
+ readonly ms: number;
33
+ }
34
+ /** The ESM entry file of an installed package of the project (exports `.` → import/default, else module/main). */
35
+ export declare function packageEntry(root: string, name: string): string | undefined;
36
+ /** The pages of a template folder: `Layout` and `Pages/<path>` → their .vue file. */
37
+ export declare function templatePages(folder: string): Promise<Map<string, string>>;
38
+ /**
39
+ * Builds the template folder `options.dir` of `options.root` into a bundle at `options.out`
40
+ * (D-0291). Throws INVALID_TEMPLATE_BUILD for wrong options and TEMPLATE_BUILD_FAILED for a
41
+ * build that fails, with the cause.
42
+ */
43
+ export declare function buildTemplateBundle(options: TemplateBuildOptions): Promise<TemplateBuildResult>;