@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.
@@ -9,13 +9,20 @@
9
9
  // template folder's `preview.json` (`{ "shared": { …props every page gets } }`). The shared
10
10
  // modules (vue, @inertiajs/vue3, the SDK) are the template repository's installed packages.
11
11
  // Inertia visits (a <Link> to another preview URL) are answered too.
12
+ //
13
+ // D-0297: each page carries a Content-Security-Policy as an app would send it: web's default policy
14
+ // (or the app's own setting, `csp`: a JSON file `{ directives?, nonce?, styleNonce? }` shaped like
15
+ // `securityHeaders.contentSecurityPolicy`), the template's `csp.json` sources and the HMR socket.
16
+ // What the policy blocks is listed on the page, so a designer sees an origin to declare. A changed
17
+ // csp.json or setting file reloads the page.
18
+ import { randomBytes } from 'node:crypto';
12
19
  import { existsSync, readFileSync, realpathSync } from 'node:fs';
13
20
  import { readdir, readFile } from 'node:fs/promises';
14
21
  import { basename, join, relative, resolve, sep } from 'node:path';
15
22
  import { pathToFileURL } from 'node:url';
16
23
  import { ConsoleLogger } from '@dokebi/core';
17
24
  import { InertiaError, InertiaUsageError } from './errors.js';
18
- import { packageEntry, templatePages } from './template-build.js';
25
+ import { carriedFiles, packageEntry, TEMPLATE_CSP_FILE, templateCsp, templatePages, } from './template-build.js';
19
26
  import { jsonValue, TEMPLATE_PAGE } from './template-bundle.js';
20
27
  import { vueTypeBarrels } from './vite-type-barrels.js';
21
28
  import { registerVueTypeScript } from './vue-typescript.js';
@@ -136,6 +143,65 @@ async function previewShared(folder) {
136
143
  }
