prunelle 0.1.1 → 0.7.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/LICENSE +21 -0
- package/llms.txt +137 -40
- package/package.json +11 -2
- package/src/a11y/declaration.ts +369 -0
- package/src/a11y/index.ts +466 -0
- package/src/a11y/rgaa-map.ts +230 -0
- package/src/attrs.ts +11 -3
- package/src/build/bundle.ts +88 -40
- package/src/build/byte-size.ts +11 -0
- package/src/build/client-entries.ts +3 -2
- package/src/build/client-plugin.ts +11 -5
- package/src/build/client-prune.ts +56 -6
- package/src/build/compile.ts +13 -10
- package/src/build/ecoindex.ts +230 -0
- package/src/build/files.ts +6 -0
- package/src/build/first-load.ts +83 -11
- package/src/build/graph.ts +29 -39
- package/src/build/index.ts +218 -113
- package/src/build/island-promote.ts +229 -0
- package/src/build/islands.ts +11 -203
- package/src/build/manifest.ts +56 -116
- package/src/build/output.ts +2 -2
- package/src/build/plugin-host.ts +113 -41
- package/src/build/precompress.ts +16 -3
- package/src/build/prerender.ts +173 -38
- package/src/build/reach.ts +136 -0
- package/src/build/render-rules.ts +2 -2
- package/src/build/report.ts +42 -5
- package/src/build/resolve.ts +8 -6
- package/src/build/routes.ts +175 -10
- package/src/build/static-headers.ts +93 -0
- package/src/build/static.ts +139 -39
- package/src/build/status-pages.ts +127 -0
- package/src/build/style-bundles.ts +526 -0
- package/src/cli/check-forms.ts +610 -0
- package/src/cli/check-imports.ts +25 -0
- package/src/cli/check-links.ts +632 -0
- package/src/cli/check-security.ts +64 -0
- package/src/cli/check.ts +107 -26
- package/src/cli/commands.ts +120 -11
- package/src/cli/docs.ts +403 -0
- package/src/cli/inspect.ts +105 -15
- package/src/cli/mcp-tools.ts +492 -0
- package/src/cli/mcp.ts +205 -0
- package/src/cli/new.ts +16 -5
- package/src/cli/render.ts +416 -0
- package/src/cli/upgrade-names.ts +73 -13
- package/src/cli/upgrade.ts +156 -18
- package/src/compiler/analyze.ts +68 -14
- package/src/compiler/browser-globals.ts +140 -17
- package/src/compiler/cacheability.ts +636 -0
- package/src/compiler/compliance-eco.ts +71 -0
- package/src/compiler/compliance-rgaa.ts +614 -0
- package/src/compiler/compliance-urls.ts +145 -0
- package/src/compiler/compliance.ts +355 -351
- package/src/compiler/data-keys.ts +199 -192
- package/src/compiler/dev-source.ts +87 -0
- package/src/compiler/dom-attrs.ts +138 -65
- package/src/compiler/dom.ts +517 -442
- package/src/compiler/expr-context.ts +167 -57
- package/src/compiler/foreign-imports.ts +88 -0
- package/src/compiler/mistakes.ts +23 -2
- package/src/compiler/props-body.ts +52 -0
- package/src/compiler/props.ts +87 -36
- package/src/compiler/scope.ts +400 -333
- package/src/compiler/server-only.ts +190 -151
- package/src/compiler/shared.ts +42 -14
- package/src/compiler/signal-reads.ts +6 -2
- package/src/compiler/ssr-prunelle-tags.ts +27 -14
- package/src/compiler/ssr.ts +220 -89
- package/src/context.ts +34 -0
- package/src/dev/error-log.ts +177 -0
- package/src/dev/host-check.ts +26 -0
- package/src/dev/index.ts +91 -34
- package/src/dev/open-editor.ts +208 -0
- package/src/dev/protocol.ts +3 -0
- package/src/dev/reload.ts +5 -3
- package/src/dev/supervisor.ts +50 -25
- package/src/dev/watchers.ts +74 -13
- package/src/dom/action.ts +47 -21
- package/src/dom/attrs.ts +15 -3
- package/src/dom/extras.ts +29 -14
- package/src/dom/index.ts +39 -10
- package/src/dom/island.ts +54 -35
- package/src/dom/loop.ts +33 -23
- package/src/eco/declaration.ts +257 -0
- package/src/eco/index.ts +65 -0
- package/src/index.ts +2 -2
- package/src/jsx-runtime.ts +2 -2
- package/src/plugins/config.ts +8 -7
- package/src/plugins/context.ts +16 -1
- package/src/plugins/index.ts +2 -2
- package/src/plugins/load.ts +30 -10
- package/src/plugins/order.ts +38 -1
- package/src/plugins/public.ts +6 -3
- package/src/plugins/services.ts +84 -0
- package/src/plugins/types.ts +51 -2
- package/src/reactivity/graph.ts +10 -0
- package/src/reactivity/index.ts +24 -16
- package/src/reactivity/selector.ts +31 -4
- package/src/reactivity/store.ts +45 -13
- package/src/server/action-flash.ts +158 -0
- package/src/server/action-protect.ts +199 -0
- package/src/server/action-registry.ts +1 -1
- package/src/server/action.ts +56 -117
- package/src/server/app-secret.ts +63 -0
- package/src/server/assets.ts +34 -2
- package/src/server/compress.ts +96 -10
- package/src/server/consent.ts +59 -22
- package/src/server/cookies.ts +16 -2
- package/src/server/document.ts +25 -10
- package/src/server/env.ts +14 -0
- package/src/server/errors.ts +305 -65
- package/src/server/form-schema.ts +343 -0
- package/src/server/health.ts +275 -0
- package/src/server/http.ts +177 -38
- package/src/server/index.ts +264 -272
- package/src/server/loader.ts +11 -2
- package/src/server/param-matchers.ts +112 -0
- package/src/server/plugin-host.ts +125 -88
- package/src/server/public.ts +6 -5
- package/src/server/rate-limit.ts +102 -36
- package/src/server/request-body.ts +1 -1
- package/src/server/route-cache.ts +445 -0
- package/src/server/route-table.ts +344 -9
- package/src/server/router.ts +125 -40
- package/src/server/routing.ts +112 -63
- package/src/server/sanitize-html.ts +309 -0
- package/src/server/security.ts +277 -50
- package/src/server/serve-handlers.ts +31 -7
- package/src/server/start.ts +60 -16
- package/src/server/static-dir.ts +87 -11
- package/src/server/stream.ts +68 -27
- package/src/ssr/consent-banner.ts +58 -0
- package/src/ssr/context.ts +105 -7
- package/src/ssr/index.ts +148 -3
- package/src/ssr/navigation.ts +2 -2
- package/src/ssr/region.ts +31 -19
- package/src/style.ts +32 -1
- package/src/test/browser.ts +28 -13
- package/src/test/index.ts +97 -12
- package/src/ts-plugin/diagnostics.ts +505 -0
- package/src/ts-plugin/fixes.ts +364 -0
- package/src/ts-plugin/index.ts +194 -0
- package/templates/_shared/AGENTS.md +2 -2
- package/templates/_shared/gitignore +5 -0
- package/templates/_shared/mcp.json +11 -0
- package/templates/_shared/src/routes/legal.tsx +15 -1
- package/templates/_shared/tsconfig.json +5 -0
- package/templates/app/.env.example +4 -0
- package/templates/app/package.json +2 -1
- package/templates/app/prunelle.config.ts +2 -0
- package/templates/app/src/auth.ts +4 -6
- package/templates/app/src/mail.ts +4 -0
- package/templates/app/src/routes/_layout.tsx +9 -1
- package/templates/app/src/routes/dashboard/index.tsx +42 -8
- package/templates/app/src/routes/login.tsx +49 -30
- package/templates/app/src/routes/privacy.tsx +25 -0
- package/templates/app/src/styles/app.css +8 -1
- package/templates/app/tests/app.test.ts +44 -3
- package/templates/blog/package.json +1 -1
- package/templates/blog/prunelle.config.ts +1 -1
- package/templates/blog/src/routes/_layout.tsx +6 -1
- package/templates/blog/src/routes/index.tsx +5 -1
- package/templates/blog/src/styles/app.css +6 -1
- package/templates/fullstack/package.json +1 -1
- package/templates/fullstack/src/components/GreetForm.tsx +2 -1
- package/templates/fullstack/src/routes/_layout.tsx +4 -0
- package/templates/fullstack/src/styles/app.css +11 -1
- package/templates/minimal/package.json +1 -1
- package/templates/minimal/src/routes/_layout.tsx +4 -0
- package/templates/minimal/src/styles/app.css +11 -1
- package/ts-plugin.cjs +4277 -0
package/src/server/static-dir.ts
CHANGED
|
@@ -1,13 +1,18 @@
|
|
|
1
1
|
// Standalone `--static` directory server (used when `outDir` holds exported HTML without `manifest.json`): every file is listed once at startup, so a request is a map lookup.
|
|
2
2
|
|
|
3
3
|
import type { FSWatcher } from 'node:fs'
|
|
4
|
+
import type { PrunellePlugin, ServerErrorInfo } from '../plugins/index'
|
|
5
|
+
import type { NavigationConfig } from '../ssr/navigation'
|
|
4
6
|
import type { PrunelleApp, PrunelleServer } from './http'
|
|
5
7
|
import type { SecurityHeadersOptions, TrustProxy } from './security'
|
|
6
8
|
import type { FileSource, ServedFile } from './served-file'
|
|
7
9
|
import { readdirSync, readFileSync, realpathSync, statSync, watch } from 'node:fs'
|
|
8
10
|
import { extname, join, resolve } from 'node:path'
|
|
9
11
|
import { isInside } from '../build/is-inside'
|
|
12
|
+
import { resolvePlugins } from '../plugins/index'
|
|
13
|
+
import { createNavigation, cspSha256 } from '../ssr/navigation'
|
|
10
14
|
import { CompressionCache, isCompressibleType } from './compress'
|
|
15
|
+
import { createErrorNotifier } from './errors'
|
|
11
16
|
import { applyHstsHeader, MIME } from './http'
|
|
12
17
|
import { decodeRequestPath } from './request-path'
|
|
13
18
|
import { buildSecurityHeaderEntries, inlineStyleHashes, PRUNELLE_ISLAND_STYLE_HASH, resolveCspPolicy, resolveHstsValue, withCspHashes } from './security'
|
|
@@ -15,6 +20,40 @@ import { createFileServer, servedFile } from './served-file'
|
|
|
15
20
|
|
|
16
21
|
const isRead = (request: Request): boolean => request.method === 'GET' || request.method === 'HEAD'
|
|
17
22
|
|
|
23
|
+
const EXTRA_STATIC_MIME: Record<string, string> = {
|
|
24
|
+
'.htm': 'text/html; charset=utf-8',
|
|
25
|
+
'.rss': 'application/rss+xml; charset=utf-8',
|
|
26
|
+
'.atom': 'application/atom+xml; charset=utf-8',
|
|
27
|
+
'.ics': 'text/calendar; charset=utf-8',
|
|
28
|
+
'.csv': 'text/csv; charset=utf-8',
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface StaticDirExtraOptions {
|
|
32
|
+
navigation?: NavigationConfig | undefined
|
|
33
|
+
plugins?: readonly PrunellePlugin[] | undefined
|
|
34
|
+
/** The app's `onError` hook; plugin `onError` hooks run too. With no hook the error is logged. */
|
|
35
|
+
onError?: ((info: ServerErrorInfo) => void) | undefined
|
|
36
|
+
errorSink?: ((info: ServerErrorInfo) => void) | undefined
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function findNotFound(rel: string | undefined, byDir: ReadonlyMap<string, ServedFile>): ServedFile | undefined {
|
|
40
|
+
if (byDir.size === 0)
|
|
41
|
+
return undefined
|
|
42
|
+
if (rel !== undefined && rel !== '') {
|
|
43
|
+
let dir = rel
|
|
44
|
+
while (true) {
|
|
45
|
+
const hit = byDir.get(dir)
|
|
46
|
+
if (hit !== undefined)
|
|
47
|
+
return hit
|
|
48
|
+
const slash = dir.lastIndexOf('/')
|
|
49
|
+
if (slash === -1)
|
|
50
|
+
break
|
|
51
|
+
dir = dir.slice(0, slash)
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return byDir.get('')
|
|
55
|
+
}
|
|
56
|
+
|
|
18
57
|
|
|
19
58
|
/** The files under `absRoot` by their path from it, `/`-separated; a symlink counts only when it lands on a file inside `realRoot`. */
|
|
20
59
|
function listFiles(absRoot: string, realRoot: string): Map<string, string> {
|
|
@@ -53,6 +92,7 @@ export function createStaticDirServer(
|
|
|
53
92
|
compressEnabled: boolean,
|
|
54
93
|
trustProxy: TrustProxy,
|
|
55
94
|
isDev = false,
|
|
95
|
+
extra?: StaticDirExtraOptions,
|
|
56
96
|
): PrunelleApp {
|
|
57
97
|
const prefix = assetPrefix.replace(/^\/+/, '').replace(/\/$/, '')
|
|
58
98
|
const absRoot = resolve(outDir)
|
|
@@ -67,16 +107,38 @@ export function createStaticDirServer(
|
|
|
67
107
|
const securityEntries = buildSecurityHeaderEntries(security)
|
|
68
108
|
const securityRecord = Object.fromEntries(securityEntries)
|
|
69
109
|
const baseCsp = resolveCspPolicy(security)
|
|
70
|
-
const
|
|
110
|
+
const nav = extra !== undefined ? createNavigation(extra.navigation) : undefined
|
|
111
|
+
const plugins = extra?.plugins !== undefined ? resolvePlugins(extra.plugins) : []
|
|
112
|
+
const extraStyleHashes = [PRUNELLE_ISLAND_STYLE_HASH, ...(nav?.styleHashes ?? [])]
|
|
113
|
+
const extraScriptHashes = [
|
|
114
|
+
...(nav?.scriptHashes ?? []),
|
|
115
|
+
...plugins.flatMap(p => p.inlineScripts ?? []).map(cspSha256),
|
|
116
|
+
]
|
|
117
|
+
const htmlCsp = baseCsp !== undefined
|
|
118
|
+
? withCspHashes(baseCsp, { styleHashes: extraStyleHashes, scriptHashes: extraScriptHashes })
|
|
119
|
+
: undefined
|
|
71
120
|
const hstsValue = resolveHstsValue(security)
|
|
72
121
|
const withHsts = hstsValue === undefined || isDev
|
|
73
122
|
? (res: Response) => res
|
|
74
123
|
: (res: Response, req: Request) => applyHstsHeader(res, req, hstsValue, trustProxy, isDev)
|
|
75
|
-
const
|
|
124
|
+
const serveFileUnguarded = createFileServer({ compressEnabled, compressCache, withHsts })
|
|
125
|
+
const notifyError = createErrorNotifier(extra?.onError, plugins, { dev: isDev, sink: extra?.errorSink })
|
|
126
|
+
// A file that fails to open answers here, where the request is known: gone since the listing is a 404, anything else is reported.
|
|
127
|
+
const serveFile = async (req: Request, file: ServedFile, status?: number): Promise<Response> => {
|
|
128
|
+
try {
|
|
129
|
+
return await serveFileUnguarded(req, file, status)
|
|
130
|
+
}
|
|
131
|
+
catch (err) {
|
|
132
|
+
if (err instanceof Error && 'code' in err && err.code === 'ENOENT')
|
|
133
|
+
return withHsts(new Response('Not Found', { status: 404, headers: { 'cache-control': 'no-store', ...securityRecord } }), req)
|
|
134
|
+
notifyError(err, req, 'route')
|
|
135
|
+
return error()
|
|
136
|
+
}
|
|
137
|
+
}
|
|
76
138
|
|
|
77
139
|
function entryFor(rel: string, path: string, all: ReadonlyMap<string, string>): ServedFile {
|
|
78
140
|
const ext = extname(rel).toLowerCase()
|
|
79
|
-
const type = MIME[ext] ?? 'application/octet-stream'
|
|
141
|
+
const type = MIME[ext] ?? EXTRA_STATIC_MIME[ext] ?? 'application/octet-stream'
|
|
80
142
|
const isHtml = ext === '.html' || ext === '.htm'
|
|
81
143
|
// An exported page's CSP gains the hashes of its own `<style>` blocks.
|
|
82
144
|
const csp = isHtml && htmlCsp !== undefined ? withCspHashes(htmlCsp, { styleHashes: inlineStyleHashes(readFileSync(path, 'utf8')) }) : undefined
|
|
@@ -100,11 +162,18 @@ export function createStaticDirServer(
|
|
|
100
162
|
}
|
|
101
163
|
|
|
102
164
|
// Each file at its own path, then `x.html` at `x` and `x/index.html` at `x`, a real file always winning.
|
|
103
|
-
function buildTable(): { table: Map<string, ServedFile>,
|
|
165
|
+
function buildTable(): { table: Map<string, ServedFile>, notFoundByDir: Map<string, ServedFile> } {
|
|
104
166
|
const files = listFiles(absRoot, realRoot)
|
|
105
167
|
const table = new Map<string, ServedFile>()
|
|
106
|
-
|
|
107
|
-
|
|
168
|
+
const notFoundByDir = new Map<string, ServedFile>()
|
|
169
|
+
for (const [rel, path] of files) {
|
|
170
|
+
const entry = entryFor(rel, path, files)
|
|
171
|
+
table.set(rel, entry)
|
|
172
|
+
if (rel === '404.html')
|
|
173
|
+
notFoundByDir.set('', entry)
|
|
174
|
+
else if (rel.endsWith('/404.html'))
|
|
175
|
+
notFoundByDir.set(rel.slice(0, -'/404.html'.length), entry)
|
|
176
|
+
}
|
|
108
177
|
for (const [rel, entry] of [...table]) {
|
|
109
178
|
if (rel.endsWith('.html') && !table.has(rel.slice(0, -5)))
|
|
110
179
|
table.set(rel.slice(0, -5), entry)
|
|
@@ -116,7 +185,7 @@ export function createStaticDirServer(
|
|
|
116
185
|
table.set(dir, entry)
|
|
117
186
|
}
|
|
118
187
|
}
|
|
119
|
-
return { table,
|
|
188
|
+
return { table, notFoundByDir }
|
|
120
189
|
}
|
|
121
190
|
|
|
122
191
|
let current = buildTable()
|
|
@@ -141,8 +210,9 @@ export function createStaticDirServer(
|
|
|
141
210
|
const found = rel === undefined ? undefined : current.table.get(rel)
|
|
142
211
|
if (found !== undefined)
|
|
143
212
|
return serveFile(req, found)
|
|
144
|
-
|
|
145
|
-
|
|
213
|
+
const notFound = findNotFound(rel, current.notFoundByDir)
|
|
214
|
+
if (notFound !== undefined)
|
|
215
|
+
return serveFile(req, notFound, 404)
|
|
146
216
|
return withHsts(new Response('Not Found', { status: 404, headers: securityRecord }), req)
|
|
147
217
|
}
|
|
148
218
|
|
|
@@ -150,14 +220,20 @@ export function createStaticDirServer(
|
|
|
150
220
|
status: 500,
|
|
151
221
|
headers: { 'content-type': 'text/plain; charset=utf-8', ...securityRecord },
|
|
152
222
|
})
|
|
223
|
+
// What escapes `serveFile` (a body stream failing after its headers) reaches `Bun.serve` without a request: logged, never silent.
|
|
224
|
+
const lastResort = (err: Error): Response => {
|
|
225
|
+
console.error('prunelle start: unhandled error while serving a file', err)
|
|
226
|
+
return error()
|
|
227
|
+
}
|
|
153
228
|
|
|
154
229
|
return {
|
|
155
230
|
handle,
|
|
231
|
+
securityHeaders: securityRecord,
|
|
156
232
|
serve(port = 3000, hostname = '127.0.0.1') {
|
|
157
|
-
return Bun.serve({ port, hostname, idleTimeout: 30, development: false, fetch: handle, error })
|
|
233
|
+
return Bun.serve({ port, hostname, idleTimeout: 30, development: false, fetch: handle, error: lastResort })
|
|
158
234
|
},
|
|
159
235
|
reloadInto(server: PrunelleServer) {
|
|
160
|
-
server.reload({ routes: {}, fetch: handle, error })
|
|
236
|
+
server.reload({ routes: {}, fetch: handle, error: lastResort })
|
|
161
237
|
},
|
|
162
238
|
async dispose() {
|
|
163
239
|
clearTimeout(timer)
|
package/src/server/stream.ts
CHANGED
|
@@ -37,6 +37,7 @@ async function settleWithin(
|
|
|
37
37
|
timer = setTimeout(() => {
|
|
38
38
|
if (onAbort !== undefined)
|
|
39
39
|
signal.removeEventListener('abort', onAbort)
|
|
40
|
+
chunk.discard?.()
|
|
40
41
|
const error = new Error(`<Suspense> boundary ${chunk.id} did not resolve within ${streamTimeout} ms`)
|
|
41
42
|
resolve({ html: runInScope(() => chunk.renderError(error)), error })
|
|
42
43
|
}, remaining)
|
|
@@ -52,7 +53,14 @@ async function settleWithin(
|
|
|
52
53
|
}
|
|
53
54
|
|
|
54
55
|
/** Streams `shell` (a document holding `STREAM_TAIL_MARK`), with every boundary of `rctx` flushed before its tail. */
|
|
55
|
-
export function streamDocument(
|
|
56
|
+
export function streamDocument(
|
|
57
|
+
shell: string,
|
|
58
|
+
rctx: RenderContext,
|
|
59
|
+
streamTimeout: number,
|
|
60
|
+
onBoundaryError: (error: unknown) => void,
|
|
61
|
+
transformChunk?: (html: string) => string | Promise<string>,
|
|
62
|
+
tracker?: Pick<StreamTracker, 'trackPage'>,
|
|
63
|
+
): ReadableStream<Uint8Array> {
|
|
56
64
|
let splitAt = shell.lastIndexOf(STREAM_TAIL_MARK)
|
|
57
65
|
let tailOffset = STREAM_TAIL_MARK.length
|
|
58
66
|
if (splitAt === -1) {
|
|
@@ -66,48 +74,67 @@ export function streamDocument(shell: string, rctx: RenderContext, streamTimeout
|
|
|
66
74
|
const abortCtrl = new AbortController()
|
|
67
75
|
let closed = false
|
|
68
76
|
const deadline = Date.now() + streamTimeout
|
|
77
|
+
// Shutdown stops waiting for the pending boundaries; the document still gets its tail.
|
|
78
|
+
let endedEarly = false
|
|
69
79
|
|
|
70
80
|
const safeEnqueue = (controller: ReadableStreamDefaultController<Uint8Array>, data: Uint8Array): void => {
|
|
71
|
-
if (closed || abortCtrl.signal.aborted)
|
|
81
|
+
if (closed || (abortCtrl.signal.aborted && !endedEarly))
|
|
72
82
|
return
|
|
73
83
|
try {
|
|
74
84
|
controller.enqueue(data)
|
|
75
85
|
}
|
|
76
86
|
catch {
|
|
77
87
|
closed = true
|
|
88
|
+
rctx.aborted = true
|
|
78
89
|
abortCtrl.abort()
|
|
79
90
|
}
|
|
80
91
|
}
|
|
81
92
|
|
|
82
93
|
return new ReadableStream<Uint8Array>({
|
|
83
94
|
async start(controller) {
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
flushed =
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
if (settled === undefined || closed || abortCtrl.signal.aborted)
|
|
95
|
+
const untrack = tracker?.trackPage(() => {
|
|
96
|
+
endedEarly = true
|
|
97
|
+
abortCtrl.abort()
|
|
98
|
+
})
|
|
99
|
+
try {
|
|
100
|
+
safeEnqueue(controller, textEncoder.encode(openingHtml))
|
|
101
|
+
// A resolved boundary can render boundaries of its own, so each flush also drains the ones it added.
|
|
102
|
+
let flushed = 0
|
|
103
|
+
const flushPending = async (): Promise<void> => {
|
|
104
|
+
if (closed || abortCtrl.signal.aborted)
|
|
95
105
|
return
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
106
|
+
const chunks = rctx.pending.slice(flushed)
|
|
107
|
+
flushed = rctx.pending.length
|
|
108
|
+
await Promise.all(chunks.map(async (chunk) => {
|
|
109
|
+
const settled = await settleWithin(chunk, deadline, streamTimeout, abortCtrl.signal, runInScope)
|
|
110
|
+
if (settled === undefined || closed || abortCtrl.signal.aborted)
|
|
111
|
+
return
|
|
112
|
+
if ('error' in settled)
|
|
113
|
+
runInScope(() => onBoundaryError(settled.error))
|
|
114
|
+
let chunkHtml = settled.html
|
|
115
|
+
if (transformChunk !== undefined && chunkHtml !== '')
|
|
116
|
+
chunkHtml = await runInScope(() => transformChunk(chunkHtml))
|
|
117
|
+
if (closed || abortCtrl.signal.aborted)
|
|
118
|
+
return
|
|
119
|
+
safeEnqueue(controller, textEncoder.encode(streamChunkScript(chunk.id, chunkHtml)))
|
|
120
|
+
await flushPending()
|
|
121
|
+
}))
|
|
122
|
+
}
|
|
123
|
+
await flushPending()
|
|
124
|
+
if (!closed && (endedEarly || !abortCtrl.signal.aborted)) {
|
|
125
|
+
safeEnqueue(controller, textEncoder.encode(tailHtml))
|
|
126
|
+
closed = true
|
|
127
|
+
safeClose(controller)
|
|
128
|
+
}
|
|
101
129
|
}
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
closed = true
|
|
106
|
-
safeClose(controller)
|
|
130
|
+
finally {
|
|
131
|
+
untrack?.()
|
|
132
|
+
rctx.aborted = true
|
|
107
133
|
}
|
|
108
134
|
},
|
|
109
135
|
cancel() {
|
|
110
136
|
closed = true
|
|
137
|
+
rctx.aborted = true
|
|
111
138
|
abortCtrl.abort()
|
|
112
139
|
},
|
|
113
140
|
})
|
|
@@ -178,14 +205,28 @@ function trackEventStream(res: Response, active: Set<() => void>, disableTimeout
|
|
|
178
205
|
return new Response(body, { status: res.status, statusText: res.statusText, headers: res.headers })
|
|
179
206
|
}
|
|
180
207
|
|
|
181
|
-
|
|
182
|
-
|
|
208
|
+
export interface StreamTracker {
|
|
209
|
+
track: (res: Response, disableTimeout?: () => void) => Response
|
|
210
|
+
/** Registers a streamed page's way to end early; the returned function drops it once the page is done. */
|
|
211
|
+
trackPage: (end: () => void) => () => void
|
|
212
|
+
closeAll: () => Promise<void>
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** Tracks active SSE streams and streamed pages so graceful shutdown can end them before `server.stop()` drains in-flight requests. */
|
|
216
|
+
export function createStreamTracker(): StreamTracker {
|
|
183
217
|
const active = new Set<() => void>()
|
|
218
|
+
const pages = new Set<() => void>()
|
|
184
219
|
return {
|
|
185
|
-
track: (res
|
|
186
|
-
|
|
220
|
+
track: (res, disableTimeout) => trackEventStream(res, active, disableTimeout),
|
|
221
|
+
trackPage: (end) => {
|
|
222
|
+
pages.add(end)
|
|
223
|
+
return () => { pages.delete(end) }
|
|
224
|
+
},
|
|
225
|
+
closeAll: () => {
|
|
187
226
|
for (const close of [...active])
|
|
188
227
|
close()
|
|
228
|
+
for (const end of [...pages])
|
|
229
|
+
end()
|
|
189
230
|
return Promise.resolve()
|
|
190
231
|
},
|
|
191
232
|
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// The markup of <ConsentBanner> and <ConsentPreferences>: one form posting to the consent endpoint, with no script.
|
|
2
|
+
|
|
3
|
+
import type { ConsentBannerProps, ConsentTexts } from '../context'
|
|
4
|
+
import type { RequestConsent } from '../server/consent'
|
|
5
|
+
import { esc, escAttr, ssrChild } from './index'
|
|
6
|
+
|
|
7
|
+
function requireCategories(consent: RequestConsent, tag: string): void {
|
|
8
|
+
if (consent.categories.length === 0)
|
|
9
|
+
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
|
+
}
|
|
11
|
+
|
|
12
|
+
function checkboxes(consent: RequestConsent, legend: string | undefined): string {
|
|
13
|
+
const boxes = consent.categories.map((category) => {
|
|
14
|
+
const checked = consent.has(category) ? ' checked' : ''
|
|
15
|
+
return `<label data-part="choice"><input type="checkbox" name="categories" value="${escAttr(category)}"${checked}> ${esc(consent.labels[category] ?? category)}</label>`
|
|
16
|
+
})
|
|
17
|
+
return `<fieldset data-part="choices"><legend>${esc(legend ?? 'Cookies by purpose')}</legend>${boxes.join('')}</fieldset>`
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// 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 ?? 'Refuse all')}</button>`
|
|
23
|
+
+ `<button type="submit" name="action" value="accept-all" data-ui="button">${esc(texts.accept ?? 'Accept all')}</button>`
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function saveButton(texts: ConsentTexts): string {
|
|
27
|
+
return `<button type="submit" name="action" value="save" data-ui="button">${esc(texts.save ?? 'Save my choices')}</button>`
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function renderConsentBanner(consent: RequestConsent | undefined, props: ConsentBannerProps): string {
|
|
31
|
+
if (consent === undefined)
|
|
32
|
+
return ''
|
|
33
|
+
requireCategories(consent, 'ConsentBanner')
|
|
34
|
+
if (consent.decided)
|
|
35
|
+
return ''
|
|
36
|
+
const labels = consent.categories.map(category => consent.labels[category] ?? category).join(', ')
|
|
37
|
+
const body = props.children !== undefined
|
|
38
|
+
? ssrChild(props.children)
|
|
39
|
+
: `<p>This site would like to set cookies for: ${esc(labels)}. You can accept or refuse them, and change your mind at any time.</p>`
|
|
40
|
+
const policy = props.policyHref !== undefined ? `<p><a href="${escAttr(props.policyHref)}">Cookie policy</a></p>` : ''
|
|
41
|
+
return `<section data-ui="consent" aria-labelledby="pru-consent-title">`
|
|
42
|
+
+ `<h2 id="pru-consent-title" data-part="title">${esc(props.title ?? 'Cookies')}</h2>`
|
|
43
|
+
+ `<div data-part="body">${body}${policy}</div>`
|
|
44
|
+
+ `<form method="post" action="${escAttr(consent.endpoint)}" data-part="form">`
|
|
45
|
+
+ `<div data-part="actions">${decisionButtons(props)}</div>`
|
|
46
|
+
+ `<details data-part="details"><summary>${esc(props.choose ?? 'Choose')}</summary>${checkboxes(consent, props.legend)}${saveButton(props)}</details>`
|
|
47
|
+
+ `</form></section>`
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function renderConsentPreferences(consent: RequestConsent | undefined, texts: ConsentTexts): string {
|
|
51
|
+
if (consent === undefined)
|
|
52
|
+
return ''
|
|
53
|
+
requireCategories(consent, 'ConsentPreferences')
|
|
54
|
+
return `<form method="post" action="${escAttr(consent.endpoint)}" data-ui="consent" data-part="preferences">`
|
|
55
|
+
+ `${checkboxes(consent, texts.legend)}`
|
|
56
|
+
+ `<div data-part="actions">${saveButton(texts)}${decisionButtons(texts)}</div>`
|
|
57
|
+
+ `</form>`
|
|
58
|
+
}
|
package/src/ssr/context.ts
CHANGED
|
@@ -1,10 +1,13 @@
|
|
|
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, ConsentGateProps } from '../context'
|
|
4
|
+
import type { CatchProps, ConsentBannerProps, ConsentGateProps, ConsentTexts } from '../context'
|
|
5
5
|
import type { Html, PrunelleChild } from '../jsx-runtime'
|
|
6
|
+
import type { RequestConsent } from '../server/consent'
|
|
7
|
+
import type { FieldConstraint } from '../server/form-schema'
|
|
6
8
|
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
7
9
|
import { registerServerContextBridge } from '../context'
|
|
10
|
+
import { renderConsentBanner, renderConsentPreferences } from './consent-banner'
|
|
8
11
|
import { raw, ssrChild } from './index'
|
|
9
12
|
import { Region } from './region'
|
|
10
13
|
|
|
@@ -18,6 +21,8 @@ export interface PendingChunk {
|
|
|
18
21
|
// Settles to the boundary's HTML, or to its error template and the error: it never rejects.
|
|
19
22
|
settled: Promise<SettledChunk>
|
|
20
23
|
renderError: (error: unknown) => string
|
|
24
|
+
/** Marks this chunk as timed out / aborted so late resolution skips rendering into the RenderContext. */
|
|
25
|
+
discard?: () => void
|
|
21
26
|
}
|
|
22
27
|
|
|
23
28
|
export interface RenderContext {
|
|
@@ -51,10 +56,18 @@ export interface RenderContext {
|
|
|
51
56
|
inTarget: boolean
|
|
52
57
|
/** Compiler-emitted inline `<style>` contents rendered during this request, for CSP hashing. */
|
|
53
58
|
inlineStyles: string[] | undefined
|
|
54
|
-
/**
|
|
55
|
-
|
|
59
|
+
/** True once HTTP headers (and CSP) have been flushed for a streamed response. */
|
|
60
|
+
headersFlushed: boolean
|
|
61
|
+
/** True once the post-flush inline `<style>` warning has been emitted for this request. */
|
|
62
|
+
warnedStreamStyle: boolean
|
|
63
|
+
/** True once the stream/region finished, timed out, was aborted, or was discarded (e.g. HEAD). */
|
|
64
|
+
aborted: boolean
|
|
65
|
+
/** Request consent state used by `<ConsentGate>`, `<ConsentBanner>` and `<ConsentPreferences>`. */
|
|
66
|
+
consent: RequestConsent | undefined
|
|
56
67
|
/** Reports an error a `<Catch>` rendered its fallback for, to the app's error hook. */
|
|
57
68
|
onCaught: ((error: unknown) => void) | undefined
|
|
69
|
+
/** Actions referenced via `useAction(fn).action` during this request, keyed by action URL. */
|
|
70
|
+
formActions: Map<string, unknown> | undefined
|
|
58
71
|
}
|
|
59
72
|
|
|
60
73
|
interface RenderScope {
|
|
@@ -63,12 +76,25 @@ interface RenderScope {
|
|
|
63
76
|
outerContexts: ReadonlyMap<symbol, unknown> | undefined
|
|
64
77
|
island: string | undefined
|
|
65
78
|
inTarget: boolean
|
|
79
|
+
formFields: ReadonlyMap<string, FieldConstraint> | undefined
|
|
66
80
|
}
|
|
67
81
|
|
|
68
82
|
const STORAGE_KEY = Symbol.for('pru.render.storage')
|
|
69
83
|
const SCOPE_STORAGE_KEY = Symbol.for('pru.render.scope.storage')
|
|
70
84
|
const renderStorage: AsyncLocalStorage<RenderContext> = ((globalThis as Record<symbol, AsyncLocalStorage<RenderContext> | undefined>)[STORAGE_KEY] ??= new AsyncLocalStorage<RenderContext>())
|
|
71
85
|
const scopeStorage: AsyncLocalStorage<RenderScope> = ((globalThis as Record<symbol, AsyncLocalStorage<RenderScope> | undefined>)[SCOPE_STORAGE_KEY] ??= new AsyncLocalStorage<RenderScope>())
|
|
86
|
+
let fallbackFormAction: { url: string, action: unknown } | undefined
|
|
87
|
+
let fallbackFormFields: ReadonlyMap<string, FieldConstraint> | undefined
|
|
88
|
+
|
|
89
|
+
;(globalThis as { __pruAct?: (url: string, action: unknown) => void }).__pruAct = (url, action) => {
|
|
90
|
+
if (url === '')
|
|
91
|
+
return
|
|
92
|
+
const ctx = renderStorage.getStore()
|
|
93
|
+
if (ctx !== undefined)
|
|
94
|
+
(ctx.formActions ??= new Map()).set(url, action)
|
|
95
|
+
else
|
|
96
|
+
fallbackFormAction = { url, action }
|
|
97
|
+
}
|
|
72
98
|
|
|
73
99
|
function activeScope(ctx: RenderContext): RenderScope {
|
|
74
100
|
const scope = scopeStorage.getStore()
|
|
@@ -80,6 +106,38 @@ function activeScope(ctx: RenderContext): RenderScope {
|
|
|
80
106
|
outerContexts: ctx.outerContexts,
|
|
81
107
|
island: ctx.island,
|
|
82
108
|
inTarget: ctx.inTarget,
|
|
109
|
+
formFields: undefined,
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export function lookupFormAction(url: string): unknown {
|
|
114
|
+
const ctx = renderStorage.getStore()
|
|
115
|
+
if (ctx !== undefined)
|
|
116
|
+
return ctx.formActions?.get(url)
|
|
117
|
+
return fallbackFormAction?.url === url ? fallbackFormAction.action : undefined
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function currentFormFields(): ReadonlyMap<string, FieldConstraint> | undefined {
|
|
121
|
+
const ctx = renderStorage.getStore()
|
|
122
|
+
return ctx !== undefined ? activeScope(ctx).formFields : fallbackFormFields
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export function runWithFormFields<T>(fields: ReadonlyMap<string, FieldConstraint>, fn: () => T): T {
|
|
126
|
+
const ctx = renderStorage.getStore()
|
|
127
|
+
if (ctx !== undefined)
|
|
128
|
+
return scopeStorage.run({ ...activeScope(ctx), formFields: fields }, fn)
|
|
129
|
+
const prev = fallbackFormFields
|
|
130
|
+
fallbackFormFields = fields
|
|
131
|
+
try {
|
|
132
|
+
const out = fn()
|
|
133
|
+
if (out instanceof Promise)
|
|
134
|
+
return out.finally(() => { fallbackFormFields = prev }) as T
|
|
135
|
+
fallbackFormFields = prev
|
|
136
|
+
return out
|
|
137
|
+
}
|
|
138
|
+
catch (err) {
|
|
139
|
+
fallbackFormFields = prev
|
|
140
|
+
throw err
|
|
83
141
|
}
|
|
84
142
|
}
|
|
85
143
|
|
|
@@ -124,6 +182,12 @@ registerServerContextBridge({
|
|
|
124
182
|
consentGate(props) {
|
|
125
183
|
return ConsentGate(props)
|
|
126
184
|
},
|
|
185
|
+
consentBanner(props) {
|
|
186
|
+
return ConsentBanner(props)
|
|
187
|
+
},
|
|
188
|
+
consentPreferences(props) {
|
|
189
|
+
return ConsentPreferences(props)
|
|
190
|
+
},
|
|
127
191
|
head(props) {
|
|
128
192
|
return Head(props)
|
|
129
193
|
},
|
|
@@ -138,7 +202,7 @@ registerServerContextBridge({
|
|
|
138
202
|
export function createRenderContext(
|
|
139
203
|
region?: string,
|
|
140
204
|
ancestors: ReadonlySet<string> = new Set(),
|
|
141
|
-
consent?:
|
|
205
|
+
consent?: RequestConsent,
|
|
142
206
|
onCaught?: (error: unknown) => void,
|
|
143
207
|
): RenderContext {
|
|
144
208
|
return {
|
|
@@ -163,8 +227,12 @@ export function createRenderContext(
|
|
|
163
227
|
regionAncestors: ancestors,
|
|
164
228
|
inTarget: false,
|
|
165
229
|
inlineStyles: undefined,
|
|
230
|
+
headersFlushed: false,
|
|
231
|
+
warnedStreamStyle: false,
|
|
232
|
+
aborted: false,
|
|
166
233
|
consent,
|
|
167
234
|
onCaught,
|
|
235
|
+
formActions: undefined,
|
|
168
236
|
}
|
|
169
237
|
}
|
|
170
238
|
|
|
@@ -173,9 +241,14 @@ export function recordInlineStyle(css: string): void {
|
|
|
173
241
|
const ctx = renderStorage.getStore()
|
|
174
242
|
if (ctx === undefined || css === '')
|
|
175
243
|
return
|
|
244
|
+
const isNew = ctx.inlineStyles === undefined || !ctx.inlineStyles.includes(css)
|
|
245
|
+
if (ctx.headersFlushed && isNew && !ctx.warnedStreamStyle) {
|
|
246
|
+
ctx.warnedStreamStyle = true
|
|
247
|
+
console.warn('prunelle: an inline <style> was rendered inside a streamed <Suspense> boundary after CSP headers were sent; move the style into a CSS file or outside <Suspense> so strict CSP does not block it.')
|
|
248
|
+
}
|
|
176
249
|
if (ctx.inlineStyles === undefined)
|
|
177
250
|
ctx.inlineStyles = [css]
|
|
178
|
-
else if (
|
|
251
|
+
else if (isNew)
|
|
179
252
|
ctx.inlineStyles.push(css)
|
|
180
253
|
}
|
|
181
254
|
|
|
@@ -231,6 +304,14 @@ export function ConsentGate(props: ConsentGateProps): Html {
|
|
|
231
304
|
return raw(ssrChild(granted ? props.children : props.fallback))
|
|
232
305
|
}
|
|
233
306
|
|
|
307
|
+
export function ConsentBanner(props: ConsentBannerProps): Html {
|
|
308
|
+
return raw(renderConsentBanner(renderStorage.getStore()?.consent, props))
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
export function ConsentPreferences(props: ConsentTexts): Html {
|
|
312
|
+
return raw(renderConsentPreferences(renderStorage.getStore()?.consent, props))
|
|
313
|
+
}
|
|
314
|
+
|
|
234
315
|
/** Collects document <head> tags during SSR; innermost <title> wins. */
|
|
235
316
|
export function Head(props: { children?: PrunelleChild }): Html {
|
|
236
317
|
const ctx = renderStorage.getStore()
|
|
@@ -277,18 +358,35 @@ export function Suspense(props: { fallback?: PrunelleChild, error?: PrunelleChil
|
|
|
277
358
|
return ''
|
|
278
359
|
}
|
|
279
360
|
}
|
|
280
|
-
|
|
361
|
+
let discarded = false
|
|
362
|
+
const isAborted = (): boolean => ctx.aborted || discarded
|
|
363
|
+
ctx.pending.push({
|
|
364
|
+
id,
|
|
365
|
+
settled: settle(ctx, scope, child, renderError, isAborted),
|
|
366
|
+
renderError,
|
|
367
|
+
discard: () => { discarded = true },
|
|
368
|
+
})
|
|
281
369
|
|
|
282
370
|
const fallbackHtml = ssrChild(props.fallback)
|
|
283
371
|
return raw(`<pru-s id="k-s-${id}">${fallbackHtml}</pru-s>`)
|
|
284
372
|
}
|
|
285
373
|
|
|
286
|
-
async function settle(
|
|
374
|
+
async function settle(
|
|
375
|
+
ctx: RenderContext,
|
|
376
|
+
scope: RenderScope,
|
|
377
|
+
child: Promise<PrunelleChild>,
|
|
378
|
+
renderError: (error: unknown) => string,
|
|
379
|
+
isAborted: () => boolean,
|
|
380
|
+
): Promise<SettledChunk> {
|
|
287
381
|
try {
|
|
288
382
|
const resolved = await child
|
|
383
|
+
if (isAborted())
|
|
384
|
+
return { html: '' }
|
|
289
385
|
return { html: runWithRenderContext(ctx, () => scopeStorage.run(scope, () => ssrChild(resolved))) }
|
|
290
386
|
}
|
|
291
387
|
catch (error) {
|
|
388
|
+
if (isAborted())
|
|
389
|
+
return { html: '' }
|
|
292
390
|
return { html: renderError(error), error }
|
|
293
391
|
}
|
|
294
392
|
}
|