prunelle 0.1.1 → 0.5.1

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 (88) 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 +3 -2
  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 +11 -2
  11. package/src/build/compile.ts +2 -1
  12. package/src/build/ecoindex.ts +229 -0
  13. package/src/build/index.ts +121 -44
  14. package/src/build/manifest.ts +66 -5
  15. package/src/build/output.ts +2 -2
  16. package/src/build/plugin-host.ts +91 -33
  17. package/src/build/precompress.ts +15 -2
  18. package/src/build/prerender.ts +2 -2
  19. package/src/build/report.ts +23 -2
  20. package/src/build/resolve.ts +4 -3
  21. package/src/build/routes.ts +175 -10
  22. package/src/build/static.ts +71 -17
  23. package/src/build/status-pages.ts +127 -0
  24. package/src/build/style-bundles.ts +338 -0
  25. package/src/cli/check-forms.ts +654 -0
  26. package/src/cli/check-links.ts +619 -0
  27. package/src/cli/check.ts +52 -5
  28. package/src/cli/commands.ts +86 -4
  29. package/src/cli/docs.ts +402 -0
  30. package/src/cli/inspect.ts +31 -2
  31. package/src/cli/mcp-tools.ts +480 -0
  32. package/src/cli/mcp.ts +205 -0
  33. package/src/cli/new.ts +2 -2
  34. package/src/cli/render.ts +261 -0
  35. package/src/cli/upgrade-names.ts +73 -13
  36. package/src/cli/upgrade.ts +137 -16
  37. package/src/compiler/analyze.ts +17 -3
  38. package/src/compiler/cacheability.ts +592 -0
  39. package/src/compiler/compliance-rgaa.ts +502 -0
  40. package/src/compiler/compliance.ts +120 -221
  41. package/src/compiler/dev-source.ts +87 -0
  42. package/src/compiler/dom.ts +7 -7
  43. package/src/compiler/ssr.ts +135 -37
  44. package/src/dev/error-log.ts +151 -0
  45. package/src/dev/index.ts +60 -29
  46. package/src/dev/open-editor.ts +204 -0
  47. package/src/dev/reload.ts +5 -3
  48. package/src/dev/supervisor.ts +3 -0
  49. package/src/dom/action.ts +4 -1
  50. package/src/dom/island.ts +11 -10
  51. package/src/plugins/config.ts +4 -4
  52. package/src/plugins/index.ts +2 -2
  53. package/src/plugins/public.ts +5 -2
  54. package/src/plugins/services.ts +62 -0
  55. package/src/plugins/types.ts +32 -0
  56. package/src/server/action-protect.ts +198 -0
  57. package/src/server/action-registry.ts +1 -1
  58. package/src/server/action.ts +82 -27
  59. package/src/server/errors.ts +291 -62
  60. package/src/server/form-schema.ts +343 -0
  61. package/src/server/health.ts +244 -0
  62. package/src/server/http.ts +86 -19
  63. package/src/server/index.ts +158 -219
  64. package/src/server/param-matchers.ts +112 -0
  65. package/src/server/plugin-host.ts +40 -14
  66. package/src/server/public.ts +3 -3
  67. package/src/server/rate-limit.ts +58 -35
  68. package/src/server/request-body.ts +1 -1
  69. package/src/server/route-cache.ts +365 -0
  70. package/src/server/route-table.ts +302 -6
  71. package/src/server/router.ts +125 -40
  72. package/src/server/routing.ts +187 -61
  73. package/src/server/security.ts +208 -32
  74. package/src/server/serve-handlers.ts +21 -7
  75. package/src/ssr/context.ts +49 -0
  76. package/src/ssr/index.ts +120 -1
  77. package/src/test/browser.ts +6 -0
  78. package/src/test/index.ts +17 -3
  79. package/src/ts-plugin/diagnostics.ts +378 -0
  80. package/src/ts-plugin/fixes.ts +364 -0
  81. package/src/ts-plugin/index.ts +194 -0
  82. package/templates/_shared/AGENTS.md +2 -2
  83. package/templates/_shared/mcp.json +11 -0
  84. package/templates/_shared/src/routes/legal.tsx +5 -0
  85. package/templates/_shared/tsconfig.json +5 -0
  86. package/templates/blog/prunelle.config.ts +1 -1
  87. package/templates/blog/src/routes/index.tsx +4 -0
  88. 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 {
@@ -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,44 @@ 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
+
65
177
  export function compileSsr(filename: string, code: string, options: CompileSsrOptions = {}): CompileResult {
66
178
  const program = options.analysis?.program ?? parseTsx(filename, code)
67
179
  const analysis = options.analysis ?? analyzeModule(filename, code, program)
@@ -82,6 +194,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
82
194
  }
83
195
 
84
196
  const islands = options.islands
197
+ const devSrc = createDevSourceAttr(filename, code, options.devSourceRoot)
85
198
  const markersAt = markerTest(options.emitMarkers ?? options.isIsland ?? analysis.isInteractive)
86
199
  const jsxNodes = analysis.jsxNodes
87
200
  const exprContext = createExprContext(program, jsxNodes)
@@ -108,12 +221,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
108
221
  const bufVar = `_o${loopCounter++}`
109
222
  const stmts: string[] = []
110
223
  const parts = new StringParts()
111
- const flush = () => {
112
- if (!parts.isEmpty()) {
113
- stmts.push(`${bufVar} += ${parts.toExpr()};`)
114
- parts.clear()
115
- }
116
- }
224
+ const flush = () => flushStringParts(bufVar, parts, stmts)
117
225
  emitChildrenIntoBuffer(children, bufVar, parts, flush, s => stmts.push(s), rawTextTag, slotMarkers, inFragment)
118
226
  if (stmts.length === 0)
119
227
  return parts.toExpr()
@@ -125,7 +233,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
125
233
  }
