@dokebi/template-inertia 0.4.20 → 0.4.22
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 +53 -4
- package/README.md +1 -1
- package/dist/errors.d.ts +2 -2
- package/dist/errors.js +3 -1
- package/dist/index.d.ts +19 -0
- package/dist/index.js +116 -12
- 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 +61 -7
- package/dist/template-bundle.js +11 -7
- package/dist/template-preview.d.ts +38 -0
- package/dist/template-preview.js +336 -0
- package/dist/template-runtime.d.ts +157 -0
- package/dist/template-runtime.js +771 -0
- package/dist/template-shared.d.ts +6 -0
- package/dist/template-shared.js +36 -2
- package/dist/template.d.ts +2 -1
- package/dist/template.js +2 -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 +7 -2
- package/templates/shared.ts +4 -0
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
// D-0291 stage 3: `dokebi template preview` — a Vite dev server in the template repository that
|
|
2
|
+
// draws every page of a template folder with made-up props, without an app server. `/` lists the
|
|
3
|
+
// pages and their cases; `/__dokebi/preview/<page>?case=<case>` draws one, in the template's
|
|
4
|
+
// Layout, with HMR. The props of a page are its `<Page>.preview.json` beside the .vue file:
|
|
5
|
+
//
|
|
6
|
+
// { "<case>": { …props }, "<another case>": { … } }
|
|
7
|
+
//
|
|
8
|
+
// (a page without one gets the case `default` with no props), over the `shared` of the
|
|
9
|
+
// template folder's `preview.json` (`{ "shared": { …props every page gets } }`). The shared
|
|
10
|
+
// modules (vue, @inertiajs/vue3, the SDK) are the template repository's installed packages.
|
|
11
|
+
// Inertia visits (a <Link> to another preview URL) are answered too.
|
|
12
|
+
import { existsSync, readFileSync, realpathSync } from 'node:fs';
|
|
13
|
+
import { readdir, readFile } from 'node:fs/promises';
|
|
14
|
+
import { basename, join, relative, resolve, sep } from 'node:path';
|
|
15
|
+
import { pathToFileURL } from 'node:url';
|
|
16
|
+
import { ConsoleLogger } from '@dokebi/core';
|
|
17
|
+
import { InertiaError, InertiaUsageError } from './errors.js';
|
|
18
|
+
import { packageEntry, templatePages } from './template-build.js';
|
|
19
|
+
import { jsonValue, TEMPLATE_PAGE } from './template-bundle.js';
|
|
20
|
+
import { registerVueTypeScript } from './vue-typescript.js';
|
|
21
|
+
/** Where a page is drawn: `/__dokebi/preview/<page>?case=<case>`. */
|
|
22
|
+
export const PREVIEW_PREFIX = '/__dokebi/preview/';
|
|
23
|
+
const ENTRY_URL = '/@dokebi-preview/entry.js';
|
|
24
|
+
const ENTRY_ID = '\0dokebi-preview-entry';
|
|
25
|
+
/** A preview file may take this many bytes. */
|
|
26
|
+
const PREVIEW_MAX_BYTES = 1024 * 1024;
|
|
27
|
+
/** A case name: what a URL may carry. */
|
|
28
|
+
const CASE = /^[A-Za-z0-9][A-Za-z0-9 _.-]{0,63}$/;
|
|
29
|
+
/** The cases of one page (`<Page>.preview.json`): case → props, checked. */
|
|
30
|
+
export async function previewCases(file) {
|
|
31
|
+
if (!existsSync(file))
|
|
32
|
+
return { default: {} };
|
|
33
|
+
const text = await readFile(file, 'utf8');
|
|
34
|
+
if (Buffer.byteLength(text) > PREVIEW_MAX_BYTES)
|
|
35
|
+
throw new InertiaUsageError('INVALID_TEMPLATE_PREVIEW', `${file} is larger than 1 MiB`);
|
|
36
|
+
let parsed;
|
|
37
|
+
try {
|
|
38
|
+
parsed = JSON.parse(text);
|
|
39
|
+
}
|
|
40
|
+
catch (error) {
|
|
41
|
+
throw new InertiaUsageError('INVALID_TEMPLATE_PREVIEW', `${file} is not JSON: ${error.message}`);
|
|
42
|
+
}
|
|
43
|
+
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed))
|
|
44
|
+
throw new InertiaUsageError('INVALID_TEMPLATE_PREVIEW', `${file} must be an object of case name → props ({ "default": { … } })`);
|
|
45
|
+
const cases = {};
|
|
46
|
+
for (const [name, props] of Object.entries(parsed)) {
|
|
47
|
+
if (!CASE.test(name))
|
|
48
|
+
throw new InertiaUsageError('INVALID_TEMPLATE_PREVIEW', `${file}: case ${JSON.stringify(name)} is not a case name (letters, digits, space, _ . -)`);
|
|
49
|
+
if (props === null || typeof props !== 'object' || Array.isArray(props) || !jsonValue(props))
|
|
50
|
+
throw new InertiaUsageError('INVALID_TEMPLATE_PREVIEW', `${file}: case ${name} must be an object of props (JSON data)`);
|
|
51
|
+
cases[name] = props;
|
|
52
|
+
}
|
|
53
|
+
if (Object.keys(cases).length === 0)
|
|
54
|
+
cases.default = {};
|
|
55
|
+
return cases;
|
|
56
|
+
}
|
|
57
|
+
/** The plural categories: an object of only these is one message, not a folder of keys. */
|
|
58
|
+
const PLURAL = new Set(['zero', 'one', 'two', 'few', 'many', 'other']);
|
|
59
|
+
/** `{ a: { b: 'x' } }` → `{ 'ns.a.b': 'x' }` (plural objects kept whole). */
|
|
60
|
+
function flatten(input, prefix, out) {
|
|
61
|
+
for (const [key, value] of Object.entries(input)) {
|
|
62
|
+
const name = `${prefix}.${key}`;
|
|
63
|
+
if (value !== null &&
|
|
64
|
+
typeof value === 'object' &&
|
|
65
|
+
!Array.isArray(value) &&
|
|
66
|
+
!Object.keys(value).every((part) => PLURAL.has(part)))
|
|
67
|
+
flatten(value, name, out);
|
|
68
|
+
else
|
|
69
|
+
out[name] = value;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* D-0291 stage 3b: the `i18n` page prop of the preview from the template's own words
|
|
74
|
+
* (`locales/<locale>/<namespace>.json`), so pages that call t() draw; undefined without words.
|
|
75
|
+
*/
|
|
76
|
+
export async function previewWords(folder, wanted) {
|
|
77
|
+
const root = join(folder, 'locales');
|
|
78
|
+
if (!existsSync(root))
|
|
79
|
+
return undefined;
|
|
80
|
+
const locales = (await readdir(root, { withFileTypes: true }))
|
|
81
|
+
.filter((entry) => entry.isDirectory() && !entry.name.startsWith('.'))
|
|
82
|
+
.map((entry) => entry.name)
|
|
83
|
+
.sort();
|
|
84
|
+
const locale = wanted !== undefined && locales.includes(wanted) ? wanted : locales[0];
|
|
85
|
+
if (locale === undefined)
|
|
86
|
+
return undefined;
|
|
87
|
+
const messages = {};
|
|
88
|
+
const namespaces = [];
|
|
89
|
+
for (const entry of await readdir(join(root, locale), { withFileTypes: true })) {
|
|
90
|
+
if (!entry.isFile() || !entry.name.endsWith('.json') || entry.name.startsWith('.'))
|
|
91
|
+
continue;
|
|
92
|
+
const namespace = entry.name.slice(0, -'.json'.length);
|
|
93
|
+
namespaces.push(namespace);
|
|
94
|
+
flatten(JSON.parse(await readFile(join(root, locale, entry.name), 'utf8')), namespace, messages);
|
|
95
|
+
}
|
|
96
|
+
return {
|
|
97
|
+
locale,
|
|
98
|
+
version: 'preview',
|
|
99
|
+
fallback: [locale],
|
|
100
|
+
namespaces: namespaces.sort(),
|
|
101
|
+
messages: { [locale]: messages },
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
/** `preview.json` of the template folder: `{ shared, locale? }`. */
|
|
105
|
+
async function previewLocale(folder) {
|
|
106
|
+
const file = join(folder, 'preview.json');
|
|
107
|
+
if (!existsSync(file))
|
|
108
|
+
return undefined;
|
|
109
|
+
try {
|
|
110
|
+
const locale = JSON.parse(await readFile(file, 'utf8'))
|
|
111
|
+
?.locale;
|
|
112
|
+
return typeof locale === 'string' ? locale : undefined;
|
|
113
|
+
}
|
|
114
|
+
catch {
|
|
115
|
+
// Its shape is reported by previewShared.
|
|
116
|
+
return undefined;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
/** `preview.json` of the template folder: `{ shared }`. */
|
|
120
|
+
async function previewShared(folder) {
|
|
121
|
+
const file = join(folder, 'preview.json');
|
|
122
|
+
if (!existsSync(file))
|
|
123
|
+
return {};
|
|
124
|
+
let parsed;
|
|
125
|
+
try {
|
|
126
|
+
parsed = JSON.parse(await readFile(file, 'utf8'));
|
|
127
|
+
}
|
|
128
|
+
catch (error) {
|
|
129
|
+
throw new InertiaUsageError('INVALID_TEMPLATE_PREVIEW', `${file} is not JSON: ${error.message}`);
|
|
130
|
+
}
|
|
131
|
+
const shared = parsed?.shared ?? {};
|
|
132
|
+
if (shared === null || typeof shared !== 'object' || Array.isArray(shared) || !jsonValue(shared))
|
|
133
|
+
throw new InertiaUsageError('INVALID_TEMPLATE_PREVIEW', `${file} must be { "shared": { …props every page gets } }`);
|
|
134
|
+
return shared;
|
|
135
|
+
}
|
|
136
|
+
const escapeHtml = (value) => value.replace(/[&<>"']/g, (char) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[char]);
|
|
137
|
+
const scriptJson = (value) => JSON.stringify(value).replace(/</g, '\\u003c');
|
|
138
|
+
/**
|
|
139
|
+
* Starts the preview of the template folder `options.dir` (D-0291 stage 3). Resolves once the
|
|
140
|
+
* server listens; `close()` stops it.
|
|
141
|
+
*/
|
|
142
|
+
export async function startTemplatePreview(options) {
|
|
143
|
+
const logger = options.logger ??
|
|
144
|
+
new ConsoleLogger({ level: 'info' }, { plugin: 'dokebi-template-inertia', process: 'template-preview' });
|
|
145
|
+
const root = resolve(options.root ?? process.cwd());
|
|
146
|
+
const folder = resolve(root, options.dir);
|
|
147
|
+
const inside = relative(root, folder);
|
|
148
|
+
if (!inside || inside.startsWith('..') || !existsSync(folder))
|
|
149
|
+
throw new InertiaUsageError('INVALID_TEMPLATE_PREVIEW', `${options.dir} must be a template folder inside ${root}`);
|
|
150
|
+
const pages = await templatePages(folder);
|
|
151
|
+
if (![...pages.keys()].some((key) => key.startsWith('Pages/')))
|
|
152
|
+
throw new InertiaUsageError('INVALID_TEMPLATE_PREVIEW', `${options.dir} has no Pages/**/*.vue`);
|
|
153
|
+
const viteEntry = packageEntry(root, 'vite');
|
|
154
|
+
if (!viteEntry)
|
|
155
|
+
throw new InertiaError('TEMPLATE_BUILD_FAILED', `vite is not installed in ${root}`, {
|
|
156
|
+
fix: 'npm install --save-dev vite @vitejs/plugin-vue',
|
|
157
|
+
});
|
|
158
|
+
const vite = (await import(pathToFileURL(viteEntry).href));
|
|
159
|
+
const configFile = options.config ? resolve(root, options.config) : undefined;
|
|
160
|
+
let ownVue = false;
|
|
161
|
+
if (configFile) {
|
|
162
|
+
const loaded = (await vite.loadConfigFromFile({ command: 'serve', mode: 'development' }, configFile, root)) ?? {
|
|
163
|
+
config: {},
|
|
164
|
+
};
|
|
165
|
+
ownVue = (loaded.config.plugins ?? [])
|
|
166
|
+
.flat(Infinity)
|
|
167
|
+
.some((plugin) => plugin?.name === 'vite:vue');
|
|
168
|
+
}
|
|
169
|
+
const vueEntry = ownVue ? undefined : packageEntry(root, '@vitejs/plugin-vue');
|
|
170
|
+
if (!ownVue && !vueEntry)
|
|
171
|
+
throw new InertiaError('TEMPLATE_BUILD_FAILED', `@vitejs/plugin-vue is not installed in ${root}`, {
|
|
172
|
+
fix: 'npm install --save-dev @vitejs/plugin-vue',
|
|
173
|
+
});
|
|
174
|
+
const vue = vueEntry
|
|
175
|
+
? (await import(pathToFileURL(vueEntry).href))
|
|
176
|
+
.default
|
|
177
|
+
: undefined;
|
|
178
|
+
registerVueTypeScript(root, logger);
|
|
179
|
+
const folderUrl = `/${inside.split(sep).join('/')}`;
|
|
180
|
+
const names = [...pages.keys()]
|
|
181
|
+
.filter((key) => key.startsWith('Pages/'))
|
|
182
|
+
.map((key) => key.slice(6));
|
|
183
|
+
/** The page object of one preview URL. */
|
|
184
|
+
const pageObject = async (name, wanted) => {
|
|
185
|
+
const cases = await previewCases(join(folder, 'Pages', `${name}.preview.json`));
|
|
186
|
+
const chosen = wanted !== null && Object.hasOwn(cases, wanted) ? wanted : Object.keys(cases)[0];
|
|
187
|
+
const props = {
|
|
188
|
+
errors: {},
|
|
189
|
+
...(await previewShared(folder)),
|
|
190
|
+
...cases[chosen],
|
|
191
|
+
};
|
|
192
|
+
// D-0291 stage 3b: the template's own words, unless the case gives its own i18n.
|
|
193
|
+
if (props.i18n === undefined) {
|
|
194
|
+
const words = await previewWords(folder, await previewLocale(folder));
|
|
195
|
+
if (words) {
|
|
196
|
+
props.i18n = words;
|
|
197
|
+
props.locale ??= words.locale;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
return {
|
|
201
|
+
cases: Object.keys(cases),
|
|
202
|
+
chosen,
|
|
203
|
+
page: {
|
|
204
|
+
component: name,
|
|
205
|
+
props,
|
|
206
|
+
url: `${PREVIEW_PREFIX}${name}?case=${encodeURIComponent(chosen)}`,
|
|
207
|
+
version: 'preview',
|
|
208
|
+
clearHistory: false,
|
|
209
|
+
encryptHistory: false,
|
|
210
|
+
},
|
|
211
|
+
};
|
|
212
|
+
};
|
|
213
|
+
const plugin = {
|
|
214
|
+
name: 'dokebi-template-preview',
|
|
215
|
+
enforce: 'pre',
|
|
216
|
+
resolveId: (source) => (source === ENTRY_URL ? ENTRY_ID : null),
|
|
217
|
+
load(id) {
|
|
218
|
+
if (id !== ENTRY_ID)
|
|
219
|
+
return null;
|
|
220
|
+
return `import { createInertiaApp, router } from '@inertiajs/vue3';
|
|
221
|
+
import { pageI18n } from '@dokebi/template-inertia/i18n';
|
|
222
|
+
import { createApp, h } from 'vue';
|
|
223
|
+
const files = import.meta.glob(${JSON.stringify(`${folderUrl}/{Layout,Pages/**/*}.vue`)});
|
|
224
|
+
const layoutFile = files[${JSON.stringify(`${folderUrl}/Layout.vue`)}];
|
|
225
|
+
const layout = layoutFile ? (await layoutFile()).default : undefined;
|
|
226
|
+
await createInertiaApp({
|
|
227
|
+
resolve: async (name) => {
|
|
228
|
+
const file = files[${JSON.stringify(`${folderUrl}/Pages/`)} + name + '.vue'];
|
|
229
|
+
if (!file) throw new Error('Unknown page: ' + name);
|
|
230
|
+
return file();
|
|
231
|
+
},
|
|
232
|
+
layout: () => layout,
|
|
233
|
+
setup({ el, App, props, plugin }) {
|
|
234
|
+
createApp({ render: () => h(App, props) }).use(plugin).use(pageI18n(props.initialPage, { router })).mount(el);
|
|
235
|
+
},
|
|
236
|
+
});
|
|
237
|
+
`;
|
|
238
|
+
},
|
|
239
|
+
configureServer(server) {
|
|
240
|
+
server.middlewares.use((request, response, next) => {
|
|
241
|
+
const url = new URL(request.url ?? '/', 'http://preview');
|
|
242
|
+
if (request.method !== 'GET' && request.method !== 'HEAD')
|
|
243
|
+
return next();
|
|
244
|
+
const send = (status, type, body, headers = {}) => {
|
|
245
|
+
response.statusCode = status;
|
|
246
|
+
response.setHeader('content-type', type);
|
|
247
|
+
response.setHeader('cache-control', 'no-store');
|
|
248
|
+
for (const [name, value] of Object.entries(headers))
|
|
249
|
+
response.setHeader(name, value);
|
|
250
|
+
response.end(request.method === 'HEAD' ? '' : body);
|
|
251
|
+
};
|
|
252
|
+
const fail = (error) => {
|
|
253
|
+
logger.log('error', 'Template preview could not draw a page', {
|
|
254
|
+
code: 'INERTIA_TEMPLATE_PREVIEW_FAILED',
|
|
255
|
+
url: url.pathname,
|
|
256
|
+
error: error.message,
|
|
257
|
+
});
|
|
258
|
+
send(500, 'text/html; charset=utf-8', `<!doctype html><pre>${escapeHtml(error.message)}</pre>`);
|
|
259
|
+
};
|
|
260
|
+
if (url.pathname === '/') {
|
|
261
|
+
Promise.all(names.map(async (name) => ({
|
|
262
|
+
name,
|
|
263
|
+
cases: Object.keys(await previewCases(join(folder, 'Pages', `${name}.preview.json`))),
|
|
264
|
+
}))).then((listed) => send(200, 'text/html; charset=utf-8', `<!doctype html><html><head><meta charset="utf-8"><title>${escapeHtml(basename(folder))} preview</title></head><body><h1>${escapeHtml(basename(folder))}</h1><ul>${listed
|
|
265
|
+
.map((item) => `<li data-page="${escapeHtml(item.name)}">${escapeHtml(item.name)}: ${item.cases
|
|
266
|
+
.map((name) => `<a href="${PREVIEW_PREFIX}${escapeHtml(item.name)}?case=${encodeURIComponent(name)}">${escapeHtml(name)}</a>`)
|
|
267
|
+
.join(' · ')}</li>`)
|
|
268
|
+
.join('')}</ul></body></html>`), fail);
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
if (!url.pathname.startsWith(PREVIEW_PREFIX))
|
|
272
|
+
return next();
|
|
273
|
+
const name = decodeURIComponent(url.pathname.slice(PREVIEW_PREFIX.length));
|
|
274
|
+
if (!TEMPLATE_PAGE.test(`Pages/${name}`) || !names.includes(name))
|
|
275
|
+
return send(404, 'text/plain; charset=utf-8', `No page ${name} in ${options.dir}`);
|
|
276
|
+
pageObject(name, url.searchParams.get('case')).then(async ({ page }) => {
|
|
277
|
+
if (request.headers['x-inertia'] === 'true')
|
|
278
|
+
return send(200, 'application/json; charset=utf-8', JSON.stringify(page), {
|
|
279
|
+
'x-inertia': 'true',
|
|
280
|
+
vary: 'X-Inertia',
|
|
281
|
+
});
|
|
282
|
+
const html = await server.transformIndexHtml(url.pathname, `<!doctype html><html><head><meta charset="utf-8"><title>${escapeHtml(name)} · preview</title><script type="module" src="${ENTRY_URL}"></script></head><body><script data-page="app" type="application/json">${scriptJson(page)}</script><div id="app"></div></body></html>`);
|
|
283
|
+
send(200, 'text/html; charset=utf-8', html);
|
|
284
|
+
}, fail);
|
|
285
|
+
});
|
|
286
|
+
},
|
|
287
|
+
};
|
|
288
|
+
let server;
|
|
289
|
+
try {
|
|
290
|
+
server = await vite.createServer({
|
|
291
|
+
root,
|
|
292
|
+
configFile: configFile ?? false,
|
|
293
|
+
logLevel: 'warn',
|
|
294
|
+
publicDir: false,
|
|
295
|
+
appType: 'custom',
|
|
296
|
+
plugins: [
|
|
297
|
+
...(vue
|
|
298
|
+
? [
|
|
299
|
+
vue({
|
|
300
|
+
script: {
|
|
301
|
+
fs: {
|
|
302
|
+
fileExists: (file) => existsSync(file),
|
|
303
|
+
readFile: (file) => readFileSync(file, 'utf8'),
|
|
304
|
+
realpath: (file) => realpathSync(file),
|
|
305
|
+
},
|
|
306
|
+
},
|
|
307
|
+
}),
|
|
308
|
+
]
|
|
309
|
+
: []),
|
|
310
|
+
plugin,
|
|
311
|
+
],
|
|
312
|
+
server: { port: options.port ?? 5180, host: options.host ?? '127.0.0.1', strictPort: false },
|
|
313
|
+
});
|
|
314
|
+
await server.listen();
|
|
315
|
+
}
|
|
316
|
+
catch (cause) {
|
|
317
|
+
throw new InertiaError('TEMPLATE_BUILD_FAILED', `The preview server of ${options.dir} did not start`, {
|
|
318
|
+
cause,
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
const address = server.httpServer?.address();
|
|
322
|
+
const port = typeof address === 'object' && address ? address.port : (options.port ?? 5180);
|
|
323
|
+
const host = options.host ?? '127.0.0.1';
|
|
324
|
+
const url = `http://${host.includes(':') ? `[${host}]` : host}:${port}/`;
|
|
325
|
+
const listed = await Promise.all(names.map(async (name) => ({
|
|
326
|
+
page: name,
|
|
327
|
+
cases: Object.keys(await previewCases(join(folder, 'Pages', `${name}.preview.json`))),
|
|
328
|
+
})));
|
|
329
|
+
logger.log('info', 'Template preview started', {
|
|
330
|
+
code: 'INERTIA_TEMPLATE_PREVIEW',
|
|
331
|
+
url,
|
|
332
|
+
dir: options.dir,
|
|
333
|
+
pages: listed.length,
|
|
334
|
+
});
|
|
335
|
+
return { url, pages: listed, close: () => server.close() };
|
|
336
|
+
}
|
|
@@ -0,0 +1,157 @@
|
|
|
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
|
+
* D-0291 stage 3b: puts a bundle's `locales/` into the page bundles of its template
|
|
115
|
+
* (@dokebi/i18n `templateBundle`); `undefined` takes them out. Absent without @dokebi/i18n.
|
|
116
|
+
*/
|
|
117
|
+
readonly words?: (app: string, template: string, directory: string | undefined) => Promise<{
|
|
118
|
+
ok: true;
|
|
119
|
+
keys: number;
|
|
120
|
+
locales: readonly string[];
|
|
121
|
+
} | {
|
|
122
|
+
ok: false;
|
|
123
|
+
reason: string;
|
|
124
|
+
}>;
|
|
125
|
+
}
|
|
126
|
+
/** Every app's template bundles. */
|
|
127
|
+
export declare class TemplateBundles {
|
|
128
|
+
#private;
|
|
129
|
+
constructor(options: TemplateBundlesOptions);
|
|
130
|
+
/** The configured template names of an app. */
|
|
131
|
+
templatesOf(app: string): readonly string[];
|
|
132
|
+
/** An app's build, from its Inertia scope (the first scope of an app wins). */
|
|
133
|
+
registerApp(app: string, build: TemplateAppBuild): void;
|
|
134
|
+
/** The apps of `templates` that are not apps (`names`, undefined: no app routing). */
|
|
135
|
+
static unknownApps(settings: TemplateSettings, names: readonly string[] | undefined): string[];
|
|
136
|
+
/** At start: every configured bundle, and the timer. Never throws. */
|
|
137
|
+
start(): Promise<void>;
|
|
138
|
+
/** A reload: the new settings for the next look; the bundles are compared now. */
|
|
139
|
+
update(settings: TemplateSettings): void;
|
|
140
|
+
stop(): void;
|
|
141
|
+
/** The current generation of an app's template, or undefined. */
|
|
142
|
+
current(app: string, template: string | undefined): TemplateGeneration | undefined;
|
|
143
|
+
/** The use of one request: undefined when its template has no bundle. */
|
|
144
|
+
use(app: string, template: string | undefined, baseVersion: string): TemplateUse | undefined;
|
|
145
|
+
/** `GET /_dokebi/templates/<app>/<template>/<buildId>/browser/…` of a kept generation. */
|
|
146
|
+
serve(path: string, reply: FastifyReply): Promise<FastifyReply>;
|
|
147
|
+
/** For tests and describe: the loaded generations. */
|
|
148
|
+
generations(): ReadonlyArray<{
|
|
149
|
+
app: string;
|
|
150
|
+
template: string;
|
|
151
|
+
buildId: string;
|
|
152
|
+
kept: string[];
|
|
153
|
+
}>;
|
|
154
|
+
}
|
|
155
|
+
/** Reads a request's template through web (`templateOf`), for `use`. */
|
|
156
|
+
export type TemplateOf = (request: FastifyRequest) => string | undefined;
|
|
157
|
+
export {};
|