prunelle 0.0.0-stage → 0.1.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/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 +106 -0
- package/src/build/client-plugin.ts +169 -0
- package/src/build/client-prune.ts +118 -0
- package/src/build/compile.ts +127 -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 +575 -0
- package/src/build/is-inside.ts +12 -0
- package/src/build/islands.ts +641 -0
- package/src/build/manifest.ts +264 -0
- package/src/build/output.ts +84 -0
- package/src/build/plugin-host.ts +220 -0
- package/src/build/precompress.ts +126 -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 +177 -0
- package/src/build/server-entry.ts +38 -0
- package/src/build/static.ts +109 -0
- package/src/cli/check.ts +334 -0
- package/src/cli/commands.ts +265 -0
- package/src/cli/index.ts +70 -0
- package/src/cli/inspect.ts +316 -0
- package/src/cli/new.ts +41 -0
- package/src/cli/upgrade-names.ts +149 -0
- package/src/cli/upgrade.ts +258 -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.ts +598 -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 +394 -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 +161 -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 +234 -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-registry.ts +78 -0
- package/src/server/action.ts +475 -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 +153 -0
- package/src/server/http.ts +441 -0
- package/src/server/index.ts +616 -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/plugin-host.ts +251 -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 +79 -0
- package/src/server/router.ts +184 -0
- package/src/server/routing.ts +339 -0
- package/src/server/security.ts +323 -0
- package/src/server/serve-handlers.ts +69 -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 +301 -0
- package/src/ssr/index.ts +477 -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 +186 -0
- package/src/test/index.ts +177 -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 +8 -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 +29 -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,153 @@
|
|
|
1
|
+
// Errors a request runs into: the app's and plugins' `onError` hooks, and the `_error` and `_404` pages rendered outside any route.
|
|
2
|
+
|
|
3
|
+
import type { BuildManifest } from '../build/index'
|
|
4
|
+
import type { Html } from '../jsx-runtime'
|
|
5
|
+
import type { PrunellePlugin, ServerErrorInfo } from '../plugins/index'
|
|
6
|
+
import type { DocumentOptions } from '../ssr/index'
|
|
7
|
+
import type { CookieStore } from './cookies'
|
|
8
|
+
import type { DocumentHooks, HtmlHeaders } from './document'
|
|
9
|
+
import type { RequestContext } from './http'
|
|
10
|
+
import { createRenderContext, runWithRenderContext } from '../ssr/context'
|
|
11
|
+
import { raw, renderDocument, ssrChild } from '../ssr/index'
|
|
12
|
+
import { addedInlineStyleHashes, headTagStyleHashes, mergeStyleHashes, resolveRenderedIslands, revivePreload } from './document'
|
|
13
|
+
import { wantsJson } from './http'
|
|
14
|
+
import { styleHashesOf } from './security'
|
|
15
|
+
|
|
16
|
+
export type NotifyError = (error: unknown, request: Request, source: ServerErrorInfo['source']) => void
|
|
17
|
+
|
|
18
|
+
/** The text of an error a dev response shows: its stack, which starts with its message. */
|
|
19
|
+
export const errorDetail = (error: unknown): string => error instanceof Error ? error.stack ?? error.message : String(error)
|
|
20
|
+
|
|
21
|
+
const errorMessage = (error: unknown): string => error instanceof Error ? error.message : String(error)
|
|
22
|
+
|
|
23
|
+
/** What a dev server answers with an unhandled error: its message and stack, as JSON when the request wants it. */
|
|
24
|
+
export function devErrorResponse(error: unknown, request: Request): Response {
|
|
25
|
+
if (wantsJson(request))
|
|
26
|
+
return Response.json({ ok: false, status: 500, error: errorMessage(error), stack: errorDetail(error) }, { status: 500 })
|
|
27
|
+
return new Response(errorDetail(error), { status: 500, headers: { 'content-type': 'text/plain; charset=utf-8' } })
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface ErrorNotifierOptions {
|
|
31
|
+
/** With no `onError` hook to hear an unhandled error, `console.error` does. */
|
|
32
|
+
dev?: boolean | undefined
|
|
33
|
+
/** Hears every unhandled error, hooks or not: how `testApp().errors` fills. */
|
|
34
|
+
sink?: ((info: ServerErrorInfo) => void) | undefined
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function createErrorNotifier(onError: ((info: ServerErrorInfo) => void) | undefined, plugins: readonly PrunellePlugin[], options: ErrorNotifierOptions = {}): NotifyError {
|
|
38
|
+
const errorHooks: { owner: string, hook: (info: ServerErrorInfo) => void }[] = []
|
|
39
|
+
if (onError !== undefined)
|
|
40
|
+
errorHooks.push({ owner: 'prunelle.config.ts', hook: onError })
|
|
41
|
+
for (const p of plugins) {
|
|
42
|
+
if (p.onError !== undefined)
|
|
43
|
+
errorHooks.push({ owner: p.name, hook: p.onError })
|
|
44
|
+
}
|
|
45
|
+
return (error, request, source) => {
|
|
46
|
+
options.sink?.({ error, request, source })
|
|
47
|
+
if (options.dev === true && errorHooks.length === 0)
|
|
48
|
+
console.error(`prunelle: unhandled error in ${source} ${request.method} ${new URL(request.url).pathname}`, error)
|
|
49
|
+
for (const { owner, hook } of errorHooks) {
|
|
50
|
+
try {
|
|
51
|
+
hook({ error, request, source })
|
|
52
|
+
}
|
|
53
|
+
catch (hookError) {
|
|
54
|
+
console.error(`prunelle: the onError hook of ${owner} threw; the other hooks still run.`, hookError)
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
interface LayoutModule {
|
|
61
|
+
default: (props: { children: Html, url?: URL, params?: Record<string, string>, locals?: object }) => Html | string | Promise<Html | string>
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
interface ErrorModule {
|
|
65
|
+
default: (props: { error: unknown }) => Html | string | Promise<Html | string>
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
interface NotFoundModule {
|
|
69
|
+
default?: (props: Record<string, unknown>) => Html | string | Promise<Html | string>
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export interface FallbackPagesOptions {
|
|
73
|
+
manifest: BuildManifest
|
|
74
|
+
modules: Record<string, unknown>
|
|
75
|
+
lang: string
|
|
76
|
+
alwaysLoadRuntime: boolean
|
|
77
|
+
navigation?: string | undefined
|
|
78
|
+
dev: boolean
|
|
79
|
+
document: DocumentHooks
|
|
80
|
+
htmlHeaders: HtmlHeaders
|
|
81
|
+
notifyError: NotifyError
|
|
82
|
+
finish: (res: Response, request: Request, cookieStore?: CookieStore) => Response
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function createFallbackPages(options: FallbackPagesOptions) {
|
|
86
|
+
const { manifest, modules, document, htmlHeaders, notifyError, finish } = options
|
|
87
|
+
const errorMod = manifest.errorFile ? modules[manifest.errorFile] as ErrorModule : undefined
|
|
88
|
+
const notFoundMod = manifest.notFoundFile ? modules[manifest.notFoundFile] as NotFoundModule : undefined
|
|
89
|
+
|
|
90
|
+
// Error and 404 pages sit outside any route, so they render with the global styles and the explicit root layout only.
|
|
91
|
+
const rootLayoutFile = manifest.rootLayoutFile
|
|
92
|
+
const rootLayoutMod = rootLayoutFile !== undefined ? modules[rootLayoutFile] as LayoutModule | undefined : undefined
|
|
93
|
+
const fallbackDoc: DocumentOptions = {
|
|
94
|
+
body: '',
|
|
95
|
+
headTags: manifest.headTags,
|
|
96
|
+
styles: manifest.globalStyles ?? manifest.styles,
|
|
97
|
+
runtimeScript: manifest.runtimeScript,
|
|
98
|
+
chunkImports: manifest.chunkImports,
|
|
99
|
+
alwaysLoadRuntime: options.alwaysLoadRuntime,
|
|
100
|
+
navigation: options.navigation,
|
|
101
|
+
lang: options.lang,
|
|
102
|
+
}
|
|
103
|
+
const fallbackHeadStyleHashes = headTagStyleHashes(fallbackDoc.headTags)
|
|
104
|
+
|
|
105
|
+
async function renderFallbackPage(status: number, renderInner: (() => unknown) | undefined, text: string, url?: URL, req?: Request, ctx?: RequestContext): Promise<Response> {
|
|
106
|
+
if (renderInner !== undefined) {
|
|
107
|
+
try {
|
|
108
|
+
const effUrl = url ?? new URL(`http://localhost/${status}`)
|
|
109
|
+
const rctx = createRenderContext(undefined, undefined, ctx?.consent, req !== undefined ? error => notifyError(error, req, 'route') : undefined)
|
|
110
|
+
const body = await runWithRenderContext(rctx, async () => {
|
|
111
|
+
let inner = ssrChild(await renderInner() as Html)
|
|
112
|
+
if (rootLayoutMod !== undefined)
|
|
113
|
+
inner = ssrChild(await rootLayoutMod.default({ children: raw(inner), url: effUrl, params: {}, locals: ctx?.locals ?? {} }) as Html)
|
|
114
|
+
return inner
|
|
115
|
+
})
|
|
116
|
+
const { hasIslands, eagerChunks } = resolveRenderedIslands(rctx, body)
|
|
117
|
+
const docHead = await document.resolveDocumentHead(rctx, manifest.headTags, effUrl, req, ctx)
|
|
118
|
+
const docHtml = renderDocument({
|
|
119
|
+
...fallbackDoc,
|
|
120
|
+
body,
|
|
121
|
+
head: docHead.head,
|
|
122
|
+
lang: docHead.lang,
|
|
123
|
+
htmlAttrs: docHead.htmlAttrs,
|
|
124
|
+
preloadChunks: [...eagerChunks, ...revivePreload(rctx, manifest.reviveScript)],
|
|
125
|
+
hasIslands,
|
|
126
|
+
})
|
|
127
|
+
const html = await document.applyHtmlTransforms(docHtml, effUrl, req, ctx)
|
|
128
|
+
const styleHashes = mergeStyleHashes(fallbackHeadStyleHashes, docHead.styleHashes, styleHashesOf(rctx.inlineStyles), addedInlineStyleHashes(docHtml, html))
|
|
129
|
+
return new Response(html, { status, headers: htmlHeaders(hasIslands, false, true, styleHashes) })
|
|
130
|
+
}
|
|
131
|
+
catch (err) {
|
|
132
|
+
if (req !== undefined)
|
|
133
|
+
notifyError(err, req, 'route')
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return new Response(text, { status, headers: { 'content-type': 'text/plain; charset=utf-8' } })
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const buildErrorResponse = (error: unknown, url?: URL, req?: Request, ctx?: RequestContext): Promise<Response> =>
|
|
140
|
+
renderFallbackPage(500, errorMod && (() => errorMod.default({ error })), options.dev ? errorDetail(error) : 'Internal Server Error', url, req, ctx)
|
|
141
|
+
|
|
142
|
+
const notFoundPage = notFoundMod?.default
|
|
143
|
+
const buildNotFoundResponse = (url?: URL, req?: Request, ctx?: RequestContext): Promise<Response> =>
|
|
144
|
+
renderFallbackPage(404, notFoundPage && (() => notFoundPage({})), 'Not Found', url, req, ctx)
|
|
145
|
+
|
|
146
|
+
async function renderError(error: unknown, cookieStore: CookieStore | undefined, url: URL, request: Request, ctx?: RequestContext): Promise<Response> {
|
|
147
|
+
if (wantsJson(request))
|
|
148
|
+
return finish(options.dev ? devErrorResponse(error, request) : Response.json({ ok: false, status: 500, error: 'Internal Server Error' }, { status: 500 }), request, cookieStore)
|
|
149
|
+
return finish(await buildErrorResponse(error, url, request, ctx), request, cookieStore)
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
return { buildNotFoundResponse, renderError }
|
|
153
|
+
}
|
|
@@ -0,0 +1,441 @@
|
|
|
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 { requestedRegion } from './region'
|
|
14
|
+
import { getClientIp, isHttpsRequest } from './security'
|
|
15
|
+
|
|
16
|
+
export const DEFAULT_MAX_REQUEST_BODY_SIZE = 1024 * 1024
|
|
17
|
+
|
|
18
|
+
const NOT_FOUND_SYMBOL = Symbol.for('pru.notFound')
|
|
19
|
+
declare const NOT_FOUND_BRAND: unique symbol
|
|
20
|
+
|
|
21
|
+
export interface NotFoundResult {
|
|
22
|
+
readonly [NOT_FOUND_BRAND]: true
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Return (or throw) from `load()` to render `_404.tsx` with HTTP status 404. */
|
|
26
|
+
export function notFound(): NotFoundResult {
|
|
27
|
+
return { [NOT_FOUND_SYMBOL]: true } as unknown as NotFoundResult
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function isNotFound(value: unknown): value is NotFoundResult {
|
|
31
|
+
return typeof value === 'object' && value !== null && (value as Record<symbol, unknown>)[NOT_FOUND_SYMBOL] === true
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
type SegmentParam<Seg extends string> =
|
|
35
|
+
Seg extends `[...${infer Name}]`
|
|
36
|
+
? { [K in Name]: string }
|
|
37
|
+
: Seg extends `[${infer Name}]`
|
|
38
|
+
? { [K in Name]: string }
|
|
39
|
+
: Seg extends `*${infer Name}`
|
|
40
|
+
? { [K in Name extends '' ? 'rest' : Name]: string }
|
|
41
|
+
: Seg extends `:${infer Name}`
|
|
42
|
+
? { [K in Name]: string }
|
|
43
|
+
: unknown
|
|
44
|
+
|
|
45
|
+
type MergeParams<A, B> = {
|
|
46
|
+
[K in keyof A | keyof B]: K extends keyof B ? B[K] : K extends keyof A ? A[K] : never
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
type ExtractRouteParamsRec<Path extends string, Acc = {}> =
|
|
50
|
+
Path extends `${infer Seg}/${infer Rest}`
|
|
51
|
+
? ExtractRouteParamsRec<Rest, Seg extends '' ? Acc : MergeParams<Acc, SegmentParam<Seg>>>
|
|
52
|
+
: Path extends ''
|
|
53
|
+
? Acc
|
|
54
|
+
: MergeParams<Acc, SegmentParam<Path>>
|
|
55
|
+
|
|
56
|
+
/** Extracts typed route params from a Prunelle route path (`'/notices/[id]'` -> `{ id: string }`, `'/docs/[...rest]'` -> `{ rest: string }`). */
|
|
57
|
+
export type ExtractRouteParams<Path extends string> =
|
|
58
|
+
string extends Path
|
|
59
|
+
? Record<string, string>
|
|
60
|
+
: ExtractRouteParamsRec<Path>
|
|
61
|
+
|
|
62
|
+
export type LoaderFn = (...args: never[]) => unknown
|
|
63
|
+
|
|
64
|
+
/** Infers the resolved page `data` type returned by a route's `load()` function, excluding `Response` and `notFound()`. */
|
|
65
|
+
export type LoaderData<T extends LoaderFn> = Exclude<Awaited<ReturnType<T>>, Response | NotFoundResult>
|
|
66
|
+
|
|
67
|
+
type InferLoaderParams<T extends LoaderFn> =
|
|
68
|
+
Parameters<T> extends [ctx: { params: infer P }, ...unknown[]]
|
|
69
|
+
? P
|
|
70
|
+
: Record<string, string>
|
|
71
|
+
|
|
72
|
+
/** 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`. */
|
|
73
|
+
export type PageProps<
|
|
74
|
+
TLoadOrPath extends LoaderFn | string | undefined = undefined,
|
|
75
|
+
TPath extends string = string,
|
|
76
|
+
> = {
|
|
77
|
+
params: TLoadOrPath extends string
|
|
78
|
+
? ExtractRouteParams<TLoadOrPath>
|
|
79
|
+
: string extends TPath
|
|
80
|
+
? (TLoadOrPath extends LoaderFn ? InferLoaderParams<TLoadOrPath> : Record<string, string>)
|
|
81
|
+
: ExtractRouteParams<TPath>
|
|
82
|
+
locals: PrunelleLocals
|
|
83
|
+
url: URL
|
|
84
|
+
} & (TLoadOrPath extends LoaderFn ? { data: LoaderData<TLoadOrPath> } : { data?: undefined })
|
|
85
|
+
|
|
86
|
+
/** Props passed to a Prunelle `_layout.tsx` component. */
|
|
87
|
+
export interface LayoutProps<Path extends string = string> {
|
|
88
|
+
children: PrunelleChild
|
|
89
|
+
params: ExtractRouteParams<Path>
|
|
90
|
+
locals: PrunelleLocals
|
|
91
|
+
url: URL
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export interface ServerOptions extends ServerRuntimeConfig {
|
|
95
|
+
root: string
|
|
96
|
+
outDir?: string | undefined
|
|
97
|
+
port?: number | undefined
|
|
98
|
+
dev?: boolean | undefined
|
|
99
|
+
nodeEnv?: string | undefined
|
|
100
|
+
/** @internal Imports a built server module by absolute path; `prunelle dev` passes one that keeps unchanged modules loaded. */
|
|
101
|
+
importModule?: ((path: string) => Promise<Record<string, unknown>>) | undefined
|
|
102
|
+
/** @internal Hears every unhandled route, action and plugin error; `testApp().errors` fills from it. */
|
|
103
|
+
errorSink?: ((info: ServerErrorInfo) => void) | undefined
|
|
104
|
+
/** @internal The build's prerender server, which runs before the production environment exists, so plugin `requires` are not checked. */
|
|
105
|
+
prerender?: boolean | undefined
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export interface RequestContext<Params = Record<string, string>> {
|
|
109
|
+
request: Request
|
|
110
|
+
url: URL
|
|
111
|
+
params: Params
|
|
112
|
+
cookies: Cookies
|
|
113
|
+
consent: RequestConsent
|
|
114
|
+
locals: PrunelleLocals
|
|
115
|
+
ip?: string | undefined
|
|
116
|
+
/** The region a `data-pru-target` link or form asked for alone (`x-pru-region`): `load()` can skip the data the others show. */
|
|
117
|
+
readonly region?: string | undefined
|
|
118
|
+
json: (data: unknown, init?: ResponseInit) => Response
|
|
119
|
+
text: (body: string, init?: ResponseInit) => Response
|
|
120
|
+
redirect: (location: string, status?: 301 | 302 | 303 | 307 | 308) => Response
|
|
121
|
+
deny: (status: number, message: string, fieldErrors?: Record<string, string>) => Response
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** `RequestContext` with `params` inferred from a Prunelle route pattern (e.g. `RouteContext<'/notices/[id]'>`). */
|
|
125
|
+
export type RouteContext<Path extends string = string> = RequestContext<ExtractRouteParams<Path>>
|
|
126
|
+
|
|
127
|
+
export type Middleware = (ctx: RequestContext, next: () => Promise<Response>) => Response | Promise<Response>
|
|
128
|
+
|
|
129
|
+
export type PrunelleServer = ReturnType<typeof Bun.serve>
|
|
130
|
+
|
|
131
|
+
export interface PrunelleApp {
|
|
132
|
+
handle: (request: Request, remoteIp?: string) => Promise<Response>
|
|
133
|
+
serve: (port?: number, hostname?: string) => PrunelleServer
|
|
134
|
+
/** @internal Swaps this app's handlers into a server another app started, with no dropped connection: `prunelle start` reloads a new build with it. */
|
|
135
|
+
reloadInto?: (server: PrunelleServer) => void
|
|
136
|
+
/** Closes active long-lived streams (such as SSE) before `server.stop()` drains normal in-flight HTTP requests. */
|
|
137
|
+
closeStreams?: () => Promise<void>
|
|
138
|
+
/** Runs plugin shutdown hooks and releases timers/resources (safe to call multiple times). */
|
|
139
|
+
dispose?: () => Promise<void>
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export type EmbeddedBody = Uint8Array<ArrayBuffer> | string
|
|
143
|
+
|
|
144
|
+
export interface EmbeddedServerConfig extends ServerRuntimeConfig {
|
|
145
|
+
manifest: BuildManifest
|
|
146
|
+
modules: Record<string, unknown>
|
|
147
|
+
assets: Record<string, EmbeddedBody>
|
|
148
|
+
publicAssets?: Record<string, EmbeddedBody> | undefined
|
|
149
|
+
publicEtags?: Record<string, string> | undefined
|
|
150
|
+
prerendered?: Record<string, string> | undefined
|
|
151
|
+
prerenderedFiles?: Record<string, string> | undefined
|
|
152
|
+
/** ETags of the prerendered HTML files, by the same key; a missing one comes from the file's size and mtime. */
|
|
153
|
+
prerenderedEtags?: Record<string, string> | undefined
|
|
154
|
+
root?: string | undefined
|
|
155
|
+
outDir?: string | undefined
|
|
156
|
+
publicDir?: string | undefined
|
|
157
|
+
dev?: boolean | undefined
|
|
158
|
+
nodeEnv?: string | undefined
|
|
159
|
+
errorSink?: ((info: ServerErrorInfo) => void) | undefined
|
|
160
|
+
prerender?: boolean | undefined
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
export const MIME: Record<string, string> = {
|
|
164
|
+
'.js': 'text/javascript; charset=utf-8',
|
|
165
|
+
'.mjs': 'text/javascript; charset=utf-8',
|
|
166
|
+
'.css': 'text/css; charset=utf-8',
|
|
167
|
+
'.html': 'text/html; charset=utf-8',
|
|
168
|
+
'.json': 'application/json; charset=utf-8',
|
|
169
|
+
'.webmanifest': 'application/manifest+json; charset=utf-8',
|
|
170
|
+
'.txt': 'text/plain; charset=utf-8',
|
|
171
|
+
'.xml': 'application/xml; charset=utf-8',
|
|
172
|
+
'.svg': 'image/svg+xml',
|
|
173
|
+
'.png': 'image/png',
|
|
174
|
+
'.jpg': 'image/jpeg',
|
|
175
|
+
'.jpeg': 'image/jpeg',
|
|
176
|
+
'.gif': 'image/gif',
|
|
177
|
+
'.webp': 'image/webp',
|
|
178
|
+
'.avif': 'image/avif',
|
|
179
|
+
'.ico': 'image/x-icon',
|
|
180
|
+
'.woff2': 'font/woff2',
|
|
181
|
+
'.woff': 'font/woff',
|
|
182
|
+
'.ttf': 'font/ttf',
|
|
183
|
+
'.otf': 'font/otf',
|
|
184
|
+
'.pdf': 'application/pdf',
|
|
185
|
+
'.wasm': 'application/wasm',
|
|
186
|
+
'.mp4': 'video/mp4',
|
|
187
|
+
'.webm': 'video/webm',
|
|
188
|
+
'.map': 'application/json',
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const ISLAND_TAG_RE = /<pru-island c="([^"]+)"([^>]*)>/g
|
|
192
|
+
|
|
193
|
+
export function extractRenderedIslands(html: string): { hasIslands: boolean, eagerChunks: string[] } {
|
|
194
|
+
let hasIslands = false
|
|
195
|
+
const eager = new Set<string>()
|
|
196
|
+
ISLAND_TAG_RE.lastIndex = 0
|
|
197
|
+
let m: RegExpExecArray | null
|
|
198
|
+
while ((m = ISLAND_TAG_RE.exec(html)) !== null) {
|
|
199
|
+
hasIslands = true
|
|
200
|
+
const attrs = m[2] ?? ''
|
|
201
|
+
if (!attrs.includes(' h="'))
|
|
202
|
+
eager.add(m[1]!)
|
|
203
|
+
}
|
|
204
|
+
return { hasIslands, eagerChunks: [...eager] }
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
export interface RequestContextOptions {
|
|
208
|
+
trustProxy?: TrustProxy | undefined
|
|
209
|
+
remoteIp?: string | undefined
|
|
210
|
+
/** The parsed `request.url`, when the caller already has it. */
|
|
211
|
+
url?: URL | undefined
|
|
212
|
+
consent?: NormalizedConsentConfig | undefined
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// None of these read the request, so every context shares them.
|
|
216
|
+
const json: RequestContext['json'] = (data, init) => {
|
|
217
|
+
const payload = JSON.stringify(data)
|
|
218
|
+
const headers = new Headers(init?.headers)
|
|
219
|
+
if (!headers.has('content-type'))
|
|
220
|
+
headers.set('content-type', 'application/json; charset=utf-8')
|
|
221
|
+
if (!headers.has('content-length'))
|
|
222
|
+
headers.set('content-length', String(Buffer.byteLength(payload, 'utf8')))
|
|
223
|
+
return new Response(payload, { ...init, headers })
|
|
224
|
+
}
|
|
225
|
+
const text: RequestContext['text'] = (body, init) => {
|
|
226
|
+
const headers = new Headers(init?.headers)
|
|
227
|
+
if (!headers.has('content-type'))
|
|
228
|
+
headers.set('content-type', 'text/plain; charset=utf-8')
|
|
229
|
+
if (!headers.has('content-length'))
|
|
230
|
+
headers.set('content-length', String(Buffer.byteLength(body, 'utf8')))
|
|
231
|
+
return new Response(body, { ...init, headers })
|
|
232
|
+
}
|
|
233
|
+
const redirect: RequestContext['redirect'] = (location, status = 302) => new Response(null, { status, headers: { location } })
|
|
234
|
+
const deny: RequestContext['deny'] = (status, message, fieldErrors) => Response.json({ ok: false, status, error: message, fieldErrors }, { status })
|
|
235
|
+
|
|
236
|
+
/** RFC 9110 weak ETag comparison supporting `*`, comma-separated lists, and `W/` prefixes. */
|
|
237
|
+
export function etagMatches(ifNoneMatch: string | null, etag: string): boolean {
|
|
238
|
+
if (!ifNoneMatch)
|
|
239
|
+
return false
|
|
240
|
+
const trimmed = ifNoneMatch.trim()
|
|
241
|
+
if (trimmed === '*')
|
|
242
|
+
return true
|
|
243
|
+
const stripWeak = (v: string) => (v.startsWith('W/') || v.startsWith('w/') ? v.slice(2) : v)
|
|
244
|
+
const target = stripWeak(etag)
|
|
245
|
+
for (const part of trimmed.split(',')) {
|
|
246
|
+
if (stripWeak(part.trim()) === target)
|
|
247
|
+
return true
|
|
248
|
+
}
|
|
249
|
+
return false
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
export function makeRequestContext(
|
|
253
|
+
request: Request,
|
|
254
|
+
params: Record<string, string>,
|
|
255
|
+
opts?: RequestContextOptions,
|
|
256
|
+
): { ctx: RequestContext, cookieStore: CookieStore } {
|
|
257
|
+
const trustProxy = opts?.trustProxy ?? false
|
|
258
|
+
const remoteIp = opts?.remoteIp
|
|
259
|
+
const consentConfig = opts?.consent
|
|
260
|
+
let cachedConsent: RequestConsent | undefined
|
|
261
|
+
const cookieStore = new CookieStore(
|
|
262
|
+
request.headers.get('cookie'),
|
|
263
|
+
isHttpsRequest(request, trustProxy),
|
|
264
|
+
category => getConsent().has(category),
|
|
265
|
+
)
|
|
266
|
+
const getConsent = (): RequestConsent => {
|
|
267
|
+
cachedConsent ??= createRequestConsent(consentConfig !== undefined ? cookieStore.get(consentConfig.cookieName) : undefined, consentConfig)
|
|
268
|
+
return cachedConsent
|
|
269
|
+
}
|
|
270
|
+
let cachedIp: string | undefined
|
|
271
|
+
let ipComputed = false
|
|
272
|
+
const ctx: RequestContext = {
|
|
273
|
+
request,
|
|
274
|
+
url: opts?.url ?? new URL(request.url),
|
|
275
|
+
params,
|
|
276
|
+
cookies: cookieStore,
|
|
277
|
+
get consent() {
|
|
278
|
+
return getConsent()
|
|
279
|
+
},
|
|
280
|
+
locals: {},
|
|
281
|
+
get ip() {
|
|
282
|
+
if (!ipComputed) {
|
|
283
|
+
ipComputed = true
|
|
284
|
+
cachedIp = getClientIp(request, trustProxy, remoteIp)
|
|
285
|
+
}
|
|
286
|
+
return cachedIp
|
|
287
|
+
},
|
|
288
|
+
set ip(val: string | undefined) {
|
|
289
|
+
ipComputed = true
|
|
290
|
+
cachedIp = val
|
|
291
|
+
},
|
|
292
|
+
get region() {
|
|
293
|
+
return requestedRegion(request)
|
|
294
|
+
},
|
|
295
|
+
json,
|
|
296
|
+
text,
|
|
297
|
+
redirect,
|
|
298
|
+
deny,
|
|
299
|
+
}
|
|
300
|
+
return { ctx, cookieStore }
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/** True when the client sent or asked for JSON: such requests get JSON errors, not pages. */
|
|
304
|
+
export function wantsJson(request: Request): boolean {
|
|
305
|
+
return (request.headers.get('accept') ?? '').includes('application/json')
|
|
306
|
+
|| (request.headers.get('content-type') ?? '').includes('application/json')
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/** Enforces `maxBytes` on incoming request bodies (both Content-Length and streaming body reads). */
|
|
310
|
+
export async function enforceRequestBodyLimit(
|
|
311
|
+
request: Request,
|
|
312
|
+
maxBytes: number,
|
|
313
|
+
): Promise<{ ok: true, request: Request } | { ok: false }> {
|
|
314
|
+
if (request.method === 'GET' || request.method === 'HEAD' || !Number.isFinite(maxBytes) || maxBytes <= 0)
|
|
315
|
+
return { ok: true, request }
|
|
316
|
+
|
|
317
|
+
const clHeader = request.headers.get('content-length')
|
|
318
|
+
if (clHeader !== null) {
|
|
319
|
+
const cl = Number(clHeader)
|
|
320
|
+
if (Number.isFinite(cl) && cl > maxBytes)
|
|
321
|
+
return { ok: false }
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
// Capture headers BEFORE accessing request.body so Bun preserves FormData multipart boundaries.
|
|
325
|
+
const headers = new Headers(request.headers)
|
|
326
|
+
const body = request.body
|
|
327
|
+
if (body === null)
|
|
328
|
+
return { ok: true, request }
|
|
329
|
+
|
|
330
|
+
const reader = body.getReader()
|
|
331
|
+
const chunks: Uint8Array[] = []
|
|
332
|
+
let total = 0
|
|
333
|
+
try {
|
|
334
|
+
while (true) {
|
|
335
|
+
const { done, value } = await reader.read()
|
|
336
|
+
if (done)
|
|
337
|
+
break
|
|
338
|
+
total += value.byteLength
|
|
339
|
+
if (total > maxBytes) {
|
|
340
|
+
try {
|
|
341
|
+
await reader.cancel()
|
|
342
|
+
}
|
|
343
|
+
catch {}
|
|
344
|
+
return { ok: false }
|
|
345
|
+
}
|
|
346
|
+
chunks.push(value)
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
finally {
|
|
350
|
+
reader.releaseLock()
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
const combined = new Uint8Array(total)
|
|
354
|
+
let offset = 0
|
|
355
|
+
for (let i = 0; i < chunks.length; i++) {
|
|
356
|
+
const chunk = chunks[i]!
|
|
357
|
+
combined.set(chunk, offset)
|
|
358
|
+
offset += chunk.byteLength
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
headers.delete('transfer-encoding')
|
|
362
|
+
return {
|
|
363
|
+
ok: true,
|
|
364
|
+
request: new Request(request.url, {
|
|
365
|
+
method: request.method,
|
|
366
|
+
headers,
|
|
367
|
+
body: combined,
|
|
368
|
+
signal: request.signal,
|
|
369
|
+
}),
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
export function applyHstsHeader(
|
|
374
|
+
res: Response,
|
|
375
|
+
request: Request,
|
|
376
|
+
hstsValue: string | undefined,
|
|
377
|
+
trustProxy: TrustProxy,
|
|
378
|
+
isDev = false,
|
|
379
|
+
resolvedEnv?: string,
|
|
380
|
+
): Response {
|
|
381
|
+
if (hstsValue === undefined || isDev || !isHttpsRequest(request, trustProxy))
|
|
382
|
+
return res
|
|
383
|
+
const env = resolvedEnv ?? nodeEnv()
|
|
384
|
+
if (env === 'development' || env === 'test')
|
|
385
|
+
return res
|
|
386
|
+
if (res.headers.has('strict-transport-security'))
|
|
387
|
+
return res
|
|
388
|
+
try {
|
|
389
|
+
res.headers.set('strict-transport-security', hstsValue)
|
|
390
|
+
return res
|
|
391
|
+
}
|
|
392
|
+
catch {
|
|
393
|
+
const headers = new Headers(res.headers)
|
|
394
|
+
headers.set('strict-transport-security', hstsValue)
|
|
395
|
+
return new Response(res.body, { status: res.status, statusText: res.statusText, headers })
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/** Adds the pending cookies (when any) and the security headers the response does not set itself. */
|
|
400
|
+
export function finalizeResponse(
|
|
401
|
+
res: Response,
|
|
402
|
+
cookieStore: CookieStore | undefined,
|
|
403
|
+
entries: readonly [string, string][],
|
|
404
|
+
): Response {
|
|
405
|
+
const hasCookies = cookieStore?.hasChanges === true
|
|
406
|
+
if (!hasCookies && entries.length === 0)
|
|
407
|
+
return res
|
|
408
|
+
|
|
409
|
+
const apply = (h: Headers): void => {
|
|
410
|
+
if (hasCookies)
|
|
411
|
+
cookieStore!.applyTo(h)
|
|
412
|
+
for (const [k, v] of entries) {
|
|
413
|
+
if (!h.has(k))
|
|
414
|
+
h.set(k, v)
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
// Mutate in place (no copy in Bun); a response with immutable headers (e.g. a proxied upstream fetch) is rebuilt.
|
|
418
|
+
try {
|
|
419
|
+
apply(res.headers)
|
|
420
|
+
return res
|
|
421
|
+
}
|
|
422
|
+
catch {
|
|
423
|
+
const headers = new Headers(res.headers)
|
|
424
|
+
apply(headers)
|
|
425
|
+
return new Response(res.body, { status: res.status, statusText: res.statusText, headers })
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/** Runs `middlewares` in order around `last`; each calls `next` at most once. */
|
|
430
|
+
export async function runChain(ctx: RequestContext, middlewares: readonly Middleware[], last: () => Response | Promise<Response>): Promise<Response> {
|
|
431
|
+
if (middlewares.length === 0)
|
|
432
|
+
return last()
|
|
433
|
+
let index = -1
|
|
434
|
+
const dispatch = async (i: number): Promise<Response> => {
|
|
435
|
+
if (i <= index)
|
|
436
|
+
throw new Error('prunelle: middleware called next() multiple times')
|
|
437
|
+
index = i
|
|
438
|
+
return i < middlewares.length ? middlewares[i]!(ctx, () => dispatch(i + 1)) : last()
|
|
439
|
+
}
|
|
440
|
+
return dispatch(0)
|
|
441
|
+
}
|