137
144
  const escapeHtml = (value) => value.replace(/[&<>"']/g, (char) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[char]);
138
145
  const scriptJson = (value) => JSON.stringify(value).replace(/</g, '\\u003c');
146
+ /** D-0297: web's default policy (`DEFAULT_DIRECTIVES` of @dokebi/web 0.4.28), which apps start from. */
147
+ const DEFAULT_CSP = {
148
+ 'default-src': ["'self'"],
149
+ 'base-uri': ["'self'"],
150
+ 'object-src': ["'none'"],
151
+ 'frame-ancestors': ["'self'"],
152
+ 'script-src': ["'self'", "'unsafe-inline'"],
153
+ 'style-src': ["'self'", "'unsafe-inline'", 'https:'],
154
+ 'img-src': ["'self'", 'data:', 'blob:', 'https:'],
155
+ 'font-src': ["'self'", 'data:', 'https:'],
156
+ 'connect-src': ["'self'"],
157
+ };
158
+ /** Appends sources as web does: an unset fetch directive starts from default-src; 'none' gives way. */
159
+ function appendSources(merged, name, sources) {
160
+ const base = merged[name] ?? (name.endsWith('-src') ? (merged['default-src'] ?? []) : []);
161
+ const kept = sources.length ? base.filter((source) => source !== "'none'") : base;
162
+ merged[name] = [...new Set([...kept, ...sources])];
163
+ }
164
+ /**
165
+ * D-0297: the policy of a preview page: the app's setting (or web's default), the template's
166
+ * declared sources, the HMR socket, and the nonce where the setting asks for one.
167
+ */
168
+ export async function previewPolicy(folder, setting, socket, nonce) {
169
+ let own = {};
170
+ if (setting !== undefined) {
171
+ let parsed;
172
+ try {
173
+ parsed = JSON.parse(await readFile(setting, 'utf8'));
174
+ }
175
+ catch (cause) {
176
+ throw new InertiaError('TEMPLATE_BUILD_FAILED', `--csp ${setting} is not a JSON file: ${cause.message}`, { cause });
177
+ }
178
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed))
179
+ throw new InertiaUsageError('INVALID_TEMPLATE_PREVIEW', `--csp ${setting} must hold the app's contentSecurityPolicy setting: { directives?, nonce?, styleNonce? }`);
180
+ own = parsed;
181
+ }
182
+ const merged = { ...DEFAULT_CSP };
183
+ for (const [name, sources] of Object.entries(own.directives ?? {}))
184
+ if (sources === false)
185
+ delete merged[name];
186
+ else if (Array.isArray(sources))
187
+ merged[name] = sources.map(String);
188
+ for (const [name, sources] of Object.entries((await templateCsp(folder)) ?? {}))
189
+ appendSources(merged, name, sources);
190
+ appendSources(merged, 'connect-src', [socket]);
191
+ const withNonce = (name, more) => {
192
+ const base = merged[name] ?? merged['default-src'] ?? [];
193
+ merged[name] = [
194
+ ...new Set([...base.filter((source) => source !== "'unsafe-inline'"), ...more]),
195
+ ];
196
+ };
197
+ if (own.nonce === true)
198
+ withNonce('script-src', [`'nonce-${nonce}'`, "'strict-dynamic'"]);
199
+ if (own.styleNonce === true)
200
+ withNonce('style-src', [`'nonce-${nonce}'`]);
201
+ return Object.entries(merged)
202
+ .map(([name, sources]) => (sources.length ? `${name} ${sources.join(' ')}` : name))
203
+ .join('; ');
204
+ }
139
205
  /**
140
206
  * Starts the preview of the template folder `options.dir` (D-0291 stage 3). Resolves once the
141
207
  * server listens; `close()` stops it.
@@ -148,9 +214,25 @@ export async function startTemplatePreview(options) {
148
214
  const inside = relative(root, folder);
149
215
  if (!inside || inside.startsWith('..') || !existsSync(folder))
150
216
  throw new InertiaUsageError('INVALID_TEMPLATE_PREVIEW', `${options.dir} must be a template folder inside ${root}`);
151
- const pages = await templatePages(folder);
152
- if (![...pages.keys()].some((key) => key.startsWith('Pages/')))
153
- throw new InertiaUsageError('INVALID_TEMPLATE_PREVIEW', `${options.dir} has no Pages/**/*.vue`);
217
+ // D-0299: the pages are read again for every request (a page added or removed while the preview
218
+ // runs is listed and drawn at once); a template without pages yet starts too.
219
+ await templatePages(folder);
220
+ // D-0298: the template's stylesheets, checked as the build checks them.
221
+ let styles;
222
+ try {
223
+ styles = [...(await carriedFiles(folder, options.styles ?? [])).keys()].map((target) => target.slice('browser/'.length));
224
+ }
225
+ catch (error) {
226
+ // A path the build would refuse is this command's usage error; anything else goes up as it is.
227
+ if (!(error instanceof InertiaUsageError))
228
+ throw error;
229
+ const refused = new InertiaUsageError('INVALID_TEMPLATE_PREVIEW', error.message.replace('--carry', '--style'));
230
+ refused.cause = error;
231
+ throw refused;
232
+ }
233
+ const notCss = styles.find((file) => !file.endsWith('.css'));
234
+ if (notCss !== undefined)
235
+ throw new InertiaUsageError('INVALID_TEMPLATE_PREVIEW', `--style ${notCss} is not a .css file`);
154
236
  const viteEntry = packageEntry(root, 'vite');
155
237
  if (!viteEntry)
156
238
  throw new InertiaError('TEMPLATE_BUILD_FAILED', `vite is not installed in ${root}`, {
@@ -177,8 +259,16 @@ export async function startTemplatePreview(options) {
177
259
  .default
178
260
  : undefined;
179
261
  registerVueTypeScript(root, logger);
262
+ // D-0297: the app's CSP setting the pages are drawn under, and the nonce of this preview (Vite
263
+ // writes it on the tags it adds; one per server is enough for a local preview).
264
+ const cspSetting = options.csp === undefined ? undefined : resolve(root, options.csp);
265
+ if (cspSetting !== undefined && !existsSync(cspSetting))
266
+ throw new InertiaUsageError('INVALID_TEMPLATE_PREVIEW', `--csp ${options.csp} is not a file`);
267
+ const nonce = randomBytes(16).toString('base64');
268
+ let socketOrigin = () => 'ws://127.0.0.1';
180
269
  const folderUrl = `/${inside.split(sep).join('/')}`;
181
- const names = [...pages.keys()]
270
+ /** D-0299: the pages of the folder now (a few readdir calls). */
271
+ const currentNames = async () => [...(await templatePages(folder)).keys()]
182
272
  .filter((key) => key.startsWith('Pages/'))
183
273
  .map((key) => key.slice(6));
184
274
  /** The page object of one preview URL. */
@@ -218,7 +308,29 @@ export async function startTemplatePreview(options) {
218
308
  load(id) {
219
309
  if (id !== ENTRY_ID)
220
310
  return null;
221
- return `import { createInertiaApp, router } from '@inertiajs/vue3';
311
+ return `// D-0297: what the page's Content-Security-Policy blocks, listed on the page.
312
+ const blocked = new Set();
313
+ document.addEventListener('securitypolicyviolation', (event) => {
314
+ const line = event.effectiveDirective + ' blocked ' + (event.blockedURI || 'an inline ' + (event.effectiveDirective.startsWith('style') ? 'style' : 'script'));
315
+ if (blocked.has(line)) return;
316
+ blocked.add(line);
317
+ console.warn('[dokebi preview] ' + line + ': declare the origin in ${TEMPLATE_CSP_FILE} (D-0297)');
318
+ let box = document.getElementById('dokebi-preview-csp');
319
+ if (!box) {
320
+ box = document.createElement('div');
321
+ box.id = 'dokebi-preview-csp';
322
+ box.setAttribute('role', 'alert');
323
+ box.style.cssText = 'position:fixed;left:8px;right:8px;bottom:8px;z-index:2147483647;max-height:40vh;overflow:auto;background:#fff4f4;color:#7a0000;border:2px solid #c00;border-radius:6px;padding:8px 12px;font:13px/1.5 system-ui,sans-serif;';
324
+ const title = document.createElement('strong');
325
+ title.textContent = 'Blocked by the Content-Security-Policy: declare these origins in ${TEMPLATE_CSP_FILE}';
326
+ box.append(title, document.createElement('ul'));
327
+ document.body.append(box);
328
+ }
329
+ const item = document.createElement('li');
330
+ item.textContent = line;
331
+ box.querySelector('ul').append(item);
332
+ });
333
+ import { createInertiaApp, router } from '@inertiajs/vue3';
222
334
  import { pageI18n } from '@dokebi/template-inertia/i18n';
223
335
  import { createApp, h } from 'vue';
224
336
  const files = import.meta.glob(${JSON.stringify(`${folderUrl}/{Layout,Pages/**/*}.vue`)});
@@ -237,6 +349,16 @@ await createInertiaApp({
237
349
  });
238
350
  `;
