@dokebi/template-inertia 0.4.20 → 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 +41 -4
- package/README.md +1 -1
- package/dist/errors.d.ts +1 -1
- package/dist/errors.js +2 -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.js +35 -5
- package/dist/template-runtime.d.ts +145 -0
- package/dist/template-runtime.js +723 -0
- package/dist/template-shared.d.ts +6 -0
- package/dist/template-shared.js +36 -2
- package/dist/template.d.ts +1 -1
- package/dist/template.js +1 -1
- package/dist/vite-plugin.js +3 -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 +1 -1
- package/templates/shared.ts +4 -0
package/dist/responder.js
CHANGED
|
@@ -323,16 +323,20 @@ export class InertiaResponder {
|
|
|
323
323
|
withShared = true) {
|
|
324
324
|
vary(reply);
|
|
325
325
|
const inertia = request.headers['x-inertia'] === 'true';
|
|
326
|
+
// D-0291: a template bundle of this request's template: its build is part of the version, so
|
|
327
|
+
// a page opened before a swap reloads on its next visit.
|
|
328
|
+
const template = this.hooks.template?.(request, this.options.version);
|
|
329
|
+
const version = template?.version ?? this.options.version;
|
|
326
330
|
// The protocol's version check is for GET visits only (the official adapters'): the 409 makes
|
|
327
331
|
// the client load X-Inertia-Location, so an error page of a POST must not turn into a GET.
|
|
328
332
|
if (inertia &&
|
|
329
333
|
(request.method === 'GET' || request.method === 'HEAD') &&
|
|
330
334
|
request.headers['x-inertia-version'] !== undefined &&
|
|
331
|
-
request.headers['x-inertia-version'] !==
|
|
335
|
+
request.headers['x-inertia-version'] !== version) {
|
|
332
336
|
return reply
|
|
333
337
|
.code(409)
|
|
334
338
|
.header('X-Inertia-Location', ownLocation(request.url))
|
|
335
|
-
.header('X-Inertia-Version',
|
|
339
|
+
.header('X-Inertia-Version', version)
|
|
336
340
|
.send();
|
|
337
341
|
}
|
|
338
342
|
// A sealed request (seal host, D-0062): the props leave as one sealed frame, never as HTML,
|
|
@@ -436,7 +440,7 @@ export class InertiaResponder {
|
|
|
436
440
|
component,
|
|
437
441
|
props: resolved,
|
|
438
442
|
url: request.url,
|
|
439
|
-
version
|
|
443
|
+
version,
|
|
440
444
|
clearHistory,
|
|
441
445
|
encryptHistory,
|
|
442
446
|
...meta.page,
|
|
@@ -498,10 +502,12 @@ export class InertiaResponder {
|
|
|
498
502
|
const frame = sealer.encode(json);
|
|
499
503
|
return reply
|
|
500
504
|
.type('text/html; charset=utf-8')
|
|
501
|
-
.send(`<!doctype html><html${htmlLanguage}><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${escapeHtml(title)}</title>${nonceMeta}${head?.tags ?? ''}${styles.map((url) => `<link rel="stylesheet" href="${escapeHtml(url)}">`).join('')}${boot?.head ?? ''}${moduleScripts}</head><body><script data-page="${rootId}" type="application/json" data-sealed="true">${escapeHtml(frame)}</script><div id="${rootId}">${boot?.root ?? ''}</div></body></html>`);
|
|
505
|
+
.send(`<!doctype html><html${htmlLanguage}><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${escapeHtml(title)}</title>${nonceMeta}${head?.tags ?? ''}${styles.map((url) => `<link rel="stylesheet" href="${escapeHtml(url)}">`).join('')}${boot?.head ?? ''}${template?.head(component, cspNonce ?? '') ?? ''}${moduleScripts}</head><body><script data-page="${rootId}" type="application/json" data-sealed="true">${escapeHtml(frame)}</script><div id="${rootId}">${boot?.root ?? ''}</div></body></html>`);
|
|
502
506
|
}
|
|
503
507
|
// Only the first HTML is server rendered; Inertia visits above stay JSON.
|
|
504
|
-
const rendered = this.ssr
|
|
508
|
+
const rendered = this.ssr
|
|
509
|
+
? await this.#serverRender(JSON.parse(json), rootId, template)
|
|
510
|
+
: undefined;
|
|
505
511
|
if (publicPage !== undefined) {
|
|
506
512
|
if (publicPage.cacheControl !== undefined) {
|
|
507
513
|
reply.header('Cache-Control', publicPage.cacheControl);
|
|
@@ -531,7 +537,7 @@ export class InertiaResponder {
|
|
|
531
537
|
const sealHost = sealer ? SEAL_HOST_META : '';
|
|
532
538
|
return reply
|
|
533
539
|
.type('text/html; charset=utf-8')
|
|
534
|
-
.send(`<!doctype html><html${htmlLanguage}><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">${sealHost}${titled ? '' : `<title>${escapeHtml(title)}</title>`}${nonceMeta}${head?.tags ?? ''}${styles.map((url) => `<link rel="stylesheet" href="${escapeHtml(url)}">`).join('')}${rendered ? '' : (boot?.head ?? '')}${moduleScripts}${ssrHead.join('')}</head><body>${rendered?.body ?? `<script data-page="${rootId}" type="application/json">${safeJson}</script><div id="${rootId}">${boot?.root ?? ''}</div>`}</body></html>`);
|
|
540
|
+
.send(`<!doctype html><html${htmlLanguage}><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">${sealHost}${titled ? '' : `<title>${escapeHtml(title)}</title>`}${nonceMeta}${head?.tags ?? ''}${styles.map((url) => `<link rel="stylesheet" href="${escapeHtml(url)}">`).join('')}${rendered ? '' : (boot?.head ?? '')}${template?.head(component, cspNonce ?? '') ?? ''}${moduleScripts}${ssrHead.join('')}</head><body>${rendered?.body ?? `<script data-page="${rootId}" type="application/json">${safeJson}</script><div id="${rootId}">${boot?.root ?? ''}</div>`}</body></html>`);
|
|
535
541
|
}
|
|
536
542
|
/**
|
|
537
543
|
* The value of one selected prop. A function runs here; a rescued deferred prop that throws is
|
|
@@ -567,10 +573,14 @@ export class InertiaResponder {
|
|
|
567
573
|
* The SSR bundle's head and root for this page, or undefined to answer client rendered
|
|
568
574
|
* (failure 'fallback'). The page object is a fresh copy, so the bundle cannot change the props.
|
|
569
575
|
*/
|
|
570
|
-
async #serverRender(page, rootId) {
|
|
576
|
+
async #serverRender(page, rootId, template) {
|
|
571
577
|
const ssr = this.ssr;
|
|
572
578
|
try {
|
|
573
|
-
|
|
579
|
+
// D-0291: under the template's bundle; a bundle page that fails is set aside and the
|
|
580
|
+
// render runs once more with the app's own page.
|
|
581
|
+
const result = template
|
|
582
|
+
? await template.render(() => Promise.resolve(ssr.render(page)), page.component)
|
|
583
|
+
: await ssr.render(page);
|
|
574
584
|
const { head, body } = (result ?? {});
|
|
575
585
|
if (!Array.isArray(head) ||
|
|
576
586
|
head.some((tag) => typeof tag !== 'string') ||
|
package/dist/template-build.js
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
// shared modules (vue, @inertiajs/vue3, the app's SDK, …) left as imports, then the manifest with
|
|
6
6
|
// each page's files, stylesheets, preloads and `meta`, and the sha256 of every file. The bundle
|
|
7
7
|
// is checked like the app will check it before it is returned.
|
|
8
|
-
import { existsSync, readFileSync } from 'node:fs';
|
|
8
|
+
import { existsSync, readFileSync, realpathSync } from 'node:fs';
|
|
9
9
|
import { lstat, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
|
|
10
10
|
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
11
11
|
import { pathToFileURL } from 'node:url';
|
|
@@ -13,12 +13,19 @@ import { ConsoleLogger } from '@dokebi/core';
|
|
|
13
13
|
import { InertiaError, InertiaUsageError } from './errors.js';
|
|
14
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';
|
|
15
15
|
import { packageVersion } from './template-shared.js';
|
|
16
|
+
import { registerVueTypeScript } from './vue-typescript.js';
|
|
16
17
|
/** The builder written into `builtWith` (scripts/testing/check-metadata.mjs keeps it the package version). */
|
|
17
|
-
const BUILDER = { name: 'dokebi-template-inertia', version: '0.4.
|
|
18
|
+
const BUILDER = { name: 'dokebi-template-inertia', version: '0.4.21' };
|
|
18
19
|
function defaultLogger() {
|
|
19
20
|
return new ConsoleLogger({ level: 'info' }, { plugin: 'dokebi-template-inertia', process: 'template-build' });
|
|
20
21
|
}
|
|
21
22
|
const usage = (message) => new InertiaUsageError('INVALID_TEMPLATE_BUILD', message);
|
|
23
|
+
/** The file access of the Vue compiler for imported props types (TypeScript 7 has none of its own). */
|
|
24
|
+
const VUE_TYPE_FILES = {
|
|
25
|
+
fileExists: (file) => existsSync(file),
|
|
26
|
+
readFile: (file) => readFileSync(file, 'utf8'),
|
|
27
|
+
realpath: (file) => realpathSync(file),
|
|
28
|
+
};
|
|
22
29
|
/** `a` is `b` or inside it. */
|
|
23
30
|
function within(a, b) {
|
|
24
31
|
const path = relative(b, a);
|
|
@@ -149,9 +156,22 @@ export async function buildTemplateBundle(options) {
|
|
|
149
156
|
throw usage(`${options.dir} has no Layout.vue and no Pages/**/*.vue`);
|
|
150
157
|
const input = Object.fromEntries(pages);
|
|
151
158
|
const vite = await importPackage(root, 'vite', 'Install Vite in the template repository: npm install --save-dev vite');
|
|
152
|
-
|
|
159
|
+
// The project's vite config (--config) may bring its own Vue plugin; otherwise one is added.
|
|
160
|
+
const configFile = options.config ? resolve(root, options.config) : undefined;
|
|
161
|
+
let ownVue = false;
|
|
162
|
+
if (configFile) {
|
|
163
|
+
const loaded = (await vite.loadConfigFromFile({ command: 'build', mode: 'production' }, configFile, root)) ?? {
|
|
164
|
+
config: {},
|
|
165
|
+
};
|
|
166
|
+
const names = (loaded.config.plugins ?? [])
|
|
167
|
+
.flat(Infinity)
|
|
168
|
+
.map((plugin) => plugin?.name);
|
|
169
|
+
ownVue = names.includes('vite:vue');
|
|
170
|
+
}
|
|
171
|
+
const vue = ownVue
|
|
153
172
|
? undefined
|
|
154
173
|
: await importPackage(root, '@vitejs/plugin-vue', 'Install the Vue plugin in the template repository: npm install --save-dev @vitejs/plugin-vue');
|
|
174
|
+
registerVueTypeScript(root, logger);
|
|
155
175
|
const isShared = (id) => shared.includes(id);
|
|
156
176
|
logger.log('info', 'Template bundle build started', {
|
|
157
177
|
code: 'INERTIA_TEMPLATE_BUILD_STARTED',
|
|
@@ -164,10 +184,11 @@ export async function buildTemplateBundle(options) {
|
|
|
164
184
|
});
|
|
165
185
|
const common = {
|
|
166
186
|
root,
|
|
167
|
-
configFile:
|
|
187
|
+
configFile: configFile ?? false,
|
|
168
188
|
logLevel: 'warn',
|
|
169
189
|
publicDir: false,
|
|
170
|
-
|
|
190
|
+
// The compiler reads the props types a page imports from files (as the app's vite config does).
|
|
191
|
+
plugins: vue ? [vue.default({ script: { fs: VUE_TYPE_FILES } })] : [],
|
|
171
192
|
};
|
|
172
193
|
const imported = new Set();
|
|
173
194
|
const collect = (items) => {
|
|
@@ -178,6 +199,9 @@ export async function buildTemplateBundle(options) {
|
|
|
178
199
|
};
|
|
179
200
|
let browserItems;
|
|
180
201
|
let serverItems;
|
|
202
|
+
// `vite build` sets process.env.NODE_ENV to production: a caller in the same process (a
|
|
203
|
+
// test, a script that builds and then serves) gets it back as it was.
|
|
204
|
+
const environment = process.env.NODE_ENV;
|
|
181
205
|
try {
|
|
182
206
|
browserItems = outputs(await vite.build({
|
|
183
207
|
...common,
|
|
@@ -225,6 +249,12 @@ export async function buildTemplateBundle(options) {
|
|
|
225
249
|
catch (cause) {
|
|
226
250
|
throw new InertiaError('TEMPLATE_BUILD_FAILED', `The Vite build of ${name} failed`, { cause });
|
|
227
251
|
}
|
|
252
|
+
finally {
|
|
253
|
+
if (environment === undefined)
|
|
254
|
+
delete process.env.NODE_ENV;
|
|
255
|
+
else
|
|
256
|
+
process.env.NODE_ENV = environment;
|
|
257
|
+
}
|
|
228
258
|
collect(browserItems);
|
|
229
259
|
collect(serverItems);
|
|
230
260
|
// The browser manifest gives each page its stylesheets and the chunks it imports.
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import type { Logger } from '@dokebi/core';
|
|
2
|
+
import type { FastifyReply, FastifyRequest } from 'fastify';
|
|
3
|
+
import { type TemplateManifest } from './template-bundle.js';
|
|
4
|
+
/** The URL prefix of bundle files (one route for every app, template and generation). */
|
|
5
|
+
export declare const TEMPLATE_FILES_PREFIX = "/_dokebi/templates/";
|
|
6
|
+
/** The registry `templatePages()` reads during server rendering (no imports there). */
|
|
7
|
+
export declare const TEMPLATE_REGISTRY: unique symbol;
|
|
8
|
+
/** `templates.<app>.<template>` of the options. */
|
|
9
|
+
export interface TemplateSource {
|
|
10
|
+
readonly path: string;
|
|
11
|
+
}
|
|
12
|
+
/** The template part of the options. */
|
|
13
|
+
export interface TemplateSettings {
|
|
14
|
+
readonly templates: Readonly<Record<string, Readonly<Record<string, TemplateSource>>>>;
|
|
15
|
+
readonly checkMs: number;
|
|
16
|
+
readonly maxBytes: number;
|
|
17
|
+
readonly keep: number;
|
|
18
|
+
readonly verifyTimeoutMs: number;
|
|
19
|
+
readonly cacheDir: string;
|
|
20
|
+
}
|
|
21
|
+
/** What the app's `verifyTemplate` receives. */
|
|
22
|
+
export interface TemplateVerifyInput {
|
|
23
|
+
readonly app: string;
|
|
24
|
+
readonly template: string;
|
|
25
|
+
/** The configured bundle folder (the mount). */
|
|
26
|
+
readonly path: string;
|
|
27
|
+
readonly buildId: string;
|
|
28
|
+
readonly manifest: TemplateManifest;
|
|
29
|
+
/** `dokebi-template.sig` as it was read with the manifest, or undefined. */
|
|
30
|
+
readonly signature: Buffer | undefined;
|
|
31
|
+
/** A file of the checked copy (`dokebi-template.json`, `browser/…`, `ssr/…`). */
|
|
32
|
+
read(file: string): Promise<Buffer>;
|
|
33
|
+
}
|
|
34
|
+
/** What it answers. */
|
|
35
|
+
export type TemplateVerifyResult = {
|
|
36
|
+
readonly accept: true;
|
|
37
|
+
readonly rejectPages?: readonly {
|
|
38
|
+
readonly page: string;
|
|
39
|
+
readonly reason: string;
|
|
40
|
+
}[];
|
|
41
|
+
} | {
|
|
42
|
+
readonly accept: false;
|
|
43
|
+
readonly reason: string;
|
|
44
|
+
};
|
|
45
|
+
export type VerifyTemplate = (bundle: TemplateVerifyInput) => TemplateVerifyResult | Promise<TemplateVerifyResult>;
|
|
46
|
+
/** The app build a template's bundle joins (from the app's Inertia scope). */
|
|
47
|
+
export interface TemplateAppBuild {
|
|
48
|
+
/** `vite.base` of the app (the URL prefix of its built files). */
|
|
49
|
+
readonly base: string;
|
|
50
|
+
/** `vite.manifest`: dokebi-shared.json is beside it. */
|
|
51
|
+
readonly manifest: string;
|
|
52
|
+
/** `ssr.bundle`, when the app renders on the server. */
|
|
53
|
+
readonly ssrBundle?: string;
|
|
54
|
+
}
|
|
55
|
+
interface PageUrls {
|
|
56
|
+
readonly js: string;
|
|
57
|
+
readonly css: readonly string[];
|
|
58
|
+
readonly preload: readonly string[];
|
|
59
|
+
}
|
|
60
|
+
/** One loaded bundle of one app's template. */
|
|
61
|
+
export declare class TemplateGeneration {
|
|
62
|
+
#private;
|
|
63
|
+
readonly app: string;
|
|
64
|
+
readonly template: string;
|
|
65
|
+
readonly buildId: string;
|
|
66
|
+
readonly manifest: TemplateManifest;
|
|
67
|
+
/** The checked copy in the cache. */
|
|
68
|
+
readonly dir: string;
|
|
69
|
+
/** Accepted pages → their URLs. */
|
|
70
|
+
readonly pages: ReadonlyMap<string, PageUrls>;
|
|
71
|
+
/** Accepted pages → their server modules (empty without server rendering). */
|
|
72
|
+
readonly server: ReadonlyMap<string, Readonly<Record<string, unknown>>>;
|
|
73
|
+
readonly importMap: Readonly<Record<string, string>>;
|
|
74
|
+
/** Pages the app's check refused. */
|
|
75
|
+
readonly rejected: readonly string[];
|
|
76
|
+
readonly setAside: Set<string>;
|
|
77
|
+
constructor(app: string, template: string, buildId: string, manifest: TemplateManifest,
|
|
78
|
+
/** The checked copy in the cache. */
|
|
79
|
+
dir: string,
|
|
80
|
+
/** Accepted pages → their URLs. */
|
|
81
|
+
pages: ReadonlyMap<string, PageUrls>,
|
|
82
|
+
/** Accepted pages → their server modules (empty without server rendering). */
|
|
83
|
+
server: ReadonlyMap<string, Readonly<Record<string, unknown>>>, importMap: Readonly<Record<string, string>>,
|
|
84
|
+
/** Pages the app's check refused. */
|
|
85
|
+
rejected: readonly string[]);
|
|
86
|
+
/** The page table of the first HTML (JSON, without the pages set aside). */
|
|
87
|
+
table(): string;
|
|
88
|
+
/** Leaves `page` to the app's own page for the rest of this generation. */
|
|
89
|
+
putAside(page: string): void;
|
|
90
|
+
/** The server module of `page`, unless it is set aside. */
|
|
91
|
+
serverPage(page: string): Readonly<Record<string, unknown>> | undefined;
|
|
92
|
+
}
|
|
93
|
+
/** The part of a template the responder uses for one request. */
|
|
94
|
+
export interface TemplateUse {
|
|
95
|
+
/** The asset version of this request's pages. */
|
|
96
|
+
readonly version: string;
|
|
97
|
+
readonly generation: TemplateGeneration;
|
|
98
|
+
/** The head markup: import map, page table, the first page's stylesheets and preloads. */
|
|
99
|
+
head(component: string, nonce: string): string;
|
|
100
|
+
/**
|
|
101
|
+
* Runs a server render with this generation; when it fails after taking bundle pages, those
|
|
102
|
+
* pages are set aside and it runs once more with the app's own.
|
|
103
|
+
*/
|
|
104
|
+
render<T>(run: () => Promise<T>, component: string): Promise<T>;
|
|
105
|
+
}
|
|
106
|
+
export interface TemplateBundlesOptions {
|
|
107
|
+
readonly logger: Logger;
|
|
108
|
+
readonly settings: TemplateSettings;
|
|
109
|
+
readonly verify: VerifyTemplate | undefined;
|
|
110
|
+
/** `logRepeatWindowMs`: a failure of the same cause is said once per window. */
|
|
111
|
+
readonly repeat: (key: string) => number | false | undefined;
|
|
112
|
+
readonly production?: boolean;
|
|
113
|
+
}
|
|
114
|
+
/** Every app's template bundles. */
|
|
115
|
+
export declare class TemplateBundles {
|
|
116
|
+
#private;
|
|
117
|
+
constructor(options: TemplateBundlesOptions);
|
|
118
|
+
/** The configured template names of an app. */
|
|
119
|
+
templatesOf(app: string): readonly string[];
|
|
120
|
+
/** An app's build, from its Inertia scope (the first scope of an app wins). */
|
|
121
|
+
registerApp(app: string, build: TemplateAppBuild): void;
|
|
122
|
+
/** The apps of `templates` that are not apps (`names`, undefined: no app routing). */
|
|
123
|
+
static unknownApps(settings: TemplateSettings, names: readonly string[] | undefined): string[];
|
|
124
|
+
/** At start: every configured bundle, and the timer. Never throws. */
|
|
125
|
+
start(): Promise<void>;
|
|
126
|
+
/** A reload: the new settings for the next look; the bundles are compared now. */
|
|
127
|
+
update(settings: TemplateSettings): void;
|
|
128
|
+
stop(): void;
|
|
129
|
+
/** The current generation of an app's template, or undefined. */
|
|
130
|
+
current(app: string, template: string | undefined): TemplateGeneration | undefined;
|
|
131
|
+
/** The use of one request: undefined when its template has no bundle. */
|
|
132
|
+
use(app: string, template: string | undefined, baseVersion: string): TemplateUse | undefined;
|
|
133
|
+
/** `GET /_dokebi/templates/<app>/<template>/<buildId>/browser/…` of a kept generation. */
|
|
134
|
+
serve(path: string, reply: FastifyReply): Promise<FastifyReply>;
|
|
135
|
+
/** For tests and describe: the loaded generations. */
|
|
136
|
+
generations(): ReadonlyArray<{
|
|
137
|
+
app: string;
|
|
138
|
+
template: string;
|
|
139
|
+
buildId: string;
|
|
140
|
+
kept: string[];
|
|
141
|
+
}>;
|
|
142
|
+
}
|
|
143
|
+
/** Reads a request's template through web (`templateOf`), for `use`. */
|
|
144
|
+
export type TemplateOf = (request: FastifyRequest) => string | undefined;
|
|
145
|
+
export {};
|