prunelle 0.0.0-stage → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (222) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +245 -0
  3. package/package.json +62 -4
  4. package/src/a11y/declaration.ts +373 -0
  5. package/src/a11y/index.ts +477 -0
  6. package/src/a11y/rgaa-map.ts +230 -0
  7. package/src/ambient.d.ts +6 -0
  8. package/src/attrs.ts +43 -0
  9. package/src/build/bundle.ts +661 -0
  10. package/src/build/byte-size.ts +11 -0
  11. package/src/build/carry.ts +57 -0
  12. package/src/build/client-entries.ts +107 -0
  13. package/src/build/client-plugin.ts +175 -0
  14. package/src/build/client-prune.ts +168 -0
  15. package/src/build/compile.ts +130 -0
  16. package/src/build/ecoindex.ts +238 -0
  17. package/src/build/files.ts +171 -0
  18. package/src/build/first-load.ts +235 -0
  19. package/src/build/graph.ts +237 -0
  20. package/src/build/index.ts +678 -0
  21. package/src/build/is-inside.ts +12 -0
  22. package/src/build/island-promote.ts +311 -0
  23. package/src/build/islands.ts +452 -0
  24. package/src/build/manifest.ts +204 -0
  25. package/src/build/output.ts +81 -0
  26. package/src/build/plugin-host.ts +294 -0
  27. package/src/build/precompress.ts +139 -0
  28. package/src/build/prerender.ts +288 -0
  29. package/src/build/reach.ts +200 -0
  30. package/src/build/render-rules.ts +205 -0
  31. package/src/build/report.ts +290 -0
  32. package/src/build/resolve.ts +52 -0
  33. package/src/build/routes.ts +342 -0
  34. package/src/build/server-entry.ts +38 -0
  35. package/src/build/static-headers.ts +112 -0
  36. package/src/build/static.ts +209 -0
  37. package/src/build/status-pages.ts +127 -0
  38. package/src/build/style-bundles.ts +526 -0
  39. package/src/cli/check-forms.ts +636 -0
  40. package/src/cli/check-imports.ts +31 -0
  41. package/src/cli/check-links.ts +632 -0
  42. package/src/cli/check-security.ts +64 -0
  43. package/src/cli/check.ts +409 -0
  44. package/src/cli/commands.ts +372 -0
  45. package/src/cli/docs.ts +403 -0
  46. package/src/cli/index.ts +70 -0
  47. package/src/cli/inspect.ts +406 -0
  48. package/src/cli/mcp-tools.ts +492 -0
  49. package/src/cli/mcp.ts +205 -0
  50. package/src/cli/new.ts +52 -0
  51. package/src/cli/render.ts +416 -0
  52. package/src/cli/upgrade-names.ts +209 -0
  53. package/src/cli/upgrade.ts +367 -0
  54. package/src/compiler/analyze.ts +651 -0
  55. package/src/compiler/ast.ts +82 -0
  56. package/src/compiler/browser-globals.ts +250 -0
  57. package/src/compiler/cacheability-private.ts +566 -0
  58. package/src/compiler/cacheability.ts +335 -0
  59. package/src/compiler/compliance-eco.ts +71 -0
  60. package/src/compiler/compliance-rgaa.ts +614 -0
  61. package/src/compiler/compliance-urls.ts +148 -0
  62. package/src/compiler/compliance.ts +653 -0
  63. package/src/compiler/data-keys.ts +302 -0
  64. package/src/compiler/dev-source.ts +87 -0
  65. package/src/compiler/dom-attrs.ts +452 -0
  66. package/src/compiler/dom.ts +641 -0
  67. package/src/compiler/emit.ts +131 -0
  68. package/src/compiler/expr-context.ts +587 -0
  69. package/src/compiler/foreign-imports.ts +88 -0
  70. package/src/compiler/index.ts +8 -0
  71. package/src/compiler/interactivity.ts +366 -0
  72. package/src/compiler/mistakes.ts +520 -0
  73. package/src/compiler/node-env.ts +50 -0
  74. package/src/compiler/patch.ts +97 -0
  75. package/src/compiler/props-body.ts +60 -0
  76. package/src/compiler/props.ts +511 -0
  77. package/src/compiler/scope.ts +635 -0
  78. package/src/compiler/server-only.ts +365 -0
  79. package/src/compiler/shared.ts +397 -0
  80. package/src/compiler/signal-reads.ts +246 -0
  81. package/src/compiler/slots.ts +227 -0
  82. package/src/compiler/spread-handlers.ts +295 -0
  83. package/src/compiler/ssr-helpers.ts +555 -0
  84. package/src/compiler/ssr-island.ts +90 -0
  85. package/src/compiler/ssr-prunelle-tags.ts +69 -0
  86. package/src/compiler/ssr.ts +525 -0
  87. package/src/context.ts +199 -0
  88. package/src/dev/child.ts +30 -0
  89. package/src/dev/error-log.ts +177 -0
  90. package/src/dev/host-check.ts +32 -0
  91. package/src/dev/index.ts +268 -0
  92. package/src/dev/modules.ts +68 -0
  93. package/src/dev/open-editor.ts +228 -0
  94. package/src/dev/protocol.ts +24 -0
  95. package/src/dev/queue.ts +79 -0
  96. package/src/dev/reload.ts +159 -0
  97. package/src/dev/supervisor.ts +212 -0
  98. package/src/dev/watchers.ts +276 -0
  99. package/src/dom/action.ts +187 -0
  100. package/src/dom/attrs.ts +84 -0
  101. package/src/dom/claim.ts +120 -0
  102. package/src/dom/extras.ts +579 -0
  103. package/src/dom/index.ts +329 -0
  104. package/src/dom/island.ts +318 -0
  105. package/src/dom/loop.ts +484 -0
  106. package/src/dom/revive.ts +36 -0
  107. package/src/eco/declaration.ts +328 -0
  108. package/src/eco/index.ts +69 -0
  109. package/src/index.ts +22 -0
  110. package/src/jsx-runtime.ts +566 -0
  111. package/src/plugins/config.ts +92 -0
  112. package/src/plugins/context.ts +109 -0
  113. package/src/plugins/index.ts +14 -0
  114. package/src/plugins/load.ts +90 -0
  115. package/src/plugins/order.ts +148 -0
  116. package/src/plugins/public.ts +15 -0
  117. package/src/plugins/requires.ts +47 -0
  118. package/src/plugins/services.ts +119 -0
  119. package/src/plugins/types.ts +278 -0
  120. package/src/reactivity/graph.ts +259 -0
  121. package/src/reactivity/index.ts +541 -0
  122. package/src/reactivity/selector.ts +78 -0
  123. package/src/reactivity/store.ts +252 -0
  124. package/src/server/action-flash.ts +158 -0
  125. package/src/server/action-protect.ts +199 -0
  126. package/src/server/action-registry.ts +78 -0
  127. package/src/server/action.ts +511 -0
  128. package/src/server/app-entry.ts +23 -0
  129. package/src/server/app-secret.ts +63 -0
  130. package/src/server/assets.ts +168 -0
  131. package/src/server/compress.ts +646 -0
  132. package/src/server/consent.ts +290 -0
  133. package/src/server/cookies.ts +153 -0
  134. package/src/server/document.ts +286 -0
  135. package/src/server/env.ts +47 -0
  136. package/src/server/errors.ts +396 -0
  137. package/src/server/form-schema.ts +337 -0
  138. package/src/server/health.ts +275 -0
  139. package/src/server/http.ts +588 -0
  140. package/src/server/index.ts +615 -0
  141. package/src/server/lifecycle.ts +75 -0
  142. package/src/server/loader.ts +131 -0
  143. package/src/server/page.ts +122 -0
  144. package/src/server/param-matchers.ts +112 -0
  145. package/src/server/plugin-host.ts +267 -0
  146. package/src/server/prerendered.ts +71 -0
  147. package/src/server/public.ts +20 -0
  148. package/src/server/rate-limit.ts +199 -0
  149. package/src/server/region.ts +96 -0
  150. package/src/server/request-body.ts +27 -0
  151. package/src/server/request-path.ts +73 -0
  152. package/src/server/request-scope.ts +22 -0
  153. package/src/server/route-cache.ts +541 -0
  154. package/src/server/route-table.ts +424 -0
  155. package/src/server/router.ts +261 -0
  156. package/src/server/routing.ts +388 -0
  157. package/src/server/sanitize-html.ts +309 -0
  158. package/src/server/security.ts +550 -0
  159. package/src/server/serve-handlers.ts +93 -0
  160. package/src/server/served-file.ts +128 -0
  161. package/src/server/standard-schema.ts +104 -0
  162. package/src/server/start.ts +143 -0
  163. package/src/server/static-dir.ts +246 -0
  164. package/src/server/stream.ts +233 -0
  165. package/src/ssr/consent-banner.ts +58 -0
  166. package/src/ssr/context.ts +399 -0
  167. package/src/ssr/index.ts +624 -0
  168. package/src/ssr/navigation.ts +96 -0
  169. package/src/ssr/region.ts +192 -0
  170. package/src/style.ts +96 -0
  171. package/src/test/browser.ts +201 -0
  172. package/src/test/index.ts +262 -0
  173. package/src/ts-plugin/diagnostics.ts +505 -0
  174. package/src/ts-plugin/fixes.ts +364 -0
  175. package/src/ts-plugin/index.ts +194 -0
  176. package/src/unrenderable.ts +35 -0
  177. package/templates/_shared/AGENTS.md +10 -0
  178. package/templates/_shared/CLAUDE.md +1 -0
  179. package/templates/_shared/gitignore +8 -0
  180. package/templates/_shared/mcp.json +11 -0
  181. package/templates/_shared/public/robots.txt +2 -0
  182. package/templates/_shared/src/routes/legal.tsx +22 -0
  183. package/templates/_shared/tsconfig.json +25 -0
  184. package/templates/app/.env.example +8 -0
  185. package/templates/app/package.json +22 -0
  186. package/templates/app/prunelle.config.ts +13 -0
  187. package/templates/app/src/auth.ts +12 -0
  188. package/templates/app/src/mail.ts +4 -0
  189. package/templates/app/src/routes/_layout.tsx +40 -0
  190. package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
  191. package/templates/app/src/routes/dashboard/index.tsx +47 -0
  192. package/templates/app/src/routes/index.tsx +15 -0
  193. package/templates/app/src/routes/login.tsx +53 -0
  194. package/templates/app/src/routes/privacy.tsx +25 -0
  195. package/templates/app/src/styles/app.css +14 -0
  196. package/templates/app/tests/app.test.ts +73 -0
  197. package/templates/blog/content/posts/welcome.md +9 -0
  198. package/templates/blog/package.json +22 -0
  199. package/templates/blog/prunelle.config.ts +23 -0
  200. package/templates/blog/src/posts.ts +26 -0
  201. package/templates/blog/src/routes/_layout.tsx +25 -0
  202. package/templates/blog/src/routes/blog/[slug].tsx +31 -0
  203. package/templates/blog/src/routes/index.tsx +33 -0
  204. package/templates/blog/src/styles/app.css +15 -0
  205. package/templates/fullstack/package.json +19 -0
  206. package/templates/fullstack/prunelle.config.ts +6 -0
  207. package/templates/fullstack/src/actions/greet.ts +19 -0
  208. package/templates/fullstack/src/components/Counter.tsx +10 -0
  209. package/templates/fullstack/src/components/GreetForm.tsx +28 -0
  210. package/templates/fullstack/src/routes/_layout.tsx +18 -0
  211. package/templates/fullstack/src/routes/api/health.ts +5 -0
  212. package/templates/fullstack/src/routes/index.tsx +13 -0
  213. package/templates/fullstack/src/styles/app.css +39 -0
  214. package/templates/fullstack/tests/app.test.ts +37 -0
  215. package/templates/minimal/package.json +19 -0
  216. package/templates/minimal/prunelle.config.ts +6 -0
  217. package/templates/minimal/src/components/Counter.tsx +10 -0
  218. package/templates/minimal/src/routes/_layout.tsx +18 -0
  219. package/templates/minimal/src/routes/index.tsx +11 -0
  220. package/templates/minimal/src/styles/app.css +32 -0
  221. package/ts-plugin.cjs +4277 -0
  222. package/README.md +0 -3