239
351
  },
352
+ // D-0297: the policy is the document's: a changed csp.json (or setting file) reloads the page.
353
+ handleHotUpdate(context) {
354
+ const file = resolve(context.file);
355
+ if (file === join(folder, TEMPLATE_CSP_FILE) ||
356
+ (cspSetting !== undefined && file === cspSetting)) {
357
+ context.server.ws.send({ type: 'full-reload' });
358
+ return [];
359
+ }
360
+ return undefined;
361
+ },
240
362
  configureServer(server) {
241
363
  server.middlewares.use((request, response, next) => {
242
364
  const url = new URL(request.url ?? '/', 'http://preview');
@@ -259,31 +381,55 @@ await createInertiaApp({
259
381
  send(500, 'text/html; charset=utf-8', `<!doctype html><pre>${escapeHtml(error.message)}</pre>`);
260
382
  };
261
383
  if (url.pathname === '/') {
262
- Promise.all(names.map(async (name) => ({
384
+ currentNames()
385
+ .then((names) => Promise.all(names.map(async (name) => ({
263
386
  name,
264
387
  cases: Object.keys(await previewCases(join(folder, 'Pages', `${name}.preview.json`))),
265
- }))).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
388
+ }))))
389
+ .then(async (listed) => send(200, 'text/html; charset=utf-8',
390
+ // D-0299: Vite's client on the list too, so an added or removed page reloads it.
391
+ await server.transformIndexHtml('/', `<!doctype html><html><head><meta charset="utf-8"><title>${escapeHtml(basename(folder))} preview</title></head><body><h1>${escapeHtml(basename(folder))}</h1>${listed.length ? '' : `<p data-empty>No page yet: add Pages/&lt;Name&gt;.vue to ${escapeHtml(options.dir)}.</p>`}<ul>${listed
266
392
  .map((item) => `<li data-page="${escapeHtml(item.name)}">${escapeHtml(item.name)}: ${item.cases
267
393
  .map((name) => `<a href="${PREVIEW_PREFIX}${escapeHtml(item.name)}?case=${encodeURIComponent(name)}">${escapeHtml(name)}</a>`)
268
394
  .join(' · ')}</li>`)
269
- .join('')}</ul></body></html>`), fail);
395
+ .join('')}</ul></body></html>`)))
396
+ .catch(fail);
270
397
  return;
271
398
  }
272
399
  if (!url.pathname.startsWith(PREVIEW_PREFIX))
273
400
  return next();
274
401
  const name = decodeURIComponent(url.pathname.slice(PREVIEW_PREFIX.length));
275
- if (!TEMPLATE_PAGE.test(`Pages/${name}`) || !names.includes(name))
402
+ if (!TEMPLATE_PAGE.test(`Pages/${name}`))
276
403
  return send(404, 'text/plain; charset=utf-8', `No page ${name} in ${options.dir}`);
277
- pageObject(name, url.searchParams.get('case')).then(async ({ page }) => {
404
+ currentNames().then(async (names) => {
405
+ if (!names.includes(name))
406
+ return send(404, 'text/plain; charset=utf-8', `No page ${name} in ${options.dir}`);
407
+ const { page } = await pageObject(name, url.searchParams.get('case'));
278
408
  if (request.headers['x-inertia'] === 'true')
279
409
  return send(200, 'application/json; charset=utf-8', JSON.stringify(page), {
280
410
  'x-inertia': 'true',
281
411
  vary: 'X-Inertia',
282
412
  });
283
- 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>`);
284
- send(200, 'text/html; charset=utf-8', html);
413
+ const policy = await previewPolicy(folder, cspSetting, socketOrigin(), nonce);
414
+ const html = await server.transformIndexHtml(url.pathname, `<!doctype html><html><head><meta charset="utf-8"><title>${escapeHtml(name)} · preview</title>${styles.map((file) => `<link rel="stylesheet" nonce="${nonce}" href="${escapeHtml(`${folderUrl}/${file}`)}">`).join('')}<script type="module" src="${ENTRY_URL}" nonce="${nonce}"></script></head><body><script data-page="app" type="application/json">${scriptJson(page)}</script><div id="app"></div></body></html>`);
415
+ send(200, 'text/html; charset=utf-8', html, { 'content-security-policy': policy });
285
416
  }, fail);
286
417
  });
