prunelle 0.1.1 → 0.6.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 (120) hide show
  1. package/llms.txt +130 -38
  2. package/package.json +8 -2
  3. package/src/a11y/declaration.ts +335 -0
  4. package/src/a11y/index.ts +446 -0
  5. package/src/a11y/rgaa-map.ts +184 -0
  6. package/src/attrs.ts +11 -3
  7. package/src/build/bundle.ts +80 -36
  8. package/src/build/client-entries.ts +3 -2
  9. package/src/build/client-plugin.ts +8 -4
  10. package/src/build/client-prune.ts +56 -6
  11. package/src/build/compile.ts +11 -9
  12. package/src/build/ecoindex.ts +229 -0
  13. package/src/build/index.ts +174 -108
  14. package/src/build/islands.ts +2 -2
  15. package/src/build/manifest.ts +66 -5
  16. package/src/build/output.ts +2 -2
  17. package/src/build/plugin-host.ts +92 -33
  18. package/src/build/precompress.ts +15 -2
  19. package/src/build/prerender.ts +128 -46
  20. package/src/build/report.ts +23 -2
  21. package/src/build/resolve.ts +8 -6
  22. package/src/build/routes.ts +175 -10
  23. package/src/build/static.ts +137 -39
  24. package/src/build/status-pages.ts +127 -0
  25. package/src/build/style-bundles.ts +526 -0
  26. package/src/cli/check-forms.ts +561 -0
  27. package/src/cli/check-links.ts +632 -0
  28. package/src/cli/check.ts +75 -20
  29. package/src/cli/commands.ts +85 -4
  30. package/src/cli/docs.ts +402 -0
  31. package/src/cli/inspect.ts +103 -14
  32. package/src/cli/mcp-tools.ts +490 -0
  33. package/src/cli/mcp.ts +205 -0
  34. package/src/cli/new.ts +2 -2
  35. package/src/cli/render.ts +421 -0
  36. package/src/cli/upgrade-names.ts +73 -13
  37. package/src/cli/upgrade.ts +137 -16
  38. package/src/compiler/analyze.ts +42 -9
  39. package/src/compiler/browser-globals.ts +140 -17
  40. package/src/compiler/cacheability.ts +636 -0
  41. package/src/compiler/compliance-rgaa.ts +508 -0
  42. package/src/compiler/compliance.ts +241 -289
  43. package/src/compiler/data-keys.ts +199 -192
  44. package/src/compiler/dev-source.ts +87 -0
  45. package/src/compiler/dom-attrs.ts +138 -65
  46. package/src/compiler/dom.ts +517 -442
  47. package/src/compiler/expr-context.ts +167 -57
  48. package/src/compiler/mistakes.ts +4 -1
  49. package/src/compiler/props.ts +87 -36
  50. package/src/compiler/scope.ts +400 -333
  51. package/src/compiler/server-only.ts +190 -151
  52. package/src/compiler/shared.ts +40 -12
  53. package/src/compiler/signal-reads.ts +6 -2
  54. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  55. package/src/compiler/ssr.ts +218 -87
  56. package/src/dev/error-log.ts +151 -0
  57. package/src/dev/index.ts +84 -34
  58. package/src/dev/open-editor.ts +204 -0
  59. package/src/dev/protocol.ts +1 -0
  60. package/src/dev/reload.ts +5 -3
  61. package/src/dev/supervisor.ts +42 -25
  62. package/src/dev/watchers.ts +47 -11
  63. package/src/dom/action.ts +43 -20
  64. package/src/dom/attrs.ts +15 -3
  65. package/src/dom/extras.ts +28 -12
  66. package/src/dom/index.ts +26 -8
  67. package/src/dom/island.ts +35 -28
  68. package/src/dom/loop.ts +10 -9
  69. package/src/plugins/config.ts +8 -7
  70. package/src/plugins/index.ts +2 -2
  71. package/src/plugins/load.ts +26 -7
  72. package/src/plugins/order.ts +38 -1
  73. package/src/plugins/public.ts +5 -2
  74. package/src/plugins/services.ts +81 -0
  75. package/src/plugins/types.ts +34 -0
  76. package/src/reactivity/graph.ts +10 -0
  77. package/src/reactivity/index.ts +24 -16
  78. package/src/reactivity/selector.ts +31 -4
  79. package/src/reactivity/store.ts +45 -13
  80. package/src/server/action-protect.ts +198 -0
  81. package/src/server/action-registry.ts +1 -1
  82. package/src/server/action.ts +82 -27
  83. package/src/server/assets.ts +34 -2
  84. package/src/server/compress.ts +91 -9
  85. package/src/server/document.ts +25 -10
  86. package/src/server/errors.ts +303 -65
  87. package/src/server/form-schema.ts +343 -0
  88. package/src/server/health.ts +244 -0
  89. package/src/server/http.ts +131 -32
  90. package/src/server/index.ts +231 -261
  91. package/src/server/loader.ts +5 -0
  92. package/src/server/param-matchers.ts +112 -0
  93. package/src/server/plugin-host.ts +123 -88
  94. package/src/server/public.ts +3 -3
  95. package/src/server/rate-limit.ts +58 -35
  96. package/src/server/request-body.ts +1 -1
  97. package/src/server/route-cache.ts +423 -0
  98. package/src/server/route-table.ts +339 -8
  99. package/src/server/router.ts +125 -40
  100. package/src/server/routing.ts +196 -63
  101. package/src/server/security.ts +208 -32
  102. package/src/server/serve-handlers.ts +21 -7
  103. package/src/server/start.ts +60 -16
  104. package/src/server/static-dir.ts +61 -8
  105. package/src/server/stream.ts +41 -22
  106. package/src/ssr/context.ts +85 -3
  107. package/src/ssr/index.ts +130 -3
  108. package/src/ssr/region.ts +31 -19
  109. package/src/test/browser.ts +28 -13
  110. package/src/test/index.ts +97 -12
  111. package/src/ts-plugin/diagnostics.ts +505 -0
  112. package/src/ts-plugin/fixes.ts +364 -0
  113. package/src/ts-plugin/index.ts +194 -0
  114. package/templates/_shared/AGENTS.md +2 -2
  115. package/templates/_shared/mcp.json +11 -0
  116. package/templates/_shared/src/routes/legal.tsx +5 -0
  117. package/templates/_shared/tsconfig.json +5 -0
  118. package/templates/blog/prunelle.config.ts +1 -1
  119. package/templates/blog/src/routes/index.tsx +4 -0
  120. package/ts-plugin.cjs +4277 -0
