prunelle 0.8.0 → 0.9.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/llms.txt +61 -44
- package/package.json +7 -2
- package/src/a11y/declaration.ts +6 -10
- package/src/a11y/index.ts +69 -125
- package/src/animate.ts +127 -0
- package/src/build/asides.ts +51 -0
- package/src/build/bundle.ts +88 -134
- package/src/build/client-entries.ts +6 -6
- package/src/build/client-outputs.ts +75 -0
- package/src/build/client-plugin.ts +9 -4
- package/src/build/ecoindex.ts +4 -2
- package/src/build/files.ts +18 -0
- package/src/build/graph.ts +14 -6
- package/src/build/index.ts +20 -10
- package/src/build/islands.ts +4 -1
- package/src/build/key-types.ts +31 -0
- package/src/build/manifest.ts +19 -1
- package/src/build/plugin-host.ts +2 -0
- package/src/build/prerender.ts +2 -2
- package/src/build/reach.ts +14 -1
- package/src/build/report.ts +1 -1
- package/src/build/route-types.ts +16 -0
- package/src/build/routes.ts +24 -15
- package/src/build/seed-ids.ts +65 -0
- package/src/build/seed-writes.ts +111 -0
- package/src/build/static-headers.ts +2 -2
- package/src/build/static.ts +1 -1
- package/src/cli/check-cache.ts +51 -0
- package/src/cli/check-consent.ts +95 -0
- package/src/cli/check-forms.ts +2 -2
- package/src/cli/check-links-patterns.ts +101 -0
- package/src/cli/check-links.ts +16 -100
- package/src/cli/check-regions.ts +185 -0
- package/src/cli/check-security.ts +50 -6
- package/src/cli/check.ts +40 -18
- package/src/cli/commands.ts +134 -14
- package/src/cli/docs.ts +21 -2
- package/src/cli/index.ts +1 -1
- package/src/cli/inspect.ts +2 -0
- package/src/cli/mcp-tools.ts +2 -2
- package/src/cli/new.ts +9 -5
- package/src/cli/upgrade-names.ts +14 -2
- package/src/cli/upgrade.ts +3 -0
- package/src/compiler/analyze.ts +2 -2
- package/src/compiler/cacheability.ts +24 -2
- package/src/compiler/compliance-contrast.ts +284 -0
- package/src/compiler/compliance-empty.ts +24 -0
- package/src/compiler/compliance-rgaa-content.ts +95 -0
- package/src/compiler/compliance-rgaa-criteria.ts +45 -0
- package/src/compiler/compliance-rgaa-pages.ts +140 -0
- package/src/compiler/compliance-rgaa.ts +19 -0
- package/src/compiler/compliance-third-party.ts +59 -0
- package/src/compiler/compliance-urls.ts +52 -0
- package/src/compiler/compliance.ts +70 -42
- package/src/compiler/cookie-inventory.ts +119 -0
- package/src/compiler/foreign-imports.ts +5 -3
- package/src/compiler/mistakes.ts +18 -9
- package/src/compiler/props-pattern.ts +211 -0
- package/src/compiler/props.ts +177 -346
- package/src/compiler/ssr-emit.ts +510 -0
- package/src/compiler/ssr-helpers.ts +170 -121
- package/src/compiler/ssr.ts +25 -440
- package/src/context.ts +14 -1
- package/src/dev/child.ts +1 -1
- package/src/dev/hot-islands.ts +71 -0
- package/src/dev/index.ts +31 -18
- package/src/dev/protocol.ts +1 -1
- package/src/dev/queue.ts +3 -2
- package/src/dev/reload.ts +1 -1
- package/src/dev/supervisor.ts +3 -1
- package/src/dev/watchers.ts +6 -2
- package/src/dom/action.ts +97 -14
- package/src/dom/extras.ts +2 -1
- package/src/dom/field-marks.ts +24 -0
- package/src/dom/hot.ts +9 -0
- package/src/dom/index.ts +25 -5
- package/src/dom/island-hot.ts +29 -0
- package/src/dom/island.ts +13 -2
- package/src/dom/prefetch.ts +132 -0
- package/src/dom/regions.ts +498 -0
- package/src/dom/swap.ts +245 -0
- package/src/dom/trusted.ts +22 -0
- package/src/dom/upload.ts +44 -0
- package/src/eco/declaration.ts +39 -40
- package/src/eco/index.ts +5 -5
- package/src/href.ts +31 -0
- package/src/index.ts +9 -3
- package/src/plugins/config.ts +1 -1
- package/src/plugins/context.ts +7 -1
- package/src/plugins/daily.ts +27 -0
- package/src/plugins/index.ts +3 -3
- package/src/plugins/order.ts +1 -1
- package/src/plugins/public.ts +8 -5
- package/src/plugins/services.ts +88 -14
- package/src/plugins/types.ts +120 -9
- package/src/reactivity/hmr.ts +90 -0
- package/src/reactivity/index.ts +38 -18
- package/src/reactivity/resource.ts +115 -0
- package/src/reactivity/seed.ts +39 -0
- package/src/reactivity/server-seed.ts +194 -0
- package/src/reactivity/store.ts +55 -1
- package/src/rgpd/draft.ts +171 -0
- package/src/rgpd/forms.ts +85 -0
- package/src/rgpd/index.ts +57 -0
- package/src/server/action-flash.ts +1 -0
- package/src/server/action-registry.ts +6 -8
- package/src/server/action.ts +51 -19
- package/src/server/app-secret.ts +14 -8
- package/src/server/cache-invalidation.ts +96 -0
- package/src/server/compress.ts +3 -1
- package/src/server/consent.ts +16 -2
- package/src/server/cookie-inventory.ts +78 -0
- package/src/server/cookies.ts +50 -0
- package/src/server/csp-report.ts +86 -0
- package/src/server/discard.ts +13 -0
- package/src/server/document.ts +2 -2
- package/src/server/env.ts +1 -1
- package/src/server/errors.ts +9 -2
- package/src/server/field-errors.ts +91 -0
- package/src/server/form-schema.ts +16 -11
- package/src/server/health.ts +33 -12
- package/src/server/http.ts +25 -10
- package/src/server/index.ts +101 -298
- package/src/server/loader.ts +1 -0
- package/src/server/page.ts +3 -9
- package/src/server/plugin-host.ts +26 -8
- package/src/server/public.ts +14 -3
- package/src/server/rate-limit.ts +39 -10
- package/src/server/region.ts +3 -0
- package/src/server/request-handler.ts +370 -0
- package/src/server/request-log.ts +94 -0
- package/src/server/route-cache.ts +41 -6
- package/src/server/route-input.ts +54 -0
- package/src/server/route-table.ts +35 -19
- package/src/server/routing.ts +12 -11
- package/src/server/sanitize-html.ts +1 -1
- package/src/server/security.ts +38 -8
- package/src/server/serve-handlers.ts +9 -5
- package/src/server/shared-store.ts +314 -0
- package/src/server/start.ts +12 -5
- package/src/server/static-dir.ts +14 -10
- package/src/server/stream.ts +2 -1
- package/src/server/surface.ts +39 -0
- package/src/server/webhook.ts +48 -0
- package/src/server/workers.ts +168 -0
- package/src/ssr/consent-banner.ts +20 -16
- package/src/ssr/consent-texts.ts +40 -0
- package/src/ssr/context.ts +26 -3
- package/src/ssr/cookie-table.ts +75 -0
- package/src/ssr/index.ts +23 -13
- package/src/ssr/navigation.ts +161 -14
- package/src/test/browser.ts +50 -22
- package/src/test/build-reuse.ts +70 -0
- package/src/test/index.ts +45 -6
- package/src/test/mount.ts +53 -0
- package/src/test/outside.ts +94 -0
- package/templates/_shared/AGENTS.md +1 -1
- package/templates/_shared/Dockerfile +22 -0
- package/templates/_shared/dockerignore +9 -0
- package/templates/_shared/gitignore +2 -0
- package/templates/app/.env.example +3 -1
- package/templates/app/compose.yaml +32 -0
- package/templates/app/db/migrations/001_notes.sql +7 -0
- package/templates/app/db/schema.ts +11 -0
- package/templates/app/package.json +1 -0
- package/templates/app/prunelle.config.ts +6 -0
- package/templates/app/src/actions/notes.ts +26 -0
- package/templates/app/src/auth.ts +4 -2
- package/templates/app/src/db.ts +5 -0
- package/templates/app/src/routes/dashboard/index.tsx +26 -1
- package/templates/app/src/routes/privacy.tsx +6 -2
- package/templates/app/tests/app.test.ts +14 -3
- package/templates/plugin/AGENTS.md +11 -0
- package/templates/plugin/CLAUDE.md +1 -0
- package/templates/plugin/README.md +27 -0
- package/templates/plugin/gitignore +2 -0
- package/templates/plugin/llms.txt +19 -0
- package/templates/plugin/package.json +33 -0
- package/templates/plugin/src/index.ts +40 -0
- package/templates/plugin/tests/fixture/prunelle.config.ts +4 -0
- package/templates/plugin/tests/fixture/src/routes/index.tsx +11 -0
- package/templates/plugin/tests/plugin.test.ts +42 -0
- package/templates/plugin/tsconfig.json +19 -0
- package/ts-plugin.cjs +3674 -2196
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// What outside clients can call: the app's server actions and API routes, each with the JSON Schema of its input.
|
|
2
|
+
|
|
3
|
+
import type { BuildManifest } from '../build/index'
|
|
4
|
+
import type { AppSurface, SurfaceInput } from '../plugins/types'
|
|
5
|
+
import { isServerAction } from './action'
|
|
6
|
+
import { extractFormSchema } from './form-schema'
|
|
7
|
+
import { isStandardSchema } from './route-input'
|
|
8
|
+
import { HTTP_METHOD_EXPORTS } from './route-table'
|
|
9
|
+
|
|
10
|
+
function inputOf(schema: unknown): SurfaceInput {
|
|
11
|
+
if (!isStandardSchema(schema))
|
|
12
|
+
return { kind: 'none' }
|
|
13
|
+
const extracted = extractFormSchema(schema)
|
|
14
|
+
return extracted.ok ? { kind: 'json', schema: extracted.jsonSchema } : { kind: 'unsupported', vendor: extracted.vendor, reason: extracted.reason }
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** A route is an API route when it answers methods and renders no page. */
|
|
18
|
+
function apiMethods(mod: Record<string, unknown>): string[] {
|
|
19
|
+
if (typeof mod.default === 'function')
|
|
20
|
+
return []
|
|
21
|
+
return [...HTTP_METHOD_EXPORTS].filter(method => typeof mod[method] === 'function')
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function appSurface(manifest: BuildManifest, modules: Record<string, unknown>): AppSurface {
|
|
25
|
+
const actions: AppSurface['actions'][number][] = []
|
|
26
|
+
for (const entry of manifest.actions) {
|
|
27
|
+
const act = (modules[entry.file] as Record<string, unknown> | undefined)?.[entry.exportName]
|
|
28
|
+
if (isServerAction(act))
|
|
29
|
+
actions.push({ name: entry.exportName, url: entry.url, input: inputOf(act.schema), rateLimited: act.rateLimit !== undefined })
|
|
30
|
+
}
|
|
31
|
+
const routes: AppSurface['routes'][number][] = []
|
|
32
|
+
for (const entry of manifest.routes) {
|
|
33
|
+
const mod = modules[entry.file] as Record<string, unknown> | undefined
|
|
34
|
+
const methods = mod === undefined ? [] : apiMethods(mod)
|
|
35
|
+
if (methods.length > 0)
|
|
36
|
+
routes.push({ path: entry.path, methods, input: inputOf(mod!.schema) })
|
|
37
|
+
}
|
|
38
|
+
return { actions, routes }
|
|
39
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// Webhook signatures: a route that turns off the cross-site check (`export const csrf = false`) proves the sender with one of these instead.
|
|
2
|
+
|
|
3
|
+
import { hmac, safeEqual } from './app-secret'
|
|
4
|
+
|
|
5
|
+
/** `standard` is Standard Webhooks (Svix, Resend, Clerk and others), `stripe` Stripe's `Stripe-Signature`, `github` GitHub's `X-Hub-Signature-256`. */
|
|
6
|
+
export type WebhookScheme = 'standard' | 'stripe' | 'github'
|
|
7
|
+
|
|
8
|
+
export interface VerifyWebhookOptions {
|
|
9
|
+
/** How far the signed timestamp may be from now, for the schemes that sign one (5 minutes). GitHub signs none. */
|
|
10
|
+
toleranceSeconds?: number | undefined
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const TOLERANCE_SECONDS = 300
|
|
14
|
+
const STANDARD_PREFIX = 'whsec_'
|
|
15
|
+
|
|
16
|
+
/** The request's body when it carries a valid signature for `scheme` under `secret`, signed within `toleranceSeconds` where the scheme signs a time; undefined otherwise. It reads the body, so the route parses the text this returns. */
|
|
17
|
+
export async function verifyWebhook(request: Request, scheme: WebhookScheme, secret: string | undefined, options: VerifyWebhookOptions = {}): Promise<string | undefined> {
|
|
18
|
+
if (!secret)
|
|
19
|
+
throw new Error(`prunelle: verifyWebhook('${scheme}') got no secret: pass the signing secret the sender shows, read from an environment variable`)
|
|
20
|
+
const body = await request.text()
|
|
21
|
+
const headers = request.headers
|
|
22
|
+
const tolerance = options.toleranceSeconds ?? TOLERANCE_SECONDS
|
|
23
|
+
if (scheme === 'github') {
|
|
24
|
+
const signature = headers.get('x-hub-signature-256') ?? ''
|
|
25
|
+
return safeEqual(signature, `sha256=${hmac(secret, body).toString('hex')}`) ? body : undefined
|
|
26
|
+
}
|
|
27
|
+
if (scheme === 'stripe') {
|
|
28
|
+
const fields = (headers.get('stripe-signature') ?? '').split(',').map(field => field.split('='))
|
|
29
|
+
const timestamp = fields.find(([key]) => key === 't')?.[1]
|
|
30
|
+
if (timestamp === undefined || !fresh(timestamp, tolerance))
|
|
31
|
+
return undefined
|
|
32
|
+
const expected = hmac(secret, `${timestamp}.${body}`).toString('hex')
|
|
33
|
+
return fields.some(([key, value]) => key === 'v1' && value !== undefined && safeEqual(value, expected)) ? body : undefined
|
|
34
|
+
}
|
|
35
|
+
const id = headers.get('webhook-id')
|
|
36
|
+
const timestamp = headers.get('webhook-timestamp')
|
|
37
|
+
if (id === null || timestamp === null || !fresh(timestamp, tolerance))
|
|
38
|
+
return undefined
|
|
39
|
+
const key = Buffer.from(secret.startsWith(STANDARD_PREFIX) ? secret.slice(STANDARD_PREFIX.length) : secret, 'base64')
|
|
40
|
+
const expected = hmac(key, `${id}.${timestamp}.${body}`).toString('base64')
|
|
41
|
+
const signatures = (headers.get('webhook-signature') ?? '').split(' ')
|
|
42
|
+
return signatures.some(entry => entry.startsWith('v1,') && safeEqual(entry.slice(3), expected)) ? body : undefined
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function fresh(timestamp: string, toleranceSeconds: number): boolean {
|
|
46
|
+
const seconds = Number(timestamp)
|
|
47
|
+
return /^\d+$/.test(timestamp) && Math.abs(Date.now() / 1000 - seconds) <= toleranceSeconds
|
|
48
|
+
}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
// `prunelle start --workers <n>`: n processes of `prunelle start` listening on one port with SO_REUSEPORT, the kernel spreading connections across them.
|
|
2
|
+
// The primary serves nothing: it gives the workers one signing secret, passes a stop signal on to them, and starts again one that dies after it listened.
|
|
3
|
+
// Each worker tells the primary it listens over the IPC channel Bun opens between them, and stops when that channel closes, as it does when the primary is killed.
|
|
4
|
+
|
|
5
|
+
import process from 'node:process'
|
|
6
|
+
|
|
7
|
+
/** `<index>/<count>` in a worker's environment; its absence means the process serves alone. */
|
|
8
|
+
export const WORKER_ENV = 'PRUNELLE_WORKER'
|
|
9
|
+
/** The secret every worker signs with when the app sets none, so a form one rendered is accepted by the others. */
|
|
10
|
+
export const WORKERS_SECRET_ENV = 'PRUNELLE_WORKERS_SECRET'
|
|
11
|
+
|
|
12
|
+
/** What a worker sends the primary once it listens. */
|
|
13
|
+
export const READY_MESSAGE = 'prunelle:ready'
|
|
14
|
+
|
|
15
|
+
const SIGNALS = ['SIGTERM', 'SIGINT', 'SIGHUP'] as const
|
|
16
|
+
const RESTART_DELAY_MS = 1000
|
|
17
|
+
const WORKER_RE = /^(\d+)\/(\d+)$/
|
|
18
|
+
|
|
19
|
+
/** This process's place among the workers of a `prunelle start --workers`, or undefined when it serves alone. */
|
|
20
|
+
export function workerOf(env: Record<string, string | undefined> = process.env): { index: number, count: number } | undefined {
|
|
21
|
+
const match = WORKER_RE.exec(env[WORKER_ENV] ?? '')
|
|
22
|
+
return match === null ? undefined : { index: Number(match[1]), count: Number(match[2]) }
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** In a worker: stops it the way SIGTERM does once the primary is gone, whose stop signal would never come, and SO_REUSEPORT would let a new primary's workers share the port with it. */
|
|
26
|
+
export function followPrimary(): void {
|
|
27
|
+
process.once('disconnect', () => process.kill(process.pid, 'SIGTERM'))
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** In a worker: tells the primary it listens, so a later exit is a crash to recover from rather than a failure to start. */
|
|
31
|
+
export function reportListening(): void {
|
|
32
|
+
process.send?.(READY_MESSAGE)
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** The count `--workers` asks for, a whole number from 1 or `auto` for one per CPU core; undefined when it is neither. */
|
|
36
|
+
export function parseWorkers(value: string, cores: number = navigator.hardwareConcurrency): number | undefined {
|
|
37
|
+
if (value === 'auto')
|
|
38
|
+
return Math.max(1, cores)
|
|
39
|
+
const count = Number(value)
|
|
40
|
+
return Number.isInteger(count) && count >= 1 ? count : undefined
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const RATE_LIMIT_CLAUSE = 'each counts rate limits alone, so a client gets its limit once per process'
|
|
44
|
+
|
|
45
|
+
export interface PerProcessInput {
|
|
46
|
+
store: string | undefined
|
|
47
|
+
/** Limiters counting in the process's memory, with or without a `store`: the app's own `createRateLimitStore()` ones and the unnamed ones of plugins. */
|
|
48
|
+
limiters: number
|
|
49
|
+
actionsRateLimited: boolean
|
|
50
|
+
cachedRoutes: boolean
|
|
51
|
+
plugins: readonly { perProcess?: string | undefined }[]
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** What each process keeps alone when several serve the app with no `store`, one clause each. */
|
|
55
|
+
export function perProcessState(input: PerProcessInput): string[] {
|
|
56
|
+
// A `store` shares the named limiters; the ones counting in memory stay per process.
|
|
57
|
+
if (input.store !== undefined)
|
|
58
|
+
return input.limiters > 0 ? [RATE_LIMIT_CLAUSE] : []
|
|
59
|
+
const clauses: string[] = []
|
|
60
|
+
if (input.limiters > 0 || input.actionsRateLimited)
|
|
61
|
+
clauses.push(RATE_LIMIT_CLAUSE)
|
|
62
|
+
if (input.cachedRoutes)
|
|
63
|
+
clauses.push('invalidateCache() drops a cached page in the process that ran it only')
|
|
64
|
+
for (const plugin of input.plugins) {
|
|
65
|
+
if (plugin.perProcess !== undefined)
|
|
66
|
+
clauses.push(plugin.perProcess)
|
|
67
|
+
}
|
|
68
|
+
return clauses
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export interface SuperviseOptions {
|
|
72
|
+
count: number
|
|
73
|
+
/** What each worker runs: this `prunelle start` again, which reads its place from `PRUNELLE_WORKER` and sends `READY_MESSAGE` once it listens. The others start once the first has. */
|
|
74
|
+
command: string[]
|
|
75
|
+
env?: Record<string, string | undefined> | undefined
|
|
76
|
+
log?: ((message: string) => void) | undefined
|
|
77
|
+
/** @internal How long a worker that died waits before it starts again (1 s). */
|
|
78
|
+
restartDelayMs?: number | undefined
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export interface Supervisor {
|
|
82
|
+
/** Passes `signal` on to every worker and starts none again. */
|
|
83
|
+
stop: (signal?: typeof SIGNALS[number]) => void
|
|
84
|
+
/** The highest exit code of the workers, once the last has exited after a stop. */
|
|
85
|
+
exited: Promise<number>
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Starts the first worker, the others once it listens, starts again one that dies after it listened, and stops them all on SIGTERM, SIGINT or SIGHUP, or when one exits before it listens. */
|
|
89
|
+
export function superviseWorkers(options: SuperviseOptions): Supervisor {
|
|
90
|
+
const env = options.env ?? process.env
|
|
91
|
+
// A worker starting workers would start more on each restart, until the machine runs out of memory.
|
|
92
|
+
if (workerOf(env) !== undefined)
|
|
93
|
+
throw new Error(`prunelle: a worker of prunelle start --workers cannot start workers of its own: unset ${WORKER_ENV} in the environment that runs prunelle start`)
|
|
94
|
+
const log = options.log ?? ((message: string) => console.error(message))
|
|
95
|
+
const secret = env.PRUNELLE_FORM_SECRET || env.AUTH_SECRET ? undefined : Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString('hex')
|
|
96
|
+
const workers = new Map<number, Bun.Subprocess>()
|
|
97
|
+
const timers = new Set<ReturnType<typeof setTimeout>>()
|
|
98
|
+
let stopping = false
|
|
99
|
+
let exitCode = 0
|
|
100
|
+
let resolveExited!: (code: number) => void
|
|
101
|
+
const exited = new Promise<number>(resolve => resolveExited = resolve)
|
|
102
|
+
|
|
103
|
+
const settle = (): void => {
|
|
104
|
+
if (stopping && workers.size === 0 && timers.size === 0) {
|
|
105
|
+
for (const [signal, listener] of listeners)
|
|
106
|
+
process.off(signal, listener)
|
|
107
|
+
resolveExited(exitCode)
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const stop = (signal: typeof SIGNALS[number] = 'SIGTERM'): void => {
|
|
112
|
+
stopping = true
|
|
113
|
+
for (const timer of timers)
|
|
114
|
+
clearTimeout(timer)
|
|
115
|
+
timers.clear()
|
|
116
|
+
for (const worker of workers.values())
|
|
117
|
+
worker.kill(signal)
|
|
118
|
+
settle()
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// The others wait for the first to listen: a config that fails to load is then reported by one worker, not by each.
|
|
122
|
+
let othersStarted = false
|
|
123
|
+
const start = (index: number): void => {
|
|
124
|
+
let listening = false
|
|
125
|
+
const worker = Bun.spawn(options.command, {
|
|
126
|
+
env: { ...env, [WORKER_ENV]: `${index}/${options.count}`, ...(secret === undefined ? {} : { [WORKERS_SECRET_ENV]: secret }) },
|
|
127
|
+
stdio: ['ignore', 'inherit', 'inherit'],
|
|
128
|
+
ipc: (message) => {
|
|
129
|
+
if (message !== READY_MESSAGE)
|
|
130
|
+
return
|
|
131
|
+
listening = true
|
|
132
|
+
if (othersStarted)
|
|
133
|
+
return
|
|
134
|
+
othersStarted = true
|
|
135
|
+
for (let other = 2; other <= options.count && !stopping; other++)
|
|
136
|
+
start(other)
|
|
137
|
+
},
|
|
138
|
+
})
|
|
139
|
+
workers.set(index, worker)
|
|
140
|
+
void worker.exited.then((code) => {
|
|
141
|
+
workers.delete(index)
|
|
142
|
+
if (stopping) {
|
|
143
|
+
exitCode = Math.max(exitCode, code)
|
|
144
|
+
return settle()
|
|
145
|
+
}
|
|
146
|
+
// Starting it again would fail the same way. Exit code 0 is a stop signal that reached the worker before the primary, as Ctrl-C does.
|
|
147
|
+
if (!listening) {
|
|
148
|
+
log(code === 0
|
|
149
|
+
? `prunelle start: worker ${index} stopped before it listened, so every worker is stopped`
|
|
150
|
+
: `prunelle start: worker ${index} exited with code ${code} before it listened, so every worker is stopped: its error is above`)
|
|
151
|
+
exitCode = code
|
|
152
|
+
return stop()
|
|
153
|
+
}
|
|
154
|
+
log(`prunelle start: worker ${index} exited with code ${code}; starting it again`)
|
|
155
|
+
const timer = setTimeout(() => {
|
|
156
|
+
timers.delete(timer)
|
|
157
|
+
start(index)
|
|
158
|
+
}, options.restartDelayMs ?? RESTART_DELAY_MS)
|
|
159
|
+
timers.add(timer)
|
|
160
|
+
})
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const listeners = SIGNALS.map(signal => [signal, () => stop(signal)] as const)
|
|
164
|
+
for (const [signal, listener] of listeners)
|
|
165
|
+
process.on(signal, listener)
|
|
166
|
+
start(1)
|
|
167
|
+
return { stop, exited }
|
|
168
|
+
}
|
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
import type { ConsentBannerProps, ConsentTexts } from '../context'
|
|
4
4
|
import type { RequestConsent } from '../server/consent'
|
|
5
|
+
import type { ConsentDefaults } from './consent-texts'
|
|
6
|
+
import { consentDefaults } from './consent-texts'
|
|
5
7
|
import { esc, escAttr, ssrChild } from './index'
|
|
6
8
|
|
|
7
9
|
function requireCategories(consent: RequestConsent, tag: string): void {
|
|
@@ -9,52 +11,54 @@ function requireCategories(consent: RequestConsent, tag: string): void {
|
|
|
9
11
|
throw new Error(`prunelle: <${tag}> has no consent category to ask about: declare them in prunelle.config.ts, such as consent: { categories: { analytics: 'Audience measurement' } }.`)
|
|
10
12
|
}
|
|
11
13
|
|
|
12
|
-
function checkboxes(consent: RequestConsent, legend: string
|
|
14
|
+
function checkboxes(consent: RequestConsent, legend: string): string {
|
|
13
15
|
const boxes = consent.categories.map((category) => {
|
|
14
16
|
const checked = consent.has(category) ? ' checked' : ''
|
|
15
17
|
return `<label data-part="choice"><input type="checkbox" name="categories" value="${escAttr(category)}"${checked}> ${esc(consent.labels[category] ?? category)}</label>`
|
|
16
18
|
})
|
|
17
|
-
return `<fieldset data-part="choices"><legend>${esc(legend
|
|
19
|
+
return `<fieldset data-part="choices"><legend>${esc(legend)}</legend>${boxes.join('')}</fieldset>`
|
|
18
20
|
}
|
|
19
21
|
|
|
20
22
|
// Refuse comes first and looks the same as Accept: the CNIL asks for a refusal as easy as a consent.
|
|
21
|
-
function decisionButtons(texts: ConsentTexts): string {
|
|
22
|
-
return `<button type="submit" name="action" value="reject-all" data-ui="button">${esc(texts.refuse ??
|
|
23
|
-
+ `<button type="submit" name="action" value="accept-all" data-ui="button">${esc(texts.accept ??
|
|
23
|
+
function decisionButtons(texts: ConsentTexts, defaults: ConsentDefaults): string {
|
|
24
|
+
return `<button type="submit" name="action" value="reject-all" data-ui="button">${esc(texts.refuse ?? defaults.refuse)}</button>`
|
|
25
|
+
+ `<button type="submit" name="action" value="accept-all" data-ui="button">${esc(texts.accept ?? defaults.accept)}</button>`
|
|
24
26
|
}
|
|
25
27
|
|
|
26
|
-
function saveButton(texts: ConsentTexts): string {
|
|
27
|
-
return `<button type="submit" name="action" value="save" data-ui="button">${esc(texts.save ??
|
|
28
|
+
function saveButton(texts: ConsentTexts, defaults: ConsentDefaults): string {
|
|
29
|
+
return `<button type="submit" name="action" value="save" data-ui="button">${esc(texts.save ?? defaults.save)}</button>`
|
|
28
30
|
}
|
|
29
31
|
|
|
30
|
-
export function renderConsentBanner(consent: RequestConsent | undefined, props: ConsentBannerProps): string {
|
|
32
|
+
export function renderConsentBanner(consent: RequestConsent | undefined, props: ConsentBannerProps, lang?: string): string {
|
|
31
33
|
if (consent === undefined)
|
|
32
34
|
return ''
|
|
33
35
|
requireCategories(consent, 'ConsentBanner')
|
|
34
36
|
if (consent.decided)
|
|
35
37
|
return ''
|
|
38
|
+
const defaults = consentDefaults(lang ?? consent.lang)
|
|
36
39
|
const labels = consent.categories.map(category => consent.labels[category] ?? category).join(', ')
|
|
37
40
|
const body = props.children !== undefined
|
|
38
41
|
? ssrChild(props.children)
|
|
39
|
-
: `<p
|
|
42
|
+
: `<p>${defaults.body(esc(labels))}</p>`
|
|
40
43
|
const policy = props.policyHref !== undefined
|
|
41
|
-
? `<p><a href="${escAttr(props.policyHref)}">${esc(props.policyLabel ??
|
|
44
|
+
? `<p><a href="${escAttr(props.policyHref)}">${esc(props.policyLabel ?? defaults.policy)}</a></p>`
|
|
42
45
|
: ''
|
|
43
46
|
return `<section data-ui="consent" aria-labelledby="pru-consent-title">`
|
|
44
|
-
+ `<h2 id="pru-consent-title" data-part="title">${esc(props.title ??
|
|
47
|
+
+ `<h2 id="pru-consent-title" data-part="title">${esc(props.title ?? defaults.title)}</h2>`
|
|
45
48
|
+ `<div data-part="body">${body}${policy}</div>`
|
|
46
49
|
+ `<form method="post" action="${escAttr(consent.endpoint)}" data-part="form">`
|
|
47
|
-
+ `<div data-part="actions">${decisionButtons(props)}</div>`
|
|
48
|
-
+ `<details data-part="details"><summary>${esc(props.choose ??
|
|
50
|
+
+ `<div data-part="actions">${decisionButtons(props, defaults)}</div>`
|
|
51
|
+
+ `<details data-part="details"><summary>${esc(props.choose ?? defaults.choose)}</summary>${checkboxes(consent, props.legend ?? defaults.legend)}${saveButton(props, defaults)}</details>`
|
|
49
52
|
+ `</form></section>`
|
|
50
53
|
}
|
|
51
54
|
|
|
52
|
-
export function renderConsentPreferences(consent: RequestConsent | undefined, texts: ConsentTexts): string {
|
|
55
|
+
export function renderConsentPreferences(consent: RequestConsent | undefined, texts: ConsentTexts, lang?: string): string {
|
|
53
56
|
if (consent === undefined)
|
|
54
57
|
return ''
|
|
55
58
|
requireCategories(consent, 'ConsentPreferences')
|
|
59
|
+
const defaults = consentDefaults(lang ?? consent.lang)
|
|
56
60
|
return `<form method="post" action="${escAttr(consent.endpoint)}" data-ui="consent" data-part="preferences">`
|
|
57
|
-
+ `${checkboxes(consent, texts.legend)}`
|
|
58
|
-
+ `<div data-part="actions">${saveButton(texts)}${decisionButtons(texts)}</div>`
|
|
61
|
+
+ `${checkboxes(consent, texts.legend ?? defaults.legend)}`
|
|
62
|
+
+ `<div data-part="actions">${saveButton(texts, defaults)}${decisionButtons(texts, defaults)}</div>`
|
|
59
63
|
+ `</form>`
|
|
60
64
|
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// The default texts of <ConsentBanner> and <ConsentPreferences>, in the language of the app's `lang`.
|
|
2
|
+
|
|
3
|
+
export interface ConsentDefaults {
|
|
4
|
+
title: string
|
|
5
|
+
/** The sentence of the banner, given the labels of the categories it asks about. */
|
|
6
|
+
body: (labels: string) => string
|
|
7
|
+
policy: string
|
|
8
|
+
accept: string
|
|
9
|
+
refuse: string
|
|
10
|
+
save: string
|
|
11
|
+
choose: string
|
|
12
|
+
legend: string
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const ENGLISH: ConsentDefaults = {
|
|
16
|
+
title: 'Cookies',
|
|
17
|
+
body: labels => `This site would like to set cookies for: ${labels}. You can accept or refuse them, and change your mind at any time.`,
|
|
18
|
+
policy: 'Cookie policy',
|
|
19
|
+
accept: 'Accept all',
|
|
20
|
+
refuse: 'Refuse all',
|
|
21
|
+
save: 'Save my choices',
|
|
22
|
+
choose: 'Choose',
|
|
23
|
+
legend: 'Cookies by purpose',
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const FRENCH: ConsentDefaults = {
|
|
27
|
+
title: 'Cookies',
|
|
28
|
+
body: labels => `Ce site souhaite déposer des cookies pour : ${labels}. Vous pouvez les accepter ou les refuser, et changer d'avis à tout moment.`,
|
|
29
|
+
policy: 'Politique de cookies',
|
|
30
|
+
accept: 'Tout accepter',
|
|
31
|
+
refuse: 'Tout refuser',
|
|
32
|
+
save: 'Enregistrer mes choix',
|
|
33
|
+
choose: 'Choisir',
|
|
34
|
+
legend: 'Cookies par finalité',
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** French for `fr`, `fr-CA` and the like, English for any other language. */
|
|
38
|
+
export function consentDefaults(lang: string): ConsentDefaults {
|
|
39
|
+
return lang.split('-', 1)[0]!.toLowerCase() === 'fr' ? FRENCH : ENGLISH
|
|
40
|
+
}
|
package/src/ssr/context.ts
CHANGED
|
@@ -1,13 +1,18 @@
|
|
|
1
1
|
// Per-request SSR context for <Head> metadata, streaming <Suspense>, rendered island tracking,
|
|
2
2
|
// universal createContext/useContext, and deterministic hydration-safe useId().
|
|
3
3
|
|
|
4
|
-
import type { CatchProps, ConsentBannerProps, ConsentGateProps, ConsentTexts } from '../context'
|
|
4
|
+
import type { CatchProps, ConsentBannerProps, ConsentGateProps, ConsentTexts, CookieTableProps } from '../context'
|
|
5
5
|
import type { Html, PrunelleChild } from '../jsx-runtime'
|
|
6
|
+
import type { RequestSeeds } from '../reactivity/index'
|
|
6
7
|
import type { RequestConsent } from '../server/consent'
|
|
7
8
|
import type { FieldConstraint } from '../server/form-schema'
|
|
8
9
|
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
9
10
|
import { registerServerContextBridge } from '../context'
|
|
11
|
+
import { getAppContext } from '../plugins/context'
|
|
12
|
+
import { COOKIE_INVENTORY } from '../server/cookie-inventory'
|
|
13
|
+
import { currentRequest } from '../server/request-scope'
|
|
10
14
|
import { renderConsentBanner, renderConsentPreferences } from './consent-banner'
|
|
15
|
+
import { renderCookieTable } from './cookie-table'
|
|
11
16
|
import { raw, ssrChild } from './index'
|
|
12
17
|
import { Region } from './region'
|
|
13
18
|
|
|
@@ -40,6 +45,8 @@ export interface RenderContext {
|
|
|
40
45
|
outerContexts: Map<symbol, unknown> | undefined
|
|
41
46
|
/** The island rendering, as its tag. */
|
|
42
47
|
island: string | undefined
|
|
48
|
+
/** What the request's islands wrote to module state, which each island's server render starts from. */
|
|
49
|
+
seeds: RequestSeeds | undefined
|
|
43
50
|
/** Maps island chunk URL -> eager (true if hydrate is undefined/'load'). */
|
|
44
51
|
renderedIslands: Map<string, boolean>
|
|
45
52
|
hasIslands: boolean
|
|
@@ -182,6 +189,9 @@ registerServerContextBridge({
|
|
|
182
189
|
return undefined
|
|
183
190
|
return `${ctx.idPrefix}${ctx.idSeq++}`
|
|
184
191
|
},
|
|
192
|
+
requestLocale() {
|
|
193
|
+
return requestLocale()
|
|
194
|
+
},
|
|
185
195
|
region(props) {
|
|
186
196
|
return Region(props)
|
|
187
197
|
},
|
|
@@ -194,6 +204,9 @@ registerServerContextBridge({
|
|
|
194
204
|
consentPreferences(props) {
|
|
195
205
|
return ConsentPreferences(props)
|
|
196
206
|
},
|
|
207
|
+
cookieTable(props) {
|
|
208
|
+
return CookieTable(props)
|
|
209
|
+
},
|
|
197
210
|
head(props) {
|
|
198
211
|
return Head(props)
|
|
199
212
|
},
|
|
@@ -224,6 +237,7 @@ export function createRenderContext(
|
|
|
224
237
|
contexts: new Map(),
|
|
225
238
|
outerContexts: undefined,
|
|
226
239
|
island: undefined,
|
|
240
|
+
seeds: undefined,
|
|
227
241
|
renderedIslands: new Map(),
|
|
228
242
|
hasIslands: false,
|
|
229
243
|
revives: false,
|
|
@@ -360,12 +374,21 @@ export function ConsentGate(props: ConsentGateProps): Html {
|
|
|
360
374
|
return raw(ssrChild(granted ? props.children : props.fallback))
|
|
361
375
|
}
|
|
362
376
|
|
|
377
|
+
function requestLocale(): string | undefined {
|
|
378
|
+
const locale = (currentRequest()?.ctx.locals as { locale?: unknown } | undefined)?.locale
|
|
379
|
+
return typeof locale === 'string' && locale !== '' ? locale : undefined
|
|
380
|
+
}
|
|
381
|
+
|
|
363
382
|
export function ConsentBanner(props: ConsentBannerProps): Html {
|
|
364
|
-
return raw(renderConsentBanner(renderStorage.getStore()?.consent, props))
|
|
383
|
+
return raw(renderConsentBanner(renderStorage.getStore()?.consent, props, requestLocale()))
|
|
365
384
|
}
|
|
366
385
|
|
|
367
386
|
export function ConsentPreferences(props: ConsentTexts): Html {
|
|
368
|
-
return raw(renderConsentPreferences(renderStorage.getStore()?.consent, props))
|
|
387
|
+
return raw(renderConsentPreferences(renderStorage.getStore()?.consent, props, requestLocale()))
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
export function CookieTable(props: CookieTableProps): Html {
|
|
391
|
+
return raw(renderCookieTable(getAppContext()?.inject(COOKIE_INVENTORY), props, requestLocale()))
|
|
369
392
|
}
|
|
370
393
|
|
|
371
394
|
const STACK_FRAME_RE = /^\s*at\s+(?:async\s+)?([A-Za-z_$][\w$]*)\s+\(/
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// The markup of <CookieTable>: one row per cookie the site sets, in the app's language, with no script.
|
|
2
|
+
|
|
3
|
+
import type { CookieTableProps } from '../context'
|
|
4
|
+
import type { CookieInventory, CookieRow } from '../server/cookie-inventory'
|
|
5
|
+
import { esc } from './index'
|
|
6
|
+
|
|
7
|
+
interface CookieTableTexts {
|
|
8
|
+
caption: string
|
|
9
|
+
name: string
|
|
10
|
+
purpose: string
|
|
11
|
+
category: string
|
|
12
|
+
lifetime: string
|
|
13
|
+
essential: string
|
|
14
|
+
session: string
|
|
15
|
+
/** A field the source does not give, such as `[to fill in: purpose]`. */
|
|
16
|
+
missing: (field: string) => string
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const ENGLISH: CookieTableTexts = {
|
|
20
|
+
caption: 'Cookies this site sets',
|
|
21
|
+
name: 'Name',
|
|
22
|
+
purpose: 'Purpose',
|
|
23
|
+
category: 'Category',
|
|
24
|
+
lifetime: 'Lifetime',
|
|
25
|
+
essential: 'Essential',
|
|
26
|
+
session: 'Browser session',
|
|
27
|
+
missing: field => `[to fill in: ${field}]`,
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const FRENCH: CookieTableTexts = {
|
|
31
|
+
caption: 'Cookies déposés par ce site',
|
|
32
|
+
name: 'Nom',
|
|
33
|
+
purpose: 'Finalité',
|
|
34
|
+
category: 'Catégorie',
|
|
35
|
+
lifetime: 'Durée de conservation',
|
|
36
|
+
essential: 'Nécessaire',
|
|
37
|
+
session: 'Session du navigateur',
|
|
38
|
+
missing: field => `[à compléter : ${field}]`,
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const FRENCH_FIELDS: Readonly<Record<string, string>> = { name: 'nom', purpose: 'finalité', category: 'catégorie', lifetime: 'durée' }
|
|
42
|
+
|
|
43
|
+
// The largest unit the lifetime is a whole number of, a month counted as 30 days and a year as 365; 30 days stays 30 days rather than 1 month.
|
|
44
|
+
const UNITS = [['year', 31_536_000, 1], ['month', 2_592_000, 2], ['day', 86_400, 1], ['hour', 3600, 1], ['minute', 60, 1]] as const
|
|
45
|
+
|
|
46
|
+
function formatLifetime(seconds: number, lang: string): string {
|
|
47
|
+
const [unit, size] = UNITS.find(([, size, least]) => seconds >= size * least && seconds % size === 0) ?? ['second', 1]
|
|
48
|
+
return new Intl.NumberFormat(lang, { style: 'unit', unit, unitDisplay: 'long' }).format(seconds / size)
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function purposeIn(purpose: CookieRow['purpose'], lang: string): string | undefined {
|
|
52
|
+
if (purpose === undefined || typeof purpose === 'string')
|
|
53
|
+
return purpose
|
|
54
|
+
return purpose[lang] ?? purpose[lang.split('-', 1)[0]!] ?? purpose.en ?? Object.values(purpose)[0]
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function renderCookieTable(inventory: CookieInventory | undefined, props: CookieTableProps, lang?: string): string {
|
|
58
|
+
if (inventory === undefined)
|
|
59
|
+
return ''
|
|
60
|
+
const activeLang = lang ?? inventory.lang
|
|
61
|
+
const french = activeLang.split('-', 1)[0]!.toLowerCase() === 'fr'
|
|
62
|
+
const texts = french ? FRENCH : ENGLISH
|
|
63
|
+
const missing = (field: string): string => esc(texts.missing(french ? FRENCH_FIELDS[field]! : field))
|
|
64
|
+
const rows = inventory.rows.map((row) => {
|
|
65
|
+
const purpose = purposeIn(row.purpose, activeLang)
|
|
66
|
+
const category = row.category === 'essential' ? texts.essential : row.category === undefined ? undefined : inventory.labels[row.category] ?? row.category
|
|
67
|
+
const lifetime = row.lifetime === 'session' ? texts.session : row.lifetime === undefined ? undefined : formatLifetime(row.lifetime, activeLang)
|
|
68
|
+
return `<tr><td>${row.name === undefined ? missing('name') : `<code>${esc(row.name)}</code>`}</td>`
|
|
69
|
+
+ `<td>${purpose === undefined ? missing('purpose') : esc(purpose)}</td>`
|
|
70
|
+
+ `<td>${category === undefined ? missing('category') : esc(category)}</td>`
|
|
71
|
+
+ `<td>${lifetime === undefined ? missing('lifetime') : esc(lifetime)}</td></tr>`
|
|
72
|
+
})
|
|
73
|
+
const head = [texts.name, texts.purpose, texts.category, texts.lifetime].map(label => `<th scope="col">${esc(label)}</th>`).join('')
|
|
74
|
+
return `<table data-ui="table"><caption>${esc(props.caption ?? texts.caption)}</caption><thead><tr>${head}</tr></thead><tbody>${rows.join('')}</tbody></table>`
|
|
75
|
+
}
|
package/src/ssr/index.ts
CHANGED
|
@@ -10,7 +10,7 @@ import { extractFormSchema, lookupFieldConstraint } from '../server/form-schema'
|
|
|
10
10
|
import { styleText } from '../style'
|
|
11
11
|
import { assertRenderable } from '../unrenderable'
|
|
12
12
|
import { currentFormFields, currentRenderContext, lookupFormAction, PRUNELLE_STREAM_SCRIPT, renderIsland, runWithFormFields } from './context'
|
|
13
|
-
import {
|
|
13
|
+
import { withKeepScroll } from './navigation'
|
|
14
14
|
export { ssrStyleBlock } from './context'
|
|
15
15
|
|
|
16
16
|
export const PRUNELLE_ISLAND_STYLE = 'pru-island,pru-slot{display:contents}'
|
|
@@ -300,10 +300,11 @@ export function ssrLoop<T>(items: Iterable<T> | null | undefined | false, render
|
|
|
300
300
|
if (!items)
|
|
301
301
|
return ''
|
|
302
302
|
const list: readonly T[] = Array.isArray(items) ? items : [...items]
|
|
303
|
-
|
|
303
|
+
// Joined once, like the loops the compiler writes inline: `+=` would leave a rope node per row for the garbage collector.
|
|
304
|
+
const out: string[] = []
|
|
304
305
|
for (let i = 0; i < list.length; i++)
|
|
305
|
-
out
|
|
306
|
-
return out
|
|
306
|
+
out.push(render(list[i] as T, i, list))
|
|
307
|
+
return out.join('')
|
|
307
308
|
}
|
|
308
309
|
|
|
309
310
|
export function ssrChild(value: PrunelleChild): string {
|
|
@@ -395,7 +396,7 @@ export function ssrInIsland(render: () => string, chunk?: string, hydrate?: Hydr
|
|
|
395
396
|
recordRenderedIsland(chunk, hydrate)
|
|
396
397
|
ctx.islandDepth++
|
|
397
398
|
try {
|
|
398
|
-
return renderOnServer(ctx.islandDepth === 1 ? () => renderIsland(ctx, name, render) : render)
|
|
399
|
+
return renderOnServer(ctx.islandDepth === 1 ? () => renderIsland(ctx, name, render) : render, ctx.seeds ??= { ops: [], out: undefined })
|
|
399
400
|
}
|
|
400
401
|
finally {
|
|
401
402
|
ctx.islandDepth--
|
|
@@ -475,6 +476,9 @@ function renderIslandBody(
|
|
|
475
476
|
inner = ssrInIsland(render, undefined, undefined, name)
|
|
476
477
|
if (ctx.idSeq > 0)
|
|
477
478
|
idAttr = ` i="${islandPrefix}"`
|
|
479
|
+
// The module state this island wrote, for the browser to start from as the server rendered it.
|
|
480
|
+
if (ctx.seeds?.out !== undefined)
|
|
481
|
+
idAttr += ` s="${escAttr(JSON.stringify(ctx.seeds.out))}"`
|
|
478
482
|
}
|
|
479
483
|
finally {
|
|
480
484
|
ctx.idPrefix = prevPrefix
|
|
@@ -556,8 +560,10 @@ export interface DocumentOptions {
|
|
|
556
560
|
htmlAttrs?: Record<string, string> | undefined
|
|
557
561
|
runtimeScript?: string | undefined
|
|
558
562
|
alwaysLoadRuntime?: boolean | undefined
|
|
559
|
-
/** Set on a route that renders a `<Region>`: the
|
|
563
|
+
/** Set on a route that renders a `<Region>`: the core region client bundle. */
|
|
560
564
|
regionScript?: string | undefined
|
|
565
|
+
/** The manifest's `buildId`, stamped on the region script so a swap can tell an answer from another build. */
|
|
566
|
+
buildId?: string | undefined
|
|
561
567
|
preloadChunks?: Iterable<string> | undefined
|
|
562
568
|
/** Script URL to the chunks it imports statically, preloaded with it: the browser then fetches them all at once. */
|
|
563
569
|
chunkImports?: Readonly<Record<string, readonly string[]>> | undefined
|
|
@@ -576,7 +582,7 @@ const TAB_ICON_RE = /<link\b[^>]*\brel=["']?(?:[^"'>]*\s)?icon(?=[\s"'>])/i
|
|
|
576
582
|
const EMPTY_ICON = '<link rel="icon" href="data:,">'
|
|
577
583
|
|
|
578
584
|
export function renderDocument(options: DocumentOptions): string {
|
|
579
|
-
const { body, head = '', headTags, lang = 'en', htmlAttrs, runtimeScript, alwaysLoadRuntime, regionScript, preloadChunks, chunkImports, styles, hasIslands, hasSuspense, hasFavicon, navigation } = options
|
|
585
|
+
const { body, head = '', headTags, lang = 'en', htmlAttrs, runtimeScript, alwaysLoadRuntime, regionScript, buildId, preloadChunks, chunkImports, styles, hasIslands, hasSuspense, hasFavicon, navigation } = options
|
|
580
586
|
let headExtra = head
|
|
581
587
|
|
|
582
588
|
if (headTags !== undefined) {
|
|
@@ -603,8 +609,10 @@ export function renderDocument(options: DocumentOptions): string {
|
|
|
603
609
|
for (const dep of chunkImports?.[script] ?? [])
|
|
604
610
|
preloads.add(dep)
|
|
605
611
|
}
|
|
606
|
-
|
|
612
|
+
const hasCombinedIslandStyle = headExtra.includes('pru-island,pru-slot,pru-s{display:contents}')
|
|
613
|
+
if (!hasCombinedIslandStyle && (hasIslands || (regionScript !== undefined && runtimeScript !== undefined)))
|
|
607
614
|
headExtra += `<style>${PRUNELLE_ISLAND_STYLE}</style>`
|
|
615
|
+
if (hasIslands) {
|
|
608
616
|
for (const chunk of preloadChunks ?? [])
|
|
609
617
|
preload(chunk, true)
|
|
610
618
|
}
|
|
@@ -614,12 +622,15 @@ export function renderDocument(options: DocumentOptions): string {
|
|
|
614
622
|
headExtra += `<link rel="modulepreload" href="${escAttr(href)}">`
|
|
615
623
|
|
|
616
624
|
if (hasSuspense)
|
|
617
|
-
headExtra += `<style>${PRUNELLE_SUSPENSE_STYLE}</style
|
|
625
|
+
headExtra += `${hasCombinedIslandStyle ? '' : `<style>${PRUNELLE_SUSPENSE_STYLE}</style>`}<script>${PRUNELLE_STREAM_SCRIPT}</script>`
|
|
618
626
|
|
|
619
627
|
if (loadsRuntime)
|
|
620
628
|
headExtra += `<script type="module" src="${escAttr(runtimeScript)}"></script>`
|
|
621
|
-
if (regionScript !== undefined)
|
|
622
|
-
|
|
629
|
+
if (regionScript !== undefined) {
|
|
630
|
+
const buildAttr = buildId === undefined ? '' : ` data-pru-build="${escAttr(buildId)}"`
|
|
631
|
+
const runtimeAttr = !loadsRuntime && runtimeScript !== undefined ? ` data-pru-runtime="${escAttr(runtimeScript)}"` : ''
|
|
632
|
+
headExtra += `<script type="module" src="${escAttr(regionScript)}"${buildAttr}${runtimeAttr}></script>`
|
|
633
|
+
}
|
|
623
634
|
|
|
624
635
|
let attrStr = ''
|
|
625
636
|
const effectiveLang = htmlAttrs?.lang ?? lang
|
|
@@ -631,6 +642,5 @@ export function renderDocument(options: DocumentOptions): string {
|
|
|
631
642
|
}
|
|
632
643
|
}
|
|
633
644
|
|
|
634
|
-
|
|
635
|
-
return `<!DOCTYPE html><html${attrStr}><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">${headExtra}</head><body>${body}${scrollTag}</body></html>`
|
|
645
|
+
return withKeepScroll(`<!DOCTYPE html><html${attrStr}><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">${headExtra}</head><body>`, body, '</body></html>', hasSuspense)
|
|
636
646
|
}
|