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
@@ -10,13 +10,13 @@ import type {
10
10
  import type { ModuleAnalysis } from './analyze'
11
11
  import type { SelectValueBinding } from './ssr-helpers'
12
12
  import type { PrunelleTagEmitter } from './ssr-prunelle-tags'
13
- import { analyzeModule, parseTsx } from './analyze'
13
+ import { analyzeModule, getExprContext, 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 {
18
19
  containsJsx,
19
- createExprContext,
20
20
  decodeHtmlEntities,
21
21
  escapeRawText,
22
22
  escapeStaticText,
@@ -24,6 +24,7 @@ import {
24
24
  isComponentTag,
25
25
  isJsxNode,
26
26
  jsxTagName,
27
+ matchJsxMapCall,
27
28
  planChildSlots,
28
29
  RAW_TEXT_ELEMENTS,
29
30
  resolvePrunelleTag,
@@ -34,11 +35,86 @@ import {
34
35
  emitSsrElementAttrs,
35
36
  precomputeSsrSubtreeFlags,
36
37
  serializeComponentProps,
38
+ staticLiteralOrTemplate,
37
39
  StringParts,
38
40
  } from './ssr-helpers'
39
41
  import { emitIsland } from './ssr-island'
40
42
  import { emitCatch, emitSuspense } from './ssr-prunelle-tags'
41
43
 
44
+ const FORM_CONTROL_TAGS = new Set(['input', 'select', 'textarea'])
45
+ const FORM_ATTR_BITS: Record<string, number> = {
46
+ type: 1,
47
+ required: 2,
48
+ minlength: 4,
49
+ maxlength: 8,
50
+ min: 16,
51
+ max: 32,
52
+ step: 64,
53
+ pattern: 128,
54
+ }
55
+
56
+ function findDynamicFormAction(node: JSXElement): Node | undefined {
57
+ for (const attr of node.openingElement.attributes) {
58
+ if (attr.type !== 'JSXAttribute' || jsxTagName(attr.name) !== 'action')
59
+ continue
60
+ if (attr.value?.type !== 'JSXExpressionContainer' || attr.value.expression.type === 'JSXEmptyExpression')
61
+ return undefined
62
+ const expr = attr.value.expression
63
+ if (staticLiteralOrTemplate(expr).ok)
64
+ return undefined
65
+ if (expr.type === 'ConditionalExpression' && staticLiteralOrTemplate(expr.consequent).ok && staticLiteralOrTemplate(expr.alternate).ok)
66
+ return undefined
67
+ return expr
68
+ }
69
+ return undefined
70
+ }
71
+
72
+ function emitFormControlAttrs(
73
+ node: JSXElement,
74
+ tag: 'input' | 'select' | 'textarea',
75
+ parts: StringParts,
76
+ use: (name: string) => string,
77
+ compileSubExpression: (node: Node) => string,
78
+ ): void {
79
+ const attrs = node.openingElement.attributes
80
+ if (attrs.some(a => a.type === 'JSXSpreadAttribute'))
81
+ return
82
+ let nameExpr: string | undefined
83
+ let typeExpr: string | undefined
84
+ let present = 0
85
+ for (const attr of attrs) {
86
+ if (attr.type !== 'JSXAttribute')
87
+ continue
88
+ const attrName = jsxTagName(attr.name).toLowerCase()
89
+ const bit = FORM_ATTR_BITS[attrName]
90
+ if (bit !== undefined)
91
+ present |= bit
92
+ if (attrName === 'name') {
93
+ if (attr.value?.type === 'Literal' && typeof attr.value.value === 'string') {
94
+ nameExpr = JSON.stringify(attr.value.value)
95
+ }
96
+ else if (attr.value?.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
97
+ const lit = staticLiteralOrTemplate(attr.value.expression)
98
+ nameExpr = lit.ok && typeof lit.value === 'string' ? JSON.stringify(lit.value) : compileSubExpression(attr.value.expression)
99
+ }
100
+ }
101
+ else if (tag === 'input' && attrName === 'type') {
102
+ if (attr.value?.type === 'Literal' && typeof attr.value.value === 'string') {
103
+ typeExpr = JSON.stringify(attr.value.value.toLowerCase())
104
+ }
105
+ else if (attr.value?.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
106
+ const lit = staticLiteralOrTemplate(attr.value.expression)
107
+ if (lit.ok && typeof lit.value === 'string')
108
+ typeExpr = JSON.stringify(lit.value.toLowerCase())
109
+ }
110
+ }
111
+ }
112
+ if (nameExpr === undefined)
113
+ return
114
+ const typeArg = typeExpr !== undefined ? `, ${typeExpr}` : ''
115
+ parts.pushExpr(`${use('ssrFormAttrs')}(${JSON.stringify(tag)}, ${nameExpr}, ${present}${typeArg})`)
116
+ }
117
+
42
118
  export interface IslandBinding {
43
119
  id: string
44
120
  chunk: string
@@ -51,6 +127,8 @@ export interface CompileSsrOptions {
51
127
  /** Hydration markers everywhere, nowhere, or only inside these source spans. */
52
128
  emitMarkers?: boolean | readonly (readonly [number, number])[] | undefined
53
129
  analysis?: ModuleAnalysis | undefined
130
+ /** Project root for dev-only `data-pru-src="file:line:col"` attributes; omit in production. */
131
+ devSourceRoot?: string | undefined
54
132
  }
55
133
 
56
134
  export interface CompileResult {
@@ -58,10 +136,94 @@ export interface CompileResult {
58
136
  analysis: ModuleAnalysis
59
137
  }
60
138
 
139
+ function emitActionFormExpr(
140
+ formAction: Node,
141
+ isAsyncForm: boolean,
142
+ nextId: () => number,
143
+ use: (name: string) => string,
144
+ compileSubExpression: (node: Node) => string,
145
+ emitBody: (bufVar: string, parts: StringParts, flush: () => void, pushStmt: (stmt: string) => void, override: { node: Node, ident: string }) => void,
146
+ ): string {
147
+ const faVar = `_fa${nextId()}`
148
+ const innerBuf = `_o${nextId()}`
149
+ const innerStmts: string[] = []
150
+ const innerParts = new StringParts()
151
+ const flushInner = () => {
152
+ if (!innerParts.isEmpty()) {
153
+ innerStmts.push(`${innerBuf} += ${innerParts.toExpr()};`)
154
+ innerParts.clear()
155
+ }
156
+ }
157
+ emitBody(innerBuf, innerParts, flushInner, s => innerStmts.push(s), { node: formAction, ident: faVar })
158
+ if (innerStmts.length > 0)
159
+ flushInner()
160
+ const body = innerStmts.length === 0 ? innerParts.toExpr() : `{ let ${innerBuf} = ""; ${innerStmts.join(' ')} return ${innerBuf}; }`
161
+ return isAsyncForm
162
+ ? `await ${use('ssrFormAsync')}(${compileSubExpression(formAction)}, async (${faVar}) => ${body})`
163
+ : `${use('ssrForm')}(${compileSubExpression(formAction)}, (${faVar}) => ${body})`
164
+ }
165
+
61
166
  function markerTest(markers: NonNullable<CompileSsrOptions['emitMarkers']>): (offset: number) => boolean {
62
167
  return typeof markers === 'boolean' ? () => markers : offset => markers.some(([start, end]) => offset >= start && offset < end)
63
168
  }
64
169
 
170
+ function flushStringParts(bufVar: string, parts: StringParts, stmts: string[]): void {
171
+ if (!parts.isEmpty()) {
172
+ stmts.push(`${bufVar} += ${parts.toExpr()};`)
173
+ parts.clear()
174
+ }
175
+ }
176
+
177
+ function isSingleLoopChild(meaningful: readonly JSXChild[], jsxNodes: WeakSet<Node>): boolean {
178
+ return meaningful.length === 1
179
+ && meaningful[0]!.type === 'JSXExpressionContainer'
180
+ && meaningful[0]!.expression.type !== 'JSXEmptyExpression'
181
+ && matchJsxMapCall(meaningful[0]!.expression, jsxNodes) !== undefined
182
+ }
183
+
184
+ function compileSsrSubExpression(
185
+ code: string,
186
+ node: Node,
187
+ jsxNodes: WeakSet<Node>,
188
+ mark: (offset: number) => string,
189
+ compileRootJsx: (n: JSXElement | JSXFragment) => string,
190
+ ): string {
191
+ if (!containsJsx(node, jsxNodes))
192
+ return mark(node.start) + code.slice(node.start, node.end)
193
+ const sub = new SourceEditor(code.slice(node.start, node.end))
194
+ const offset = node.start
195
+ walk(node, (child) => {
196
+ if (isJsxNode(child)) {
197
+ sub.replace(child.start - offset, child.end - offset, compileRootJsx(child) + mark(child.end))
198
+ return false
199
+ }
200
+ return undefined
201
+ })
202
+ return mark(node.start) + sub.toString()
203
+ }
204
+
205
+ function compileSsrExprAsString(
206
+ expr: Node,
207
+ use: (name: string) => string,
208
+ compileSubExpression: (node: Node) => string,
209
+ compileJsxToStringExpr: (node: JSXElement | JSXFragment) => string,
210
+ ): string {
211
+ if (isJsxNode(expr))
212
+ return compileJsxToStringExpr(expr)
213
+ if (expr.type === 'LogicalExpression' && expr.operator === '&&') {
214
+ const right = unwrapParens(expr.right)
215
+ if (isJsxNode(right))
216
+ return `((${compileSubExpression(expr.left)}) ? (${compileJsxToStringExpr(right)}) : "")`
217
+ }
218
+ if (expr.type === 'ConditionalExpression') {
219
+ const consNode = unwrapParens(expr.consequent)
220
+ const altNode = unwrapParens(expr.alternate)
221
+ if (isJsxNode(consNode) || isJsxNode(altNode))
222
+ return `((${compileSubExpression(expr.test)}) ? (${compileSsrExprAsString(consNode, use, compileSubExpression, compileJsxToStringExpr)}) : (${compileSsrExprAsString(altNode, use, compileSubExpression, compileJsxToStringExpr)}))`
223
+ }
224
+ return `${use('esc')}(${compileSubExpression(expr)})`
225
+ }
226
+
65
227
  export function compileSsr(filename: string, code: string, options: CompileSsrOptions = {}): CompileResult {
66
228
  const program = options.analysis?.program ?? parseTsx(filename, code)
67
229
  const analysis = options.analysis ?? analyzeModule(filename, code, program)
@@ -82,38 +244,24 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
82
244
  }
83
245
 
84
246
  const islands = options.islands
247
+ const devSrc = createDevSourceAttr(filename, code, options.devSourceRoot)
85
248
  const markersAt = markerTest(options.emitMarkers ?? options.isIsland ?? analysis.isInteractive)
86
249
  const jsxNodes = analysis.jsxNodes
87
- const exprContext = createExprContext(program, jsxNodes)
250
+ const exprContext = getExprContext(analysis)
88
251
  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()
252
+ const compileSubExpression = (node: Node): string => compileSsrSubExpression(code, node, jsxNodes, mark, compileRootJsx)
253
+ const compileComponentRaw = (node: JSXElement, tag: string): string => {
254
+ let out = ''
255
+ emitComponent(node, tag, new StringParts(), (e) => { out = e })
256
+ return out
105
257
  }
258
+ const prunelleTags: PrunelleTagEmitter = { use, compileSubExpression, compileChildren: compileChildrenListToStringExpr, compileJsx: compileJsxToStringExpr, compileComponentRaw, markersAt, directAwaitNodes, jsxNodes }
106
259
 
107
260
  function compileChildrenListToStringExpr(children: readonly JSXChild[], slotMarkers = markersAt(children[0]?.start ?? 0), inFragment = false, rawTextTag?: 'style' | 'script'): string {
108
261
  const bufVar = `_o${loopCounter++}`
109
262
  const stmts: string[] = []
110
263
  const parts = new StringParts()
111
- const flush = () => {
112
- if (!parts.isEmpty()) {
113
- stmts.push(`${bufVar} += ${parts.toExpr()};`)
114
- parts.clear()
115
- }
116
- }
264
+ const flush = () => flushStringParts(bufVar, parts, stmts)
117
265
  emitChildrenIntoBuffer(children, bufVar, parts, flush, s => stmts.push(s), rawTextTag, slotMarkers, inFragment)
118
266
  if (stmts.length === 0)
119
267
  return parts.toExpr()
@@ -125,7 +273,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
125
273
  }
126
274
 
127
275
  // 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 {
276
+ function emitIntoBuffer(node: JSXElement | JSXFragment, bufVar: string, parts: StringParts, flushParts: () => void, pushStmt: (stmt: string) => void, actionOverride?: { node: Node, ident: string }): void {
129
277
  if (node.type === 'JSXFragment') {
130
278
  emitChildrenIntoBuffer(node.children, bufVar, parts, flushParts, pushStmt, undefined, markersAt(node.start), true)
131
279
  return
@@ -137,21 +285,21 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
137
285
  return
138
286
  }
139
287
 
140
- parts.pushStatic(`<${tag}`)
288
+ if (tag === 'form' && actionOverride === undefined) {
289
+ const formAction = findDynamicFormAction(node)
290
+ if (formAction !== undefined) {
291
+ parts.pushExpr(emitActionFormExpr(formAction, directAwaitNodes.has(node), () => loopCounter++, use, compileSubExpression, (b, p, f, ps, ov) => emitIntoBuffer(node, b, p, f, ps, ov)))
292
+ return
293
+ }
294
+ }
295
+
296
+ parts.pushStatic(`<${tag}${devSrc(node, tag)}`)
141
297
  const isTextarea = tag === 'textarea'
142
298
  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
-
299
+ const compileAttrExpr = actionOverride !== undefined ? (n: Node) => (n === actionOverride.node ? actionOverride.ident : compileSubExpression(n)) : compileSubExpression
300
+ const { innerHtmlExpr, textareaValue, nextSelectValue } = emitSsrElementAttrs({ node, tag, parts, activeSelectValue, flushParts, pushStmt, nextId: () => loopCounter++, use, compileSubExpression: compileAttrExpr })
301
+ if (FORM_CONTROL_TAGS.has(tag))
302
+ emitFormControlAttrs(node, tag as 'input' | 'select' | 'textarea', parts, use, compileSubExpression)
155
303
  parts.pushStatic('>')
156
304
  if (VOID_ELEMENTS.has(tag))
157
305
  return
@@ -161,28 +309,23 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
161
309
  activeSelectValue = nextSelectValue
162
310
 
163
311
  try {
164
- if (innerHtmlExpr !== undefined) {
312
+ if (innerHtmlExpr !== undefined)
165
313
  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
- }
314
+ else if (isTextarea && textareaValue !== undefined && filterMeaningfulChildren(node.children).length === 0)
315
+ textareaValue.staticText !== undefined ? parts.pushStatic(escapeStaticText(textareaValue.staticText)) : textareaValue.expr !== undefined && parts.pushExpr(`${use('esc')}(${textareaValue.expr})`)
173
316
  else if (tag === 'style') {
174
317
  const styleExpr = compileChildrenListToStringExpr(node.children, false, false, 'style')
175
318
  if (styleExpr !== '""')
176
319
  parts.pushExpr(`${use('ssrStyleBlock')}(${styleExpr})`)
177
320
  }
178
- else {
321
+ else
179
322
  emitChildrenIntoBuffer(node.children, bufVar, parts, flushParts, pushStmt, RAW_TEXT_ELEMENTS.has(tag) ? tag as 'style' | 'script' : undefined)
180
- }
181
323
  }
182
324
  finally {
183
325
  activeSelectValue = prevSelectValue
184
326
  }
185
- parts.pushStatic(`</${tag}>`)
327
+ if (actionOverride === undefined)
328
+ parts.pushStatic(`</${tag}>`)
186
329
  }
187
330
 
188
331
  function emitChildrenIntoBuffer(
@@ -244,12 +387,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
244
387
  const idxVar = idxParam ?? `_i${n}`
245
388
  const innerStmts: string[] = []
246
389
  const innerParts = new StringParts()
247
- const flushInner = () => {
248
- if (!innerParts.isEmpty()) {
249
- innerStmts.push(`${bufVar} += ${innerParts.toExpr()};`)
250
- innerParts.clear()
251
- }
252
- }
390
+ const flushInner = () => flushStringParts(bufVar, innerParts, innerStmts)
253
391
  emitIntoBuffer(match.body as JSXElement | JSXFragment, bufVar, innerParts, flushInner, s => innerStmts.push(s))
254
392
  flushInner()
255
393
 
@@ -260,7 +398,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
260
398
  }
261
399
  else if (match.isJsxBody) {
262
400
  const target = compileSubExpression(match.target)
263
- const params = match.params.map(p => code.slice(p.start, p.end)).join(', ')
401
+ const params = match.params.map(p => compileSubExpression(p)).join(', ')
264
402
  parts.pushExpr(`${use('ssrLoop')}(${target}, (${params}) => ${compileJsxToStringExpr(match.body as JSXElement | JSXFragment)})`)
265
403
  }
266
404
  else {
@@ -287,24 +425,9 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
287
425
  }
288
426
  }
289
427
 
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
- }
428
+ const compileExpressionAsString = (expr: Node): string => compileSsrExprAsString(expr, use, compileSubExpression, compileJsxToStringExpr)
306
429
 
307
- function emitComponent(node: JSXElement, tag: string, parts: StringParts): void {
430
+ function emitComponent(node: JSXElement, tag: string, parts: StringParts, onRaw?: (expr: string) => void): void {
308
431
  const { propEntries, allStaticProps, staticPropsObj, hydrateExpr, staticHydrate } = serializeComponentProps(node.openingElement.attributes, compileSubExpression)
309
432
  const childNodes = node.children
310
433
  const meaningfulChildren = filterMeaningfulChildren(childNodes)
@@ -314,7 +437,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
314
437
 
315
438
  const prunelleTag = resolvePrunelleTag(tag, analysis.imports)
316
439
  if (prunelleTag === 'Suspense' || prunelleTag === 'Catch') {
317
- ;(prunelleTag === 'Suspense' ? emitSuspense : emitCatch)(prunelleTags, node, tag, propEntries, parts)
440
+ ;(prunelleTag === 'Suspense' ? emitSuspense : emitCatch)(prunelleTags, node, tag, propEntries, parts, onRaw)
318
441
  return
319
442
  }
320
443
 
@@ -324,28 +447,41 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
324
447
 
325
448
  const childrenHaveAwait = hasChildren && childNodes.some(c => directAwaitNodes.has(c))
326
449
  const childMarkers = islandInfo === undefined && markersAt(node.start)
327
- const childExpr = hasChildren ? compileChildrenListToStringExpr(childNodes, childMarkers, childMarkers && meaningfulChildren.length > 1) : '""'
450
+ const onlyComp = onRaw !== undefined && islandInfo === undefined && meaningfulChildren.length === 1 && meaningfulChildren[0]!.type === 'JSXElement' && isComponentTag(jsxTagName(meaningfulChildren[0]!.openingElement.name)) ? meaningfulChildren[0]! : undefined
451
+ const childExpr = onlyComp !== undefined
452
+ ? compileComponentRaw(onlyComp, jsxTagName(onlyComp.openingElement.name))
453
+ : hasChildren ? compileChildrenListToStringExpr(childNodes, childMarkers, childMarkers && (meaningfulChildren.length > 1 || isSingleLoopChild(meaningfulChildren, jsxNodes))) : '""'
328
454
 
329
455
  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)
456
+ const target = onRaw !== undefined ? new StringParts() : parts
457
+ emitIsland({ use, nextId: () => loopCounter++, markersAt }, { island: islandInfo, tag, call, start: node.start, propEntries, allStaticProps, staticPropsObj, hydrateExpr, staticHydrate, hasChildren, childExpr, childrenHaveAwait }, target)
458
+ if (onRaw !== undefined)
459
+ onRaw(`${use('raw')}(${target.toExpr()})`)
331
460
  return
332
461
  }
333
462
 
463
+ const emitOut = (expr: string): void => {
464
+ if (onRaw !== undefined)
465
+ onRaw(expr)
466
+ else
467
+ parts.pushExpr(`${use('ssrChild')}(${expr})`)
468
+ }
469
+ const wrappedChild = onlyComp !== undefined ? childExpr : `${use('raw')}(${childExpr})`
334
470
  const childrenHaveDynamic = hasChildren && childNodes.some(c => dynamicChildNodes.has(c))
335
471
 
336
472
  // Lazy memoized getter for non-async dynamic/component children so Providers & context components run before their children!
337
473
  if (childrenHaveDynamic && !childrenHaveAwait) {
338
474
  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} }; })()))`)
475
+ const propsWithGetter = [...propEntries, `get children() { return ${cVar} === undefined ? (${cVar} = ${wrappedChild}) : ${cVar} }`].join(', ')
476
+ emitOut(`${call}((() => { let ${cVar}; return { ${propsWithGetter} }; })())`)
341
477
  return
342
478
  }
343
479
 
344
480
  if (hasChildren)
345
- propEntries.push(`children: ${use('raw')}(${childExpr})`)
481
+ propEntries.push(`children: ${wrappedChild}`)
346
482
 
347
483
  const propsObj = propEntries.length > 0 ? `{ ${propEntries.join(', ')} }` : '{}'
348
- parts.pushExpr(`${use('ssrChild')}(${call}(${propsObj}))`)
484
+ emitOut(`${call}(${propsObj})`)
349
485
  }
350
486
 
351
487
  function compileJsxToStringExpr(node: JSXElement | JSXFragment): string {
@@ -353,12 +489,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
353
489
  const stmts: string[] = []
354
490
  const parts = new StringParts()
355
491
 
356
- const flush = () => {
357
- if (!parts.isEmpty()) {
358
- stmts.push(`${bufVar} += ${parts.toExpr()};`)
359
- parts.clear()
360
- }
361
- }
492
+ const flush = () => flushStringParts(bufVar, parts, stmts)
362
493
 
363
494
  emitIntoBuffer(node, bufVar, parts, flush, s => stmts.push(s))
364
495
 
@@ -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
+ }