prunelle 0.1.1 → 0.5.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 (105) hide show
  1. package/llms.txt +23 -19
  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 +91 -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 +654 -0
  27. package/src/cli/check-links.ts +619 -0
  28. package/src/cli/check.ts +52 -5
  29. package/src/cli/commands.ts +86 -4
  30. package/src/cli/docs.ts +402 -0
  31. package/src/cli/inspect.ts +31 -2
  32. package/src/cli/mcp-tools.ts +480 -0
  33. package/src/cli/mcp.ts +205 -0
  34. package/src/cli/new.ts +2 -2
  35. package/src/cli/render.ts +261 -0
  36. package/src/cli/upgrade-names.ts +73 -13
  37. package/src/cli/upgrade.ts +137 -16
  38. package/src/compiler/analyze.ts +20 -6
  39. package/src/compiler/cacheability.ts +592 -0
  40. package/src/compiler/compliance-rgaa.ts +502 -0
  41. package/src/compiler/compliance.ts +120 -221
  42. package/src/compiler/dev-source.ts +87 -0
  43. package/src/compiler/dom-attrs.ts +138 -65
  44. package/src/compiler/dom.ts +12 -11
  45. package/src/compiler/expr-context.ts +167 -57
  46. package/src/compiler/props.ts +87 -36
  47. package/src/compiler/scope.ts +56 -17
  48. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  49. package/src/compiler/ssr.ts +216 -84
  50. package/src/dev/error-log.ts +151 -0
  51. package/src/dev/index.ts +84 -34
  52. package/src/dev/open-editor.ts +204 -0
  53. package/src/dev/protocol.ts +1 -0
  54. package/src/dev/reload.ts +5 -3
  55. package/src/dev/supervisor.ts +42 -25
  56. package/src/dev/watchers.ts +47 -11
  57. package/src/dom/action.ts +4 -1
  58. package/src/dom/attrs.ts +15 -3
  59. package/src/dom/extras.ts +2 -2
  60. package/src/dom/island.ts +11 -10
  61. package/src/plugins/config.ts +4 -4
  62. package/src/plugins/index.ts +2 -2
  63. package/src/plugins/public.ts +5 -2
  64. package/src/plugins/services.ts +62 -0
  65. package/src/plugins/types.ts +32 -0
  66. package/src/server/action-protect.ts +198 -0
  67. package/src/server/action-registry.ts +1 -1
  68. package/src/server/action.ts +82 -27
  69. package/src/server/assets.ts +34 -2
  70. package/src/server/compress.ts +91 -9
  71. package/src/server/errors.ts +303 -65
  72. package/src/server/form-schema.ts +343 -0
  73. package/src/server/health.ts +244 -0
  74. package/src/server/http.ts +128 -31
  75. package/src/server/index.ts +230 -260
  76. package/src/server/loader.ts +5 -0
  77. package/src/server/param-matchers.ts +112 -0
  78. package/src/server/plugin-host.ts +123 -88
  79. package/src/server/public.ts +3 -3
  80. package/src/server/rate-limit.ts +58 -35
  81. package/src/server/request-body.ts +1 -1
  82. package/src/server/route-cache.ts +423 -0
  83. package/src/server/route-table.ts +339 -8
  84. package/src/server/router.ts +125 -40
  85. package/src/server/routing.ts +196 -63
  86. package/src/server/security.ts +208 -32
  87. package/src/server/serve-handlers.ts +21 -7
  88. package/src/server/start.ts +60 -16
  89. package/src/server/static-dir.ts +61 -8
  90. package/src/server/stream.ts +41 -22
  91. package/src/ssr/context.ts +85 -3
  92. package/src/ssr/index.ts +120 -1
  93. package/src/ssr/region.ts +31 -19
  94. package/src/test/browser.ts +6 -0
  95. package/src/test/index.ts +17 -3
  96. package/src/ts-plugin/diagnostics.ts +378 -0
  97. package/src/ts-plugin/fixes.ts +364 -0
  98. package/src/ts-plugin/index.ts +194 -0
  99. package/templates/_shared/AGENTS.md +2 -2
  100. package/templates/_shared/mcp.json +11 -0
  101. package/templates/_shared/src/routes/legal.tsx +5 -0
  102. package/templates/_shared/tsconfig.json +5 -0
  103. package/templates/blog/prunelle.config.ts +1 -1
  104. package/templates/blog/src/routes/index.tsx +4 -0
  105. package/ts-plugin.cjs +4277 -0
@@ -12,6 +12,7 @@ import type { SelectValueBinding } from './ssr-helpers'
12
12
  import type { PrunelleTagEmitter } from './ssr-prunelle-tags'
13
13
  import { analyzeModule, parseTsx } from './analyze'