418
+ // D-0299: a page added or removed (or the Layout) reloads the open pages and the list.
419
+ const pagesFolder = join(folder, 'Pages') + sep;
420
+ const layout = join(folder, 'Layout.vue');
421
+ const changed = (event) => (file) => {
422
+ const path = resolve(file);
423
+ if (path !== layout && !(path.startsWith(pagesFolder) && path.endsWith('.vue')))
424
+ return;
425
+ logger.log('debug', 'Template preview page added or removed; the pages reload', {
426
+ event,
427
+ file: relative(root, path),
428
+ });
429
+ server.ws.send({ type: 'full-reload' });
430
+ };
431
+ server.watcher.on('add', changed('add'));
432
+ server.watcher.on('unlink', changed('unlink'));
287
433
  },
288
434
  };
289
435
  let server;
@@ -294,6 +440,7 @@ await createInertiaApp({
294
440
  logLevel: 'warn',
295
441
  publicDir: false,
296
442
  appType: 'custom',
443
+ html: { cspNonce: nonce },
297
444
  plugins: [
298
445
  ...(vue
299
446
  ? [
@@ -325,7 +472,8 @@ await createInertiaApp({
325
472
  const port = typeof address === 'object' && address ? address.port : (options.port ?? 5180);
326
473
  const host = options.host ?? '127.0.0.1';
327
474
  const url = `http://${host.includes(':') ? `[${host}]` : host}:${port}/`;
328
- const listed = await Promise.all(names.map(async (name) => ({
475
+ socketOrigin = () => `ws://${host.includes(':') ? `[${host}]` : host}:${port}`;
476
+ const listed = await Promise.all((await currentNames()).map(async (name) => ({
329
477
  page: name,
330
478
  cases: Object.keys(await previewCases(join(folder, 'Pages', `${name}.preview.json`))),
331
479
  })));
@@ -38,6 +38,11 @@ export type TemplateVerifyResult = {
38
38
  readonly page: string;
39
39
  readonly reason: string;
40
40
  }[];
41
+ /**
42
+ * D-0297: the sources of the manifest's `csp` the app lets the bundle's answers add (the
43
+ * rest are left out, warn INERTIA_TEMPLATE_CSP_REFUSED). Left out: every declared source.
44
+ */
45
+ readonly csp?: Readonly<Record<string, readonly string[]>>;
41
46
  } | {
42
47
  readonly accept: false;
43
48
  readonly reason: string;
@@ -97,6 +102,10 @@ export interface TemplateState {
97
102
  readonly reason?: string;
98
103
  /** The last look at the mount that found a change (a load, a refusal), Date.now(). */
99
104
  readonly checkedAt?: number;
105
+ /** D-0297: the CSP sources the answers of the bundle in use add (after verifyTemplate). */
106
+ readonly csp?: Readonly<Record<string, readonly string[]>>;
107
+ /** D-0297: declared sources verifyTemplate left out. */
108
+ readonly cspRefused?: Readonly<Record<string, readonly string[]>>;
100
109
  }
101
110
  /** D-0294: what changed a template's state. */
102
111
  export type TemplateChange = 'loaded' | 'failed' | 'page-failed' | 'removed';
@@ -124,6 +133,10 @@ export declare class TemplateGeneration {
124
133
  readonly rejected: readonly string[];
125
134
  /** D-0294: the refusals of `rejected`, with verifyTemplate's reasons. */
126
135
  readonly rejectedWhy: readonly TemplatePageRefusal[];
136
+ /** D-0297: the CSP sources its answers add, and what web made of them (`cspAddition`). */
137
+ readonly csp: TemplateCsp | undefined;
138
+ /** D-0298: the URLs of the template's own stylesheets (the manifest's `styles`), in order. */
139
+ readonly styles: readonly string[];
127
140
  readonly setAside: Set<string>;
128
141
  /** D-0294: why each page set aside at render was (and when). */
129
142
  readonly setAsideWhy: Map<string, TemplatePageRefusal>;
@@ -139,7 +152,11 @@ export declare class TemplateGeneration {
139
152
  /** Pages the app's check refused. */
140
153
  rejected: readonly string[],
141
154
  /** D-0294: the refusals of `rejected`, with verifyTemplate's reasons. */
142
- rejectedWhy?: readonly TemplatePageRefusal[]);
155
+ rejectedWhy?: readonly TemplatePageRefusal[],
156
+ /** D-0297: the CSP sources its answers add, and what web made of them (`cspAddition`). */
157
+ csp?: TemplateCsp | undefined,
158
+ /** D-0298: the URLs of the template's own stylesheets (the manifest's `styles`), in order. */
159
+ styles?: readonly string[]);
143
160
  /** The page table of the first HTML (JSON, without the pages set aside). */
144
161
  table(): string;
145
162
  /** Leaves `page` to the app's own page for the rest of this generation. */
@@ -147,6 +164,14 @@ export declare class TemplateGeneration {
147
164
  /** The server module of `page`, unless it is set aside. */
148
165
  serverPage(page: string): Readonly<Record<string, unknown>> | undefined;
149
166
  }
167
+ /** D-0297: the CSP sources of a generation. */
168
+ export interface TemplateCsp {
169
+ readonly sources: Readonly<Record<string, readonly string[]>>;
170
+ /** Declared sources verifyTemplate left out. */
171
+ readonly refused: Readonly<Record<string, readonly string[]>>;
172
+ /** What `web.cspAddition` made of `sources` (undefined: nothing to add, or an older web). */
173
+ readonly addition: unknown;
174
+ }
150
175
  /** The part of a template the responder uses for one request. */
151
176
  export interface TemplateUse {
152
177
  /** The asset version of this request's pages. */
@@ -179,6 +204,11 @@ export interface TemplateBundlesOptions {
179
204
  ok: false;
180
205
  reason: string;
181
206
  }>;
207
+ /**
208
+ * D-0297: web's `cspAddition` (the sources a bundle's answers add); absent with a web before
209
+ * 0.4.28, then a bundle's `csp` is not used (warn INERTIA_TEMPLATE_CSP_UNSUPPORTED).
210
+ */
211
+ readonly cspAddition?: (directives: Readonly<Record<string, readonly string[]>>) => unknown;
182
212
  }
183
213
  /** Every app's template bundles. */
184
214
  export declare class TemplateBundles {
@@ -41,6 +41,8 @@ export class TemplateGeneration {
41
41
  importMap;
42
42
  rejected;
43
43
  rejectedWhy;
44
+ csp;
45
+ styles;
44
46
  setAside = new Set();
45
47
  /** D-0294: why each page set aside at render was (and when). */
46
48
  setAsideWhy = new Map();
@@ -57,7 +59,11 @@ export class TemplateGeneration {
57
59
  /** Pages the app's check refused. */
58
60
  rejected,
59
61
  /** D-0294: the refusals of `rejected`, with verifyTemplate's reasons. */
60
- rejectedWhy = []) {
62
+ rejectedWhy = [],
63
+ /** D-0297: the CSP sources its answers add, and what web made of them (`cspAddition`). */
64
+ csp = undefined,
65
+ /** D-0298: the URLs of the template's own stylesheets (the manifest's `styles`), in order. */
66
+ styles = []) {
61
67
  this.app = app;
62
68
  this.template = template;
63
69
  this.buildId = buildId;
@@ -68,6 +74,8 @@ export class TemplateGeneration {
68
74
  this.importMap = importMap;
69
75
  this.rejected = rejected;
70
76
  this.rejectedWhy = rejectedWhy;
77
+ this.csp = csp;
78
+ this.styles = styles;
71
79
  }
72
80
  /** The page table of the first HTML (JSON, without the pages set aside). */
73
81
  table() {
@@ -197,6 +205,7 @@ export class TemplateBundles {
197
205
  #repeat;
198
206
  #production;
199
207
  #words;
208
+ #cspAddition;
200
209
  #settings;
201
210
  #apps = new Map();
202
211
  #slots = new Map();
@@ -212,6 +221,7 @@ export class TemplateBundles {
212
221
  this.#repeat = options.repeat;
213
222
  this.#production = options.production ?? process.env.NODE_ENV === 'production';
214
223
  this.#words = options.words;
224
+ this.#cspAddition = options.cspAddition;
215
225
  this.#cacheRoot = resolve(options.settings.cacheDir);
216
226
  const store = this.#store;
217
227
  globalThis[TEMPLATE_REGISTRY] = Object.freeze({
@@ -567,6 +577,8 @@ export class TemplateBundles {
567
577
  throw new Refused('INERTIA_TEMPLATE_REJECTED', problems.map((problem) => problem.message).join('; '), { shared: needed });
568
578
  // The app's own judgement: signature and page contracts.
569
579
  let rejectPages = [];
580
+ // D-0297: the declared CSP sources the app lets in (all, unless verifyTemplate narrows them).
581
+ let allowedCsp = manifest.csp;
570
582
  if (this.#verify) {
571
583
  const verify = this.#verify;
572
584
  let timer;
@@ -606,6 +618,11 @@ export class TemplateBundles {
606
618
  if (!answer.accept)
607
619
  throw new Refused('INERTIA_TEMPLATE_REJECTED', `verifyTemplate refused it: ${String(answer.reason)}`);
608
620
  rejectPages = answer.rejectPages ?? [];
621
+ if (answer.csp !== undefined) {
622
+ if (answer.csp === null || typeof answer.csp !== 'object' || Array.isArray(answer.csp))
623
+ throw new Refused('INERTIA_TEMPLATE_REJECTED', 'verifyTemplate answered csp that is not an object of directive → sources');
624
+ allowedCsp = answer.csp;
625
+ }
609
626
  }
610
627
  else if (this.#production)
611
628
  throw new Refused('INERTIA_TEMPLATE_UNVERIFIED', 'no verifyTemplate: in production a bundle runs only after the app judged it');
@@ -679,7 +696,8 @@ export class TemplateBundles {
679
696
  const hasWords = Object.keys(manifest.files).some((file) => file.startsWith('locales/'));
680
697
  if (hasWords || slot.words)
681
698
  await this.#setWords(slot, hasWords ? join(dir, 'locales') : undefined, buildId);
682
- const generation = new TemplateGeneration(slot.app, slot.template, buildId, manifest, dir, pages, server, importMap, [...refused], refusedWhy);
699
+ const csp = this.#csp(slot, buildId, manifest.csp, allowedCsp);
700
+ const generation = new TemplateGeneration(slot.app, slot.template, buildId, manifest, dir, pages, server, importMap, [...refused], refusedWhy, csp, (manifest.styles ?? []).map(url));
683
701
  const previous = slot.current;
684
702
  slot.current = generation;
685
703
  slot.failure = undefined;
@@ -696,6 +714,8 @@ export class TemplateBundles {
696
714
  pages: pages.size,
697
715
  rejectedPages: [...refused],
698
716
  serverRendering: provided.server !== undefined,
717
+ styles: manifest.styles ?? [],
718
+ csp: csp?.sources ?? null,
699
719
  kept: slot.kept.map((kept) => kept.buildId),
700
720
  ms: Math.round(performance.now() - begin),
701
721
  });
@@ -709,6 +729,56 @@ export class TemplateBundles {
709
729
  this.#fail(slot, error);
710
730
  }
711
731
  }
732
+ /**
733
+ * D-0297: the CSP sources of a generation: the declared ones the app let in, made into web's
734
+ * addition once (each answer of the template then adds it). Undefined without a declaration.
735
+ */
736
+ #csp(slot, buildId, declared, allowed) {
737
+ if (declared === undefined)
738
+ return undefined;
739
+ const sources = {};
740
+ const refused = {};
741
+ for (const [name, list] of Object.entries(declared)) {
742
+ const allowedList = allowed?.[name];
743
+ const kept = Array.isArray(allowedList)
744
+ ? list.filter((source) => allowedList.includes(source))
745
+ : [];
746
+ const left = list.filter((source) => !kept.includes(source));
747
+ if (kept.length)
748
+ sources[name] = Object.freeze(kept);
749
+ if (left.length)
750
+ refused[name] = Object.freeze(left);
751
+ }
752
+ if (Object.keys(refused).length)
753
+ this.#logger.log('warn', 'Template bundle CSP sources left out by verifyTemplate', {
754
+ code: 'INERTIA_TEMPLATE_CSP_REFUSED',
755
+ app: slot.app,
756
+ template: slot.template,
757
+ buildId,
758
+ refused,
759
+ });
760
+ let addition;
761
+ if (Object.keys(sources).length) {
762
+ if (this.#cspAddition)
763
+ addition = this.#cspAddition(sources);
764
+ else {
765
+ const repeated = this.#repeat(`csp ${slot.app} ${slot.template}`);
766
+ if (repeated !== undefined)
767
+ this.#logger.log('warn', 'Template bundle CSP sources not used: web has no cspAddition', {
768
+ code: 'INERTIA_TEMPLATE_CSP_UNSUPPORTED',
769
+ app: slot.app,
770
+ template: slot.template,
771
+ sources,
772
+ fix: 'npm install @dokebi/web@^0.4.28',
773
+ });
774
+ }
775
+ }
776
+ return Object.freeze({
777
+ sources: Object.freeze(sources),
778
+ refused: Object.freeze(refused),
779
+ addition,
780
+ });
781
+ }
712
782
  /** D-0291 stage 3b: hands a generation's words (or none) to @dokebi/i18n. Never throws. */
713
783
  async #setWords(slot, directory, buildId) {
714
784
  const words = this.#words;
@@ -805,13 +875,17 @@ export class TemplateBundles {
805
875
  .filter((page) => !generation.setAside.has(page))
806
876
  .map((page) => generation.pages.get(page))
807
877
  .filter((urls) => urls !== undefined);
878
+ // D-0298: the template's own stylesheets first, in their order, then the pages' own.
879
+ const look = generation.styles
880
+ .map((href) => `<link rel="stylesheet"${attribute} href="${escapeHtml(href)}">`)
881
+ .join('');
808
882
  const css = [...new Set(first.flatMap((urls) => urls.css))]
809
883
  .map((href) => `<link rel="stylesheet" href="${escapeHtml(href)}">`)
810
884
  .join('');
811
885
  const preload = [...new Set(first.flatMap((urls) => [urls.js, ...urls.preload]))]
812
886
  .map((href) => `<link rel="modulepreload"${attribute} href="${escapeHtml(href)}">`)
813
887
  .join('');
814
- return `${map}${table}${css}${preload}`;
888
+ return `${map}${table}${look}${css}${preload}`;
815
889
  },
816
890
  async render(run, component) {
817
891
  // The page first: a failure that took the component's own bundle page sets that page
@@ -900,6 +974,12 @@ function stateOf(slot) {
900
974
  buildId: current.buildId,
901
975
  loadedAt: current.loadedAt,
902
976
  rejectedPages: Object.freeze([...current.rejectedWhy, ...current.setAsideWhy.values()]),
977
+ ...(current.csp === undefined
978
+ ? {}
979
+ : {
980
+ csp: current.csp.sources,
981
+ ...(Object.keys(current.csp.refused).length ? { cspRefused: current.csp.refused } : {}),
982
+ }),
903
983
  });
904
984
  return Object.freeze({
905
985
  ...base,
@@ -1,4 +1,4 @@
1
- export { buildTemplateBundle, packageEntry, TEMPLATE_CARRY_FOLDER, type TemplateBuildOptions, type TemplateBuildResult, templatePages, } from './template-build.js';
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';
1
+ export { buildTemplateBundle, packageEntry, TEMPLATE_CARRY_FOLDER, TEMPLATE_CSP_FILE, type TemplateBuildOptions, type TemplateBuildResult, templatePages, } from './template-build.js';
2
+ export { checkTemplateBundle, compatibleLine, cspDeclarationProblem, type ProvidedShared, SERVER_ONLY_SHARED, SHARED_DEFAULTS, sharedProblems, TEMPLATE_CSP_DIRECTIVES, TEMPLATE_FORMAT, TEMPLATE_MANIFEST, TEMPLATE_MAX_BYTES, TEMPLATE_NAME, TEMPLATE_SIGNATURE, TEMPLATE_STYLES_MAX, type TemplateCheck, type TemplateCheckLimits, type TemplateManifest, type TemplatePage, type TemplateProblem, } from './template-bundle.js';
3
+ export { PREVIEW_PREFIX, previewCases, previewPolicy, previewWords, startTemplatePreview, type TemplatePreview, type TemplatePreviewOptions, type TemplatePreviewPage, } from './template-preview.js';
4
4
  export { type DokebiInertiaTemplateOptions, packageVersion, SHARED_FILE, type SharedFile, sharedEntryName, } from './template-shared.js';
package/dist/template.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // `@dokebi/template-inertia/template` (D-0291): template bundles — the format and its check, and
2
2
  // the build that `dokebi template build` runs in a template repository.
3
- export { buildTemplateBundle, packageEntry, TEMPLATE_CARRY_FOLDER, templatePages, } from './template-build.js';
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';
3
+ export { buildTemplateBundle, packageEntry, TEMPLATE_CARRY_FOLDER, TEMPLATE_CSP_FILE, templatePages, } from './template-build.js';
4
+ export { checkTemplateBundle, compatibleLine, cspDeclarationProblem, SERVER_ONLY_SHARED, SHARED_DEFAULTS, sharedProblems, TEMPLATE_CSP_DIRECTIVES, TEMPLATE_FORMAT, TEMPLATE_MANIFEST, TEMPLATE_MAX_BYTES, TEMPLATE_NAME, TEMPLATE_SIGNATURE, TEMPLATE_STYLES_MAX, } from './template-bundle.js';
5
+ export { PREVIEW_PREFIX, previewCases, previewPolicy, previewWords, startTemplatePreview, } from './template-preview.js';
6
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.26",
3
+ "version": "0.4.27",
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",
@@ -65,7 +65,7 @@
65
65
  },
66
66
  "peerDependencies": {
67
67
  "@dokebi/core": "^0.4.2",
68
- "@dokebi/web": "^0.4.19",
68
+ "@dokebi/web": "^0.4.28",
69
69
  "fastify": "^5.12.7",
70
70
  "vue": "^3.5.0"
71
71
  },
@@ -81,7 +81,7 @@
81
81
  "dependencies": [
82
82
  {
83
83
  "name": "dokebi-web",
84
- "version": "^0.4.19"
84
+ "version": "^0.4.28"
85
85
  },
86
86
  {
87
87
  "name": "dokebi-session",
@@ -154,7 +154,7 @@
154
154
  "devDependencies": {
155
155
  "@dokebi/i18n": "0.2.10",
156
156
  "@dokebi/session": "0.4.11",
157
- "@dokebi/web": "0.4.27",
157
+ "@dokebi/web": "0.4.28",
158
158
  "@dokebi/websocket": "0.4.10",
159
159
  "@dokebi/websocket-hub": "0.4.6",
160
160
  "@inertiajs/vue3": "3.9.1",
@@ -8,4 +8,5 @@ export async function shared(_request: FastifyRequest) {
8
8
 
9
9
  // D-0291: with template bundles (options.dokebi-template-inertia.templates), export
10
10
  // verifyTemplate(bundle) here too: it judges a bundle (its signature, each page's meta.contract)
11
- // before the app uses it; in production a bundle is not used without it (AI.md §4.3).
11
+ // before the app uses it; in production a bundle is not used without it (AI.md §4.3). Its answer
12
+ // may also narrow the CSP sources the bundle declares (`csp`, D-0297).