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,87 @@
1
+ // Standard Schema v1 spec types (https://standardschema.dev) — works with Zod, Valibot, ArkType, TypeBox, etc.
2
+
3
+ export interface StandardSchemaIssue {
4
+ readonly message: string
5
+ readonly path?: ReadonlyArray<PropertyKey | { readonly key: PropertyKey }> | undefined
6
+ }
7
+
8
+ export interface StandardSchemaV1<Input = unknown, Output = Input> {
9
+ readonly '~standard': {
10
+ readonly version: 1
11
+ readonly vendor: string
12
+ readonly validate: (value: unknown) =>
13
+ | { readonly value: Output, readonly issues?: undefined }
14
+ | { readonly issues: ReadonlyArray<StandardSchemaIssue> }
15
+ | Promise<
16
+ | { readonly value: Output, readonly issues?: undefined }
17
+ | { readonly issues: ReadonlyArray<StandardSchemaIssue> }
18
+ >
19
+ readonly types?: { readonly input: Input, readonly output: Output } | undefined
20
+ }
21
+ }
22
+
23
+ export type InferInput<S extends StandardSchemaV1> = NonNullable<S['~standard']['types']>['input']
24
+ export type InferOutput<S extends StandardSchemaV1> = NonNullable<S['~standard']['types']>['output']
25
+
26
+ export interface ValidationFailure {
27
+ ok: false
28
+ issues: ReadonlyArray<StandardSchemaIssue>
29
+ fieldErrors: Record<string, string>
30
+ }
31
+
32
+ export interface ValidationSuccess<T> {
33
+ ok: true
34
+ value: T
35
+ }
36
+
37
+ export type ValidationResult<T> = ValidationSuccess<T> | ValidationFailure
38
+
39
+ export function formatIssuePath(issue: StandardSchemaIssue): string {
40
+ if (!issue.path || issue.path.length === 0)
41
+ return ''
42
+ return issue.path
43
+ .map(seg => (typeof seg === 'object' && seg !== null && 'key' in seg ? String(seg.key) : String(seg)))
44
+ .join('.')
45
+ }
46
+
47
+ export function formatSchemaIssues(issues: ReadonlyArray<StandardSchemaIssue>): string {
48
+ return issues
49
+ .map((issue) => {
50
+ const path = formatIssuePath(issue)
51
+ return path ? `${path}: ${issue.message}` : issue.message
52
+ })
53
+ .join('; ')
54
+ }
55
+
56
+ function buildValidationFailure(issues: ReadonlyArray<StandardSchemaIssue>): ValidationFailure {
57
+ const fieldErrors: Record<string, string> = {}
58
+ for (const issue of issues) {
59
+ const key = formatIssuePath(issue)
60
+ if (!Object.hasOwn(fieldErrors, key))
61
+ Object.defineProperty(fieldErrors, key, { value: issue.message, enumerable: true, writable: true, configurable: true })
62
+ }
63
+ return { ok: false, issues, fieldErrors }
64
+ }
65
+
66
+ export function validateSchemaSync<S extends StandardSchemaV1>(
67
+ schema: S,
68
+ input: unknown,
69
+ asyncErrorMessage = 'prunelle: synchronous Standard Schema validator required',
70
+ ): ValidationResult<InferOutput<S>> {
71
+ const res = schema['~standard'].validate(input)
72
+ if (res instanceof Promise)
73
+ throw new TypeError(asyncErrorMessage)
74
+ if (res.issues && res.issues.length > 0)
75
+ return buildValidationFailure(res.issues)
76
+ return { ok: true, value: (res as { value: InferOutput<S> }).value }
77
+ }
78
+
79
+ export async function validateSchema<S extends StandardSchemaV1>(
80
+ schema: S,
81
+ input: unknown,
82
+ ): Promise<ValidationResult<InferOutput<S>>> {
83
+ const res = await schema['~standard'].validate(input)
84
+ if (res.issues && res.issues.length > 0)
85
+ return buildValidationFailure(res.issues)
86
+ return { ok: true, value: (res as { value: InferOutput<S> }).value }
87
+ }
@@ -0,0 +1,99 @@
1
+ // `prunelle start`: serves the built app, and reloads it in-process when a `prunelle build` swaps a new outDir in, so a deploy needs no restart.
2
+
3
+ import type { FSWatcher } from 'node:fs'
4
+ import type { PrunelleApp, PrunelleServer } from './http'
5
+ import { existsSync, readdirSync, watch } from 'node:fs'
6
+ import { basename, dirname, join, relative } from 'node:path'
7
+ import { startBuiltApp } from './loader'
8
+
9
+ /** How long a swap may leave the outDir missing before the server goes back to the build it had. */
10
+ const SWAP_TIMEOUT_MS = 2000
11
+
12
+ export interface StartOptions {
13
+ root: string
14
+ port: number
15
+ hostname: string
16
+ }
17
+
18
+ /** The server, and an app that forwards to whichever build it serves, for `handleSignals()`. */
19
+ export async function startServer(options: StartOptions): Promise<{ app: PrunelleApp, server: PrunelleServer }> {
20
+ const first = await startBuiltApp({ root: options.root })
21
+ let current = first.app
22
+ const server = current.serve(options.port, options.hostname)
23
+ const app: PrunelleApp = {
24
+ handle: async (request, remoteIp) => current.handle(request, remoteIp),
25
+ serve: () => server,
26
+ closeStreams: async () => current.closeStreams?.(),
27
+ dispose: async () => {
28
+ watcher?.close()
29
+ await current.dispose?.()
30
+ },
31
+ }
32
+ const watcher = current.reloadInto !== undefined
33
+ ? watchSwaps(first.outDir, first.entry === undefined, () => current, next => current = next, options.root, server)
34
+ : undefined
35
+ return { app, server }
36
+ }
37
+
38
+ /** Watches the folder holding `outDir` for the rename a build's swap makes, then loads the new build and swaps its handlers in. */
39
+ function watchSwaps(outDir: string, isStatic: boolean, current: () => PrunelleApp, setCurrent: (app: PrunelleApp) => void, root: string, server: PrunelleServer): FSWatcher {
40
+ const name = basename(outDir)
41
+ const shown = relative(root, outDir) || '.'
42
+ // A `--static` export has no manifest: the folder being back with files in it is the sign.
43
+ const landed = (): boolean => existsSync(join(outDir, 'manifest.json')) || (isStatic && existsSync(outDir) && readdirSync(outDir).length > 0)
44
+ let held: { promise: Promise<PrunelleApp>, resolve: (app: PrunelleApp) => void } | undefined
45
+ let loading = false
46
+ let again = false
47
+ let timer: ReturnType<typeof setTimeout> | undefined
48
+
49
+ // From the first rename until the new build answers, requests wait for it: no page of the old build links an asset the new one dropped.
50
+ const hold = (): void => {
51
+ if (held !== undefined)
52
+ return
53
+ const { promise, resolve } = Promise.withResolvers<PrunelleApp>()
54
+ held = { promise, resolve }
55
+ server.reload({ routes: {}, fetch: async (request: Request) => (await promise).handle(request, server.requestIP(request)?.address) })
56
+ }
57
+
58
+ const swapIn = async (): Promise<void> => {
59
+ if (loading) {
60
+ again = true
61
+ return
62
+ }
63
+ loading = true
64
+ const prev = current()
65
+ try {
66
+ if (!landed())
67
+ throw new Error(isStatic ? `${shown}/ is missing or empty` : `${shown}/manifest.json is missing`)
68
+ setCurrent((await startBuiltApp({ root, outDir })).app)
69
+ console.log(`prunelle start: serving the new build in ${shown}/`)
70
+ }
71
+ catch (err) {
72
+ console.error(`prunelle start: the build in ${shown}/ failed to load, so the previous one keeps answering: ${err instanceof Error ? err.message : String(err)}`)
73
+ }
74
+ loading = false
75
+ if (again) {
76
+ again = false
77
+ void swapIn()
78
+ return
79
+ }
80
+ current().reloadInto!(server)
81
+ held?.resolve(current())
82
+ held = undefined
83
+ if (current() !== prev) {
84
+ await prev.closeStreams?.()
85
+ await prev.dispose?.()
86
+ }
87
+ }
88
+
89
+ const watcher = watch(dirname(outDir), (_event, file) => {
90
+ if (file !== name)
91
+ return
92
+ hold()
93
+ clearTimeout(timer)
94
+ // The swap renames the old folder away, then the stage in: the second rename brings the manifest back.
95
+ timer = setTimeout(() => void swapIn(), landed() ? 0 : SWAP_TIMEOUT_MS)
96
+ })
97
+ watcher.on('error', err => console.error(`prunelle start: stopped watching ${shown}/ for new builds: ${err.message}`))
98
+ return watcher
99
+ }
@@ -0,0 +1,167 @@
1
+ // Standalone `--static` directory server (used when `outDir` holds exported HTML without `manifest.json`): every file is listed once at startup, so a request is a map lookup.
2
+
3
+ import type { FSWatcher } from 'node:fs'
4
+ import type { PrunelleApp, PrunelleServer } from './http'
5
+ import type { SecurityHeadersOptions, TrustProxy } from './security'
6
+ import type { FileSource, ServedFile } from './served-file'
7
+ import { readdirSync, readFileSync, realpathSync, statSync, watch } from 'node:fs'
8
+ import { extname, join, resolve } from 'node:path'
9
+ import { isInside } from '../build/is-inside'
10
+ import { CompressionCache, isCompressibleType } from './compress'
11
+ import { applyHstsHeader, MIME } from './http'
12
+ import { decodeRequestPath } from './request-path'
13
+ import { buildSecurityHeaderEntries, inlineStyleHashes, PRUNELLE_ISLAND_STYLE_HASH, resolveCspPolicy, resolveHstsValue, withCspHashes } from './security'
14
+ import { createFileServer, servedFile } from './served-file'
15
+
16
+ const isRead = (request: Request): boolean => request.method === 'GET' || request.method === 'HEAD'
17
+
18
+
19
+ /** The files under `absRoot` by their path from it, `/`-separated; a symlink counts only when it lands on a file inside `realRoot`. */
20
+ function listFiles(absRoot: string, realRoot: string): Map<string, string> {
21
+ const files = new Map<string, string>()
22
+ let entries: string[]
23
+ try {
24
+ entries = readdirSync(absRoot, { recursive: true, encoding: 'utf8' })
25
+ }
26
+ catch (err) {
27
+ console.error(`prunelle start: could not list ${absRoot}: ${err instanceof Error ? err.message : String(err)}`)
28
+ return files
29
+ }
30
+ for (const rel of entries) {
31
+ const abs = join(absRoot, rel)
32
+ try {
33
+ const real = realpathSync(abs)
34
+ if (isInside(realRoot, real, { orSame: true }) && statSync(real).isFile())
35
+ files.set(rel.replaceAll('\\', '/'), real)
36
+ }
37
+ catch {
38
+ continue // a dangling symlink, or a file removed while listing
39
+ }
40
+ }
41
+ return files
42
+ }
43
+
44
+ /** The listed path a URL names: decoded like every request path, no leading or trailing slash; undefined when it cannot name a file. */
45
+ function requestedRel(pathname: string): string | undefined {
46
+ return decodeRequestPath(pathname)?.staticPath?.replace(/^\/+/, '').replace(/\/+$/, '')
47
+ }
48
+
49
+ export function createStaticDirServer(
50
+ outDir: string,
51
+ assetPrefix: string,
52
+ security: SecurityHeadersOptions | false | undefined,
53
+ compressEnabled: boolean,
54
+ trustProxy: TrustProxy,
55
+ isDev = false,
56
+ ): PrunelleApp {
57
+ const prefix = assetPrefix.replace(/^\/+/, '').replace(/\/$/, '')
58
+ const absRoot = resolve(outDir)
59
+ let realRoot = absRoot
60
+ try {
61
+ realRoot = realpathSync(absRoot)
62
+ }
63
+ catch {
64
+ realRoot = absRoot // listed as empty below, which answers 404s
65
+ }
66
+ const compressCache = compressEnabled ? new CompressionCache() : undefined
67
+ const securityEntries = buildSecurityHeaderEntries(security)
68
+ const securityRecord = Object.fromEntries(securityEntries)
69
+ const baseCsp = resolveCspPolicy(security)
70
+ const htmlCsp = baseCsp !== undefined ? withCspHashes(baseCsp, { styleHashes: [PRUNELLE_ISLAND_STYLE_HASH] }) : undefined
71
+ const hstsValue = resolveHstsValue(security)
72
+ const withHsts = hstsValue === undefined || isDev
73
+ ? (res: Response) => res
74
+ : (res: Response, req: Request) => applyHstsHeader(res, req, hstsValue, trustProxy, isDev)
75
+ const serveFile = createFileServer({ compressEnabled, compressCache, withHsts })
76
+
77
+ function entryFor(rel: string, path: string, all: ReadonlyMap<string, string>): ServedFile {
78
+ const ext = extname(rel).toLowerCase()
79
+ const type = MIME[ext] ?? 'application/octet-stream'
80
+ const isHtml = ext === '.html' || ext === '.htm'
81
+ // An exported page's CSP gains the hashes of its own `<style>` blocks.
82
+ const csp = isHtml && htmlCsp !== undefined ? withCspHashes(htmlCsp, { styleHashes: inlineStyleHashes(readFileSync(path, 'utf8')) }) : undefined
83
+ const sidecar = (ext: string): FileSource | undefined => {
84
+ const at = compressEnabled ? all.get(`${rel}.${ext}`) : undefined
85
+ return at === undefined ? undefined : { path: at }
86
+ }
87
+ return servedFile({
88
+ key: `sd:${path}`,
89
+ source: { path },
90
+ headers: {
91
+ ...securityRecord,
92
+ ...(csp !== undefined ? { 'content-security-policy': csp } : {}),
93
+ 'content-type': type,
94
+ 'cache-control': prefix !== '' && rel.startsWith(`${prefix}/`) ? 'public, max-age=31536000, immutable' : 'public, max-age=0, must-revalidate',
95
+ },
96
+ compressible: compressEnabled && isCompressibleType(type),
97
+ br: sidecar('br'),
98
+ gz: sidecar('gz'),
99
+ })
100
+ }
101
+
102
+ // Each file at its own path, then `x.html` at `x` and `x/index.html` at `x`, a real file always winning.
103
+ function buildTable(): { table: Map<string, ServedFile>, notFound: ServedFile | undefined } {
104
+ const files = listFiles(absRoot, realRoot)
105
+ const table = new Map<string, ServedFile>()
106
+ for (const [rel, path] of files)
107
+ table.set(rel, entryFor(rel, path, files))
108
+ for (const [rel, entry] of [...table]) {
109
+ if (rel.endsWith('.html') && !table.has(rel.slice(0, -5)))
110
+ table.set(rel.slice(0, -5), entry)
111
+ }
112
+ for (const [rel, entry] of [...table]) {
113
+ if (rel === 'index.html' || rel.endsWith('/index.html')) {
114
+ const dir = rel.slice(0, -'index.html'.length).replace(/\/$/, '')
115
+ if (!table.has(dir))
116
+ table.set(dir, entry)
117
+ }
118
+ }
119
+ return { table, notFound: table.get('404.html') }
120
+ }
121
+
122
+ let current = buildTable()
123
+ // A file written in place is listed again; a `prunelle build` swap replaces the whole app (`start.ts`).
124
+ let timer: ReturnType<typeof setTimeout> | undefined
125
+ let watcher: FSWatcher | undefined
126
+ try {
127
+ watcher = watch(absRoot, { recursive: true }, () => {
128
+ clearTimeout(timer)
129
+ timer = setTimeout(() => current = buildTable(), 20)
130
+ })
131
+ watcher.unref()
132
+ }
133
+ catch (err) {
134
+ console.warn(`prunelle start: files changed in ${absRoot} will be served only after a restart: ${err instanceof Error ? err.message : String(err)}`)
135
+ }
136
+
137
+ const handle = async (req: Request): Promise<Response> => {
138
+ if (!isRead(req))
139
+ return withHsts(new Response('Method Not Allowed', { status: 405, headers: { ...securityRecord, allow: 'GET, HEAD' } }), req)
140
+ const rel = requestedRel(new URL(req.url).pathname)
141
+ const found = rel === undefined ? undefined : current.table.get(rel)
142
+ if (found !== undefined)
143
+ return serveFile(req, found)
144
+ if (current.notFound !== undefined)
145
+ return serveFile(req, current.notFound, 404)
146
+ return withHsts(new Response('Not Found', { status: 404, headers: securityRecord }), req)
147
+ }
148
+
149
+ const error = (): Response => new Response('Internal Server Error', {
150
+ status: 500,
151
+ headers: { 'content-type': 'text/plain; charset=utf-8', ...securityRecord },
152
+ })
153
+
154
+ return {
155
+ handle,
156
+ serve(port = 3000, hostname = '127.0.0.1') {
157
+ return Bun.serve({ port, hostname, idleTimeout: 30, development: false, fetch: handle, error })
158
+ },
159
+ reloadInto(server: PrunelleServer) {
160
+ server.reload({ routes: {}, fetch: handle, error })
161
+ },
162
+ async dispose() {
163
+ clearTimeout(timer)
164
+ watcher?.close()
165
+ },
166
+ }
167
+ }
@@ -0,0 +1,192 @@
1
+ // A page with pending `<Suspense>` boundaries: its document flushes first, then each boundary as a script once it resolves or times out.
2
+
3
+ import type { PendingChunk, RenderContext, SettledChunk } from '../ssr/context'
4
+ import { getAppContext, runWithAppContext } from '../plugins/index'
5
+ import { streamChunkScript } from '../ssr/context'
6
+ import { currentRequest, runInRequest } from './request-scope'
7
+
8
+ const textEncoder = new TextEncoder()
9
+ // Where a streamed page's document splits: everything before it flushes first, resolved boundaries go in between.
10
+ export const STREAM_TAIL_MARK = '<!--pru:stream-tail-->'
11
+
12
+ function captureAsyncScope(): <T>(fn: () => T) => T {
13
+ const appCtx = getAppContext()
14
+ const reqScope = currentRequest()
15
+ return <T>(fn: () => T): T => {
16
+ const inner = reqScope !== undefined ? () => runInRequest(reqScope, fn) : fn
17
+ return appCtx !== undefined ? runWithAppContext(appCtx, inner) : inner()
18
+ }
19
+ }
20
+
21
+ /** `streamTimeout` is only named in the error: the page's boundaries share one `deadlineMs`. */
22
+ async function settleWithin(
23
+ chunk: PendingChunk,
24
+ deadlineMs: number,
25
+ streamTimeout: number,
26
+ signal: AbortSignal,
27
+ runInScope: <T>(fn: () => T) => T,
28
+ ): Promise<SettledChunk | undefined> {
29
+ if (signal.aborted)
30
+ return undefined
31
+ const remaining = Math.max(0, deadlineMs - Date.now())
32
+ let timer: ReturnType<typeof setTimeout> | undefined
33
+ let onAbort: (() => void) | undefined
34
+ const abortedOrTimedOut = new Promise<SettledChunk | undefined>((resolve) => {
35
+ onAbort = () => resolve(undefined)
36
+ signal.addEventListener('abort', onAbort, { once: true })
37
+ timer = setTimeout(() => {
38
+ if (onAbort !== undefined)
39
+ signal.removeEventListener('abort', onAbort)
40
+ const error = new Error(`<Suspense> boundary ${chunk.id} did not resolve within ${streamTimeout} ms`)
41
+ resolve({ html: runInScope(() => chunk.renderError(error)), error })
42
+ }, remaining)
43
+ })
44
+ try {
45
+ return await Promise.race([chunk.settled, abortedOrTimedOut])
46
+ }
47
+ finally {
48
+ clearTimeout(timer)
49
+ if (onAbort !== undefined)
50
+ signal.removeEventListener('abort', onAbort)
51
+ }
52
+ }
53
+
54
+ /** Streams `shell` (a document holding `STREAM_TAIL_MARK`), with every boundary of `rctx` flushed before its tail. */
55
+ export function streamDocument(shell: string, rctx: RenderContext, streamTimeout: number, onBoundaryError: (error: unknown) => void): ReadableStream<Uint8Array> {
56
+ let splitAt = shell.lastIndexOf(STREAM_TAIL_MARK)
57
+ let tailOffset = STREAM_TAIL_MARK.length
58
+ if (splitAt === -1) {
59
+ splitAt = shell.lastIndexOf('</body>')
60
+ tailOffset = 0
61
+ }
62
+ const openingHtml = splitAt === -1 ? shell : shell.slice(0, splitAt)
63
+ const tailHtml = splitAt === -1 ? '' : shell.slice(splitAt + tailOffset)
64
+
65
+ const runInScope = captureAsyncScope()
66
+ const abortCtrl = new AbortController()
67
+ let closed = false
68
+ const deadline = Date.now() + streamTimeout
69
+
70
+ const safeEnqueue = (controller: ReadableStreamDefaultController<Uint8Array>, data: Uint8Array): void => {
71
+ if (closed || abortCtrl.signal.aborted)
72
+ return
73
+ try {
74
+ controller.enqueue(data)
75
+ }
76
+ catch {
77
+ closed = true
78
+ abortCtrl.abort()
79
+ }
80
+ }
81
+
82
+ return new ReadableStream<Uint8Array>({
83
+ async start(controller) {
84
+ safeEnqueue(controller, textEncoder.encode(openingHtml))
85
+ // A resolved boundary can render boundaries of its own, so each flush also drains the ones it added.
86
+ let flushed = 0
87
+ const flushPending = async (): Promise<void> => {
88
+ if (closed || abortCtrl.signal.aborted)
89
+ return
90
+ const chunks = rctx.pending.slice(flushed)
91
+ flushed = rctx.pending.length
92
+ await Promise.all(chunks.map(async (chunk) => {
93
+ const settled = await settleWithin(chunk, deadline, streamTimeout, abortCtrl.signal, runInScope)
94
+ if (settled === undefined || closed || abortCtrl.signal.aborted)
95
+ return
96
+ if ('error' in settled)
97
+ runInScope(() => onBoundaryError(settled.error))
98
+ safeEnqueue(controller, textEncoder.encode(streamChunkScript(chunk.id, settled.html)))
99
+ await flushPending()
100
+ }))
101
+ }
102
+ await flushPending()
103
+ if (!closed && !abortCtrl.signal.aborted) {
104
+ safeEnqueue(controller, textEncoder.encode(tailHtml))
105
+ closed = true
106
+ safeClose(controller)
107
+ }
108
+ },
109
+ cancel() {
110
+ closed = true
111
+ abortCtrl.abort()
112
+ },
113
+ })
114
+ }
115
+
116
+ function safeClose(controller: ReadableStreamDefaultController<Uint8Array>): boolean {
117
+ try {
118
+ controller.close()
119
+ return true
120
+ }
121
+ catch {
122
+ return false
123
+ }
124
+ }
125
+
126
+ function trackEventStream(res: Response, active: Set<() => void>, disableTimeout?: () => void): Response {
127
+ disableTimeout?.()
128
+ if (res.body === null)
129
+ return res
130
+ const reader = res.body.getReader()
131
+ let closed = false
132
+ let closeStream: (() => void) | undefined
133
+ const body = new ReadableStream<Uint8Array>({
134
+ start(controller) {
135
+ closeStream = () => {
136
+ if (closed)
137
+ return
138
+ closed = true
139
+ active.delete(closeStream!)
140
+ safeClose(controller)
141
+ void reader.cancel().catch(() => undefined)
142
+ }
143
+ active.add(closeStream)
144
+ },
145
+ async pull(controller) {
146
+ if (closed)
147
+ return
148
+ try {
149
+ const { done, value } = await reader.read()
150
+ if (closed)
151
+ return
152
+ if (done) {
153
+ closed = true
154
+ if (closeStream !== undefined)
155
+ active.delete(closeStream)
156
+ controller.close()
157
+ }
158
+ else {
159
+ controller.enqueue(value)
160
+ }
161
+ }
162
+ catch (err) {
163
+ if (!closed) {
164
+ closed = true
165
+ if (closeStream !== undefined)
166
+ active.delete(closeStream)
167
+ controller.error(err)
168
+ }
169
+ }
170
+ },
171
+ cancel(reason) {
172
+ closed = true
173
+ if (closeStream !== undefined)
174
+ active.delete(closeStream)
175
+ return reader.cancel(reason)
176
+ },
177
+ })
178
+ return new Response(body, { status: res.status, statusText: res.statusText, headers: res.headers })
179
+ }
180
+
181
+ /** Tracks active SSE streams so graceful shutdown can end them before `server.stop()` drains in-flight requests. */
182
+ export function createStreamTracker() {
183
+ const active = new Set<() => void>()
184
+ return {
185
+ track: (res: Response, disableTimeout?: () => void): Response => trackEventStream(res, active, disableTimeout),
186
+ closeAll: (): Promise<void> => {
187
+ for (const close of [...active])
188
+ close()
189
+ return Promise.resolve()
190
+ },
191
+ }
192
+ }