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.
Files changed (181) hide show
  1. package/llms.txt +148 -0
  2. package/package.json +53 -4
  3. package/src/ambient.d.ts +6 -0
  4. package/src/attrs.ts +35 -0
  5. package/src/build/bundle.ts +613 -0
  6. package/src/build/carry.ts +57 -0
  7. package/src/build/client-entries.ts +107 -0
  8. package/src/build/client-plugin.ts +169 -0
  9. package/src/build/client-prune.ts +118 -0
  10. package/src/build/compile.ts +128 -0
  11. package/src/build/files.ts +156 -0
  12. package/src/build/first-load.ts +164 -0
  13. package/src/build/graph.ts +247 -0
  14. package/src/build/index.ts +614 -0
  15. package/src/build/is-inside.ts +12 -0
  16. package/src/build/islands.ts +641 -0
  17. package/src/build/manifest.ts +281 -0
  18. package/src/build/output.ts +84 -0
  19. package/src/build/plugin-host.ts +220 -0
  20. package/src/build/precompress.ts +139 -0
  21. package/src/build/prerender.ts +150 -0
  22. package/src/build/render-rules.ts +205 -0
  23. package/src/build/report.ts +247 -0
  24. package/src/build/resolve.ts +50 -0
  25. package/src/build/routes.ts +338 -0
  26. package/src/build/server-entry.ts +38 -0
  27. package/src/build/static.ts +163 -0
  28. package/src/build/status-pages.ts +127 -0
  29. package/src/cli/check-forms.ts +654 -0
  30. package/src/cli/check-links.ts +619 -0
  31. package/src/cli/check.ts +367 -0
  32. package/src/cli/commands.ts +265 -0
  33. package/src/cli/index.ts +70 -0
  34. package/src/cli/inspect.ts +335 -0
  35. package/src/cli/new.ts +41 -0
  36. package/src/cli/upgrade-names.ts +209 -0
  37. package/src/cli/upgrade.ts +354 -0
  38. package/src/compiler/analyze.ts +618 -0
  39. package/src/compiler/ast.ts +82 -0
  40. package/src/compiler/browser-globals.ts +127 -0
  41. package/src/compiler/compliance-rgaa.ts +502 -0
  42. package/src/compiler/compliance.ts +497 -0
  43. package/src/compiler/data-keys.ts +295 -0
  44. package/src/compiler/dom-attrs.ts +379 -0
  45. package/src/compiler/dom.ts +566 -0
  46. package/src/compiler/emit.ts +131 -0
  47. package/src/compiler/expr-context.ts +408 -0
  48. package/src/compiler/index.ts +8 -0
  49. package/src/compiler/interactivity.ts +366 -0
  50. package/src/compiler/mistakes.ts +499 -0
  51. package/src/compiler/node-env.ts +50 -0
  52. package/src/compiler/patch.ts +97 -0
  53. package/src/compiler/props.ts +460 -0
  54. package/src/compiler/scope.ts +568 -0
  55. package/src/compiler/server-only.ts +326 -0
  56. package/src/compiler/shared.ts +369 -0
  57. package/src/compiler/signal-reads.ts +242 -0
  58. package/src/compiler/slots.ts +227 -0
  59. package/src/compiler/ssr-helpers.ts +555 -0
  60. package/src/compiler/ssr-island.ts +90 -0
  61. package/src/compiler/ssr-prunelle-tags.ts +56 -0
  62. package/src/compiler/ssr.ts +491 -0
  63. package/src/context.ts +165 -0
  64. package/src/dev/child.ts +30 -0
  65. package/src/dev/index.ts +208 -0
  66. package/src/dev/modules.ts +68 -0
  67. package/src/dev/protocol.ts +21 -0
  68. package/src/dev/queue.ts +79 -0
  69. package/src/dev/reload.ts +157 -0
  70. package/src/dev/supervisor.ts +187 -0
  71. package/src/dev/watchers.ts +215 -0
  72. package/src/dom/action.ts +164 -0
  73. package/src/dom/attrs.ts +72 -0
  74. package/src/dom/claim.ts +120 -0
  75. package/src/dom/extras.ts +562 -0
  76. package/src/dom/index.ts +289 -0
  77. package/src/dom/island.ts +284 -0
  78. package/src/dom/loop.ts +450 -0
  79. package/src/dom/revive.ts +36 -0
  80. package/src/index.ts +22 -0
  81. package/src/jsx-runtime.ts +566 -0
  82. package/src/plugins/config.ts +86 -0
  83. package/src/plugins/context.ts +66 -0
  84. package/src/plugins/index.ts +14 -0
  85. package/src/plugins/load.ts +70 -0
  86. package/src/plugins/order.ts +111 -0
  87. package/src/plugins/public.ts +12 -0
  88. package/src/plugins/requires.ts +47 -0
  89. package/src/plugins/services.ts +35 -0
  90. package/src/plugins/types.ts +242 -0
  91. package/src/reactivity/graph.ts +249 -0
  92. package/src/reactivity/index.ts +533 -0
  93. package/src/reactivity/selector.ts +51 -0
  94. package/src/reactivity/store.ts +208 -0
  95. package/src/server/action-protect.ts +186 -0
  96. package/src/server/action-registry.ts +78 -0
  97. package/src/server/action.ts +498 -0
  98. package/src/server/app-entry.ts +23 -0
  99. package/src/server/assets.ts +136 -0
  100. package/src/server/compress.ts +560 -0
  101. package/src/server/consent.ts +253 -0
  102. package/src/server/cookies.ts +139 -0
  103. package/src/server/document.ts +271 -0
  104. package/src/server/env.ts +33 -0
  105. package/src/server/errors.ts +382 -0
  106. package/src/server/form-schema.ts +343 -0
  107. package/src/server/health.ts +244 -0
  108. package/src/server/http.ts +508 -0
  109. package/src/server/index.ts +687 -0
  110. package/src/server/lifecycle.ts +75 -0
  111. package/src/server/loader.ts +118 -0
  112. package/src/server/page.ts +107 -0
  113. package/src/server/param-matchers.ts +112 -0
  114. package/src/server/plugin-host.ts +256 -0
  115. package/src/server/prerendered.ts +71 -0
  116. package/src/server/public.ts +19 -0
  117. package/src/server/rate-limit.ts +133 -0
  118. package/src/server/region.ts +96 -0
  119. package/src/server/request-body.ts +27 -0
  120. package/src/server/request-path.ts +73 -0
  121. package/src/server/request-scope.ts +22 -0
  122. package/src/server/route-table.ts +82 -0
  123. package/src/server/router.ts +261 -0
  124. package/src/server/routing.ts +377 -0
  125. package/src/server/security.ts +472 -0
  126. package/src/server/serve-handlers.ts +83 -0
  127. package/src/server/served-file.ts +128 -0
  128. package/src/server/standard-schema.ts +87 -0
  129. package/src/server/start.ts +99 -0
  130. package/src/server/static-dir.ts +167 -0
  131. package/src/server/stream.ts +192 -0
  132. package/src/ssr/context.ts +350 -0
  133. package/src/ssr/index.ts +596 -0
  134. package/src/ssr/navigation.ts +96 -0
  135. package/src/ssr/region.ts +171 -0
  136. package/src/style.ts +33 -0
  137. package/src/test/browser.ts +192 -0
  138. package/src/test/index.ts +191 -0
  139. package/src/unrenderable.ts +35 -0
  140. package/templates/_shared/AGENTS.md +10 -0
  141. package/templates/_shared/CLAUDE.md +1 -0
  142. package/templates/_shared/gitignore +3 -0
  143. package/templates/_shared/public/robots.txt +2 -0
  144. package/templates/_shared/src/routes/legal.tsx +13 -0
  145. package/templates/_shared/tsconfig.json +20 -0
  146. package/templates/app/.env.example +4 -0
  147. package/templates/app/package.json +21 -0
  148. package/templates/app/prunelle.config.ts +11 -0
  149. package/templates/app/src/auth.ts +14 -0
  150. package/templates/app/src/routes/_layout.tsx +32 -0
  151. package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
  152. package/templates/app/src/routes/dashboard/index.tsx +13 -0
  153. package/templates/app/src/routes/index.tsx +15 -0
  154. package/templates/app/src/routes/login.tsx +34 -0
  155. package/templates/app/src/styles/app.css +7 -0
  156. package/templates/app/tests/app.test.ts +32 -0
  157. package/templates/blog/content/posts/welcome.md +9 -0
  158. package/templates/blog/package.json +22 -0
  159. package/templates/blog/prunelle.config.ts +23 -0
  160. package/templates/blog/src/posts.ts +26 -0
  161. package/templates/blog/src/routes/_layout.tsx +20 -0
  162. package/templates/blog/src/routes/blog/[slug].tsx +31 -0
  163. package/templates/blog/src/routes/index.tsx +33 -0
  164. package/templates/blog/src/styles/app.css +10 -0
  165. package/templates/fullstack/package.json +19 -0
  166. package/templates/fullstack/prunelle.config.ts +6 -0
  167. package/templates/fullstack/src/actions/greet.ts +19 -0
  168. package/templates/fullstack/src/components/Counter.tsx +10 -0
  169. package/templates/fullstack/src/components/GreetForm.tsx +27 -0
  170. package/templates/fullstack/src/routes/_layout.tsx +14 -0
  171. package/templates/fullstack/src/routes/api/health.ts +5 -0
  172. package/templates/fullstack/src/routes/index.tsx +13 -0
  173. package/templates/fullstack/src/styles/app.css +29 -0
  174. package/templates/fullstack/tests/app.test.ts +37 -0
  175. package/templates/minimal/package.json +19 -0
  176. package/templates/minimal/prunelle.config.ts +6 -0
  177. package/templates/minimal/src/components/Counter.tsx +10 -0
  178. package/templates/minimal/src/routes/_layout.tsx +14 -0
  179. package/templates/minimal/src/routes/index.tsx +11 -0
  180. package/templates/minimal/src/styles/app.css +22 -0
  181. package/README.md +0 -3