14
14
  import { walk } from './ast'
15
+ import { createDevSourceAttr } from './dev-source'
15
16
  import { mistake } from './mistakes'
16
17
  import { alignLines, lineMarker, SourceEditor } from './patch'
17
18
  import {
@@ -24,6 +25,7 @@ import {
24
25
  isComponentTag,
25
26
  isJsxNode,
26
27
  jsxTagName,
28
+ matchJsxMapCall,
27
29
  planChildSlots,
28
30
  RAW_TEXT_ELEMENTS,
29
31
  resolvePrunelleTag,
@@ -34,11 +36,86 @@ import {
34
36
  emitSsrElementAttrs,
35
37
  precomputeSsrSubtreeFlags,
36
38
  serializeComponentProps,
39
+ staticLiteralOrTemplate,
37
40
  StringParts,
38
41
  } from './ssr-helpers'
39
42
  import { emitIsland } from './ssr-island'
40
43
  import { emitCatch, emitSuspense } from './ssr-prunelle-tags'
41
44
 
45
+ const FORM_CONTROL_TAGS = new Set(['input', 'select', 'textarea'])
46
+ const FORM_ATTR_BITS: Record<string, number> = {
47
+ type: 1,
48
+ required: 2,
49
+ minlength: 4,
50
+ maxlength: 8,
51
+ min: 16,
52
+ max: 32,
53
+ step: 64,
54
+ pattern: 128,
55
+ }
56
+
57
+ function findDynamicFormAction(node: JSXElement): Node | undefined {
58
+ for (const attr of node.openingElement.attributes) {
59
+ if (attr.type !== 'JSXAttribute' || jsxTagName(attr.name) !== 'action')
60
+ continue
61
+ if (attr.value?.type !== 'JSXExpressionContainer' || attr.value.expression.type === 'JSXEmptyExpression')
62
+ return undefined
63
+ const expr = attr.value.expression
64
+ if (staticLiteralOrTemplate(expr).ok)
65
+ return undefined
66
+ if (expr.type === 'ConditionalExpression' && staticLiteralOrTemplate(expr.consequent).ok && staticLiteralOrTemplate(expr.alternate).ok)
67
+ return undefined
68
+ return expr
69
+ }
70
+ return undefined
71
+ }
72
+
73
+ function emitFormControlAttrs(
74
+ node: JSXElement,
75
+ tag: 'input' | 'select' | 'textarea',
76
+ parts: StringParts,
77
+ use: (name: string) => string,
78
+ compileSubExpression: (node: Node) => string,
79
+ ): void {
80
+ const attrs = node.openingElement.attributes
81
+ if (attrs.some(a => a.type === 'JSXSpreadAttribute'))
82
+ return
83
+ let nameExpr: string | undefined
84
+ let typeExpr: string | undefined
85
+ let present = 0
86
+ for (const attr of attrs) {
87
+ if (attr.type !== 'JSXAttribute')
88
+ continue
89
+ const attrName = jsxTagName(attr.name).toLowerCase()
90
+ const bit = FORM_ATTR_BITS[attrName]
91
+ if (bit !== undefined)
92
+ present |= bit
93
+ if (attrName === 'name') {
94
+ if (attr.value?.type === 'Literal' && typeof attr.value.value === 'string') {
95
+ nameExpr = JSON.stringify(attr.value.value)
96
+ }
97
+ else if (attr.value?.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
98
+ const lit = staticLiteralOrTemplate(attr.value.expression)
99
+ nameExpr = lit.ok && typeof lit.value === 'string' ? JSON.stringify(lit.value) : compileSubExpression(attr.value.expression)
100
+ }
101
+ }
102
+ else if (tag === 'input' && attrName === 'type') {
103
+ if (attr.value?.type === 'Literal' && typeof attr.value.value === 'string') {
104
+ typeExpr = JSON.stringify(attr.value.value.toLowerCase())
105
+ }
106
+ else if (attr.value?.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
107
+ const lit = staticLiteralOrTemplate(attr.value.expression)
108
+ if (lit.ok && typeof lit.value === 'string')
109
+ typeExpr = JSON.stringify(lit.value.toLowerCase())
110
+ }
111
+ }
112
+ }
113
+ if (nameExpr === undefined)
114
+ return
115
+ const typeArg = typeExpr !== undefined ? `, ${typeExpr}` : ''
116
+ parts.pushExpr(`${use('ssrFormAttrs')}(${JSON.stringify(tag)}, ${nameExpr}, ${present}${typeArg})`)
117
+ }
118
+
42
119
  export interface IslandBinding {
43
120
  id: string
44
121
  chunk: string
@@ -51,6 +128,8 @@ export interface CompileSsrOptions {
51
128
  /** Hydration markers everywhere, nowhere, or only inside these source spans. */
52
129
  emitMarkers?: boolean | readonly (readonly [number, number])[] | undefined
53
130
  analysis?: ModuleAnalysis | undefined
131
+ /** Project root for dev-only `data-pru-src="file:line:col"` attributes; omit in production. */
132
+ devSourceRoot?: string | undefined
54
133
  }
55
134
 
56
135
  export interface CompileResult {
@@ -58,10 +137,94 @@ export interface CompileResult {
58
137
  analysis: ModuleAnalysis
59
138
  }
60
139
 
140
+ function emitActionFormExpr(
141
+ formAction: Node,
142
+ isAsyncForm: boolean,
143
+ nextId: () => number,
144
+ use: (name: string) => string,
145
+ compileSubExpression: (node: Node) => string,
146
+ emitBody: (bufVar: string, parts: StringParts, flush: () => void, pushStmt: (stmt: string) => void, override: { node: Node, ident: string }) => void,
147
+ ): string {
148
+ const faVar = `_fa${nextId()}`
149
+ const innerBuf = `_o${nextId()}`
150
+ const innerStmts: string[] = []
151
+ const innerParts = new StringParts()
152
+ const flushInner = () => {
153
+ if (!innerParts.isEmpty()) {
154
+ innerStmts.push(`${innerBuf} += ${innerParts.toExpr()};`)
155
+ innerParts.clear()
156
+ }
157
+ }
158
+ emitBody(innerBuf, innerParts, flushInner, s => innerStmts.push(s), { node: formAction, ident: faVar })
159
+ if (innerStmts.length > 0)
160
+ flushInner()
161
+ const body = innerStmts.length === 0 ? innerParts.toExpr() : `{ let ${innerBuf} = ""; ${innerStmts.join(' ')} return ${innerBuf}; }`
162
+ return isAsyncForm
163
+ ? `await ${use('ssrFormAsync')}(${compileSubExpression(formAction)}, async (${faVar}) => ${body})`
164
+ : `${use('ssrForm')}(${compileSubExpression(formAction)}, (${faVar}) => ${body})`
165
+ }
166
+
61
167
  function markerTest(markers: NonNullable<CompileSsrOptions['emitMarkers']>): (offset: number) => boolean {
62
168
  return typeof markers === 'boolean' ? () => markers : offset => markers.some(([start, end]) => offset >= start && offset < end)
63
169
  }
64
170
 
171
+ function flushStringParts(bufVar: string, parts: StringParts, stmts: string[]): void {
172
+ if (!parts.isEmpty()) {
173
+ stmts.push(`${bufVar} += ${parts.toExpr()};`)
174
+ parts.clear()
175
+ }
176
+ }
177
+
178
+ function isSingleLoopChild(meaningful: readonly JSXChild[], jsxNodes: WeakSet<Node>): boolean {
179
+ return meaningful.length === 1
180
+ && meaningful[0]!.type === 'JSXExpressionContainer'
181
+ && meaningful[0]!.expression.type !== 'JSXEmptyExpression'
182
+ && matchJsxMapCall(meaningful[0]!.expression, jsxNodes) !== undefined
183
+ }
184
+
185
+ function compileSsrSubExpression(
186
+ code: string,
187
+ node: Node,
188
+ jsxNodes: WeakSet<Node>,
189
+ mark: (offset: number) => string,
190
+ compileRootJsx: (n: JSXElement | JSXFragment) => string,
191
+ ): string {
192
+ if (!containsJsx(node, jsxNodes))
193
+ return mark(node.start) + code.slice(node.start, node.end)
194
+ const sub = new SourceEditor(code.slice(node.start, node.end))
195
+ const offset = node.start
196
+ walk(node, (child) => {
197
+ if (isJsxNode(child)) {
198
+ sub.replace(child.start - offset, child.end - offset, compileRootJsx(child) + mark(child.end))
199
+ return false
200
+ }
201
+ return undefined
202
+ })
203
+ return mark(node.start) + sub.toString()
204
+ }
205
+
206
+ function compileSsrExprAsString(
207
+ expr: Node,
208
+ use: (name: string) => string,
209
+ compileSubExpression: (node: Node) => string,
210
+ compileJsxToStringExpr: (node: JSXElement | JSXFragment) => string,
211
+ ): string {
212
+ if (isJsxNode(expr))
213
+ return compileJsxToStringExpr(expr)
214
+ if (expr.type === 'LogicalExpression' && expr.operator === '&&') {
215
+ const right = unwrapParens(expr.right)
216
+ if (isJsxNode(right))
217
+ return `((${compileSubExpression(expr.left)}) ? (${compileJsxToStringExpr(right)}) : "")`
218
+ }
219
+ if (expr.type === 'ConditionalExpression') {
220
+ const consNode = unwrapParens(expr.consequent)
221
+ const altNode = unwrapParens(expr.alternate)
222
+ if (isJsxNode(consNode) || isJsxNode(altNode))
223
+ return `((${compileSubExpression(expr.test)}) ? (${compileSsrExprAsString(consNode, use, compileSubExpression, compileJsxToStringExpr)}) : (${compileSsrExprAsString(altNode, use, compileSubExpression, compileJsxToStringExpr)}))`
224
+ }
225
+ return `${use('esc')}(${compileSubExpression(expr)})`
226
+ }
227
+
65
228
  export function compileSsr(filename: string, code: string, options: CompileSsrOptions = {}): CompileResult {
66
229
  const program = options.analysis?.program ?? parseTsx(filename, code)
67
230
  const analysis = options.analysis ?? analyzeModule(filename, code, program)
@@ -82,38 +245,24 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
82
245
  }
83
246
 
84
247
  const islands = options.islands
248
+ const devSrc = createDevSourceAttr(filename, code, options.devSourceRoot)
85
249
  const markersAt = markerTest(options.emitMarkers ?? options.isIsland ?? analysis.isInteractive)
86
250
  const jsxNodes = analysis.jsxNodes
87
251
  const exprContext = createExprContext(program, jsxNodes)
88
252
  const { directAwaitNodes, dynamicChildNodes } = precomputeSsrSubtreeFlags(program)
89
- const prunelleTags: PrunelleTagEmitter = { use, compileSubExpression, compileChildren: compileChildrenListToStringExpr, compileJsx: compileJsxToStringExpr, markersAt, directAwaitNodes }
90
-
91
- function compileSubExpression(node: Node): string {
92
- if (!containsJsx(node, jsxNodes))
93
- return mark(node.start) + code.slice(node.start, node.end)
94
-
95
- const sub = new SourceEditor(code.slice(node.start, node.end))
96
- const offset = node.start
97
- walk(node, (child) => {
98
- if (isJsxNode(child)) {
99
- sub.replace(child.start - offset, child.end - offset, compileRootJsx(child) + mark(child.end))
100
- return false
101
- }
102
- return undefined
103
- })
104
- return mark(node.start) + sub.toString()
253
+ const compileSubExpression = (node: Node): string => compileSsrSubExpression(code, node, jsxNodes, mark, compileRootJsx)
254
+ const compileComponentRaw = (node: JSXElement, tag: string): string => {
255
+ let out = ''
256
+ emitComponent(node, tag, new StringParts(), (e) => { out = e })
257
+ return out
105
258
  }
259
+ const prunelleTags: PrunelleTagEmitter = { use, compileSubExpression, compileChildren: compileChildrenListToStringExpr, compileJsx: compileJsxToStringExpr, compileComponentRaw, markersAt, directAwaitNodes, jsxNodes }
106
260
 
107
261
  function compileChildrenListToStringExpr(children: readonly JSXChild[], slotMarkers = markersAt(children[0]?.start ?? 0), inFragment = false, rawTextTag?: 'style' | 'script'): string {
108
262
  const bufVar = `_o${loopCounter++}`
109
263
  const stmts: string[] = []
110
264
  const parts = new StringParts()
111
- const flush = () => {
112
- if (!parts.isEmpty()) {
113
- stmts.push(`${bufVar} += ${parts.toExpr()};`)
114
- parts.clear()
115
- }
116
- }
265
+ const flush = () => flushStringParts(bufVar, parts, stmts)
117
266
  emitChildrenIntoBuffer(children, bufVar, parts, flush, s => stmts.push(s), rawTextTag, slotMarkers, inFragment)
118
267
  if (stmts.length === 0)
119
268
  return parts.toExpr()
@@ -125,7 +274,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
125
274
  }
126
275
 
127
276
  // Emits JSX directly into a string accumulator variable `_out` (zero closures on nested `.map()` loops!)
128
- function emitIntoBuffer(node: JSXElement | JSXFragment, bufVar: string, parts: StringParts, flushParts: () => void, pushStmt: (stmt: string) => void): void {
277
+ function emitIntoBuffer(node: JSXElement | JSXFragment, bufVar: string, parts: StringParts, flushParts: () => void, pushStmt: (stmt: string) => void, actionOverride?: { node: Node, ident: string }): void {
129
278
  if (node.type === 'JSXFragment') {
130
279
  emitChildrenIntoBuffer(node.children, bufVar, parts, flushParts, pushStmt, undefined, markersAt(node.start), true)
131
280
  return
@@ -137,21 +286,21 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
137
286
  return
138
287
  }
139
288
 
140
- parts.pushStatic(`<${tag}`)
289
+ if (tag === 'form' && actionOverride === undefined) {
290
+ const formAction = findDynamicFormAction(node)
291
+ if (formAction !== undefined) {
292
+ parts.pushExpr(emitActionFormExpr(formAction, directAwaitNodes.has(node), () => loopCounter++, use, compileSubExpression, (b, p, f, ps, ov) => emitIntoBuffer(node, b, p, f, ps, ov)))
293
+ return
294
+ }
295
+ }
296
+
297
+ parts.pushStatic(`<${tag}${devSrc(node, tag)}`)
141
298
  const isTextarea = tag === 'textarea'
142
299
  const isSelect = tag === 'select'
143
- const { innerHtmlExpr, textareaValue, nextSelectValue } = emitSsrElementAttrs({
144
- node,
145
- tag,
146
- parts,
147
- activeSelectValue,
148
- flushParts,
149
- pushStmt,
150
- nextId: () => loopCounter++,
151
- use,
152
- compileSubExpression,
153
- })
154
-
300
+ const compileAttrExpr = actionOverride !== undefined ? (n: Node) => (n === actionOverride.node ? actionOverride.ident : compileSubExpression(n)) : compileSubExpression
301
+ const { innerHtmlExpr, textareaValue, nextSelectValue } = emitSsrElementAttrs({ node, tag, parts, activeSelectValue, flushParts, pushStmt, nextId: () => loopCounter++, use, compileSubExpression: compileAttrExpr })
302
+ if (FORM_CONTROL_TAGS.has(tag))
303
+ emitFormControlAttrs(node, tag as 'input' | 'select' | 'textarea', parts, use, compileSubExpression)
155
304
  parts.pushStatic('>')
156
305
  if (VOID_ELEMENTS.has(tag))
157
306
  return
@@ -161,28 +310,23 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
161
310
  activeSelectValue = nextSelectValue
162
311
 
163
312
  try {
164
- if (innerHtmlExpr !== undefined) {
313
+ if (innerHtmlExpr !== undefined)
165
314
  parts.pushExpr(innerHtmlExpr)
166
- }
167
- else if (isTextarea && textareaValue !== undefined && filterMeaningfulChildren(node.children).length === 0) {
168
- if (textareaValue.staticText !== undefined)
169
- parts.pushStatic(escapeStaticText(textareaValue.staticText))
170
- else if (textareaValue.expr !== undefined)
171
- parts.pushExpr(`${use('esc')}(${textareaValue.expr})`)
172
- }
315
+ else if (isTextarea && textareaValue !== undefined && filterMeaningfulChildren(node.children).length === 0)
316
+ textareaValue.staticText !== undefined ? parts.pushStatic(escapeStaticText(textareaValue.staticText)) : textareaValue.expr !== undefined && parts.pushExpr(`${use('esc')}(${textareaValue.expr})`)
173
317
  else if (tag === 'style') {
174
318
  const styleExpr = compileChildrenListToStringExpr(node.children, false, false, 'style')
175
319
  if (styleExpr !== '""')
176
320
  parts.pushExpr(`${use('ssrStyleBlock')}(${styleExpr})`)
177
321
  }
178
- else {
322
+ else
179
323
  emitChildrenIntoBuffer(node.children, bufVar, parts, flushParts, pushStmt, RAW_TEXT_ELEMENTS.has(tag) ? tag as 'style' | 'script' : undefined)
180
- }
181
324
  }
182
325
  finally {
183
326
  activeSelectValue = prevSelectValue
184
327
  }
185
- parts.pushStatic(`</${tag}>`)
328
+ if (actionOverride === undefined)
329
+ parts.pushStatic(`</${tag}>`)
186
330
  }
187
331
 
188
332
  function emitChildrenIntoBuffer(
@@ -244,12 +388,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
244
388
  const idxVar = idxParam ?? `_i${n}`
245
389
  const innerStmts: string[] = []
246
390
  const innerParts = new StringParts()
247
- const flushInner = () => {
248
- if (!innerParts.isEmpty()) {
249
- innerStmts.push(`${bufVar} += ${innerParts.toExpr()};`)
250
- innerParts.clear()
251
- }
252
- }
391
+ const flushInner = () => flushStringParts(bufVar, innerParts, innerStmts)
253
392
  emitIntoBuffer(match.body as JSXElement | JSXFragment, bufVar, innerParts, flushInner, s => innerStmts.push(s))
254
393
  flushInner()
255
394
 
@@ -260,7 +399,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
260
399
  }
261
400
  else if (match.isJsxBody) {
262
401
  const target = compileSubExpression(match.target)
263
- const params = match.params.map(p => code.slice(p.start, p.end)).join(', ')
402
+ const params = match.params.map(p => compileSubExpression(p)).join(', ')
264
403
  parts.pushExpr(`${use('ssrLoop')}(${target}, (${params}) => ${compileJsxToStringExpr(match.body as JSXElement | JSXFragment)})`)
265
404
  }
266
405
  else {
@@ -287,24 +426,9 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
287
426
  }
288
427
  }
289
428
 
290
- function compileExpressionAsString(expr: Node): string {
291
- if (isJsxNode(expr))
292
- return compileJsxToStringExpr(expr)
293
- if (expr.type === 'LogicalExpression' && expr.operator === '&&') {
294
- const right = unwrapParens(expr.right)
295
- if (isJsxNode(right))
296
- return `((${compileSubExpression(expr.left)}) ? (${compileJsxToStringExpr(right)}) : "")`
297
- }
298
- if (expr.type === 'ConditionalExpression') {
299
- const consNode = unwrapParens(expr.consequent)
300
- const altNode = unwrapParens(expr.alternate)
301
- if (isJsxNode(consNode) || isJsxNode(altNode))
302
- return `((${compileSubExpression(expr.test)}) ? (${compileExpressionAsString(consNode)}) : (${compileExpressionAsString(altNode)}))`
303
- }
304
- return `${use('esc')}(${compileSubExpression(expr)})`
305
- }
429
+ const compileExpressionAsString = (expr: Node): string => compileSsrExprAsString(expr, use, compileSubExpression, compileJsxToStringExpr)
306
430
 
307
- function emitComponent(node: JSXElement, tag: string, parts: StringParts): void {
431
+ function emitComponent(node: JSXElement, tag: string, parts: StringParts, onRaw?: (expr: string) => void): void {
308
432
  const { propEntries, allStaticProps, staticPropsObj, hydrateExpr, staticHydrate } = serializeComponentProps(node.openingElement.attributes, compileSubExpression)
309
433
  const childNodes = node.children
310
434
  const meaningfulChildren = filterMeaningfulChildren(childNodes)
@@ -314,7 +438,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
314
438
 
315
439
  const prunelleTag = resolvePrunelleTag(tag, analysis.imports)
316
440
  if (prunelleTag === 'Suspense' || prunelleTag === 'Catch') {
317
- ;(prunelleTag === 'Suspense' ? emitSuspense : emitCatch)(prunelleTags, node, tag, propEntries, parts)
441
+ ;(prunelleTag === 'Suspense' ? emitSuspense : emitCatch)(prunelleTags, node, tag, propEntries, parts, onRaw)
318
442
  return
319
443
  }
320
444
 
@@ -324,28 +448,41 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
324
448
 
325
449
  const childrenHaveAwait = hasChildren && childNodes.some(c => directAwaitNodes.has(c))
326
450
  const childMarkers = islandInfo === undefined && markersAt(node.start)
327
- const childExpr = hasChildren ? compileChildrenListToStringExpr(childNodes, childMarkers, childMarkers && meaningfulChildren.length > 1) : '""'
451
+ const onlyComp = onRaw !== undefined && islandInfo === undefined && meaningfulChildren.length === 1 && meaningfulChildren[0]!.type === 'JSXElement' && isComponentTag(jsxTagName(meaningfulChildren[0]!.openingElement.name)) ? meaningfulChildren[0]! : undefined
452
+ const childExpr = onlyComp !== undefined
453
+ ? compileComponentRaw(onlyComp, jsxTagName(onlyComp.openingElement.name))
454
+ : hasChildren ? compileChildrenListToStringExpr(childNodes, childMarkers, childMarkers && (meaningfulChildren.length > 1 || isSingleLoopChild(meaningfulChildren, jsxNodes))) : '""'
328
455
 
329
456
  if (islandInfo !== undefined) {
330
- emitIsland({ use, nextId: () => loopCounter++, markersAt }, { island: islandInfo, tag, call, start: node.start, propEntries, allStaticProps, staticPropsObj, hydrateExpr, staticHydrate, hasChildren, childExpr, childrenHaveAwait }, parts)
457
+ const target = onRaw !== undefined ? new StringParts() : parts
458
+ emitIsland({ use, nextId: () => loopCounter++, markersAt }, { island: islandInfo, tag, call, start: node.start, propEntries, allStaticProps, staticPropsObj, hydrateExpr, staticHydrate, hasChildren, childExpr, childrenHaveAwait }, target)
459
+ if (onRaw !== undefined)
460
+ onRaw(`${use('raw')}(${target.toExpr()})`)
331
461
  return
332
462
  }
333
463
 
464
+ const emitOut = (expr: string): void => {
465
+ if (onRaw !== undefined)
466
+ onRaw(expr)
467
+ else
468
+ parts.pushExpr(`${use('ssrChild')}(${expr})`)
469
+ }
470
+ const wrappedChild = onlyComp !== undefined ? childExpr : `${use('raw')}(${childExpr})`
334
471
  const childrenHaveDynamic = hasChildren && childNodes.some(c => dynamicChildNodes.has(c))
335
472
 
336
473
  // Lazy memoized getter for non-async dynamic/component children so Providers & context components run before their children!
337
474
  if (childrenHaveDynamic && !childrenHaveAwait) {
338
475
  const cVar = `_c${loopCounter++}`
339
- const propsWithGetter = [...propEntries, `get children() { return ${cVar} === undefined ? (${cVar} = ${use('raw')}(${childExpr})) : ${cVar} }`].join(', ')
340
- parts.pushExpr(`${use('ssrChild')}(${call}((() => { let ${cVar}; return { ${propsWithGetter} }; })()))`)
476
+ const propsWithGetter = [...propEntries, `get children() { return ${cVar} === undefined ? (${cVar} = ${wrappedChild}) : ${cVar} }`].join(', ')
477
+ emitOut(`${call}((() => { let ${cVar}; return { ${propsWithGetter} }; })())`)
341
478
  return
342
479
  }
343
480
 
344
481
  if (hasChildren)
345
- propEntries.push(`children: ${use('raw')}(${childExpr})`)
482
+ propEntries.push(`children: ${wrappedChild}`)
346
483
 
347
484
  const propsObj = propEntries.length > 0 ? `{ ${propEntries.join(', ')} }` : '{}'
348
- parts.pushExpr(`${use('ssrChild')}(${call}(${propsObj}))`)
485
+ emitOut(`${call}(${propsObj})`)
349
486
  }
350
487
 
351
488
  function compileJsxToStringExpr(node: JSXElement | JSXFragment): string {
@@ -353,12 +490,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
353
490
  const stmts: string[] = []
354
491
  const parts = new StringParts()
355
492
 
356
- const flush = () => {
357
- if (!parts.isEmpty()) {
358
- stmts.push(`${bufVar} += ${parts.toExpr()};`)
359
- parts.clear()
360
- }
361
- }
493
+ const flush = () => flushStringParts(bufVar, parts, stmts)
362
494
 
363
495
  emitIntoBuffer(node, bufVar, parts, flush, s => stmts.push(s))
364
496
 
@@ -0,0 +1,151 @@
1
+ // Persists the last dev build error, child crash, and recent runtime errors under `.prunelle-dev/last-errors.json`
2
+ // so `prunelle mcp` (`dev_errors` tool) can inspect live dev failures without touching `dist/` or tracked files.
3
+
4
+ import type { ServerErrorInfo } from '../plugins/index'
5
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
6
+ import { dirname, join, resolve } from 'node:path'
7
+
8
+ export interface DevErrorEntry {
9
+ kind: 'build' | 'runtime' | 'crash'
10
+ timestamp: string
11
+ message: string
12
+ source?: string | undefined
13
+ method?: string | undefined
14
+ path?: string | undefined
15
+ }
16
+
17
+ export interface DevErrorLog {
18
+ updatedAt: string
19
+ buildError?: string | undefined
20
+ crashError?: string | undefined
21
+ runtimeErrors: DevErrorEntry[]
22
+ }
23
+
24
+ const MAX_RUNTIME_ERRORS = 20
25
+
26
+ function errorLogPath(root: string): string {
27
+ return join(resolve(root), '.prunelle-dev', 'last-errors.json')
28
+ }
29
+
30
+ function isDevErrorEntry(value: unknown): value is DevErrorEntry {
31
+ if (typeof value !== 'object' || value === null)
32
+ return false
33
+ const rec = value as Record<string, unknown>
34
+ return (rec.kind === 'build' || rec.kind === 'runtime' || rec.kind === 'crash')
35
+ && typeof rec.timestamp === 'string'
36
+ && typeof rec.message === 'string'
37
+ }
38
+
39
+ /** Reads `.prunelle-dev/last-errors.json` safely, returning `undefined` when missing or unreadable. */
40
+ export function readDevErrorLog(root: string): DevErrorLog | undefined {
41
+ const file = errorLogPath(root)
42
+ if (!existsSync(file))
43
+ return undefined
44
+ try {
45
+ const parsed = JSON.parse(readFileSync(file, 'utf8')) as unknown
46
+ if (typeof parsed !== 'object' || parsed === null)
47
+ return undefined
48
+ const rec = parsed as Record<string, unknown>
49
+ const updatedAt = typeof rec.updatedAt === 'string' ? rec.updatedAt : new Date(0).toISOString()
50
+ const buildError = typeof rec.buildError === 'string' && rec.buildError.length > 0 ? rec.buildError : undefined
51
+ const crashError = typeof rec.crashError === 'string' && rec.crashError.length > 0 ? rec.crashError : undefined
52
+ const runtimeErrors = Array.isArray(rec.runtimeErrors) ? rec.runtimeErrors.filter(isDevErrorEntry) : []
53
+ return {
54
+ updatedAt,
55
+ ...(buildError !== undefined ? { buildError } : {}),
56
+ ...(crashError !== undefined ? { crashError } : {}),
57
+ runtimeErrors,
58
+ }
59
+ }
60
+ catch {
61
+ return undefined
62
+ }
63
+ }
64
+
65
+ function writeDevErrorLog(root: string, log: DevErrorLog): void {
66
+ const file = errorLogPath(root)
67
+ const payload = JSON.stringify(log, null, 2)
68
+ try {
69
+ mkdirSync(dirname(file), { recursive: true })
70
+ const tmp = `${file}.${process.pid}.${Date.now()}.tmp`
71
+ writeFileSync(tmp, payload, 'utf8')
72
+ renameSync(tmp, file)
73
+ }
74
+ catch {
75
+ try {
76
+ mkdirSync(dirname(file), { recursive: true })
77
+ writeFileSync(file, payload, 'utf8')
78
+ }
79
+ catch {
80
+ return
81
+ }
82
+ }
83
+ }
84
+
85
+ function loadOrCreateLog(root: string, now: string): DevErrorLog {
86
+ const existing = readDevErrorLog(root)
87
+ if (existing !== undefined)
88
+ return { ...existing, updatedAt: now, runtimeErrors: [...existing.runtimeErrors] }
89
+ return { updatedAt: now, runtimeErrors: [] }
90
+ }
91
+
92
+ /** Records or clears the active dev build error (passing `undefined` clears it after a successful build). */
93
+ export function recordDevBuildError(root: string, message: string | undefined): void {
94
+ const now = new Date().toISOString()
95
+ const log = loadOrCreateLog(root, now)
96
+ if (message !== undefined && message.length > 0)
97
+ log.buildError = message
98
+ else
99
+ delete log.buildError
100
+ writeDevErrorLog(root, log)
101
+ }
102
+
103
+ /** Records or clears the active dev child crash message (passing `undefined` clears it once the child is ready). */
104
+ export function recordDevCrashError(root: string, message: string | undefined): void {
105
+ const now = new Date().toISOString()
106
+ const log = loadOrCreateLog(root, now)
107
+ if (message !== undefined && message.length > 0)
108
+ log.crashError = message
109
+ else
110
+ delete log.crashError
111
+ writeDevErrorLog(root, log)
112
+ }
113
+
114
+ /** Appends a runtime error to `.prunelle-dev/last-errors.json`, keeping the last 20 entries. */
115
+ export function recordDevRuntimeError(root: string, entry: Omit<DevErrorEntry, 'kind' | 'timestamp'>): void {
116
+ const now = new Date().toISOString()
117
+ const log = loadOrCreateLog(root, now)
118
+ log.runtimeErrors.push({
119
+ kind: 'runtime',
120
+ timestamp: now,
121
+ message: entry.message,
122
+ ...(entry.source !== undefined ? { source: entry.source } : {}),
123
+ ...(entry.method !== undefined ? { method: entry.method } : {}),
124
+ ...(entry.path !== undefined ? { path: entry.path } : {}),
125
+ })
126
+ if (log.runtimeErrors.length > MAX_RUNTIME_ERRORS)
127
+ log.runtimeErrors = log.runtimeErrors.slice(-MAX_RUNTIME_ERRORS)
128
+ writeDevErrorLog(root, log)
129
+ }
130
+
131
+ function safePathname(rawUrl: string): string {
132
+ try {
133
+ return new URL(rawUrl).pathname
134
+ }
135
+ catch {
136
+ return rawUrl
137
+ }
138
+ }
139
+
140
+ /** Builds an `errorSink` callback for `devServer` that records unhandled runtime errors into `.prunelle-dev/last-errors.json`. */
141
+ export function createDevRuntimeErrorSink(root: string): (info: ServerErrorInfo) => void {
142
+ return (info) => {
143
+ const message = info.error instanceof Error ? info.error.stack ?? info.error.message : String(info.error)
144
+ recordDevRuntimeError(root, {
145
+ message,
146
+ source: info.source,
147
+ method: info.request.method,
148
+ path: safePathname(info.request.url),
149
+ })
150
+ }
151
+ }