prunelle 0.0.0-stage → 0.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/llms.txt +152 -0
- package/package.json +59 -4
- package/src/a11y/declaration.ts +335 -0
- package/src/a11y/index.ts +446 -0
- package/src/a11y/rgaa-map.ts +184 -0
- package/src/ambient.d.ts +6 -0
- package/src/attrs.ts +43 -0
- package/src/build/bundle.ts +657 -0
- package/src/build/carry.ts +57 -0
- package/src/build/client-entries.ts +107 -0
- package/src/build/client-plugin.ts +173 -0
- package/src/build/client-prune.ts +168 -0
- package/src/build/compile.ts +129 -0
- package/src/build/ecoindex.ts +229 -0
- package/src/build/files.ts +156 -0
- package/src/build/first-load.ts +164 -0
- package/src/build/graph.ts +247 -0
- package/src/build/index.ts +641 -0
- package/src/build/is-inside.ts +12 -0
- package/src/build/islands.ts +641 -0
- package/src/build/manifest.ts +325 -0
- package/src/build/output.ts +84 -0
- package/src/build/plugin-host.ts +278 -0
- package/src/build/precompress.ts +139 -0
- package/src/build/prerender.ts +232 -0
- package/src/build/render-rules.ts +205 -0
- package/src/build/report.ts +268 -0
- package/src/build/resolve.ts +52 -0
- package/src/build/routes.ts +342 -0
- package/src/build/server-entry.ts +38 -0
- package/src/build/static.ts +207 -0
- package/src/build/status-pages.ts +127 -0
- package/src/build/style-bundles.ts +526 -0
- package/src/cli/check-forms.ts +654 -0
- package/src/cli/check-links.ts +619 -0
- package/src/cli/check.ts +381 -0
- package/src/cli/commands.ts +345 -0
- package/src/cli/docs.ts +402 -0
- package/src/cli/index.ts +70 -0
- package/src/cli/inspect.ts +345 -0
- package/src/cli/mcp-tools.ts +480 -0
- package/src/cli/mcp.ts +205 -0
- package/src/cli/new.ts +41 -0
- package/src/cli/render.ts +261 -0
- package/src/cli/upgrade-names.ts +209 -0
- package/src/cli/upgrade.ts +354 -0
- package/src/compiler/analyze.ts +632 -0
- package/src/compiler/ast.ts +82 -0
- package/src/compiler/browser-globals.ts +127 -0
- package/src/compiler/cacheability.ts +592 -0
- package/src/compiler/compliance-rgaa.ts +502 -0
- package/src/compiler/compliance.ts +497 -0
- package/src/compiler/data-keys.ts +295 -0
- package/src/compiler/dev-source.ts +87 -0
- package/src/compiler/dom-attrs.ts +452 -0
- package/src/compiler/dom.ts +567 -0
- package/src/compiler/emit.ts +131 -0
- package/src/compiler/expr-context.ts +518 -0
- package/src/compiler/index.ts +8 -0
- package/src/compiler/interactivity.ts +366 -0
- package/src/compiler/mistakes.ts +499 -0
- package/src/compiler/node-env.ts +50 -0
- package/src/compiler/patch.ts +97 -0
- package/src/compiler/props.ts +511 -0
- package/src/compiler/scope.ts +607 -0
- package/src/compiler/server-only.ts +326 -0
- package/src/compiler/shared.ts +369 -0
- package/src/compiler/signal-reads.ts +242 -0
- package/src/compiler/slots.ts +227 -0
- package/src/compiler/ssr-helpers.ts +555 -0
- package/src/compiler/ssr-island.ts +90 -0
- package/src/compiler/ssr-prunelle-tags.ts +69 -0
- package/src/compiler/ssr.ts +526 -0
- package/src/context.ts +165 -0
- package/src/dev/child.ts +30 -0
- package/src/dev/error-log.ts +151 -0
- package/src/dev/index.ts +258 -0
- package/src/dev/modules.ts +68 -0
- package/src/dev/open-editor.ts +204 -0
- package/src/dev/protocol.ts +22 -0
- package/src/dev/queue.ts +79 -0
- package/src/dev/reload.ts +159 -0
- package/src/dev/supervisor.ts +204 -0
- package/src/dev/watchers.ts +251 -0
- package/src/dom/action.ts +164 -0
- package/src/dom/attrs.ts +84 -0
- package/src/dom/claim.ts +120 -0
- package/src/dom/extras.ts +562 -0
- package/src/dom/index.ts +289 -0
- package/src/dom/island.ts +285 -0
- package/src/dom/loop.ts +450 -0
- package/src/dom/revive.ts +36 -0
- package/src/index.ts +22 -0
- package/src/jsx-runtime.ts +566 -0
- package/src/plugins/config.ts +86 -0
- package/src/plugins/context.ts +66 -0
- package/src/plugins/index.ts +14 -0
- package/src/plugins/load.ts +70 -0
- package/src/plugins/order.ts +111 -0
- package/src/plugins/public.ts +15 -0
- package/src/plugins/requires.ts +47 -0
- package/src/plugins/services.ts +97 -0
- package/src/plugins/types.ts +261 -0
- package/src/reactivity/graph.ts +249 -0
- package/src/reactivity/index.ts +533 -0
- package/src/reactivity/selector.ts +51 -0
- package/src/reactivity/store.ts +208 -0
- package/src/server/action-protect.ts +198 -0
- package/src/server/action-registry.ts +78 -0
- package/src/server/action.ts +530 -0
- package/src/server/app-entry.ts +23 -0
- package/src/server/assets.ts +168 -0
- package/src/server/compress.ts +642 -0
- package/src/server/consent.ts +253 -0
- package/src/server/cookies.ts +139 -0
- package/src/server/document.ts +271 -0
- package/src/server/env.ts +33 -0
- package/src/server/errors.ts +391 -0
- package/src/server/form-schema.ts +343 -0
- package/src/server/health.ts +244 -0
- package/src/server/http.ts +538 -0
- package/src/server/index.ts +586 -0
- package/src/server/lifecycle.ts +75 -0
- package/src/server/loader.ts +123 -0
- package/src/server/page.ts +107 -0
- package/src/server/param-matchers.ts +112 -0
- package/src/server/plugin-host.ts +265 -0
- package/src/server/prerendered.ts +71 -0
- package/src/server/public.ts +19 -0
- package/src/server/rate-limit.ts +156 -0
- package/src/server/region.ts +96 -0
- package/src/server/request-body.ts +27 -0
- package/src/server/request-path.ts +73 -0
- package/src/server/request-scope.ts +22 -0
- package/src/server/route-cache.ts +423 -0
- package/src/server/route-table.ts +410 -0
- package/src/server/router.ts +261 -0
- package/src/server/routing.ts +472 -0
- package/src/server/security.ts +499 -0
- package/src/server/serve-handlers.ts +83 -0
- package/src/server/served-file.ts +128 -0
- package/src/server/standard-schema.ts +87 -0
- package/src/server/start.ts +143 -0
- package/src/server/static-dir.ts +220 -0
- package/src/server/stream.ts +211 -0
- package/src/ssr/context.ts +383 -0
- package/src/ssr/index.ts +596 -0
- package/src/ssr/navigation.ts +96 -0
- package/src/ssr/region.ts +183 -0
- package/src/style.ts +33 -0
- package/src/test/browser.ts +192 -0
- package/src/test/index.ts +191 -0
- package/src/ts-plugin/diagnostics.ts +378 -0
- package/src/ts-plugin/fixes.ts +364 -0
- package/src/ts-plugin/index.ts +194 -0
- package/src/unrenderable.ts +35 -0
- package/templates/_shared/AGENTS.md +10 -0
- package/templates/_shared/CLAUDE.md +1 -0
- package/templates/_shared/gitignore +3 -0
- package/templates/_shared/mcp.json +11 -0
- package/templates/_shared/public/robots.txt +2 -0
- package/templates/_shared/src/routes/legal.tsx +13 -0
- package/templates/_shared/tsconfig.json +25 -0
- package/templates/app/.env.example +4 -0
- package/templates/app/package.json +21 -0
- package/templates/app/prunelle.config.ts +11 -0
- package/templates/app/src/auth.ts +14 -0
- package/templates/app/src/routes/_layout.tsx +32 -0
- package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
- package/templates/app/src/routes/dashboard/index.tsx +13 -0
- package/templates/app/src/routes/index.tsx +15 -0
- package/templates/app/src/routes/login.tsx +34 -0
- package/templates/app/src/styles/app.css +7 -0
- package/templates/app/tests/app.test.ts +32 -0
- package/templates/blog/content/posts/welcome.md +9 -0
- package/templates/blog/package.json +22 -0
- package/templates/blog/prunelle.config.ts +23 -0
- package/templates/blog/src/posts.ts +26 -0
- package/templates/blog/src/routes/_layout.tsx +20 -0
- package/templates/blog/src/routes/blog/[slug].tsx +31 -0
- package/templates/blog/src/routes/index.tsx +33 -0
- package/templates/blog/src/styles/app.css +10 -0
- package/templates/fullstack/package.json +19 -0
- package/templates/fullstack/prunelle.config.ts +6 -0
- package/templates/fullstack/src/actions/greet.ts +19 -0
- package/templates/fullstack/src/components/Counter.tsx +10 -0
- package/templates/fullstack/src/components/GreetForm.tsx +27 -0
- package/templates/fullstack/src/routes/_layout.tsx +14 -0
- package/templates/fullstack/src/routes/api/health.ts +5 -0
- package/templates/fullstack/src/routes/index.tsx +13 -0
- package/templates/fullstack/src/styles/app.css +29 -0
- package/templates/fullstack/tests/app.test.ts +37 -0
- package/templates/minimal/package.json +19 -0
- package/templates/minimal/prunelle.config.ts +6 -0
- package/templates/minimal/src/components/Counter.tsx +10 -0
- package/templates/minimal/src/routes/_layout.tsx +14 -0
- package/templates/minimal/src/routes/index.tsx +11 -0
- package/templates/minimal/src/styles/app.css +22 -0
- package/ts-plugin.cjs +4277 -0
- package/README.md +0 -3
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// What `prunelle dev` and its app process share, kept apart so the parent never loads the build to read it.
|
|
2
|
+
|
|
3
|
+
export type RecycleReason = 'config' | 'memory'
|
|
4
|
+
|
|
5
|
+
/** The header the parent sets to the browser's address on each request it passes to the app process. */
|
|
6
|
+
export const DEV_CLIENT_IP_HEADER = 'x-pru-dev-client-ip'
|
|
7
|
+
|
|
8
|
+
/** The environment variable holding the app process's {@link DevChildOptions}, as JSON. */
|
|
9
|
+
export const DEV_CHILD_ENV = 'PRUNELLE_DEV_CHILD'
|
|
10
|
+
|
|
11
|
+
export interface DevChildOptions {
|
|
12
|
+
root: string
|
|
13
|
+
routesDir?: string | undefined
|
|
14
|
+
unix: string
|
|
15
|
+
maxRequestBodySize?: number | undefined
|
|
16
|
+
maxRssMb?: number | undefined
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export type DevChildMessage =
|
|
20
|
+
| { t: 'ready', assetPrefix: string }
|
|
21
|
+
| { t: 'event', payload: string }
|
|
22
|
+
| { t: 'recycle', reason: RecycleReason }
|
package/src/dev/queue.ts
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// prunelle dev's serialized rebuild queue: saves within 40 ms coalesce, and a save during a build runs one more build after it.
|
|
2
|
+
|
|
3
|
+
import type { ChangeKind } from './watchers'
|
|
4
|
+
|
|
5
|
+
export interface PendingBuild {
|
|
6
|
+
/** Every change was a stylesheet: the browser swaps its `<link>`s. */
|
|
7
|
+
cssOnly: boolean
|
|
8
|
+
/** Every change was an existing `public/` file: the app is re-created from the current build. */
|
|
9
|
+
publicOnly: boolean
|
|
10
|
+
/** `prunelle.config.ts` changed: the build cache and the config start over. */
|
|
11
|
+
resetCache: boolean
|
|
12
|
+
/** A file no bundle holds changed: every server module is imported again. */
|
|
13
|
+
reloadAll: boolean
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const nothingYet = (): PendingBuild => ({ cssOnly: true, publicOnly: true, resetCache: false, reloadAll: false })
|
|
17
|
+
|
|
18
|
+
export function createRebuildQueue(run: (build: PendingBuild) => Promise<void>) {
|
|
19
|
+
let next = nothingYet()
|
|
20
|
+
let building = false
|
|
21
|
+
let pending = false
|
|
22
|
+
let stopped = false
|
|
23
|
+
let inFlight: Promise<void> | undefined
|
|
24
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
25
|
+
|
|
26
|
+
function drain(): Promise<void> {
|
|
27
|
+
clearTimeout(timer)
|
|
28
|
+
if (building) {
|
|
29
|
+
pending = true
|
|
30
|
+
return inFlight ?? Promise.resolve()
|
|
31
|
+
}
|
|
32
|
+
building = true
|
|
33
|
+
inFlight = (async () => {
|
|
34
|
+
try {
|
|
35
|
+
do {
|
|
36
|
+
clearTimeout(timer)
|
|
37
|
+
const build = next
|
|
38
|
+
next = nothingYet()
|
|
39
|
+
pending = false
|
|
40
|
+
await run(build)
|
|
41
|
+
} while (pending && !stopped)
|
|
42
|
+
}
|
|
43
|
+
finally {
|
|
44
|
+
building = false
|
|
45
|
+
inFlight = undefined
|
|
46
|
+
}
|
|
47
|
+
})()
|
|
48
|
+
return inFlight
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
return {
|
|
52
|
+
schedule(kind: ChangeKind): void {
|
|
53
|
+
if (stopped)
|
|
54
|
+
return
|
|
55
|
+
if (kind === 'config')
|
|
56
|
+
next.resetCache = true
|
|
57
|
+
if (kind === 'config' || kind === 'full')
|
|
58
|
+
next.reloadAll = true
|
|
59
|
+
if (kind !== 'css')
|
|
60
|
+
next.cssOnly = false
|
|
61
|
+
if (kind !== 'public')
|
|
62
|
+
next.publicOnly = false
|
|
63
|
+
clearTimeout(timer)
|
|
64
|
+
timer = setTimeout(() => void drain(), 40)
|
|
65
|
+
},
|
|
66
|
+
/** A full build now, or right after the one running. */
|
|
67
|
+
now(): Promise<void> {
|
|
68
|
+
next.cssOnly = false
|
|
69
|
+
next.publicOnly = false
|
|
70
|
+
return drain()
|
|
71
|
+
},
|
|
72
|
+
/** Drops what is scheduled and resolves once the running build is done. */
|
|
73
|
+
stop(): Promise<void> {
|
|
74
|
+
stopped = true
|
|
75
|
+
clearTimeout(timer)
|
|
76
|
+
return inFlight ?? Promise.resolve()
|
|
77
|
+
},
|
|
78
|
+
}
|
|
79
|
+
}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
// What prunelle dev adds to the app's answers: the reload script and its event stream, the build-error overlay, and the script's injection into streamed HTML.
|
|
2
|
+
|
|
3
|
+
import { wantsJson } from '../server/http'
|
|
4
|
+
import { withCspHashes } from '../server/security'
|
|
5
|
+
import { REGION_HEADER } from '../server/region'
|
|
6
|
+
import { cspSha256 } from '../ssr/navigation'
|
|
7
|
+
import { OPEN_EDITOR_SUBPATH } from './open-editor'
|
|
8
|
+
|
|
9
|
+
export function makeDevReloadAssets(assetPrefix: string): { script: string, hash: string, eventsPath: string, openEditorPath: string } {
|
|
10
|
+
const prefix = assetPrefix.replace(/\/$/, '')
|
|
11
|
+
const eventsPath = `${prefix}/dev-events`
|
|
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);})();`
|
|
14
|
+
const hash = cspSha256(js)
|
|
15
|
+
return { script: `<script>${js}</script>`, hash, eventsPath, openEditorPath }
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function renderErrorOverlay(errText: string, reloadScript: string): string {
|
|
19
|
+
const escaped = errText
|
|
20
|
+
.replaceAll('&', '&')
|
|
21
|
+
.replaceAll('<', '<')
|
|
22
|
+
.replaceAll('>', '>')
|
|
23
|
+
return `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>Prunelle Dev Error</title><style>body{margin:0;min-height:100vh;background:#0d1117;color:#e6edf3;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;display:grid;place-items:center;padding:2rem}main{max-width:56rem;width:100%;background:#161b22;border:1px solid #f85149;border-radius:10px;padding:1.5rem 2rem;box-shadow:0 16px 48px rgba(0,0,0,.45)}h1{margin:0 0 1rem;color:#ff7b72;font-size:1.15rem}pre{margin:0;white-space:pre-wrap;word-break:break-word;line-height:1.5;font-size:.9rem;color:#ffa198}p{margin:1rem 0 0;font-size:.8rem;color:#8b949e}</style></head><body><main><h1>Prunelle Dev Build Error</h1><pre>${escaped}</pre><p>Save a fix to auto-reload.</p></main>${reloadScript}</body></html>`
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function shouldInjectReload(request: Request, res: Response, ct: string): boolean {
|
|
27
|
+
return ct.includes('text/html')
|
|
28
|
+
&& request.method !== 'HEAD'
|
|
29
|
+
&& res.body !== null
|
|
30
|
+
&& !res.headers.has('content-encoding')
|
|
31
|
+
&& !request.headers.has(REGION_HEADER)
|
|
32
|
+
&& !res.headers.has(REGION_HEADER)
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// Injects the dev reload script into an HTML response while preserving streaming (<Suspense>).
|
|
36
|
+
export function injectReloadStream(body: ReadableStream<Uint8Array>, reloadScript: string): ReadableStream<Uint8Array> {
|
|
37
|
+
const decoder = new TextDecoder()
|
|
38
|
+
const encoder = new TextEncoder()
|
|
39
|
+
let injected = false
|
|
40
|
+
let tail = ''
|
|
41
|
+
const KEEP = 16 // enough to span a split `</body>` tag across chunk boundaries
|
|
42
|
+
|
|
43
|
+
return body.pipeThrough(new TransformStream<Uint8Array, Uint8Array>({
|
|
44
|
+
transform(chunk, controller) {
|
|
45
|
+
if (injected) {
|
|
46
|
+
controller.enqueue(chunk)
|
|
47
|
+
return
|
|
48
|
+
}
|
|
49
|
+
const text = tail + decoder.decode(chunk, { stream: true })
|
|
50
|
+
const idx = text.indexOf('</body>')
|
|
51
|
+
if (idx !== -1) {
|
|
52
|
+
injected = true
|
|
53
|
+
tail = ''
|
|
54
|
+
controller.enqueue(encoder.encode(`${text.slice(0, idx)}${reloadScript}${text.slice(idx)}`))
|
|
55
|
+
return
|
|
56
|
+
}
|
|
57
|
+
if (text.length > KEEP) {
|
|
58
|
+
const split = text.length - KEEP
|
|
59
|
+
controller.enqueue(encoder.encode(text.slice(0, split)))
|
|
60
|
+
tail = text.slice(split)
|
|
61
|
+
}
|
|
62
|
+
else {
|
|
63
|
+
tail = text
|
|
64
|
+
}
|
|
65
|
+
},
|
|
66
|
+
flush(controller) {
|
|
67
|
+
const rest = tail + decoder.decode()
|
|
68
|
+
if (injected) {
|
|
69
|
+
if (rest.length > 0)
|
|
70
|
+
controller.enqueue(encoder.encode(rest))
|
|
71
|
+
return
|
|
72
|
+
}
|
|
73
|
+
const idx = rest.indexOf('</body>')
|
|
74
|
+
if (idx !== -1)
|
|
75
|
+
controller.enqueue(encoder.encode(`${rest.slice(0, idx)}${reloadScript}${rest.slice(idx)}`))
|
|
76
|
+
else
|
|
77
|
+
controller.enqueue(encoder.encode(rest + reloadScript))
|
|
78
|
+
},
|
|
79
|
+
}))
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** The reload script's event stream: `controller` joins `clients` until the browser goes away. */
|
|
83
|
+
function reloadEvents(request: Request, clients: Set<ReadableStreamDefaultController<Uint8Array>>): Response {
|
|
84
|
+
let ctrl: ReadableStreamDefaultController<Uint8Array> | undefined
|
|
85
|
+
let open = true
|
|
86
|
+
const stream = new ReadableStream<Uint8Array>({
|
|
87
|
+
start(controller) {
|
|
88
|
+
ctrl = controller
|
|
89
|
+
clients.add(controller)
|
|
90
|
+
controller.enqueue(new TextEncoder().encode(': connected\n\n'))
|
|
91
|
+
request.signal.addEventListener('abort', () => {
|
|
92
|
+
clients.delete(controller)
|
|
93
|
+
if (open) {
|
|
94
|
+
open = false
|
|
95
|
+
controller.close()
|
|
96
|
+
}
|
|
97
|
+
}, { once: true })
|
|
98
|
+
},
|
|
99
|
+
cancel() {
|
|
100
|
+
open = false
|
|
101
|
+
if (ctrl !== undefined)
|
|
102
|
+
clients.delete(ctrl)
|
|
103
|
+
},
|
|
104
|
+
})
|
|
105
|
+
return new Response(stream, {
|
|
106
|
+
headers: {
|
|
107
|
+
'content-type': 'text/event-stream; charset=utf-8',
|
|
108
|
+
'cache-control': 'no-cache, no-transform',
|
|
109
|
+
'x-accel-buffering': 'no',
|
|
110
|
+
},
|
|
111
|
+
})
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** The answer to every request while the build is broken: JSON or text when the client asks for it, else the overlay. */
|
|
115
|
+
export function buildErrorResponse(request: Request, error: string, reloadScript: string): Response {
|
|
116
|
+
if (wantsJson(request))
|
|
117
|
+
return Response.json({ ok: false, status: 500, error }, { status: 500 })
|
|
118
|
+
if ((request.headers.get('accept') ?? '').startsWith('text/plain'))
|
|
119
|
+
return new Response(error, { status: 500, headers: { 'content-type': 'text/plain; charset=utf-8' } })
|
|
120
|
+
return new Response(renderErrorOverlay(error, reloadScript), {
|
|
121
|
+
status: 500,
|
|
122
|
+
headers: { 'content-type': 'text/html; charset=utf-8' },
|
|
123
|
+
})
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** An HTML answer with the reload script before `</body>` and its hash in the CSP; any other answer as it is. */
|
|
127
|
+
export function withReloadScript(request: Request, res: Response, assets: { script: string, hash: string }): Response {
|
|
128
|
+
if (!shouldInjectReload(request, res, res.headers.get('content-type') ?? ''))
|
|
129
|
+
return res
|
|
130
|
+
const headers = new Headers(res.headers)
|
|
131
|
+
headers.delete('content-length')
|
|
132
|
+
const existingCsp = headers.get('content-security-policy')
|
|
133
|
+
if (existingCsp !== null)
|
|
134
|
+
headers.set('content-security-policy', withCspHashes(existingCsp, { scriptHashes: [assets.hash] }))
|
|
135
|
+
return new Response(injectReloadStream(res.body!, assets.script), { status: res.status, headers })
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** The browsers' reload streams: `broadcast` reaches each, and a ping every 15 s keeps idle ones open. */
|
|
139
|
+
export function createReloadHub() {
|
|
140
|
+
const clients = new Set<ReadableStreamDefaultController<Uint8Array>>()
|
|
141
|
+
const encoder = new TextEncoder()
|
|
142
|
+
const push = (chunk: Uint8Array): void => {
|
|
143
|
+
for (const c of clients) {
|
|
144
|
+
try {
|
|
145
|
+
c.enqueue(chunk)
|
|
146
|
+
}
|
|
147
|
+
catch {
|
|
148
|
+
clients.delete(c)
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
const ping = encoder.encode(': ping\n\n')
|
|
153
|
+
const pinger = setInterval(() => push(ping), 15_000)
|
|
154
|
+
return {
|
|
155
|
+
events: (request: Request): Response => reloadEvents(request, clients),
|
|
156
|
+
broadcast: (payload: string): void => push(encoder.encode(`data: ${payload}\n\n`)),
|
|
157
|
+
close: (): void => clearInterval(pinger),
|
|
158
|
+
}
|
|
159
|
+
}
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
// `prunelle dev`: keeps the port and the browsers' reload stream, and runs the app in a child process it replaces when prunelle.config.ts or what it imports changes, or past a memory limit.
|
|
2
|
+
|
|
3
|
+
import type { FSWatcher } from 'node:fs'
|
|
4
|
+
import type { Subprocess } from 'bun'
|
|
5
|
+
import type { DevChildMessage, DevChildOptions } from './protocol'
|
|
6
|
+
import { existsSync, mkdtempSync, rmSync, watch } from 'node:fs'
|
|
7
|
+
import { tmpdir } from 'node:os'
|
|
8
|
+
import { join, resolve } from 'node:path'
|
|
9
|
+
import { recordDevCrashError } from './error-log'
|
|
10
|
+
import { DEV_CHILD_ENV, DEV_CLIENT_IP_HEADER } from './protocol'
|
|
11
|
+
import { buildErrorResponse, createReloadHub, makeDevReloadAssets } from './reload'
|
|
12
|
+
|
|
13
|
+
export interface DevSupervisorOptions {
|
|
14
|
+
root: string
|
|
15
|
+
port?: number | undefined
|
|
16
|
+
hostname?: string | undefined
|
|
17
|
+
routesDir?: string | undefined
|
|
18
|
+
maxRequestBodySize?: number | undefined
|
|
19
|
+
/** The app process is replaced once its RSS passes this after a rebuild. */
|
|
20
|
+
maxRssMb?: number | undefined
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
interface Child {
|
|
24
|
+
proc: Subprocess<'ignore', 'inherit', 'pipe'>
|
|
25
|
+
socket: string
|
|
26
|
+
stopping: boolean
|
|
27
|
+
crashHandled: Promise<void>
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const CHILD_ENTRY = join(import.meta.dir, 'child.ts')
|
|
31
|
+
const STOP_GRACE_MS = 5000
|
|
32
|
+
const KEPT_STDERR = 8192
|
|
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
|
+
}
|
|
56
|
+
|
|
57
|
+
export async function devSupervisor(options: DevSupervisorOptions): Promise<{ url: string, stop: () => Promise<void> }> {
|
|
58
|
+
const root = resolve(options.root)
|
|
59
|
+
const socketDir = mkdtempSync(join(tmpdir(), 'prunelle-dev-sockets-'))
|
|
60
|
+
const hub = createReloadHub()
|
|
61
|
+
let reloadAssets = makeDevReloadAssets('/_pru')
|
|
62
|
+
let spawned = 0
|
|
63
|
+
let live: Child | undefined
|
|
64
|
+
let crashed: string | undefined
|
|
65
|
+
let stopped = false
|
|
66
|
+
let saveWatchers: FSWatcher[] = []
|
|
67
|
+
// Requests wait on this while a child starts.
|
|
68
|
+
let ready: Promise<Child | undefined>
|
|
69
|
+
|
|
70
|
+
function spawnChild(): Promise<Child | undefined> {
|
|
71
|
+
if (stopped)
|
|
72
|
+
return Promise.resolve(undefined)
|
|
73
|
+
const socket = join(socketDir, `${++spawned}.sock`)
|
|
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
|
+
}
|
|
81
|
+
let onReady: (child: Child | undefined) => void = () => {}
|
|
82
|
+
const started = new Promise<Child | undefined>((res) => { onReady = res })
|
|
83
|
+
const proc = Bun.spawn({
|
|
84
|
+
cmd: [process.execPath, CHILD_ENTRY],
|
|
85
|
+
cwd: root,
|
|
86
|
+
env: { ...process.env, [DEV_CHILD_ENV]: JSON.stringify(childOptions) },
|
|
87
|
+
stdio: ['ignore', 'inherit', 'pipe'],
|
|
88
|
+
serialization: 'json',
|
|
89
|
+
ipc(message: DevChildMessage) {
|
|
90
|
+
if (message.t === 'event')
|
|
91
|
+
hub.broadcast(message.payload)
|
|
92
|
+
else if (message.t === 'ready') {
|
|
93
|
+
reloadAssets = makeDevReloadAssets(message.assetPrefix)
|
|
94
|
+
crashed = undefined
|
|
95
|
+
recordDevCrashError(root, undefined)
|
|
96
|
+
onReady(child)
|
|
97
|
+
}
|
|
98
|
+
else if (child === live && !child.stopping && !stopped) {
|
|
99
|
+
console.log(`[prunelle dev] ${message.reason === 'config' ? 'prunelle.config.ts or a file it imports changed' : `the app passed ${childOptions.maxRssMb} MB`}: starting a new app process`)
|
|
100
|
+
ready = stopChild(child).then(spawnChild)
|
|
101
|
+
}
|
|
102
|
+
},
|
|
103
|
+
})
|
|
104
|
+
const stderrDone = drainStderr(proc.stderr)
|
|
105
|
+
const crashHandled = proc.exited.then(async (code) => {
|
|
106
|
+
rmSync(socket, { force: true })
|
|
107
|
+
if (child.stopping || stopped)
|
|
108
|
+
return
|
|
109
|
+
const stderrTail = await stderrDone
|
|
110
|
+
const how = proc.signalCode !== null ? `was killed by ${proc.signalCode}` : `exited with code ${code}`
|
|
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)
|
|
113
|
+
if (live === child)
|
|
114
|
+
live = undefined
|
|
115
|
+
onReady(undefined)
|
|
116
|
+
hub.broadcast('reload')
|
|
117
|
+
restartOnSave()
|
|
118
|
+
})
|
|
119
|
+
const child: Child = { proc, socket, stopping: false, crashHandled }
|
|
120
|
+
live = child
|
|
121
|
+
return started
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// A crashed app restarts on the next edit under the root (not recursively) or its source folders.
|
|
125
|
+
function restartOnSave(): void {
|
|
126
|
+
const dirs = [[root, false], [join(root, 'src'), true], ...(options.routesDir !== undefined ? [[resolve(root, options.routesDir), true] as const] : [])] as const
|
|
127
|
+
for (const [dir, recursive] of dirs) {
|
|
128
|
+
if (!existsSync(dir))
|
|
129
|
+
continue
|
|
130
|
+
saveWatchers.push(watch(dir, { recursive }, () => {
|
|
131
|
+
for (const w of saveWatchers)
|
|
132
|
+
w.close()
|
|
133
|
+
saveWatchers = []
|
|
134
|
+
if (!stopped)
|
|
135
|
+
ready = spawnChild()
|
|
136
|
+
}))
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
ready = spawnChild()
|
|
141
|
+
await ready
|
|
142
|
+
|
|
143
|
+
const server = Bun.serve({
|
|
144
|
+
port: options.port ?? 3000,
|
|
145
|
+
hostname: options.hostname ?? '127.0.0.1',
|
|
146
|
+
idleTimeout: 30,
|
|
147
|
+
maxRequestBodySize: options.maxRequestBodySize ?? DEFAULT_SUPERVISOR_MAX_BODY,
|
|
148
|
+
async fetch(request, srv) {
|
|
149
|
+
const url = new URL(request.url)
|
|
150
|
+
if (url.pathname === reloadAssets.eventsPath) {
|
|
151
|
+
srv.timeout(request, 0)
|
|
152
|
+
return hub.events(request)
|
|
153
|
+
}
|
|
154
|
+
const child = await ready
|
|
155
|
+
if (child === undefined)
|
|
156
|
+
return buildErrorResponse(request, crashed ?? 'prunelle dev: the app process is not running.', reloadAssets.script)
|
|
157
|
+
const headers = new Headers(request.headers)
|
|
158
|
+
headers.set(DEV_CLIENT_IP_HEADER, srv.requestIP(request)?.address ?? '')
|
|
159
|
+
try {
|
|
160
|
+
const res = await fetch(`http://localhost${url.pathname}${url.search}`, {
|
|
161
|
+
unix: child.socket,
|
|
162
|
+
method: request.method,
|
|
163
|
+
headers,
|
|
164
|
+
body: request.body,
|
|
165
|
+
redirect: 'manual',
|
|
166
|
+
signal: request.signal,
|
|
167
|
+
})
|
|
168
|
+
if (!res.headers.has('content-length'))
|
|
169
|
+
srv.timeout(request, 0)
|
|
170
|
+
return res
|
|
171
|
+
}
|
|
172
|
+
catch (err) {
|
|
173
|
+
if (request.signal.aborted)
|
|
174
|
+
return new Response(null, { status: 499 })
|
|
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)])
|
|
177
|
+
return buildErrorResponse(request, crashed ?? `prunelle dev: the app process did not answer: ${err instanceof Error ? err.message : String(err)}`, reloadAssets.script)
|
|
178
|
+
}
|
|
179
|
+
},
|
|
180
|
+
})
|
|
181
|
+
|
|
182
|
+
const host = options.hostname === undefined || options.hostname === '0.0.0.0' ? '127.0.0.1' : options.hostname
|
|
183
|
+
const url = `http://${host}:${server.port}`
|
|
184
|
+
console.log(`[prunelle dev] listening on ${url}`)
|
|
185
|
+
let stopPromise: Promise<void> | undefined
|
|
186
|
+
|
|
187
|
+
return {
|
|
188
|
+
url,
|
|
189
|
+
stop() {
|
|
190
|
+
stopPromise ??= (async () => {
|
|
191
|
+
stopped = true
|
|
192
|
+
for (const w of saveWatchers)
|
|
193
|
+
w.close()
|
|
194
|
+
server.stop(true)
|
|
195
|
+
hub.close()
|
|
196
|
+
if (live !== undefined)
|
|
197
|
+
await stopChild(live)
|
|
198
|
+
rmSync(join(root, '.prunelle-dev'), { recursive: true, force: true })
|
|
199
|
+
rmSync(socketDir, { recursive: true, force: true })
|
|
200
|
+
})()
|
|
201
|
+
return stopPromise
|
|
202
|
+
},
|
|
203
|
+
}
|
|
204
|
+
}
|