@dokebi/template-inertia 0.4.24 → 0.4.26

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
@@ -268,6 +268,7 @@ A template can live apart from the app: a `views/<template>/` folder (Layout.vue
268
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
269
  - The signature (`dokebi-template.sig`) is the template repository's next step: sign the manifest (its file hashes cover the rest).
270
270
  - The same source builds the same bundle (`buildId` = the first 12 hex of the manifest's sha256).
271
+ - **`--carry <file>`** (repeatable or comma separated, 0.4.26, D-0296; `carry` of `buildTemplateBundle`): a file of the template folder, its path relative to the folder (`design.json`, `kit/fonts.json`), goes into the bundle as it is at `browser/<path>`, listed in `files` like every other file, so the signature covers it and `template check` and the app's load find any change. The result lists them (`carried: ['browser/design.json']`). The app reads one in `verifyTemplate` (`bundle.read('browser/design.json')`), and the browser can fetch it at `<base>_dokebi/templates/<app>/<template>/<buildId>/browser/<path>` — it is served like the pages' files, so **never carry a secret**. Refused (`INVALID_TEMPLATE_BUILD`, before anything is emptied or built): a path outside the folder, absolute or with `.`/`..`, a hidden file, a folder, a link, a missing file, and one under `pages/`, `chunks/` or `assets/` in any case (the build's own folders; `Pages/` is the same folder on macOS). Nothing else of the folder goes in. Any app that loads bundles (0.4.21+) takes such a bundle: the format is unchanged.
271
272
  - **`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
273
  - **`--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
274
  - **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.
@@ -342,6 +343,8 @@ A template can live apart from the app: a `views/<template>/` folder (Layout.vue
342
343
  - **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.
343
344
  - **A module that does not compile answers 500, not 404 (0.4.23, [D-0292](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0292-vite-host-explains-module-404.md))**: in middleware mode Vite's error middleware logs a transform error, sends it to the open pages' overlay and calls `next()` without it, so the host answered an empty 404 (a `[@vue/compiler-sfc] Unresolvable type reference` looked like a missing page). The host keeps the error of each request (an error middleware in a `configureServer` post hook, before Vite's own) and answers it 500: error `INERTIA_VITE_MODULE_FAILED` with `url` and the whole `error`, and a `text/plain` body with the URL and Vite's message on this machine (`500 Internal Server Error\n` alone for a remote host, a `devHosts` tunnel). Vite still logs it and sends the overlay.
344
345
  - **A type added to a file a barrel re-exports reaches the pages (0.4.23, D-0292)**: `defineProps<X>()` resolves X through @vue/compiler-sfc's type scopes, cached per file; for `export * from './event'` the compiler copies the source file's types into the barrel's scope, and @vitejs/plugin-vue clears only the changed file. A new type in an existing file that a barrel re-exports was `Unresolvable type reference` in dev until the barrel changed or dev restarted (vue-tsc and the build passed). The Vite host (and `dokebi template preview`) now clears, on every change or removal of a `.ts`/`.tsx`/`.mts`/`.cts` file, the type cache of the files that `export *` or `export type *` from it — in its folder and each folder above it up to its package root (the nearest package.json), and their own re-exporters — through the vue/compiler-sfc plugin-vue resolves from the project root (debug `Vue type caches of re-exporting files cleared` with `barrels`). The host also registers a TypeScript with a JS API on that compiler, as `dokebiInertia()` does, so a vite.config without it resolves imported props types too. The type files that compiler reads (outside node_modules) join the host's comparison with the disk (D-0283, D-0289: the page load, app connect, server render and `DOKEBI_DEV_RESCAN_MS` timer), which before saw only the modules Vite loads: an edit of a type file the watcher reports late or never reaches the pages within that time too (info `INERTIA_VITE_WATCH_MISSED` names it). The host learns them by wrapping the compiler's file access (`script.fs`, through @vitejs/plugin-vue's public `api.options`): its own `fs` when the config gives one, else node:fs with the answers of TypeScript's `ts.sys`.
346
+ - **A props type changed by a checkout reaches the pages at once, and stays (0.4.25, [D-0295](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0295-vite-host-type-changes-after-checkout.md))**: after a `git merge --ff` of many files, a page kept the old props of a type a barrel re-exports until the type file and the page were touched (the dev compiler had rebuilt the barrel from the old cache of the changed file while it cleared the barrels, and kept it). The changed type file's own cache is now cleared first, before the barrels, so a page that compiles meanwhile (a server render, another page of the same checkout) reads the new types. And a request that finds changed type files in the comparison with the disk (app connect, server render, a page loading Vite's client) goes on only once Vite has cleared their caches and invalidated the pages compiled with them (at most 2 s; none with `server.hmr: false`): the first server render after a checkout has the new props, where it used to have the old ones until the next request (debug `Vite handled the changed type files before the request`).
347
+ - **Files of the template folder ride in the bundle (0.4.26, [D-0296](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0296-template-bundle-carried-files.md))**: `dokebi template build --carry design.json` (`carry` of `buildTemplateBundle`) puts a file of the template folder — the options a designer declares, say — into the bundle at `browser/<path>`, hashed in the manifest the signature covers, where a template repository had to add it after the build and rewrite the manifest itself (§4.3).
345
348
  - **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.
346
349
  - **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`).
347
350
  - 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`).
@@ -407,7 +410,7 @@ A template can live apart from the app: a `views/<template>/` folder (Layout.vue
407
410
  | `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) |
408
411
  | `INVALID_TEMPLATE_PREVIEW` | `InertiaUsageError` | (D-0291) `dokebi template preview`: the folder is outside the project or has no `Pages/**/*.vue`, or a `<Page>.preview.json` / `preview.json` is not the documented shape (§4.3) |
409
412
  | `INVALID_TEMPLATE_LISTENER` | `InertiaUsageError` | (D-0294) `onTemplateState` was given something other than a function |
410
- | `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) |
413
+ | `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; a `--carry` path that is not a plain file of the template folder or lands in the build's own folders (0.4.26, D-0296) (§4.3) |
411
414
  | `INVALID_PRUNE` | `InertiaUsageError` | `pruneBuildFiles` without a manifest path, or an `olderThanMs`, `maxManifestBytes` or `now` that is not a whole number from 0 |
412
415
 
413
416
  ## 7. Cautions
package/dist/index.js CHANGED
@@ -1237,7 +1237,7 @@ class InertiaRuntime {
1237
1237
  }
1238
1238
  export const createPlugin = definePlugin({
1239
1239
  name: 'dokebi-template-inertia',
1240
- version: '0.4.24',
1240
+ version: '0.4.26',
1241
1241
  core: '^0.4.2',
1242
1242
  options,
1243
1243
  entry: parseEntry,
@@ -1,4 +1,6 @@
1
1
  import { type Logger } from '@dokebi/core';
2
+ /** D-0296: carried files go under this folder of the bundle (served like the pages' files). */
3
+ export declare const TEMPLATE_CARRY_FOLDER = "browser";
2
4
  export interface TemplateBuildOptions {
3
5
  /** The project (template repository) root: its node_modules has vite and @vitejs/plugin-vue. Default: the working directory. */
4
6
  readonly root?: string;
@@ -16,6 +18,12 @@ export interface TemplateBuildOptions {
16
18
  readonly maxBytes?: number;
17
19
  /** A vite config file of the project to merge (aliases, more plugins). Default: none. */
18
20
  readonly config?: string;
21
+ /**
22
+ * D-0296: files of the template folder (paths relative to it) put into the bundle as they are, at
23
+ * `browser/<path>`, listed in the manifest's `files` so the signature covers them. Served like
24
+ * the pages' files: public, never a secret.
25
+ */
26
+ readonly carry?: readonly string[];
19
27
  readonly logger?: Logger;
20
28
  }
21
29
  export interface TemplateBuildResult {
@@ -27,6 +35,8 @@ export interface TemplateBuildResult {
27
35
  readonly pages: readonly string[];
28
36
  /** The shared modules the pages import → their versions in this project. */
29
37
  readonly shared: Readonly<Record<string, string | null>>;
38
+ /** D-0296: the carried files, as bundle paths (`browser/design.json`). */
39
+ readonly carried: readonly string[];
30
40
  readonly files: number;
31
41
  readonly bytes: number;
32
42
  readonly ms: number;
@@ -11,11 +11,15 @@ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'nod
11
11
  import { pathToFileURL } from 'node:url';
12
12
  import { ConsoleLogger } from '@dokebi/core';
13
13
  import { InertiaError, InertiaUsageError } from './errors.js';
14
- import { checkTemplateBundle, jsonValue, PAGE_META_MAX_BYTES, SHARED_DEFAULTS, SHARED_SPECIFIER, sha256, TEMPLATE_FORMAT, TEMPLATE_MANIFEST, TEMPLATE_MAX_BYTES, TEMPLATE_NAME, TEMPLATE_PAGE, TEMPLATE_VERSION, } from './template-bundle.js';
14
+ import { checkTemplateBundle, jsonValue, PAGE_META_MAX_BYTES, SHARED_DEFAULTS, SHARED_SPECIFIER, sha256, TEMPLATE_FILE, TEMPLATE_FORMAT, TEMPLATE_MANIFEST, TEMPLATE_MAX_BYTES, TEMPLATE_NAME, TEMPLATE_PAGE, TEMPLATE_VERSION, } from './template-bundle.js';
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.24' };
18
+ const BUILDER = { name: 'dokebi-template-inertia', version: '0.4.26' };
19
+ /** D-0296: carried files go under this folder of the bundle (served like the pages' files). */
20
+ export const TEMPLATE_CARRY_FOLDER = 'browser';
21
+ /** The folders Vite writes under browser/: a carried file never takes them (any case). */
22
+ const BUILT_FOLDERS = ['pages', 'chunks', 'assets'];
19
23
  function defaultLogger() {
20
24
  return new ConsoleLogger({ level: 'info' }, { plugin: 'dokebi-template-inertia', process: 'template-build' });
21
25
  }
@@ -97,6 +101,38 @@ async function listFiles(dir, root = dir, found = []) {
97
101
  }
98
102
  return found;
99
103
  }
104
+ /**
105
+ * D-0296: the carried files, checked before the build: bundle path → the file in the template
106
+ * folder. A path is relative to the folder, a plain file inside it (no link on the way), not one of
107
+ * Vite's folders, and a bundle file name.
108
+ */
109
+ async function carriedFiles(folder, paths) {
110
+ const carried = new Map();
111
+ const real = realpathSync(folder);
112
+ for (const path of paths) {
113
+ if (typeof path !== 'string' || path === '' || isAbsolute(path))
114
+ throw usage(`--carry ${String(path)} must be a file path relative to the template folder`);
115
+ const parts = path.split(/[\\/]/);
116
+ const target = `${TEMPLATE_CARRY_FOLDER}/${parts.join('/')}`;
117
+ if (parts.some((part) => part === '' || part === '.' || part === '..') ||
118
+ !TEMPLATE_FILE.test(target))
119
+ throw usage(`--carry ${path} is not a plain path inside the template folder (letters, digits, _ . @ + -, no .., no hidden file)`);
120
+ if (BUILT_FOLDERS.includes(parts[0].toLowerCase()))
121
+ throw usage(`--carry ${path} would land in browser/${parts[0]}/, where the build writes its files: put it in another folder`);
122
+ const file = join(folder, ...parts);
123
+ const info = await lstat(file).catch((error) => {
124
+ if (error.code === 'ENOENT' || error.code === 'ENOTDIR')
125
+ return undefined;
126
+ throw error;
127
+ });
128
+ if (info === undefined)
129
+ throw usage(`--carry ${path} is not in ${folder}`);
130
+ if (!info.isFile() || !within(realpathSync(file), real))
131
+ throw usage(`--carry ${path} must be a plain file of the template folder, not a folder or a link`);
132
+ carried.set(target, file);
133
+ }
134
+ return carried;
135
+ }
100
136
  const outputs = (result) => (Array.isArray(result) ? result : [result]).flatMap((item) => item.output ?? []);
101
137
  /**
102
138
  * Builds the template folder `options.dir` of `options.root` into a bundle at `options.out`
@@ -139,6 +175,8 @@ export async function buildTemplateBundle(options) {
139
175
  if (typeof module !== 'string' || !SHARED_SPECIFIER.test(module))
140
176
  throw new InertiaUsageError('INVALID_TEMPLATE_SHARED', `--shared ${String(module)} is not a package name with an optional subpath`);
141
177
  const shared = [...new Set([...SHARED_DEFAULTS, ...own])];
178
+ // Before anything is emptied or built.
179
+ const carry = await carriedFiles(folder, options.carry ?? []);
142
180
  const out = resolve(root, options.out ?? join('dist', 'template', name));
143
181
  if (!within(out, root) || within(root, out) || within(folder, out) || within(out, folder))
144
182
  throw usage(`--out ${relative(root, out) || '.'} must be a folder inside the project, apart from the template folder (the build imports the server pages from there)`);
@@ -340,6 +378,12 @@ export async function buildTemplateBundle(options) {
340
378
  await writeFile(join(out, 'locales', file), text);
341
379
  wordFiles++;
342
380
  }
381
+ // D-0296: the carried files, as they are, after Vite emptied browser/.
382
+ for (const [target, file] of carry) {
383
+ const to = join(out, ...target.split('/'));
384
+ await mkdir(dirname(to), { recursive: true });
385
+ await writeFile(to, await readFile(file));
386
+ }
343
387
  const files = {};
344
388
  for (const top of wordFiles ? ['browser', 'ssr', 'locales'] : ['browser', 'ssr'])
345
389
  for (const file of await listFiles(join(out, top))) {
@@ -368,6 +412,7 @@ export async function buildTemplateBundle(options) {
368
412
  buildId: check.buildId,
369
413
  pages: Object.keys(pageEntries),
370
414
  shared: manifest.shared,
415
+ carried: [...carry.keys()],
371
416
  files: Object.keys(files).length,
372
417
  bytes: check.bytes,
373
418
  ms: Math.round(performance.now() - begin),
@@ -380,6 +425,7 @@ export async function buildTemplateBundle(options) {
380
425
  out: relative(root, out),
381
426
  pages: result.pages.length,
382
427
  words: wordFiles,
428
+ carried: result.carried,
383
429
  files: result.files,
384
430
  bytes: result.bytes,
385
431
  shared: manifest.shared,
@@ -10,6 +10,11 @@ export declare const TEMPLATE_NAME: RegExp;
10
10
  export declare const TEMPLATE_VERSION: RegExp;
11
11
  /** A page of a bundle: `Layout`, or `Pages/<path>` without the `.vue`. */
12
12
  export declare const TEMPLATE_PAGE: RegExp;
13
+ /**
14
+ * A file of a bundle: under browser/ or ssr/, or a screen-word file `locales/<locale>/<ns>.json`
15
+ * (D-0291 stage 3b), plain path segments only.
16
+ */
17
+ export declare const TEMPLATE_FILE: RegExp;
13
18
  /** A shared module specifier: a package name with an optional subpath. */
14
19
  export declare const SHARED_SPECIFIER: RegExp;
15
20
  /** A page's `meta` (JSON) may take this many bytes. */
@@ -30,7 +30,7 @@ export const TEMPLATE_PAGE = /^(?:Layout|Pages(?:\/[A-Za-z0-9_][A-Za-z0-9_.-]{0,
30
30
  * A file of a bundle: under browser/ or ssr/, or a screen-word file `locales/<locale>/<ns>.json`
31
31
  * (D-0291 stage 3b), plain path segments only.
32
32
  */
33
- const FILE = /^(?:(?:browser|ssr)(?:\/[A-Za-z0-9_@+][A-Za-z0-9_.@+-]{0,199}){1,32}|locales\/[A-Za-z][A-Za-z0-9_-]{0,34}(?:\/[A-Za-z0-9_][A-Za-z0-9_.-]{0,99}){1,8}\.json)$/;
33
+ export const TEMPLATE_FILE = /^(?:(?:browser|ssr)(?:\/[A-Za-z0-9_@+][A-Za-z0-9_.@+-]{0,199}){1,32}|locales\/[A-Za-z][A-Za-z0-9_-]{0,34}(?:\/[A-Za-z0-9_][A-Za-z0-9_.-]{0,99}){1,8}\.json)$/;
34
34
  /** The folders of a bundle. */
35
35
  const FOLDERS = ['browser', 'ssr', 'locales'];
36
36
  /** A shared module specifier: a package name with an optional subpath. */
@@ -90,7 +90,7 @@ export function manifestProblem(value) {
90
90
  if (!plain(value.files))
91
91
  return 'files must be an object of path → { bytes, sha256 }';
92
92
  for (const [file, entry] of Object.entries(value.files)) {
93
- if (!FILE.test(file) || file.split('/').some((part) => part === '..' || part === '.'))
93
+ if (!TEMPLATE_FILE.test(file) || file.split('/').some((part) => part === '..' || part === '.'))
94
94
  return `file ${file} is not a path under browser/ or ssr/, or a locales/<locale>/<namespace>.json`;
95
95
  if (!plain(entry) ||
96
96
  !Number.isSafeInteger(entry.bytes) ||
@@ -1,4 +1,4 @@
1
- export { buildTemplateBundle, packageEntry, type TemplateBuildOptions, type TemplateBuildResult, templatePages, } from './template-build.js';
1
+ export { buildTemplateBundle, packageEntry, TEMPLATE_CARRY_FOLDER, type TemplateBuildOptions, type TemplateBuildResult, templatePages, } from './template-build.js';
2
2
  export { checkTemplateBundle, compatibleLine, type ProvidedShared, SERVER_ONLY_SHARED, SHARED_DEFAULTS, sharedProblems, TEMPLATE_FORMAT, TEMPLATE_MANIFEST, TEMPLATE_MAX_BYTES, TEMPLATE_NAME, TEMPLATE_SIGNATURE, type TemplateCheck, type TemplateCheckLimits, type TemplateManifest, type TemplatePage, type TemplateProblem, } from './template-bundle.js';
3
3
  export { PREVIEW_PREFIX, previewCases, 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
@@ -1,6 +1,6 @@
1
1
  // `@dokebi/template-inertia/template` (D-0291): template bundles — the format and its check, and
2
2
  // the build that `dokebi template build` runs in a template repository.
3
- export { buildTemplateBundle, packageEntry, templatePages, } from './template-build.js';
3
+ export { buildTemplateBundle, packageEntry, TEMPLATE_CARRY_FOLDER, templatePages, } from './template-build.js';
4
4
  export { checkTemplateBundle, compatibleLine, SERVER_ONLY_SHARED, SHARED_DEFAULTS, sharedProblems, TEMPLATE_FORMAT, TEMPLATE_MANIFEST, TEMPLATE_MAX_BYTES, TEMPLATE_NAME, TEMPLATE_SIGNATURE, } from './template-bundle.js';
5
5
  export { PREVIEW_PREFIX, previewCases, previewWords, startTemplatePreview, } from './template-preview.js';
6
6
  export { packageVersion, SHARED_FILE, sharedEntryName, } from './template-shared.js';
package/dist/vite-dev.js CHANGED
@@ -23,7 +23,7 @@ import { DependencyCache } from './vite-deps.js';
23
23
  import { ViteRequestErrors } from './vite-dev-errors.js';
24
24
  import { DEV_CLIENT_HEADER, dokebiDevFiles } from './vite-files.js';
25
25
  import { NotLoadedReporter } from './vite-not-loaded.js';
26
- import { vueTypeBarrels } from './vite-type-barrels.js';
26
+ import { TypeFileUpdates, vueTypeBarrels } from './vite-type-barrels.js';
27
27
  import { ServedFiles, staleEventFilter } from './vite-watch.js';
28
28
  import { registerVueTypeScript } from './vue-typescript.js';
29
29
  const { describeError } = diagnostics;
@@ -49,6 +49,11 @@ const HOST_PATH = '/__dokebi/vite-host';
49
49
  const SSR_PATH = `${HOST_PATH}/ssr`;
50
50
  /** Largest server-render request (the page JSON) the host reads. */
51
51
  const SSR_BODY_MAX_BYTES = 32 * 1024 * 1024;
52
+ /**
53
+ * D-0295: the longest a request waits for Vite to handle the type files a comparison found
54
+ * changed (clearing type caches takes milliseconds; Vite handles none for `server.hmr: false`).
55
+ */
56
+ const TYPE_SETTLE_MS = 2000;
52
57
  /** Loopback addresses of the host (a browser resolves `*.localhost` to either); never all. */
53
58
  const LOOPBACK_HOSTS = ['127.0.0.1', '::1'];
54
59
  /** Tries for a port that is free on both loopback addresses. */
@@ -265,6 +270,69 @@ export async function startViteHost(logger, root = process.cwd(), settings = {})
265
270
  sendJson(response, 500, { error: errorJson(error) });
266
271
  }
267
272
  };
273
+ /** Hands a request to Vite's middlewares, explaining what Vite answers nothing for. */
274
+ const serve = (request, response, server, cache) => {
275
+ // Vite answers 504 for a pre-bundled file it cannot serve: if the folder changed under it,
276
+ // re-optimize so the next page load gets files that exist (D-0128).
277
+ if (cache)
278
+ response.once('finish', () => {
279
+ if (response.statusCode === 504)
280
+ void cache.ensure('outdated').catch(report('deps'));
281
+ });
282
+ const url = String(request.url ?? '/');
283
+ const reporter = notLoaded;
284
+ if (reporter)
285
+ response.once('finish', () => reporter.served(url, request.method, response.statusCode));
286
+ server.middlewares(request, response, (error) => {
287
+ // D-0292: an error Vite's error middleware dropped (a module that does not compile)
288
+ // answers 500 with it, not an empty 404.
289
+ const failed = failures.take(request);
290
+ if ((error === undefined || error === null) && failed !== undefined && failed !== null) {
291
+ failures.answer(request, response, failed, url);
292
+ return;
293
+ }
294
+ // D-0292: a module URL Vite answers nothing for (it drops ERR_LOAD_URL) is explained, and
295
+ // run through Vite once more when the file is there and allowed.
296
+ const subject = reporter && (error === undefined || error === null) && !response.headersSent
297
+ ? reporter.subject(url, request.method, request.headers)
298
+ : undefined;
299
+ if (!reporter || !subject) {
300
+ viteFallthrough(response, error, report('vite'));
301
+ return;
302
+ }
303
+ void (async () => {
304
+ const diagnosis = await reporter.diagnose(subject);
305
+ if (!diagnosis.retry || response.headersSent) {
306
+ viteFallthrough(response, undefined, report('vite'));
307
+ reporter.report(diagnosis, response.statusCode);
308
+ return;
309
+ }
310
+ await reporter.refresh(subject, diagnosis);
311
+ request.url = url;
312
+ response.once('finish', () => reporter.report(diagnosis, response.statusCode));
313
+ server.middlewares(request, response, (again) => {
314
+ const failedAgain = failures.take(request);
315
+ if ((again === undefined || again === null) &&
316
+ failedAgain !== undefined &&
317
+ failedAgain !== null)
318
+ failures.answer(request, response, failedAgain, url);
319
+ else
320
+ viteFallthrough(response, again, report('vite'));
321
+ });
322
+ })().catch((failure) => {
323
+ report('not-loaded')(failure);
324
+ viteFallthrough(response, undefined, report('vite'));
325
+ });
326
+ });
327
+ };
328
+ // D-0295: a request that asked for the comparison goes on once Vite handled the type files it
329
+ // found changed (their caches cleared, the pages compiled with them invalidated).
330
+ const settle = (found) => {
331
+ const types = found.files.filter((file) => served.has(file, 'types'));
332
+ if (types.length === 0 || started?.config.server.hmr === false)
333
+ return Promise.resolve();
334
+ return typeUpdates.settled(types, TYPE_SETTLE_MS);
335
+ };
268
336
  const endpoint = await openLoopback(logger, (request, response) => {
269
337
  if (!keyMatches(expected, request.headers[VITE_HOST_KEY_HEADER])) {
270
338
  if (logger.isEnabled('debug'))
@@ -291,10 +359,12 @@ export async function startViteHost(logger, root = process.cwd(), settings = {})
291
359
  if (path === HOST_PATH && !browser) {
292
360
  // D-0283: files changed under Vite that the watcher has not reported (a `git pull` that
293
361
  // restarted the app) are read again before the app's pages are served.
294
- served.sweep('client');
362
+ const changed = settle(served.sweep('client'));
295
363
  // An app process connects (it started or restarted): it is answered once the pre-bundled
296
364
  // dependencies match what Vite serves, so its pages get hashes that load (D-0128).
297
- void (cache ? cache.ensure('client').catch(report('deps')) : Promise.resolve()).then(() => sendJson(response, 200, {
365
+ void changed
366
+ .then(() => (cache ? cache.ensure('client').catch(report('deps')) : undefined))
367
+ .then(() => sendJson(response, 200, {
298
368
  root,
299
369
  pid: process.pid,
300
370
  // D-0249: where Vite's client sends the HMR socket, when not to the page's origin.
@@ -303,71 +373,21 @@ export async function startViteHost(logger, root = process.cwd(), settings = {})
303
373
  }
304
374
  else if (path === SSR_PATH && request.method === 'POST' && !browser) {
305
375
  // D-0283: the server render reads the files as they are on disk.
306
- served.sweep('ssr');
307
- void ssr(request, response, server);
376
+ // D-0295: after Vite handled a changed type file, so the pages get the new props.
377
+ void settle(served.sweep('ssr')).then(() => ssr(request, response, server));
308
378
  }
309
- else {
379
+ else if (browser && path === `${server.config.base}@vite/client`) {
310
380
  // D-0283: a page loads Vite's client first; its modules then come as they are on disk.
311
- if (browser && path === `${server.config.base}@vite/client`)
312
- served.sweep('page');
313
- // Vite answers 504 for a pre-bundled file it cannot serve: if the folder changed under it,
314
- // re-optimize so the next page load gets files that exist (D-0128).
315
- if (cache)
316
- response.once('finish', () => {
317
- if (response.statusCode === 504)
318
- void cache.ensure('outdated').catch(report('deps'));
319
- });
320
- const url = String(request.url ?? '/');
321
- const reporter = notLoaded;
322
- if (reporter)
323
- response.once('finish', () => reporter.served(url, request.method, response.statusCode));
324
- server.middlewares(request, response, (error) => {
325
- // D-0292: an error Vite's error middleware dropped (a module that does not compile)
326
- // answers 500 with it, not an empty 404.
327
- const failed = failures.take(request);
328
- if ((error === undefined || error === null) && failed !== undefined && failed !== null) {
329
- failures.answer(request, response, failed, url);
330
- return;
331
- }
332
- // D-0292: a module URL Vite answers nothing for (it drops ERR_LOAD_URL) is explained, and
333
- // run through Vite once more when the file is there and allowed.
334
- const subject = reporter && (error === undefined || error === null) && !response.headersSent
335
- ? reporter.subject(url, request.method, request.headers)
336
- : undefined;
337
- if (!reporter || !subject) {
338
- viteFallthrough(response, error, report('vite'));
339
- return;
340
- }
341
- void (async () => {
342
- const diagnosis = await reporter.diagnose(subject);
343
- if (!diagnosis.retry || response.headersSent) {
344
- viteFallthrough(response, undefined, report('vite'));
345
- reporter.report(diagnosis, response.statusCode);
346
- return;
347
- }
348
- await reporter.refresh(subject, diagnosis);
349
- request.url = url;
350
- response.once('finish', () => reporter.report(diagnosis, response.statusCode));
351
- server.middlewares(request, response, (again) => {
352
- const failedAgain = failures.take(request);
353
- if ((again === undefined || again === null) &&
354
- failedAgain !== undefined &&
355
- failedAgain !== null)
356
- failures.answer(request, response, failedAgain, url);
357
- else
358
- viteFallthrough(response, again, report('vite'));
359
- });
360
- })().catch((failure) => {
361
- report('not-loaded')(failure);
362
- viteFallthrough(response, undefined, report('vite'));
363
- });
364
- });
381
+ void settle(served.sweep('page')).then(() => serve(request, response, server, cache));
365
382
  }
383
+ else
384
+ serve(request, response, server, cache);
366
385
  });
367
386
  // Events FSEvents still holds from before the start are no edits (D-0045 addendum 4); the same
368
387
  // records find the edits the watcher has not reported (D-0283).
369
388
  const served = new ServedFiles(logger);
370
389
  served.recordConfig(root);
390
+ const typeUpdates = new TypeFileUpdates(logger);
371
391
  const failures = new ViteRequestErrors(logger);
372
392
  // D-0292: the Vue compiler resolves imported props types through TypeScript's JS API (with
373
393
  // TypeScript 7 only @typescript/typescript6 has one). dokebiInertia() registers it; a vite.config
@@ -386,6 +406,8 @@ export async function startViteHost(logger, root = process.cwd(), settings = {})
386
406
  // D-0292: the type files the Vue compiler reads join the comparison with the disk, so an
387
407
  // edit the watcher misses reaches the pages like one of a module Vite loads.
388
408
  vueTypeBarrels(logger, root, { onTypeFile: (file) => served.record(file, 'types') }),
409
+ // D-0295: after plugin-vue, so a request can wait until Vite handled a changed type file.
410
+ typeUpdates.plugin(),
389
411
  ],
390
412
  server: {
391
413
  middlewareMode: true,
@@ -7,6 +7,49 @@ export declare class TypeBarrels {
7
7
  /** A TypeScript file changed or went away: clears the type caches of the files re-exporting it. */
8
8
  changed(file: string): Promise<string[]>;
9
9
  }
10
+ /** A module graph of Vite's (an environment's, or the one of Vite 5), as far as the waiter uses it. */
11
+ interface FileGraph {
12
+ onFileChange?(file: string): void;
13
+ }
14
+ /** The hot update context Vite gives `handleHotUpdate`, as far as the waiter uses it. */
15
+ interface SettledContext {
16
+ readonly file: string;
17
+ readonly modules: readonly {
18
+ readonly file?: string | null;
19
+ }[];
20
+ readonly server: {
21
+ readonly environments?: Record<string, {
22
+ readonly moduleGraph?: FileGraph;
23
+ }>;
24
+ readonly moduleGraph?: FileGraph;
25
+ };
26
+ }
27
+ /**
28
+ * D-0295: the host's comparison with the disk (D-0283) hands Vite a changed type file as the
29
+ * watcher's `change`. Vite then clears the type caches (vueTypeBarrels, plugin-vue) and plugin-vue
30
+ * names the pages compiled with that file, but all of that is asynchronous: the request that asked
31
+ * for the comparison (a server render, an app connecting, a page loading Vite's client) went on
32
+ * first, and the server render drew the page with the old props (the type changed, the page did
33
+ * not). `settled(files)` resolves once Vite's hot update of each file has passed plugin-vue (the
34
+ * plugin is `enforce: 'post'`). The pages plugin-vue named are invalidated there in every
35
+ * environment, so the request that waited compiles them again.
36
+ */
37
+ export declare class TypeFileUpdates {
38
+ #private;
39
+ constructor(logger: Logger);
40
+ /**
41
+ * Resolves true once Vite handled every file, false after `ms` (Vite runs no hot update for a
42
+ * config file or with `server.hmr: false`; the request then goes on as before).
43
+ */
44
+ settled(files: readonly string[], ms: number): Promise<boolean>;
45
+ /** The Vite plugin: the last `handleHotUpdate` of a file someone waits for. */
46
+ plugin(): {
47
+ name: 'dokebi-inertia:vue-type-settled';
48
+ enforce: 'post';
49
+ apply: 'serve';
50
+ handleHotUpdate(context: SettledContext): void;
51
+ };
52
+ }
10
53
  /** The file access @vue/compiler-sfc takes as `script.fs` (what it reads type files through). */
11
54
  export interface TypeFileSystem {
12
55
  fileExists(file: string): boolean;
@@ -67,6 +67,13 @@ export class TypeBarrels {
67
67
  if (!invalidate)
68
68
  return [];
69
69
  const changed = posix(resolve(file));
70
+ // D-0295: the changed file itself first, before the walk below waits on the disk. A page that
71
+ // compiles during the walk (a server render, another page, other files of the same checkout)
72
+ // rebuilds a barrel just cleared from the cache of the file it re-exports: with that cache still
73
+ // old, the barrel kept the old types for good, also after plugin-vue cleared the file (shop dev,
74
+ // 2026-11-30, after a `git merge --ff` of 45 files). Each barrel is cleared after what it
75
+ // re-exports, so one rebuilt in between reads the new types.
76
+ invalidate(changed);
70
77
  const cleared = [];
71
78
  const seen = new Set([changed]);
72
79
  const queue = [changed];
@@ -144,6 +151,109 @@ export class TypeBarrels {
144
151
  return found;
145
152
  }
146
153
  }
154
+ /**
155
+ * D-0295: the host's comparison with the disk (D-0283) hands Vite a changed type file as the
156
+ * watcher's `change`. Vite then clears the type caches (vueTypeBarrels, plugin-vue) and plugin-vue
157
+ * names the pages compiled with that file, but all of that is asynchronous: the request that asked
158
+ * for the comparison (a server render, an app connecting, a page loading Vite's client) went on
159
+ * first, and the server render drew the page with the old props (the type changed, the page did
160
+ * not). `settled(files)` resolves once Vite's hot update of each file has passed plugin-vue (the
161
+ * plugin is `enforce: 'post'`). The pages plugin-vue named are invalidated there in every
162
+ * environment, so the request that waited compiles them again.
163
+ */
164
+ export class TypeFileUpdates {
165
+ #logger;
166
+ #waiting = new Map();
167
+ constructor(logger) {
168
+ this.#logger = logger;
169
+ }
170
+ /**
171
+ * Resolves true once Vite handled every file, false after `ms` (Vite runs no hot update for a
172
+ * config file or with `server.hmr: false`; the request then goes on as before).
173
+ */
174
+ settled(files, ms) {
175
+ const keys = [...new Set(files.map((file) => posix(resolve(file))))];
176
+ if (keys.length === 0)
177
+ return Promise.resolve(true);
178
+ const begin = performance.now();
179
+ return new Promise((answer) => {
180
+ let left = keys.length;
181
+ let over = false;
182
+ const entries = [];
183
+ const finish = (handled) => {
184
+ if (over)
185
+ return;
186
+ over = true;
187
+ clearTimeout(timer);
188
+ for (const [key, done] of entries)
189
+ this.#drop(key, done);
190
+ const fields = { files: keys.length, ms: Math.round(performance.now() - begin) };
191
+ if (!handled)
192
+ this.#logger.log('debug', 'Vite dev host went on before Vite handled every changed type file', { ...fields, left });
193
+ else if (this.#logger.isEnabled('debug'))
194
+ this.#logger.log('debug', 'Vite handled the changed type files before the request', fields);
195
+ answer(handled);
196
+ };
197
+ const timer = setTimeout(() => finish(false), ms);
198
+ for (const key of keys) {
199
+ const done = () => {
200
+ this.#drop(key, done);
201
+ left--;
202
+ if (left === 0)
203
+ finish(true);
204
+ };
205
+ entries.push([key, done]);
206
+ let waiting = this.#waiting.get(key);
207
+ if (!waiting) {
208
+ waiting = new Set();
209
+ this.#waiting.set(key, waiting);
210
+ }
211
+ waiting.add(done);
212
+ }
213
+ });
214
+ }
215
+ #drop(key, done) {
216
+ const waiting = this.#waiting.get(key);
217
+ if (!waiting)
218
+ return;
219
+ waiting.delete(done);
220
+ if (waiting.size === 0)
221
+ this.#waiting.delete(key);
222
+ }
223
+ /** The Vite plugin: the last `handleHotUpdate` of a file someone waits for. */
224
+ plugin() {
225
+ return {
226
+ name: 'dokebi-inertia:vue-type-settled',
227
+ enforce: 'post',
228
+ apply: 'serve',
229
+ handleHotUpdate: (context) => {
230
+ const key = posix(resolve(context.file));
231
+ const waiting = this.#waiting.get(key);
232
+ if (!waiting)
233
+ return;
234
+ // The pages compiled with the file (plugin-vue added them): Vite invalidates them only
235
+ // after every plugin, and the waiting request must not get them as compiled before.
236
+ const graphs = context.server.environments
237
+ ? Object.values(context.server.environments).map((environment) => environment.moduleGraph)
238
+ : [context.server.moduleGraph];
239
+ const pages = new Set();
240
+ for (const module of context.modules)
241
+ if (typeof module.file === 'string' && posix(module.file) !== key)
242
+ pages.add(module.file);
243
+ for (const page of pages)
244
+ for (const graph of graphs)
245
+ graph?.onFileChange?.(page);
246
+ if (this.#logger.isEnabled('debug'))
247
+ this.#logger.log('debug', 'Vite handled a changed type file a request waits for', {
248
+ file: key,
249
+ pages: [...pages],
250
+ });
251
+ for (const done of [...waiting])
252
+ done();
253
+ },
254
+ };
255
+ }
256
+ }
147
257
  /** What TypeScript's `ts.sys` gives the compiler, on node:fs (no TypeScript needed). */
148
258
  const NODE_FS = {
149
259
  fileExists: (file) => statSync(file, { throwIfNoEntry: false })?.isFile() === true,
@@ -65,6 +65,8 @@ export declare class ServedFiles {
65
65
  mode?: string;
66
66
  configFileDependencies?: readonly string[];
67
67
  }): void;
68
+ /** Whether `file` has a record for `environment` (D-0295: `types`, the files Vue's compiler read). */
69
+ has(file: string, environment: string): boolean;
68
70
  /** Whether an event for `file` is no change (dropped); a change updates the records. */
69
71
  stale(file: string, event: string): boolean;
70
72
  /** The Vite whose module graphs and watcher a sweep uses (Vite's `configureServer`). */
@@ -116,6 +116,10 @@ export class ServedFiles {
116
116
  for (const file of config.configFileDependencies ?? [])
117
117
  this.record(file, STARTUP);
118
118
  }
119
+ /** Whether `file` has a record for `environment` (D-0295: `types`, the files Vue's compiler read). */
120
+ has(file, environment) {
121
+ return this.#records.get(normal(file))?.has(environment) === true;
122
+ }
119
123
  /** Whether an event for `file` is no change (dropped); a change updates the records. */
120
124
  stale(file, event) {
121
125
  const path = normal(file);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dokebi/template-inertia",
3
- "version": "0.4.24",
3
+ "version": "0.4.26",
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",
@@ -156,7 +156,7 @@
156
156
  "@dokebi/session": "0.4.11",
157
157
  "@dokebi/web": "0.4.27",
158
158
  "@dokebi/websocket": "0.4.10",
159
- "@dokebi/websocket-hub": "0.4.5",
159
+ "@dokebi/websocket-hub": "0.4.6",
160
160
  "@inertiajs/vue3": "3.9.1",
161
161
  "vue": "3.5.44"
162
162
  },