@dokebi/template-inertia 0.4.18 → 0.4.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,344 @@
1
+ // D-0291: the template bundle — a `views/<template>/` folder built apart from the app (Layout.vue,
2
+ // Pages/**, its components, styles), loaded by the app while it runs. This module is the format
3
+ // (manifest `dokebi-template.json`, format 1) and its check; it reads files only, so the build
4
+ // (`dokebi template build`), `dokebi template check` and the app's loader (stage 2) share it.
5
+ //
6
+ // <bundle>/dokebi-template.json the manifest below
7
+ // <bundle>/dokebi-template.sig the signature, in a form the app chooses (read, never judged here)
8
+ // <bundle>/browser/… one ES module entry per page, its chunks and CSS (hashed names)
9
+ // <bundle>/ssr/… the same pages for server rendering
10
+ //
11
+ // The shared modules (vue, @inertiajs/vue3, the app's SDK, …) are not in the bundle: its code
12
+ // imports them by name, and the app's own build provides them (template-shared.ts), so a page of
13
+ // the bundle and the app share one instance of each.
14
+ import { createHash } from 'node:crypto';
15
+ import { lstat, readdir, readFile } from 'node:fs/promises';
16
+ import { join, relative, sep } from 'node:path';
17
+ /** The manifest file of a bundle. */
18
+ export const TEMPLATE_MANIFEST = 'dokebi-template.json';
19
+ /** The signature file of a bundle (optional; its form is the app's). */
20
+ export const TEMPLATE_SIGNATURE = 'dokebi-template.sig';
21
+ /** The manifest format this version writes and reads. */
22
+ export const TEMPLATE_FORMAT = 1;
23
+ /** A template name: the folder name of `views/<template>/` and `domains.<host>.template`. */
24
+ export const TEMPLATE_NAME = /^[a-z][a-z0-9-]{0,31}$/;
25
+ /** A template version (the template repository's): 1 to 64 of letters, digits, `.`, `+`, `-`. */
26
+ export const TEMPLATE_VERSION = /^[0-9A-Za-z][0-9A-Za-z.+-]{0,63}$/;
27
+ /** A page of a bundle: `Layout`, or `Pages/<path>` without the `.vue`. */
28
+ export const TEMPLATE_PAGE = /^(?:Layout|Pages(?:\/[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}){1,16})$/;
29
+ /** A file of a bundle: under browser/ or ssr/, plain path segments only. */
30
+ const FILE = /^(?:browser|ssr)(?:\/[A-Za-z0-9_@+][A-Za-z0-9_.@+-]{0,199}){1,32}$/;
31
+ /** A shared module specifier: a package name with an optional subpath. */
32
+ export const SHARED_SPECIFIER = /^(?:@[a-z0-9][a-z0-9._-]{0,213}\/)?[a-z0-9][a-z0-9._-]{0,213}(?:\/[A-Za-z0-9_.@+-]{1,200}){0,16}$/;
33
+ /** A page's `meta` (JSON) may take this many bytes. */
34
+ export const PAGE_META_MAX_BYTES = 4096;
35
+ /** Default limits of one bundle. */
36
+ export const TEMPLATE_MAX_BYTES = 50 * 1024 * 1024;
37
+ export const TEMPLATE_MAX_FILES = 4096;
38
+ /**
39
+ * The shared modules every bundle may import and every app build provides (when it opts in with
40
+ * `dokebiInertia({ templates })`). `vue/server-renderer` is provided by the server build only.
41
+ */
42
+ export const SHARED_DEFAULTS = Object.freeze([
43
+ 'vue',
44
+ 'vue/server-renderer',
45
+ '@inertiajs/vue3',
46
+ '@dokebi/template-inertia/i18n',
47
+ '@dokebi/template-inertia/pages',
48
+ ]);
49
+ /** The defaults the server build alone provides. */
50
+ export const SERVER_ONLY_SHARED = Object.freeze(['vue/server-renderer']);
51
+ function plain(value) {
52
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
53
+ }
54
+ /** The JSON `meta` value of a page is plain data (objects, arrays, strings, finite numbers…). */
55
+ export function jsonValue(value, depth = 0) {
56
+ if (depth > 16)
57
+ return false;
58
+ if (value === null || typeof value === 'string' || typeof value === 'boolean')
59
+ return true;
60
+ if (typeof value === 'number')
61
+ return Number.isFinite(value);
62
+ if (Array.isArray(value))
63
+ return value.every((item) => jsonValue(item, depth + 1));
64
+ if (!plain(value) || Object.getPrototypeOf(value) !== Object.prototype)
65
+ return false;
66
+ return Object.values(value).every((item) => jsonValue(item, depth + 1));
67
+ }
68
+ /** The problem of a manifest's shape, or undefined (paths, names, page references). */
69
+ export function manifestProblem(value) {
70
+ if (!plain(value))
71
+ return 'the manifest is not a JSON object';
72
+ if (value.format !== TEMPLATE_FORMAT)
73
+ return `format must be ${TEMPLATE_FORMAT}`;
74
+ if (typeof value.name !== 'string' || !TEMPLATE_NAME.test(value.name))
75
+ return 'name must be a template name (^[a-z][a-z0-9-]{0,31}$)';
76
+ if (typeof value.version !== 'string' || !TEMPLATE_VERSION.test(value.version))
77
+ return 'version must be 1 to 64 letters, digits, ".", "+" or "-"';
78
+ if (typeof value.builtWith !== 'string' || !TEMPLATE_VERSION.test(value.builtWith))
79
+ return 'builtWith must be the template-inertia version';
80
+ if (!plain(value.shared))
81
+ return 'shared must be an object of module → version';
82
+ for (const [name, version] of Object.entries(value.shared))
83
+ if (!SHARED_SPECIFIER.test(name) || (version !== null && typeof version !== 'string'))
84
+ return `shared ${name} must be a module name with a version string or null`;
85
+ if (!plain(value.files))
86
+ return 'files must be an object of path → { bytes, sha256 }';
87
+ for (const [file, entry] of Object.entries(value.files)) {
88
+ if (!FILE.test(file) || file.split('/').some((part) => part === '..' || part === '.'))
89
+ return `file ${file} is not a path under browser/ or ssr/`;
90
+ if (!plain(entry) ||
91
+ !Number.isSafeInteger(entry.bytes) ||
92
+ entry.bytes < 0 ||
93
+ typeof entry.sha256 !== 'string' ||
94
+ !/^[0-9a-f]{64}$/.test(entry.sha256))
95
+ return `file ${file} needs bytes (a whole number) and sha256 (64 hex)`;
96
+ }
97
+ if (!plain(value.pages) || Object.keys(value.pages).length === 0)
98
+ return 'pages must name at least one page';
99
+ const files = value.files;
100
+ for (const [page, entry] of Object.entries(value.pages)) {
101
+ if (!TEMPLATE_PAGE.test(page))
102
+ return `page ${page} is not Layout or Pages/<path>`;
103
+ if (!plain(entry))
104
+ return `page ${page} is not an object`;
105
+ for (const key of ['browser', 'ssr'])
106
+ if (typeof entry[key] !== 'string' || !Object.hasOwn(files, entry[key]))
107
+ return `page ${page}: ${key} must be a file of files`;
108
+ for (const key of ['css', 'preload']) {
109
+ const list = entry[key];
110
+ if (!Array.isArray(list) ||
111
+ list.some((file) => typeof file !== 'string' || !Object.hasOwn(files, file)))
112
+ return `page ${page}: ${key} must be a list of files of files`;
113
+ }
114
+ if (entry.meta !== undefined) {
115
+ if (!jsonValue(entry.meta))
116
+ return `page ${page}: meta must be JSON data`;
117
+ if (Buffer.byteLength(JSON.stringify(entry.meta)) > PAGE_META_MAX_BYTES)
118
+ return `page ${page}: meta is larger than ${PAGE_META_MAX_BYTES} bytes`;
119
+ }
120
+ }
121
+ return undefined;
122
+ }
123
+ /** Every file under `dir` (relative, `/`-separated), links and other non-files reported. */
124
+ async function walk(dir, root, found, links, max) {
125
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
126
+ if (found.length + links.length > max)
127
+ return;
128
+ const path = join(dir, entry.name);
129
+ const name = relative(root, path).split(sep).join('/');
130
+ if (entry.isSymbolicLink() || (!entry.isFile() && !entry.isDirectory()))
131
+ links.push(name);
132
+ else if (entry.isDirectory())
133
+ await walk(path, root, found, links, max);
134
+ else
135
+ found.push(name);
136
+ }
137
+ }
138
+ /** sha256 (hex) of bytes. */
139
+ export function sha256(bytes) {
140
+ return createHash('sha256').update(bytes).digest('hex');
141
+ }
142
+ /**
143
+ * Checks one bundle folder: the manifest's shape, every file's size and sha256, no file the
144
+ * manifest does not list (but the manifest and the signature), no link, the limits. Reads only;
145
+ * never throws for what the folder holds (a missing folder is TEMPLATE_MANIFEST_MISSING).
146
+ */
147
+ export async function checkTemplateBundle(dir, limits = {}) {
148
+ const maxBytes = limits.maxBytes ?? TEMPLATE_MAX_BYTES;
149
+ const maxFiles = limits.maxFiles ?? TEMPLATE_MAX_FILES;
150
+ const problems = [];
151
+ let text;
152
+ try {
153
+ const info = await lstat(join(dir, TEMPLATE_MANIFEST));
154
+ if (!info.isFile())
155
+ return {
156
+ bytes: 0,
157
+ problems: [
158
+ {
159
+ code: 'TEMPLATE_FILE_LINK',
160
+ file: TEMPLATE_MANIFEST,
161
+ message: `${TEMPLATE_MANIFEST} is not a plain file`,
162
+ },
163
+ ],
164
+ };
165
+ if (info.size > 4 * 1024 * 1024)
166
+ return {
167
+ bytes: 0,
168
+ problems: [
169
+ {
170
+ code: 'TEMPLATE_TOO_LARGE',
171
+ file: TEMPLATE_MANIFEST,
172
+ message: `${TEMPLATE_MANIFEST} is larger than 4 MiB`,
173
+ },
174
+ ],
175
+ };
176
+ text = await readFile(join(dir, TEMPLATE_MANIFEST));
177
+ }
178
+ catch (error) {
179
+ return {
180
+ bytes: 0,
181
+ problems: [
182
+ {
183
+ code: 'TEMPLATE_MANIFEST_MISSING',
184
+ file: TEMPLATE_MANIFEST,
185
+ message: `${TEMPLATE_MANIFEST} could not be read: ${error.message}`,
186
+ },
187
+ ],
188
+ };
189
+ }
190
+ let parsed;
191
+ try {
192
+ parsed = JSON.parse(text.toString('utf8'));
193
+ }
194
+ catch (error) {
195
+ return {
196
+ bytes: 0,
197
+ problems: [
198
+ {
199
+ code: 'TEMPLATE_MANIFEST_INVALID',
200
+ file: TEMPLATE_MANIFEST,
201
+ message: `${TEMPLATE_MANIFEST} is not JSON: ${error.message}`,
202
+ },
203
+ ],
204
+ };
205
+ }
206
+ if (plain(parsed) && parsed.format !== TEMPLATE_FORMAT)
207
+ return {
208
+ bytes: 0,
209
+ problems: [
210
+ {
211
+ code: 'TEMPLATE_FORMAT_UNSUPPORTED',
212
+ file: TEMPLATE_MANIFEST,
213
+ message: `format ${String(parsed.format)} is not ${TEMPLATE_FORMAT}: build the bundle with this template-inertia, or upgrade the app`,
214
+ },
215
+ ],
216
+ };
217
+ const shape = manifestProblem(parsed);
218
+ if (shape !== undefined)
219
+ return {
220
+ bytes: 0,
221
+ problems: [{ code: 'TEMPLATE_MANIFEST_INVALID', file: TEMPLATE_MANIFEST, message: shape }],
222
+ };
223
+ const manifest = parsed;
224
+ const buildId = sha256(text).slice(0, 12);
225
+ const listed = new Map(Object.entries(manifest.files));
226
+ if (listed.size > maxFiles)
227
+ problems.push({
228
+ code: 'TEMPLATE_TOO_LARGE',
229
+ message: `the bundle lists ${listed.size} files, more than ${maxFiles}`,
230
+ });
231
+ const declared = [...listed.values()].reduce((sum, entry) => sum + entry.bytes, 0);
232
+ if (declared > maxBytes)
233
+ problems.push({
234
+ code: 'TEMPLATE_TOO_LARGE',
235
+ message: `the bundle's files take ${declared} bytes, more than ${maxBytes}`,
236
+ });
237
+ if (problems.length)
238
+ return { manifest, buildId, bytes: 0, problems };
239
+ const found = [];
240
+ const links = [];
241
+ for (const top of ['browser', 'ssr']) {
242
+ try {
243
+ const info = await lstat(join(dir, top));
244
+ if (!info.isDirectory()) {
245
+ links.push(top);
246
+ continue;
247
+ }
248
+ }
249
+ catch {
250
+ // A bundle without that folder: its listed files are reported missing below.
251
+ continue;
252
+ }
253
+ await walk(join(dir, top), dir, found, links, maxFiles);
254
+ }
255
+ for (const entry of await readdir(dir, { withFileTypes: true }))
256
+ if (entry.name !== TEMPLATE_MANIFEST &&
257
+ entry.name !== TEMPLATE_SIGNATURE &&
258
+ entry.name !== 'browser' &&
259
+ entry.name !== 'ssr')
260
+ problems.push({
261
+ code: 'TEMPLATE_FILE_EXTRA',
262
+ file: entry.name,
263
+ message: `${entry.name} is not part of a bundle (only ${TEMPLATE_MANIFEST}, ${TEMPLATE_SIGNATURE}, browser/ and ssr/)`,
264
+ });
265
+ for (const link of links)
266
+ problems.push({
267
+ code: 'TEMPLATE_FILE_LINK',
268
+ file: link,
269
+ message: `${link} is a link or a special file; a bundle holds plain files only`,
270
+ });
271
+ let bytes = 0;
272
+ for (const file of found) {
273
+ const entry = listed.get(file);
274
+ if (entry === undefined) {
275
+ problems.push({
276
+ code: 'TEMPLATE_FILE_EXTRA',
277
+ file,
278
+ message: `${file} is not in the manifest's files`,
279
+ });
280
+ continue;
281
+ }
282
+ const content = await readFile(join(dir, file));
283
+ bytes += content.length;
284
+ if (bytes > maxBytes) {
285
+ problems.push({
286
+ code: 'TEMPLATE_TOO_LARGE',
287
+ message: `the bundle's files take more than ${maxBytes} bytes`,
288
+ });
289
+ break;
290
+ }
291
+ if (content.length !== entry.bytes || sha256(content) !== entry.sha256)
292
+ problems.push({
293
+ code: 'TEMPLATE_FILE_CHANGED',
294
+ file,
295
+ message: `${file} is not the file the manifest names (size or sha256 differs)`,
296
+ });
297
+ }
298
+ const present = new Set(found);
299
+ for (const file of listed.keys())
300
+ if (!present.has(file))
301
+ problems.push({
302
+ code: 'TEMPLATE_FILE_MISSING',
303
+ file,
304
+ message: `${file} is in the manifest but not in the folder`,
305
+ });
306
+ return { manifest, buildId, bytes, problems };
307
+ }
308
+ /** The major part of a version for compatibility: `3` of 3.5.1, `0.4` of 0.4.19. */
309
+ export function compatibleLine(version) {
310
+ const match = /^v?(\d+)\.(\d+)(?:\.\d+)?/.exec(version);
311
+ if (!match)
312
+ return undefined;
313
+ return match[1] === '0' ? `0.${match[2]}` : match[1];
314
+ }
315
+ /**
316
+ * The problems of a bundle's shared modules against what an app build provides: a module the app
317
+ * does not provide, or one whose package is another major (0.x: minor) than the bundle was built
318
+ * with. A version unknown on either side (a local alias) is not compared.
319
+ */
320
+ export function sharedProblems(bundle, provided) {
321
+ const problems = [];
322
+ for (const [module, built] of Object.entries(bundle)) {
323
+ const own = provided[module];
324
+ if (own === undefined) {
325
+ problems.push({
326
+ code: 'TEMPLATE_SHARED_MISSING',
327
+ module,
328
+ message: `the bundle imports ${module}, which the app build does not provide (add it to dokebiInertia({ templates: { shared } }) and build the app again)`,
329
+ });
330
+ continue;
331
+ }
332
+ if (built === null || own.version === null)
333
+ continue;
334
+ const want = compatibleLine(built);
335
+ const have = compatibleLine(own.version);
336
+ if (want !== undefined && have !== undefined && want !== have)
337
+ problems.push({
338
+ code: 'TEMPLATE_SHARED_VERSION',
339
+ module,
340
+ message: `the bundle was built with ${module} ${built}, the app provides ${own.version} (another major version)`,
341
+ });
342
+ }
343
+ return problems;
344
+ }
@@ -0,0 +1,93 @@
1
+ import type { Logger } from '@dokebi/core';
2
+ /** `dokebiInertia({ templates })` (D-0291). */
3
+ export interface DokebiInertiaTemplateOptions {
4
+ /**
5
+ * The app's own modules template bundles share with its pages (its SDK: components,
6
+ * composables, stores), as package names (`@shop/sdk`, `@shop/sdk/components`). vue,
7
+ * vue/server-renderer, @inertiajs/vue3 and @dokebi/template-inertia/{i18n,pages} are always
8
+ * provided.
9
+ */
10
+ readonly shared?: readonly string[];
11
+ }
12
+ /** Where a build writes what it provides, under its outDir. */
13
+ export declare const SHARED_FILE = ".vite/dokebi-shared.json";
14
+ /** `dokebi-shared.json`. */
15
+ export interface SharedFile {
16
+ readonly format: 1;
17
+ readonly ssr: boolean;
18
+ /** The URL prefix of the browser build (`base`); `/` for the server build. */
19
+ readonly base: string;
20
+ /** Module → the file of the build that provides it (relative to outDir) and its package version. */
21
+ readonly modules: Readonly<Record<string, {
22
+ readonly file: string;
23
+ readonly version: string | null;
24
+ }>>;
25
+ }
26
+ /** The checked shared list (defaults first), or throws INVALID_TEMPLATE_SHARED. */
27
+ export declare function sharedModules(options: DokebiInertiaTemplateOptions | undefined): string[];
28
+ /** The entry name of a shared module: `dokebi-shared/vue`, `dokebi-shared/shop__sdk`. */
29
+ export declare function sharedEntryName(module: string): string;
30
+ /**
31
+ * The version of the package of `module` as installed for `root`: the nearest
32
+ * node_modules/<package>/package.json walking up (a workspace link counts), or null for a module
33
+ * that is no installed package (a local alias).
34
+ */
35
+ export declare function packageVersion(root: string, module: string): string | null;
36
+ /**
37
+ * Whether `module`, as Node resolves it for `root`, has a default export: a server build leaves
38
+ * installed packages to Node (an external), so the entry cannot see their exports. A probe file
39
+ * in root's node_modules/.cache imports it the way the built server code will.
40
+ */
41
+ export declare function externalHasDefault(root: string, module: string): Promise<boolean>;
42
+ /** The part of Rollup's input options this reads and changes. */
43
+ export interface InputOptionsShape {
44
+ readonly input?: string | readonly string[] | Readonly<Record<string, string>>;
45
+ readonly preserveEntrySignatures?: unknown;
46
+ readonly [key: string]: unknown;
47
+ }
48
+ /** The part of a plugin context `load` uses. */
49
+ export interface SharedLoadContext {
50
+ resolve(source: string, importer?: string): Promise<{
51
+ readonly id: string;
52
+ readonly external?: unknown;
53
+ } | null>;
54
+ load(options: {
55
+ id: string;
56
+ }): Promise<{
57
+ readonly exports?: readonly string[] | null;
58
+ }>;
59
+ }
60
+ /** One output chunk as `writeBundle` sees it. */
61
+ interface OutputChunkShape {
62
+ readonly type: string;
63
+ readonly isEntry?: boolean;
64
+ readonly facadeModuleId?: string | null;
65
+ readonly fileName: string;
66
+ }
67
+ /** The shared entries of one app build (`dokebiInertia({ templates })`). */
68
+ export declare class SharedEntries {
69
+ #private;
70
+ constructor(logger: Logger, options: DokebiInertiaTemplateOptions);
71
+ /** The modules this build provides (the server build alone has vue/server-renderer). */
72
+ get modules(): readonly string[];
73
+ configResolved(config: {
74
+ readonly root: string;
75
+ readonly command: string;
76
+ readonly base?: string;
77
+ readonly build: {
78
+ readonly ssr?: unknown;
79
+ readonly outDir: string;
80
+ };
81
+ }): void;
82
+ /**
83
+ * Rollup's `options`: the shared entries join the app's inputs (a string or list input is
84
+ * named as Rollup names it, by file name), and entry exports are kept.
85
+ */
86
+ options(input: InputOptionsShape): InputOptionsShape | null;
87
+ resolveId(source: string): string | null;
88
+ /** The entry text: every export of the module, and its default when it has one. */
89
+ load(context: SharedLoadContext, id: string): Promise<string | null>;
90
+ /** `writeBundle`: `dokebi-shared.json` beside the build's manifest. */
91
+ writeBundle(bundle: Readonly<Record<string, OutputChunkShape>>): Promise<void>;
92
+ }
93
+ export {};
@@ -0,0 +1,197 @@
1
+ // D-0291 §2: the app build provides the shared modules of template bundles. With
2
+ // `dokebiInertia({ templates: { shared: ['@shop/sdk'] } })` every `vite build` of the app (the
3
+ // browser build and the server build) gets one more entry per shared module, `export * from
4
+ // '<module>'` (and its default), named `dokebi-shared/<module>`. Entries of one build share module
5
+ // instances, so the vue a bundle page receives through that entry is the vue of the app's own
6
+ // pages. The build writes which file provides which module, with its package version, to
7
+ // `<outDir>/.vite/dokebi-shared.json`; the app (stage 2) points the bundle's imports there: an
8
+ // import map in the browser, a resolve hook on the server.
9
+ import { randomBytes } from 'node:crypto';
10
+ import { existsSync, readFileSync } from 'node:fs';
11
+ import { mkdir, rm, writeFile } from 'node:fs/promises';
12
+ import { dirname, isAbsolute, join, parse, resolve } from 'node:path';
13
+ import { pathToFileURL } from 'node:url';
14
+ import { InertiaUsageError } from './errors.js';
15
+ import { SERVER_ONLY_SHARED, SHARED_DEFAULTS, SHARED_SPECIFIER } from './template-bundle.js';
16
+ /** Where a build writes what it provides, under its outDir. */
17
+ export const SHARED_FILE = '.vite/dokebi-shared.json';
18
+ const PREFIX = '\0dokebi-shared:';
19
+ /** The checked shared list (defaults first), or throws INVALID_TEMPLATE_SHARED. */
20
+ export function sharedModules(options) {
21
+ const own = options?.shared ?? [];
22
+ if (!Array.isArray(own) || own.length > 64)
23
+ throw new InertiaUsageError('INVALID_TEMPLATE_SHARED', 'templates.shared must be a list of at most 64 module names');
24
+ for (const name of own)
25
+ if (typeof name !== 'string' || !SHARED_SPECIFIER.test(name))
26
+ throw new InertiaUsageError('INVALID_TEMPLATE_SHARED', `templates.shared: ${String(name)} is not a package name with an optional subpath`);
27
+ return [...new Set([...SHARED_DEFAULTS, ...own])];
28
+ }
29
+ /** The entry name of a shared module: `dokebi-shared/vue`, `dokebi-shared/shop__sdk`. */
30
+ export function sharedEntryName(module) {
31
+ return `dokebi-shared/${module.replace(/^@/, '').replace(/[^A-Za-z0-9._-]+/g, '__')}`;
32
+ }
33
+ /**
34
+ * The version of the package of `module` as installed for `root`: the nearest
35
+ * node_modules/<package>/package.json walking up (a workspace link counts), or null for a module
36
+ * that is no installed package (a local alias).
37
+ */
38
+ export function packageVersion(root, module) {
39
+ const parts = module.split('/');
40
+ const name = module.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];
41
+ for (let dir = resolve(root);; dir = dirname(dir)) {
42
+ const file = join(dir, 'node_modules', name, 'package.json');
43
+ if (existsSync(file)) {
44
+ try {
45
+ const version = JSON.parse(readFileSync(file, 'utf8')).version;
46
+ return typeof version === 'string' ? version : null;
47
+ }
48
+ catch {
49
+ return null;
50
+ }
51
+ }
52
+ if (dirname(dir) === dir)
53
+ return null;
54
+ }
55
+ }
56
+ /**
57
+ * Whether `module`, as Node resolves it for `root`, has a default export: a server build leaves
58
+ * installed packages to Node (an external), so the entry cannot see their exports. A probe file
59
+ * in root's node_modules/.cache imports it the way the built server code will.
60
+ */
61
+ export async function externalHasDefault(root, module) {
62
+ const folder = join(root, 'node_modules', '.cache', 'dokebi-shared');
63
+ await mkdir(folder, { recursive: true });
64
+ const probe = join(folder, `probe-${randomBytes(6).toString('hex')}.mjs`);
65
+ await writeFile(probe, `export * as namespace from ${JSON.stringify(module)};\n`);
66
+ try {
67
+ const { namespace } = (await import(pathToFileURL(probe).href));
68
+ return Object.hasOwn(namespace, 'default');
69
+ }
70
+ finally {
71
+ await rm(probe, { force: true });
72
+ }
73
+ }
74
+ /** The shared entries of one app build (`dokebiInertia({ templates })`). */
75
+ export class SharedEntries {
76
+ #logger;
77
+ #modules;
78
+ #root = process.cwd();
79
+ #ssr = false;
80
+ #base = '/';
81
+ #outDir = 'dist';
82
+ #build = false;
83
+ constructor(logger, options) {
84
+ this.#logger = logger;
85
+ this.#modules = sharedModules(options);
86
+ const names = new Map();
87
+ for (const module of this.#modules) {
88
+ const name = sharedEntryName(module);
89
+ const other = names.get(name);
90
+ if (other !== undefined)
91
+ throw new InertiaUsageError('INVALID_TEMPLATE_SHARED', `templates.shared: ${module} and ${other} make the same entry name ${name}`);
92
+ names.set(name, module);
93
+ }
94
+ }
95
+ /** The modules this build provides (the server build alone has vue/server-renderer). */
96
+ get modules() {
97
+ return this.#ssr
98
+ ? this.#modules
99
+ : this.#modules.filter((module) => !SERVER_ONLY_SHARED.includes(module));
100
+ }
101
+ configResolved(config) {
102
+ this.#root = config.root;
103
+ this.#build = config.command === 'build';
104
+ this.#ssr = Boolean(config.build.ssr);
105
+ this.#base = this.#ssr ? '/' : config.base || '/';
106
+ this.#outDir = isAbsolute(config.build.outDir)
107
+ ? config.build.outDir
108
+ : join(config.root, config.build.outDir);
109
+ }
110
+ /**
111
+ * Rollup's `options`: the shared entries join the app's inputs (a string or list input is
112
+ * named as Rollup names it, by file name), and entry exports are kept.
113
+ */
114
+ options(input) {
115
+ if (!this.#build)
116
+ return null;
117
+ const own = input.input;
118
+ const named = own === undefined
119
+ ? {}
120
+ : typeof own === 'string'
121
+ ? { [parse(own).name]: own }
122
+ : Array.isArray(own)
123
+ ? Object.fromEntries(own.map((file) => [parse(file).name, file]))
124
+ : { ...own };
125
+ for (const module of this.modules)
126
+ named[sharedEntryName(module)] = `${PREFIX}${module}`;
127
+ this.#logger.log('debug', 'Inertia build provides the shared modules of template bundles', {
128
+ code: 'INERTIA_TEMPLATE_SHARED_ENTRIES',
129
+ ssr: this.#ssr,
130
+ modules: this.modules,
131
+ });
132
+ return {
133
+ ...input,
134
+ input: named,
135
+ preserveEntrySignatures: input.preserveEntrySignatures === undefined || input.preserveEntrySignatures === false
136
+ ? 'exports-only'
137
+ : input.preserveEntrySignatures,
138
+ };
139
+ }
140
+ resolveId(source) {
141
+ return source.startsWith(PREFIX) ? source : null;
142
+ }
143
+ /** The entry text: every export of the module, and its default when it has one. */
144
+ async load(context, id) {
145
+ if (!id.startsWith(PREFIX))
146
+ return null;
147
+ const module = id.slice(PREFIX.length);
148
+ const spec = JSON.stringify(module);
149
+ const resolved = await context.resolve(module, join(this.#root, 'package.json'));
150
+ if (resolved === null)
151
+ throw new InertiaUsageError('INVALID_TEMPLATE_SHARED', `templates.shared: ${module} cannot be resolved from ${this.#root} (install it, or correct the name)`);
152
+ // An external (an installed package in the server build) stays an import; Node is asked
153
+ // whether it has a default export, as the built server code will import it.
154
+ let withDefault;
155
+ if (resolved.external) {
156
+ try {
157
+ withDefault = await externalHasDefault(this.#root, module);
158
+ }
159
+ catch (cause) {
160
+ throw new InertiaUsageError('INVALID_TEMPLATE_SHARED', `templates.shared: ${module} cannot be imported from ${this.#root} by Node: ${cause.message}`);
161
+ }
162
+ }
163
+ else
164
+ withDefault = (await context.load({ id: resolved.id })).exports?.includes('default') === true;
165
+ return `export * from ${spec};\n${withDefault ? `export { default } from ${spec};\n` : ''}`;
166
+ }
167
+ /** `writeBundle`: `dokebi-shared.json` beside the build's manifest. */
168
+ async writeBundle(bundle) {
169
+ if (!this.#build)
170
+ return;
171
+ const modules = {};
172
+ for (const chunk of Object.values(bundle)) {
173
+ const facade = chunk.facadeModuleId;
174
+ if (chunk.type !== 'chunk' || !chunk.isEntry || !facade?.startsWith(PREFIX))
175
+ continue;
176
+ const module = facade.slice(PREFIX.length);
177
+ modules[module] = { file: chunk.fileName, version: packageVersion(this.#root, module) };
178
+ }
179
+ const missing = this.modules.filter((module) => modules[module] === undefined);
180
+ if (missing.length)
181
+ this.#logger.log('warn', 'Inertia build did not emit some shared module entries', {
182
+ code: 'INERTIA_TEMPLATE_SHARED_MISSING',
183
+ modules: missing,
184
+ fix: 'Keep the inputs dokebiInertia({ templates }) adds (do not replace build.rollupOptions.input in another plugin).',
185
+ });
186
+ const file = { format: 1, ssr: this.#ssr, base: this.#base, modules };
187
+ const path = join(this.#outDir, SHARED_FILE);
188
+ await mkdir(dirname(path), { recursive: true });
189
+ await writeFile(path, `${JSON.stringify(file, null, 2)}\n`);
190
+ this.#logger.log('info', 'Inertia build wrote the shared modules of template bundles', {
191
+ code: 'INERTIA_TEMPLATE_SHARED_WRITTEN',
192
+ file: path,
193
+ ssr: this.#ssr,
194
+ modules: Object.keys(modules),
195
+ });
196
+ }
197
+ }
@@ -0,0 +1,3 @@
1
+ export { buildTemplateBundle, packageEntry, type TemplateBuildOptions, type TemplateBuildResult, templatePages, } from './template-build.js';
2
+ export { checkTemplateBundle, compatibleLine, type ProvidedShared, 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
+ export { type DokebiInertiaTemplateOptions, packageVersion, SHARED_FILE, type SharedFile, sharedEntryName, } from './template-shared.js';
@@ -0,0 +1,5 @@
1
+ // `@dokebi/template-inertia/template` (D-0291): template bundles — the format and its check, and
2
+ // the build that `dokebi template build` runs in a template repository.
3
+ export { buildTemplateBundle, packageEntry, templatePages, } from './template-build.js';
4
+ export { checkTemplateBundle, compatibleLine, SHARED_DEFAULTS, sharedProblems, TEMPLATE_FORMAT, TEMPLATE_MANIFEST, TEMPLATE_MAX_BYTES, TEMPLATE_NAME, TEMPLATE_SIGNATURE, } from './template-bundle.js';
5
+ export { packageVersion, SHARED_FILE, sharedEntryName, } from './template-shared.js';