prunelle 0.0.0-stage → 0.2.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 +148 -0
- package/package.json +53 -4
- package/src/ambient.d.ts +6 -0
- package/src/attrs.ts +35 -0
- package/src/build/bundle.ts +613 -0
- package/src/build/carry.ts +57 -0
- package/src/build/client-entries.ts +107 -0
- package/src/build/client-plugin.ts +169 -0
- package/src/build/client-prune.ts +118 -0
- package/src/build/compile.ts +128 -0
- package/src/build/files.ts +156 -0
- package/src/build/first-load.ts +164 -0
- package/src/build/graph.ts +247 -0
- package/src/build/index.ts +614 -0
- package/src/build/is-inside.ts +12 -0
- package/src/build/islands.ts +641 -0
- package/src/build/manifest.ts +281 -0
- package/src/build/output.ts +84 -0
- package/src/build/plugin-host.ts +220 -0
- package/src/build/precompress.ts +139 -0
- package/src/build/prerender.ts +150 -0
- package/src/build/render-rules.ts +205 -0
- package/src/build/report.ts +247 -0
- package/src/build/resolve.ts +50 -0
- package/src/build/routes.ts +338 -0
- package/src/build/server-entry.ts +38 -0
- package/src/build/static.ts +163 -0
- package/src/build/status-pages.ts +127 -0
- package/src/cli/check-forms.ts +654 -0
- package/src/cli/check-links.ts +619 -0
- package/src/cli/check.ts +367 -0
- package/src/cli/commands.ts +265 -0
- package/src/cli/index.ts +70 -0
- package/src/cli/inspect.ts +335 -0
- package/src/cli/new.ts +41 -0
- package/src/cli/upgrade-names.ts +209 -0
- package/src/cli/upgrade.ts +354 -0
- package/src/compiler/analyze.ts +618 -0
- package/src/compiler/ast.ts +82 -0
- package/src/compiler/browser-globals.ts +127 -0
- package/src/compiler/compliance-rgaa.ts +502 -0
- package/src/compiler/compliance.ts +497 -0
- package/src/compiler/data-keys.ts +295 -0
- package/src/compiler/dom-attrs.ts +379 -0
- package/src/compiler/dom.ts +566 -0
- package/src/compiler/emit.ts +131 -0
- package/src/compiler/expr-context.ts +408 -0
- package/src/compiler/index.ts +8 -0
- package/src/compiler/interactivity.ts +366 -0
- package/src/compiler/mistakes.ts +499 -0
- package/src/compiler/node-env.ts +50 -0
- package/src/compiler/patch.ts +97 -0
- package/src/compiler/props.ts +460 -0
- package/src/compiler/scope.ts +568 -0
- package/src/compiler/server-only.ts +326 -0
- package/src/compiler/shared.ts +369 -0
- package/src/compiler/signal-reads.ts +242 -0
- package/src/compiler/slots.ts +227 -0
- package/src/compiler/ssr-helpers.ts +555 -0
- package/src/compiler/ssr-island.ts +90 -0
- package/src/compiler/ssr-prunelle-tags.ts +56 -0
- package/src/compiler/ssr.ts +491 -0
- package/src/context.ts +165 -0
- package/src/dev/child.ts +30 -0
- package/src/dev/index.ts +208 -0
- package/src/dev/modules.ts +68 -0
- package/src/dev/protocol.ts +21 -0
- package/src/dev/queue.ts +79 -0
- package/src/dev/reload.ts +157 -0
- package/src/dev/supervisor.ts +187 -0
- package/src/dev/watchers.ts +215 -0
- package/src/dom/action.ts +164 -0
- package/src/dom/attrs.ts +72 -0
- package/src/dom/claim.ts +120 -0
- package/src/dom/extras.ts +562 -0
- package/src/dom/index.ts +289 -0
- package/src/dom/island.ts +284 -0
- package/src/dom/loop.ts +450 -0
- package/src/dom/revive.ts +36 -0
- package/src/index.ts +22 -0
- package/src/jsx-runtime.ts +566 -0
- package/src/plugins/config.ts +86 -0
- package/src/plugins/context.ts +66 -0
- package/src/plugins/index.ts +14 -0
- package/src/plugins/load.ts +70 -0
- package/src/plugins/order.ts +111 -0
- package/src/plugins/public.ts +12 -0
- package/src/plugins/requires.ts +47 -0
- package/src/plugins/services.ts +35 -0
- package/src/plugins/types.ts +242 -0
- package/src/reactivity/graph.ts +249 -0
- package/src/reactivity/index.ts +533 -0
- package/src/reactivity/selector.ts +51 -0
- package/src/reactivity/store.ts +208 -0
- package/src/server/action-protect.ts +186 -0
- package/src/server/action-registry.ts +78 -0
- package/src/server/action.ts +498 -0
- package/src/server/app-entry.ts +23 -0
- package/src/server/assets.ts +136 -0
- package/src/server/compress.ts +560 -0
- package/src/server/consent.ts +253 -0
- package/src/server/cookies.ts +139 -0
- package/src/server/document.ts +271 -0
- package/src/server/env.ts +33 -0
- package/src/server/errors.ts +382 -0
- package/src/server/form-schema.ts +343 -0
- package/src/server/health.ts +244 -0
- package/src/server/http.ts +508 -0
- package/src/server/index.ts +687 -0
- package/src/server/lifecycle.ts +75 -0
- package/src/server/loader.ts +118 -0
- package/src/server/page.ts +107 -0
- package/src/server/param-matchers.ts +112 -0
- package/src/server/plugin-host.ts +256 -0
- package/src/server/prerendered.ts +71 -0
- package/src/server/public.ts +19 -0
- package/src/server/rate-limit.ts +133 -0
- package/src/server/region.ts +96 -0
- package/src/server/request-body.ts +27 -0
- package/src/server/request-path.ts +73 -0
- package/src/server/request-scope.ts +22 -0
- package/src/server/route-table.ts +82 -0
- package/src/server/router.ts +261 -0
- package/src/server/routing.ts +377 -0
- package/src/server/security.ts +472 -0
- package/src/server/serve-handlers.ts +83 -0
- package/src/server/served-file.ts +128 -0
- package/src/server/standard-schema.ts +87 -0
- package/src/server/start.ts +99 -0
- package/src/server/static-dir.ts +167 -0
- package/src/server/stream.ts +192 -0
- package/src/ssr/context.ts +350 -0
- package/src/ssr/index.ts +596 -0
- package/src/ssr/navigation.ts +96 -0
- package/src/ssr/region.ts +171 -0
- package/src/style.ts +33 -0
- package/src/test/browser.ts +192 -0
- package/src/test/index.ts +191 -0
- package/src/unrenderable.ts +35 -0
- package/templates/_shared/AGENTS.md +10 -0
- package/templates/_shared/CLAUDE.md +1 -0
- package/templates/_shared/gitignore +3 -0
- package/templates/_shared/public/robots.txt +2 -0
- package/templates/_shared/src/routes/legal.tsx +13 -0
- package/templates/_shared/tsconfig.json +20 -0
- package/templates/app/.env.example +4 -0
- package/templates/app/package.json +21 -0
- package/templates/app/prunelle.config.ts +11 -0
- package/templates/app/src/auth.ts +14 -0
- package/templates/app/src/routes/_layout.tsx +32 -0
- package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
- package/templates/app/src/routes/dashboard/index.tsx +13 -0
- package/templates/app/src/routes/index.tsx +15 -0
- package/templates/app/src/routes/login.tsx +34 -0
- package/templates/app/src/styles/app.css +7 -0
- package/templates/app/tests/app.test.ts +32 -0
- package/templates/blog/content/posts/welcome.md +9 -0
- package/templates/blog/package.json +22 -0
- package/templates/blog/prunelle.config.ts +23 -0
- package/templates/blog/src/posts.ts +26 -0
- package/templates/blog/src/routes/_layout.tsx +20 -0
- package/templates/blog/src/routes/blog/[slug].tsx +31 -0
- package/templates/blog/src/routes/index.tsx +33 -0
- package/templates/blog/src/styles/app.css +10 -0
- package/templates/fullstack/package.json +19 -0
- package/templates/fullstack/prunelle.config.ts +6 -0
- package/templates/fullstack/src/actions/greet.ts +19 -0
- package/templates/fullstack/src/components/Counter.tsx +10 -0
- package/templates/fullstack/src/components/GreetForm.tsx +27 -0
- package/templates/fullstack/src/routes/_layout.tsx +14 -0
- package/templates/fullstack/src/routes/api/health.ts +5 -0
- package/templates/fullstack/src/routes/index.tsx +13 -0
- package/templates/fullstack/src/styles/app.css +29 -0
- package/templates/fullstack/tests/app.test.ts +37 -0
- package/templates/minimal/package.json +19 -0
- package/templates/minimal/prunelle.config.ts +6 -0
- package/templates/minimal/src/components/Counter.tsx +10 -0
- package/templates/minimal/src/routes/_layout.tsx +14 -0
- package/templates/minimal/src/routes/index.tsx +11 -0
- package/templates/minimal/src/styles/app.css +22 -0
- package/README.md +0 -3
|
@@ -0,0 +1,508 @@
|
|
|
1
|
+
// HTTP helpers, MIME table, RequestContext factory, and island tag scanner for Prunelle server.
|
|
2
|
+
|
|
3
|
+
import type { BuildManifest } from '../build/index'
|
|
4
|
+
import type { PrunelleChild } from '../jsx-runtime'
|
|
5
|
+
import type { ServerErrorInfo, ServerRuntimeConfig } from '../plugins/index'
|
|
6
|
+
import type { NormalizedConsentConfig, RequestConsent } from './consent'
|
|
7
|
+
import type { Cookies } from './cookies'
|
|
8
|
+
import type { PrunelleLocals } from './index'
|
|
9
|
+
import type { TrustProxy } from './security'
|
|
10
|
+
import { createRequestConsent } from './consent'
|
|
11
|
+
import { CookieStore } from './cookies'
|
|
12
|
+
import { nodeEnv } from './env'
|
|
13
|
+
import { resolveFallbackRequestId } from './health'
|
|
14
|
+
import { requestedRegion } from './region'
|
|
15
|
+
import { getClientIp, isHttpsRequest } from './security'
|
|
16
|
+
|
|
17
|
+
export const DEFAULT_MAX_REQUEST_BODY_SIZE = 1024 * 1024
|
|
18
|
+
|
|
19
|
+
const NOT_FOUND_SYMBOL = Symbol.for('pru.notFound')
|
|
20
|
+
declare const NOT_FOUND_BRAND: unique symbol
|
|
21
|
+
|
|
22
|
+
export interface NotFoundResult {
|
|
23
|
+
readonly [NOT_FOUND_BRAND]: true
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Return (or throw) from `load()` to render `_404.tsx` with HTTP status 404. */
|
|
27
|
+
export function notFound(): NotFoundResult {
|
|
28
|
+
return { [NOT_FOUND_SYMBOL]: true } as unknown as NotFoundResult
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function isNotFound(value: unknown): value is NotFoundResult {
|
|
32
|
+
return typeof value === 'object' && value !== null && (value as Record<symbol, unknown>)[NOT_FOUND_SYMBOL] === true
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Maps built-in (and augmented) route param matcher names to their TypeScript param value types. */
|
|
36
|
+
export interface ParamMatcherTypes {
|
|
37
|
+
integer: `${number}`
|
|
38
|
+
uuid: `${string}-${string}-${string}-${string}-${string}`
|
|
39
|
+
slug: string
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
type MatcherValue<Name extends string> = Name extends keyof ParamMatcherTypes ? ParamMatcherTypes[Name] : string
|
|
43
|
+
|
|
44
|
+
type ParseParamSpec<Spec extends string> =
|
|
45
|
+
Spec extends `${infer Name}=${infer Matcher}`
|
|
46
|
+
? [Name, MatcherValue<Matcher>]
|
|
47
|
+
: [Spec, string]
|
|
48
|
+
|
|
49
|
+
type SegmentParam<Seg extends string> =
|
|
50
|
+
Seg extends `(${string})`
|
|
51
|
+
? unknown
|
|
52
|
+
: Seg extends `[[${infer Spec}]]`
|
|
53
|
+
? { [K in ParseParamSpec<Spec>[0]]?: ParseParamSpec<Spec>[1] | undefined }
|
|
54
|
+
: Seg extends `[...${infer Spec}]`
|
|
55
|
+
? { [K in ParseParamSpec<Spec>[0]]: string }
|
|
56
|
+
: Seg extends `[${infer Spec}]`
|
|
57
|
+
? { [K in ParseParamSpec<Spec>[0]]: ParseParamSpec<Spec>[1] }
|
|
58
|
+
: Seg extends `*${infer Spec}`
|
|
59
|
+
? { [K in ParseParamSpec<Spec>[0] extends '' ? 'rest' : ParseParamSpec<Spec>[0]]: string }
|
|
60
|
+
: Seg extends `:${infer Spec}?`
|
|
61
|
+
? { [K in ParseParamSpec<Spec>[0]]?: ParseParamSpec<Spec>[1] | undefined }
|
|
62
|
+
: Seg extends `:${infer Spec}`
|
|
63
|
+
? { [K in ParseParamSpec<Spec>[0]]: ParseParamSpec<Spec>[1] }
|
|
64
|
+
: unknown
|
|
65
|
+
|
|
66
|
+
type MergeParams<A, B> = unknown extends B
|
|
67
|
+
? A
|
|
68
|
+
: { [K in keyof (Omit<A, keyof B> & B)]: (Omit<A, keyof B> & B)[K] }
|
|
69
|
+
|
|
70
|
+
type ExtractRouteParamsRec<Path extends string, Acc = {}> =
|
|
71
|
+
Path extends `${infer Seg}/${infer Rest}`
|
|
72
|
+
? ExtractRouteParamsRec<Rest, Seg extends '' ? Acc : MergeParams<Acc, SegmentParam<Seg>>>
|
|
73
|
+
: Path extends ''
|
|
74
|
+
? Acc
|
|
75
|
+
: MergeParams<Acc, SegmentParam<Path>>
|
|
76
|
+
|
|
77
|
+
/** Extracts typed route params from a Prunelle route path (`'/notices/[id=integer]'` -> `{ id: `${number}` }`, `'/[[lang]]/about'` -> `{ lang?: string | undefined }`, `'/docs/[...rest]'` -> `{ rest: string }`). */
|
|
78
|
+
export type ExtractRouteParams<Path extends string> =
|
|
79
|
+
string extends Path
|
|
80
|
+
? Record<string, string>
|
|
81
|
+
: ExtractRouteParamsRec<Path>
|
|
82
|
+
|
|
83
|
+
export type LoaderFn = (...args: never[]) => unknown
|
|
84
|
+
|
|
85
|
+
/** Infers the resolved page `data` type returned by a route's `load()` function, excluding `Response` and `notFound()`. */
|
|
86
|
+
export type LoaderData<T extends LoaderFn> = Exclude<Awaited<ReturnType<T>>, Response | NotFoundResult>
|
|
87
|
+
|
|
88
|
+
type InferLoaderParams<T extends LoaderFn> =
|
|
89
|
+
Parameters<T> extends [ctx: { params: infer P }, ...unknown[]]
|
|
90
|
+
? P
|
|
91
|
+
: Record<string, string>
|
|
92
|
+
|
|
93
|
+
/** Props passed to a Prunelle route page component. Pass `typeof load` to infer `data` (and `params` when `load` uses `RouteContext<Path>`), or a route path string when there is no `load`. */
|
|
94
|
+
export type PageProps<
|
|
95
|
+
TLoadOrPath extends LoaderFn | string | undefined = undefined,
|
|
96
|
+
TPath extends string = string,
|
|
97
|
+
> = {
|
|
98
|
+
params: TLoadOrPath extends string
|
|
99
|
+
? ExtractRouteParams<TLoadOrPath>
|
|
100
|
+
: string extends TPath
|
|
101
|
+
? (TLoadOrPath extends LoaderFn ? InferLoaderParams<TLoadOrPath> : Record<string, string>)
|
|
102
|
+
: ExtractRouteParams<TPath>
|
|
103
|
+
locals: PrunelleLocals
|
|
104
|
+
url: URL
|
|
105
|
+
} & (TLoadOrPath extends LoaderFn ? { data: LoaderData<TLoadOrPath> } : { data?: undefined })
|
|
106
|
+
|
|
107
|
+
/** Props passed to a Prunelle `_layout.tsx` component. */
|
|
108
|
+
export interface LayoutProps<Path extends string = string> {
|
|
109
|
+
children: PrunelleChild
|
|
110
|
+
params: ExtractRouteParams<Path>
|
|
111
|
+
locals: PrunelleLocals
|
|
112
|
+
url: URL
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Props passed to a Prunelle status page (`_401.tsx`, `_403.tsx`, `_404.tsx`, `_429.tsx`, `_503.tsx`). */
|
|
116
|
+
export interface StatusPageProps<Path extends string = string> {
|
|
117
|
+
status: number
|
|
118
|
+
message: string
|
|
119
|
+
params: ExtractRouteParams<Path>
|
|
120
|
+
locals: PrunelleLocals
|
|
121
|
+
url: URL
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export interface ServerOptions extends ServerRuntimeConfig {
|
|
125
|
+
root: string
|
|
126
|
+
outDir?: string | undefined
|
|
127
|
+
port?: number | undefined
|
|
128
|
+
dev?: boolean | undefined
|
|
129
|
+
nodeEnv?: string | undefined
|
|
130
|
+
/** @internal Imports a built server module by absolute path; `prunelle dev` passes one that keeps unchanged modules loaded. */
|
|
131
|
+
importModule?: ((path: string) => Promise<Record<string, unknown>>) | undefined
|
|
132
|
+
/** @internal Hears every unhandled route, action and plugin error; `testApp().errors` fills from it. */
|
|
133
|
+
errorSink?: ((info: ServerErrorInfo) => void) | undefined
|
|
134
|
+
/** @internal The build's prerender server, which runs before the production environment exists, so plugin `requires` are not checked. */
|
|
135
|
+
prerender?: boolean | undefined
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export interface RequestContext<Params = Record<string, string>> {
|
|
139
|
+
request: Request
|
|
140
|
+
url: URL
|
|
141
|
+
params: Params
|
|
142
|
+
cookies: Cookies
|
|
143
|
+
consent: RequestConsent
|
|
144
|
+
locals: PrunelleLocals
|
|
145
|
+
ip?: string | undefined
|
|
146
|
+
/** Unique identifier for this request, echoed in the `x-request-id` response header and passed to `onError`. */
|
|
147
|
+
readonly requestId: string
|
|
148
|
+
/** The region a `data-pru-target` link or form asked for alone (`x-pru-region`): `load()` can skip the data the others show. */
|
|
149
|
+
readonly region?: string | undefined
|
|
150
|
+
json: (data: unknown, init?: ResponseInit) => Response
|
|
151
|
+
text: (body: string, init?: ResponseInit) => Response
|
|
152
|
+
redirect: (location: string, status?: 301 | 302 | 303 | 307 | 308) => Response
|
|
153
|
+
deny: (status: number, message: string, fieldErrors?: Record<string, string>) => Response
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** `RequestContext` with `params` inferred from a Prunelle route pattern (e.g. `RouteContext<'/notices/[id]'>`). */
|
|
157
|
+
export type RouteContext<Path extends string = string> = RequestContext<ExtractRouteParams<Path>>
|
|
158
|
+
|
|
159
|
+
export type Middleware = (ctx: RequestContext, next: () => Promise<Response>) => Response | Promise<Response>
|
|
160
|
+
|
|
161
|
+
export type PrunelleServer = ReturnType<typeof Bun.serve>
|
|
162
|
+
|
|
163
|
+
export interface PrunelleApp {
|
|
164
|
+
handle: (request: Request, remoteIp?: string) => Promise<Response>
|
|
165
|
+
serve: (port?: number, hostname?: string) => PrunelleServer
|
|
166
|
+
/** @internal Swaps this app's handlers into a server another app started, with no dropped connection: `prunelle start` reloads a new build with it. */
|
|
167
|
+
reloadInto?: (server: PrunelleServer) => void
|
|
168
|
+
/** Closes active long-lived streams (such as SSE) before `server.stop()` drains normal in-flight HTTP requests. */
|
|
169
|
+
closeStreams?: () => Promise<void>
|
|
170
|
+
/** Runs plugin shutdown hooks and releases timers/resources (safe to call multiple times). */
|
|
171
|
+
dispose?: () => Promise<void>
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export type EmbeddedBody = Uint8Array<ArrayBuffer> | string
|
|
175
|
+
|
|
176
|
+
export interface EmbeddedServerConfig extends ServerRuntimeConfig {
|
|
177
|
+
manifest: BuildManifest
|
|
178
|
+
modules: Record<string, unknown>
|
|
179
|
+
assets: Record<string, EmbeddedBody>
|
|
180
|
+
publicAssets?: Record<string, EmbeddedBody> | undefined
|
|
181
|
+
publicEtags?: Record<string, string> | undefined
|
|
182
|
+
prerendered?: Record<string, string> | undefined
|
|
183
|
+
prerenderedFiles?: Record<string, string> | undefined
|
|
184
|
+
/** ETags of the prerendered HTML files, by the same key; a missing one comes from the file's size and mtime. */
|
|
185
|
+
prerenderedEtags?: Record<string, string> | undefined
|
|
186
|
+
root?: string | undefined
|
|
187
|
+
outDir?: string | undefined
|
|
188
|
+
publicDir?: string | undefined
|
|
189
|
+
dev?: boolean | undefined
|
|
190
|
+
nodeEnv?: string | undefined
|
|
191
|
+
errorSink?: ((info: ServerErrorInfo) => void) | undefined
|
|
192
|
+
prerender?: boolean | undefined
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
export const MIME: Record<string, string> = {
|
|
196
|
+
'.js': 'text/javascript; charset=utf-8',
|
|
197
|
+
'.mjs': 'text/javascript; charset=utf-8',
|
|
198
|
+
'.css': 'text/css; charset=utf-8',
|
|
199
|
+
'.html': 'text/html; charset=utf-8',
|
|
200
|
+
'.json': 'application/json; charset=utf-8',
|
|
201
|
+
'.webmanifest': 'application/manifest+json; charset=utf-8',
|
|
202
|
+
'.txt': 'text/plain; charset=utf-8',
|
|
203
|
+
'.xml': 'application/xml; charset=utf-8',
|
|
204
|
+
'.svg': 'image/svg+xml',
|
|
205
|
+
'.png': 'image/png',
|
|
206
|
+
'.jpg': 'image/jpeg',
|
|
207
|
+
'.jpeg': 'image/jpeg',
|
|
208
|
+
'.gif': 'image/gif',
|
|
209
|
+
'.webp': 'image/webp',
|
|
210
|
+
'.avif': 'image/avif',
|
|
211
|
+
'.ico': 'image/x-icon',
|
|
212
|
+
'.woff2': 'font/woff2',
|
|
213
|
+
'.woff': 'font/woff',
|
|
214
|
+
'.ttf': 'font/ttf',
|
|
215
|
+
'.otf': 'font/otf',
|
|
216
|
+
'.pdf': 'application/pdf',
|
|
217
|
+
'.wasm': 'application/wasm',
|
|
218
|
+
'.mp4': 'video/mp4',
|
|
219
|
+
'.webm': 'video/webm',
|
|
220
|
+
'.map': 'application/json',
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
const ISLAND_TAG_RE = /<pru-island c="([^"]+)"([^>]*)>/g
|
|
224
|
+
|
|
225
|
+
export function extractRenderedIslands(html: string): { hasIslands: boolean, eagerChunks: string[] } {
|
|
226
|
+
let hasIslands = false
|
|
227
|
+
const eager = new Set<string>()
|
|
228
|
+
ISLAND_TAG_RE.lastIndex = 0
|
|
229
|
+
let m: RegExpExecArray | null
|
|
230
|
+
while ((m = ISLAND_TAG_RE.exec(html)) !== null) {
|
|
231
|
+
hasIslands = true
|
|
232
|
+
const attrs = m[2] ?? ''
|
|
233
|
+
if (!attrs.includes(' h="'))
|
|
234
|
+
eager.add(m[1]!)
|
|
235
|
+
}
|
|
236
|
+
return { hasIslands, eagerChunks: [...eager] }
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
export interface RequestContextOptions {
|
|
240
|
+
trustProxy?: TrustProxy | undefined
|
|
241
|
+
remoteIp?: string | undefined
|
|
242
|
+
/** The parsed `request.url`, when the caller already has it. */
|
|
243
|
+
url?: URL | undefined
|
|
244
|
+
consent?: NormalizedConsentConfig | undefined
|
|
245
|
+
requestId?: string | undefined
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// None of these read the request, so every context shares them.
|
|
249
|
+
const json: RequestContext['json'] = (data, init) => {
|
|
250
|
+
const payload = JSON.stringify(data)
|
|
251
|
+
const headers = new Headers(init?.headers)
|
|
252
|
+
if (!headers.has('content-type'))
|
|
253
|
+
headers.set('content-type', 'application/json; charset=utf-8')
|
|
254
|
+
if (!headers.has('content-length'))
|
|
255
|
+
headers.set('content-length', String(Buffer.byteLength(payload, 'utf8')))
|
|
256
|
+
return new Response(payload, { ...init, headers })
|
|
257
|
+
}
|
|
258
|
+
const text: RequestContext['text'] = (body, init) => {
|
|
259
|
+
const headers = new Headers(init?.headers)
|
|
260
|
+
if (!headers.has('content-type'))
|
|
261
|
+
headers.set('content-type', 'text/plain; charset=utf-8')
|
|
262
|
+
if (!headers.has('content-length'))
|
|
263
|
+
headers.set('content-length', String(Buffer.byteLength(body, 'utf8')))
|
|
264
|
+
return new Response(body, { ...init, headers })
|
|
265
|
+
}
|
|
266
|
+
export interface DeniedInfo {
|
|
267
|
+
status: number
|
|
268
|
+
message: string
|
|
269
|
+
fieldErrors?: Record<string, string> | undefined
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
const DENIED_RESPONSES = new WeakMap<Response, DeniedInfo>()
|
|
273
|
+
|
|
274
|
+
/** Metadata attached to a `Response` produced by `ctx.deny()`. */
|
|
275
|
+
export function getDeniedInfo(res: Response): DeniedInfo | undefined {
|
|
276
|
+
return DENIED_RESPONSES.get(res)
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
const redirect: RequestContext['redirect'] = (location, status = 302) => new Response(null, { status, headers: { location } })
|
|
280
|
+
const deny: RequestContext['deny'] = (status, message, fieldErrors) => {
|
|
281
|
+
const res = Response.json({ ok: false, status, error: message, fieldErrors }, { status })
|
|
282
|
+
DENIED_RESPONSES.set(res, { status, message, fieldErrors })
|
|
283
|
+
return res
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** RFC 9110 weak ETag comparison supporting `*`, comma-separated lists, and `W/` prefixes. */
|
|
287
|
+
export function etagMatches(ifNoneMatch: string | null, etag: string): boolean {
|
|
288
|
+
if (!ifNoneMatch)
|
|
289
|
+
return false
|
|
290
|
+
const trimmed = ifNoneMatch.trim()
|
|
291
|
+
if (trimmed === '*')
|
|
292
|
+
return true
|
|
293
|
+
const stripWeak = (v: string) => (v.startsWith('W/') || v.startsWith('w/') ? v.slice(2) : v)
|
|
294
|
+
const target = stripWeak(etag)
|
|
295
|
+
for (const part of trimmed.split(',')) {
|
|
296
|
+
if (stripWeak(part.trim()) === target)
|
|
297
|
+
return true
|
|
298
|
+
}
|
|
299
|
+
return false
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
export function makeRequestContext(
|
|
303
|
+
request: Request,
|
|
304
|
+
params: Record<string, string>,
|
|
305
|
+
opts?: RequestContextOptions,
|
|
306
|
+
): { ctx: RequestContext, cookieStore: CookieStore } {
|
|
307
|
+
const trustProxy = opts?.trustProxy ?? false
|
|
308
|
+
const remoteIp = opts?.remoteIp
|
|
309
|
+
const consentConfig = opts?.consent
|
|
310
|
+
let cachedConsent: RequestConsent | undefined
|
|
311
|
+
const cookieStore = new CookieStore(
|
|
312
|
+
request.headers.get('cookie'),
|
|
313
|
+
isHttpsRequest(request, trustProxy),
|
|
314
|
+
category => getConsent().has(category),
|
|
315
|
+
)
|
|
316
|
+
const getConsent = (): RequestConsent => {
|
|
317
|
+
cachedConsent ??= createRequestConsent(consentConfig !== undefined ? cookieStore.get(consentConfig.cookieName) : undefined, consentConfig)
|
|
318
|
+
return cachedConsent
|
|
319
|
+
}
|
|
320
|
+
const requestId = opts?.requestId ?? resolveFallbackRequestId(request, trustProxy)
|
|
321
|
+
let cachedIp: string | undefined
|
|
322
|
+
let ipComputed = false
|
|
323
|
+
const ctx: RequestContext = {
|
|
324
|
+
request,
|
|
325
|
+
url: opts?.url ?? new URL(request.url),
|
|
326
|
+
params,
|
|
327
|
+
cookies: cookieStore,
|
|
328
|
+
get consent() {
|
|
329
|
+
return getConsent()
|
|
330
|
+
},
|
|
331
|
+
locals: {},
|
|
332
|
+
requestId,
|
|
333
|
+
get ip() {
|
|
334
|
+
if (!ipComputed) {
|
|
335
|
+
ipComputed = true
|
|
336
|
+
cachedIp = getClientIp(request, trustProxy, remoteIp)
|
|
337
|
+
}
|
|
338
|
+
return cachedIp
|
|
339
|
+
},
|
|
340
|
+
set ip(val: string | undefined) {
|
|
341
|
+
ipComputed = true
|
|
342
|
+
cachedIp = val
|
|
343
|
+
},
|
|
344
|
+
get region() {
|
|
345
|
+
return requestedRegion(request)
|
|
346
|
+
},
|
|
347
|
+
json,
|
|
348
|
+
text,
|
|
349
|
+
redirect,
|
|
350
|
+
deny,
|
|
351
|
+
}
|
|
352
|
+
return { ctx, cookieStore }
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/** True when the client sent or asked for JSON: such requests get JSON errors, not pages. */
|
|
356
|
+
export function wantsJson(request: Request): boolean {
|
|
357
|
+
return (request.headers.get('accept') ?? '').includes('application/json')
|
|
358
|
+
|| (request.headers.get('content-type') ?? '').includes('application/json')
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/** True when the client explicitly accepts HTML and does not ask for JSON (e.g. browser navigation). */
|
|
362
|
+
export function acceptsHtml(request: Request): boolean {
|
|
363
|
+
if (wantsJson(request))
|
|
364
|
+
return false
|
|
365
|
+
return (request.headers.get('accept') ?? '').includes('text/html')
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/** Enforces `maxBytes` on incoming request bodies (both Content-Length and streaming body reads). */
|
|
369
|
+
export async function enforceRequestBodyLimit(
|
|
370
|
+
request: Request,
|
|
371
|
+
maxBytes: number,
|
|
372
|
+
): Promise<{ ok: true, request: Request } | { ok: false }> {
|
|
373
|
+
if (request.method === 'GET' || request.method === 'HEAD' || !Number.isFinite(maxBytes) || maxBytes <= 0)
|
|
374
|
+
return { ok: true, request }
|
|
375
|
+
|
|
376
|
+
const clHeader = request.headers.get('content-length')
|
|
377
|
+
if (clHeader !== null) {
|
|
378
|
+
const cl = Number(clHeader)
|
|
379
|
+
if (Number.isFinite(cl) && cl > maxBytes)
|
|
380
|
+
return { ok: false }
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
// Capture headers BEFORE accessing request.body so Bun preserves FormData multipart boundaries.
|
|
384
|
+
const headers = new Headers(request.headers)
|
|
385
|
+
const body = request.body
|
|
386
|
+
if (body === null)
|
|
387
|
+
return { ok: true, request }
|
|
388
|
+
|
|
389
|
+
const reader = body.getReader()
|
|
390
|
+
const chunks: Uint8Array[] = []
|
|
391
|
+
let total = 0
|
|
392
|
+
try {
|
|
393
|
+
while (true) {
|
|
394
|
+
const { done, value } = await reader.read()
|
|
395
|
+
if (done)
|
|
396
|
+
break
|
|
397
|
+
total += value.byteLength
|
|
398
|
+
if (total > maxBytes) {
|
|
399
|
+
try {
|
|
400
|
+
await reader.cancel()
|
|
401
|
+
}
|
|
402
|
+
catch {}
|
|
403
|
+
return { ok: false }
|
|
404
|
+
}
|
|
405
|
+
chunks.push(value)
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
finally {
|
|
409
|
+
reader.releaseLock()
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
const combined = new Uint8Array(total)
|
|
413
|
+
let offset = 0
|
|
414
|
+
for (let i = 0; i < chunks.length; i++) {
|
|
415
|
+
const chunk = chunks[i]!
|
|
416
|
+
combined.set(chunk, offset)
|
|
417
|
+
offset += chunk.byteLength
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
headers.delete('transfer-encoding')
|
|
421
|
+
return {
|
|
422
|
+
ok: true,
|
|
423
|
+
request: new Request(request.url, {
|
|
424
|
+
method: request.method,
|
|
425
|
+
headers,
|
|
426
|
+
body: combined,
|
|
427
|
+
signal: request.signal,
|
|
428
|
+
}),
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
export function applyHstsHeader(
|
|
433
|
+
res: Response,
|
|
434
|
+
request: Request,
|
|
435
|
+
hstsValue: string | undefined,
|
|
436
|
+
trustProxy: TrustProxy,
|
|
437
|
+
isDev = false,
|
|
438
|
+
resolvedEnv?: string,
|
|
439
|
+
): Response {
|
|
440
|
+
if (hstsValue === undefined || isDev || !isHttpsRequest(request, trustProxy))
|
|
441
|
+
return res
|
|
442
|
+
const env = resolvedEnv ?? nodeEnv()
|
|
443
|
+
if (env === 'development' || env === 'test')
|
|
444
|
+
return res
|
|
445
|
+
if (res.headers.has('strict-transport-security'))
|
|
446
|
+
return res
|
|
447
|
+
try {
|
|
448
|
+
res.headers.set('strict-transport-security', hstsValue)
|
|
449
|
+
return res
|
|
450
|
+
}
|
|
451
|
+
catch {
|
|
452
|
+
const headers = new Headers(res.headers)
|
|
453
|
+
headers.set('strict-transport-security', hstsValue)
|
|
454
|
+
return new Response(res.body, { status: res.status, statusText: res.statusText, headers })
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
/** Adds the pending cookies (when any), security headers, `x-request-id`, and dev `Server-Timing`. */
|
|
459
|
+
export function finalizeResponse(
|
|
460
|
+
res: Response,
|
|
461
|
+
cookieStore: CookieStore | undefined,
|
|
462
|
+
entries: readonly [string, string][],
|
|
463
|
+
requestId?: string,
|
|
464
|
+
serverTiming?: string,
|
|
465
|
+
): Response {
|
|
466
|
+
const hasCookies = cookieStore?.hasChanges === true
|
|
467
|
+
const hasRequestId = requestId !== undefined
|
|
468
|
+
const hasTiming = serverTiming !== undefined && serverTiming !== ''
|
|
469
|
+
if (!hasCookies && entries.length === 0 && !hasRequestId && !hasTiming)
|
|
470
|
+
return res
|
|
471
|
+
|
|
472
|
+
const apply = (h: Headers): void => {
|
|
473
|
+
if (hasCookies)
|
|
474
|
+
cookieStore!.applyTo(h)
|
|
475
|
+
for (const [k, v] of entries) {
|
|
476
|
+
if (!h.has(k))
|
|
477
|
+
h.set(k, v)
|
|
478
|
+
}
|
|
479
|
+
if (hasRequestId && !h.has('x-request-id'))
|
|
480
|
+
h.set('x-request-id', requestId)
|
|
481
|
+
if (hasTiming)
|
|
482
|
+
h.set('server-timing', serverTiming)
|
|
483
|
+
}
|
|
484
|
+
// Mutate in place (no copy in Bun); a response with immutable headers (e.g. a proxied upstream fetch) is rebuilt.
|
|
485
|
+
try {
|
|
486
|
+
apply(res.headers)
|
|
487
|
+
return res
|
|
488
|
+
}
|
|
489
|
+
catch {
|
|
490
|
+
const headers = new Headers(res.headers)
|
|
491
|
+
apply(headers)
|
|
492
|
+
return new Response(res.body, { status: res.status, statusText: res.statusText, headers })
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
/** Runs `middlewares` in order around `last`; each calls `next` at most once. */
|
|
497
|
+
export async function runChain(ctx: RequestContext, middlewares: readonly Middleware[], last: () => Response | Promise<Response>): Promise<Response> {
|
|
498
|
+
if (middlewares.length === 0)
|
|
499
|
+
return last()
|
|
500
|
+
let index = -1
|
|
501
|
+
const dispatch = async (i: number): Promise<Response> => {
|
|
502
|
+
if (i <= index)
|
|
503
|
+
throw new Error('prunelle: middleware called next() multiple times')
|
|
504
|
+
index = i
|
|
505
|
+
return i < middlewares.length ? middlewares[i]!(ctx, () => dispatch(i + 1)) : last()
|
|
506
|
+
}
|
|
507
|
+
return dispatch(0)
|
|
508
|
+
}
|