@dokebi/template-inertia 0.4.26 → 0.4.27

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.
@@ -11,11 +11,11 @@ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'nod
11
11
  import { pathToFileURL } from 'node:url';
12
12
  import { ConsoleLogger } from '@dokebi/core';
13
13
  import { InertiaError, InertiaUsageError } from './errors.js';
14
- import { checkTemplateBundle, jsonValue, PAGE_META_MAX_BYTES, SHARED_DEFAULTS, SHARED_SPECIFIER, sha256, TEMPLATE_FILE, TEMPLATE_FORMAT, TEMPLATE_MANIFEST, TEMPLATE_MAX_BYTES, TEMPLATE_NAME, TEMPLATE_PAGE, TEMPLATE_VERSION, } from './template-bundle.js';
14
+ import { checkTemplateBundle, cspDeclarationProblem, jsonValue, PAGE_META_MAX_BYTES, SHARED_DEFAULTS, SHARED_SPECIFIER, sha256, TEMPLATE_FILE, TEMPLATE_FORMAT, TEMPLATE_MANIFEST, TEMPLATE_MAX_BYTES, TEMPLATE_NAME, TEMPLATE_PAGE, TEMPLATE_STYLES_MAX, TEMPLATE_VERSION, } from './template-bundle.js';
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.26' };
18
+ const BUILDER = { name: 'dokebi-template-inertia', version: '0.4.27' };
19
19
  /** D-0296: carried files go under this folder of the bundle (served like the pages' files). */
20
20
  export const TEMPLATE_CARRY_FOLDER = 'browser';
21
21
  /** The folders Vite writes under browser/: a carried file never takes them (any case). */
