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,286 @@
1
+ // What every rendered document shares: its HTML headers, the plugins' `head` hooks and `transformHtml` passes, and the islands it rendered.
2
+
3
+ import type { DocumentHeadContext, PrunellePlugin, ServerErrorInfo } from '../plugins/index'
4
+ import type { RenderContext } from '../ssr/context'
5
+ import type { Navigation } from '../ssr/navigation'
6
+ import type { RequestContext } from './http'
7
+ import type { SecurityHeadersOptions, TrustProxy } from './security'
8
+ import { cspSha256 } from '../ssr/navigation'
9
+ import { readBufferedOrPassThrough } from './compress'
10
+ import { extractRenderedIslands, makeRequestContext } from './http'
11
+ import { inlineStyleHashes, PRUNELLE_ISLAND_STYLE_HASH, PRUNELLE_STREAM_SCRIPT_HASH, PRUNELLE_SUSPENSE_STYLE_HASH, resolveCspPolicy, withCspHashes } from './security'
12
+
13
+ const TITLE_INNER_RE = /^<title\b[^>]*>([\s\S]*?)<\/title>$/i
14
+ const UNESCAPED_TITLE_CHAR_RE = /[<>]|&(?!(?:#\d+|#x[\da-f]+|[a-z][a-z0-9]+);)/gi
15
+
16
+ // Escapes raw `<`, `>` and unescaped `&` in plugin-supplied `head.title` values without double-escaping existing HTML entities (such as `&amp;` from compiled `<Head><title>` or `@prunellejs/seo`).
17
+ function escapeTitleHtml(title: string): string {
18
+ return title.replace(UNESCAPED_TITLE_CHAR_RE, (ch) => {
19
+ if (ch === '<')
20
+ return '&lt;'
21
+ if (ch === '>')
22
+ return '&gt;'
23
+ return '&amp;'
24
+ })
25
+ }
26
+
27
+ /** `styleHashes` are the page's own `<style>` blocks (`inlineStyleHashes`), added to its CSP. */
28
+ export type HtmlHeaders = (hasIslands: boolean, hasSuspense: boolean, isDynamic: boolean, styleHashes?: readonly string[]) => Record<string, string>
29
+
30
+ const STYLED_HEADER_CACHE_SIZE = 256
31
+
32
+ // HTML headers, one set per (dynamic, islands, suspense) combination: the CSP only gains the hashes a page needs.
33
+ export function createHtmlHeaders(security: SecurityHeadersOptions | false | undefined, securityRecord: Record<string, string>, navigation?: Navigation, plugins: readonly PrunellePlugin[] = []): HtmlHeaders {
34
+ const baseCsp = resolveCspPolicy(security)
35
+ const navStyles = navigation?.styleHashes ?? []
36
+ const navScripts = [...navigation?.scriptHashes ?? [], ...plugins.flatMap(plugin => plugin.inlineScripts ?? []).map(cspSha256)]
37
+ const htmlHeaderSets: Record<string, string>[] = []
38
+ const prunelleStyleHashes: string[][] = []
39
+ const prunelleScriptHashes: string[][] = []
40
+ for (let i = 0; i < 8; i++) {
41
+ const isDynamic = (i & 4) !== 0
42
+ const hasIslands = (i & 2) !== 0
43
+ const hasSuspense = (i & 1) !== 0
44
+ const headers: Record<string, string> = { 'content-type': 'text/html; charset=utf-8', ...securityRecord }
45
+ if (isDynamic)
46
+ headers['cache-control'] = 'private'
47
+ const styleHashes = [...navStyles, ...(hasIslands ? [PRUNELLE_ISLAND_STYLE_HASH] : []), ...(hasSuspense ? [PRUNELLE_SUSPENSE_STYLE_HASH] : [])]
48
+ const scriptHashes = [...navScripts, ...(hasSuspense ? [PRUNELLE_STREAM_SCRIPT_HASH] : [])]
49
+ prunelleStyleHashes.push(styleHashes)
50
+ prunelleScriptHashes.push(scriptHashes)
51
+ if (baseCsp !== undefined)
52
+ headers['content-security-policy'] = withCspHashes(baseCsp, { styleHashes, scriptHashes })
53
+ htmlHeaderSets.push(headers)
54
+ }
55
+
56
+ // Pages sharing a layout share its blocks, so their header sets are kept with LRU eviction.
57
+ const styledSets = new Map<string, Record<string, string>>()
58
+ return (hasIslands, hasSuspense, isDynamic, styleHashes) => {
59
+ const index = (isDynamic ? 4 : 0) | (hasIslands ? 2 : 0) | (hasSuspense ? 1 : 0)
60
+ const base = htmlHeaderSets[index]!
61
+ if (baseCsp === undefined || styleHashes === undefined || styleHashes.length === 0)
62
+ return base
63
+ const key = `${index} ${styleHashes.join(' ')}`
64
+ let headers = styledSets.get(key)
65
+ if (headers !== undefined) {
66
+ styledSets.delete(key)
67
+ styledSets.set(key, headers)
68
+ return headers
69
+ }
70
+ headers = {
71
+ ...base,
72
+ 'content-security-policy': withCspHashes(baseCsp, {
73
+ styleHashes: [...prunelleStyleHashes[index]!, ...styleHashes],
74
+ scriptHashes: prunelleScriptHashes[index]!,
75
+ }),
76
+ }
77
+ if (styledSets.size >= STYLED_HEADER_CACHE_SIZE)
78
+ styledSets.delete(styledSets.keys().next().value!)
79
+ styledSets.set(key, headers)
80
+ return headers
81
+ }
82
+ }
83
+
84
+ /** Merges multiple style-hash arrays into a deduplicated list, preserving order. */
85
+ export function mergeStyleHashes(...groups: readonly (readonly string[] | undefined)[]): string[] {
86
+ let out: string[] | undefined
87
+ for (const group of groups) {
88
+ if (group === undefined || group.length === 0)
89
+ continue
90
+ out ??= []
91
+ for (const h of group) {
92
+ if (!out.includes(h))
93
+ out.push(h)
94
+ }
95
+ }
96
+ return out ?? []
97
+ }
98
+
99
+ /** Extracts CSP style hashes from framework/plugin-configured `headTags` once at startup. */
100
+ export function headTagStyleHashes(headTags: Iterable<string> | undefined): string[] {
101
+ if (headTags === undefined)
102
+ return []
103
+ let combined = ''
104
+ for (const tag of headTags)
105
+ combined += tag
106
+ return combined === '' ? [] : inlineStyleHashes(combined)
107
+ }
108
+
109
+ /** Returns only `<style>` hashes newly introduced by plugin `transformHtml` hooks (never preexisting HTML). */
110
+ export function addedInlineStyleHashes(before: string, after: string): string[] {
111
+ if (before === after)
112
+ return []
113
+ const afterHashes = inlineStyleHashes(after)
114
+ if (afterHashes.length === 0)
115
+ return []
116
+ const beforeSet = new Set(inlineStyleHashes(before))
117
+ return afterHashes.filter(h => !beforeSet.has(h))
118
+ }
119
+
120
+ function withBaseCsp(res: Response, htmlHeaders: HtmlHeaders): Response {
121
+ const csp = htmlHeaders(false, false, true)['content-security-policy']
122
+ if (csp === undefined)
123
+ return res
124
+ const headers = new Headers(res.headers)
125
+ headers.set('content-security-policy', csp)
126
+ return new Response(res.body, { status: res.status, statusText: res.statusText, headers })
127
+ }
128
+
129
+ /** A plugin's HTML page without a CSP of its own gets the app's, its `<style>` blocks hashed like a rendered page's. */
130
+ export async function withPluginHtmlCsp(res: Response, htmlHeaders: HtmlHeaders): Promise<Response> {
131
+ if (res.body === null || res.headers.has('content-security-policy') || !(res.headers.get('content-type') ?? '').trim().toLowerCase().startsWith('text/html'))
132
+ return res
133
+ // Never decode pre-compressed bytes as UTF-8; attach base CSP without touching the body.
134
+ if (res.headers.has('content-encoding'))
135
+ return withBaseCsp(res, htmlHeaders)
136
+ const probed = await readBufferedOrPassThrough(res)
137
+ if ('passthrough' in probed)
138
+ return withBaseCsp(probed.passthrough, htmlHeaders)
139
+ const html = new TextDecoder().decode(probed.buffered)
140
+ const headers = new Headers(res.headers)
141
+ const csp = htmlHeaders(false, false, true, inlineStyleHashes(html))['content-security-policy']
142
+ if (csp !== undefined)
143
+ headers.set('content-security-policy', csp)
144
+ return new Response(html, { status: res.status, statusText: res.statusText, headers })
145
+ }
146
+
147
+ /** The revivers, for a page whose island props need them; nothing otherwise. */
148
+ export function revivePreload(rctx: RenderContext, reviveScript: string | undefined): string[] {
149
+ return rctx.revives && reviveScript !== undefined ? [reviveScript] : []
150
+ }
151
+
152
+ export function resolveRenderedIslands(rctx: RenderContext, body: string): { hasIslands: boolean, eagerChunks: string[] } {
153
+ if (rctx.hasIslands) {
154
+ const eagerChunks: string[] = []
155
+ for (const [chunk, eager] of rctx.renderedIslands) {
156
+ if (eager)
157
+ eagerChunks.push(chunk)
158
+ }
159
+ return { hasIslands: true, eagerChunks }
160
+ }
161
+ // Fallback only if raw HTML injected a <pru-island> without going through ssrIsland/ssrIslandStatic.
162
+ if (body.includes('<pru-island'))
163
+ return extractRenderedIslands(body)
164
+ return { hasIslands: false, eagerChunks: [] }
165
+ }
166
+
167
+ export interface DocumentHooksOptions {
168
+ plugins: readonly PrunellePlugin[]
169
+ lang: string
170
+ trustProxy: TrustProxy
171
+ notifyError: (error: unknown, request: Request, source: ServerErrorInfo['source']) => void
172
+ }
173
+
174
+ export function createDocumentHooks(options: DocumentHooksOptions) {
175
+ const { lang, trustProxy, notifyError } = options
176
+ const headHooks = options.plugins
177
+ .map(p => p.head)
178
+ .filter((fn): fn is NonNullable<PrunellePlugin['head']> => typeof fn === 'function')
179
+ const htmlTransformers = options.plugins
180
+ .map(p => p.transformHtml)
181
+ .filter((fn): fn is NonNullable<PrunellePlugin['transformHtml']> => typeof fn === 'function')
182
+ const hasHeadHooks = headHooks.length > 0
183
+ const hasHtmlTransformers = htmlTransformers.length > 0
184
+
185
+ async function resolveDocumentHead(
186
+ rctx: RenderContext,
187
+ baseHeadTags: readonly string[] | undefined,
188
+ url: URL,
189
+ req?: Request,
190
+ ctx?: RequestContext,
191
+ ): Promise<{ head: string, lang: string, htmlAttrs: Record<string, string>, styleHashes: string[] }> {
192
+ const collectedParts = rctx.headParts.join('')
193
+ if (!hasHeadHooks) {
194
+ return {
195
+ head: (rctx.title ?? '') + collectedParts,
196
+ lang: rctx.htmlAttrs.lang ?? lang,
197
+ htmlAttrs: rctx.htmlAttrs,
198
+ styleHashes: [],
199
+ }
200
+ }
201
+
202
+ const headCtx = ctx ?? makeRequestContext(req ?? new Request(url.toString()), {}, { trustProxy, url }).ctx
203
+ const htmlAttrs: Record<string, string> = { ...rctx.htmlAttrs }
204
+ const initialTitleTag = rctx.title
205
+ const initialTitleInner = initialTitleTag !== undefined ? TITLE_INNER_RE.exec(initialTitleTag)?.[1] : undefined
206
+ let currentTitle = initialTitleInner
207
+ let titleDirty = false
208
+ let currentLang = htmlAttrs.lang ?? lang
209
+ let headRest = collectedParts
210
+ if (baseHeadTags !== undefined) {
211
+ for (let i = 0; i < baseHeadTags.length; i++)
212
+ headRest += baseHeadTags[i]
213
+ }
214
+ const added: string[] = []
215
+ const renderTitleTag = (): string => (
216
+ titleDirty
217
+ ? (currentTitle !== undefined ? `<title>${escapeTitleHtml(currentTitle)}</title>` : '')
218
+ : (initialTitleTag ?? '')
219
+ )
220
+
221
+ const docHead: DocumentHeadContext = {
222
+ get lang() {
223
+ return htmlAttrs.lang ?? currentLang
224
+ },
225
+ set lang(v: string) {
226
+ currentLang = v
227
+ htmlAttrs.lang = v
228
+ },
229
+ htmlAttrs,
230
+ get title() {
231
+ return currentTitle
232
+ },
233
+ set title(v: string | undefined) {
234
+ currentTitle = v
235
+ titleDirty = true
236
+ },
237
+ get headHtml() {
238
+ return renderTitleTag() + headRest
239
+ },
240
+ add(html: string) {
241
+ if (html !== '') {
242
+ added.push(html)
243
+ headRest += html
244
+ }
245
+ },
246
+ }
247
+
248
+ for (const hook of headHooks) {
249
+ try {
250
+ await hook(docHead, headCtx)
251
+ }
252
+ catch (err) {
253
+ notifyError(err, req ?? headCtx.request, 'plugin')
254
+ }
255
+ }
256
+
257
+ const titleHtml = renderTitleTag()
258
+ const addedHtml = added.length > 0 ? added.join('') : ''
259
+ return {
260
+ head: titleHtml + collectedParts + addedHtml,
261
+ lang: htmlAttrs.lang ?? currentLang,
262
+ htmlAttrs,
263
+ styleHashes: addedHtml !== '' ? inlineStyleHashes(addedHtml) : [],
264
+ }
265
+ }
266
+
267
+ async function applyHtmlTransforms(html: string, url: URL, req?: Request, ctx?: RequestContext): Promise<string> {
268
+ if (!hasHtmlTransformers)
269
+ return html
270
+ const transformCtx = ctx ?? makeRequestContext(req ?? new Request(url.toString()), {}, { trustProxy, url }).ctx
271
+ let out = html
272
+ for (const transform of htmlTransformers) {
273
+ try {
274
+ out = await transform(out, transformCtx)
275
+ }
276
+ catch (err) {
277
+ notifyError(err, req ?? transformCtx.request, 'plugin')
278
+ }
279
+ }
280
+ return out
281
+ }
282
+
283
+ return { hasHeadHooks, hasHtmlTransformers, htmlTransformers, resolveDocumentHead, applyHtmlTransforms }
284
+ }
285
+
286
+ export type DocumentHooks = ReturnType<typeof createDocumentHooks>
@@ -0,0 +1,47 @@
1
+ // Typed environment variable loader using any Standard Schema validator.
2
+
3
+ import type { InferOutput, StandardSchemaV1 } from './standard-schema'
4
+ import { getAppContext } from '../plugins/context'
5
+ import { formatIssuePath, validateSchemaSync } from './standard-schema'
6
+
7
+ const NODE_ENV_KEY = 'NODE_ENV'
8
+
9
+ /** Reads NODE_ENV at runtime (preferring the active AppRuntimeContext when set): the dynamic key keeps Bun.build from constant-folding it in compiled binaries. */
10
+ export function nodeEnv(): string | undefined {
11
+ return getAppContext()?.nodeEnv ?? process.env[NODE_ENV_KEY]
12
+ }
13
+
14
+ const DEV_KEY = 'PRUNELLE_DEV'
15
+ // A compiled binary runs its entry from Bun's embedded filesystem.
16
+ const BINARY_MAIN_RE = /^\/\$bunfs\//
17
+
18
+ /** Whether `PRUNELLE_DEV=1` asks for dev mode where the caller did not say; it throws under NODE_ENV=production and inside a compiled binary, where the dev-only routes would reach visitors. */
19
+ export function devFromEnv(): boolean {
20
+ if (process.env[DEV_KEY] !== '1')
21
+ return false
22
+ const where = BINARY_MAIN_RE.test(Bun.main) ? 'inside a compiled binary' : nodeEnv() === 'production' ? 'with NODE_ENV=production' : undefined
23
+ if (where !== undefined)
24
+ throw new Error(`prunelle: PRUNELLE_DEV=1 is set ${where}, where dev mode would open the CMS write routes, the mail outbox and the other dev-only routes to visitors: unset PRUNELLE_DEV, or use prunelle dev.`)
25
+ return true
26
+ }
27
+
28
+ export function defineEnv<S extends StandardSchemaV1>(
29
+ schema: S,
30
+ source: Record<string, string | undefined> = process.env,
31
+ ): Readonly<InferOutput<S>> {
32
+ const result = validateSchemaSync(
33
+ schema,
34
+ source,
35
+ 'prunelle: defineEnv() requires a synchronous Standard Schema validator',
36
+ )
37
+ if (!result.ok) {
38
+ const details = result.issues
39
+ .map(issue => ` - ${formatIssuePath(issue) || '(root)'}: ${issue.message}`)
40
+ .join('\n')
41
+ throw new Error(`prunelle: invalid environment variables:\n${details}`)
42
+ }
43
+
44
+ return typeof result.value === 'object' && result.value !== null
45
+ ? Object.freeze({ ...result.value })
46
+ : result.value
47
+ }