126
234
 
127
235
  // 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 {
236
+ function emitIntoBuffer(node: JSXElement | JSXFragment, bufVar: string, parts: StringParts, flushParts: () => void, pushStmt: (stmt: string) => void, actionOverride?: { node: Node, ident: string }): void {
129
237
  if (node.type === 'JSXFragment') {
130
238
  emitChildrenIntoBuffer(node.children, bufVar, parts, flushParts, pushStmt, undefined, markersAt(node.start), true)
131
239
  return
@@ -137,21 +245,21 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
137
245
  return
138
246
  }
139
247
 
140
- parts.pushStatic(`<${tag}`)
248
+ if (tag === 'form' && actionOverride === undefined) {
249
+ const formAction = findDynamicFormAction(node)
250
+ if (formAction !== undefined) {
251
+ parts.pushExpr(emitActionFormExpr(formAction, directAwaitNodes.has(node), () => loopCounter++, use, compileSubExpression, (b, p, f, ps, ov) => emitIntoBuffer(node, b, p, f, ps, ov)))
252
+ return
253
+ }
254
+ }
255
+
256
+ parts.pushStatic(`<${tag}${devSrc(node, tag)}`)
141
257
  const isTextarea = tag === 'textarea'
142
258
  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
-
259
+ const compileAttrExpr = actionOverride !== undefined ? (n: Node) => (n === actionOverride.node ? actionOverride.ident : compileSubExpression(n)) : compileSubExpression
260
+ const { innerHtmlExpr, textareaValue, nextSelectValue } = emitSsrElementAttrs({ node, tag, parts, activeSelectValue, flushParts, pushStmt, nextId: () => loopCounter++, use, compileSubExpression: compileAttrExpr })
261
+ if (FORM_CONTROL_TAGS.has(tag))
262
+ emitFormControlAttrs(node, tag as 'input' | 'select' | 'textarea', parts, use, compileSubExpression)
155
263
  parts.pushStatic('>')
156
264
  if (VOID_ELEMENTS.has(tag))
157
265
  return
@@ -161,28 +269,23 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
161
269
  activeSelectValue = nextSelectValue
162
270
 
163
271
  try {
164
- if (innerHtmlExpr !== undefined) {
272
+ if (innerHtmlExpr !== undefined)
165
273
  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
- }
274
+ else if (isTextarea && textareaValue !== undefined && filterMeaningfulChildren(node.children).length === 0)
275
+ textareaValue.staticText !== undefined ? parts.pushStatic(escapeStaticText(textareaValue.staticText)) : textareaValue.expr !== undefined && parts.pushExpr(`${use('esc')}(${textareaValue.expr})`)
173
276
  else if (tag === 'style') {
174
277
  const styleExpr = compileChildrenListToStringExpr(node.children, false, false, 'style')
175
278
  if (styleExpr !== '""')
176
279
  parts.pushExpr(`${use('ssrStyleBlock')}(${styleExpr})`)
177
280
  }
178
- else {
281
+ else
179
282
  emitChildrenIntoBuffer(node.children, bufVar, parts, flushParts, pushStmt, RAW_TEXT_ELEMENTS.has(tag) ? tag as 'style' | 'script' : undefined)
180
- }
181
283
  }
182
284
  finally {
183
285
  activeSelectValue = prevSelectValue
184
286
  }
185
- parts.pushStatic(`</${tag}>`)
287
+ if (actionOverride === undefined)
288
+ parts.pushStatic(`</${tag}>`)
186
289
  }