@@ -0,0 +1,128 @@
1
+ // One file served as it is (a hashed asset, a public file, a prerendered page, a `--static` file): its headers, validators and encoded variants are fixed when it is listed, so a request only picks one.
2
+
3
+ import type { CompressionCache } from './compress'
4
+ import { statSync } from 'node:fs'
5
+ import { markCompressionHandled, mergeVaryValue, pickEncoding, pickPrecompressedEncoding, toWeakEtag } from './compress'
6
+ import { etagMatches } from './http'
7
+
8
+ const textEncoder = new TextEncoder()
9
+
10
+ /** A file on disk (or embedded in a binary), bytes, or an HTML string. */
11
+ export type FileSource = { path: string } | { bytes: Uint8Array<ArrayBuffer> } | { text: string }
12
+
13
+ interface Variant {
14
+ body: BodyInit
15
+ headers: Record<string, string>
16
+ /** The file's path and size, for a variant on disk the compression cache may keep in memory. */
17
+ disk: { path: string, size: () => number } | undefined
18
+ }
19
+
20
+ export interface ServedFile {
21
+ /** The compression cache key, which changes with the file's version. */
22
+ key: string
23
+ etag: string | undefined
24
+ headers: Record<string, string>
25
+ notModifiedHeaders: Record<string, string>
26
+ /** Headers of the variant compressed here on first request; undefined when the file is never compressed here. */
27
+ compressedHeaders: Record<string, string> | undefined
28
+ br: Variant | undefined
29
+ gz: Variant | undefined
30
+ body: BodyInit
31
+ read: () => Uint8Array<ArrayBuffer> | Promise<Uint8Array<ArrayBuffer>>
32
+ /** The identity body's byte length, read on the first `HEAD`. */
33
+ size: () => number
34
+ }
35
+
36
+ export interface ServedFileInit {
37
+ key: string
38
+ source: FileSource
39
+ /** `content-type`, `cache-control` and the security headers. */
40
+ headers: Record<string, string>
41
+ /** Defaults to the source's size and mtime, or a hash of its bytes. */
42
+ etag?: string | undefined
43
+ /** Whether the server may compress it on first request. */
44
+ compressible: boolean
45
+ br?: FileSource | undefined
46
+ gz?: FileSource | undefined
47
+ }
48
+
49
+ export function bodyOf(source: FileSource): BodyInit {
50
+ return 'path' in source ? Bun.file(source.path) : 'bytes' in source ? source.bytes : source.text
51
+ }
52
+
53
+ async function bytesOf(source: FileSource): Promise<Uint8Array<ArrayBuffer>> {
54
+ return 'path' in source ? new Uint8Array(await Bun.file(source.path).arrayBuffer()) : 'bytes' in source ? source.bytes : textEncoder.encode(source.text)
55
+ }
56
+
57
+ /** `W/"<size>-<mtime>"` for a file on disk, a hash of the bytes otherwise. */
58
+ export function sourceEtag(source: FileSource): string {
59
+ if ('path' in source) {
60
+ const st = statSync(source.path)
61
+ return `W/"${st.size.toString(36)}-${Math.floor(st.mtimeMs).toString(36)}"`
62
+ }
63
+ return `W/"${Bun.hash('bytes' in source ? source.bytes : source.text).toString(36)}"`
64
+ }
65
+
66
+ export function servedFile(init: ServedFileInit): ServedFile {
67
+ const etag = init.etag ?? sourceEtag(init.source)
68
+ const varies = init.compressible || init.br !== undefined || init.gz !== undefined
69
+ const headers: Record<string, string> = { ...init.headers, etag, ...(varies ? { vary: mergeVaryValue(init.headers.vary, 'Accept-Encoding') } : {}) }
70
+ const { 'content-type': _type, ...notModifiedHeaders } = headers
71
+ const onDisk = (path: string): Variant['disk'] => {
72
+ let bytes: number | undefined
73
+ return { path, size: () => bytes ??= Bun.file(path).size }
74
+ }
75
+ const encoded = (source: FileSource | undefined, encoding: string): Variant | undefined =>
76
+ source === undefined ? undefined : { body: bodyOf(source), headers: { ...headers, 'content-encoding': encoding, 'etag': toWeakEtag(etag) }, disk: 'path' in source ? onDisk(source.path) : undefined }
77
+ let size: number | undefined
78
+ return {
79
+ key: `${init.key}:${etag}`,
80
+ etag,
81
+ headers,
82
+ notModifiedHeaders,
83
+ compressedHeaders: init.compressible ? { ...headers, etag: toWeakEtag(etag) } : undefined,
84
+ br: encoded(init.br, 'br'),
85
+ gz: encoded(init.gz, 'gzip'),
86
+ body: bodyOf(init.source),
87
+ read: () => bytesOf(init.source),
88
+ size: () => size ??= 'path' in init.source ? Bun.file(init.source.path).size : 'bytes' in init.source ? init.source.bytes.byteLength : textEncoder.encode(init.source.text).byteLength,
89
+ }
90
+ }
91
+
92
+ /** Answers a request for a listed file: a 304 to a matching `If-None-Match`, its length to a `HEAD`, else a precompressed sidecar, a variant compressed here, or the file. */
93
+ export function createFileServer(options: {
94
+ compressEnabled: boolean
95
+ compressCache: CompressionCache | undefined
96
+ withHsts: (res: Response, request: Request) => Response
97
+ }) {
98
+ const { compressEnabled, compressCache, withHsts } = options
99
+ const done = (res: Response, request: Request): Response => markCompressionHandled(withHsts(res, request))
100
+
101
+ return async function serveFile(request: Request, file: ServedFile, status = 200): Promise<Response> {
102
+ if (status === 200 && file.etag !== undefined && etagMatches(request.headers.get('if-none-match'), file.etag))
103
+ return done(new Response(null, { status: 304, headers: file.notModifiedHeaders }), request)
104
+ if (request.method === 'HEAD')
105
+ return done(new Response(null, { status, headers: { ...file.headers, 'content-length': String(file.size()) } }), request)
106
+ const accept = request.headers.get('accept-encoding')
107
+ if (compressEnabled && (file.br !== undefined || file.gz !== undefined)) {
108
+ const pre = pickPrecompressedEncoding(accept, { br: file.br !== undefined, gz: file.gz !== undefined })
109
+ if (pre !== undefined) {
110
+ const variant = pre === 'br' ? file.br! : file.gz!
111
+ const { disk } = variant
112
+ const kept = disk !== undefined && compressCache?.keeps(disk.size()) === true
113
+ ? await compressCache.sidecar(`${file.key}:${pre}`, async () => new Uint8Array(await Bun.file(disk.path).arrayBuffer()))
114
+ : undefined
115
+ return done(new Response(kept ?? variant.body, { status, headers: variant.headers }), request)
116
+ }
117
+ }
118
+ if (file.compressedHeaders !== undefined && compressCache !== undefined) {
119
+ const enc = pickEncoding(accept)
120
+ if (enc !== undefined) {
121
+ const compressed = await compressCache.file(file.key, enc, file.read)
122
+ if (compressed !== undefined)
123
+ return done(new Response(compressed, { status, headers: { ...file.compressedHeaders, 'content-encoding': enc } }), request)
124
+ }
125
+ }
126
+ return done(new Response(file.body, { status, headers: file.headers }), request)
127
+ }
128
+ }
@@ -0,0 +1,104 @@
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 type StandardJSONSchemaTarget =
9
+ | 'draft-2020-12'
10
+ | 'draft-07'
11
+ | 'openapi-3.0'
12
+ | ({} & string)
13
+
14
+ export interface StandardJSONSchemaOptions {
15
+ readonly target: StandardJSONSchemaTarget
16
+ readonly libraryOptions?: Record<string, unknown> | undefined
17
+ }
18
+
19
+ export interface StandardJSONSchemaConverter {
20
+ readonly input: (options: StandardJSONSchemaOptions) => Record<string, unknown>
21
+ readonly output?: ((options: StandardJSONSchemaOptions) => Record<string, unknown>) | undefined
22
+ }
23
+
24
+ export interface StandardSchemaV1<Input = unknown, Output = Input> {
25
+ readonly '~standard': {
26
+ readonly version: 1
27
+ readonly vendor: string
28
+ readonly validate: (value: unknown) =>
29
+ | { readonly value: Output, readonly issues?: undefined }
30
+ | { readonly issues: ReadonlyArray<StandardSchemaIssue> }
31
+ | Promise<
32
+ | { readonly value: Output, readonly issues?: undefined }
33
+ | { readonly issues: ReadonlyArray<StandardSchemaIssue> }
34
+ >
35
+ readonly types?: { readonly input: Input, readonly output: Output } | undefined
36
+ readonly jsonSchema?: StandardJSONSchemaConverter | undefined
37
+ }
38
+ }
39
+
40
+ export type InferInput<S extends StandardSchemaV1> = NonNullable<S['~standard']['types']>['input']
41
+ export type InferOutput<S extends StandardSchemaV1> = NonNullable<S['~standard']['types']>['output']
42
+
43
+ export interface ValidationFailure {
44
+ ok: false
45
+ issues: ReadonlyArray<StandardSchemaIssue>
46
+ fieldErrors: Record<string, string>
47
+ }
48
+
49
+ export interface ValidationSuccess<T> {
50
+ ok: true
51
+ value: T
52
+ }
53
+
54
+ export type ValidationResult<T> = ValidationSuccess<T> | ValidationFailure
55
+
56
+ export function formatIssuePath(issue: StandardSchemaIssue): string {
57
+ if (!issue.path || issue.path.length === 0)
58
+ return ''
59
+ return issue.path
60
+ .map(seg => (typeof seg === 'object' && seg !== null && 'key' in seg ? String(seg.key) : String(seg)))
61
+ .join('.')
62
+ }
63
+
64
+ export function formatSchemaIssues(issues: ReadonlyArray<StandardSchemaIssue>): string {
65
+ return issues
66
+ .map((issue) => {
67
+ const path = formatIssuePath(issue)
68
+ return path ? `${path}: ${issue.message}` : issue.message
69
+ })
70
+ .join('; ')
71
+ }
72
+
73
+ function buildValidationFailure(issues: ReadonlyArray<StandardSchemaIssue>): ValidationFailure {
74
+ const fieldErrors: Record<string, string> = {}
75
+ for (const issue of issues) {
76
+ const key = formatIssuePath(issue)
77
+ if (!Object.hasOwn(fieldErrors, key))
78
+ Object.defineProperty(fieldErrors, key, { value: issue.message, enumerable: true, writable: true, configurable: true })
79
+ }
80
+ return { ok: false, issues, fieldErrors }
81
+ }
82
+
83
+ export function validateSchemaSync<S extends StandardSchemaV1>(
84
+ schema: S,
85
+ input: unknown,
86
+ asyncErrorMessage = 'prunelle: synchronous Standard Schema validator required',
87
+ ): ValidationResult<InferOutput<S>> {
88
+ const res = schema['~standard'].validate(input)
89
+ if (res instanceof Promise)
90
+ throw new TypeError(asyncErrorMessage)
91
+ if (res.issues && res.issues.length > 0)
92
+ return buildValidationFailure(res.issues)
93
+ return { ok: true, value: (res as { value: InferOutput<S> }).value }
94
+ }
95
+
96
+ export async function validateSchema<S extends StandardSchemaV1>(
97
+ schema: S,
98
+ input: unknown,
99
+ ): Promise<ValidationResult<InferOutput<S>>> {
100
+ const res = await schema['~standard'].validate(input)
101
+ if (res.issues && res.issues.length > 0)
102
+ return buildValidationFailure(res.issues)
103
+ return { ok: true, value: (res as { value: InferOutput<S> }).value }
104
+ }
@@ -0,0 +1,143 @@
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 { PrunelleApp, PrunelleServer } from './http'
4
+ import { existsSync, readdirSync, watch } from 'node:fs'
5
+ import { basename, dirname, join, relative } from 'node:path'
6
+ import { startBuiltApp } from './loader'
7
+
8
+ /** How long a swap may leave the outDir missing before the server goes back to the build it had. */
9
+ const SWAP_TIMEOUT_MS = 2000
10
+
11
+ export interface StartOptions {
12
+ root: string
13
+ port: number
14
+ hostname: string
15
+ }
16
+
17
+ async function disposeApp(app: PrunelleApp): Promise<void> {
18
+ try {
19
+ await app.closeStreams?.()
20
+ await app.dispose?.()
21
+ }
22
+ catch (err) {
23
+ console.error('prunelle start: failed to dispose previous build:', err)
24
+ }
25
+ }
26
+
27
+ /** The server, and an app that forwards to whichever build it serves, for `handleSignals()`. */
28
+ export async function startServer(options: StartOptions): Promise<{ app: PrunelleApp, server: PrunelleServer }> {
29
+ const first = await startBuiltApp({ root: options.root })
30
+ let current = first.app
31
+ const server = current.serve(options.port, options.hostname)
32
+ const app: PrunelleApp = {
33
+ handle: async (request, remoteIp, disableTimeout) => current.handle(request, remoteIp, disableTimeout),
34
+ serve: () => server,
35
+ closeStreams: async () => current.closeStreams?.(),
36
+ dispose: async () => {
37
+ watcher?.stop()
38
+ await current.dispose?.()
39
+ },
40
+ }
41
+ const watcher = current.reloadInto !== undefined
42
+ ? watchSwaps(first.outDir, first.entry === undefined, () => current, next => current = next, options.root, server)
43
+ : undefined
44
+ return { app, server }
45
+ }
46
+
47
+ /** Watches the folder holding `outDir` for the rename a build's swap makes, then loads the new build and swaps its handlers in. */
48
+ function watchSwaps(outDir: string, isStatic: boolean, current: () => PrunelleApp, setCurrent: (app: PrunelleApp) => void, root: string, server: PrunelleServer): { stop: () => void } {
49
+ const name = basename(outDir)
50
+ const shown = relative(root, outDir) || '.'
51
+ // A `--static` export has no manifest: the folder being back with files in it is the sign.
52
+ const landed = (): boolean => existsSync(join(outDir, 'manifest.json')) || (isStatic && existsSync(outDir) && readdirSync(outDir).length > 0)
53
+ let held: { promise: Promise<PrunelleApp>, resolve: (app: PrunelleApp) => void, reject: (err: unknown) => void } | undefined
54
+ let loading = false
55
+ let again = false
56
+ let disposed = false
57
+ let timer: ReturnType<typeof setTimeout> | undefined
58
+
59
+ // From the first rename until the new build answers, requests wait for it: no page of the old build links an asset the new one dropped.
60
+ const hold = (): void => {
61
+ if (held !== undefined || disposed)
62
+ return
63
+ const { promise, resolve, reject } = Promise.withResolvers<PrunelleApp>()
64
+ void promise.catch(() => undefined)
65
+ held = { promise, resolve, reject }
66
+ server.reload({
67
+ routes: {},
68
+ fetch: async (request: Request) => {
69
+ let target: PrunelleApp
70
+ try {
71
+ target = await promise
72
+ }
73
+ catch {
74
+ return new Response('Service Unavailable', { status: 503, headers: { ...current().securityHeaders, 'content-type': 'text/plain; charset=utf-8' } })
75
+ }
76
+ return target.handle(request, server.requestIP(request)?.address, () => server.timeout(request, 0))
77
+ },
78
+ })
79
+ }
80
+
81
+ const swapIn = async (): Promise<void> => {
82
+ if (disposed)
83
+ return
84
+ if (loading) {
85
+ again = true
86
+ return
87
+ }
88
+ loading = true
89
+ const prev = current()
90
+ let loaded: PrunelleApp | undefined
91
+ try {
92
+ if (!landed())
93
+ throw new Error(isStatic ? `${shown}/ is missing or empty` : `${shown}/manifest.json is missing`)
94
+ loaded = (await startBuiltApp({ root, outDir })).app
95
+ if (disposed) {
96
+ await disposeApp(loaded)
97
+ loading = false
98
+ return
99
+ }
100
+ setCurrent(loaded)
101
+ console.log(`prunelle start: serving the new build in ${shown}/`)
102
+ }
103
+ catch (err) {
104
+ console.error(`prunelle start: the build in ${shown}/ failed to load, so the previous one keeps answering: ${err instanceof Error ? err.message : String(err)}`)
105
+ }
106
+ loading = false
107
+ const swapped = loaded !== undefined && current() !== prev
108
+ if (again) {
109
+ again = false
110
+ if (swapped)
111
+ void disposeApp(prev)
112
+ void swapIn()
113
+ return
114
+ }
115
+ current().reloadInto!(server)
116
+ held?.resolve(current())
117
+ held = undefined
118
+ if (swapped)
119
+ await disposeApp(prev)
120
+ }
121
+
122
+ const watcher = watch(dirname(outDir), (_event, file) => {
123
+ if (file !== name || disposed)
124
+ return
125
+ hold()
126
+ clearTimeout(timer)
127
+ // The swap renames the old folder away, then the stage in: the second rename brings the manifest back.
128
+ timer = setTimeout(() => void swapIn(), landed() ? 0 : SWAP_TIMEOUT_MS)
129
+ })
130
+ watcher.on('error', err => console.error(`prunelle start: stopped watching ${shown}/ for new builds: ${err.message}`))
131
+ return {
132
+ stop() {
133
+ disposed = true
134
+ clearTimeout(timer)
135
+ timer = undefined
136
+ watcher.close()
137
+ if (held !== undefined) {
138
+ held.reject(new Error('prunelle start: server disposed while reloading build'))
139
+ held = undefined
140
+ }
141
+ },
142
+ }
143
+ }
@@ -0,0 +1,246 @@
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 { PrunellePlugin, ServerErrorInfo } from '../plugins/index'
5
+ import type { NavigationConfig } from '../ssr/navigation'
6
+ import type { PrunelleApp, PrunelleServer } from './http'
7
+ import type { SecurityHeadersOptions, TrustProxy } from './security'
8
+ import type { FileSource, ServedFile } from './served-file'
9
+ import { readdirSync, readFileSync, realpathSync, statSync, watch } from 'node:fs'
10
+ import { extname, join, resolve } from 'node:path'
11
+ import { isInside } from '../build/is-inside'
12
+ import { resolvePlugins } from '../plugins/index'
13
+ import { createNavigation, cspSha256 } from '../ssr/navigation'
14
+ import { CompressionCache, isCompressibleType } from './compress'
15
+ import { createErrorNotifier } from './errors'
16
+ import { applyHstsHeader, MIME } from './http'
17
+ import { decodeRequestPath } from './request-path'
18
+ import { buildSecurityHeaderEntries, inlineStyleHashes, PRUNELLE_ISLAND_STYLE_HASH, resolveCspPolicy, resolveHstsValue, withCspHashes } from './security'
19
+ import { createFileServer, servedFile } from './served-file'
20
+
21
+ const isRead = (request: Request): boolean => request.method === 'GET' || request.method === 'HEAD'
22
+
23
+ const EXTRA_STATIC_MIME: Record<string, string> = {
24
+ '.htm': 'text/html; charset=utf-8',
25
+ '.rss': 'application/rss+xml; charset=utf-8',
26
+ '.atom': 'application/atom+xml; charset=utf-8',
27
+ '.ics': 'text/calendar; charset=utf-8',
28
+ '.csv': 'text/csv; charset=utf-8',
29
+ }
30
+
31
+ export interface StaticDirExtraOptions {
32
+ navigation?: NavigationConfig | undefined
33
+ plugins?: readonly PrunellePlugin[] | undefined
34
+ /** The app's `onError` hook; plugin `onError` hooks run too. With no hook the error is logged. */
35
+ onError?: ((info: ServerErrorInfo) => void) | undefined
36
+ errorSink?: ((info: ServerErrorInfo) => void) | undefined
37
+ httpsSite?: boolean | undefined
38
+ nodeEnv?: string | undefined
39
+ }
40
+
41
+ function findNotFound(rel: string | undefined, byDir: ReadonlyMap<string, ServedFile>): ServedFile | undefined {
42
+ if (byDir.size === 0)
43
+ return undefined
44
+ if (rel !== undefined && rel !== '') {
45
+ let dir = rel
46
+ while (true) {
47
+ const hit = byDir.get(dir)
48
+ if (hit !== undefined)
49
+ return hit
50
+ const slash = dir.lastIndexOf('/')
51
+ if (slash === -1)
52
+ break
53
+ dir = dir.slice(0, slash)
54
+ }
55
+ }
56
+ return byDir.get('')
57
+ }
58
+
59
+
60
+ /** The files under `absRoot` by their path from it, `/`-separated; a symlink counts only when it lands on a file inside `realRoot`. */
61
+ function listFiles(absRoot: string, realRoot: string): Map<string, string> {
62
+ const files = new Map<string, string>()
63
+ let entries: string[]
64
+ try {
65
+ entries = readdirSync(absRoot, { recursive: true, encoding: 'utf8' })
66
+ }
67
+ catch (err) {
68
+ console.error(`prunelle start: could not list ${absRoot}: ${err instanceof Error ? err.message : String(err)}`)
69
+ return files
70
+ }
71
+ for (const rel of entries) {
72
+ const abs = join(absRoot, rel)
73
+ try {
74
+ const real = realpathSync(abs)
75
+ if (isInside(realRoot, real, { orSame: true }) && statSync(real).isFile())
76
+ files.set(rel.replaceAll('\\', '/'), real)
77
+ }
78
+ catch {
79
+ continue // a dangling symlink, or a file removed while listing
80
+ }
81
+ }
82
+ return files
83
+ }
84
+
85
+ /** The listed path a URL names: decoded like every request path, no leading or trailing slash; undefined when it cannot name a file. */
86
+ function requestedRel(pathname: string): string | undefined {
87
+ return decodeRequestPath(pathname)?.staticPath?.replace(/^\/+/, '').replace(/\/+$/, '')
88
+ }
89
+
90
+ export function createStaticDirServer(
91
+ outDir: string,
92
+ assetPrefix: string,
93
+ security: SecurityHeadersOptions | false | undefined,
94
+ compressEnabled: boolean,
95
+ trustProxy: TrustProxy,
96
+ isDev = false,
97
+ extra?: StaticDirExtraOptions,
98
+ ): PrunelleApp {
99
+ const prefix = assetPrefix.replace(/^\/+/, '').replace(/\/$/, '')
100
+ const absRoot = resolve(outDir)
101
+ let realRoot = absRoot
102
+ try {
103
+ realRoot = realpathSync(absRoot)
104
+ }
105
+ catch {
106
+ realRoot = absRoot // listed as empty below, which answers 404s
107
+ }
108
+ const compressCache = compressEnabled ? new CompressionCache() : undefined
109
+ const securityEntries = buildSecurityHeaderEntries(security)
110
+ const securityRecord = Object.fromEntries(securityEntries)
111
+ const baseCsp = resolveCspPolicy(security)
112
+ const nav = extra !== undefined ? createNavigation(extra.navigation) : undefined
113
+ const plugins = extra?.plugins !== undefined ? resolvePlugins(extra.plugins) : []
114
+ const extraStyleHashes = [PRUNELLE_ISLAND_STYLE_HASH, ...(nav?.styleHashes ?? [])]
115
+ const extraScriptHashes = [
116
+ ...(nav?.scriptHashes ?? []),
117
+ ...plugins.flatMap(p => p.inlineScripts ?? []).map(cspSha256),
118
+ ]
119
+ const htmlCsp = baseCsp !== undefined
120
+ ? withCspHashes(baseCsp, { styleHashes: extraStyleHashes, scriptHashes: extraScriptHashes })
121
+ : undefined
122
+ const httpsSite = !isDev && extra?.httpsSite === true
123
+ const hstsValue = resolveHstsValue(security)
124
+ const withHsts = hstsValue === undefined || isDev
125
+ ? (res: Response) => res
126
+ : (res: Response, req: Request) => applyHstsHeader(res, req, hstsValue, trustProxy, isDev, extra?.nodeEnv, httpsSite)
127
+ const serveFileUnguarded = createFileServer({ compressEnabled, compressCache, withHsts })
128
+ const notifyError = createErrorNotifier(extra?.onError, plugins, { dev: isDev, sink: extra?.errorSink })
129
+ // A file that fails to open answers here, where the request is known: gone since the listing is a 404, anything else is reported.
130
+ const serveFile = async (req: Request, file: ServedFile, status?: number): Promise<Response> => {
131
+ try {
132
+ return await serveFileUnguarded(req, file, status)
133
+ }
134
+ catch (err) {
135
+ if (err instanceof Error && 'code' in err && err.code === 'ENOENT')
136
+ return withHsts(new Response('Not Found', { status: 404, headers: { 'cache-control': 'no-store', ...securityRecord } }), req)
137
+ notifyError(err, req, 'route')
138
+ return error()
139
+ }
140
+ }
141
+
142
+ function entryFor(rel: string, path: string, all: ReadonlyMap<string, string>): ServedFile {
143
+ const ext = extname(rel).toLowerCase()
144
+ const type = MIME[ext] ?? EXTRA_STATIC_MIME[ext] ?? 'application/octet-stream'
145
+ const isHtml = ext === '.html' || ext === '.htm'
146
+ // An exported page's CSP gains the hashes of its own `<style>` blocks.
147
+ const csp = isHtml && htmlCsp !== undefined ? withCspHashes(htmlCsp, { styleHashes: inlineStyleHashes(readFileSync(path, 'utf8')) }) : undefined
148
+ const sidecar = (ext: string): FileSource | undefined => {
149
+ const at = compressEnabled ? all.get(`${rel}.${ext}`) : undefined
150
+ return at === undefined ? undefined : { path: at }
151
+ }
152
+ return servedFile({
153
+ key: `sd:${path}`,
154
+ source: { path },
155
+ headers: {
156
+ ...securityRecord,
157
+ ...(csp !== undefined ? { 'content-security-policy': csp } : {}),
158
+ 'content-type': type,
159
+ 'cache-control': prefix !== '' && rel.startsWith(`${prefix}/`) ? 'public, max-age=31536000, immutable' : 'public, max-age=0, must-revalidate',
160
+ },
161
+ compressible: compressEnabled && isCompressibleType(type),
162
+ br: sidecar('br'),
163
+ gz: sidecar('gz'),
164
+ })
165
+ }
166
+
167
+ // Each file at its own path, then `x.html` at `x` and `x/index.html` at `x`, a real file always winning.
168
+ function buildTable(): { table: Map<string, ServedFile>, notFoundByDir: Map<string, ServedFile> } {
169
+ const files = listFiles(absRoot, realRoot)
170
+ const table = new Map<string, ServedFile>()
171
+ const notFoundByDir = new Map<string, ServedFile>()
172
+ for (const [rel, path] of files) {
173
+ const entry = entryFor(rel, path, files)
174
+ table.set(rel, entry)
175
+ if (rel === '404.html')
176
+ notFoundByDir.set('', entry)
177
+ else if (rel.endsWith('/404.html'))
178
+ notFoundByDir.set(rel.slice(0, -'/404.html'.length), entry)
179
+ }
180
+ for (const [rel, entry] of [...table]) {
181
+ if (rel.endsWith('.html') && !table.has(rel.slice(0, -5)))
182
+ table.set(rel.slice(0, -5), entry)
183
+ }
184
+ for (const [rel, entry] of [...table]) {
185
+ if (rel === 'index.html' || rel.endsWith('/index.html')) {
186
+ const dir = rel.slice(0, -'index.html'.length).replace(/\/$/, '')
187
+ if (!table.has(dir))
188
+ table.set(dir, entry)
189
+ }
190
+ }
191
+ return { table, notFoundByDir }
192
+ }
193
+
194
+ let current = buildTable()
195
+ // A file written in place is listed again; a `prunelle build` swap replaces the whole app (`start.ts`).
196
+ let timer: ReturnType<typeof setTimeout> | undefined
197
+ let watcher: FSWatcher | undefined
198
+ try {
199
+ watcher = watch(absRoot, { recursive: true }, () => {
200
+ clearTimeout(timer)
201
+ timer = setTimeout(() => current = buildTable(), 20)
202
+ })
203
+ watcher.unref()
204
+ }
205
+ catch (err) {
206
+ console.warn(`prunelle start: files changed in ${absRoot} will be served only after a restart: ${err instanceof Error ? err.message : String(err)}`)
207
+ }
208
+
209
+ const handle = async (req: Request): Promise<Response> => {
210
+ if (!isRead(req))
211
+ return withHsts(new Response('Method Not Allowed', { status: 405, headers: { ...securityRecord, allow: 'GET, HEAD' } }), req)
212
+ const rel = requestedRel(new URL(req.url).pathname)
213
+ const found = rel === undefined ? undefined : current.table.get(rel)
214
+ if (found !== undefined)
215
+ return serveFile(req, found)
216
+ const notFound = findNotFound(rel, current.notFoundByDir)
217
+ if (notFound !== undefined)
218
+ return serveFile(req, notFound, 404)
219
+ return withHsts(new Response('Not Found', { status: 404, headers: securityRecord }), req)
220
+ }
221
+
222
+ const error = (): Response => new Response('Internal Server Error', {
223
+ status: 500,
224
+ headers: { 'content-type': 'text/plain; charset=utf-8', ...securityRecord },
225
+ })
226
+ // What escapes `serveFile` (a body stream failing after its headers) reaches `Bun.serve` without a request: logged, never silent.
227
+ const lastResort = (err: Error): Response => {
228
+ console.error('prunelle start: unhandled error while serving a file', err)
229
+ return error()
230
+ }
231
+
232
+ return {
233
+ handle,
234
+ securityHeaders: securityRecord,
235
+ serve(port = 3000, hostname = '127.0.0.1') {
236
+ return Bun.serve({ port, hostname, idleTimeout: 30, development: false, fetch: handle, error: lastResort })
237
+ },
238
+ reloadInto(server: PrunelleServer) {
239
+ server.reload({ routes: {}, fetch: handle, error: lastResort })
240
+ },
241
+ async dispose() {
242
+ clearTimeout(timer)
243
+ watcher?.close()
244
+ },
245
+ }
246
+ }