@@ -106,7 +106,7 @@ async function listFiles(dir, root = dir, found = []) {
106
106
  * folder. A path is relative to the folder, a plain file inside it (no link on the way), not one of
107
107
  * Vite's folders, and a bundle file name.
108
108
  */
109
- async function carriedFiles(folder, paths) {
109
+ export async function carriedFiles(folder, paths) {
110
110
  const carried = new Map();
111
111
  const real = realpathSync(folder);
112
112
  for (const path of paths) {
@@ -133,6 +133,39 @@ async function carriedFiles(folder, paths) {
133
133
  }
134
134
  return carried;
135
135
  }
136
+ /** D-0297: the file of a template folder that declares the sources of other origins it uses. */
137
+ export const TEMPLATE_CSP_FILE = 'csp.json';
138
+ /**
139
+ * D-0297: the template folder's `csp.json`, checked (INVALID_TEMPLATE_BUILD), each list sorted and
140
+ * without repeats, empty lists left out; undefined without the file or with nothing in it.
141
+ */
142
+ export async function templateCsp(folder) {
143
+ const file = join(folder, TEMPLATE_CSP_FILE);
144
+ let text;
145
+ try {
146
+ text = await readFile(file, 'utf8');
147
+ }
148
+ catch (error) {
149
+ if (error.code === 'ENOENT')
150
+ return undefined;
151
+ throw error;
152
+ }
153
+ let parsed;
154
+ try {
155
+ parsed = JSON.parse(text);
156
+ }
157
+ catch (cause) {
158
+ throw new InertiaError('TEMPLATE_BUILD_FAILED', `${TEMPLATE_CSP_FILE} is not JSON: ${cause.message}`, { cause });
159
+ }
160
+ const problem = cspDeclarationProblem(parsed);
161
+ if (problem)
162
+ throw usage(`${TEMPLATE_CSP_FILE}: ${problem}`);
163
+ const declared = {};
164
+ for (const [name, sources] of Object.entries(parsed).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))
165
+ if (sources.length)
166
+ declared[name] = [...new Set(sources)].sort();
167
+ return Object.keys(declared).length ? declared : undefined;
168
+ }
136
169
  const outputs = (result) => (Array.isArray(result) ? result : [result]).flatMap((item) => item.output ?? []);
137
170
  /**
138
171
  * Builds the template folder `options.dir` of `options.root` into a bundle at `options.out`
@@ -177,6 +210,17 @@ export async function buildTemplateBundle(options) {
177
210
  const shared = [...new Set([...SHARED_DEFAULTS, ...own])];
178
211
  // Before anything is emptied or built.
179
212
  const carry = await carriedFiles(folder, options.carry ?? []);
213
+ // D-0298: the stylesheets are carried files too, in their order.
214
+ const styleFiles = await carriedFiles(folder, options.styles ?? []);
215
+ for (const [target, file] of styleFiles) {
216
+ if (!target.endsWith('.css'))
217
+ throw usage(`--style ${target.slice(TEMPLATE_CARRY_FOLDER.length + 1)} is not a .css file`);
218
+ carry.set(target, file);
219
+ }
220
+ const styles = [...styleFiles.keys()];
221
+ if (styles.length > TEMPLATE_STYLES_MAX)
222
+ throw usage(`--style names ${styles.length} stylesheets; at most ${TEMPLATE_STYLES_MAX}`);
223
+ const csp = await templateCsp(folder);
180
224
  const out = resolve(root, options.out ?? join('dist', 'template', name));
181
225
  if (!within(out, root) || within(root, out) || within(folder, out) || within(out, folder))
182
226
  throw usage(`--out ${relative(root, out) || '.'} must be a folder inside the project, apart from the template folder (the build imports the server pages from there)`);
@@ -190,170 +234,176 @@ export async function buildTemplateBundle(options) {
190
234
  await rm(out, { recursive: true, force: true });
191
235
  }
192
236
  const pages = await templatePages(folder);
193
- if (pages.size === 0)
194
- throw usage(`${options.dir} has no Layout.vue and no Pages/**/*.vue`);
195
- const input = Object.fromEntries(pages);
196
- const vite = await importPackage(root, 'vite', 'Install Vite in the template repository: npm install --save-dev vite');
197
- // The project's vite config (--config) may bring its own Vue plugin; otherwise one is added.
198
- const configFile = options.config ? resolve(root, options.config) : undefined;
199
- let ownVue = false;
200
- if (configFile) {
201
- const loaded = (await vite.loadConfigFromFile({ command: 'build', mode: 'production' }, configFile, root)) ?? {
202
- config: {},
203
- };
204
- const names = (loaded.config.plugins ?? [])
205
- .flat(Infinity)
206
- .map((plugin) => plugin?.name);
207
- ownVue = names.includes('vite:vue');
208
- }
209
- const vue = ownVue
210
- ? undefined
211
- : await importPackage(root, '@vitejs/plugin-vue', 'Install the Vue plugin in the template repository: npm install --save-dev @vitejs/plugin-vue');
212
- registerVueTypeScript(root, logger);
213
- const isShared = (id) => shared.includes(id);
214
- logger.log('info', 'Template bundle build started', {
215
- code: 'INERTIA_TEMPLATE_BUILD_STARTED',
216
- name,
217
- version,
218
- dir: relative(root, folder),
219
- out: relative(root, out),
220
- pages: pages.size,
221
- shared,
222
- });
223
- const common = {
224
- root,
225
- configFile: configFile ?? false,
226
- logLevel: 'warn',
227
- publicDir: false,
228
- // The compiler reads the props types a page imports from files (as the app's vite config does).
229
- plugins: vue ? [vue.default({ script: { fs: VUE_TYPE_FILES } })] : [],
230
- };
237
+ // D-0298: a template of styles alone (carried files, screen words) is a bundle too.
238
+ if (pages.size === 0 && carry.size === 0 && !existsSync(join(folder, 'locales')))
239
+ throw usage(`${options.dir} has no Layout.vue, no Pages/**/*.vue and nothing carried (--style, --carry) or locales/`);
231
240
  const imported = new Set();
232
- const collect = (items) => {
233
- for (const item of items)
234
- for (const id of [...(item.imports ?? []), ...(item.dynamicImports ?? [])])
235
- if (isShared(id))
236
- imported.add(id);
237
- };
238
- let browserItems;
239
- let serverItems;
240
- // `vite build` sets process.env.NODE_ENV to production: a caller in the same process (a
241
- // test, a script that builds and then serves) gets it back as it was.
242
- const environment = process.env.NODE_ENV;
243
- try {
244
- browserItems = outputs(await vite.build({
245
- ...common,
246
- base: './',
247
- build: {
248
- outDir: join(out, 'browser'),
249
- emptyOutDir: true,
250
- manifest: true,
251
- cssCodeSplit: true,
252
- modulePreload: false,
253
- copyPublicDir: false,
254
- rollupOptions: {
255
- input,
256
- external: isShared,
257
- preserveEntrySignatures: 'strict',
258
- output: {
259
- entryFileNames: 'pages/[name]-[hash].js',
260
- chunkFileNames: 'chunks/[name]-[hash].js',
261
- assetFileNames: 'assets/[name]-[hash][extname]',
241
+ const pageEntries = {};
242
+ // D-0298: a bundle without pages (styles and other carried files only) runs no Vite build.
243
+ if (pages.size > 0) {
244
+ const input = Object.fromEntries(pages);
245
+ const vite = await importPackage(root, 'vite', 'Install Vite in the template repository: npm install --save-dev vite');
246
+ // The project's vite config (--config) may bring its own Vue plugin; otherwise one is added.
247
+ const configFile = options.config ? resolve(root, options.config) : undefined;
248
+ let ownVue = false;
249
+ if (configFile) {
250
+ const loaded = (await vite.loadConfigFromFile({ command: 'build', mode: 'production' }, configFile, root)) ?? {
251
+ config: {},
252
+ };
253
+ const names = (loaded.config.plugins ?? [])
254
+ .flat(Infinity)
255
+ .map((plugin) => plugin?.name);
256
+ ownVue = names.includes('vite:vue');
257
+ }
258
+ const vue = ownVue
259
+ ? undefined
260
+ : await importPackage(root, '@vitejs/plugin-vue', 'Install the Vue plugin in the template repository: npm install --save-dev @vitejs/plugin-vue');
261
+ registerVueTypeScript(root, logger);
262
+ const isShared = (id) => shared.includes(id);
263
+ logger.log('info', 'Template bundle build started', {
264
+ code: 'INERTIA_TEMPLATE_BUILD_STARTED',
265
+ name,
266
+ version,
267
+ dir: relative(root, folder),
268
+ out: relative(root, out),
269
+ pages: pages.size,
270
+ shared,
271
+ });
272
+ const common = {
273
+ root,
274
+ configFile: configFile ?? false,
275
+ logLevel: 'warn',
276
+ publicDir: false,
277
+ // The compiler reads the props types a page imports from files (as the app's vite config does).
278
+ plugins: vue ? [vue.default({ script: { fs: VUE_TYPE_FILES } })] : [],
279
+ };
280
+ const collect = (items) => {
281
+ for (const item of items)
282
+ for (const id of [...(item.imports ?? []), ...(item.dynamicImports ?? [])])
283
+ if (isShared(id))
284
+ imported.add(id);
285
+ };
286
+ let browserItems;
287
+ let serverItems;
288
+ // `vite build` sets process.env.NODE_ENV to production: a caller in the same process (a
289
+ // test, a script that builds and then serves) gets it back as it was.
290
+ const environment = process.env.NODE_ENV;
291
+ try {
292
+ browserItems = outputs(await vite.build({
293
+ ...common,
294
+ base: './',
295
+ build: {
296
+ outDir: join(out, 'browser'),
297
+ emptyOutDir: true,
298
+ manifest: true,
299
+ cssCodeSplit: true,
300
+ modulePreload: false,
301
+ copyPublicDir: false,
302
+ rollupOptions: {
303
+ input,
304
+ external: isShared,
305
+ preserveEntrySignatures: 'strict',
306
+ output: {
307
+ entryFileNames: 'pages/[name]-[hash].js',
308
+ chunkFileNames: 'chunks/[name]-[hash].js',
309
+ assetFileNames: 'assets/[name]-[hash][extname]',
310
+ },
262
311
  },
263
312
  },
264
- },
265
- }));
266
- serverItems = outputs(await vite.build({
267
- ...common,
268
- ssr: { noExternal: true },
269
- build: {
270
- ssr: true,
271
- outDir: join(out, 'ssr'),
272
- emptyOutDir: true,
273
- copyPublicDir: false,
274
- rollupOptions: {
275
- input,
276
- external: isShared,
277
- preserveEntrySignatures: 'strict',
278
- output: {
279
- format: 'es',
280
- entryFileNames: 'pages/[name].js',
281
- chunkFileNames: 'chunks/[name]-[hash].js',
313
+ }));
314
+ serverItems = outputs(await vite.build({
315
+ ...common,
316
+ ssr: { noExternal: true },
317
+ build: {
318
+ ssr: true,
319
+ outDir: join(out, 'ssr'),
320
+ emptyOutDir: true,
321
+ copyPublicDir: false,
322
+ rollupOptions: {
323
+ input,
324
+ external: isShared,
325
+ preserveEntrySignatures: 'strict',
326
+ output: {
327
+ format: 'es',
328
+ entryFileNames: 'pages/[name].js',
329
+ chunkFileNames: 'chunks/[name]-[hash].js',
330
+ },
282
331
  },
283
332
  },
284
- },
285
- }));
286
- }
287
- catch (cause) {
288
- throw new InertiaError('TEMPLATE_BUILD_FAILED', `The Vite build of ${name} failed`, { cause });
289
- }
290
- finally {
291
- if (environment === undefined)
292
- delete process.env.NODE_ENV;
293
- else
294
- process.env.NODE_ENV = environment;
295
- }
296
- collect(browserItems);
297
- collect(serverItems);
298
- // The browser manifest gives each page its stylesheets and the chunks it imports.
299
- const manifestPath = join(out, 'browser', '.vite', 'manifest.json');
300
- const vm = JSON.parse(await readFile(manifestPath, 'utf8'));
301
- await rm(join(out, 'browser', '.vite'), { recursive: true, force: true });
302
- const byName = new Map();
303
- for (const entry of Object.values(vm))
304
- if (entry.isEntry && entry.name)
305
- byName.set(entry.name, entry);
306
- const server = new Map();
307
- for (const item of serverItems)
308
- if (item.type === 'chunk' && item.isEntry && item.name)
309
- server.set(item.name, item.fileName);
310
- const pageEntries = {};
311
- for (const page of pages.keys()) {
312
- const entry = byName.get(page);
313
- const ssrFile = server.get(page);
314
- if (entry === undefined || ssrFile === undefined)
315
- throw new InertiaError('TEMPLATE_BUILD_FAILED', `The build has no entry for ${page} (browser ${entry ? 'yes' : 'no'}, server ${ssrFile ? 'yes' : 'no'})`);
316
- const css = [];
317
- const preload = [];
318
- const seen = new Set();
319
- const visit = (key) => {
320
- if (seen.has(key))
321
- return;
322
- seen.add(key);
323
- const chunk = vm[key];
324
- if (!chunk)
325
- return;
326
- for (const next of chunk.imports ?? [])
327
- visit(next);
328
- if (chunk !== entry)
329
- preload.push(`browser/${chunk.file}`);
330
- for (const file of chunk.css ?? [])
331
- if (!css.includes(`browser/${file}`))
332
- css.push(`browser/${file}`);
333
- };
334
- const key = Object.keys(vm).find((candidate) => vm[candidate] === entry);
335
- visit(key);
336
- let meta;
337
- try {
338
- const module = (await import(`${pathToFileURL(join(out, 'ssr', ssrFile)).href}?build=${Date.now()}`));
339
- meta = module.meta;
333
+ }));
340
334
  }
341
335
  catch (cause) {
342
- throw new InertiaError('TEMPLATE_BUILD_FAILED', `The server module of ${page} could not be imported to read its meta: ${cause.message}`, { cause });
336
+ throw new InertiaError('TEMPLATE_BUILD_FAILED', `The Vite build of ${name} failed`, {
337
+ cause,
338
+ });
343
339
  }
344
- if (meta !== undefined) {
345
- if (!jsonValue(meta))
346
- throw new InertiaError('TEMPLATE_BUILD_FAILED', `${page} exports a meta that is not JSON data`);
347
- if (Buffer.byteLength(JSON.stringify(meta)) > PAGE_META_MAX_BYTES)
348
- throw new InertiaError('TEMPLATE_BUILD_FAILED', `${page} exports a meta larger than ${PAGE_META_MAX_BYTES} bytes`);
340
+ finally {
341
+ if (environment === undefined)
342
+ delete process.env.NODE_ENV;
343
+ else
344
+ process.env.NODE_ENV = environment;
345
+ }
346
+ collect(browserItems);
347
+ collect(serverItems);
348
+ // The browser manifest gives each page its stylesheets and the chunks it imports.
349
+ const manifestPath = join(out, 'browser', '.vite', 'manifest.json');
350
+ const vm = JSON.parse(await readFile(manifestPath, 'utf8'));
351
+ await rm(join(out, 'browser', '.vite'), { recursive: true, force: true });
352
+ const byName = new Map();
353
+ for (const entry of Object.values(vm))
354
+ if (entry.isEntry && entry.name)
355
+ byName.set(entry.name, entry);
356
+ const server = new Map();
357
+ for (const item of serverItems)
358
+ if (item.type === 'chunk' && item.isEntry && item.name)
359
+ server.set(item.name, item.fileName);
360
+ for (const page of pages.keys()) {
361
+ const entry = byName.get(page);
362
+ const ssrFile = server.get(page);
363
+ if (entry === undefined || ssrFile === undefined)
364
+ throw new InertiaError('TEMPLATE_BUILD_FAILED', `The build has no entry for ${page} (browser ${entry ? 'yes' : 'no'}, server ${ssrFile ? 'yes' : 'no'})`);
365
+ const css = [];
366
+ const preload = [];
367
+ const seen = new Set();
368
+ const visit = (key) => {
369
+ if (seen.has(key))
370
+ return;
371
+ seen.add(key);
372
+ const chunk = vm[key];
373
+ if (!chunk)
374
+ return;
375
+ for (const next of chunk.imports ?? [])
376
+ visit(next);
377
+ if (chunk !== entry)
378
+ preload.push(`browser/${chunk.file}`);
379
+ for (const file of chunk.css ?? [])
380
+ if (!css.includes(`browser/${file}`))
381
+ css.push(`browser/${file}`);
382
+ };
383
+ const key = Object.keys(vm).find((candidate) => vm[candidate] === entry);
384
+ visit(key);
385
+ let meta;
386
+ try {
387
+ const module = (await import(`${pathToFileURL(join(out, 'ssr', ssrFile)).href}?build=${Date.now()}`));
388
+ meta = module.meta;
389
+ }
390
+ catch (cause) {
391
+ throw new InertiaError('TEMPLATE_BUILD_FAILED', `The server module of ${page} could not be imported to read its meta: ${cause.message}`, { cause });
392
+ }
393
+ if (meta !== undefined) {
394
+ if (!jsonValue(meta))
395
+ throw new InertiaError('TEMPLATE_BUILD_FAILED', `${page} exports a meta that is not JSON data`);
396
+ if (Buffer.byteLength(JSON.stringify(meta)) > PAGE_META_MAX_BYTES)
397
+ throw new InertiaError('TEMPLATE_BUILD_FAILED', `${page} exports a meta larger than ${PAGE_META_MAX_BYTES} bytes`);
398
+ }
399
+ pageEntries[page] = {
400
+ browser: `browser/${entry.file}`,
401
+ css,
402
+ preload,
403
+ ssr: `ssr/${ssrFile}`,
404
+ ...(meta === undefined ? {} : { meta }),
405
+ };
349
406
  }
350
- pageEntries[page] = {
351
- browser: `browser/${entry.file}`,
352
- css,
353
- preload,
354
- ssr: `ssr/${ssrFile}`,
355
- ...(meta === undefined ? {} : { meta }),
356
- };
357
407
  }
358
408
  // D-0291 stage 3b: the template's screen words, locales/<locale>/<namespace>.json, as they are
359
409
  // (the app's @dokebi/i18n reads them with its own loader and rules).
@@ -386,7 +436,7 @@ export async function buildTemplateBundle(options) {
386
436
  }
387
437
  const files = {};
388
438
  for (const top of wordFiles ? ['browser', 'ssr', 'locales'] : ['browser', 'ssr'])
389
- for (const file of await listFiles(join(out, top))) {
439
+ for (const file of existsSync(join(out, top)) ? await listFiles(join(out, top)) : []) {
390
440
  const content = await readFile(join(out, top, file));
391
441
  files[`${top}/${file}`] = { bytes: content.length, sha256: sha256(content) };
392
442
  }
@@ -398,6 +448,8 @@ export async function buildTemplateBundle(options) {
398
448
  shared: Object.fromEntries([...imported].sort().map((module) => [module, packageVersion(root, module)])),
399
449
  pages: pageEntries,
400
450
  files,
451
+ ...(styles.length ? { styles } : {}),
452
+ ...(csp === undefined ? {} : { csp }),
401
453
  };
402
454
  await writeFile(join(out, TEMPLATE_MANIFEST), `${JSON.stringify(manifest, null, 2)}\n`);
403
455
  const check = await checkTemplateBundle(out, {
@@ -413,6 +465,8 @@ export async function buildTemplateBundle(options) {
413
465
  pages: Object.keys(pageEntries),
414
466
  shared: manifest.shared,
415
467
  carried: [...carry.keys()],
468
+ styles,
469
+ ...(csp === undefined ? {} : { csp }),
416
470
  files: Object.keys(files).length,
417
471
  bytes: check.bytes,
418
472
  ms: Math.round(performance.now() - begin),
@@ -426,6 +480,8 @@ export async function buildTemplateBundle(options) {
426
480
  pages: result.pages.length,
427
481
  words: wordFiles,
428
482
  carried: result.carried,
483
+ styles,
484
+ csp,
429
485
  files: result.files,
430
486
  bytes: result.bytes,
431
487
  shared: manifest.shared,
@@ -17,6 +17,17 @@ export declare const TEMPLATE_PAGE: RegExp;
17
17
  export declare const TEMPLATE_FILE: RegExp;
18
18
  /** A shared module specifier: a package name with an optional subpath. */
19
19
  export declare const SHARED_SPECIFIER: RegExp;
20
+ /**
21
+ * D-0297: the CSP directives a template may add sources to (its `csp.json`, the manifest's `csp`):
22
+ * the widgets, APIs, styles, fonts, images and frames of other origins its pages use.
23
+ */
24
+ export declare const TEMPLATE_CSP_DIRECTIVES: readonly string[];
25
+ /** D-0298: at most this many template stylesheets. */
26
+ export declare const TEMPLATE_STYLES_MAX = 32;
27
+ /** At most this many sources per directive. */
28
+ export declare const TEMPLATE_CSP_MAX_SOURCES = 32;
29
+ /** D-0297: the problem of a template's CSP declaration, or undefined. */
30
+ export declare function cspDeclarationProblem(value: unknown): string | undefined;
20
31
  /** A page's `meta` (JSON) may take this many bytes. */
21
32
  export declare const PAGE_META_MAX_BYTES = 4096;
22
33
  /** Default limits of one bundle. */
@@ -57,6 +68,16 @@ export interface TemplateManifest {
57
68
  readonly bytes: number;
58
69
  readonly sha256: string;
59
70
  }>>;
71
+ /**
72
+ * D-0297: the sources of other origins the pages use (the template folder's `csp.json`), added
73
+ * to the CSP of the answers drawn with this template. Apps before 0.4.27 ignore it.
74
+ */
75
+ readonly csp?: Readonly<Record<string, readonly string[]>>;
76
+ /**
77
+ * D-0298: the template's own stylesheets (`browser/…css` files of `files`), in order: the app
78
+ * puts them into the first HTML of every page of the template. Apps before 0.4.27 ignore it.
79
+ */
80
+ readonly styles?: readonly string[];
60
81
  }
61
82
  /** What is wrong with a bundle (one entry per problem; the code is stable). */
62
83
  export interface TemplateProblem {
@@ -35,6 +35,46 @@ export const TEMPLATE_FILE = /^(?:(?:browser|ssr)(?:\/[A-Za-z0-9_@+][A-Za-z0-9_.
35
35
  const FOLDERS = ['browser', 'ssr', 'locales'];
36
36
  /** A shared module specifier: a package name with an optional subpath. */
37
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}$/;
38
+ /**
39
+ * D-0297: the CSP directives a template may add sources to (its `csp.json`, the manifest's `csp`):
40
+ * the widgets, APIs, styles, fonts, images and frames of other origins its pages use.
41
+ */
42
+ export const TEMPLATE_CSP_DIRECTIVES = Object.freeze([
43
+ 'script-src',
44
+ 'style-src',
45
+ 'connect-src',
46
+ 'font-src',
47
+ 'img-src',
48
+ 'frame-src',
49
+ ]);
50
+ /** D-0298: at most this many template stylesheets. */
51
+ export const TEMPLATE_STYLES_MAX = 32;
52
+ /** At most this many sources per directive. */
53
+ export const TEMPLATE_CSP_MAX_SOURCES = 32;
54
+ /**
55
+ * D-0297: one source a template may declare: an https origin (a wss one in connect-src), its host
56
+ * with an optional `*.` in front, an optional port and path. No keyword ('unsafe-inline', a
57
+ * nonce), no bare scheme (`https:`, `data:`), no `*`, no plain http.
58
+ */
59
+ const CSP_SOURCE = /^(?:https|wss):\/\/(?:\*\.)?[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+(?::\d{1,5})?(?:\/[A-Za-z0-9._~%!$&'()*+=:@/-]{0,200})?$/;
60
+ /** D-0297: the problem of a template's CSP declaration, or undefined. */
61
+ export function cspDeclarationProblem(value) {
62
+ if (!plain(value))
63
+ return 'csp must be an object of directive → sources';
64
+ for (const [name, sources] of Object.entries(value)) {
65
+ if (!TEMPLATE_CSP_DIRECTIVES.includes(name))
66
+ return `csp ${name} is not one of ${TEMPLATE_CSP_DIRECTIVES.join(', ')}`;
67
+ if (!Array.isArray(sources) || sources.length > TEMPLATE_CSP_MAX_SOURCES)
68
+ return `csp ${name} must be a list of at most ${TEMPLATE_CSP_MAX_SOURCES} sources`;
69
+ for (const source of sources) {
70
+ if (typeof source !== 'string' || !CSP_SOURCE.test(source))
71
+ return `csp ${name}: ${String(source)} is not an https origin (https://host[:port][/path], *.host allowed; wss:// in connect-src): no keyword, bare scheme, * or http`;
72
+ if (source.startsWith('wss:') && name !== 'connect-src')
73
+ return `csp ${name}: ${source} — wss:// belongs in connect-src`;
74
+ }
75
+ }
76
+ return undefined;
77
+ }
38
78
  /** A page's `meta` (JSON) may take this many bytes. */