@@ -1,12 +1,16 @@
1
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
2
 
3
3
  import type { FSWatcher } from 'node:fs'
4
+ import type { PrunellePlugin } from '../plugins/index'
5
+ import type { NavigationConfig } from '../ssr/navigation'
4
6
  import type { PrunelleApp, PrunelleServer } from './http'
5
7
  import type { SecurityHeadersOptions, TrustProxy } from './security'
6
8
  import type { FileSource, ServedFile } from './served-file'
7
9
  import { readdirSync, readFileSync, realpathSync, statSync, watch } from 'node:fs'
8
10
  import { extname, join, resolve } from 'node:path'
9
11
  import { isInside } from '../build/is-inside'
12
+ import { resolvePlugins } from '../plugins/index'
13
+ import { createNavigation, cspSha256 } from '../ssr/navigation'
10
14
  import { CompressionCache, isCompressibleType } from './compress'
11
15
  import { applyHstsHeader, MIME } from './http'
12
16
  import { decodeRequestPath } from './request-path'
@@ -15,6 +19,37 @@ import { createFileServer, servedFile } from './served-file'
15
19
 
16
20
  const isRead = (request: Request): boolean => request.method === 'GET' || request.method === 'HEAD'
17
21
 
22
+ const EXTRA_STATIC_MIME: Record<string, string> = {
23
+ '.htm': 'text/html; charset=utf-8',
24
+ '.rss': 'application/rss+xml; charset=utf-8',
25
+ '.atom': 'application/atom+xml; charset=utf-8',
26
+ '.ics': 'text/calendar; charset=utf-8',
27
+ '.csv': 'text/csv; charset=utf-8',
28
+ }
29
+
30
+ export interface StaticDirExtraOptions {
31
+ navigation?: NavigationConfig | undefined
32
+ plugins?: readonly PrunellePlugin[] | undefined
33
+ }
34
+
35
+ function findNotFound(rel: string | undefined, byDir: ReadonlyMap<string, ServedFile>): ServedFile | undefined {
36
+ if (byDir.size === 0)
37
+ return undefined
38
+ if (rel !== undefined && rel !== '') {
39
+ let dir = rel
40
+ while (true) {
41
+ const hit = byDir.get(dir)
42
+ if (hit !== undefined)
43
+ return hit
44
+ const slash = dir.lastIndexOf('/')
45
+ if (slash === -1)
46
+ break
47
+ dir = dir.slice(0, slash)
48
+ }
49
+ }
50
+ return byDir.get('')
51
+ }
52
+
18
53
 
19
54
  /** The files under `absRoot` by their path from it, `/`-separated; a symlink counts only when it lands on a file inside `realRoot`. */