187
290
 
188
291
  function emitChildrenIntoBuffer(
@@ -353,12 +456,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
353
456
  const stmts: string[] = []
354
457
  const parts = new StringParts()
355
458
 
356
- const flush = () => {
357
- if (!parts.isEmpty()) {
358
- stmts.push(`${bufVar} += ${parts.toExpr()};`)
359
- parts.clear()
360
- }
361
- }
459
+ const flush = () => flushStringParts(bufVar, parts, stmts)
362
460
 
363
461
  emitIntoBuffer(node, bufVar, parts, flush, s => stmts.push(s))
364
462
 
@@ -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
+ }
package/src/dev/index.ts CHANGED
@@ -13,7 +13,9 @@ import { build, createBuildCache } from '../build/index'
13
13
  import { loadConfig, resolveServerConfig } from '../plugins/index'
14
14
  import { DEFAULT_MAX_REQUEST_BODY_SIZE } from '../server/http'
15
15
  import { createServer } from '../server/index'
16
+ import { createDevRuntimeErrorSink, recordDevBuildError } from './error-log'
16
17
  import { createModuleStore } from './modules'
18
+ import { handleOpenEditorRequest } from './open-editor'
17
19
  import { DEV_CLIENT_IP_HEADER } from './protocol'
18
20
  import { createRebuildQueue } from './queue'
19
21
  import { buildErrorResponse, createReloadHub, makeDevReloadAssets, withReloadScript } from './reload'
