prunelle 0.1.1 → 0.7.2
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 +373 -0
- package/src/a11y/index.ts +477 -0
- package/src/a11y/rgaa-map.ts +230 -0
- package/src/attrs.ts +11 -3
- package/src/build/bundle.ts +89 -41
- 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 +238 -0
- package/src/build/files.ts +15 -0
- package/src/build/first-load.ts +85 -14
- package/src/build/graph.ts +29 -39
- package/src/build/index.ts +225 -122
- package/src/build/island-promote.ts +311 -0
- package/src/build/islands.ts +14 -203
- package/src/build/manifest.ts +56 -116
- package/src/build/output.ts +3 -6
- package/src/build/plugin-host.ts +115 -41
- package/src/build/precompress.ts +16 -3
- package/src/build/prerender.ts +177 -39
- package/src/build/reach.ts +200 -0
- package/src/build/render-rules.ts +2 -2
- package/src/build/report.ts +48 -5
- package/src/build/resolve.ts +8 -6
- package/src/build/routes.ts +175 -10
- package/src/build/static-headers.ts +112 -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 +636 -0
- package/src/cli/check-imports.ts +31 -0
- package/src/cli/check-links.ts +632 -0
- package/src/cli/check-security.ts +64 -0
- package/src/cli/check.ts +101 -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 -22
- package/src/compiler/analyze.ts +87 -54
- package/src/compiler/browser-globals.ts +140 -17
- package/src/compiler/cacheability-private.ts +566 -0
- package/src/compiler/cacheability.ts +335 -0
- package/src/compiler/compliance-eco.ts +71 -0
- package/src/compiler/compliance-rgaa.ts +614 -0
- package/src/compiler/compliance-urls.ts +148 -0
- package/src/compiler/compliance.ts +407 -352
- 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 +260 -81
- package/src/compiler/foreign-imports.ts +88 -0
- package/src/compiler/mistakes.ts +23 -2
- package/src/compiler/props-body.ts +60 -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/spread-handlers.ts +295 -0
- 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 +32 -0
- package/src/dev/index.ts +94 -34
- package/src/dev/open-editor.ts +228 -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 +57 -40
- package/src/dom/index.ts +54 -14
- package/src/dom/island.ts +102 -68
- package/src/dom/loop.ts +66 -32
- package/src/eco/declaration.ts +328 -0
- package/src/eco/index.ts +69 -0
- package/src/index.ts +2 -2
- package/src/jsx-runtime.ts +2 -2
- package/src/plugins/config.ts +18 -12
- package/src/plugins/context.ts +44 -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 +64 -20
- 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 +188 -152
- 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 +308 -65
- package/src/server/form-schema.ts +337 -0
- package/src/server/health.ts +275 -0
- package/src/server/http.ts +186 -39
- package/src/server/index.ts +272 -273
- package/src/server/loader.ts +15 -2
- package/src/server/page.ts +15 -0
- 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 +541 -0
- package/src/server/route-table.ts +356 -11
- 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 +279 -52
- package/src/server/serve-handlers.ts +31 -7
- package/src/server/standard-schema.ts +17 -0
- package/src/server/start.ts +60 -16
- package/src/server/static-dir.ts +91 -12
- package/src/server/stream.ts +68 -27
- package/src/ssr/consent-banner.ts +58 -0
- package/src/ssr/context.ts +106 -8
- package/src/ssr/index.ts +151 -4
- package/src/ssr/navigation.ts +2 -2
- package/src/ssr/region.ts +40 -19
- package/src/style.ts +64 -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/start.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
// `prunelle start`: serves the built app, and reloads it in-process when a `prunelle build` swaps a new outDir in, so a deploy needs no restart.
|
|
2
2
|
|
|
3
|
-
import type { FSWatcher } from 'node:fs'
|
|
4
3
|
import type { PrunelleApp, PrunelleServer } from './http'
|
|
5
4
|
import { existsSync, readdirSync, watch } from 'node:fs'
|
|
6
5
|
import { basename, dirname, join, relative } from 'node:path'
|
|
@@ -15,17 +14,27 @@ export interface StartOptions {
|
|
|
15
14
|
hostname: string
|
|
16
15
|
}
|
|
17
16
|
|
|
17
|
+
async function disposeApp(app: PrunelleApp): Promise<void> {
|
|
18
|
+
try {
|
|
19
|
+
await app.closeStreams?.()
|
|
20
|
+
await app.dispose?.()
|
|
21
|
+
}
|
|
22
|
+
catch (err) {
|
|
23
|
+
console.error('prunelle start: failed to dispose previous build:', err)
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
18
27
|
/** The server, and an app that forwards to whichever build it serves, for `handleSignals()`. */
|
|
19
28
|
export async function startServer(options: StartOptions): Promise<{ app: PrunelleApp, server: PrunelleServer }> {
|
|
20
29
|
const first = await startBuiltApp({ root: options.root })
|
|
21
30
|
let current = first.app
|
|
22
31
|
const server = current.serve(options.port, options.hostname)
|
|
23
32
|
const app: PrunelleApp = {
|
|
24
|
-
handle: async (request, remoteIp) => current.handle(request, remoteIp),
|
|
33
|
+
handle: async (request, remoteIp, disableTimeout) => current.handle(request, remoteIp, disableTimeout),
|
|
25
34
|
serve: () => server,
|
|
26
35
|
closeStreams: async () => current.closeStreams?.(),
|
|
27
36
|
dispose: async () => {
|
|
28
|
-
watcher?.
|
|
37
|
+
watcher?.stop()
|
|
29
38
|
await current.dispose?.()
|
|
30
39
|
},
|
|
31
40
|
}
|
|
@@ -36,58 +45,82 @@ export async function startServer(options: StartOptions): Promise<{ app: Prunell
|
|
|
36
45
|
}
|
|
37
46
|
|
|
38
47
|
/** Watches the folder holding `outDir` for the rename a build's swap makes, then loads the new build and swaps its handlers in. */
|
|
39
|
-
function watchSwaps(outDir: string, isStatic: boolean, current: () => PrunelleApp, setCurrent: (app: PrunelleApp) => void, root: string, server: PrunelleServer):
|
|
48
|
+
function watchSwaps(outDir: string, isStatic: boolean, current: () => PrunelleApp, setCurrent: (app: PrunelleApp) => void, root: string, server: PrunelleServer): { stop: () => void } {
|
|
40
49
|
const name = basename(outDir)
|
|
41
50
|
const shown = relative(root, outDir) || '.'
|
|
42
51
|
// A `--static` export has no manifest: the folder being back with files in it is the sign.
|
|
43
52
|
const landed = (): boolean => existsSync(join(outDir, 'manifest.json')) || (isStatic && existsSync(outDir) && readdirSync(outDir).length > 0)
|
|
44
|
-
let held: { promise: Promise<PrunelleApp>, resolve: (app: PrunelleApp) => void } | undefined
|
|
53
|
+
let held: { promise: Promise<PrunelleApp>, resolve: (app: PrunelleApp) => void, reject: (err: unknown) => void } | undefined
|
|
45
54
|
let loading = false
|
|
46
55
|
let again = false
|
|
56
|
+
let disposed = false
|
|
47
57
|
let timer: ReturnType<typeof setTimeout> | undefined
|
|
48
58
|
|
|
49
59
|
// From the first rename until the new build answers, requests wait for it: no page of the old build links an asset the new one dropped.
|
|
50
60
|
const hold = (): void => {
|
|
51
|
-
if (held !== undefined)
|
|
61
|
+
if (held !== undefined || disposed)
|
|
52
62
|
return
|
|
53
|
-
const { promise, resolve } = Promise.withResolvers<PrunelleApp>()
|
|
54
|
-
|
|
55
|
-
|
|
63
|
+
const { promise, resolve, reject } = Promise.withResolvers<PrunelleApp>()
|
|
64
|
+
void promise.catch(() => undefined)
|
|
65
|
+
held = { promise, resolve, reject }
|
|
66
|
+
server.reload({
|
|
67
|
+
routes: {},
|
|
68
|
+
fetch: async (request: Request) => {
|
|
69
|
+
let target: PrunelleApp
|
|
70
|
+
try {
|
|
71
|
+
target = await promise
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
return new Response('Service Unavailable', { status: 503, headers: { ...current().securityHeaders, 'content-type': 'text/plain; charset=utf-8' } })
|
|
75
|
+
}
|
|
76
|
+
return target.handle(request, server.requestIP(request)?.address, () => server.timeout(request, 0))
|
|
77
|
+
},
|
|
78
|
+
})
|
|
56
79
|
}
|
|
57
80
|
|
|
58
81
|
const swapIn = async (): Promise<void> => {
|
|
82
|
+
if (disposed)
|
|
83
|
+
return
|
|
59
84
|
if (loading) {
|
|
60
85
|
again = true
|
|
61
86
|
return
|
|
62
87
|
}
|
|
63
88
|
loading = true
|
|
64
89
|
const prev = current()
|
|
90
|
+
let loaded: PrunelleApp | undefined
|
|
65
91
|
try {
|
|
66
92
|
if (!landed())
|
|
67
93
|
throw new Error(isStatic ? `${shown}/ is missing or empty` : `${shown}/manifest.json is missing`)
|
|
68
|
-
|
|
94
|
+
loaded = (await startBuiltApp({ root, outDir })).app
|
|
95
|
+
if (disposed) {
|
|
96
|
+
await disposeApp(loaded)
|
|
97
|
+
loading = false
|
|
98
|
+
return
|
|
99
|
+
}
|
|
100
|
+
setCurrent(loaded)
|
|
69
101
|
console.log(`prunelle start: serving the new build in ${shown}/`)
|
|
70
102
|
}
|
|
71
103
|
catch (err) {
|
|
72
104
|
console.error(`prunelle start: the build in ${shown}/ failed to load, so the previous one keeps answering: ${err instanceof Error ? err.message : String(err)}`)
|
|
73
105
|
}
|
|
74
106
|
loading = false
|
|
107
|
+
const swapped = loaded !== undefined && current() !== prev
|
|
75
108
|
if (again) {
|
|
76
109
|
again = false
|
|
110
|
+
if (swapped)
|
|
111
|
+
void disposeApp(prev)
|
|
77
112
|
void swapIn()
|
|
78
113
|
return
|
|
79
114
|
}
|
|
80
115
|
current().reloadInto!(server)
|
|
81
116
|
held?.resolve(current())
|
|
82
117
|
held = undefined
|
|
83
|
-
if (
|
|
84
|
-
await prev
|
|
85
|
-
await prev.dispose?.()
|
|
86
|
-
}
|
|
118
|
+
if (swapped)
|
|
119
|
+
await disposeApp(prev)
|
|
87
120
|
}
|
|
88
121
|
|
|
89
122
|
const watcher = watch(dirname(outDir), (_event, file) => {
|
|
90
|
-
if (file !== name)
|
|
123
|
+
if (file !== name || disposed)
|
|
91
124
|
return
|
|
92
125
|
hold()
|
|
93
126
|
clearTimeout(timer)
|
|
@@ -95,5 +128,16 @@ function watchSwaps(outDir: string, isStatic: boolean, current: () => PrunelleAp
|
|
|
95
128
|
timer = setTimeout(() => void swapIn(), landed() ? 0 : SWAP_TIMEOUT_MS)
|
|
96
129
|
})
|
|
97
130
|
watcher.on('error', err => console.error(`prunelle start: stopped watching ${shown}/ for new builds: ${err.message}`))
|
|
98
|
-
return
|
|
131
|
+
return {
|
|
132
|
+
stop() {
|
|
133
|
+
disposed = true
|
|
134
|
+
clearTimeout(timer)
|
|
135
|
+
timer = undefined
|
|
136
|
+
watcher.close()
|
|
137
|
+
if (held !== undefined) {
|
|
138
|
+
held.reject(new Error('prunelle start: server disposed while reloading build'))
|
|
139
|
+
held = undefined
|
|
140
|
+
}
|
|
141
|
+
},
|
|
142
|
+
}
|
|
99
143
|
}
|
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,42 @@ 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
|
+
httpsSite?: boolean | undefined
|
|
38
|
+
nodeEnv?: string | undefined
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function findNotFound(rel: string | undefined, byDir: ReadonlyMap<string, ServedFile>): ServedFile | undefined {
|
|
42
|
+
if (byDir.size === 0)
|
|
43
|
+
return undefined
|
|
44
|
+
if (rel !== undefined && rel !== '') {
|
|
45
|
+
let dir = rel
|
|
46
|
+
while (true) {
|
|
47
|
+
const hit = byDir.get(dir)
|
|
48
|
+
if (hit !== undefined)
|
|
49
|
+
return hit
|
|
50
|
+
const slash = dir.lastIndexOf('/')
|
|
51
|
+
if (slash === -1)
|
|
52
|
+
break
|
|
53
|
+
dir = dir.slice(0, slash)
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return byDir.get('')
|
|
57
|
+
}
|
|
58
|
+
|
|
18
59
|
|
|
19
60
|
/** The files under `absRoot` by their path from it, `/`-separated; a symlink counts only when it lands on a file inside `realRoot`. */
|
|
20
61
|
function listFiles(absRoot: string, realRoot: string): Map<string, string> {
|
|
@@ -53,6 +94,7 @@ export function createStaticDirServer(
|
|
|
53
94
|
compressEnabled: boolean,
|
|
54
95
|
trustProxy: TrustProxy,
|
|
55
96
|
isDev = false,
|
|
97
|
+
extra?: StaticDirExtraOptions,
|
|
56
98
|
): PrunelleApp {
|
|
57
99
|
const prefix = assetPrefix.replace(/^\/+/, '').replace(/\/$/, '')
|
|
58
100
|
const absRoot = resolve(outDir)
|
|
@@ -67,16 +109,39 @@ export function createStaticDirServer(
|
|
|
67
109
|
const securityEntries = buildSecurityHeaderEntries(security)
|
|
68
110
|
const securityRecord = Object.fromEntries(securityEntries)
|
|
69
111
|
const baseCsp = resolveCspPolicy(security)
|
|
70
|
-
const
|
|
112
|
+
const nav = extra !== undefined ? createNavigation(extra.navigation) : undefined
|
|
113
|
+
const plugins = extra?.plugins !== undefined ? resolvePlugins(extra.plugins) : []
|
|
114
|
+
const extraStyleHashes = [PRUNELLE_ISLAND_STYLE_HASH, ...(nav?.styleHashes ?? [])]
|
|
115
|
+
const extraScriptHashes = [
|
|
116
|
+
...(nav?.scriptHashes ?? []),
|
|
117
|
+
...plugins.flatMap(p => p.inlineScripts ?? []).map(cspSha256),
|
|
118
|
+
]
|
|
119
|
+
const htmlCsp = baseCsp !== undefined
|
|
120
|
+
? withCspHashes(baseCsp, { styleHashes: extraStyleHashes, scriptHashes: extraScriptHashes })
|
|
121
|
+
: undefined
|
|
122
|
+
const httpsSite = !isDev && extra?.httpsSite === true
|
|
71
123
|
const hstsValue = resolveHstsValue(security)
|
|
72
124
|
const withHsts = hstsValue === undefined || isDev
|
|
73
125
|
? (res: Response) => res
|
|
74
|
-
: (res: Response, req: Request) => applyHstsHeader(res, req, hstsValue, trustProxy, isDev)
|
|
75
|
-
const
|
|
126
|
+
: (res: Response, req: Request) => applyHstsHeader(res, req, hstsValue, trustProxy, isDev, extra?.nodeEnv, httpsSite)
|
|
127
|
+
const serveFileUnguarded = createFileServer({ compressEnabled, compressCache, withHsts })
|
|
128
|
+
const notifyError = createErrorNotifier(extra?.onError, plugins, { dev: isDev, sink: extra?.errorSink })
|
|
129
|
+
// A file that fails to open answers here, where the request is known: gone since the listing is a 404, anything else is reported.
|
|
130
|
+
const serveFile = async (req: Request, file: ServedFile, status?: number): Promise<Response> => {
|
|
131
|
+
try {
|
|
132
|
+
return await serveFileUnguarded(req, file, status)
|
|
133
|
+
}
|
|
134
|
+
catch (err) {
|
|
135
|
+
if (err instanceof Error && 'code' in err && err.code === 'ENOENT')
|
|
136
|
+
return withHsts(new Response('Not Found', { status: 404, headers: { 'cache-control': 'no-store', ...securityRecord } }), req)
|
|
137
|
+
notifyError(err, req, 'route')
|
|
138
|
+
return error()
|
|
139
|
+
}
|
|
140
|
+
}
|
|
76
141
|
|
|
77
142
|
function entryFor(rel: string, path: string, all: ReadonlyMap<string, string>): ServedFile {
|
|
78
143
|
const ext = extname(rel).toLowerCase()
|
|
79
|
-
const type = MIME[ext] ?? 'application/octet-stream'
|
|
144
|
+
const type = MIME[ext] ?? EXTRA_STATIC_MIME[ext] ?? 'application/octet-stream'
|
|
80
145
|
const isHtml = ext === '.html' || ext === '.htm'
|
|
81
146
|
// An exported page's CSP gains the hashes of its own `<style>` blocks.
|
|
82
147
|
const csp = isHtml && htmlCsp !== undefined ? withCspHashes(htmlCsp, { styleHashes: inlineStyleHashes(readFileSync(path, 'utf8')) }) : undefined
|
|
@@ -100,11 +165,18 @@ export function createStaticDirServer(
|
|
|
100
165
|
}
|
|
101
166
|
|
|
102
167
|
// 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>,
|
|
168
|
+
function buildTable(): { table: Map<string, ServedFile>, notFoundByDir: Map<string, ServedFile> } {
|
|
104
169
|
const files = listFiles(absRoot, realRoot)
|
|
105
170
|
const table = new Map<string, ServedFile>()
|
|
106
|
-
|
|
107
|
-
|
|
171
|
+
const notFoundByDir = new Map<string, ServedFile>()
|
|
172
|
+
for (const [rel, path] of files) {
|
|
173
|
+
const entry = entryFor(rel, path, files)
|
|
174
|
+
table.set(rel, entry)
|
|
175
|
+
if (rel === '404.html')
|
|
176
|
+
notFoundByDir.set('', entry)
|
|
177
|
+
else if (rel.endsWith('/404.html'))
|
|
178
|
+
notFoundByDir.set(rel.slice(0, -'/404.html'.length), entry)
|
|
179
|
+
}
|
|
108
180
|
for (const [rel, entry] of [...table]) {
|
|
109
181
|
if (rel.endsWith('.html') && !table.has(rel.slice(0, -5)))
|
|
110
182
|
table.set(rel.slice(0, -5), entry)
|
|
@@ -116,7 +188,7 @@ export function createStaticDirServer(
|
|
|
116
188
|
table.set(dir, entry)
|
|
117
189
|
}
|
|
118
190
|
}
|
|
119
|
-
return { table,
|
|
191
|
+
return { table, notFoundByDir }
|
|
120
192
|
}
|
|
121
193
|
|
|
122
194
|
let current = buildTable()
|
|
@@ -141,8 +213,9 @@ export function createStaticDirServer(
|
|
|
141
213
|
const found = rel === undefined ? undefined : current.table.get(rel)
|
|
142
214
|
if (found !== undefined)
|
|
143
215
|
return serveFile(req, found)
|
|
144
|
-
|
|
145
|
-
|
|
216
|
+
const notFound = findNotFound(rel, current.notFoundByDir)
|
|
217
|
+
if (notFound !== undefined)
|
|
218
|
+
return serveFile(req, notFound, 404)
|
|
146
219
|
return withHsts(new Response('Not Found', { status: 404, headers: securityRecord }), req)
|
|
147
220
|
}
|
|
148
221
|
|
|
@@ -150,14 +223,20 @@ export function createStaticDirServer(
|
|
|
150
223
|
status: 500,
|
|
151
224
|
headers: { 'content-type': 'text/plain; charset=utf-8', ...securityRecord },
|
|
152
225
|
})
|
|
226
|
+
// What escapes `serveFile` (a body stream failing after its headers) reaches `Bun.serve` without a request: logged, never silent.
|
|
227
|
+
const lastResort = (err: Error): Response => {
|
|
228
|
+
console.error('prunelle start: unhandled error while serving a file', err)
|
|
229
|
+
return error()
|
|
230
|
+
}
|
|
153
231
|
|
|
154
232
|
return {
|
|
155
233
|
handle,
|
|
234
|
+
securityHeaders: securityRecord,
|
|
156
235
|
serve(port = 3000, hostname = '127.0.0.1') {
|
|
157
|
-
return Bun.serve({ port, hostname, idleTimeout: 30, development: false, fetch: handle, error })
|
|
236
|
+
return Bun.serve({ port, hostname, idleTimeout: 30, development: false, fetch: handle, error: lastResort })
|
|
158
237
|
},
|
|
159
238
|
reloadInto(server: PrunelleServer) {
|
|
160
|
-
server.reload({ routes: {}, fetch: handle, error })
|
|
239
|
+
server.reload({ routes: {}, fetch: handle, error: lastResort })
|
|
161
240
|
},
|
|
162
241
|
async dispose() {
|
|
163
242
|
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
|
+
}
|