@dokebi/template-inertia 0.4.19 → 0.4.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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'] !== this.options.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', this.options.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: this.options.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 ? await this.#serverRender(JSON.parse(json), rootId) : undefined;
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
- const result = await ssr.render(page);
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') ||
@@ -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>;
@@ -0,0 +1,365 @@
1
+ // D-0291 §7: `dokebi template build` — builds a template folder (`views/<template>/` shape:
2
+ // Layout.vue, Pages/**/*.vue, the components and styles they import) into a bundle
3
+ // (template-bundle.ts) apart from any app. Runs in the template repository, with the project's own
4
+ // Vite and @vitejs/plugin-vue: one browser build and one server build, an entry per page, the
5
+ // shared modules (vue, @inertiajs/vue3, the app's SDK, …) left as imports, then the manifest with
6
+ // each page's files, stylesheets, preloads and `meta`, and the sha256 of every file. The bundle
7
+ // is checked like the app will check it before it is returned.
8
+ import { existsSync, readFileSync, realpathSync } from 'node:fs';
9
+ import { lstat, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
10
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
11
+ import { pathToFileURL } from 'node:url';
12
+ import { ConsoleLogger } from '@dokebi/core';
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';
15
+ import { packageVersion } from './template-shared.js';
16
+ import { registerVueTypeScript } from './vue-typescript.js';
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.21' };
19
+ function defaultLogger() {
20
+ return new ConsoleLogger({ level: 'info' }, { plugin: 'dokebi-template-inertia', process: 'template-build' });
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
+ };
29
+ /** `a` is `b` or inside it. */
30
+ function within(a, b) {
31
+ const path = relative(b, a);
32
+ return path === '' || (!path.startsWith('..') && !isAbsolute(path));
33
+ }
34
+ /** The ESM entry file of an installed package of the project (exports `.` → import/default, else module/main). */
35
+ export function packageEntry(root, name) {
36
+ for (let dir = resolve(root);; dir = dirname(dir)) {
37
+ const folder = join(dir, 'node_modules', name);
38
+ const file = join(folder, 'package.json');
39
+ if (existsSync(file)) {
40
+ const json = JSON.parse(readFileSync(file, 'utf8'));
41
+ const pick = (value) => {
42
+ if (typeof value === 'string')
43
+ return value;
44
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
45
+ return undefined;
46
+ const record = value;
47
+ if ('.' in record)
48
+ return pick(record['.']);
49
+ return pick(record.import) ?? pick(record.default) ?? pick(record.node);
50
+ };
51
+ const entry = pick(json.exports) ?? json.module ?? json.main ?? 'index.js';
52
+ return join(folder, entry);
53
+ }
54
+ if (dirname(dir) === dir)
55
+ return undefined;
56
+ }
57
+ }
58
+ async function importPackage(root, name, fix) {
59
+ const entry = packageEntry(root, name);
60
+ if (entry === undefined)
61
+ throw new InertiaError('TEMPLATE_BUILD_FAILED', `${name} is not installed in ${root}`, {
62
+ fix,
63
+ });
64
+ return (await import(pathToFileURL(entry).href));
65
+ }
66
+ /** The pages of a template folder: `Layout` and `Pages/<path>` → their .vue file. */
67
+ export async function templatePages(folder) {
68
+ const pages = new Map();
69
+ const layout = join(folder, 'Layout.vue');
70
+ if (existsSync(layout))
71
+ pages.set('Layout', layout);
72
+ const walk = async (dir) => {
73
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
74
+ const path = join(dir, entry.name);
75
+ if (entry.isDirectory())
76
+ await walk(path);
77
+ else if (entry.isFile() && entry.name.endsWith('.vue')) {
78
+ const key = relative(folder, path).split(sep).join('/').slice(0, -'.vue'.length);
79
+ if (!TEMPLATE_PAGE.test(key))
80
+ throw usage(`${relative(folder, path)} is not a page name: Pages/ paths are letters, digits, _, . and - (at most 16 folders deep)`);
81
+ pages.set(key, path);
82
+ }
83
+ }
84
+ };
85
+ if (existsSync(join(folder, 'Pages')))
86
+ await walk(join(folder, 'Pages'));
87
+ return pages;
88
+ }
89
+ /** Every file under a folder, relative with `/`. */
90
+ async function listFiles(dir, root = dir, found = []) {
91
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
92
+ const path = join(dir, entry.name);
93
+ if (entry.isDirectory())
94
+ await listFiles(path, root, found);
95
+ else if (entry.isFile())
96
+ found.push(relative(root, path).split(sep).join('/'));
97
+ }
98
+ return found;
99
+ }
100
+ const outputs = (result) => (Array.isArray(result) ? result : [result]).flatMap((item) => item.output ?? []);
101
+ /**
102
+ * Builds the template folder `options.dir` of `options.root` into a bundle at `options.out`
103
+ * (D-0291). Throws INVALID_TEMPLATE_BUILD for wrong options and TEMPLATE_BUILD_FAILED for a
104
+ * build that fails, with the cause.
105
+ */
106
+ export async function buildTemplateBundle(options) {
107
+ const begin = performance.now();
108
+ const logger = options.logger ?? defaultLogger();
109
+ const root = resolve(options.root ?? process.cwd());
110
+ if (typeof options.dir !== 'string' || options.dir === '')
111
+ throw usage('dir is required');
112
+ const folder = resolve(root, options.dir);
113
+ if (!within(folder, root) || folder === root)
114
+ throw usage(`${options.dir} must be a folder inside ${root}, not the project itself`);
115
+ if (!existsSync(folder) || !(await stat(folder)).isDirectory())
116
+ throw usage(`${options.dir} is not a folder`);
117
+ const name = options.name ?? basename(folder);
118
+ if (!TEMPLATE_NAME.test(name))
119
+ throw usage(`${name} is not a template name (^[a-z][a-z0-9-]{0,31}$); pass --name`);
120
+ let version = options.version;
121
+ if (version === undefined) {
122
+ try {
123
+ const own = JSON.parse(await readFile(join(root, 'package.json'), 'utf8'));
124
+ if (typeof own.version === 'string')
125
+ version = own.version;
126
+ }
127
+ catch (error) {
128
+ // No readable package.json: --version is needed (the usage error below says so).
129
+ logger.log('debug', 'Template version not read from package.json', {
130
+ root,
131
+ error: error.message,
132
+ });
133
+ }
134
+ }
135
+ if (version === undefined || !TEMPLATE_VERSION.test(version))
136
+ throw usage(`the template version ${version === undefined ? 'is missing' : `${version} is not letters, digits, . + -`}: pass --version or set version in package.json`);
137
+ const own = options.shared ?? [];
138
+ for (const module of own)
139
+ if (typeof module !== 'string' || !SHARED_SPECIFIER.test(module))
140
+ throw new InertiaUsageError('INVALID_TEMPLATE_SHARED', `--shared ${String(module)} is not a package name with an optional subpath`);
141
+ const shared = [...new Set([...SHARED_DEFAULTS, ...own])];
142
+ const out = resolve(root, options.out ?? join('dist', 'template', name));
143
+ if (!within(out, root) || within(root, out) || within(folder, out) || within(out, folder))
144
+ 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)`);
145
+ if (existsSync(out)) {
146
+ const info = await lstat(out);
147
+ if (!info.isDirectory())
148
+ throw usage(`--out ${out} is not a folder`);
149
+ const present = await readdir(out);
150
+ if (present.length && !present.includes(TEMPLATE_MANIFEST))
151
+ throw usage(`--out ${out} holds files and no ${TEMPLATE_MANIFEST}: it is not an earlier bundle, so it is not emptied`);
152
+ await rm(out, { recursive: true, force: true });
153
+ }
154
+ const pages = await templatePages(folder);
155
+ if (pages.size === 0)
156
+ throw usage(`${options.dir} has no Layout.vue and no Pages/**/*.vue`);
157
+ const input = Object.fromEntries(pages);
158
+ const vite = await importPackage(root, 'vite', 'Install Vite in the template repository: npm install --save-dev vite');
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
172
+ ? undefined
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);
175
+ const isShared = (id) => shared.includes(id);
176
+ logger.log('info', 'Template bundle build started', {
177
+ code: 'INERTIA_TEMPLATE_BUILD_STARTED',
178
+ name,
179
+ version,
180
+ dir: relative(root, folder),
181
+ out: relative(root, out),
182
+ pages: pages.size,
183
+ shared,
184
+ });
185
+ const common = {
186
+ root,
187
+ configFile: configFile ?? false,
188
+ logLevel: 'warn',
189
+ publicDir: false,
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 } })] : [],
192
+ };
193
+ const imported = new Set();
194
+ const collect = (items) => {
195
+ for (const item of items)
196
+ for (const id of [...(item.imports ?? []), ...(item.dynamicImports ?? [])])
197
+ if (isShared(id))
198
+ imported.add(id);
199
+ };
200
+ let browserItems;
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;
205
+ try {
206
+ browserItems = outputs(await vite.build({
207
+ ...common,
208
+ base: './',
209
+ build: {
210
+ outDir: join(out, 'browser'),
211
+ emptyOutDir: true,
212
+ manifest: true,
213
+ cssCodeSplit: true,
214
+ modulePreload: false,
215
+ copyPublicDir: false,
216
+ rollupOptions: {
217
+ input,
218
+ external: isShared,
219
+ preserveEntrySignatures: 'strict',
220
+ output: {
221
+ entryFileNames: 'pages/[name]-[hash].js',
222
+ chunkFileNames: 'chunks/[name]-[hash].js',
223
+ assetFileNames: 'assets/[name]-[hash][extname]',
224
+ },
225
+ },
226
+ },
227
+ }));
228
+ serverItems = outputs(await vite.build({
229
+ ...common,
230
+ ssr: { noExternal: true },
231
+ build: {
232
+ ssr: true,
233
+ outDir: join(out, 'ssr'),
234
+ emptyOutDir: true,
235
+ copyPublicDir: false,
236
+ rollupOptions: {
237
+ input,
238
+ external: isShared,
239
+ preserveEntrySignatures: 'strict',
240
+ output: {
241
+ format: 'es',
242
+ entryFileNames: 'pages/[name].js',
243
+ chunkFileNames: 'chunks/[name]-[hash].js',
244
+ },
245
+ },
246
+ },
247
+ }));
248
+ }
249
+ catch (cause) {
250
+ throw new InertiaError('TEMPLATE_BUILD_FAILED', `The Vite build of ${name} failed`, { cause });
251
+ }
252
+ finally {
253
+ if (environment === undefined)
254
+ delete process.env.NODE_ENV;
255
+ else
256
+ process.env.NODE_ENV = environment;
257
+ }
258
+ collect(browserItems);
259
+ collect(serverItems);
260
+ // The browser manifest gives each page its stylesheets and the chunks it imports.
261
+ const manifestPath = join(out, 'browser', '.vite', 'manifest.json');
262
+ const vm = JSON.parse(await readFile(manifestPath, 'utf8'));
263
+ await rm(join(out, 'browser', '.vite'), { recursive: true, force: true });
264
+ const byName = new Map();
265
+ for (const entry of Object.values(vm))
266
+ if (entry.isEntry && entry.name)
267
+ byName.set(entry.name, entry);
268
+ const server = new Map();
269
+ for (const item of serverItems)
270
+ if (item.type === 'chunk' && item.isEntry && item.name)
271
+ server.set(item.name, item.fileName);
272
+ const pageEntries = {};
273
+ for (const page of pages.keys()) {
274
+ const entry = byName.get(page);
275
+ const ssrFile = server.get(page);
276
+ if (entry === undefined || ssrFile === undefined)
277
+ throw new InertiaError('TEMPLATE_BUILD_FAILED', `The build has no entry for ${page} (browser ${entry ? 'yes' : 'no'}, server ${ssrFile ? 'yes' : 'no'})`);
278
+ const css = [];
279
+ const preload = [];
280
+ const seen = new Set();
281
+ const visit = (key) => {
282
+ if (seen.has(key))
283
+ return;
284
+ seen.add(key);
285
+ const chunk = vm[key];
286
+ if (!chunk)
287
+ return;
288
+ for (const next of chunk.imports ?? [])
289
+ visit(next);
290
+ if (chunk !== entry)
291
+ preload.push(`browser/${chunk.file}`);
292
+ for (const file of chunk.css ?? [])
293
+ if (!css.includes(`browser/${file}`))
294
+ css.push(`browser/${file}`);
295
+ };
296
+ const key = Object.keys(vm).find((candidate) => vm[candidate] === entry);
297
+ visit(key);
298
+ let meta;
299
+ try {
300
+ const module = (await import(`${pathToFileURL(join(out, 'ssr', ssrFile)).href}?build=${Date.now()}`));
301
+ meta = module.meta;
302
+ }
303
+ catch (cause) {
304
+ throw new InertiaError('TEMPLATE_BUILD_FAILED', `The server module of ${page} could not be imported to read its meta: ${cause.message}`, { cause });
305
+ }
306
+ if (meta !== undefined) {
307
+ if (!jsonValue(meta))
308
+ throw new InertiaError('TEMPLATE_BUILD_FAILED', `${page} exports a meta that is not JSON data`);
309
+ if (Buffer.byteLength(JSON.stringify(meta)) > PAGE_META_MAX_BYTES)
310
+ throw new InertiaError('TEMPLATE_BUILD_FAILED', `${page} exports a meta larger than ${PAGE_META_MAX_BYTES} bytes`);
311
+ }
312
+ pageEntries[page] = {
313
+ browser: `browser/${entry.file}`,
314
+ css,
315
+ preload,
316
+ ssr: `ssr/${ssrFile}`,
317
+ ...(meta === undefined ? {} : { meta }),
318
+ };
319
+ }
320
+ const files = {};
321
+ for (const top of ['browser', 'ssr'])
322
+ for (const file of await listFiles(join(out, top))) {
323
+ const content = await readFile(join(out, top, file));
324
+ files[`${top}/${file}`] = { bytes: content.length, sha256: sha256(content) };
325
+ }
326
+ const manifest = {
327
+ format: TEMPLATE_FORMAT,
328
+ name,
329
+ version,
330
+ builtWith: BUILDER.version,
331
+ shared: Object.fromEntries([...imported].sort().map((module) => [module, packageVersion(root, module)])),
332
+ pages: pageEntries,
333
+ files,
334
+ };
335
+ await writeFile(join(out, TEMPLATE_MANIFEST), `${JSON.stringify(manifest, null, 2)}\n`);
336
+ const check = await checkTemplateBundle(out, {
337
+ maxBytes: options.maxBytes ?? TEMPLATE_MAX_BYTES,
338
+ });
339
+ if (check.problems.length || check.buildId === undefined)
340
+ throw new InertiaError('TEMPLATE_BUILD_FAILED', `The built bundle does not pass its own check: ${check.problems.map((problem) => problem.message).join('; ')}`);
341
+ const result = {
342
+ out,
343
+ name,
344
+ version,
345
+ buildId: check.buildId,
346
+ pages: Object.keys(pageEntries),
347
+ shared: manifest.shared,
348
+ files: Object.keys(files).length,
349
+ bytes: check.bytes,
350
+ ms: Math.round(performance.now() - begin),
351
+ };
352
+ logger.log('info', 'Template bundle built', {
353
+ code: 'INERTIA_TEMPLATE_BUILT',
354
+ name,
355
+ version,
356
+ buildId: result.buildId,
357
+ out: relative(root, out),
358
+ pages: result.pages.length,
359
+ files: result.files,
360
+ bytes: result.bytes,
361
+ shared: manifest.shared,
362
+ ms: result.ms,
363
+ });
364
+ return result;
365
+ }
@@ -0,0 +1,102 @@
1
+ /** The manifest file of a bundle. */
2
+ export declare const TEMPLATE_MANIFEST = "dokebi-template.json";
3
+ /** The signature file of a bundle (optional; its form is the app's). */
4
+ export declare const TEMPLATE_SIGNATURE = "dokebi-template.sig";
5
+ /** The manifest format this version writes and reads. */
6
+ export declare const TEMPLATE_FORMAT = 1;
7
+ /** A template name: the folder name of `views/<template>/` and `domains.<host>.template`. */
8
+ export declare const TEMPLATE_NAME: RegExp;
9
+ /** A template version (the template repository's): 1 to 64 of letters, digits, `.`, `+`, `-`. */
10
+ export declare const TEMPLATE_VERSION: RegExp;
11
+ /** A page of a bundle: `Layout`, or `Pages/<path>` without the `.vue`. */
12
+ export declare const TEMPLATE_PAGE: RegExp;
13
+ /** A shared module specifier: a package name with an optional subpath. */
14
+ export declare const SHARED_SPECIFIER: RegExp;
15
+ /** A page's `meta` (JSON) may take this many bytes. */
16
+ export declare const PAGE_META_MAX_BYTES = 4096;
17
+ /** Default limits of one bundle. */
18
+ export declare const TEMPLATE_MAX_BYTES: number;
19
+ export declare const TEMPLATE_MAX_FILES = 4096;
20
+ /**
21
+ * The shared modules every bundle may import and every app build provides (when it opts in with
22
+ * `dokebiInertia({ templates })`). `vue/server-renderer` is provided by the server build only.
23
+ */
24
+ export declare const SHARED_DEFAULTS: readonly string[];
25
+ /** The defaults the server build alone provides. */
26
+ export declare const SERVER_ONLY_SHARED: readonly string[];
27
+ /** One page of a bundle. */
28
+ export interface TemplatePage {
29
+ /** The browser entry (`browser/pages/…js`). */
30
+ readonly browser: string;
31
+ /** The stylesheets the page needs (its own and its chunks'), in load order. */
32
+ readonly css: readonly string[];
33
+ /** The chunks the browser entry imports, for `modulepreload`. */
34
+ readonly preload: readonly string[];
35
+ /** The server-render module (`ssr/pages/…js`). */
36
+ readonly ssr: string;
37
+ /** What the page exports as `meta` (JSON, at most 4 KiB): the app judges it (a contract). */
38
+ readonly meta?: unknown;
39
+ }
40
+ /** `dokebi-template.json`, format 1. */
41
+ export interface TemplateManifest {
42
+ readonly format: 1;
43
+ readonly name: string;
44
+ readonly version: string;
45
+ /** The @dokebi/template-inertia version that built it. */
46
+ readonly builtWith: string;
47
+ /** The shared modules its code imports → the version of their package when it was built. */
48
+ readonly shared: Readonly<Record<string, string | null>>;
49
+ readonly pages: Readonly<Record<string, TemplatePage>>;
50
+ /** Every file under browser/ and ssr/ → its size and sha256 (hex). */
51
+ readonly files: Readonly<Record<string, {
52
+ readonly bytes: number;
53
+ readonly sha256: string;
54
+ }>>;
55
+ }
56
+ /** What is wrong with a bundle (one entry per problem; the code is stable). */
57
+ export interface TemplateProblem {
58
+ readonly code: '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';
59
+ readonly message: string;
60
+ readonly file?: string;
61
+ readonly page?: string;
62
+ readonly module?: string;
63
+ }
64
+ /** The check of one bundle folder. */
65
+ export interface TemplateCheck {
66
+ /** The manifest, when it could be read and has the right shape. */
67
+ readonly manifest?: TemplateManifest;
68
+ /** The first 12 hex of the manifest's sha256: the same in every process that reads it. */
69
+ readonly buildId?: string;
70
+ /** The bytes of the files under browser/ and ssr/ that were read. */
71
+ readonly bytes: number;
72
+ readonly problems: readonly TemplateProblem[];
73
+ }
74
+ export interface TemplateCheckLimits {
75
+ readonly maxBytes?: number;
76
+ readonly maxFiles?: number;
77
+ }
78
+ /** The JSON `meta` value of a page is plain data (objects, arrays, strings, finite numbers…). */
79
+ export declare function jsonValue(value: unknown, depth?: number): boolean;
80
+ /** The problem of a manifest's shape, or undefined (paths, names, page references). */
81
+ export declare function manifestProblem(value: unknown): string | undefined;
82
+ /** sha256 (hex) of bytes. */
83
+ export declare function sha256(bytes: Uint8Array): string;
84
+ /**
85
+ * Checks one bundle folder: the manifest's shape, every file's size and sha256, no file the
86
+ * manifest does not list (but the manifest and the signature), no link, the limits. Reads only;
87
+ * never throws for what the folder holds (a missing folder is TEMPLATE_MANIFEST_MISSING).
88
+ */
89
+ export declare function checkTemplateBundle(dir: string, limits?: TemplateCheckLimits): Promise<TemplateCheck>;
90
+ /** A shared module the app build provides (its `dokebi-shared.json` entry). */
91
+ export interface ProvidedShared {
92
+ readonly file: string;
93
+ readonly version: string | null;
94
+ }
95
+ /** The major part of a version for compatibility: `3` of 3.5.1, `0.4` of 0.4.19. */
96
+ export declare function compatibleLine(version: string): string | undefined;
97
+ /**
98
+ * The problems of a bundle's shared modules against what an app build provides: a module the app
99
+ * does not provide, or one whose package is another major (0.x: minor) than the bundle was built
100
+ * with. A version unknown on either side (a local alias) is not compared.
101
+ */
102
+ export declare function sharedProblems(bundle: Readonly<Record<string, string | null>>, provided: Readonly<Record<string, ProvidedShared>>): TemplateProblem[];