@@ -37,6 +39,55 @@ export interface DevServerOptions {
37
39
 
38
40
  const errorText = (err: unknown): string => err instanceof Error ? err.stack ?? err.message : String(err)
39
41
 
42
+ function startDevHttpServer(
43
+ options: DevServerOptions,
44
+ maxRequestBodySize: number,
45
+ configPort: number | undefined,
46
+ onFetch: (request: Request, srv: Server<undefined>) => Promise<Response>,
47
+ ): { server: Server<undefined>, url: string } {
48
+ const hostname = options.hostname ?? '127.0.0.1'
49
+ const serveOptions = { maxRequestBodySize, fetch: onFetch }
50
+ const server = options.unix !== undefined
51
+ ? Bun.serve({ ...serveOptions, unix: options.unix })
52
+ : Bun.serve({ ...serveOptions, port: options.port ?? configPort ?? 3000, hostname, idleTimeout: 30 })
53
+ // `0.0.0.0` is printed as the loopback address a browser on this machine opens.
54
+ const url = options.unix !== undefined ? `unix:${options.unix}` : `http://${hostname === '0.0.0.0' ? '127.0.0.1' : hostname}:${server.port}`
55
+ if (options.unix === undefined)
56
+ console.log(`[prunelle dev] listening on ${url}`)
57
+ return { server, url }
58
+ }
59
+
60
+ async function handleAppFetch(
61
+ request: Request,
62
+ srv: Server<undefined>,
63
+ state: {
64
+ root: string
65
+ unix: string | undefined
66
+ hub: ReturnType<typeof createReloadHub> | undefined
67
+ reloadAssets: ReturnType<typeof makeDevReloadAssets>
68
+ lastError: string | undefined
69
+ app: PrunelleApp | undefined
70
+ },
71
+ ): Promise<Response> {
72
+ const { pathname } = new URL(request.url)
73
+ if (state.hub !== undefined && pathname === state.reloadAssets.eventsPath) {
74
+ srv.timeout(request, 0)
75
+ return state.hub.events(request)
76
+ }
77
+ if (pathname === state.reloadAssets.openEditorPath)
78
+ return handleOpenEditorRequest(request, state.root)
79
+ if (state.lastError !== undefined)
80
+ return buildErrorResponse(request, state.lastError, state.reloadAssets.script)
81
+
82
+ const remoteIp = state.unix !== undefined ? request.headers.get(DEV_CLIENT_IP_HEADER) ?? undefined : srv.requestIP(request)?.address
83
+ const res = await state.app!.handle(request, remoteIp)
84
+ const ct = res.headers.get('content-type') ?? ''
85
+ const isStreamedHtml = ct.includes('text/html') && request.method !== 'HEAD' && res.body !== null && !res.headers.has('content-length')
86
+ if (ct.includes('text/event-stream') || isStreamedHtml)
87
+ srv.timeout(request, 0)
88
+ return withReloadScript(request, res, state.reloadAssets)
89
+ }
90
+
40
91
  export async function devServer(options: DevServerOptions): Promise<{
41
92
  url: string
42
93
  assetPrefix: string
@@ -65,7 +116,7 @@ export async function devServer(options: DevServerOptions): Promise<{
65
116
  routesDir: options.routesDir,
66
117
  schedule: kind => kind === 'config' && recycle !== undefined ? recycle('config') : queue.schedule(kind),
67
118
  })
68
- const serverOptions = { root, dev: true, compress: false, ...(options.maxRequestBodySize !== undefined ? { maxRequestBodySize: options.maxRequestBodySize } : {}) }
119
+ const serverOptions = { root, dev: true, compress: false, errorSink: createDevRuntimeErrorSink(root), ...(options.maxRequestBodySize !== undefined ? { maxRequestBodySize: options.maxRequestBodySize } : {}) }
69
120
 
70
121
  let buildNum = 0
71
122
  let current: { app: PrunelleApp, outDir: string } | undefined
@@ -119,6 +170,7 @@ export async function devServer(options: DevServerOptions): Promise<{
119
170
  return
120
171
  }
121
172
  lastError = undefined
173
+ recordDevBuildError(root, undefined)
122
174
  watchers.syncBuild(buildCache.watchedFiles, manifest.publicFiles)
123
175
  if (n > 2)
124
176
  rmSync(join(devRoot, `b${n - 2}`), { recursive: true, force: true })
@@ -131,6 +183,7 @@ export async function devServer(options: DevServerOptions): Promise<{
131
183
  if (stopped)
132
184
  return
133
185
  lastError = errorText(err)
186
+ recordDevBuildError(root, lastError)
134
187
  console.error(`[prunelle dev] build error:\n${lastError}`)
135
188
  // Push reload over SSE so open browser tabs immediately display the error overlay
136
189
  broadcast('reload')
@@ -150,34 +203,12 @@ export async function devServer(options: DevServerOptions): Promise<{
150
203
  }
151
204
 
152
205
  const runtimeCfg = resolveServerConfig(initialCfg, { maxRequestBodySize: options.maxRequestBodySize })
153
- const hostname = options.hostname ?? '127.0.0.1'
154
- const serveOptions = {
155
- maxRequestBodySize: runtimeCfg.maxRequestBodySize ?? DEFAULT_MAX_REQUEST_BODY_SIZE,
156
- async fetch(request: Request, srv: Server<undefined>): Promise<Response> {
157
- if (hub !== undefined && new URL(request.url).pathname === reloadAssets.eventsPath) {
158
- srv.timeout(request, 0)
159
- return hub.events(request)
160
- }
161
- if (lastError !== undefined)
162
- return buildErrorResponse(request, lastError, reloadAssets.script)
163
-
164
- const remoteIp = options.unix !== undefined ? request.headers.get(DEV_CLIENT_IP_HEADER) ?? undefined : srv.requestIP(request)?.address
165
- const res = await current!.app.handle(request, remoteIp)
166
- const ct = res.headers.get('content-type') ?? ''
167
- const isStreamedHtml = ct.includes('text/html') && request.method !== 'HEAD' && res.body !== null && !res.headers.has('content-length')
168
- if (ct.includes('text/event-stream') || isStreamedHtml)
169
- srv.timeout(request, 0)
170
- return withReloadScript(request, res, reloadAssets)
171
- },
172
- }
173
- const server = options.unix !== undefined
174
- ? Bun.serve({ ...serveOptions, unix: options.unix })
175
- : Bun.serve({ ...serveOptions, port: options.port ?? initialCfg.port ?? 3000, hostname, idleTimeout: 30 })
176
-
177
- // `0.0.0.0` is printed as the loopback address a browser on this machine opens.
178
- const url = options.unix !== undefined ? `unix:${options.unix}` : `http://${hostname === '0.0.0.0' ? '127.0.0.1' : hostname}:${server.port}`
179
- if (options.unix === undefined)
180
- console.log(`[prunelle dev] listening on ${url}`)
206
+ const { server, url } = startDevHttpServer(
207
+ options,
208
+ runtimeCfg.maxRequestBodySize ?? DEFAULT_MAX_REQUEST_BODY_SIZE,
209
+ initialCfg.port,
210
+ (request, srv) => handleAppFetch(request, srv, { root, unix: options.unix, hub, reloadAssets, lastError, app: current?.app }),
211
+ )
181
212
  let stopPromise: Promise<void> | undefined
182
213
 
183
214
  return {