@foliwake/server 0.0.0-stage → 0.4.0

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/README.md CHANGED
@@ -1,3 +1,1001 @@
1
- # Temporary Holding Version
1
+ # @foliwake/server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ <!-- usage -->
4
+
5
+ `@foliwake/server` is the server toolkit for any app that shows Foliwake pages, with no framework
6
+ dependency: Web `Request`/`Response` and plain functions. It parses the app's `foliwake.remote.json`, reads a
7
+ page's body from the site's live or preview origin with the credential, checks and prepares it per request,
8
+ serves the page's code release and pictures through your app's origin (proxies), builds a
9
+ Content-Security-Policy, and computes preload hints. `@foliwake/next` is built on it; use this package
10
+ directly with another server framework (a Vite or Remix server, Hono, Express with Web adapters, a worker).
11
+
12
+ | Entry | What |
13
+ | --- | --- |
14
+ | `@foliwake/server/config` | `loadFoliwakeConfig`, `parseFoliwakeConfig`, `clientSettings`, `pageAllowed`, `FoliwakeConfigError` |
15
+ | `@foliwake/server/origin` | `createOriginClient`: the only place a password is read (per request, from the variable the config names) |
16
+ | `@foliwake/server/page` | `readEnvelope` (primitive inputs: safe inside a cache function), `preparePage`, `FoliwakePageError` |
17
+ | `@foliwake/server/handlers` | `codeHandler`, `mediaHandler`: the code and media proxies |
18
+ | `@foliwake/server/html` | the strict body check: `checkPlainBody`, `checkBody`, `serialize`, `srcsetCandidates` |
19
+ | `@foliwake/server/csp` | `foliwakeCsp` |
20
+ | `@foliwake/server/preload` | `preloadHints`: modulepreload and stylesheet hints for a page's blocks |
21
+ | `@foliwake/server/schemas/remote-2.schema.json` | the JSON Schema of the config file |
22
+
23
+ ## Install
24
+
25
+ The packages are published on npm (npmjs.com) under the `@foliwake` scope; no registry setup or token is
26
+ needed. Install an exact version, the same for every `@foliwake/*` package:
27
+
28
+ ```bash
29
+ pnpm add @foliwake/server@0.3.0
30
+ ```
31
+
32
+ The config file sits in the app's root and holds no secrets, only the names of the variables with passwords or keys:
33
+
34
+ ```json
35
+ {
36
+ "$schema": "./node_modules/@foliwake/server/schemas/remote-2.schema.json",
37
+ "version": 2,
38
+ "site": "mysite",
39
+ "live": { "url": "https://mysite.example.org" },
40
+ "preview": { "url": "https://preview.mysite.example.org", "auth": { "type": "basic", "username": "app", "passwordEnv": "MYSITE_PREVIEW_PASSWORD" } },
41
+ "app": {
42
+ "pages": ["/**"],
43
+ "proxies": { "code": "/foliwake-code", "media": "/foliwake-media", "pages": null },
44
+ "blocks": { "entry": "scripts/blocks.js", "contract": "foliwake-blocks/2", "eventPrefix": "demo" },
45
+ "revalidate": 300
46
+ }
47
+ }
48
+ ```
49
+
50
+ An endpoint is open (no `auth`), behind HTTP Basic (`"type": "basic"`), or behind a delivery that checks
51
+ service tokens (for example an edge worker in front of the site's storage):
52
+
53
+ ```json
54
+ "live": {
55
+ "url": "https://mysite.worker.example.org",
56
+ "auth": { "type": "service-token", "issuer": "mysite-app", "kid": "mysite-app-2026-11", "privateKeyEnv": "MYSITE_LIVE_SIGNING_KEY" }
57
+ }
58
+ ```
59
+
60
+ With `service-token`, every origin request carries `Authorization: Bearer <JWT>`, signed for that request
61
+ alone: ES256, header `kid`, claims `iss` (= `issuer`, the delivery's `TOKEN_ISSUER`), `aud: site:<site>`,
62
+ `iat`, `exp = iat + 60` and `path`, the exact path of the request as sent, without the query
63
+ (`/lessons/a.plain.html`, `/lessons/query-index.json`). A token for a page does not open its `.plain.html`.
64
+ The variable holds the ES256 private key as JWK JSON text; the delivery holds the public key under the same
65
+ `kid`. Tokens are never cached, reused or logged.
66
+
67
+ ## Minimal example
68
+
69
+ ```ts
70
+ import { loadFoliwakeConfig } from '@foliwake/server/config';
71
+ import { createOriginClient } from '@foliwake/server/origin';
72
+ import { preparePage, readEnvelope } from '@foliwake/server/page';
73
+
74
+ const config = await loadFoliwakeConfig(); // FOLIWAKE_REMOTE, else ./foliwake.remote.json
75
+ const client = createOriginClient(config, process.env);
76
+
77
+ const envelope = await readEnvelope(config, client, config.site, 'live', '/lessons/a'); // cacheable
78
+ const page = preparePage(config, envelope); // per request: checked, rewritten, serialisable
79
+ console.log(page.identity, page.blocks);
80
+ ```
81
+
82
+ ## Examples
83
+
84
+ ### A page endpoint for the browser, with a cache of envelopes
85
+
86
+ Cache only the envelope (what the origin answered) and prepare per request, so your callbacks (`rewriteLink`,
87
+ `transform`) always run on the current code. The prepared page is what `@foliwake/client` or
88
+ `@foliwake/react` mount.
89
+
90
+ ```ts
91
+ import { loadFoliwakeConfig } from '@foliwake/server/config';
92
+ import { createOriginClient } from '@foliwake/server/origin';
93
+ import { FoliwakePageError, preparePage, readEnvelope, type PageEnvelope } from '@foliwake/server/page';
94
+ import { preloadHints } from '@foliwake/server/preload';
95
+
96
+ const config = await loadFoliwakeConfig();
97
+ const client = createOriginClient(config, process.env);
98
+ const cache = new Map<string, { at: number; envelope: PageEnvelope }>();
99
+
100
+ async function liveEnvelope(path: string): Promise<PageEnvelope> {
101
+ const hit = cache.get(path);
102
+ if (hit && Date.now() - hit.at < config.app!.revalidate * 1000) return hit.envelope;
103
+ const envelope = await readEnvelope(config, client, config.site, 'live', path);
104
+ cache.set(path, { at: Date.now(), envelope });
105
+ return envelope;
106
+ }
107
+
108
+ /** GET /api/page?path=/lessons/a */
109
+ export async function pageEndpoint(request: Request): Promise<Response> {
110
+ const path = new URL(request.url).searchParams.get('path') ?? '/';
111
+ try {
112
+ const page = preparePage(config, await liveEnvelope(path), { rewriteLink: (href) => `/learn${href}` });
113
+ page.preload = await preloadHints(config, client, page);
114
+ return Response.json(page, { headers: { 'Cache-Control': 'private, no-store' } });
115
+ } catch (error) {
116
+ if (error instanceof FoliwakePageError && (error.kind === 'not_found' || error.kind === 'not_allowed')) return new Response(null, { status: 404 });
117
+ throw error;
118
+ }
119
+ }
120
+ ```
121
+
122
+ ### Code and media proxies
123
+
124
+ Mount the handlers under the prefixes of `app.proxies` and pass them the path segments after the prefix. They
125
+ serve only files of a `cd_…` code release and hashed pictures, add the credential on the server and forward
126
+ nothing from the browser. Live files are cached for a year (immutable); preview answers are
127
+ `private, no-store` and need `authorizePreview`.
128
+
129
+ ```ts
130
+ import { loadFoliwakeConfig } from '@foliwake/server/config';
131
+ import { codeHandler, mediaHandler } from '@foliwake/server/handlers';
132
+ import { createOriginClient } from '@foliwake/server/origin';
133
+
134
+ const config = await loadFoliwakeConfig();
135
+ const client = createOriginClient(config, process.env);
136
+ const isAuthor = async (request: Request) => (request.headers.get('cookie') ?? '').includes('role=author'); // your sign-in
137
+ const code = codeHandler(config, client, { authorizePreview: isAuthor });
138
+ const media = mediaHandler(config, client, { authorizePreview: isAuthor });
139
+
140
+ /** Route requests under /foliwake-code/ and /foliwake-media/ (app.proxies) to the handlers. */
141
+ export async function proxies(request: Request): Promise<Response | null> {
142
+ const { pathname } = new URL(request.url);
143
+ const segments = (prefix: string) => pathname.slice(prefix.length + 1).split('/').filter(Boolean);
144
+ if (pathname.startsWith(`${config.app!.proxies.code}/`)) return code(request, { path: segments(config.app!.proxies.code) });
145
+ if (pathname.startsWith(`${config.app!.proxies.media}/`)) return media(request, { path: segments(config.app!.proxies.media) });
146
+ return null;
147
+ }
148
+ ```
149
+
150
+ ### CSP and browser settings
151
+
152
+ ```ts
153
+ import { clientSettings, loadFoliwakeConfig } from '@foliwake/server/config';
154
+ import { foliwakeCsp } from '@foliwake/server/csp';
155
+
156
+ const config = await loadFoliwakeConfig();
157
+
158
+ // One header value for every route: blocks load from your own origin, so no Foliwake host is named.
159
+ export const csp = foliwakeCsp({
160
+ strategy: 'self-inline',
161
+ mediaBase: config.app?.media?.base ?? null,
162
+ reportUri: '/csp-report',
163
+ dev: process.env.NODE_ENV === 'development',
164
+ });
165
+
166
+ // The only part of the config a browser may see: site, proxy prefixes, blocks contract and event prefix.
167
+ export const settingsForBrowser = clientSettings(config);
168
+ ```
169
+
170
+ ## Compatibility
171
+
172
+ | | |
173
+ | --- | --- |
174
+ | Node.js | 22.22 or newer (Web `fetch`, `Request`, `Response`, streams) |
175
+ | Foliwake origin | plain/2: `X-Code-Release` with every `.plain.html` (a body without it is refused) |
176
+ | Config | `foliwake.remote.json` version 2 |
177
+ | Blocks contract | `foliwake-blocks/2` |
178
+
179
+ Changes per version, breaking ones marked: `CHANGELOG.md` in the package
180
+ (`node_modules/@foliwake/server/CHANGELOG.md`).
181
+
182
+ ## Good to know
183
+
184
+ - Bodies are checked before and after your `transform`: no scripts, styles, frames, inline SVG or MathML, no
185
+ `on…` attributes or `javascript:` URLs; `srcset` and entities are parsed like a browser does. What is
186
+ returned is serialised from the checked tree. A refused body throws `FoliwakePageError` with kind `invalid`.
187
+ - Origin responses are size-limited while streaming (body 2 MB, code 5 MB, media 25 MB); requests time out
188
+ after 10 s.
189
+ - Credentials never appear in messages; a missing or malformed password or key variable is a
190
+ `FoliwakeConfigError` that names the variable, not its value. The secret is read at each request, so a
191
+ rotated secret works without a restart. A private key whose own `kid` differs from the config's is refused.
192
+ - Rotating a service-token key: add the new public key to the delivery's key set first (both `kid`s listed),
193
+ then switch the app's `kid` and private key, then remove the old public key.
194
+ - `preparePage` leaves `page.preload` empty; `preloadHints` fills it from the release's
195
+ `components/components.json` (only blocks that declare a `.js` or `.css` get hints).
196
+
197
+ ## See also
198
+
199
+ - [`@foliwake/next`](https://www.npmjs.com/package/@foliwake/next): this toolkit wired into a Next.js App
200
+ Router app.
201
+ - [`@foliwake/client`](https://www.npmjs.com/package/@foliwake/client) and
202
+ [`@foliwake/react`](https://www.npmjs.com/package/@foliwake/react): mount the prepared page in the browser.
203
+
204
+ License: Apache-2.0.
205
+
206
+ <!-- usagestop -->
207
+
208
+ ## API
209
+
210
+ <!-- api -->
211
+
212
+ <!-- Generated by `pnpm packages:reference` from the type declarations; do not edit by hand. -->
213
+
214
+ ### `@foliwake/server/config`
215
+
216
+ **Functions and components**
217
+
218
+ #### `appOf()`
219
+
220
+ The app settings; throws when the config has none.
221
+
222
+ ```ts
223
+ function appOf(config: FoliwakeAppConfig): FoliwakeAppSettings
224
+ ```
225
+
226
+ **Returns** `FoliwakeAppSettings`
227
+
228
+ #### `checkEnvName()`
229
+
230
+ Validates an environment variable NAME (never a value).
231
+
232
+ ```ts
233
+ function checkEnvName(value: unknown, where: string, extra?: ParseOptions['envNameProblem']): string
234
+ ```
235
+
236
+ **Returns** `string`
237
+
238
+ #### `checkUsername()`
239
+
240
+ Validates a Basic user name (no `:` or control characters, at most 128 characters).
241
+
242
+ ```ts
243
+ function checkUsername(value: unknown, where: string): string
244
+ ```
245
+
246
+ **Returns** `string`
247
+
248
+ #### `clientSettings()`
249
+
250
+ The explicit browser projection: nothing else of the config reaches a browser.
251
+
252
+ ```ts
253
+ function clientSettings(config: FoliwakeAppConfig): ClientSettings
254
+ ```
255
+
256
+ **Returns** `ClientSettings`
257
+
258
+ #### `configFilePath()`
259
+
260
+ Which file: an explicit `file` beats FOLIWAKE_REMOTE beats `<cwd>/foliwake.remote.json`.
261
+
262
+ ```ts
263
+ function configFilePath(opts?: {
264
+ cwd?: string;
265
+ file?: string;
266
+ env?: NodeJS.ProcessEnv;
267
+ }): string
268
+ ```
269
+
270
+ **Returns** `string`
271
+
272
+ #### `endpointOf()`
273
+
274
+ The endpoint of a channel; a missing one is an error, never replaced by the other channel.
275
+
276
+ ```ts
277
+ function endpointOf(config: FoliwakeAppConfig, channel: ChannelName): FoliwakeEndpoint
278
+ ```
279
+
280
+ **Returns** `FoliwakeEndpoint`
281
+
282
+ #### `isLoopbackName()`
283
+
284
+ True for 127.x, localhost, *.localhost and ::1.
285
+
286
+ ```ts
287
+ function isLoopbackName(hostname: string): boolean
288
+ ```
289
+
290
+ **Returns** `boolean`
291
+
292
+ #### `loadFoliwakeConfig()`
293
+
294
+ Reads and parses the config file (see configFilePath).
295
+
296
+ ```ts
297
+ function loadFoliwakeConfig(opts?: {
298
+ cwd?: string;
299
+ file?: string;
300
+ env?: NodeJS.ProcessEnv;
301
+ } & Omit<ParseOptions, 'file'>): Promise<FoliwakeAppConfig>
302
+ ```
303
+
304
+ **Returns** `Promise<FoliwakeAppConfig>`
305
+
306
+ #### `pageAllowed()`
307
+
308
+ Whether the app may read this page path (`app.pages`).
309
+
310
+ ```ts
311
+ function pageAllowed(config: FoliwakeAppConfig, pagePath: string): boolean
312
+ ```
313
+
314
+ **Returns** `boolean`
315
+
316
+ #### `parseFoliwakeConfig()`
317
+
318
+ Parses the text of a version 2 config. Throws FoliwakeConfigError with a message that names the field.
319
+
320
+ ```ts
321
+ function parseFoliwakeConfig(text: string, opts?: ParseOptions): FoliwakeAppConfig
322
+ ```
323
+
324
+ **Returns** `FoliwakeAppConfig`
325
+
326
+ #### `parseRemoteUrl()`
327
+
328
+ A site origin: https (http only for loopback), no credentials, path, query or fragment.
329
+
330
+ ```ts
331
+ function parseRemoteUrl(value: unknown, where: string): string
332
+ ```
333
+
334
+ **Returns** `string`
335
+
336
+ **Classes**
337
+
338
+ #### `FoliwakeConfigError`
339
+
340
+ A configuration problem; the message is shown as is (it never contains a secret).
341
+
342
+ ```ts
343
+ class FoliwakeConfigError extends Error
344
+ ```
345
+
346
+ | Member | Type | Description |
347
+ | --- | --- | --- |
348
+ | `name` | `string` | |
349
+
350
+ **Constants**
351
+
352
+ #### `CHANNELS`
353
+
354
+ The channels a config can name.
355
+
356
+ ```ts
357
+ const CHANNELS: readonly ChannelName[]
358
+ ```
359
+
360
+ #### `CONFIG_ENV`
361
+
362
+ The environment variable that names another config file.
363
+
364
+ ```ts
365
+ const CONFIG_ENV = "FOLIWAKE_REMOTE"
366
+ ```
367
+
368
+ #### `CONFIG_FILE`
369
+
370
+ The default config file name, looked up in the current directory.
371
+
372
+ ```ts
373
+ const CONFIG_FILE = "foliwake.remote.json"
374
+ ```
375
+
376
+ **Interfaces**
377
+
378
+ #### `BasicAuth`
379
+
380
+ HTTP Basic credentials: a user name and the NAME of the variable holding the password.
381
+
382
+ ```ts
383
+ interface BasicAuth
384
+ ```
385
+
386
+ | Member | Type | Description |
387
+ | --- | --- | --- |
388
+ | `type` | `'basic'` | |
389
+ | `username` | `string` | |
390
+ | `passwordEnv` | `string` | |
391
+
392
+ #### `FoliwakeAppConfig`
393
+
394
+ A parsed and validated `foliwake.remote.json` (version 2). It holds credential variable names, never secrets.
395
+
396
+ ```ts
397
+ interface FoliwakeAppConfig
398
+ ```
399
+
400
+ | Member | Type | Description |
401
+ | --- | --- | --- |
402
+ | `version` | `2` | |
403
+ | `site` | `string` | |
404
+ | `live` | `FoliwakeEndpoint \| null` | |
405
+ | `preview` | `FoliwakeEndpoint \| null` | |
406
+ | `app` | `FoliwakeAppSettings \| null` | Null only when parsed with `requireApp: false` (the engine CLI). |
407
+ | `from` | `string` | Where the config came from, for messages. |
408
+
409
+ #### `FoliwakeAppSettings`
410
+
411
+ The `app` part of the config, with defaults applied.
412
+
413
+ ```ts
414
+ interface FoliwakeAppSettings
415
+ ```
416
+
417
+ | Member | Type | Description |
418
+ | --- | --- | --- |
419
+ | `pages` | `readonly string[]` | Page globs the app may read. |
420
+ | `proxies` | `{ code: string; media: string; pages: null; }` | App-origin URL prefixes of the proxies. |
421
+ | `blocks` | `{ entry: string \| null; contract: string; major: number; eventPrefix: string; }` | Where `mountBlocks` lives in a code release; null: bodies stay static. |
422
+ | `media` | `{ base: string; transform: 'cloudflare-images' \| null; } \| null` | Live media through a transforming host; null: media through the proxy. |
423
+ | `revalidate` | `number` | Seconds before a cached envelope is stale (stale-while-revalidate). |
424
+
425
+ #### `FoliwakeEndpoint`
426
+
427
+ A channel's origin and its optional credential.
428
+
429
+ ```ts
430
+ interface FoliwakeEndpoint
431
+ ```
432
+
433
+ | Member | Type | Description |
434
+ | --- | --- | --- |
435
+ | `origin` | `string` | Origin only: scheme, host, port. |
436
+ | `auth` | `RemoteAuth \| null` | |
437
+
438
+ #### `ParseOptions`
439
+
440
+ Options of `parseFoliwakeConfig`.
441
+
442
+ ```ts
443
+ interface ParseOptions
444
+ ```
445
+
446
+ | Member | Type | Description |
447
+ | --- | --- | --- |
448
+ | `file?` | `string` | For messages (default foliwake.remote.json). |
449
+ | `requireApp?` | `boolean` | Refuse a file without `app` (default true; the CLI passes false). |
450
+ | `envNameProblem?` | `(name: string, what: string) => string \| null` | An additional rule for credential variable names (the engine CLI passes its own). |
451
+
452
+ #### `ServiceTokenAuth`
453
+
454
+ A service token: each request carries a fresh ES256 JWT for its exact path, signed with the private key in the variable `privateKeyEnv` (a JWK as JSON text). Delivery checks it with the public key of `kid`.
455
+
456
+ ```ts
457
+ interface ServiceTokenAuth
458
+ ```
459
+
460
+ | Member | Type | Description |
461
+ | --- | --- | --- |
462
+ | `type` | `'service-token'` | |
463
+ | `issuer` | `string` | The `iss` the delivery expects (its TOKEN_ISSUER). |
464
+ | `kid` | `string` | The key id the delivery looks the public key up by. |
465
+ | `privateKeyEnv` | `string` | The NAME of the variable holding the private key. |
466
+
467
+ **Types**
468
+
469
+ #### `RemoteAuth`
470
+
471
+ The credential of an endpoint.
472
+
473
+ ```ts
474
+ type RemoteAuth = BasicAuth | ServiceTokenAuth
475
+ ```
476
+
477
+ **Also exported** (documented where they are defined)
478
+
479
+ - from `@foliwake/blocks-contract/page`: `ClientSettings`
480
+
481
+ ### `@foliwake/server/origin`
482
+
483
+ **Functions and components**
484
+
485
+ #### `createOriginClient()`
486
+
487
+ The client for the config's origins. The secret is read from the environment at each request (a rotated secret takes effect without a restart) and goes only into the Authorization header: `basic` sends the password of `passwordEnv`; `service-token` signs a fresh token for the request's exact path with the private key of `privateKeyEnv`.
488
+
489
+ ```ts
490
+ function createOriginClient(config: FoliwakeAppConfig, env?: NodeJS.ProcessEnv, opts?: OriginClientOptions): OriginClient
491
+ ```
492
+
493
+ | Parameter | Type | Description |
494
+ | --- | --- | --- |
495
+ | `config` | `FoliwakeAppConfig` | |
496
+ | `env?` | `NodeJS.ProcessEnv` | Where secrets are read (default `process.env`). |
497
+ | `opts?` | `OriginClientOptions` | |
498
+
499
+ **Returns** `OriginClient`
500
+
501
+ **Constants**
502
+
503
+ #### `SERVICE_TOKEN_LIFETIME_SECONDS`
504
+
505
+ Seconds a service token lives: `exp = iat + 60`. Delivery accepts at most 120, with 5 s of clock skew.
506
+
507
+ ```ts
508
+ const SERVICE_TOKEN_LIFETIME_SECONDS = 60
509
+ ```
510
+
511
+ **Interfaces**
512
+
513
+ #### `OriginClient`
514
+
515
+ Requests to the configured live and preview origins, with the credential added per request.
516
+
517
+ ```ts
518
+ interface OriginClient
519
+ ```
520
+
521
+ | Member | Type | Description |
522
+ | --- | --- | --- |
523
+ | `readonly config` | `FoliwakeAppConfig` | |
524
+ | `originOf()` | `(channel: ChannelName) => string` | The origin of a channel (for messages and loopback checks). |
525
+ | `request()` | `(channel: ChannelName, path: string, opts?: OriginRequestOptions) => Promise<Response>` | GET/HEAD `<origin><path>`; `redirect: 'manual'`, 10 s timeout unless `signal` is given. |
526
+
527
+ #### `OriginClientOptions`
528
+
529
+ Options of `createOriginClient`.
530
+
531
+ ```ts
532
+ interface OriginClientOptions
533
+ ```
534
+
535
+ | Member | Type | Description |
536
+ | --- | --- | --- |
537
+ | `fetch?` | `typeof fetch` | A fetch implementation (tests); default globalThis.fetch. |
538
+ | `timeoutMs?` | `number` | |
539
+ | `now?` | `() => number` | The clock of service tokens, in milliseconds (tests); default Date.now. |
540
+
541
+ #### `OriginRequestOptions`
542
+
543
+ Options of one origin request.
544
+
545
+ ```ts
546
+ interface OriginRequestOptions
547
+ ```
548
+
549
+ | Member | Type | Description |
550
+ | --- | --- | --- |
551
+ | `method?` | `'GET' \| 'HEAD'` | |
552
+ | `signal?` | `AbortSignal` | |
553
+ | `headers?` | `Record<string, string>` | Only these headers are sent (never a browser's). |
554
+
555
+ ### `@foliwake/server/page`
556
+
557
+ **Functions and components**
558
+
559
+ #### `blocksUrlOf()`
560
+
561
+ The same-origin URL of the blocks module, or null when the config names no blocks entry.
562
+
563
+ ```ts
564
+ function blocksUrlOf(config: FoliwakeAppConfig, channel: ChannelName, codeRelease: CodeReleaseId): {
565
+ base: string;
566
+ url: string;
567
+ } | null
568
+ ```
569
+
570
+ **Returns** `{ base: string; url: string; } \| null`
571
+
572
+ #### `plainPath()`
573
+
574
+ The origin URL path of a page's body (`/` → `/index.plain.html`).
575
+
576
+ ```ts
577
+ function plainPath(pagePath: string): string
578
+ ```
579
+
580
+ **Returns** `string`
581
+
582
+ #### `preparePage()`
583
+
584
+ Per request, after the cache: check → rewrite media/links → transform → check again → serialise.
585
+
586
+ ```ts
587
+ function preparePage(config: FoliwakeAppConfig, envelope: PageEnvelope, opts?: PrepareOptions): FoliwakePageData
588
+ ```
589
+
590
+ | Parameter | Type | Description |
591
+ | --- | --- | --- |
592
+ | `config` | `FoliwakeAppConfig` | |
593
+ | `envelope` | `PageEnvelope` | What readEnvelope (or a cached copy of it) returned. |
594
+ | `opts?` | `PrepareOptions` | |
595
+
596
+ **Returns** `FoliwakePageData`: The serialisable page for a client component (`preload` is empty; readPage of the Next package fills it). Throws FoliwakePageError('invalid') when the body or the transform's output is refused.
597
+
598
+ #### `readEnvelope()`
599
+
600
+ Reads `<path>.plain.html` from the channel's origin. Primitive inputs only, no callbacks and no signal (an internal 10 s timeout), so it can run inside a cache function. Refuses paths outside `app.pages`.
601
+
602
+ ```ts
603
+ function readEnvelope(config: FoliwakeAppConfig, client: OriginClient, site: string, channel: ChannelName, path: string): Promise<PageEnvelope>
604
+ ```
605
+
606
+ | Parameter | Type | Description |
607
+ | --- | --- | --- |
608
+ | `config` | `FoliwakeAppConfig` | |
609
+ | `client` | `OriginClient` | |
610
+ | `site` | `string` | The config's site (`config.site`); another site is refused. |
611
+ | `channel` | `ChannelName` | |
612
+ | `path` | `string` | The page path (`/`, `/lessons/a`). |
613
+
614
+ **Returns** `Promise<PageEnvelope>`: The envelope; throws FoliwakePageError (`not_found`, `not_allowed`, `origin`, `unauthorized`, …).
615
+
616
+ **Classes**
617
+
618
+ #### `FoliwakePageError`
619
+
620
+ A page that cannot be shown. `status`: the origin's HTTP status when there was one.
621
+
622
+ ```ts
623
+ class FoliwakePageError extends Error
624
+ new FoliwakePageError(kind: PageErrorKind, message: string, opts?: {
625
+ status?: number;
626
+ cause?: unknown;
627
+ })
628
+ ```
629
+
630
+ | Member | Type | Description |
631
+ | --- | --- | --- |
632
+ | `name` | `string` | |
633
+ | `readonly kind` | `PageErrorKind` | |
634
+ | `readonly status?` | `number` | |
635
+
636
+ **Interfaces**
637
+
638
+ #### `PrepareOptions`
639
+
640
+ Options of `preparePage`.
641
+
642
+ ```ts
643
+ interface PrepareOptions
644
+ ```
645
+
646
+ | Member | Type | Description |
647
+ | --- | --- | --- |
648
+ | `mode?` | `string` | The site's mode of the page (a token, `[a-z][a-z0-9-]`, at most 32 characters), given to the blocks as `host.mode`; absent → none. `exam` is refused: the assessment extension's exam needs answers stripped by the origin, which does not exist yet, so an exam body would carry its answers. |
649
+ | `rewriteLink?` | `(href: string) => string` | Root-relative links (`/x`) of `<a href>`; returns the app's URL. |
650
+ | `transform?` | `(html: string, envelope: PageEnvelope) => string` | The app's own change of the body (allow-list, artwork, …); its output is checked again. |
651
+
652
+ **Types**
653
+
654
+ #### `PageErrorKind`
655
+
656
+ Why a page cannot be shown (`FoliwakePageError.kind`).
657
+
658
+ ```ts
659
+ type PageErrorKind = 'not_found' | 'not_allowed' | 'origin' | 'invalid' | 'unauthorized' | 'too_large'
660
+ ```
661
+
662
+ **Also exported** (documented where they are defined)
663
+
664
+ - from `@foliwake/blocks-contract/import-map`: `pageImportMap`
665
+ - from `@foliwake/blocks-contract/page`: `FoliwakePageData`, `PageEnvelope`
666
+
667
+ ### `@foliwake/server/handlers`
668
+
669
+ **Functions and components**
670
+
671
+ #### `codeHandler()`
672
+
673
+ `GET|HEAD <proxies.code>/[preview/]<cd>/<path inside the code release>`.
674
+
675
+ ```ts
676
+ function codeHandler(config: FoliwakeAppConfig, client: OriginClient, opts: ProxyOptions): Handler
677
+ ```
678
+
679
+ **Returns** `Handler`
680
+
681
+ #### `mediaHandler()`
682
+
683
+ `GET|HEAD <proxies.media>/[preview/]<sha256>.<ext>`: images only, one hashed segment.
684
+
685
+ ```ts
686
+ function mediaHandler(config: FoliwakeAppConfig, client: OriginClient, opts: ProxyOptions): Handler
687
+ ```
688
+
689
+ **Returns** `Handler`
690
+
691
+ **Interfaces**
692
+
693
+ #### `ProxyOptions`
694
+
695
+ Options of `codeHandler` and `mediaHandler`.
696
+
697
+ ```ts
698
+ interface ProxyOptions
699
+ ```
700
+
701
+ | Member | Type | Description |
702
+ | --- | --- | --- |
703
+ | `authorizePreview` | `AuthorizePreview` | The app's author check for `preview/…` requests, or `false` to answer them 404. Required. |
704
+
705
+ **Types**
706
+
707
+ #### `AuthorizePreview`
708
+
709
+ The app's author check for preview requests, or `false` (preview answers 404).
710
+
711
+ ```ts
712
+ type AuthorizePreview = ((request: Request) => boolean | Promise<boolean>) | false
713
+ ```
714
+
715
+ #### `Handler`
716
+
717
+ A proxy handler: the request and the path segments after the proxy prefix.
718
+
719
+ ```ts
720
+ type Handler = (request: Request, params: {
721
+ path: string[];
722
+ }) => Promise<Response>
723
+ ```
724
+
725
+ ### `@foliwake/server/html`
726
+
727
+ **Functions and components**
728
+
729
+ #### `checkBody()`
730
+
731
+ Parses and checks a body; returns the checked tree. Throws FoliwakePageError('invalid').
732
+
733
+ ```ts
734
+ function checkBody(html: string, pagePath?: string): HtmlNode[]
735
+ ```
736
+
737
+ **Returns** `HtmlNode[]`
738
+
739
+ #### `checkPlainBody()`
740
+
741
+ Checks a body (the strict body check); throws FoliwakePageError('invalid').
742
+
743
+ ```ts
744
+ function checkPlainBody(html: string, pagePath?: string): void
745
+ ```
746
+
747
+ **Returns** `void`
748
+
749
+ #### `componentNames()`
750
+
751
+ Distinct `data-component` names, sorted.
752
+
753
+ ```ts
754
+ function componentNames(nodes: readonly HtmlNode[]): string[]
755
+ ```
756
+
757
+ **Returns** `string[]`
758
+
759
+ #### `elements()`
760
+
761
+ Every element below `nodes`, depth first.
762
+
763
+ ```ts
764
+ function elements(nodes: readonly HtmlNode[]): Generator<HtmlElement>
765
+ ```
766
+
767
+ **Returns** `Generator<HtmlElement>`
768
+
769
+ #### `parseStrict()`
770
+
771
+ Parses a body strictly. Comments are dropped; a doctype or processing instruction is an error.
772
+
773
+ ```ts
774
+ function parseStrict(html: string): HtmlNode[]
775
+ ```
776
+
777
+ **Returns** `HtmlNode[]`
778
+
779
+ #### `sanitizedHtml()`
780
+
781
+ The checked body, serialised from its tree.
782
+
783
+ ```ts
784
+ function sanitizedHtml(nodes: readonly HtmlNode[]): string
785
+ ```
786
+
787
+ **Returns** `string`
788
+
789
+ #### `serialize()`
790
+
791
+ Serialises the tree as HTML (the WHATWG fragment serialisation rules for the elements a body may hold).
792
+
793
+ ```ts
794
+ function serialize(nodes: readonly HtmlNode[]): string
795
+ ```
796
+
797
+ **Returns** `string`
798
+
799
+ #### `srcsetCandidates()`
800
+
801
+ Splits a srcset into candidates: the URL ends at whitespace; descriptors run to the next comma.
802
+
803
+ ```ts
804
+ function srcsetCandidates(srcset: string): {
805
+ url: string;
806
+ descriptor: string;
807
+ }[]
808
+ ```
809
+
810
+ **Returns** `{ url: string; descriptor: string; }[]`
811
+
812
+ #### `urlProblem()`
813
+
814
+ Why a URL value is not allowed for this element/attribute, or null. Values are entity-decoded already.
815
+
816
+ ```ts
817
+ function urlProblem(element: string, attribute: string, value: string, pagePath?: string): string | null
818
+ ```
819
+
820
+ **Returns** `string \| null`
821
+
822
+ **Classes**
823
+
824
+ #### `HtmlParseError`
825
+
826
+ A body that cannot be parsed strictly.
827
+
828
+ ```ts
829
+ class HtmlParseError extends Error
830
+ ```
831
+
832
+ | Member | Type | Description |
833
+ | --- | --- | --- |
834
+ | `name` | `string` | |
835
+
836
+ **Constants**
837
+
838
+ #### `COMPONENT_NAME`
839
+
840
+ A valid `data-component` name.
841
+
842
+ ```ts
843
+ const COMPONENT_NAME: RegExp
844
+ ```
845
+
846
+ #### `REFUSED_ELEMENTS`
847
+
848
+ Elements a body may not hold (incl. foreign content: no inline SVG or MathML in 0.1). `<form>` is allowed only as the engine writes it for the question block: an explicit `method="dialog"`, no `action`, `target` or `enctype`; no control may override the submission (`formmethod`, `formaction`, `formtarget`, `formenctype`) or associate itself with another form (`form`). Such a form closes a dialog at most; it submits nowhere.
849
+
850
+ ```ts
851
+ const REFUSED_ELEMENTS: ReadonlySet<string>
852
+ ```
853
+
854
+ **Types**
855
+
856
+ #### `HtmlElement`
857
+
858
+ An element of a parsed body.
859
+
860
+ ```ts
861
+ type HtmlElement = {
862
+ type: 'tag';
863
+ name: string;
864
+ attribs: Record<string, string>;
865
+ children: HtmlNode[];
866
+ }
867
+ ```
868
+
869
+ #### `HtmlNode`
870
+
871
+ A node of a parsed body.
872
+
873
+ ```ts
874
+ type HtmlNode = HtmlText | HtmlElement
875
+ ```
876
+
877
+ #### `HtmlText`
878
+
879
+ A text node of a parsed body.
880
+
881
+ ```ts
882
+ type HtmlText = {
883
+ type: 'text';
884
+ data: string;
885
+ }
886
+ ```
887
+
888
+ ### `@foliwake/server/csp`
889
+
890
+ **Functions and components**
891
+
892
+ #### `foliwakeCsp()`
893
+
894
+ The policy as one header value.
895
+
896
+ ```ts
897
+ function foliwakeCsp(opts: CspOptions): string
898
+ ```
899
+
900
+ **Returns** `string`
901
+
902
+ **Constants**
903
+
904
+ #### `REACT_SHELL_SCRIPT`
905
+
906
+ React DOM 19.2's inline `requestAnimationFrame(function(){$RT=performance.now()});` in PPR static shells.
907
+
908
+ ```ts
909
+ const REACT_SHELL_SCRIPT = "requestAnimationFrame(function(){$RT=performance.now()});"
910
+ ```
911
+
912
+ #### `REACT_SHELL_SCRIPT_HASH`
913
+
914
+ The CSP hash source of `REACT_SHELL_SCRIPT` (used by the `nonce` strategy).
915
+
916
+ ```ts
917
+ const REACT_SHELL_SCRIPT_HASH = "'sha256-7mu4H06fwDCjmnxxr/xNHyuQC6pLTHr4M2E4jXw5WZs='"
918
+ ```
919
+
920
+ **Interfaces**
921
+
922
+ #### `CspOptions`
923
+
924
+ Options of `foliwakeCsp`.
925
+
926
+ ```ts
927
+ interface CspOptions
928
+ ```
929
+
930
+ | Member | Type | Description |
931
+ | --- | --- | --- |
932
+ | `strategy` | `'self-inline' \| 'nonce'` | `self-inline` (recommended; works with partial prerendering) or `nonce` (experimental, not recommended). |
933
+ | `nonce?` | `string` | Required with 'nonce'. |
934
+ | `mediaBase?` | `string \| null` | The media host whose pictures pages show: `app.media.base` (live pictures through a transforming host), or the site's own CDN when the site resizes images on one (`media.resize: "cdn"`, whose `cdnBase` is in every live `srcset`). An https address; only its origin (scheme and host) is added to `img-src`. |
935
+ | `dev?` | `boolean` | Development: adds 'unsafe-eval' (React's debugging) and websocket connections for HMR. |
936
+ | `reportUri?` | `string` | Where browsers report violations (`report-uri`). |
937
+ | `extra?` | `Partial<Record<string, string[]>>` | More sources per directive, e.g. { 'connect-src': ['https://api.example.org'] }. |
938
+
939
+ ### `@foliwake/server/preload`
940
+
941
+ **Functions and components**
942
+
943
+ #### `clearPreloadCache()`
944
+
945
+ Forgets every remembered code file (tests).
946
+
947
+ ```ts
948
+ function clearPreloadCache(): void
949
+ ```
950
+
951
+ **Returns** `void`
952
+
953
+ #### `codePath()`
954
+
955
+ A path inside the code release the proxy would serve, or null.
956
+
957
+ ```ts
958
+ function codePath(relative: string): string | null
959
+ ```
960
+
961
+ **Returns** `string \| null`
962
+
963
+ #### `preloadHints()`
964
+
965
+ Hints for a prepared page: modulepreload for its modules, preload as=style for its block stylesheets.
966
+
967
+ ```ts
968
+ function preloadHints(config: FoliwakeAppConfig, client: OriginClient, page: FoliwakePageData): Promise<PreloadHint[]>
969
+ ```
970
+
971
+ **Returns** `Promise<PreloadHint[]>`
972
+
973
+ #### `resolveInRelease()`
974
+
975
+ Resolves `specifier` against the module at `from` (both inside the release), or null when it leaves it.
976
+
977
+ ```ts
978
+ function resolveInRelease(from: string, specifier: string): string | null
979
+ ```
980
+
981
+ **Returns** `string \| null`
982
+
983
+ #### `staticImports()`
984
+
985
+ The relative static import specifiers of an ES module's text, and the kit's (KIT_SPECIFIER).
986
+
987
+ ```ts
988
+ function staticImports(source: string): string[]
989
+ ```
990
+
991
+ **Returns** `string[]`
992
+
993
+ **Also exported** (documented where they are defined)
994
+
995
+ - from `@foliwake/blocks-contract/page`: `PreloadHint`
996
+
997
+ ### `@foliwake/server/schemas/remote-2.schema.json`
998
+
999
+ A file, not a module: `schemas/remote-2.schema.json` in the package.
1000
+
1001
+ <!-- apistop -->