20
55
  function listFiles(absRoot: string, realRoot: string): Map<string, string> {
@@ -53,6 +88,7 @@ export function createStaticDirServer(
53
88
  compressEnabled: boolean,
54
89
  trustProxy: TrustProxy,
55
90
  isDev = false,
91
+ extra?: StaticDirExtraOptions,
56
92
  ): PrunelleApp {
57
93
  const prefix = assetPrefix.replace(/^\/+/, '').replace(/\/$/, '')
58
94
  const absRoot = resolve(outDir)
@@ -67,7 +103,16 @@ export function createStaticDirServer(
67
103
  const securityEntries = buildSecurityHeaderEntries(security)
68
104
  const securityRecord = Object.fromEntries(securityEntries)
69
105
  const baseCsp = resolveCspPolicy(security)
70
- const htmlCsp = baseCsp !== undefined ? withCspHashes(baseCsp, { styleHashes: [PRUNELLE_ISLAND_STYLE_HASH] }) : undefined
106
+ const nav = extra !== undefined ? createNavigation(extra.navigation) : undefined
107
+ const plugins = extra?.plugins !== undefined ? resolvePlugins(extra.plugins) : []
108
+ const extraStyleHashes = [PRUNELLE_ISLAND_STYLE_HASH, ...(nav?.styleHashes ?? [])]
109
+ const extraScriptHashes = [
110
+ ...(nav?.scriptHashes ?? []),
111
+ ...plugins.flatMap(p => p.inlineScripts ?? []).map(cspSha256),
112
+ ]
113
+ const htmlCsp = baseCsp !== undefined
114
+ ? withCspHashes(baseCsp, { styleHashes: extraStyleHashes, scriptHashes: extraScriptHashes })
115
+ : undefined
71
116
  const hstsValue = resolveHstsValue(security)
72
117
  const withHsts = hstsValue === undefined || isDev
73
118
  ? (res: Response) => res
@@ -76,7 +121,7 @@ export function createStaticDirServer(
76
121
 
77
122
  function entryFor(rel: string, path: string, all: ReadonlyMap<string, string>): ServedFile {
78
123
  const ext = extname(rel).toLowerCase()
79
- const type = MIME[ext] ?? 'application/octet-stream'
124
+ const type = MIME[ext] ?? EXTRA_STATIC_MIME[ext] ?? 'application/octet-stream'
80
125
  const isHtml = ext === '.html' || ext === '.htm'
81
126
  // An exported page's CSP gains the hashes of its own `<style>` blocks.
82
127
  const csp = isHtml && htmlCsp !== undefined ? withCspHashes(htmlCsp, { styleHashes: inlineStyleHashes(readFileSync(path, 'utf8')) }) : undefined
@@ -100,11 +145,18 @@ export function createStaticDirServer(
100
145
  }
101
146
 
102
147
  // 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 } {
148
+ function buildTable(): { table: Map<string, ServedFile>, notFoundByDir: Map<string, ServedFile> } {
104
149
  const files = listFiles(absRoot, realRoot)
105
150
  const table = new Map<string, ServedFile>()
106
- for (const [rel, path] of files)
107
- table.set(rel, entryFor(rel, path, files))
151
+ const notFoundByDir = new Map<string, ServedFile>()
152
+ for (const [rel, path] of files) {
153
+ const entry = entryFor(rel, path, files)
154
+ table.set(rel, entry)
155
+ if (rel === '404.html')
156
+ notFoundByDir.set('', entry)
157
+ else if (rel.endsWith('/404.html'))
158
+ notFoundByDir.set(rel.slice(0, -'/404.html'.length), entry)
159
+ }
108
160
  for (const [rel, entry] of [...table]) {
109
161
  if (rel.endsWith('.html') && !table.has(rel.slice(0, -5)))
110
162
  table.set(rel.slice(0, -5), entry)
@@ -116,7 +168,7 @@ export function createStaticDirServer(
116
168
  table.set(dir, entry)
117
169
  }
118
170
  }
119
- return { table, notFound: table.get('404.html') }
171
+ return { table, notFoundByDir }
120
172
  }
121
173
 
122
174
  let current = buildTable()
@@ -141,8 +193,9 @@ export function createStaticDirServer(
141
193
  const found = rel === undefined ? undefined : current.table.get(rel)
142
194
  if (found !== undefined)
143
195
  return serveFile(req, found)
144
- if (current.notFound !== undefined)
145
- return serveFile(req, current.notFound, 404)
196
+ const notFound = findNotFound(rel, current.notFoundByDir)
197
+ if (notFound !== undefined)
198
+ return serveFile(req, notFound, 404)
146
199
  return withHsts(new Response('Not Found', { status: 404, headers: securityRecord }), req)
147
200
  }
148
201
 
@@ -37,6 +37,7 @@ async function settleWithin(
37
37
  timer = setTimeout(() => {
38
38
  if (onAbort !== undefined)
39
39
  signal.removeEventListener('abort', onAbort)
40
+ chunk.discard?.()
40
41
  const error = new Error(`<Suspense> boundary ${chunk.id} did not resolve within ${streamTimeout} ms`)
41
42
  resolve({ html: runInScope(() => chunk.renderError(error)), error })
42
43
  }, remaining)
@@ -52,7 +53,13 @@ async function settleWithin(
52
53
  }
53
54
 
54
55
  /** 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
+ export function streamDocument(
57
+ shell: string,
58
+ rctx: RenderContext,
59
+ streamTimeout: number,
60
+ onBoundaryError: (error: unknown) => void,
61
+ transformChunk?: (html: string) => string | Promise<string>,
62
+ ): ReadableStream<Uint8Array> {
56
63
  let splitAt = shell.lastIndexOf(STREAM_TAIL_MARK)
57
64
  let tailOffset = STREAM_TAIL_MARK.length
58
65
  if (splitAt === -1) {
@@ -75,39 +82,51 @@ export function streamDocument(shell: string, rctx: RenderContext, streamTimeout
75
82
  }
76
83
  catch {
77
84
  closed = true
85
+ rctx.aborted = true
78
86
  abortCtrl.abort()
79
87
  }
80
88
  }
81
89
 
82
90
  return new ReadableStream<Uint8Array>({
83
91
  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)
92
+ try {
93
+ safeEnqueue(controller, textEncoder.encode(openingHtml))
94
+ // A resolved boundary can render boundaries of its own, so each flush also drains the ones it added.
95
+ let flushed = 0
96
+ const flushPending = async (): Promise<void> => {
97
+ if (closed || abortCtrl.signal.aborted)
95
98
  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
- }))
99
+ const chunks = rctx.pending.slice(flushed)
100
+ flushed = rctx.pending.length
101
+ await Promise.all(chunks.map(async (chunk) => {
102
+ const settled = await settleWithin(chunk, deadline, streamTimeout, abortCtrl.signal, runInScope)
103
+ if (settled === undefined || closed || abortCtrl.signal.aborted)
104
+ return
105
+ if ('error' in settled)
106
+ runInScope(() => onBoundaryError(settled.error))
107
+ let chunkHtml = settled.html
108
+ if (transformChunk !== undefined && chunkHtml !== '')
109
+ chunkHtml = await runInScope(() => transformChunk(chunkHtml))
110
+ if (closed || abortCtrl.signal.aborted)
111
+ return
112
+ safeEnqueue(controller, textEncoder.encode(streamChunkScript(chunk.id, chunkHtml)))
113
+ await flushPending()
114
+ }))
115
+ }
116
+ await flushPending()
117
+ if (!closed && !abortCtrl.signal.aborted) {
118
+ safeEnqueue(controller, textEncoder.encode(tailHtml))
119
+ closed = true
120
+ safeClose(controller)
121
+ }
101
122
  }
102
- await flushPending()
103
- if (!closed && !abortCtrl.signal.aborted) {
104
- safeEnqueue(controller, textEncoder.encode(tailHtml))
105
- closed = true
106
- safeClose(controller)
123
+ finally {
124
+ rctx.aborted = true
107
125
  }
108
126
  },
109
127
  cancel() {
110
128
  closed = true
129
+ rctx.aborted = true
111
130
  abortCtrl.abort()
112
131
  },
113
132
  })
@@ -3,6 +3,7 @@
3
3
 
4
4
  import type { CatchProps, ConsentGateProps } from '../context'
5
5
  import type { Html, PrunelleChild } from '../jsx-runtime'
6
+ import type { FieldConstraint } from '../server/form-schema'
6
7
  import { AsyncLocalStorage } from 'node:async_hooks'
7
8
  import { registerServerContextBridge } from '../context'
8
9
  import { raw, ssrChild } from './index'
@@ -18,6 +19,8 @@ export interface PendingChunk {
18
19
  // Settles to the boundary's HTML, or to its error template and the error: it never rejects.
19
20
  settled: Promise<SettledChunk>
20
21
  renderError: (error: unknown) => string
22
+ /** Marks this chunk as timed out / aborted so late resolution skips rendering into the RenderContext. */
23
+ discard?: () => void
21
24
  }
22
25
 
23
26
  export interface RenderContext {
@@ -51,10 +54,18 @@ export interface RenderContext {
51
54
  inTarget: boolean
52
55
  /** Compiler-emitted inline `<style>` contents rendered during this request, for CSP hashing. */
53
56
  inlineStyles: string[] | undefined
57
+ /** True once HTTP headers (and CSP) have been flushed for a streamed response. */
58
+ headersFlushed: boolean
59
+ /** True once the post-flush inline `<style>` warning has been emitted for this request. */
60
+ warnedStreamStyle: boolean
61
+ /** True once the stream/region finished, timed out, was aborted, or was discarded (e.g. HEAD). */
62
+ aborted: boolean
54
63
  /** Request consent state used by `<ConsentGate>`. */
55
64
  consent: { has(category: string): boolean } | undefined
56
65
  /** Reports an error a `<Catch>` rendered its fallback for, to the app's error hook. */
57
66
  onCaught: ((error: unknown) => void) | undefined
67
+ /** Actions referenced via `useAction(fn).action` during this request, keyed by action URL. */
68
+ formActions: Map<string, unknown> | undefined
58
69
  }
59
70
 
60
71
  interface RenderScope {
@@ -63,12 +74,25 @@ interface RenderScope {
63
74
  outerContexts: ReadonlyMap<symbol, unknown> | undefined
64
75
  island: string | undefined
65
76
  inTarget: boolean
77
+ formFields: ReadonlyMap<string, FieldConstraint> | undefined
66
78
  }
67
79
 
68
80
  const STORAGE_KEY = Symbol.for('pru.render.storage')
69
81
  const SCOPE_STORAGE_KEY = Symbol.for('pru.render.scope.storage')
70
82
  const renderStorage: AsyncLocalStorage<RenderContext> = ((globalThis as Record<symbol, AsyncLocalStorage<RenderContext> | undefined>)[STORAGE_KEY] ??= new AsyncLocalStorage<RenderContext>())
71
83
  const scopeStorage: AsyncLocalStorage<RenderScope> = ((globalThis as Record<symbol, AsyncLocalStorage<RenderScope> | undefined>)[SCOPE_STORAGE_KEY] ??= new AsyncLocalStorage<RenderScope>())
84
+ let fallbackFormAction: { url: string, action: unknown } | undefined
85
+ let fallbackFormFields: ReadonlyMap<string, FieldConstraint> | undefined
86
+
87
+ ;(globalThis as { __pruAct?: (url: string, action: unknown) => void }).__pruAct = (url, action) => {
88
+ if (url === '')
89
+ return
90
+ const ctx = renderStorage.getStore()
91
+ if (ctx !== undefined)
92
+ (ctx.formActions ??= new Map()).set(url, action)
93
+ else
94
+ fallbackFormAction = { url, action }
95
+ }
72
96
 
73
97
  function activeScope(ctx: RenderContext): RenderScope {
74
98
  const scope = scopeStorage.getStore()
@@ -80,6 +104,38 @@ function activeScope(ctx: RenderContext): RenderScope {
80
104
  outerContexts: ctx.outerContexts,
81
105
  island: ctx.island,
82
106
  inTarget: ctx.inTarget,
107
+ formFields: undefined,
108
+ }
109
+ }
110
+
111
+ export function lookupFormAction(url: string): unknown {
112
+ const ctx = renderStorage.getStore()
113
+ if (ctx !== undefined)
114
+ return ctx.formActions?.get(url)
115
+ return fallbackFormAction?.url === url ? fallbackFormAction.action : undefined
116
+ }
117
+
118
+ export function currentFormFields(): ReadonlyMap<string, FieldConstraint> | undefined {
119
+ const ctx = renderStorage.getStore()
120
+ return ctx !== undefined ? activeScope(ctx).formFields : fallbackFormFields
121
+ }
122
+
123
+ export function runWithFormFields<T>(fields: ReadonlyMap<string, FieldConstraint>, fn: () => T): T {
124
+ const ctx = renderStorage.getStore()
125
+ if (ctx !== undefined)
126
+ return scopeStorage.run({ ...activeScope(ctx), formFields: fields }, fn)
127
+ const prev = fallbackFormFields
128
+ fallbackFormFields = fields
129
+ try {
130
+ const out = fn()
131
+ if (out instanceof Promise)
132
+ return out.finally(() => { fallbackFormFields = prev }) as T
133
+ fallbackFormFields = prev
134
+ return out
135
+ }
136
+ catch (err) {
137
+ fallbackFormFields = prev
138
+ throw err
83
139
  }
84
140
  }
85
141
 
@@ -163,8 +219,12 @@ export function createRenderContext(
163
219
  regionAncestors: ancestors,
164
220
  inTarget: false,
165
221
  inlineStyles: undefined,
222
+ headersFlushed: false,
223
+ warnedStreamStyle: false,
224
+ aborted: false,
166
225
  consent,
167
226
  onCaught,
227
+ formActions: undefined,
168
228
  }
169
229
  }
170
230
 
@@ -173,9 +233,14 @@ export function recordInlineStyle(css: string): void {
173
233
  const ctx = renderStorage.getStore()
174
234
  if (ctx === undefined || css === '')
175
235
  return
236
+ const isNew = ctx.inlineStyles === undefined || !ctx.inlineStyles.includes(css)
237
+ if (ctx.headersFlushed && isNew && !ctx.warnedStreamStyle) {
238
+ ctx.warnedStreamStyle = true
239
+ console.warn('prunelle: an inline <style> was rendered inside a streamed <Suspense> boundary after CSP headers were sent; move the style into a CSS file or outside <Suspense> so strict CSP does not block it.')
240
+ }
176
241
  if (ctx.inlineStyles === undefined)
177
242
  ctx.inlineStyles = [css]
178
- else if (!ctx.inlineStyles.includes(css))
243
+ else if (isNew)
179
244
  ctx.inlineStyles.push(css)
180
245
  }
181
246
 
@@ -277,18 +342,35 @@ export function Suspense(props: { fallback?: PrunelleChild, error?: PrunelleChil
277
342
  return ''
278
343
  }
279
344
  }
280
- ctx.pending.push({ id, settled: settle(ctx, scope, child, renderError), renderError })
345
+ let discarded = false
346
+ const isAborted = (): boolean => ctx.aborted || discarded
347
+ ctx.pending.push({
348
+ id,
349
+ settled: settle(ctx, scope, child, renderError, isAborted),
350
+ renderError,
351
+ discard: () => { discarded = true },
352
+ })
281
353
 
282
354
  const fallbackHtml = ssrChild(props.fallback)
283
355
  return raw(`<pru-s id="k-s-${id}">${fallbackHtml}</pru-s>`)
284
356
  }
285
357
 
286
- async function settle(ctx: RenderContext, scope: RenderScope, child: Promise<PrunelleChild>, renderError: (error: unknown) => string): Promise<SettledChunk> {
358
+ async function settle(
359
+ ctx: RenderContext,
360
+ scope: RenderScope,
361
+ child: Promise<PrunelleChild>,
362
+ renderError: (error: unknown) => string,
363
+ isAborted: () => boolean,
364
+ ): Promise<SettledChunk> {
287
365
  try {
288
366
  const resolved = await child
367
+ if (isAborted())
368
+ return { html: '' }
289
369
  return { html: runWithRenderContext(ctx, () => scopeStorage.run(scope, () => ssrChild(resolved))) }
290
370
  }
291
371
  catch (error) {
372
+ if (isAborted())
373
+ return { html: '' }
292
374
  return { html: renderError(error), error }
293
375
  }
294
376
  }
package/src/ssr/index.ts CHANGED
@@ -1,11 +1,15 @@
1
1
  // Prunelle SSR runtime: flat string concatenation with fast-path escaping and zero-overhead islands.
2
2
 
3
3
  import type { Html, HydrateStrategy, PrunelleChild } from '../jsx-runtime'
4
+ import type { ServerAction } from '../server/action'
5
+ import type { FieldConstraint } from '../server/form-schema'
4
6
  import { isBlockedAttr, isStringBoolAttr, isUnsafeUrlAttr } from '../attrs'
5
7
  import { renderOnServer } from '../reactivity/index'
8
+ import { renderProtectFields } from '../server/action-protect'
9
+ import { extractFormSchema, lookupFieldConstraint } from '../server/form-schema'
6
10
  import { styleText } from '../style'
7
11
  import { assertRenderable } from '../unrenderable'
8
- import { currentRenderContext, PRUNELLE_STREAM_SCRIPT, renderIsland } from './context'
12
+ import { currentFormFields, currentRenderContext, lookupFormAction, PRUNELLE_STREAM_SCRIPT, renderIsland, runWithFormFields } from './context'
9
13
  import { keepScrollTag } from './navigation'
10
14
  export { ssrStyleBlock } from './context'
11
15
 
@@ -143,6 +147,8 @@ export function ssrSpread(props: Record<string, unknown> | null | undefined, tag
143
147
  if (props == null || typeof props !== 'object')
144
148
  return ''
145
149
  let out = ''
150
+ let formPresent = 0
151
+ const trackForm = (tag === 'input' || tag === 'select' || tag === 'textarea') && currentFormFields() !== undefined
146
152
  for (const [rawKey, value] of Object.entries(props)) {
147
153
  if (rawKey === 'key' || rawKey === 'ref' || rawKey === '$hydrate' || rawKey === 'children')
148
154
  continue
@@ -151,8 +157,121 @@ export function ssrSpread(props: Record<string, unknown> | null | undefined, tag
151
157
  const name = rawKey === 'className' ? 'class' : rawKey === 'htmlFor' ? 'for' : rawKey
152
158
  if (isBlockedAttr(name))
153
159
  continue
160
+ if (trackForm && value !== undefined) {
161
+ const bit = FORM_ATTR_BITS[name.toLowerCase()]
162
+ if (bit !== undefined)
163
+ formPresent |= bit
164
+ }
154
165
  out += name === 'style' ? ssrStyle(value) : ssrAttr(name, value, tag)
155
166
  }
167
+ if (trackForm && typeof props.name === 'string')
168
+ out += ssrFormAttrs(tag, props.name, formPresent, props.type)
169
+ return out
170
+ }
171
+
172
+ const FORM_ATTR_BITS: Record<string, number> = {
173
+ type: 1,
174
+ required: 2,
175
+ minlength: 4,
176
+ maxlength: 8,
177
+ min: 16,
178
+ max: 32,
179
+ step: 64,
180
+ pattern: 128,
181
+ }
182
+ const TEXT_INPUT_TYPES = new Set(['text', 'search', 'url', 'tel', 'email', 'password'])
183
+ const NON_REQUIRED_INPUT_TYPES = new Set(['hidden', 'submit', 'button', 'reset', 'image'])
184
+
185
+ function resolveActionForForm(action: unknown): ServerAction<unknown, unknown> | undefined {
186
+ if (typeof action === 'function' && (action as { __pruAction?: boolean }).__pruAction === true)
187
+ return action as ServerAction<unknown, unknown>
188
+ if (typeof action === 'string') {
189
+ const found = lookupFormAction(action)
190
+ if (typeof found === 'function' && (found as { __pruAction?: boolean }).__pruAction === true)
191
+ return found as ServerAction<unknown, unknown>
192
+ }
193
+ return undefined
194
+ }
195
+
196
+ function formFieldsOf(act: ServerAction<unknown, unknown>): ReadonlyMap<string, FieldConstraint> | undefined {
197
+ if (act.schema === undefined)
198
+ return undefined
199
+ const extracted = extractFormSchema(act.schema)
200
+ return extracted.ok && extracted.fields.size > 0 ? extracted.fields : undefined
201
+ }
202
+
203
+ /** Wraps an action-bound `<form>` render during SSR: injects schema constraints for child fields and appends honeypot / signed timestamp inputs. */
204
+ export function ssrForm(action: unknown, render: (action: unknown) => string): string {
205
+ const act = resolveActionForForm(action)
206
+ if (act === undefined)
207
+ return `${render(action)}</form>`
208
+ const hidden = renderProtectFields(act.protect, act.url)
209
+ const fields = formFieldsOf(act)
210
+ const body = fields !== undefined ? runWithFormFields(fields, () => render(action)) : render(action)
211
+ return `${body}${hidden}</form>`
212
+ }
213
+
214
+ /** Async variant of `ssrForm` for action-bound `<form>` elements containing `await`. */
215
+ export async function ssrFormAsync(action: unknown, render: (action: unknown) => Promise<string>): Promise<string> {
216
+ const act = resolveActionForForm(action)
217
+ if (act === undefined)
218
+ return `${await render(action)}</form>`
219
+ const hidden = renderProtectFields(act.protect, act.url)
220
+ const fields = formFieldsOf(act)
221
+ const body = fields !== undefined ? await runWithFormFields(fields, () => render(action)) : await render(action)
222
+ return `${body}${hidden}</form>`
223
+ }
224
+
225
+ /** Emits schema-derived HTML5 constraint attributes on `<input>`, `<select>`, and `<textarea>` inside an action-bound `<form>`. */
226
+ export function ssrFormAttrs(tag: 'input' | 'select' | 'textarea', name: unknown, present: number, inputType?: unknown): string {
227
+ const fields = currentFormFields()
228
+ if (fields === undefined || typeof name !== 'string' || name === '')
229
+ return ''
230
+ const c = lookupFieldConstraint(fields, name)
231
+ if (c === undefined)
232
+ return ''
233
+
234
+ let out = ''
235
+ const explicitType = typeof inputType === 'string' ? inputType.toLowerCase() : undefined
236
+ let effectiveType: string | undefined
237
+ if (tag === 'input') {
238
+ if (explicitType === undefined && (present & 1) === 0 && c.type !== undefined) {
239
+ out += ` type="${c.type}"`
240
+ effectiveType = c.type
241
+ }
242
+ else {
243
+ effectiveType = explicitType ?? 'text'
244
+ }
245
+ }
246
+
247
+ const skipRequired = tag === 'input' && (
248
+ NON_REQUIRED_INPUT_TYPES.has(effectiveType!)
249
+ || (effectiveType === 'checkbox' && c.isArray === true)
250
+ )
251
+ if (c.required === true && (present & 2) === 0 && !skipRequired)
252
+ out += ' required'
253
+
254
+ const supportsLength = tag === 'textarea' || (tag === 'input' && TEXT_INPUT_TYPES.has(effectiveType!))
255
+ if (supportsLength) {
256
+ if (c.minLength !== undefined && (present & 4) === 0)
257
+ out += ` minlength="${c.minLength}"`
258
+ if (c.maxLength !== undefined && (present & 8) === 0)
259
+ out += ` maxlength="${c.maxLength}"`
260
+ }
261
+
262
+ if (tag === 'input') {
263
+ if (effectiveType === 'number' || effectiveType === 'range') {
264
+ if (c.min !== undefined && (present & 16) === 0)
265
+ out += ` min="${c.min}"`
266
+ if (c.max !== undefined && (present & 32) === 0)
267
+ out += ` max="${c.max}"`
268
+ if (c.step !== undefined && (present & 64) === 0)
269
+ out += ` step="${c.step}"`
270
+ }
271
+ if (TEXT_INPUT_TYPES.has(effectiveType!) && c.pattern !== undefined && (present & 128) === 0)
272
+ out += ` pattern="${escAttr(c.pattern)}"`
273
+ }
274
+
156
275
  return out
157
276
  }
158
277
 
@@ -215,8 +334,16 @@ function serializeIslandProps(props: Record<string, unknown>): string {
215
334
  throw new TypeError(`prunelle: island prop "${key}" is a function, which cannot reach the browser; define it inside the island, or import it there.`)
216
335
  if (typeof orig === 'object' && orig !== null && 'peek' in orig && 'value' in orig)
217
336
  throw new TypeError(`prunelle: island prop "${key}" is a signal; pass ${key}.value, or import the signal in the island from a shared module.`)
218
- if (typeof orig === 'object' && orig !== null && !Array.isArray(orig) && Object.hasOwn(orig, '__k'))
219
- return { __k: 'O', v: Object.entries(orig).filter(([, x]) => x !== undefined) }
337
+ if (typeof orig === 'object' && orig !== null && !Array.isArray(orig)) {
338
+ const proto = Object.getPrototypeOf(orig) as { constructor?: { name?: string } } | null
339
+ if (proto !== Object.prototype && proto !== null) {
340
+ const typeName = proto?.constructor?.name || 'Object'
341
+ const propName = key ? `"${key}"` : '(root)'
342
+ throw new TypeError(`prunelle: island prop ${propName} (${typeName}) cannot be serialized to the browser; pass a plain object, array, primitive, Date, Map, Set, URL, RegExp, or BigInt.`)
343
+ }
344
+ if (Object.hasOwn(orig, '__k'))
345
+ return { __k: 'O', v: Object.entries(orig).filter(([, x]) => x !== undefined) }
346
+ }
220
347
  return value
221
348
  })
222
349
  }
package/src/ssr/region.ts CHANGED
@@ -83,6 +83,7 @@ async function settleChunkWithin(
83
83
  let timer: ReturnType<typeof setTimeout> | undefined
84
84
  const timedOut = new Promise<SettledChunk>((resolve) => {
85
85
  timer = setTimeout(() => {
86
+ chunk.discard?.()
86
87
  const error = new Error(`<Suspense> boundary ${chunk.id} did not resolve within ${streamTimeout} ms`)
87
88
  resolve({ html: runInScope(() => chunk.renderError(error)), error })
88
89
  }, remaining)
@@ -98,8 +99,7 @@ async function settleChunkWithin(
98
99
  async function awaitRegionDiscovery(
99
100
  ctx: RenderContext,
100
101
  deadline: number,
101
- onError: ((error: unknown) => void) | undefined,
102
- runInScope: <T>(fn: () => T) => T,
102
+ reportError: (id: number, error: unknown) => void,
103
103
  ): Promise<void> {
104
104
  const watched = new Set<number>()
105
105
  let pendingCount = 0
@@ -125,8 +125,8 @@ async function awaitRegionDiscovery(
125
125
  pendingCount--
126
126
  if (done)
127
127
  return
128
- if ('error' in settled && onError !== undefined)
129
- runInScope(() => onError(settled.error))
128
+ if ('error' in settled)
129
+ reportError(chunk.id, settled.error)
130
130
  if (ctx.regionHtml !== undefined) {
131
131
  finish()
132
132
  return
@@ -150,22 +150,34 @@ export async function finishRegion(ctx: RenderContext, options?: FinishRegionOpt
150
150
  const onError = options?.onError
151
151
  const runInScope = options?.runInScope ?? (<T>(fn: () => T) => fn())
152
152
  const deadline = Date.now() + streamTimeout
153
+ const reported = new Set<number>()
154
+ const reportError = (id: number, error: unknown): void => {
155
+ if (onError === undefined || reported.has(id))
156
+ return
157
+ reported.add(id)
158
+ runInScope(() => onError(error))
159
+ }
153
160
 
154
- if (ctx.regionHtml === undefined && ctx.pending.length > 0)
155
- await awaitRegionDiscovery(ctx, deadline, onError, runInScope)
161
+ try {
162
+ if (ctx.regionHtml === undefined && ctx.pending.length > 0)
163
+ await awaitRegionDiscovery(ctx, deadline, reportError)
156
164
 
157
- let html = ctx.regionHtml
158
- if (html === undefined)
159
- return undefined
160
- for (let i = 0; i < ctx.pending.length; i++) {
161
- const chunk = ctx.pending[i]!
162
- const range = findPlaceholderRange(html, chunk.id)
163
- if (range === undefined)
164
- continue
165
- const settled = await settleChunkWithin(chunk, deadline, streamTimeout, runInScope)
166
- if ('error' in settled && onError !== undefined)
167
- runInScope(() => onError(settled.error))
168
- html = html.slice(0, range[0]) + settled.html + html.slice(range[1])
165
+ let html = ctx.regionHtml
166
+ if (html === undefined)
167
+ return undefined
168
+ for (let i = 0; i < ctx.pending.length; i++) {
169
+ const chunk = ctx.pending[i]!
170
+ const range = findPlaceholderRange(html, chunk.id)
171
+ if (range === undefined)
172
+ continue
173
+ const settled = await settleChunkWithin(chunk, deadline, streamTimeout, runInScope)
174
+ if ('error' in settled)
175
+ reportError(chunk.id, settled.error)
176
+ html = html.slice(0, range[0]) + settled.html + html.slice(range[1])
177
+ }
178
+ return html
179
+ }
180
+ finally {
181
+ ctx.aborted = true
169
182
  }
170
- return html
171
183
  }