39
79
  export const PAGE_META_MAX_BYTES = 4096;
40
80
  /** Default limits of one bundle. */
@@ -99,9 +139,26 @@ export function manifestProblem(value) {
99
139
  !/^[0-9a-f]{64}$/.test(entry.sha256))
100
140
  return `file ${file} needs bytes (a whole number) and sha256 (64 hex)`;
101
141
  }
102
- if (!plain(value.pages) || Object.keys(value.pages).length === 0)
103
- return 'pages must name at least one page';
142
+ if (value.csp !== undefined) {
143
+ const problem = cspDeclarationProblem(value.csp);
144
+ if (problem)
145
+ return problem;
146
+ }
147
+ // D-0298: a bundle may have no page (a template of styles alone).
148
+ if (!plain(value.pages))
149
+ return 'pages must be an object of page → files';
104
150
  const files = value.files;
151
+ if (value.styles !== undefined) {
152
+ const list = value.styles;
153
+ if (!Array.isArray(list) ||
154
+ list.length > TEMPLATE_STYLES_MAX ||
155
+ list.some((file) => typeof file !== 'string' ||
156
+ !file.startsWith('browser/') ||
157
+ !file.endsWith('.css') ||
158
+ !Object.hasOwn(files, file)) ||
159
+ new Set(list).size !== list.length)
160
+ return `styles must be a list of at most ${TEMPLATE_STYLES_MAX} different browser/….css files of files`;
161
+ }
105
162
  for (const [page, entry] of Object.entries(value.pages)) {
106
163
  if (!TEMPLATE_PAGE.test(page))
107
164
  return `page ${page} is not Layout or Pages/<path>`;
@@ -12,6 +12,17 @@ export interface TemplatePreviewOptions {
12
12
  readonly host?: string;
13
13
  /** A vite config of the project to merge; @vitejs/plugin-vue is added unless it has its own. */
14
14
  readonly config?: string;
15
+ /**
16
+ * D-0297: a JSON file of the app's `securityHeaders.contentSecurityPolicy` (`{ directives?,
17
+ * nonce?, styleNonce? }`), relative to root: the policy the pages are drawn under. Default: web's
18
+ * default policy.
19
+ */
20
+ readonly csp?: string;
21
+ /**
22
+ * D-0298: the template's own stylesheets (`.css` files of the template folder, in order), linked
23
+ * in every page as the app does with a bundle's `styles` (and updated by HMR).
24
+ */
25
+ readonly styles?: readonly string[];
15
26
  readonly logger?: Logger;
16
27
  }
17
28
  export interface TemplatePreviewPage {
@@ -31,6 +42,11 @@ export declare function previewCases(file: string): Promise<Record<string, Recor
31
42
  * (`locales/<locale>/<namespace>.json`), so pages that call t() draw; undefined without words.
32
43
  */
33
44
  export declare function previewWords(folder: string, wanted?: string): Promise<Record<string, unknown> | undefined>;
45
+ /**
46
+ * D-0297: the policy of a preview page: the app's setting (or web's default), the template's
47
+ * declared sources, the HMR socket, and the nonce where the setting asks for one.
48
+ */
49
+ export declare function previewPolicy(folder: string, setting: string | undefined, socket: string, nonce: string): Promise<string>;
34
50
  /**
35
51
  * Starts the preview of the template folder `options.dir` (D-0291 stage 3). Resolves once the
36
52
  * server listens; `close()` stops it.