@@ -0,0 +1,75 @@
1
+ // Graceful stop for `prunelle start` and compiled binaries; `prunelle dev` keeps its own.
2
+
3
+ import type { PrunelleApp } from './http'
4
+
5
+ const SIGNALS = ['SIGTERM', 'SIGINT', 'SIGHUP'] as const
6
+
7
+ export interface HandleSignalsOptions {
8
+ timeoutMs?: number | undefined
9
+ /** @internal Exit callback (defaults to `process.exit`). */
10
+ exit?: ((code: number) => void) | undefined
11
+ }
12
+
13
+ // On the first signal the server stops taking connections, ends long-lived streams, waits for open requests to drain, then runs onShutdown hooks; exits 0 when done, or 1 after `timeoutMs`.
14
+ export function handleSignals(
15
+ app: PrunelleApp,
16
+ server: ReturnType<PrunelleApp['serve']>,
17
+ { timeoutMs = 10_000, exit = (code: number) => process.exit(code) }: HandleSignalsOptions = {},
18
+ ): () => void {
19
+ let stopping = false
20
+ const listeners: [typeof SIGNALS[number], () => void][] = []
21
+
22
+ const stop = async (): Promise<void> => {
23
+ if (stopping)
24
+ return
25
+ stopping = true
26
+ let timedOut = false
27
+ const forced = setTimeout(() => {
28
+ timedOut = true
29
+ console.error(`prunelle: requests still open after ${timeoutMs} ms; closing them`)
30
+ exit(1)
31
+ }, timeoutMs)
32
+ let exitCode = 0
33
+ try {
34
+ const drained = server.stop()
35
+ try {
36
+ await app.closeStreams?.()
37
+ }
38
+ catch (error) {
39
+ exitCode = 1
40
+ console.error('prunelle: error closing streams during shutdown:', error)
41
+ }
42
+ await drained
43
+ }
44
+ catch (error) {
45
+ exitCode = 1
46
+ console.error('prunelle: error draining server during shutdown:', error)
47
+ }
48
+ finally {
49
+ try {
50
+ await app.dispose?.()
51
+ }
52
+ catch (error) {
53
+ exitCode = 1
54
+ console.error('prunelle: error disposing app during shutdown:', error)
55
+ }
56
+ clearTimeout(forced)
57
+ }
58
+ if (!timedOut)
59
+ exit(exitCode)
60
+ }
61
+
62
+ for (const signal of SIGNALS) {
63
+ const listener = () => {
64
+ void stop()
65
+ }
66
+ listeners.push([signal, listener])
67
+ process.on(signal, listener)
68
+ }
69
+
70
+ return () => {
71
+ for (const [signal, listener] of listeners)
72
+ process.off(signal, listener)
73
+ listeners.length = 0
74
+ }
75
+ }
@@ -0,0 +1,118 @@
1
+ // Filesystem server loader: reads `dist/manifest.json`, maps the built assets on disk, and starts the app from `dist/server/_entry.js` (or serves a `--static` dir).
2
+
3
+ import type { BuildManifest } from '../build/index'
4
+ import type { ServerEntry } from './app-entry'
5
+ import type { EmbeddedBody, PrunelleApp, ServerOptions } from './http'
6
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
7
+ import { join, resolve } from 'node:path'
8
+ import { SERVER_ENTRY_FILE } from '../build/server-entry'
9
+ import { loadConfig, resolveServerConfig } from '../plugins/index'
10
+ import { createStaticDirServer } from './static-dir'
11
+
12
+ let serverLoadSeq = 0
13
+
14
+ export async function createServer(options: ServerOptions): Promise<PrunelleApp> {
15
+ return (await startBuiltApp(options)).app
16
+ }
17
+
18
+ /** The app, the folder it was built into, and the entry it was assembled from, whose bundled modules `testApp().import()` and the prerender step read. */
19
+ export async function startBuiltApp(options: ServerOptions): Promise<{ app: PrunelleApp, outDir: string, entry?: ServerEntry | undefined }> {
20
+ const built = await loadServerEntry(options)
21
+ if (built.entry === undefined)
22
+ return { app: await serveStaticDir(options, built.root, built.outDir), outDir: built.outDir }
23
+ const { root, outDir, manifest, entry } = built
24
+ const clientDir = join(outDir, 'client')
25
+ const assets: Record<string, EmbeddedBody> = {}
26
+ const publicAssets: Record<string, EmbeddedBody> = {}
27
+ const publicEtags: Record<string, string> = {}
28
+ const prerenderedFiles: Record<string, string> = {}
29
+ const srcPublicDir = resolve(root, entry.prunelleConfig.publicDir ?? 'public')
30
+
31
+ // File paths only: Bun.file() serves them zero-copy, and nothing is read at startup.
32
+ const withSidecars = (files: Record<string, EmbeddedBody>, rel: string, abs: string): void => {
33
+ files[rel] = abs
34
+ for (const ext of ['.br', '.gz']) {
35
+ if (existsSync(`${abs}${ext}`))
36
+ files[`${rel}${ext}`] = `${abs}${ext}`
37
+ }
38
+ }
39
+ for (const rel of [...manifest.assets, ...(manifest.carriedAssets ?? [])]) {
40
+ const abs = join(clientDir, rel)
41
+ if (existsSync(abs))
42
+ withSidecars(assets, rel, abs)
43
+ }
44
+
45
+ for (const rel of manifest.publicFiles ?? []) {
46
+ const outAbs = join(outDir, 'public', rel)
47
+ const abs = existsSync(outAbs) ? outAbs : join(srcPublicDir, rel)
48
+ if (existsSync(abs)) {
49
+ withSidecars(publicAssets, rel, abs)
50
+ const st = statSync(abs)
51
+ publicEtags[rel] = `W/"${st.size.toString(36)}-${Math.floor(st.mtimeMs).toString(36)}"`
52
+ }
53
+ }
54
+
55
+ for (const r of manifest.routes) {
56
+ for (const relHtml of Object.values(r.prerendered ?? {})) {
57
+ const abs = join(outDir, relHtml)
58
+ if (existsSync(abs))
59
+ withSidecars(prerenderedFiles, relHtml, abs)
60
+ }
61
+ }
62
+
63
+ const app = await entry.createApp({
64
+ ...resolveServerConfig(undefined, options),
65
+ manifest,
66
+ assets,
67
+ publicAssets,
68
+ publicEtags,
69
+ prerenderedFiles,
70
+ root,
71
+ outDir,
72
+ publicDir: join(outDir, 'public'),
73
+ dev: options.dev ?? (process.env.PRUNELLE_DEV === '1'),
74
+ nodeEnv: options.nodeEnv,
75
+ errorSink: options.errorSink,
76
+ prerender: options.prerender,
77
+ })
78
+ return { app, outDir, entry }
79
+ }
80
+
81
+ type BuiltOutput =
82
+ | { root: string, outDir: string, manifest: BuildManifest, entry: ServerEntry }
83
+ | { root: string, outDir: string, entry?: undefined }
84
+
85
+ /** Finds the build output and imports its server entry; a `--static` export has none. */
86
+ async function loadServerEntry(options: ServerOptions): Promise<BuiltOutput> {
87
+ const root = resolve(options.root)
88
+ let outDir = resolve(root, options.outDir ?? 'dist')
89
+ // prunelle.config.ts is read natively only to find an `outDir` it moved; the app itself runs from its bundled copy.
90
+ if (options.outDir === undefined && !existsSync(join(outDir, 'manifest.json')))
91
+ outDir = resolve(root, (await loadConfig(root, { dev: options.dev, nodeEnv: options.nodeEnv })).outDir ?? 'dist')
92
+ const manifestPath = join(outDir, 'manifest.json')
93
+ if (!existsSync(manifestPath)) {
94
+ if (existsSync(outDir) && readdirSync(outDir).length > 0)
95
+ return { root, outDir }
96
+ throw new Error(`prunelle server: missing ${manifestPath}. Run build() first.`)
97
+ }
98
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as BuildManifest
99
+ const entryPath = join(outDir, 'server', SERVER_ENTRY_FILE)
100
+ if (!existsSync(entryPath))
101
+ throw new Error(`prunelle server: missing ${entryPath}, the server entry prunelle build writes. Run prunelle build again.`)
102
+ const stamp = `${Date.now()}-${++serverLoadSeq}`
103
+ const importModule = options.importModule ?? ((path: string) => import(`${path}?v=${stamp}`))
104
+ const entry = await importModule(entryPath) as unknown as ServerEntry
105
+ return { root, outDir, manifest, entry }
106
+ }
107
+
108
+ async function serveStaticDir(options: ServerOptions, root: string, outDir: string): Promise<PrunelleApp> {
109
+ const config = await loadConfig(root, { dev: options.dev, nodeEnv: options.nodeEnv })
110
+ return createStaticDirServer(
111
+ outDir,
112
+ options.assetPrefix ?? config.assetPrefix ?? '/_pru',
113
+ options.security ?? config.security,
114
+ (options.compress ?? config.compress) !== false,
115
+ options.trustProxy ?? config.trustProxy ?? false,
116
+ options.dev ?? (process.env.PRUNELLE_DEV === '1'),
117
+ )
118
+ }
@@ -0,0 +1,107 @@
1
+ // What a route file is to the server: the page, layout and middleware modules it loads, and the answers derived from their exports.
2
+
3
+ import type { BuildManifest, RouteManifestEntry } from '../build/index'
4
+ import type { Html } from '../jsx-runtime'
5
+ import type { Middleware, RequestContext } from './http'
6
+ import type { PrunelleLocals } from './index'
7
+
8
+ export interface LoadedPageModule {
9
+ default?: (props: Record<string, unknown>) => Html | string | Promise<Html | string>
10
+ load?: (ctx: RequestContext) => unknown | Promise<unknown>
11
+ clientData?: readonly string[] | ((data: unknown) => unknown) | undefined
12
+ csrf?: boolean | undefined
13
+ GET?: (ctx: RequestContext) => Response | Promise<Response>
14
+ POST?: (ctx: RequestContext) => Response | Promise<Response>
15
+ PUT?: (ctx: RequestContext) => Response | Promise<Response>
16
+ PATCH?: (ctx: RequestContext) => Response | Promise<Response>
17
+ DELETE?: (ctx: RequestContext) => Response | Promise<Response>
18
+ HEAD?: (ctx: RequestContext) => Response | Promise<Response>
19
+ OPTIONS?: (ctx: RequestContext) => Response | Promise<Response>
20
+ [key: string]: unknown
21
+ }
22
+
23
+ export interface LoadedLayoutModule {
24
+ default: (props: { children: Html, url?: URL, params?: Record<string, string>, locals?: PrunelleLocals }) => Html | string | Promise<Html | string>
25
+ }
26
+
27
+ export interface LoadedMiddlewareModule {
28
+ default: Middleware
29
+ }
30
+
31
+ const HTTP_METHOD_EXPORTS = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'] as const
32
+
33
+ export function mergedHeadTags(manifest: BuildManifest, entry: RouteManifestEntry): string[] | undefined {
34
+ return entry.headTags !== undefined && entry.headTags.length > 0
35
+ ? [...(manifest.headTags ?? []), ...entry.headTags]
36
+ : manifest.headTags
37
+ }
38
+
39
+ export function allowedMethodsHeader(mod: LoadedPageModule): string {
40
+ const allowed = new Set<string>()
41
+ if (typeof mod.default === 'function') {
42
+ allowed.add('GET')
43
+ allowed.add('HEAD')
44
+ }
45
+ for (const m of HTTP_METHOD_EXPORTS) {
46
+ if (typeof mod[m] === 'function')
47
+ allowed.add(m)
48
+ }
49
+ if (allowed.has('GET'))
50
+ allowed.add('HEAD')
51
+ return [...allowed].join(', ')
52
+ }
53
+
54
+ async function cancelBodyQuietly(body: ReadableStream<Uint8Array>): Promise<void> {
55
+ try {
56
+ await body.cancel()
57
+ }
58
+ catch {}
59
+ }
60
+
61
+ export function stripHeadBody(res: Response): Response {
62
+ if (res.body !== null)
63
+ void cancelBodyQuietly(res.body)
64
+ return new Response(null, { status: res.status, statusText: res.statusText, headers: res.headers })
65
+ }
66
+
67
+ export function isPlainObject(v: unknown): v is Record<string, unknown> {
68
+ return typeof v === 'object' && v !== null && !Array.isArray(v)
69
+ }
70
+
71
+ function pickObjectKeys(obj: Record<string, unknown>, keys: readonly string[]): Record<string, unknown> | undefined {
72
+ if (keys.length === 0)
73
+ return undefined
74
+ const picked: Record<string, unknown> = {}
75
+ let count = 0
76
+ for (const k of keys) {
77
+ if (Object.hasOwn(obj, k)) {
78
+ Object.defineProperty(picked, k, { value: obj[k], enumerable: true, writable: true, configurable: true })
79
+ count++
80
+ }
81
+ }
82
+ return count > 0 ? picked : undefined
83
+ }
84
+
85
+ export function pickPageIslandProps(data: unknown, entry: RouteManifestEntry, mod: LoadedPageModule): Record<string, unknown> {
86
+ if (data === undefined)
87
+ return {}
88
+ if (typeof mod.clientData === 'function') {
89
+ const subset = mod.clientData(data)
90
+ return subset === undefined ? {} : { data: subset }
91
+ }
92
+ if (Array.isArray(mod.clientData)) {
93
+ if (!isPlainObject(data))
94
+ return {}
95
+ const subset = pickObjectKeys(data, mod.clientData)
96
+ return subset === undefined ? {} : { data: subset }
97
+ }
98
+ if (entry.islandDataKeys !== undefined) {
99
+ if (entry.islandDataKeys.length === 0)
100
+ return {}
101
+ if (isPlainObject(data)) {
102
+ const subset = pickObjectKeys(data, entry.islandDataKeys)
103
+ return subset === undefined ? {} : { data: subset }
104
+ }
105
+ }
106
+ return { data }
107
+ }
@@ -0,0 +1,112 @@
1
+ // Route parameter matchers (built-in `integer`, `uuid`, `slug` and app-defined `src/params/<name>.ts`) and shared route-pattern segment parsing.
2
+
3
+ export type ParamMatcher = (value: string) => boolean
4
+ export type ParamMatcherMap = Readonly<Record<string, ParamMatcher>>
5
+
6
+ const INTEGER_RE = /^\d+$/
7
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
8
+ const SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
9
+
10
+ export const BUILTIN_PARAM_MATCHERS: ParamMatcherMap = {
11
+ integer: value => INTEGER_RE.test(value),
12
+ uuid: value => UUID_RE.test(value),
13
+ slug: value => SLUG_RE.test(value),
14
+ }
15
+
16
+ export const BUILTIN_PARAM_MATCHER_NAMES = ['integer', 'uuid', 'slug'] as const
17
+
18
+ export function isBuiltinMatcher(name: string): boolean {
19
+ return Object.hasOwn(BUILTIN_PARAM_MATCHERS, name)
20
+ }
21
+
22
+ /** Extracts a matcher function from an app param matcher module (`export function match` or `export default`). */
23
+ export function extractMatcherFn(mod: unknown): ParamMatcher | undefined {
24
+ if (typeof mod === 'function')
25
+ return mod as ParamMatcher
26
+ if (mod !== null && typeof mod === 'object') {
27
+ const rec = mod as Record<string, unknown>
28
+ if (typeof rec.match === 'function')
29
+ return rec.match as ParamMatcher
30
+ if (typeof rec.default === 'function')
31
+ return rec.default as ParamMatcher
32
+ }
33
+ return undefined
34
+ }
35
+
36
+ /** Merges built-in matchers with app matchers listed in the build manifest. */
37
+ export function resolveParamMatchers(
38
+ manifestMatchers: Readonly<Record<string, string>> | undefined,
39
+ modules: Readonly<Record<string, unknown>>,
40
+ ): ParamMatcherMap {
41
+ if (manifestMatchers === undefined)
42
+ return BUILTIN_PARAM_MATCHERS
43
+ const merged: Record<string, ParamMatcher> = { ...BUILTIN_PARAM_MATCHERS }
44
+ for (const [name, modKey] of Object.entries(manifestMatchers)) {
45
+ const fn = extractMatcherFn(modules[modKey])
46
+ if (fn !== undefined)
47
+ merged[name] = fn
48
+ }
49
+ return merged
50
+ }
51
+
52
+ export interface ParsedPatternSegment {
53
+ kind: 'static' | 'param' | 'optional' | 'catchall'
54
+ /** Exact literal for static, parameter name for param/optional/catchall. */
55
+ value: string
56
+ matcherName?: string | undefined
57
+ }
58
+
59
+ function splitNameAndMatcher(spec: string, fallbackName?: string): { name: string, matcherName?: string | undefined } {
60
+ const eq = spec.indexOf('=')
61
+ if (eq === -1)
62
+ return { name: spec || fallbackName || '' }
63
+ const name = spec.slice(0, eq) || fallbackName || ''
64
+ const matcherName = spec.slice(eq + 1)
65
+ return matcherName.length > 0 ? { name, matcherName } : { name }
66
+ }
67
+
68
+ /** Parses one segment of a compiled route pattern (`about`, `:id`, `:id=integer`, `:lang?`, `:page=integer?`, `*rest`, `*path=slug`). */
69
+ export function parsePatternSegment(seg: string): ParsedPatternSegment {
70
+ if (seg.startsWith('*')) {
71
+ const { name, matcherName } = splitNameAndMatcher(seg.slice(1), 'rest')
72
+ return { kind: 'catchall', value: name, matcherName }
73
+ }
74
+ if (seg.startsWith(':')) {
75
+ const body = seg.slice(1)
76
+ const optional = body.endsWith('?')
77
+ const spec = optional ? body.slice(0, -1) : body
78
+ const { name, matcherName } = splitNameAndMatcher(spec)
79
+ return { kind: optional ? 'optional' : 'param', value: name, matcherName }
80
+ }
81
+ return { kind: 'static', value: seg }
82
+ }
83
+
84
+ /** Lists every param matcher reference in a compiled route pattern (e.g. `'/users/:id=integer'` -> `[{ param: 'id', matcher: 'integer' }]`). */
85
+ export function extractPatternMatchers(routePath: string): { param: string, matcher: string }[] {
86
+ const result: { param: string, matcher: string }[] = []
87
+ if (!routePath.includes('='))
88
+ return result
89
+ for (const seg of routePath.split('/')) {
90
+ if (seg === '')
91
+ continue
92
+ const parsed = parsePatternSegment(seg)
93
+ if (parsed.matcherName !== undefined)
94
+ result.push({ param: parsed.value, matcher: parsed.matcherName })
95
+ }
96
+ return result
97
+ }
98
+
99
+ /** Lists optional parameter names in a compiled route pattern (e.g. `'/:lang?/about'` -> `['lang']`). */
100
+ export function extractOptionalParams(routePath: string): string[] {
101
+ const result: string[] = []
102
+ if (!routePath.includes('?'))
103
+ return result
104
+ for (const seg of routePath.split('/')) {
105
+ if (seg === '')
106
+ continue
107
+ const parsed = parsePatternSegment(seg)
108
+ if (parsed.kind === 'optional')
109
+ result.push(parsed.value)
110
+ }
111
+ return result
112
+ }
@@ -0,0 +1,256 @@
1
+ // What plugins see of a running server: each `server(api)` hook, and the middleware, routes, rewrites and shutdown hooks those hooks register.
2
+
3
+ import type { BuildManifest } from '../build/index'
4
+ import type { AppRuntimeContext } from '../plugins/context'
5
+ import type { PrunellePlugin, MiddlewareOptions, PluginRouteOptions, ServerPluginAPI } from '../plugins/index'
6
+ import type { HealthCheckEntry } from './health'
7
+ import type { EmbeddedServerConfig, Middleware, RequestContext } from './http'
8
+
9
+ import type { TrustProxy } from './security'
10
+ import { runWithAppContext } from '../plugins/context'
11
+ import { enforceRequirements } from '../plugins/requires'
12
+ import { normalizeConsentConfig, registerConsentRoute } from './consent'
13
+ import { assertRateLimit, createRateLimitStore, hitFor, tooManyRequests } from './rate-limit'
14
+ import type { RequestPath } from './request-path'
15
+ import type { RouteMatch } from './router'
16
+ import { Router } from './router'
17
+
18
+ export interface PluginRouteDef {
19
+ plugin: string
20
+ handler: (ctx: RequestContext) => Response | Promise<Response>
21
+ csrf: boolean
22
+ trustedOrigins: Set<string> | undefined
23
+ trustProxy: TrustProxy
24
+ /** The catch-all takes an encoded separator for this method (`PluginRouteOptions.encodedSlashes`). */
25
+ encodedSlashes: boolean
26
+ }
27
+
28
+ interface ScopedMiddleware {
29
+ mw: Middleware
30
+ scope: 'all' | 'rendered' | 'dynamic' | string
31
+ }
32
+
33
+ /** What a request reaches, as middleware scopes see it: a page built ahead of time, a page with no `load` that renders the same for everyone, or anything else answered per request. */
34
+ export type RequestKind = 'prerendered' | 'static' | 'dynamic'
35
+
36
+ const isKindScope = (scope: string): boolean => scope === 'all' || scope === 'rendered' || scope === 'dynamic'
37
+
38
+ export interface ServerPluginHostOptions {
39
+ plugins: readonly PrunellePlugin[]
40
+ config: EmbeddedServerConfig
41
+ manifest: BuildManifest
42
+ appCtx: AppRuntimeContext
43
+ root: string
44
+ outDir: string
45
+ assetPrefix: string
46
+ site: string | undefined
47
+ dev: boolean
48
+ trustProxy: TrustProxy
49
+ trustedOriginsList: readonly string[]
50
+ trustedOrigins: Set<string> | undefined
51
+ }
52
+
53
+ function middlewareAppliesToPath(scope: ScopedMiddleware['scope'], path: string, kind: RequestKind): boolean {
54
+ if (scope === 'all')
55
+ return true
56
+ if (scope === 'rendered')
57
+ return kind !== 'prerendered'
58
+ if (scope === 'dynamic')
59
+ return kind === 'dynamic'
60
+ const normScope = scope.length > 1 && scope.endsWith('/') ? scope.slice(0, -1) : scope
61
+ const normPath = path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path
62
+ if (normScope === '/')
63
+ return normPath.startsWith('/')
64
+ return normPath === normScope || normPath.startsWith(`${normScope}/`)
65
+ }
66
+
67
+ /** The methods of `match` that may answer `path`: for a path with an encoded separator, only those that set `encodedSlashes`; none left is no match. */
68
+ export function takesEncoded(match: RouteMatch<Map<string, PluginRouteDef>> | undefined, path: RequestPath): RouteMatch<Map<string, PluginRouteDef>> | undefined {
69
+ if (match === undefined || path.encoded === undefined || path.encoded.size === 0)
70
+ return match
71
+ const data = new Map([...match.data].filter(([, def]) => def.encodedSlashes))
72
+ return data.size === 0 ? undefined : { data, params: match.params }
73
+ }
74
+
75
+ export function allowedPluginMethodsHeader(methods: ReadonlyMap<string, PluginRouteDef>): string {
76
+ const allowed = new Set<string>()
77
+ for (const m of methods.keys()) {
78
+ if (m === 'ALL')
79
+ continue
80
+ allowed.add(m)
81
+ }
82
+ if (allowed.has('GET'))
83
+ allowed.add('HEAD')
84
+ return [...allowed].join(', ')
85
+ }
86
+
87
+ function assertRouteFree(pluginName: string, upperMethod: string, normPath: string, byMethod: ReadonlyMap<string, PluginRouteDef>): void {
88
+ const directConflict = byMethod.get(upperMethod)
89
+ if (directConflict !== undefined)
90
+ throw new Error(`prunelle: plugin "${pluginName}" registered ${upperMethod} ${normPath}, which collides with "${directConflict.plugin}". Mount one of the plugins on a different path.`)
91
+ if (upperMethod === 'ALL' && byMethod.size > 0) {
92
+ const [existingMethod, existingDef] = byMethod.entries().next().value!
93
+ throw new Error(`prunelle: plugin "${pluginName}" registered ALL ${normPath}, which collides with ${existingMethod} ${normPath} from "${existingDef.plugin}". Mount one of the plugins on a different path.`)
94
+ }
95
+ const allConflict = byMethod.get('ALL')
96
+ if (allConflict !== undefined)
97
+ throw new Error(`prunelle: plugin "${pluginName}" registered ${upperMethod} ${normPath}, which collides with ALL ${normPath} from "${allConflict.plugin}". Mount one of the plugins on a different path.`)
98
+ }
99
+
100
+ export async function createServerPluginHost(options: ServerPluginHostOptions) {
101
+ const { plugins, config, manifest, appCtx, trustedOrigins, trustProxy } = options
102
+ // The counters of every limited route and action of this server, dropped with it.
103
+ const rateLimits = createRateLimitStore()
104
+ const scopedMiddlewares: ScopedMiddleware[] = []
105
+ const healthChecks: HealthCheckEntry[] = []
106
+ const shutdownHooks: { plugin: string, hook: () => void | Promise<void> }[] = []
107
+ const rewrites: ((pathname: string, ctx: RequestContext) => string | undefined)[] = []
108
+ const router = new Router<Map<string, PluginRouteDef>>()
109
+ const routeEntries = new Map<string, Map<string, PluginRouteDef>>()
110
+
111
+ const registerRouteFor = (pluginName: string) => (
112
+ method: string,
113
+ path: string,
114
+ handler: (ctx: RequestContext) => Response | Promise<Response>,
115
+ routeOptions?: PluginRouteOptions,
116
+ ): void => {
117
+ const upperMethod = method.toUpperCase()
118
+ const normPath = path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path
119
+ const encodedSlashes = routeOptions?.encodedSlashes === true
120
+ if (encodedSlashes && !normPath.split('/').some(seg => seg.startsWith('*')))
121
+ throw new Error(`prunelle: plugin "${pluginName}" set encodedSlashes on ${upperMethod} ${normPath}, which has no catch-all: only a \`*name\` segment takes an encoded /, so end the path with one, or drop the option.`)
122
+ let byMethod = routeEntries.get(normPath)
123
+ if (byMethod === undefined) {
124
+ byMethod = new Map()
125
+ routeEntries.set(normPath, byMethod)
126
+ router.add(normPath, byMethod, { encodedSlashes })
127
+ }
128
+ else {
129
+ assertRouteFree(pluginName, upperMethod, normPath, byMethod)
130
+ // The path matches encoded separators once any method takes them; takesEncoded still refuses them to the others.
131
+ if (encodedSlashes)
132
+ router.add(normPath, byMethod, { encodedSlashes })
133
+ }
134
+ let routeTrustedOrigins = trustedOrigins
135
+ if (routeOptions?.trustedOrigins !== undefined && routeOptions.trustedOrigins.length > 0) {
136
+ routeTrustedOrigins = new Set([...(trustedOrigins ?? []), ...routeOptions.trustedOrigins])
137
+ }
138
+ const limit = routeOptions?.rateLimit
139
+ let limited = handler
140
+ if (limit !== undefined) {
141
+ assertRateLimit(limit, `${upperMethod} ${normPath} from "${pluginName}"`)
142
+ const limiter = rateLimits.limiter(limit)
143
+ limited = (ctx) => {
144
+ const retryAfter = hitFor(limiter, limit, ctx)
145
+ return retryAfter > 0 ? tooManyRequests(retryAfter) : handler(ctx)
146
+ }
147
+ }
148
+ byMethod.set(upperMethod, {
149
+ plugin: pluginName,
150
+ handler: limited,
151
+ csrf: routeOptions?.csrf ?? true,
152
+ trustedOrigins: routeTrustedOrigins,
153
+ trustProxy: routeOptions?.trustProxy ?? trustProxy,
154
+ encodedSlashes,
155
+ })
156
+ }
157
+
158
+ const consentConfig = normalizeConsentConfig(config.consent)
159
+ if (consentConfig !== undefined)
160
+ registerConsentRoute(registerRouteFor('pru:consent'), consentConfig, trustedOrigins, trustProxy)
161
+
162
+ const {
163
+ manifest: _m,
164
+ modules: _mods,
165
+ assets: _a,
166
+ publicAssets: _pa,
167
+ publicEtags: _pe,
168
+ prerendered: _pr,
169
+ prerenderedFiles: _pf,
170
+ ...forwardedConfig
171
+ } = config as EmbeddedServerConfig & Record<string, unknown>
172
+ const readonlyRuntimeConfig: Readonly<Record<string, unknown>> = Object.freeze({ ...forwardedConfig })
173
+
174
+ if (config.prerender !== true) {
175
+ const production = !options.dev && (appCtx.nodeEnv ?? process.env.NODE_ENV) === 'production'
176
+ await runWithAppContext(appCtx, () => enforceRequirements(plugins, { root: options.root, site: options.site }, production))
177
+ }
178
+ for (const plugin of plugins) {
179
+ if (plugin.server !== undefined) {
180
+ const pluginApi: ServerPluginAPI = {
181
+ root: options.root,
182
+ outDir: options.outDir,
183
+ assetPrefix: options.assetPrefix,
184
+ site: options.site,
185
+ dev: options.dev,
186
+ trustProxy,
187
+ trustedOrigins: options.trustedOriginsList,
188
+ config: readonlyRuntimeConfig,
189
+ use(mw: Middleware, middlewareOptions?: MiddlewareOptions) {
190
+ scopedMiddlewares.push({ mw, scope: middlewareOptions?.scope ?? 'all' })
191
+ },
192
+ route: registerRouteFor(plugin.name),
193
+ rateLimiter(limit) {
194
+ assertRateLimit(limit, `the rateLimiter of "${plugin.name}"`)
195
+ return rateLimits.limiter(limit)
196
+ },
197
+ rewrite(fn) {
198
+ rewrites.push(fn)
199
+ },
200
+ provide: appCtx.provide,
201
+ inject: appCtx.inject,
202
+ getBuildData<T = Record<string, unknown>>(pluginName?: string): T | undefined {
203
+ return manifest.pluginData?.[pluginName ?? plugin.name] as T | undefined
204
+ },
205
+ healthCheck(name, fn) {
206
+ healthChecks.push({ name, fn })
207
+ },
208
+ onShutdown(fn) {
209
+ shutdownHooks.push({ plugin: plugin.name, hook: fn })
210
+ },
211
+ }
212
+ await runWithAppContext(appCtx, () => plugin.server!(pluginApi))
213
+ }
214
+ }
215
+
216
+ const allMiddlewares: readonly Middleware[] = scopedMiddlewares.map(m => m.mw)
217
+ const hasPathScopedMiddlewares = scopedMiddlewares.some(m => !isKindScope(m.scope))
218
+ // With no path-scoped middleware the list depends on the kind alone, so it is worked out once per kind.
219
+ const byKind: Record<RequestKind, readonly Middleware[]> = {
220
+ prerendered: scopedMiddlewares.filter(m => middlewareAppliesToPath(m.scope, '/', 'prerendered')).map(m => m.mw),
221
+ static: scopedMiddlewares.filter(m => middlewareAppliesToPath(m.scope, '/', 'static')).map(m => m.mw),
222
+ dynamic: allMiddlewares,
223
+ }
224
+ const middlewaresFor = (path: string, kind: RequestKind = 'dynamic'): readonly Middleware[] => {
225
+ if (!hasPathScopedMiddlewares)
226
+ return byKind[kind]
227
+ return scopedMiddlewares.filter(m => middlewareAppliesToPath(m.scope, path, kind)).map(m => m.mw)
228
+ }
229
+ const middlewaresForPaths = (paths: readonly string[], kind: RequestKind = 'dynamic'): readonly Middleware[] => {
230
+ if (!hasPathScopedMiddlewares)
231
+ return byKind[kind]
232
+ return scopedMiddlewares
233
+ .filter(m => paths.some(path => middlewareAppliesToPath(m.scope, path, kind)))
234
+ .map(m => m.mw)
235
+ }
236
+
237
+ let disposed = false
238
+ async function dispose(): Promise<void> {
239
+ if (disposed)
240
+ return
241
+ disposed = true
242
+ rateLimits.close()
243
+ for (const { plugin, hook } of shutdownHooks) {
244
+ try {
245
+ await hook()
246
+ }
247
+ catch (error) {
248
+ console.error(`prunelle: the onShutdown hook of ${plugin} threw; the other hooks still run.`, error)
249
+ }
250
+ }
251
+ }
252
+
253
+ return { router, rewrites, healthChecks, allMiddlewares, hasPathScopedMiddlewares, middlewaresFor, middlewaresForPaths, rateLimits, dispose }
254
+ }
255
+
256
+ export type ServerPluginHost = Awaited<ReturnType<typeof createServerPluginHost>>