prunelle 0.1.1 → 0.5.3

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 +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 +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 +62 -0
  75. package/src/plugins/types.ts +32 -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 +128 -31
  90. package/src/server/index.ts +230 -260
  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
package/src/dev/index.ts CHANGED
@@ -6,14 +6,16 @@ import type { BuildCacheStats } from '../build/graph'
6
6
  import type { PrunelleApp } from '../server/index'
7
7
  import type { RecycleReason } from './protocol'
8
8
  import type { PendingBuild } from './queue'
9
- import { rmSync } from 'node:fs'
9
+ import { existsSync, readdirSync, rmSync } from 'node:fs'
10
10
  import { join, resolve } from 'node:path'
11
11
  import { clearBuildCache } from '../build/graph'
12
12
  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,65 @@ export interface DevServerOptions {
37
39
 
38
40
  const errorText = (err: unknown): string => err instanceof Error ? err.stack ?? err.message : String(err)
39
41
 
42
+ /** Removes stale dev build folders (`b*`, `server/`) while keeping `.prunelle-dev/last-errors.json` intact across child recycles. */
43
+ function cleanDevArtifacts(devRoot: string): void {
44
+ if (!existsSync(devRoot))
45
+ return
46
+ for (const entry of readdirSync(devRoot)) {
47
+ if (entry !== 'last-errors.json')
48
+ rmSync(join(devRoot, entry), { recursive: true, force: true })
49
+ }
50
+ }
51
+
52
+ function startDevHttpServer(
53
+ options: DevServerOptions,
54
+ maxRequestBodySize: number,
55
+ configPort: number | undefined,
56
+ onFetch: (request: Request, srv: Server<undefined>) => Promise<Response>,
57
+ ): { server: Server<undefined>, url: string } {
58
+ const hostname = options.hostname ?? '127.0.0.1'
59
+ const serveOptions = { maxRequestBodySize, fetch: onFetch }
60
+ const server = options.unix !== undefined
61
+ ? Bun.serve({ ...serveOptions, unix: options.unix })
62
+ : Bun.serve({ ...serveOptions, port: options.port ?? configPort ?? 3000, hostname, idleTimeout: 30 })
63
+ // `0.0.0.0` is printed as the loopback address a browser on this machine opens.
64
+ const url = options.unix !== undefined ? `unix:${options.unix}` : `http://${hostname === '0.0.0.0' ? '127.0.0.1' : hostname}:${server.port}`
65
+ if (options.unix === undefined)
66
+ console.log(`[prunelle dev] listening on ${url}`)
67
+ return { server, url }
68
+ }
69
+
70
+ async function handleAppFetch(
71
+ request: Request,
72
+ srv: Server<undefined>,
73
+ state: {
74
+ root: string
75
+ unix: string | undefined
76
+ hub: ReturnType<typeof createReloadHub> | undefined
77
+ reloadAssets: ReturnType<typeof makeDevReloadAssets>
78
+ lastError: string | undefined
79
+ app: PrunelleApp | undefined
80
+ },
81
+ ): Promise<Response> {
82
+ const { pathname } = new URL(request.url)
83
+ if (state.hub !== undefined && pathname === state.reloadAssets.eventsPath) {
84
+ srv.timeout(request, 0)
85
+ return state.hub.events(request)
86
+ }
87
+ if (pathname === state.reloadAssets.openEditorPath)
88
+ return handleOpenEditorRequest(request, state.root)
89
+ if (state.lastError !== undefined)
90
+ return buildErrorResponse(request, state.lastError, state.reloadAssets.script)
91
+
92
+ const remoteIp = state.unix !== undefined ? request.headers.get(DEV_CLIENT_IP_HEADER) ?? undefined : srv.requestIP(request)?.address
93
+ const res = await state.app!.handle(request, remoteIp)
94
+ const ct = res.headers.get('content-type') ?? ''
95
+ const isStreamedHtml = ct.includes('text/html') && request.method !== 'HEAD' && res.body !== null && !res.headers.has('content-length')
96
+ if (ct.includes('text/event-stream') || isStreamedHtml)
97
+ srv.timeout(request, 0)
98
+ return withReloadScript(request, res, state.reloadAssets)
99
+ }
100
+
40
101
  export async function devServer(options: DevServerOptions): Promise<{
41
102
  url: string
42
103
  assetPrefix: string
@@ -47,8 +108,8 @@ export async function devServer(options: DevServerOptions): Promise<{
47
108
  const root = resolve(options.root)
48
109
  const devRoot = join(root, '.prunelle-dev')
49
110
  const initialCfg = await loadConfig(root, { dev: true })
50
- // Clean stale `.prunelle-dev/` left behind by a previously killed dev process.
51
- rmSync(devRoot, { recursive: true, force: true })
111
+ // Clean stale build folders left behind by a previously killed or recycled dev process, preserving last-errors.json.
112
+ cleanDevArtifacts(devRoot)
52
113
  let activeCfg = initialCfg
53
114
  let activeAssetPrefix = (initialCfg.assetPrefix ?? '/_pru').replace(/\/$/, '')
54
115
  let reloadAssets = makeDevReloadAssets(activeAssetPrefix)
@@ -56,7 +117,13 @@ export async function devServer(options: DevServerOptions): Promise<{
56
117
  const modules = createModuleStore(join(devRoot, 'server'))
57
118
  const hub = options.broadcast === undefined ? createReloadHub() : undefined
58
119
  const broadcast = options.broadcast ?? hub!.broadcast
59
- const recycle = options.recycle
120
+ let recycled = false
121
+ const recycle = options.recycle === undefined
122
+ ? undefined
123
+ : (reason: RecycleReason) => {
124
+ recycled = true
125
+ options.recycle!(reason)
126
+ }
60
127
  const queue = createRebuildQueue(runSingleBuild)
61
128
  const watchers = createDevWatchers({
62
129
  root,
@@ -65,7 +132,7 @@ export async function devServer(options: DevServerOptions): Promise<{
65
132
  routesDir: options.routesDir,
66
133
  schedule: kind => kind === 'config' && recycle !== undefined ? recycle('config') : queue.schedule(kind),
67
134
  })
68
- const serverOptions = { root, dev: true, compress: false, ...(options.maxRequestBodySize !== undefined ? { maxRequestBodySize: options.maxRequestBodySize } : {}) }
135
+ const serverOptions = { root, dev: true, compress: false, errorSink: createDevRuntimeErrorSink(root), ...(options.maxRequestBodySize !== undefined ? { maxRequestBodySize: options.maxRequestBodySize } : {}) }
69
136
 
70
137
  let buildNum = 0
71
138
  let current: { app: PrunelleApp, outDir: string } | undefined
@@ -119,6 +186,7 @@ export async function devServer(options: DevServerOptions): Promise<{
119
186
  return
120
187
  }
121
188
  lastError = undefined
189
+ recordDevBuildError(root, undefined)
122
190
  watchers.syncBuild(buildCache.watchedFiles, manifest.publicFiles)
123
191
  if (n > 2)
124
192
  rmSync(join(devRoot, `b${n - 2}`), { recursive: true, force: true })
@@ -131,6 +199,7 @@ export async function devServer(options: DevServerOptions): Promise<{
131
199
  if (stopped)
132
200
  return
133
201
  lastError = errorText(err)
202
+ recordDevBuildError(root, lastError)
134
203
  console.error(`[prunelle dev] build error:\n${lastError}`)
135
204
  // Push reload over SSE so open browser tabs immediately display the error overlay
136
205
  broadcast('reload')
@@ -150,34 +219,12 @@ export async function devServer(options: DevServerOptions): Promise<{
150
219
  }
151
220
 
152
221
  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}`)
222
+ const { server, url } = startDevHttpServer(
223
+ options,
224
+ runtimeCfg.maxRequestBodySize ?? DEFAULT_MAX_REQUEST_BODY_SIZE,
225
+ initialCfg.port,
226
+ (request, srv) => handleAppFetch(request, srv, { root, unix: options.unix, hub, reloadAssets, lastError, app: current?.app }),
227
+ )
181
228
  let stopPromise: Promise<void> | undefined
182
229
 
183
230
  return {
@@ -200,7 +247,10 @@ export async function devServer(options: DevServerOptions): Promise<{
200
247
  catch (err) {
201
248
  console.warn(`[prunelle dev] the app failed to dispose: ${errorText(err)}`)
202
249
  }
203
- rmSync(devRoot, { recursive: true, force: true })
250
+ if (recycled)
251
+ cleanDevArtifacts(devRoot)
252
+ else
253
+ rmSync(devRoot, { recursive: true, force: true })
204
254
  })()
205
255
  return stopPromise
206
256
  },
@@ -0,0 +1,204 @@
1
+ // Opens a project source file at `line:col` in `$PRUNELLE_EDITOR` or `$VISUAL` on Alt-click in `prunelle dev`.
2
+
3
+ import { existsSync, realpathSync } from 'node:fs'
4
+ import { relative, resolve } from 'node:path'
5
+ import { isInside } from '../build/is-inside'
6
+
7
+ export const OPEN_EDITOR_SUBPATH = 'open-editor'
8
+
9
+ export interface ParsedSourceLoc {
10
+ file: string
11
+ relFile: string
12
+ line: number
13
+ col: number
14
+ }
15
+
16
+ const POSITIVE_INT_RE = /^\d+$/
17
+ const BIN_EXT_RE = /\.(?:exe|cmd|bat)$/i
18
+ const MISSING_EDITOR_ERROR = 'Set PRUNELLE_EDITOR or VISUAL to open files on Alt-click.'
19
+
20
+ const VSCODE_EDITORS = new Set(['code', 'code-insiders', 'codium', 'vscodium', 'cursor', 'windsurf'])
21
+ const ZED_EDITORS = new Set(['zed', 'zeditor'])
22
+ const JETBRAINS_EDITORS = new Set(['idea', 'webstorm', 'phpstorm', 'pycharm', 'goland', 'rubymine', 'rider', 'clion', 'datagrip', 'fleet', 'studio'])
23
+ const SUBLIME_HELIX_EDITORS = new Set(['subl', 'sublime_text', 'hx'])
24
+ const TERMINAL_EDITORS = new Set(['vim', 'nvim', 'vi', 'nano', 'emacs', 'emacsclient'])
25
+
26
+ /** Splits an editor command string into argv tokens, honoring single/double quotes without invoking a shell. */
27
+ function splitEditorSpec(spec: string): string[] {
28
+ const tokens: string[] = []
29
+ let current = ''
30
+ let quote: '\'' | '"' | undefined
31
+ let hasToken = false
32
+
33
+ for (let i = 0; i < spec.length; i++) {
34
+ const ch = spec[i]!
35
+ if (quote !== undefined) {
36
+ if (ch === '\\' && quote === '"' && i + 1 < spec.length && (spec[i + 1] === '"' || spec[i + 1] === '\\')) {
37
+ current += spec[++i]!
38
+ }
39
+ else if (ch === quote) {
40
+ quote = undefined
41
+ }
42
+ else {
43
+ current += ch
44
+ }
45
+ continue
46
+ }
47
+
48
+ if (ch === '\'' || ch === '"') {
49
+ quote = ch
50
+ hasToken = true
51
+ continue
52
+ }
53
+ if (ch === '\\' && i + 1 < spec.length && /\s/.test(spec[i + 1]!)) {
54
+ current += spec[++i]!
55
+ hasToken = true
56
+ continue
57
+ }
58
+ if (/\s/.test(ch)) {
59
+ if (hasToken) {
60
+ tokens.push(current)
61
+ current = ''
62
+ hasToken = false
63
+ }
64
+ continue
65
+ }
66
+ current += ch
67
+ hasToken = true
68
+ }
69
+
70
+ if (hasToken)
71
+ tokens.push(current)
72
+ return tokens
73
+ }
74
+
75
+ /** Parses and validates a `relPath:line:col` location, confining it strictly inside `root`. */
76
+ export function parseSourceLoc(raw: string, root: string): ParsedSourceLoc | { error: string, status: 400 | 403 | 404 } {
77
+ const trimmed = raw.trim()
78
+ const lastColon = trimmed.lastIndexOf(':')
79
+ const prevColon = lastColon > 0 ? trimmed.lastIndexOf(':', lastColon - 1) : -1
80
+ if (lastColon <= 0 || prevColon <= 0)
81
+ return { error: 'Invalid source location; expected file:line:col.', status: 400 }
82
+
83
+ const relPart = trimmed.slice(0, prevColon)
84
+ const lineStr = trimmed.slice(prevColon + 1, lastColon)
85
+ const colStr = trimmed.slice(lastColon + 1)
86
+ if (relPart === '' || relPart.includes('\0') || !POSITIVE_INT_RE.test(lineStr) || !POSITIVE_INT_RE.test(colStr))
87
+ return { error: 'Invalid source location; expected file:line:col.', status: 400 }
88
+
89
+ const line = Number.parseInt(lineStr, 10)
90
+ const col = Number.parseInt(colStr, 10)
91
+ if (!Number.isSafeInteger(line) || line < 1 || !Number.isSafeInteger(col) || col < 1)
92
+ return { error: 'Line and column must be positive integers.', status: 400 }
93
+
94
+ const resolvedRoot = resolve(root)
95
+ const file = resolve(resolvedRoot, relPart)
96
+ if (!isInside(resolvedRoot, file))
97
+ return { error: 'Source file is outside the project root.', status: 403 }
98
+ if (!existsSync(file))
99
+ return { error: 'Source file does not exist.', status: 404 }
100
+
101
+ const realRoot = realpathSync(resolvedRoot)
102
+ const realFile = realpathSync(file)
103
+ if (!isInside(realRoot, realFile))
104
+ return { error: 'Source file is outside the project root.', status: 403 }
105
+
106
+ return { file, relFile: relative(resolvedRoot, file).replaceAll('\\', '/'), line, col }
107
+ }
108
+
109
+ /** Builds the argv array to open `loc` in `editorSpec` (supporting `{file}`/`{line}`/`{col}` templates and common editors). */
110
+ export function buildEditorCommand(editorSpec: string, loc: { file: string, line: number, col: number }): string[] {
111
+ const parts = splitEditorSpec(editorSpec.trim())
112
+ if (parts.length === 0)
113
+ return []
114
+
115
+ const lineStr = String(loc.line)
116
+ const colStr = String(loc.col)
117
+ if (parts.some(p => p.includes('{file}') || p.includes('{line}') || p.includes('{col}')))
118
+ return parts.map(p => p.replaceAll('{file}', loc.file).replaceAll('{line}', lineStr).replaceAll('{col}', colStr))
119
+
120
+ const rawBin = parts[0]!.split(/[\\/]/).pop() ?? ''
121
+ const bin = rawBin.toLowerCase().replace(BIN_EXT_RE, '')
122
+ const fileLineCol = `${loc.file}:${lineStr}:${colStr}`
123
+
124
+ if (VSCODE_EDITORS.has(bin))
125
+ return [...parts, '--goto', fileLineCol]
126
+ if (ZED_EDITORS.has(bin) || SUBLIME_HELIX_EDITORS.has(bin))
127
+ return [...parts, fileLineCol]
128
+ if (JETBRAINS_EDITORS.has(bin))
129
+ return [...parts, '--line', lineStr, '--column', colStr, loc.file]
130
+ if (TERMINAL_EDITORS.has(bin))
131
+ return [...parts, `+${lineStr}`, loc.file]
132
+ return [...parts, fileLineCol]
133
+ }
134
+
135
+ export interface OpenEditorOptions {
136
+ env?: Record<string, string | undefined> | undefined
137
+ spawn?: ((cmd: string[]) => void) | undefined
138
+ }
139
+
140
+ export function openInEditor(
141
+ rawSrc: string,
142
+ root: string,
143
+ options?: OpenEditorOptions,
144
+ ): { ok: true, command: string[] } | { ok: false, status: number, error: string } {
145
+ const env = options?.env ?? process.env
146
+ const editor = env.PRUNELLE_EDITOR?.trim() || env.VISUAL?.trim()
147
+ if (!editor)
148
+ return { ok: false, status: 400, error: MISSING_EDITOR_ERROR }
149
+
150
+ const parsed = parseSourceLoc(rawSrc, root)
151
+ if ('error' in parsed)
152
+ return { ok: false, status: parsed.status, error: parsed.error }
153
+
154
+ const command = buildEditorCommand(editor, parsed)
155
+ if (command.length === 0)
156
+ return { ok: false, status: 400, error: MISSING_EDITOR_ERROR }
157
+
158
+ try {
159
+ if (options?.spawn !== undefined) {
160
+ options.spawn(command)
161
+ }
162
+ else {
163
+ const proc = Bun.spawn(command, { cwd: root, stdin: 'ignore', stdout: 'ignore', stderr: 'ignore' })
164
+ proc.unref()
165
+ }
166
+ }
167
+ catch (err) {
168
+ return {
169
+ ok: false,
170
+ status: 500,
171
+ error: `Failed to launch editor "${command[0]}": ${err instanceof Error ? err.message : String(err)}`,
172
+ }
173
+ }
174
+
175
+ return { ok: true, command }
176
+ }
177
+
178
+ /** Handles `POST /_pru/open-editor` from the dev server's Alt-click listener. */
179
+ export async function handleOpenEditorRequest(
180
+ request: Request,
181
+ root: string,
182
+ options?: OpenEditorOptions,
183
+ ): Promise<Response> {
184
+ if (request.method !== 'POST')
185
+ return Response.json({ ok: false, error: 'Method Not Allowed' }, { status: 405, headers: { allow: 'POST' } })
186
+
187
+ let rawSrc = new URL(request.url).searchParams.get('src') ?? ''
188
+ if (rawSrc === '') {
189
+ try {
190
+ const body = await request.json() as unknown
191
+ if (body !== null && typeof body === 'object' && typeof (body as { src?: unknown }).src === 'string')
192
+ rawSrc = (body as { src: string }).src
193
+ }
194
+ catch {
195
+ return Response.json({ ok: false, error: 'Invalid JSON body; expected { "src": "file:line:col" }.' }, { status: 400 })
196
+ }
197
+ }
198
+
199
+ if (rawSrc.trim() === '')
200
+ return Response.json({ ok: false, error: 'Missing "src" location.' }, { status: 400 })
201
+
202
+ const result = openInEditor(rawSrc, root, options)
203
+ return Response.json(result, { status: result.ok ? 200 : result.status })
204
+ }
@@ -12,6 +12,7 @@ export interface DevChildOptions {
12
12
  root: string
13
13
  routesDir?: string | undefined
14
14
  unix: string
15
+ maxRequestBodySize?: number | undefined
15
16
  maxRssMb?: number | undefined
16
17
  }
17
18
 
package/src/dev/reload.ts CHANGED
@@ -4,13 +4,15 @@ import { wantsJson } from '../server/http'
4
4
  import { withCspHashes } from '../server/security'
5
5
  import { REGION_HEADER } from '../server/region'
6
6
  import { cspSha256 } from '../ssr/navigation'
7
+ import { OPEN_EDITOR_SUBPATH } from './open-editor'
7
8
 
8
- export function makeDevReloadAssets(assetPrefix: string): { script: string, hash: string, eventsPath: string } {
9
+ export function makeDevReloadAssets(assetPrefix: string): { script: string, hash: string, eventsPath: string, openEditorPath: string } {
9
10
  const prefix = assetPrefix.replace(/\/$/, '')
10
11
  const eventsPath = `${prefix}/dev-events`
11
- const js = `(()=>{const stem=u=>u.replace(/-[a-z0-9]+\\.css$/i,'');const s=new EventSource(${JSON.stringify(eventsPath)});s.onmessage=(e)=>{if(e.data.startsWith('css:')){const urls=JSON.parse(e.data.slice(4));const byStem=new Map(urls.map(u=>[stem(u),u]));const old=[...document.querySelectorAll('link[rel="stylesheet"][href^=${JSON.stringify(`${prefix}/`)}]')];if(old.length===0){location.reload();return;}const next=[];for(const o of old){const m=byStem.get(stem(o.getAttribute('href')||''));if(m)next.push(m);}if(next.length===0){location.reload();return;}let left=next.length;for(const u of next){const l=document.createElement('link');l.rel='stylesheet';l.href=u;const done=()=>{if(--left===0)for(const o of old)o.remove();};l.onload=done;l.onerror=done;document.head.appendChild(l);}}else{location.reload();}};})();`
12
+ const openEditorPath = `${prefix}/${OPEN_EDITOR_SUBPATH}`
13
+ const js = `(()=>{const stem=u=>u.replace(/-[a-z0-9]+\\.css$/i,'');const s=new EventSource(${JSON.stringify(eventsPath)});s.onmessage=(e)=>{if(e.data.startsWith('css:')){const urls=JSON.parse(e.data.slice(4));const byStem=new Map();for(const u of urls){const k=stem(u);byStem.set(k,byStem.has(k)?null:u);}const old=[...document.querySelectorAll('link[rel="stylesheet"][href^=${JSON.stringify(`${prefix}/`)}]')];if(old.length===0){location.reload();return;}const next=[];for(const o of old){const m=byStem.get(stem(o.getAttribute('href')||''));if(m===null){location.reload();return;}if(m)next.push(m);}if(next.length===0){location.reload();return;}let left=next.length;for(const u of next){const l=document.createElement('link');l.rel='stylesheet';l.href=u;const done=()=>{if(--left===0)for(const o of old)o.remove();};l.onload=done;l.onerror=done;document.head.appendChild(l);}}else{location.reload();}};document.addEventListener('click',e=>{if(!e.altKey||e.ctrlKey||e.metaKey||e.button!==0)return;const t=e.target instanceof Element?e.target.closest('[data-pru-src]'):null;if(!t)return;e.preventDefault();e.stopImmediatePropagation();fetch(${JSON.stringify(openEditorPath)},{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({src:t.getAttribute('data-pru-src')})}).catch(()=>{});},true);})();`
12
14
  const hash = cspSha256(js)
13
- return { script: `<script>${js}</script>`, hash, eventsPath }
15
+ return { script: `<script>${js}</script>`, hash, eventsPath, openEditorPath }
14
16
  }
15
17
 
16
18
  export function renderErrorOverlay(errText: string, reloadScript: string): string {
@@ -6,7 +6,7 @@ import type { DevChildMessage, DevChildOptions } from './protocol'
6
6
  import { existsSync, mkdtempSync, rmSync, watch } from 'node:fs'
7
7
  import { tmpdir } from 'node:os'
8
8
  import { join, resolve } from 'node:path'
9
- import { DEFAULT_MAX_REQUEST_BODY_SIZE } from '../server/http'
9
+ import { recordDevCrashError } from './error-log'
10
10
  import { DEV_CHILD_ENV, DEV_CLIENT_IP_HEADER } from './protocol'
11
11
  import { buildErrorResponse, createReloadHub, makeDevReloadAssets } from './reload'
12
12
 
@@ -24,12 +24,35 @@ interface Child {
24
24
  proc: Subprocess<'ignore', 'inherit', 'pipe'>
25
25
  socket: string
26
26
  stopping: boolean
27
+ crashHandled: Promise<void>
27
28
  }
28
29
 
29
30
  const CHILD_ENTRY = join(import.meta.dir, 'child.ts')
30
31
  const STOP_GRACE_MS = 5000
31
32
  const KEPT_STDERR = 8192
32
33
  const DEFAULT_MAX_RSS_MB = 2048
34
+ // When no CLI/API limit is set, let the child process enforce `prunelle.config.ts`'s `maxRequestBodySize` (including updates across recycles).
35
+ const DEFAULT_SUPERVISOR_MAX_BODY = 1024 * 1024 * 1024
36
+
37
+ async function drainStderr(stream: ReadableStream<Uint8Array>): Promise<string> {
38
+ let tail = ''
39
+ const decoder = new TextDecoder()
40
+ for await (const chunk of stream) {
41
+ process.stderr.write(chunk)
42
+ tail = (tail + decoder.decode(chunk, { stream: true })).slice(-KEPT_STDERR)
43
+ }
44
+ const rest = decoder.decode()
45
+ return rest !== '' ? (tail + rest).slice(-KEPT_STDERR) : tail
46
+ }
47
+
48
+ async function stopChild(child: Child): Promise<void> {
49
+ child.stopping = true
50
+ if (child.proc.exitCode === null && child.proc.signalCode === null)
51
+ child.proc.send({ t: 'stop' })
52
+ const kill = setTimeout(() => child.proc.kill('SIGKILL'), STOP_GRACE_MS)
53
+ await child.proc.exited
54
+ clearTimeout(kill)
55
+ }
33
56
 
34
57
  export async function devSupervisor(options: DevSupervisorOptions): Promise<{ url: string, stop: () => Promise<void> }> {
35
58
  const root = resolve(options.root)
@@ -48,8 +71,13 @@ export async function devSupervisor(options: DevSupervisorOptions): Promise<{ ur
48
71
  if (stopped)
49
72
  return Promise.resolve(undefined)
50
73
  const socket = join(socketDir, `${++spawned}.sock`)
51
- const childOptions: DevChildOptions = { root, routesDir: options.routesDir, unix: socket, maxRssMb: options.maxRssMb ?? DEFAULT_MAX_RSS_MB }
52
- let stderrTail = ''
74
+ const childOptions: DevChildOptions = {
75
+ root,
76
+ routesDir: options.routesDir,
77
+ unix: socket,
78
+ ...(options.maxRequestBodySize !== undefined ? { maxRequestBodySize: options.maxRequestBodySize } : {}),
79
+ maxRssMb: options.maxRssMb ?? DEFAULT_MAX_RSS_MB,
80
+ }
53
81
  let onReady: (child: Child | undefined) => void = () => {}
54
82
  const started = new Promise<Child | undefined>((res) => { onReady = res })
55
83
  const proc = Bun.spawn({
@@ -64,6 +92,7 @@ export async function devSupervisor(options: DevSupervisorOptions): Promise<{ ur
64
92
  else if (message.t === 'ready') {
65
93
  reloadAssets = makeDevReloadAssets(message.assetPrefix)
66
94
  crashed = undefined
95
+ recordDevCrashError(root, undefined)
67
96
  onReady(child)
68
97
  }
69
98
  else if (child === live && !child.stopping && !stopped) {
@@ -72,39 +101,26 @@ export async function devSupervisor(options: DevSupervisorOptions): Promise<{ ur
72
101
  }
73
102
  },
74
103
  })
75
- const child: Child = { proc, socket, stopping: false }
76
- live = child
77
- void (async () => {
78
- const decoder = new TextDecoder()
79
- for await (const chunk of proc.stderr) {
80
- process.stderr.write(chunk)
81
- stderrTail = (stderrTail + decoder.decode(chunk, { stream: true })).slice(-KEPT_STDERR)
82
- }
83
- })()
84
- void proc.exited.then((code) => {
104
+ const stderrDone = drainStderr(proc.stderr)
105
+ const crashHandled = proc.exited.then(async (code) => {
85
106
  rmSync(socket, { force: true })
86
107
  if (child.stopping || stopped)
87
108
  return
109
+ const stderrTail = await stderrDone
88
110
  const how = proc.signalCode !== null ? `was killed by ${proc.signalCode}` : `exited with code ${code}`
89
111
  crashed = [`prunelle dev: the app process ${how}.`, stderrTail.trim(), 'Save a file to start it again.'].filter(Boolean).join('\n\n')
112
+ recordDevCrashError(root, crashed)
90
113
  if (live === child)
91
114
  live = undefined
92
115
  onReady(undefined)
93
116
  hub.broadcast('reload')
94
117
  restartOnSave()
95
118
  })
119
+ const child: Child = { proc, socket, stopping: false, crashHandled }
120
+ live = child
96
121
  return started
97
122
  }
98
123
 
99
- async function stopChild(child: Child): Promise<void> {
100
- child.stopping = true
101
- if (child.proc.exitCode === null && child.proc.signalCode === null)
102
- child.proc.send({ t: 'stop' })
103
- const kill = setTimeout(() => child.proc.kill('SIGKILL'), STOP_GRACE_MS)
104
- await child.proc.exited
105
- clearTimeout(kill)
106
- }
107
-
108
124
  // A crashed app restarts on the next edit under the root (not recursively) or its source folders.
109
125
  function restartOnSave(): void {
110
126
  const dirs = [[root, false], [join(root, 'src'), true], ...(options.routesDir !== undefined ? [[resolve(root, options.routesDir), true] as const] : [])] as const
@@ -128,7 +144,7 @@ export async function devSupervisor(options: DevSupervisorOptions): Promise<{ ur
128
144
  port: options.port ?? 3000,
129
145
  hostname: options.hostname ?? '127.0.0.1',
130
146
  idleTimeout: 30,
131
- maxRequestBodySize: options.maxRequestBodySize ?? DEFAULT_MAX_REQUEST_BODY_SIZE,
147
+ maxRequestBodySize: options.maxRequestBodySize ?? DEFAULT_SUPERVISOR_MAX_BODY,
132
148
  async fetch(request, srv) {
133
149
  const url = new URL(request.url)
134
150
  if (url.pathname === reloadAssets.eventsPath) {
@@ -156,8 +172,8 @@ export async function devSupervisor(options: DevSupervisorOptions): Promise<{ ur
156
172
  catch (err) {
157
173
  if (request.signal.aborted)
158
174
  return new Response(null, { status: 499 })
159
- // A refused connection is most often the child dying: its exit, and its stderr, come right after.
160
- await Promise.race([child.proc.exited, Bun.sleep(1000)])
175
+ // A refused connection is most often the child dying: wait for its exit and drained stderr before answering.
176
+ await Promise.race([child.crashHandled, Bun.sleep(1000)])
161
177
  return buildErrorResponse(request, crashed ?? `prunelle dev: the app process did not answer: ${err instanceof Error ? err.message : String(err)}`, reloadAssets.script)
162
178
  }
163
179
  },
@@ -179,6 +195,7 @@ export async function devSupervisor(options: DevSupervisorOptions): Promise<{ ur
179
195
  hub.close()
180
196
  if (live !== undefined)
181
197
  await stopChild(live)
198
+ rmSync(join(root, '.prunelle-dev'), { recursive: true, force: true })
182
199
  rmSync(socketDir, { recursive: true, force: true })
183
200
  })()
184
201
  return stopPromise