@dokebi/template-inertia 0.4.21 → 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 +12 -0
- package/dist/errors.d.ts +1 -1
- package/dist/errors.js +1 -0
- package/dist/index.js +10 -2
- package/dist/template-build.js +27 -3
- 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 +12 -0
- package/dist/template-runtime.js +48 -0
- package/dist/template.d.ts +1 -0
- package/dist/template.js +1 -0
- package/package.json +7 -2
package/AI.md
CHANGED
|
@@ -301,6 +301,17 @@ A template can live apart from the app: a `views/<template>/` folder (Layout.vue
|
|
|
301
301
|
- **Logs:** info `INERTIA_TEMPLATE_LOADED` (app, template, name, version, buildId, previous, pages, rejectedPages, serverRendering, kept, ms), warn `INERTIA_TEMPLATE_PAGE_REJECTED`, info `INERTIA_TEMPLATE_REMOVED`, info `INERTIA_TEMPLATE_DEV_SKIPPED`.
|
|
302
302
|
- **Not under `dokebi dev`:** there the pages come from Vite, and bundles are not used (info `INERTIA_TEMPLATE_DEV_SKIPPED`); work on a template in the template repository.
|
|
303
303
|
|
|
304
|
+
**Screen words of a bundle (0.4.22, with @dokebi/i18n 0.2.10).** A template folder may hold `locales/<locale>/<namespace>.json` (the shape of `views/<template>/locales`, D-0282): `template build` copies them into the bundle (`locales/…`, hashed like the rest), and when the app loads the bundle they become the words of that template's pages, over the app's own template words, checked by the app's i18n (keys its catalogs have, the same placeholders, its locales). Words the app refuses leave the bundle in use with the words of before (warn `INERTIA_TEMPLATE_LOCALES_REJECTED`, with the reason); a new generation without words, or a template taken out of `templates`, takes them out. Without @dokebi/i18n they are not used (info `INERTIA_TEMPLATE_LOCALES_UNUSED`). An app on template-inertia before 0.4.22 refuses a bundle that holds `locales/`.
|
|
305
|
+
|
|
306
|
+
**Working on a template (0.4.22).**
|
|
307
|
+
|
|
308
|
+
- **Preview:** `npx dokebi template preview <dir> [--port 5180] [--host 127.0.0.1] [--config <vite config>]` in the template repository starts a Vite dev server (HMR, the repository's real vue, Inertia and SDK packages; no app server). `/` lists every page and its cases; `/__dokebi/preview/<page>?case=<case>` draws one in the template's Layout, and a `<Link>` to another preview URL is an Inertia visit. API: `startTemplatePreview(options)` of `@dokebi/template-inertia/template` → `{ url, pages, close() }`.
|
|
309
|
+
- `Pages/<page>.preview.json` beside the page: an object of named cases, `{ "default": { "total": 12000 }, "empty cart": { "total": 0 } }` (JSON data, case names letters, digits, space, `_ . -`; a page without one gets the case `default` with no props). The first case is the one `/__dokebi/preview/<page>` draws.
|
|
310
|
+
- `preview.json` of the template folder: `{ "shared": { "app": { "name": "site", "template": "luxe" }, "auth": { … } } }`, under every case (the props the app's shared data gives in production).
|
|
311
|
+
- The preview files are not in the bundle: `template build` builds the `.vue` pages only.
|
|
312
|
+
- The template's own words (`locales/`) become the `i18n` prop of every case (in `preview.json`'s `locale`, else the first locale folder), so pages that call `t()` draw; a case that gives its own `i18n` keeps it. Keys only the app's catalogs have show as their key in the preview.
|
|
313
|
+
- **doctor** (`npx dokebi doctor`, `--production` on the server where the bundles are mounted) checks every bundle of `templates` as the app will: a key that is not an app (`TEMPLATE_APP_UNKNOWN`), a missing bundle (`TEMPLATE_BUNDLE_MISSING`), one the app would refuse (`TEMPLATE_BUNDLE_INVALID`, the check's problems in `details`), shared modules the app build does not provide in the same major version (`TEMPLATE_BUNDLE_SHARED`, against `dist/.vite/dokebi-shared.json` and `dist/ssr/.vite/dokebi-shared.json`; `TEMPLATE_SHARED_FILE_MISSING` without them), and an Inertia entry without `verifyTemplate` (`TEMPLATE_BUNDLE_UNVERIFIED`). With `--production` a missing bundle, a missing shared file and a missing `verifyTemplate` are errors; without, warnings (a laptop has no mounts).
|
|
314
|
+
|
|
304
315
|
## 5. SSR (D-0039)
|
|
305
316
|
|
|
306
317
|
- `ssr.bundle` is a build file that exports `render(page) → { head: string[]; body: string }`. In Inertia v3, calling `createInertiaApp({ resolve, layout })` on the server without a page returns a `(page, renderToString)` function (see the `views/ssr.js` that `--ssr` creates).
|
|
@@ -384,6 +395,7 @@ A template can live apart from the app: a `views/<template>/` folder (Layout.vue
|
|
|
384
395
|
| `TEMPLATE_APP_UNKNOWN` | `InertiaError` | (D-0291) a key of `templates` is not an app of @dokebi/app (`data.apps`): stops the start, fails a reload (§4.3) |
|
|
385
396
|
| `TEMPLATE_BUILD_FAILED` | `InertiaError` | (`dokebi template build`, D-0291) the Vite build of a template failed, a page's server module could not be imported to read its `meta`, a `meta` is not JSON data or larger than 4 KiB, or the built bundle fails its own check; the original error is the `cause` (§4.3) |
|
|
386
397
|
| `INVALID_TEMPLATE_SHARED` | `InertiaUsageError` | (D-0291) `templates.shared` of `dokebiInertia()` or `--shared` names something that is not a package name with an optional subpath, more than 64, two names that make one entry, or a module that cannot be resolved or imported from the project (§4.3) |
|
|
398
|
+
| `INVALID_TEMPLATE_PREVIEW` | `InertiaUsageError` | (D-0291) `dokebi template preview`: the folder is outside the project or has no `Pages/**/*.vue`, or a `<Page>.preview.json` / `preview.json` is not the documented shape (§4.3) |
|
|
387
399
|
| `INVALID_TEMPLATE_BUILD` | `InertiaUsageError` | (D-0291) `dokebi template build`: the folder is missing, outside the project or has no page, a page path is not a page name, the name or version is wrong, or `--out` is the project, the template folder, or a folder that holds files and no earlier bundle (§4.3) |
|
|
388
400
|
| `INVALID_PRUNE` | `InertiaUsageError` | `pruneBuildFiles` without a manifest path, or an `olderThanMs`, `maxManifestBytes` or `now` that is not a whole number from 0 |
|
|
389
401
|
|
package/dist/errors.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { DokebiError, type DokebiErrorOptions } from '@dokebi/core';
|
|
|
2
2
|
/** Codes of `InertiaError` (failures of setup, files and the page flow). */
|
|
3
3
|
export type InertiaErrorCode = 'SSR_BUNDLE_MISSING' | 'SSR_BUNDLE_INVALID' | 'SSR_ENTRY_MISSING' | 'SSR_TIMEOUT' | 'VITE_MANIFEST_MISSING' | 'VITE_MANIFEST_INVALID' | 'VITE_DEV_MISSING' | 'VITE_DEV_UNAVAILABLE' | 'METHOD_NOT_ALLOWED' | 'CLOSED' | 'MODULE_PAGES_APP_MISSING' | 'MODULE_PAGES_FAILED' | 'TEMPLATE_BUILD_FAILED' | 'TEMPLATE_APP_UNKNOWN';
|
|
4
4
|
/** Codes of `InertiaUsageError` (a wrong argument: a TypeError, as before 0.4.0). */
|
|
5
|
-
export type InertiaUsageErrorCode = 'INVALID_ENTRY' | 'INVALID_SCOPE' | 'INVALID_RENDER' | 'INVALID_PROPS' | 'INVALID_URL' | 'INVALID_PROP_HELPER' | 'SSR_INVALID_RESULT' | 'INVALID_PRUNE' | 'INVALID_TEMPLATE_SHARED' | 'INVALID_TEMPLATE_BUILD';
|
|
5
|
+
export type InertiaUsageErrorCode = 'INVALID_ENTRY' | 'INVALID_SCOPE' | 'INVALID_RENDER' | 'INVALID_PROPS' | 'INVALID_URL' | 'INVALID_PROP_HELPER' | 'SSR_INVALID_RESULT' | 'INVALID_PRUNE' | 'INVALID_TEMPLATE_SHARED' | 'INVALID_TEMPLATE_BUILD' | 'INVALID_TEMPLATE_PREVIEW';
|
|
6
6
|
/** Failures of @dokebi/template-inertia; compare `code`, not the class. */
|
|
7
7
|
export declare class InertiaError extends DokebiError<InertiaErrorCode> {
|
|
8
8
|
constructor(code: InertiaErrorCode, message: string, options?: DokebiErrorOptions);
|
package/dist/errors.js
CHANGED
|
@@ -24,6 +24,7 @@ const FIX = {
|
|
|
24
24
|
SSR_INVALID_RESULT: 'The SSR render(page) must return { head: string[], body: string } whose body has the root element (rootId).',
|
|
25
25
|
INVALID_PRUNE: "pruneBuildFiles({ manifest: 'dist/.vite/manifest.json', olderThanMs?, dryRun?, maxManifestBytes?, now? }): a manifest path, and whole non-negative numbers.",
|
|
26
26
|
INVALID_TEMPLATE_SHARED: "Give dokebiInertia({ templates: { shared } }) (and dokebi template build --shared) installed package names with an optional subpath, at most 64, such as ['@shop/sdk', '@shop/sdk/components'] (D-0291).",
|
|
27
|
+
INVALID_TEMPLATE_PREVIEW: 'dokebi template preview <dir>: a template folder inside the project with Pages/**/*.vue; each <Page>.preview.json is an object of case name → props ({ "default": { … } }), and preview.json of the folder is { "shared": { … } }, both JSON data up to 1 MiB (D-0291).',
|
|
27
28
|
INVALID_TEMPLATE_BUILD: 'dokebi template build <dir>: a folder with Layout.vue and/or Pages/**/*.vue inside the project, a template name (^[a-z][a-z0-9-]{0,31}$), a version (letters, digits, . + -) and an --out folder that is neither the project nor the template folder (D-0291).',
|
|
28
29
|
};
|
|
29
30
|
/** Failures of @dokebi/template-inertia; compare `code`, not the class. */
|
package/dist/index.js
CHANGED
|
@@ -299,6 +299,7 @@ const session = optionalDependency({
|
|
|
299
299
|
name: 'dokebi-session',
|
|
300
300
|
version: '^0.4.0',
|
|
301
301
|
});
|
|
302
|
+
const i18n = optionalDependency({ name: 'dokebi-i18n', version: '^0.2.0' });
|
|
302
303
|
/** The boot text of a scope for its debug record: the CSP hashes of its inline style and script. */
|
|
303
304
|
function bootLog(options) {
|
|
304
305
|
const boot = options.bootFallback;
|
|
@@ -863,11 +864,18 @@ class InertiaRuntime {
|
|
|
863
864
|
const templateApps = Object.keys(this.settings.templates.templates);
|
|
864
865
|
let templateRuntime;
|
|
865
866
|
if (serving && !describing && !develop) {
|
|
867
|
+
const translations = context.getOptionalDependency(i18n);
|
|
866
868
|
const loaded = new TemplateBundles({
|
|
867
869
|
logger,
|
|
868
870
|
settings: this.settings.templates,
|
|
869
871
|
verify: this.entry.verifyTemplate,
|
|
870
872
|
repeat: (key) => repeats.take(key),
|
|
873
|
+
// D-0291 stage 3b: a bundle's locales/ become its template's screen words.
|
|
874
|
+
...(typeof translations?.templateBundle === 'function'
|
|
875
|
+
? {
|
|
876
|
+
words: (app, template, directory) => translations.templateBundle(app, template, directory),
|
|
877
|
+
}
|
|
878
|
+
: {}),
|
|
871
879
|
});
|
|
872
880
|
templateRuntime = loaded;
|
|
873
881
|
this.#templates = { bundles: loaded, server };
|
|
@@ -1203,12 +1211,12 @@ class InertiaRuntime {
|
|
|
1203
1211
|
}
|
|
1204
1212
|
export const createPlugin = definePlugin({
|
|
1205
1213
|
name: 'dokebi-template-inertia',
|
|
1206
|
-
version: '0.4.
|
|
1214
|
+
version: '0.4.22',
|
|
1207
1215
|
core: '^0.4.2',
|
|
1208
1216
|
options,
|
|
1209
1217
|
entry: parseEntry,
|
|
1210
1218
|
contributes: [viewEngines],
|
|
1211
1219
|
collects: [viewData],
|
|
1212
|
-
dependencies: () => [web, session],
|
|
1220
|
+
dependencies: () => [web, session, i18n],
|
|
1213
1221
|
instance: ({ options, entry }) => new InertiaRuntime(settings(options), entry ?? {}),
|
|
1214
1222
|
});
|
package/dist/template-build.js
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
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
8
|
import { existsSync, readFileSync, realpathSync } from 'node:fs';
|
|
9
|
-
import { lstat, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
|
|
9
|
+
import { lstat, mkdir, 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';
|
|
12
12
|
import { ConsoleLogger } from '@dokebi/core';
|
|
@@ -15,7 +15,7 @@ import { checkTemplateBundle, jsonValue, PAGE_META_MAX_BYTES, SHARED_DEFAULTS, S
|
|
|
15
15
|
import { packageVersion } from './template-shared.js';
|
|
16
16
|
import { registerVueTypeScript } from './vue-typescript.js';
|
|
17
17
|
/** The builder written into `builtWith` (scripts/testing/check-metadata.mjs keeps it the package version). */
|
|
18
|
-
const BUILDER = { name: 'dokebi-template-inertia', version: '0.4.
|
|
18
|
+
const BUILDER = { name: 'dokebi-template-inertia', version: '0.4.22' };
|
|
19
19
|
function defaultLogger() {
|
|
20
20
|
return new ConsoleLogger({ level: 'info' }, { plugin: 'dokebi-template-inertia', process: 'template-build' });
|
|
21
21
|
}
|
|
@@ -317,8 +317,31 @@ export async function buildTemplateBundle(options) {
|
|
|
317
317
|
...(meta === undefined ? {} : { meta }),
|
|
318
318
|
};
|
|
319
319
|
}
|
|
320
|
+
// D-0291 stage 3b: the template's screen words, locales/<locale>/<namespace>.json, as they are
|
|
321
|
+
// (the app's @dokebi/i18n reads them with its own loader and rules).
|
|
322
|
+
const wordsFolder = join(folder, 'locales');
|
|
323
|
+
let wordFiles = 0;
|
|
324
|
+
if (existsSync(wordsFolder))
|
|
325
|
+
for (const file of await listFiles(wordsFolder)) {
|
|
326
|
+
if (file.split('/').some((part) => part.startsWith('.')))
|
|
327
|
+
continue;
|
|
328
|
+
if (!/^[A-Za-z][A-Za-z0-9_-]{0,34}(?:\/[A-Za-z0-9_][A-Za-z0-9_.-]{0,99}){1,8}\.json$/.test(file))
|
|
329
|
+
throw usage(`locales/${file} is not a screen-word file: locales/<locale>/<namespace>.json (letters, digits, _ . -)`);
|
|
330
|
+
const text = await readFile(join(wordsFolder, file), 'utf8');
|
|
331
|
+
try {
|
|
332
|
+
const parsed = JSON.parse(text);
|
|
333
|
+
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed))
|
|
334
|
+
throw new Error('not an object of keys');
|
|
335
|
+
}
|
|
336
|
+
catch (cause) {
|
|
337
|
+
throw new InertiaError('TEMPLATE_BUILD_FAILED', `locales/${file} is not a JSON object of words: ${cause.message}`, { cause });
|
|
338
|
+
}
|
|
339
|
+
await mkdir(dirname(join(out, 'locales', file)), { recursive: true });
|
|
340
|
+
await writeFile(join(out, 'locales', file), text);
|
|
341
|
+
wordFiles++;
|
|
342
|
+
}
|
|
320
343
|
const files = {};
|
|
321
|
-
for (const top of ['browser', 'ssr'])
|
|
344
|
+
for (const top of wordFiles ? ['browser', 'ssr', 'locales'] : ['browser', 'ssr'])
|
|
322
345
|
for (const file of await listFiles(join(out, top))) {
|
|
323
346
|
const content = await readFile(join(out, top, file));
|
|
324
347
|
files[`${top}/${file}`] = { bytes: content.length, sha256: sha256(content) };
|
|
@@ -356,6 +379,7 @@ export async function buildTemplateBundle(options) {
|
|
|
356
379
|
buildId: result.buildId,
|
|
357
380
|
out: relative(root, out),
|
|
358
381
|
pages: result.pages.length,
|
|
382
|
+
words: wordFiles,
|
|
359
383
|
files: result.files,
|
|
360
384
|
bytes: result.bytes,
|
|
361
385
|
shared: manifest.shared,
|
package/dist/template-bundle.js
CHANGED
|
@@ -26,8 +26,13 @@ export const TEMPLATE_NAME = /^[a-z][a-z0-9-]{0,31}$/;
|
|
|
26
26
|
export const TEMPLATE_VERSION = /^[0-9A-Za-z][0-9A-Za-z.+-]{0,63}$/;
|
|
27
27
|
/** A page of a bundle: `Layout`, or `Pages/<path>` without the `.vue`. */
|
|
28
28
|
export const TEMPLATE_PAGE = /^(?:Layout|Pages(?:\/[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}){1,16})$/;
|
|
29
|
-
/**
|
|
30
|
-
|
|
29
|
+
/**
|
|
30
|
+
* A file of a bundle: under browser/ or ssr/, or a screen-word file `locales/<locale>/<ns>.json`
|
|
31
|
+
* (D-0291 stage 3b), plain path segments only.
|
|
32
|
+
*/
|
|
33
|
+
const FILE = /^(?:(?:browser|ssr)(?:\/[A-Za-z0-9_@+][A-Za-z0-9_.@+-]{0,199}){1,32}|locales\/[A-Za-z][A-Za-z0-9_-]{0,34}(?:\/[A-Za-z0-9_][A-Za-z0-9_.-]{0,99}){1,8}\.json)$/;
|
|
34
|
+
/** The folders of a bundle. */
|
|
35
|
+
const FOLDERS = ['browser', 'ssr', 'locales'];
|
|
31
36
|
/** A shared module specifier: a package name with an optional subpath. */
|
|
32
37
|
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
38
|
/** A page's `meta` (JSON) may take this many bytes. */
|
|
@@ -86,7 +91,7 @@ export function manifestProblem(value) {
|
|
|
86
91
|
return 'files must be an object of path → { bytes, sha256 }';
|
|
87
92
|
for (const [file, entry] of Object.entries(value.files)) {
|
|
88
93
|
if (!FILE.test(file) || file.split('/').some((part) => part === '..' || part === '.'))
|
|
89
|
-
return `file ${file} is not a path under browser/ or ssr
|
|
94
|
+
return `file ${file} is not a path under browser/ or ssr/, or a locales/<locale>/<namespace>.json`;
|
|
90
95
|
if (!plain(entry) ||
|
|
91
96
|
!Number.isSafeInteger(entry.bytes) ||
|
|
92
97
|
entry.bytes < 0 ||
|
|
@@ -238,7 +243,7 @@ export async function checkTemplateBundle(dir, limits = {}) {
|
|
|
238
243
|
return { manifest, buildId, bytes: 0, problems };
|
|
239
244
|
const found = [];
|
|
240
245
|
const links = [];
|
|
241
|
-
for (const top of
|
|
246
|
+
for (const top of FOLDERS) {
|
|
242
247
|
try {
|
|
243
248
|
const info = await lstat(join(dir, top));
|
|
244
249
|
if (!info.isDirectory()) {
|
|
@@ -255,12 +260,11 @@ export async function checkTemplateBundle(dir, limits = {}) {
|
|
|
255
260
|
for (const entry of await readdir(dir, { withFileTypes: true }))
|
|
256
261
|
if (entry.name !== TEMPLATE_MANIFEST &&
|
|
257
262
|
entry.name !== TEMPLATE_SIGNATURE &&
|
|
258
|
-
entry.name
|
|
259
|
-
entry.name !== 'ssr')
|
|
263
|
+
!FOLDERS.includes(entry.name))
|
|
260
264
|
problems.push({
|
|
261
265
|
code: 'TEMPLATE_FILE_EXTRA',
|
|
262
266
|
file: entry.name,
|
|
263
|
-
message: `${entry.name} is not part of a bundle (only ${TEMPLATE_MANIFEST}, ${TEMPLATE_SIGNATURE}, browser/ and
|
|
267
|
+
message: `${entry.name} is not part of a bundle (only ${TEMPLATE_MANIFEST}, ${TEMPLATE_SIGNATURE}, browser/, ssr/ and locales/)`,
|
|
264
268
|
});
|
|
265
269
|
for (const link of links)
|
|
266
270
|
problems.push({
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { type Logger } from '@dokebi/core';
|
|
2
|
+
/** Where a page is drawn: `/__dokebi/preview/<page>?case=<case>`. */
|
|
3
|
+
export declare const PREVIEW_PREFIX = "/__dokebi/preview/";
|
|
4
|
+
export interface TemplatePreviewOptions {
|
|
5
|
+
/** The template repository root (its node_modules has vite and @vitejs/plugin-vue). */
|
|
6
|
+
readonly root?: string;
|
|
7
|
+
/** The template folder, relative to root. */
|
|
8
|
+
readonly dir: string;
|
|
9
|
+
/** 0 picks a free port (default 5180). */
|
|
10
|
+
readonly port?: number;
|
|
11
|
+
/** Default 127.0.0.1 (loopback only). */
|
|
12
|
+
readonly host?: string;
|
|
13
|
+
/** A vite config of the project to merge; @vitejs/plugin-vue is added unless it has its own. */
|
|
14
|
+
readonly config?: string;
|
|
15
|
+
readonly logger?: Logger;
|
|
16
|
+
}
|
|
17
|
+
export interface TemplatePreviewPage {
|
|
18
|
+
/** The page name (`Home`, `board/List`), as `render(…, 'Home')` names it. */
|
|
19
|
+
readonly page: string;
|
|
20
|
+
readonly cases: readonly string[];
|
|
21
|
+
}
|
|
22
|
+
export interface TemplatePreview {
|
|
23
|
+
readonly url: string;
|
|
24
|
+
readonly pages: readonly TemplatePreviewPage[];
|
|
25
|
+
close(): Promise<void>;
|
|
26
|
+
}
|
|
27
|
+
/** The cases of one page (`<Page>.preview.json`): case → props, checked. */
|
|
28
|
+
export declare function previewCases(file: string): Promise<Record<string, Record<string, unknown>>>;
|
|
29
|
+
/**
|
|
30
|
+
* D-0291 stage 3b: the `i18n` page prop of the preview from the template's own words
|
|
31
|
+
* (`locales/<locale>/<namespace>.json`), so pages that call t() draw; undefined without words.
|
|
32
|
+
*/
|
|
33
|
+
export declare function previewWords(folder: string, wanted?: string): Promise<Record<string, unknown> | undefined>;
|
|
34
|
+
/**
|
|
35
|
+
* Starts the preview of the template folder `options.dir` (D-0291 stage 3). Resolves once the
|
|
36
|
+
* server listens; `close()` stops it.
|
|
37
|
+
*/
|
|
38
|
+
export declare function startTemplatePreview(options: TemplatePreviewOptions): Promise<TemplatePreview>;
|
|
@@ -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
|
+
}
|
|
@@ -110,6 +110,18 @@ export interface TemplateBundlesOptions {
|
|
|
110
110
|
/** `logRepeatWindowMs`: a failure of the same cause is said once per window. */
|
|
111
111
|
readonly repeat: (key: string) => number | false | undefined;
|
|
112
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
|
+
}>;
|
|
113
125
|
}
|
|
114
126
|
/** Every app's template bundles. */
|
|
115
127
|
export declare class TemplateBundles {
|
package/dist/template-runtime.js
CHANGED
|
@@ -181,6 +181,7 @@ export class TemplateBundles {
|
|
|
181
181
|
#verify;
|
|
182
182
|
#repeat;
|
|
183
183
|
#production;
|
|
184
|
+
#words;
|
|
184
185
|
#settings;
|
|
185
186
|
#apps = new Map();
|
|
186
187
|
#slots = new Map();
|
|
@@ -194,6 +195,7 @@ export class TemplateBundles {
|
|
|
194
195
|
this.#verify = options.verify;
|
|
195
196
|
this.#repeat = options.repeat;
|
|
196
197
|
this.#production = options.production ?? process.env.NODE_ENV === 'production';
|
|
198
|
+
this.#words = options.words;
|
|
197
199
|
this.#cacheRoot = resolve(options.settings.cacheDir);
|
|
198
200
|
const store = this.#store;
|
|
199
201
|
globalThis[TEMPLATE_REGISTRY] = Object.freeze({
|
|
@@ -272,6 +274,7 @@ export class TemplateBundles {
|
|
|
272
274
|
kept: [],
|
|
273
275
|
seen: undefined,
|
|
274
276
|
loading: undefined,
|
|
277
|
+
words: false,
|
|
275
278
|
};
|
|
276
279
|
this.#slots.set(key, slot);
|
|
277
280
|
}
|
|
@@ -284,6 +287,8 @@ export class TemplateBundles {
|
|
|
284
287
|
for (const [key, slot] of this.#slots)
|
|
285
288
|
if (!wanted.has(key)) {
|
|
286
289
|
this.#slots.delete(key);
|
|
290
|
+
if (slot.words)
|
|
291
|
+
work.push(this.#setWords(slot, undefined, undefined));
|
|
287
292
|
this.#logger.log('info', 'Template bundle no longer configured; the app pages answer', {
|
|
288
293
|
code: 'INERTIA_TEMPLATE_REMOVED',
|
|
289
294
|
app: slot.app,
|
|
@@ -570,6 +575,11 @@ export class TemplateBundles {
|
|
|
570
575
|
if (target !== undefined)
|
|
571
576
|
importMap[module] = target;
|
|
572
577
|
}
|
|
578
|
+
// D-0291 stage 3b: the bundle's screen words, just before it serves (a refused set leaves the
|
|
579
|
+
// bundle in use with the words of before; a bundle without words takes them out).
|
|
580
|
+
const hasWords = Object.keys(manifest.files).some((file) => file.startsWith('locales/'));
|
|
581
|
+
if (hasWords || slot.words)
|
|
582
|
+
await this.#setWords(slot, hasWords ? join(dir, 'locales') : undefined, buildId);
|
|
573
583
|
const generation = new TemplateGeneration(slot.app, slot.template, buildId, manifest, dir, pages, server, importMap, [...refused]);
|
|
574
584
|
const previous = slot.current;
|
|
575
585
|
slot.current = generation;
|
|
@@ -596,6 +606,44 @@ export class TemplateBundles {
|
|
|
596
606
|
this.#fail(slot, error);
|
|
597
607
|
}
|
|
598
608
|
}
|
|
609
|
+
/** D-0291 stage 3b: hands a generation's words (or none) to @dokebi/i18n. Never throws. */
|
|
610
|
+
async #setWords(slot, directory, buildId) {
|
|
611
|
+
const words = this.#words;
|
|
612
|
+
if (!words) {
|
|
613
|
+
if (directory !== undefined) {
|
|
614
|
+
const repeated = this.#repeat(`words unused ${slot.app} ${slot.template}`);
|
|
615
|
+
if (repeated !== undefined)
|
|
616
|
+
this.#logger.log('info', 'Template bundle words are not used: @dokebi/i18n is not registered', {
|
|
617
|
+
code: 'INERTIA_TEMPLATE_LOCALES_UNUSED',
|
|
618
|
+
app: slot.app,
|
|
619
|
+
template: slot.template,
|
|
620
|
+
});
|
|
621
|
+
}
|
|
622
|
+
return;
|
|
623
|
+
}
|
|
624
|
+
let answer;
|
|
625
|
+
try {
|
|
626
|
+
answer = await words(slot.app, slot.template, directory);
|
|
627
|
+
}
|
|
628
|
+
catch (error) {
|
|
629
|
+
answer = { ok: false, reason: error.message };
|
|
630
|
+
}
|
|
631
|
+
if (answer.ok) {
|
|
632
|
+
slot.words = directory !== undefined;
|
|
633
|
+
return;
|
|
634
|
+
}
|
|
635
|
+
const repeated = this.#repeat(`words ${slot.app} ${slot.template} ${answer.reason}`);
|
|
636
|
+
if (repeated !== undefined)
|
|
637
|
+
this.#logger.log('warn', 'Template bundle words refused; its pages keep the words of before', {
|
|
638
|
+
code: 'INERTIA_TEMPLATE_LOCALES_REJECTED',
|
|
639
|
+
app: slot.app,
|
|
640
|
+
template: slot.template,
|
|
641
|
+
buildId: buildId ?? null,
|
|
642
|
+
reason: answer.reason,
|
|
643
|
+
...(repeated ? { repeated } : {}),
|
|
644
|
+
fix: 'Replace only keys the app’s catalogs have, with the same placeholders and in the app’s locales (D-0282 rules), then build the bundle again.',
|
|
645
|
+
});
|
|
646
|
+
}
|
|
599
647
|
/** A package.json at the cache root: the bundle's .js modules are ES modules. */
|
|
600
648
|
async #ensureModuleScope() {
|
|
601
649
|
const file = join(this.#cacheRoot, 'package.json');
|
package/dist/template.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
1
|
export { buildTemplateBundle, packageEntry, type TemplateBuildOptions, type TemplateBuildResult, templatePages, } from './template-build.js';
|
|
2
2
|
export { checkTemplateBundle, compatibleLine, type ProvidedShared, SERVER_ONLY_SHARED, SHARED_DEFAULTS, sharedProblems, TEMPLATE_FORMAT, TEMPLATE_MANIFEST, TEMPLATE_MAX_BYTES, TEMPLATE_NAME, TEMPLATE_SIGNATURE, type TemplateCheck, type TemplateCheckLimits, type TemplateManifest, type TemplatePage, type TemplateProblem, } from './template-bundle.js';
|
|
3
|
+
export { PREVIEW_PREFIX, previewCases, previewWords, startTemplatePreview, type TemplatePreview, type TemplatePreviewOptions, type TemplatePreviewPage, } from './template-preview.js';
|
|
3
4
|
export { type DokebiInertiaTemplateOptions, packageVersion, SHARED_FILE, type SharedFile, sharedEntryName, } from './template-shared.js';
|
package/dist/template.js
CHANGED
|
@@ -2,4 +2,5 @@
|
|
|
2
2
|
// the build that `dokebi template build` runs in a template repository.
|
|
3
3
|
export { buildTemplateBundle, packageEntry, templatePages, } from './template-build.js';
|
|
4
4
|
export { checkTemplateBundle, compatibleLine, SERVER_ONLY_SHARED, SHARED_DEFAULTS, sharedProblems, TEMPLATE_FORMAT, TEMPLATE_MANIFEST, TEMPLATE_MAX_BYTES, TEMPLATE_NAME, TEMPLATE_SIGNATURE, } from './template-bundle.js';
|
|
5
|
+
export { PREVIEW_PREFIX, previewCases, previewWords, startTemplatePreview, } from './template-preview.js';
|
|
5
6
|
export { packageVersion, SHARED_FILE, sharedEntryName, } from './template-shared.js';
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dokebi/template-inertia",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.22",
|
|
4
4
|
"description": "Inertia v3 server adapter for Dokebi: page JSON, Vite manifest assets and optional server-side rendering.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"dokebi",
|
|
@@ -87,6 +87,11 @@
|
|
|
87
87
|
"name": "dokebi-session",
|
|
88
88
|
"version": "^0.4.0",
|
|
89
89
|
"optional": true
|
|
90
|
+
},
|
|
91
|
+
{
|
|
92
|
+
"name": "dokebi-i18n",
|
|
93
|
+
"version": "^0.2.0",
|
|
94
|
+
"optional": true
|
|
90
95
|
}
|
|
91
96
|
],
|
|
92
97
|
"contributes": [
|
|
@@ -147,7 +152,7 @@
|
|
|
147
152
|
]
|
|
148
153
|
},
|
|
149
154
|
"devDependencies": {
|
|
150
|
-
"@dokebi/i18n": "0.2.
|
|
155
|
+
"@dokebi/i18n": "0.2.10",
|
|
151
156
|
"@dokebi/session": "0.4.11",
|
|
152
157
|
"@dokebi/web": "0.4.27",
|
|
153
158
|
"@dokebi/websocket": "0.4.10",
|