prunelle 0.1.1 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/llms.txt +137 -40
- package/package.json +11 -2
- package/src/a11y/declaration.ts +369 -0
- package/src/a11y/index.ts +466 -0
- package/src/a11y/rgaa-map.ts +230 -0
- package/src/attrs.ts +11 -3
- package/src/build/bundle.ts +88 -40
- package/src/build/byte-size.ts +11 -0
- package/src/build/client-entries.ts +3 -2
- package/src/build/client-plugin.ts +11 -5
- package/src/build/client-prune.ts +56 -6
- package/src/build/compile.ts +13 -10
- package/src/build/ecoindex.ts +230 -0
- package/src/build/files.ts +6 -0
- package/src/build/first-load.ts +83 -11
- package/src/build/graph.ts +29 -39
- package/src/build/index.ts +218 -113
- package/src/build/island-promote.ts +229 -0
- package/src/build/islands.ts +11 -203
- package/src/build/manifest.ts +56 -116
- package/src/build/output.ts +2 -2
- package/src/build/plugin-host.ts +113 -41
- package/src/build/precompress.ts +16 -3
- package/src/build/prerender.ts +173 -38
- package/src/build/reach.ts +136 -0
- package/src/build/render-rules.ts +2 -2
- package/src/build/report.ts +42 -5
- package/src/build/resolve.ts +8 -6
- package/src/build/routes.ts +175 -10
- package/src/build/static-headers.ts +93 -0
- package/src/build/static.ts +139 -39
- package/src/build/status-pages.ts +127 -0
- package/src/build/style-bundles.ts +526 -0
- package/src/cli/check-forms.ts +610 -0
- package/src/cli/check-imports.ts +25 -0
- package/src/cli/check-links.ts +632 -0
- package/src/cli/check-security.ts +64 -0
- package/src/cli/check.ts +107 -26
- package/src/cli/commands.ts +120 -11
- package/src/cli/docs.ts +403 -0
- package/src/cli/inspect.ts +105 -15
- package/src/cli/mcp-tools.ts +492 -0
- package/src/cli/mcp.ts +205 -0
- package/src/cli/new.ts +16 -5
- package/src/cli/render.ts +416 -0
- package/src/cli/upgrade-names.ts +73 -13
- package/src/cli/upgrade.ts +156 -18
- package/src/compiler/analyze.ts +68 -14
- package/src/compiler/browser-globals.ts +140 -17
- package/src/compiler/cacheability.ts +636 -0
- package/src/compiler/compliance-eco.ts +71 -0
- package/src/compiler/compliance-rgaa.ts +614 -0
- package/src/compiler/compliance-urls.ts +145 -0
- package/src/compiler/compliance.ts +355 -351
- package/src/compiler/data-keys.ts +199 -192
- package/src/compiler/dev-source.ts +87 -0
- package/src/compiler/dom-attrs.ts +138 -65
- package/src/compiler/dom.ts +517 -442
- package/src/compiler/expr-context.ts +167 -57
- package/src/compiler/foreign-imports.ts +88 -0
- package/src/compiler/mistakes.ts +23 -2
- package/src/compiler/props-body.ts +52 -0
- package/src/compiler/props.ts +87 -36
- package/src/compiler/scope.ts +400 -333
- package/src/compiler/server-only.ts +190 -151
- package/src/compiler/shared.ts +42 -14
- package/src/compiler/signal-reads.ts +6 -2
- package/src/compiler/ssr-prunelle-tags.ts +27 -14
- package/src/compiler/ssr.ts +220 -89
- package/src/context.ts +34 -0
- package/src/dev/error-log.ts +177 -0
- package/src/dev/host-check.ts +26 -0
- package/src/dev/index.ts +91 -34
- package/src/dev/open-editor.ts +208 -0
- package/src/dev/protocol.ts +3 -0
- package/src/dev/reload.ts +5 -3
- package/src/dev/supervisor.ts +50 -25
- package/src/dev/watchers.ts +74 -13
- package/src/dom/action.ts +47 -21
- package/src/dom/attrs.ts +15 -3
- package/src/dom/extras.ts +29 -14
- package/src/dom/index.ts +39 -10
- package/src/dom/island.ts +54 -35
- package/src/dom/loop.ts +33 -23
- package/src/eco/declaration.ts +257 -0
- package/src/eco/index.ts +65 -0
- package/src/index.ts +2 -2
- package/src/jsx-runtime.ts +2 -2
- package/src/plugins/config.ts +8 -7
- package/src/plugins/context.ts +16 -1
- package/src/plugins/index.ts +2 -2
- package/src/plugins/load.ts +30 -10
- package/src/plugins/order.ts +38 -1
- package/src/plugins/public.ts +6 -3
- package/src/plugins/services.ts +84 -0
- package/src/plugins/types.ts +51 -2
- package/src/reactivity/graph.ts +10 -0
- package/src/reactivity/index.ts +24 -16
- package/src/reactivity/selector.ts +31 -4
- package/src/reactivity/store.ts +45 -13
- package/src/server/action-flash.ts +158 -0
- package/src/server/action-protect.ts +199 -0
- package/src/server/action-registry.ts +1 -1
- package/src/server/action.ts +56 -117
- package/src/server/app-secret.ts +63 -0
- package/src/server/assets.ts +34 -2
- package/src/server/compress.ts +96 -10
- package/src/server/consent.ts +59 -22
- package/src/server/cookies.ts +16 -2
- package/src/server/document.ts +25 -10
- package/src/server/env.ts +14 -0
- package/src/server/errors.ts +305 -65
- package/src/server/form-schema.ts +343 -0
- package/src/server/health.ts +275 -0
- package/src/server/http.ts +177 -38
- package/src/server/index.ts +264 -272
- package/src/server/loader.ts +11 -2
- package/src/server/param-matchers.ts +112 -0
- package/src/server/plugin-host.ts +125 -88
- package/src/server/public.ts +6 -5
- package/src/server/rate-limit.ts +102 -36
- package/src/server/request-body.ts +1 -1
- package/src/server/route-cache.ts +445 -0
- package/src/server/route-table.ts +344 -9
- package/src/server/router.ts +125 -40
- package/src/server/routing.ts +112 -63
- package/src/server/sanitize-html.ts +309 -0
- package/src/server/security.ts +277 -50
- package/src/server/serve-handlers.ts +31 -7
- package/src/server/start.ts +60 -16
- package/src/server/static-dir.ts +87 -11
- package/src/server/stream.ts +68 -27
- package/src/ssr/consent-banner.ts +58 -0
- package/src/ssr/context.ts +105 -7
- package/src/ssr/index.ts +148 -3
- package/src/ssr/navigation.ts +2 -2
- package/src/ssr/region.ts +31 -19
- package/src/style.ts +32 -1
- package/src/test/browser.ts +28 -13
- package/src/test/index.ts +97 -12
- package/src/ts-plugin/diagnostics.ts +505 -0
- package/src/ts-plugin/fixes.ts +364 -0
- package/src/ts-plugin/index.ts +194 -0
- package/templates/_shared/AGENTS.md +2 -2
- package/templates/_shared/gitignore +5 -0
- package/templates/_shared/mcp.json +11 -0
- package/templates/_shared/src/routes/legal.tsx +15 -1
- package/templates/_shared/tsconfig.json +5 -0
- package/templates/app/.env.example +4 -0
- package/templates/app/package.json +2 -1
- package/templates/app/prunelle.config.ts +2 -0
- package/templates/app/src/auth.ts +4 -6
- package/templates/app/src/mail.ts +4 -0
- package/templates/app/src/routes/_layout.tsx +9 -1
- package/templates/app/src/routes/dashboard/index.tsx +42 -8
- package/templates/app/src/routes/login.tsx +49 -30
- package/templates/app/src/routes/privacy.tsx +25 -0
- package/templates/app/src/styles/app.css +8 -1
- package/templates/app/tests/app.test.ts +44 -3
- package/templates/blog/package.json +1 -1
- package/templates/blog/prunelle.config.ts +1 -1
- package/templates/blog/src/routes/_layout.tsx +6 -1
- package/templates/blog/src/routes/index.tsx +5 -1
- package/templates/blog/src/styles/app.css +6 -1
- package/templates/fullstack/package.json +1 -1
- package/templates/fullstack/src/components/GreetForm.tsx +2 -1
- package/templates/fullstack/src/routes/_layout.tsx +4 -0
- package/templates/fullstack/src/styles/app.css +11 -1
- package/templates/minimal/package.json +1 -1
- package/templates/minimal/src/routes/_layout.tsx +4 -0
- package/templates/minimal/src/styles/app.css +11 -1
- package/ts-plugin.cjs +4277 -0
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
// Persists the last dev build error, child crash, and recent runtime errors in an append-only journal, `.prunelle-dev/last-errors.jsonl`,
|
|
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 { appendFileSync, mkdirSync, readFileSync, renameSync, statSync, 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
|
+
/** Past this size the journal is folded back to its current state. */
|
|
26
|
+
const COMPACT_BYTES = 256 * 1024
|
|
27
|
+
|
|
28
|
+
/** One line of the journal: a build or crash message (none clears it), or a runtime error. */
|
|
29
|
+
type JournalRecord =
|
|
30
|
+
| { op: 'build' | 'crash', at: string, message?: string | undefined }
|
|
31
|
+
| { op: 'runtime', at: string, entry: DevErrorEntry }
|
|
32
|
+
|
|
33
|
+
function errorLogPath(root: string): string {
|
|
34
|
+
return join(resolve(root), '.prunelle-dev', 'last-errors.jsonl')
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function isDevErrorEntry(value: unknown): value is DevErrorEntry {
|
|
38
|
+
if (typeof value !== 'object' || value === null)
|
|
39
|
+
return false
|
|
40
|
+
const rec = value as Record<string, unknown>
|
|
41
|
+
return (rec.kind === 'build' || rec.kind === 'runtime' || rec.kind === 'crash')
|
|
42
|
+
&& typeof rec.timestamp === 'string'
|
|
43
|
+
&& typeof rec.message === 'string'
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function parseRecord(line: string): JournalRecord | undefined {
|
|
47
|
+
try {
|
|
48
|
+
const rec = JSON.parse(line) as Record<string, unknown>
|
|
49
|
+
if (typeof rec.at !== 'string')
|
|
50
|
+
return undefined
|
|
51
|
+
if ((rec.op === 'build' || rec.op === 'crash') && (rec.message === undefined || typeof rec.message === 'string'))
|
|
52
|
+
return { op: rec.op, at: rec.at, message: rec.message }
|
|
53
|
+
if (rec.op === 'runtime' && isDevErrorEntry(rec.entry))
|
|
54
|
+
return { op: 'runtime', at: rec.at, entry: rec.entry }
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
// A line cut by a crash is skipped; the rest of the journal still reads.
|
|
58
|
+
return undefined
|
|
59
|
+
}
|
|
60
|
+
return undefined
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Folds the journal lines, in order, into the state they leave. */
|
|
64
|
+
function foldJournal(text: string): DevErrorLog | undefined {
|
|
65
|
+
let log: DevErrorLog | undefined
|
|
66
|
+
for (const line of text.split('\n')) {
|
|
67
|
+
const rec = line === '' ? undefined : parseRecord(line)
|
|
68
|
+
if (rec === undefined)
|
|
69
|
+
continue
|
|
70
|
+
log ??= { updatedAt: rec.at, runtimeErrors: [] }
|
|
71
|
+
log.updatedAt = rec.at
|
|
72
|
+
if (rec.op === 'runtime') {
|
|
73
|
+
log.runtimeErrors.push(rec.entry)
|
|
74
|
+
if (log.runtimeErrors.length > MAX_RUNTIME_ERRORS)
|
|
75
|
+
log.runtimeErrors.shift()
|
|
76
|
+
continue
|
|
77
|
+
}
|
|
78
|
+
const key = rec.op === 'build' ? 'buildError' : 'crashError'
|
|
79
|
+
if (rec.message !== undefined && rec.message.length > 0)
|
|
80
|
+
log[key] = rec.message
|
|
81
|
+
else
|
|
82
|
+
delete log[key]
|
|
83
|
+
}
|
|
84
|
+
return log
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Reads `.prunelle-dev/last-errors.jsonl` safely, returning `undefined` when missing or unreadable. */
|
|
88
|
+
export function readDevErrorLog(root: string): DevErrorLog | undefined {
|
|
89
|
+
try {
|
|
90
|
+
return foldJournal(readFileSync(errorLogPath(root), 'utf8'))
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
return undefined
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** The records that rebuild `log`, for a compacted journal. */
|
|
98
|
+
function recordsOf(log: DevErrorLog): JournalRecord[] {
|
|
99
|
+
return [
|
|
100
|
+
...(log.buildError !== undefined ? [{ op: 'build', at: log.updatedAt, message: log.buildError } as const] : []),
|
|
101
|
+
...(log.crashError !== undefined ? [{ op: 'crash', at: log.updatedAt, message: log.crashError } as const] : []),
|
|
102
|
+
...log.runtimeErrors.map(entry => ({ op: 'runtime', at: entry.timestamp, entry }) as const),
|
|
103
|
+
]
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Appends one record. A short `O_APPEND` write lands whole, so two processes (the supervisor and its child) never overwrite each other.
|
|
108
|
+
* Only a journal past `COMPACT_BYTES` is rewritten, through a temp file.
|
|
109
|
+
*/
|
|
110
|
+
function appendRecord(root: string, rec: JournalRecord): void {
|
|
111
|
+
const file = errorLogPath(root)
|
|
112
|
+
try {
|
|
113
|
+
mkdirSync(dirname(file), { recursive: true })
|
|
114
|
+
appendFileSync(file, `${JSON.stringify(rec)}\n`, 'utf8')
|
|
115
|
+
if (statSync(file).size <= COMPACT_BYTES)
|
|
116
|
+
return
|
|
117
|
+
const log = foldJournal(readFileSync(file, 'utf8'))
|
|
118
|
+
if (log === undefined)
|
|
119
|
+
return
|
|
120
|
+
const tmp = `${file}.${process.pid}.${Date.now()}.tmp`
|
|
121
|
+
writeFileSync(tmp, recordsOf(log).map(r => `${JSON.stringify(r)}\n`).join(''), 'utf8')
|
|
122
|
+
renameSync(tmp, file)
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
// The log is a convenience for `prunelle mcp`; a read-only folder must not take the dev server down.
|
|
126
|
+
return
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Records or clears the active dev build error (passing `undefined` clears it after a successful build). */
|
|
131
|
+
export function recordDevBuildError(root: string, message: string | undefined): void {
|
|
132
|
+
appendRecord(root, { op: 'build', at: new Date().toISOString(), message })
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Records or clears the active dev child crash message (passing `undefined` clears it once the child is ready). */
|
|
136
|
+
export function recordDevCrashError(root: string, message: string | undefined): void {
|
|
137
|
+
appendRecord(root, { op: 'crash', at: new Date().toISOString(), message })
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Appends a runtime error to `.prunelle-dev/last-errors.jsonl`; reading keeps the last 20. */
|
|
141
|
+
export function recordDevRuntimeError(root: string, entry: Omit<DevErrorEntry, 'kind' | 'timestamp'>): void {
|
|
142
|
+
const at = new Date().toISOString()
|
|
143
|
+
appendRecord(root, {
|
|
144
|
+
op: 'runtime',
|
|
145
|
+
at,
|
|
146
|
+
entry: {
|
|
147
|
+
kind: 'runtime',
|
|
148
|
+
timestamp: at,
|
|
149
|
+
message: entry.message,
|
|
150
|
+
...(entry.source !== undefined ? { source: entry.source } : {}),
|
|
151
|
+
...(entry.method !== undefined ? { method: entry.method } : {}),
|
|
152
|
+
...(entry.path !== undefined ? { path: entry.path } : {}),
|
|
153
|
+
},
|
|
154
|
+
})
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function safePathname(rawUrl: string): string {
|
|
158
|
+
try {
|
|
159
|
+
return new URL(rawUrl).pathname
|
|
160
|
+
}
|
|
161
|
+
catch {
|
|
162
|
+
return rawUrl
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Builds an `errorSink` callback for `devServer` that records unhandled runtime errors into `.prunelle-dev/last-errors.json`. */
|
|
167
|
+
export function createDevRuntimeErrorSink(root: string): (info: ServerErrorInfo) => void {
|
|
168
|
+
return (info) => {
|
|
169
|
+
const message = info.error instanceof Error ? info.error.stack ?? info.error.message : String(info.error)
|
|
170
|
+
recordDevRuntimeError(root, {
|
|
171
|
+
message,
|
|
172
|
+
source: info.source,
|
|
173
|
+
method: info.request.method,
|
|
174
|
+
path: safePathname(info.request.url),
|
|
175
|
+
})
|
|
176
|
+
}
|
|
177
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// A DNS-rebinding page reaches a dev server under the page's own domain name, so the dev server answers only the names it can be opened under.
|
|
2
|
+
|
|
3
|
+
const LOOPBACK_NAMES = new Set(['localhost', '127.0.0.1', '[::1]'])
|
|
4
|
+
const IPV4_RE = /^\d{1,3}(?:\.\d{1,3}){3}$/
|
|
5
|
+
|
|
6
|
+
function hostnameOf(host: string): string | undefined {
|
|
7
|
+
return URL.canParse(`http://${host}`) ? new URL(`http://${host}`).hostname : undefined
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/** Refuses with `421` a request whose `Host` is not loopback, `*.localhost`, an IP address, the bound `hostname` or the host of one of `origins`. */
|
|
11
|
+
export function createDevHostCheck(hostname: string | undefined, origins: readonly (string | undefined)[]): (request: Request) => Response | undefined {
|
|
12
|
+
const names = new Set<string>()
|
|
13
|
+
if (hostname !== undefined)
|
|
14
|
+
names.add(hostnameOf(hostname) ?? hostname)
|
|
15
|
+
for (const origin of origins) {
|
|
16
|
+
if (origin !== undefined && URL.canParse(origin))
|
|
17
|
+
names.add(new URL(origin).hostname)
|
|
18
|
+
}
|
|
19
|
+
return (request) => {
|
|
20
|
+
const host = request.headers.get('host') ?? ''
|
|
21
|
+
const name = hostnameOf(host)
|
|
22
|
+
if (name !== undefined && (LOOPBACK_NAMES.has(name) || name.endsWith('.localhost') || name.startsWith('[') || IPV4_RE.test(name) || names.has(name)))
|
|
23
|
+
return undefined
|
|
24
|
+
return new Response(`prunelle dev: refused Host "${name ?? host}": a dev server answers only localhost, an IP address, its --host and the hosts of site and trustedOrigins in prunelle.config.ts, so that a page on another domain cannot reach it by DNS rebinding. Add the origin you open it under to trustedOrigins.\n`, { status: 421, headers: { 'content-type': 'text/plain; charset=utf-8' } })
|
|
25
|
+
}
|
|
26
|
+
}
|
package/src/dev/index.ts
CHANGED
|
@@ -6,14 +6,17 @@ 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 { createDevHostCheck } from './host-check'
|
|
19
|
+
import { handleOpenEditorRequest } from './open-editor'
|
|
17
20
|
import { DEV_CLIENT_IP_HEADER } from './protocol'
|
|
18
21
|
import { createRebuildQueue } from './queue'
|
|
19
22
|
import { buildErrorResponse, createReloadHub, makeDevReloadAssets, withReloadScript } from './reload'
|
|
@@ -37,6 +40,69 @@ export interface DevServerOptions {
|
|
|
37
40
|
|
|
38
41
|
const errorText = (err: unknown): string => err instanceof Error ? err.stack ?? err.message : String(err)
|
|
39
42
|
|
|
43
|
+
/** Removes stale dev build folders (`b*`, `server/`) while keeping `.prunelle-dev/last-errors.jsonl` intact across child recycles. */
|
|
44
|
+
function cleanDevArtifacts(devRoot: string): void {
|
|
45
|
+
if (!existsSync(devRoot))
|
|
46
|
+
return
|
|
47
|
+
for (const entry of readdirSync(devRoot)) {
|
|
48
|
+
if (entry !== 'last-errors.jsonl')
|
|
49
|
+
rmSync(join(devRoot, entry), { recursive: true, force: true })
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function startDevHttpServer(
|
|
54
|
+
options: DevServerOptions,
|
|
55
|
+
maxRequestBodySize: number,
|
|
56
|
+
configPort: number | undefined,
|
|
57
|
+
onFetch: (request: Request, srv: Server<undefined>) => Promise<Response>,
|
|
58
|
+
): { server: Server<undefined>, url: string } {
|
|
59
|
+
const hostname = options.hostname ?? '127.0.0.1'
|
|
60
|
+
const serveOptions = { maxRequestBodySize, fetch: onFetch }
|
|
61
|
+
const server = options.unix !== undefined
|
|
62
|
+
? Bun.serve({ ...serveOptions, unix: options.unix })
|
|
63
|
+
: Bun.serve({ ...serveOptions, port: options.port ?? configPort ?? 3000, hostname, idleTimeout: 30 })
|
|
64
|
+
// `0.0.0.0` is printed as the loopback address a browser on this machine opens.
|
|
65
|
+
const url = options.unix !== undefined ? `unix:${options.unix}` : `http://${hostname === '0.0.0.0' ? '127.0.0.1' : hostname}:${server.port}`
|
|
66
|
+
if (options.unix === undefined)
|
|
67
|
+
console.log(`[prunelle dev] listening on ${url}`)
|
|
68
|
+
return { server, url }
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async function handleAppFetch(
|
|
72
|
+
request: Request,
|
|
73
|
+
srv: Server<undefined>,
|
|
74
|
+
state: {
|
|
75
|
+
root: string
|
|
76
|
+
unix: string | undefined
|
|
77
|
+
checkHost: ((request: Request) => Response | undefined) | undefined
|
|
78
|
+
hub: ReturnType<typeof createReloadHub> | undefined
|
|
79
|
+
reloadAssets: ReturnType<typeof makeDevReloadAssets>
|
|
80
|
+
lastError: string | undefined
|
|
81
|
+
app: PrunelleApp | undefined
|
|
82
|
+
},
|
|
83
|
+
): Promise<Response> {
|
|
84
|
+
const refused = state.checkHost?.(request)
|
|
85
|
+
if (refused !== undefined)
|
|
86
|
+
return refused
|
|
87
|
+
const { pathname } = new URL(request.url)
|
|
88
|
+
if (state.hub !== undefined && pathname === state.reloadAssets.eventsPath) {
|
|
89
|
+
srv.timeout(request, 0)
|
|
90
|
+
return state.hub.events(request)
|
|
91
|
+
}
|
|
92
|
+
if (pathname === state.reloadAssets.openEditorPath)
|
|
93
|
+
return handleOpenEditorRequest(request, state.root)
|
|
94
|
+
if (state.lastError !== undefined)
|
|
95
|
+
return buildErrorResponse(request, state.lastError, state.reloadAssets.script)
|
|
96
|
+
|
|
97
|
+
const remoteIp = state.unix !== undefined ? request.headers.get(DEV_CLIENT_IP_HEADER) ?? undefined : srv.requestIP(request)?.address
|
|
98
|
+
const res = await state.app!.handle(request, remoteIp)
|
|
99
|
+
const ct = res.headers.get('content-type') ?? ''
|
|
100
|
+
const isStreamedHtml = ct.includes('text/html') && request.method !== 'HEAD' && res.body !== null && !res.headers.has('content-length')
|
|
101
|
+
if (ct.includes('text/event-stream') || isStreamedHtml)
|
|
102
|
+
srv.timeout(request, 0)
|
|
103
|
+
return withReloadScript(request, res, state.reloadAssets)
|
|
104
|
+
}
|
|
105
|
+
|
|
40
106
|
export async function devServer(options: DevServerOptions): Promise<{
|
|
41
107
|
url: string
|
|
42
108
|
assetPrefix: string
|
|
@@ -47,8 +113,8 @@ export async function devServer(options: DevServerOptions): Promise<{
|
|
|
47
113
|
const root = resolve(options.root)
|
|
48
114
|
const devRoot = join(root, '.prunelle-dev')
|
|
49
115
|
const initialCfg = await loadConfig(root, { dev: true })
|
|
50
|
-
// Clean stale
|
|
51
|
-
|
|
116
|
+
// Clean stale build folders left behind by a previously killed or recycled dev process, preserving last-errors.jsonl.
|
|
117
|
+
cleanDevArtifacts(devRoot)
|
|
52
118
|
let activeCfg = initialCfg
|
|
53
119
|
let activeAssetPrefix = (initialCfg.assetPrefix ?? '/_pru').replace(/\/$/, '')
|
|
54
120
|
let reloadAssets = makeDevReloadAssets(activeAssetPrefix)
|
|
@@ -56,7 +122,13 @@ export async function devServer(options: DevServerOptions): Promise<{
|
|
|
56
122
|
const modules = createModuleStore(join(devRoot, 'server'))
|
|
57
123
|
const hub = options.broadcast === undefined ? createReloadHub() : undefined
|
|
58
124
|
const broadcast = options.broadcast ?? hub!.broadcast
|
|
59
|
-
|
|
125
|
+
let recycled = false
|
|
126
|
+
const recycle = options.recycle === undefined
|
|
127
|
+
? undefined
|
|
128
|
+
: (reason: RecycleReason) => {
|
|
129
|
+
recycled = true
|
|
130
|
+
options.recycle!(reason)
|
|
131
|
+
}
|
|
60
132
|
const queue = createRebuildQueue(runSingleBuild)
|
|
61
133
|
const watchers = createDevWatchers({
|
|
62
134
|
root,
|
|
@@ -65,7 +137,7 @@ export async function devServer(options: DevServerOptions): Promise<{
|
|
|
65
137
|
routesDir: options.routesDir,
|
|
66
138
|
schedule: kind => kind === 'config' && recycle !== undefined ? recycle('config') : queue.schedule(kind),
|
|
67
139
|
})
|
|
68
|
-
const serverOptions = { root, dev: true, compress: false, ...(options.maxRequestBodySize !== undefined ? { maxRequestBodySize: options.maxRequestBodySize } : {}) }
|
|
140
|
+
const serverOptions = { root, dev: true, devHost: options.hostname ?? '127.0.0.1', compress: false, errorSink: createDevRuntimeErrorSink(root), ...(options.maxRequestBodySize !== undefined ? { maxRequestBodySize: options.maxRequestBodySize } : {}) }
|
|
69
141
|
|
|
70
142
|
let buildNum = 0
|
|
71
143
|
let current: { app: PrunelleApp, outDir: string } | undefined
|
|
@@ -119,6 +191,7 @@ export async function devServer(options: DevServerOptions): Promise<{
|
|
|
119
191
|
return
|
|
120
192
|
}
|
|
121
193
|
lastError = undefined
|
|
194
|
+
recordDevBuildError(root, undefined)
|
|
122
195
|
watchers.syncBuild(buildCache.watchedFiles, manifest.publicFiles)
|
|
123
196
|
if (n > 2)
|
|
124
197
|
rmSync(join(devRoot, `b${n - 2}`), { recursive: true, force: true })
|
|
@@ -131,6 +204,7 @@ export async function devServer(options: DevServerOptions): Promise<{
|
|
|
131
204
|
if (stopped)
|
|
132
205
|
return
|
|
133
206
|
lastError = errorText(err)
|
|
207
|
+
recordDevBuildError(root, lastError)
|
|
134
208
|
console.error(`[prunelle dev] build error:\n${lastError}`)
|
|
135
209
|
// Push reload over SSE so open browser tabs immediately display the error overlay
|
|
136
210
|
broadcast('reload')
|
|
@@ -150,34 +224,14 @@ export async function devServer(options: DevServerOptions): Promise<{
|
|
|
150
224
|
}
|
|
151
225
|
|
|
152
226
|
const runtimeCfg = resolveServerConfig(initialCfg, { maxRequestBodySize: options.maxRequestBodySize })
|
|
153
|
-
|
|
154
|
-
const
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
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}`)
|
|
227
|
+
// Behind the supervisor's socket, the supervisor has checked the Host already.
|
|
228
|
+
const checkHost = options.unix === undefined ? createDevHostCheck(options.hostname, [initialCfg.site, ...initialCfg.trustedOrigins ?? []]) : undefined
|
|
229
|
+
const { server, url } = startDevHttpServer(
|
|
230
|
+
options,
|
|
231
|
+
runtimeCfg.maxRequestBodySize ?? DEFAULT_MAX_REQUEST_BODY_SIZE,
|
|
232
|
+
initialCfg.port,
|
|
233
|
+
(request, srv) => handleAppFetch(request, srv, { root, unix: options.unix, checkHost, hub, reloadAssets, lastError, app: current?.app }),
|
|
234
|
+
)
|
|
181
235
|
let stopPromise: Promise<void> | undefined
|
|
182
236
|
|
|
183
237
|
return {
|
|
@@ -200,7 +254,10 @@ export async function devServer(options: DevServerOptions): Promise<{
|
|
|
200
254
|
catch (err) {
|
|
201
255
|
console.warn(`[prunelle dev] the app failed to dispose: ${errorText(err)}`)
|
|
202
256
|
}
|
|
203
|
-
|
|
257
|
+
if (recycled)
|
|
258
|
+
cleanDevArtifacts(devRoot)
|
|
259
|
+
else
|
|
260
|
+
rmSync(devRoot, { recursive: true, force: true })
|
|
204
261
|
})()
|
|
205
262
|
return stopPromise
|
|
206
263
|
},
|
|
@@ -0,0 +1,208 @@
|
|
|
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
|
+
import { verifyOrigin } from '../server/security'
|
|
7
|
+
|
|
8
|
+
export const OPEN_EDITOR_SUBPATH = 'open-editor'
|
|
9
|
+
|
|
10
|
+
export interface ParsedSourceLoc {
|
|
11
|
+
file: string
|
|
12
|
+
relFile: string
|
|
13
|
+
line: number
|
|
14
|
+
col: number
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const POSITIVE_INT_RE = /^\d+$/
|
|
18
|
+
const BIN_EXT_RE = /\.(?:exe|cmd|bat)$/i
|
|
19
|
+
const MISSING_EDITOR_ERROR = 'Set PRUNELLE_EDITOR or VISUAL to open files on Alt-click.'
|
|
20
|
+
|
|
21
|
+
const VSCODE_EDITORS = new Set(['code', 'code-insiders', 'codium', 'vscodium', 'cursor', 'windsurf'])
|
|
22
|
+
const ZED_EDITORS = new Set(['zed', 'zeditor'])
|
|
23
|
+
const JETBRAINS_EDITORS = new Set(['idea', 'webstorm', 'phpstorm', 'pycharm', 'goland', 'rubymine', 'rider', 'clion', 'datagrip', 'fleet', 'studio'])
|
|
24
|
+
const SUBLIME_HELIX_EDITORS = new Set(['subl', 'sublime_text', 'hx'])
|
|
25
|
+
const TERMINAL_EDITORS = new Set(['vim', 'nvim', 'vi', 'nano', 'emacs', 'emacsclient'])
|
|
26
|
+
|
|
27
|
+
/** Splits an editor command string into argv tokens, honoring single/double quotes without invoking a shell. */
|
|
28
|
+
function splitEditorSpec(spec: string): string[] {
|
|
29
|
+
const tokens: string[] = []
|
|
30
|
+
let current = ''
|
|
31
|
+
let quote: '\'' | '"' | undefined
|
|
32
|
+
let hasToken = false
|
|
33
|
+
|
|
34
|
+
for (let i = 0; i < spec.length; i++) {
|
|
35
|
+
const ch = spec[i]!
|
|
36
|
+
if (quote !== undefined) {
|
|
37
|
+
if (ch === '\\' && quote === '"' && i + 1 < spec.length && (spec[i + 1] === '"' || spec[i + 1] === '\\')) {
|
|
38
|
+
current += spec[++i]!
|
|
39
|
+
}
|
|
40
|
+
else if (ch === quote) {
|
|
41
|
+
quote = undefined
|
|
42
|
+
}
|
|
43
|
+
else {
|
|
44
|
+
current += ch
|
|
45
|
+
}
|
|
46
|
+
continue
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
if (ch === '\'' || ch === '"') {
|
|
50
|
+
quote = ch
|
|
51
|
+
hasToken = true
|
|
52
|
+
continue
|
|
53
|
+
}
|
|
54
|
+
if (ch === '\\' && i + 1 < spec.length && /\s/.test(spec[i + 1]!)) {
|
|
55
|
+
current += spec[++i]!
|
|
56
|
+
hasToken = true
|
|
57
|
+
continue
|
|
58
|
+
}
|
|
59
|
+
if (/\s/.test(ch)) {
|
|
60
|
+
if (hasToken) {
|
|
61
|
+
tokens.push(current)
|
|
62
|
+
current = ''
|
|
63
|
+
hasToken = false
|
|
64
|
+
}
|
|
65
|
+
continue
|
|
66
|
+
}
|
|
67
|
+
current += ch
|
|
68
|
+
hasToken = true
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
if (hasToken)
|
|
72
|
+
tokens.push(current)
|
|
73
|
+
return tokens
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Parses and validates a `relPath:line:col` location, confining it strictly inside `root`. */
|
|
77
|
+
export function parseSourceLoc(raw: string, root: string): ParsedSourceLoc | { error: string, status: 400 | 403 | 404 } {
|
|
78
|
+
const trimmed = raw.trim()
|
|
79
|
+
const lastColon = trimmed.lastIndexOf(':')
|
|
80
|
+
const prevColon = lastColon > 0 ? trimmed.lastIndexOf(':', lastColon - 1) : -1
|
|
81
|
+
if (lastColon <= 0 || prevColon <= 0)
|
|
82
|
+
return { error: 'Invalid source location; expected file:line:col.', status: 400 }
|
|
83
|
+
|
|
84
|
+
const relPart = trimmed.slice(0, prevColon)
|
|
85
|
+
const lineStr = trimmed.slice(prevColon + 1, lastColon)
|
|
86
|
+
const colStr = trimmed.slice(lastColon + 1)
|
|
87
|
+
if (relPart === '' || relPart.includes('\0') || !POSITIVE_INT_RE.test(lineStr) || !POSITIVE_INT_RE.test(colStr))
|
|
88
|
+
return { error: 'Invalid source location; expected file:line:col.', status: 400 }
|
|
89
|
+
|
|
90
|
+
const line = Number.parseInt(lineStr, 10)
|
|
91
|
+
const col = Number.parseInt(colStr, 10)
|
|
92
|
+
if (!Number.isSafeInteger(line) || line < 1 || !Number.isSafeInteger(col) || col < 1)
|
|
93
|
+
return { error: 'Line and column must be positive integers.', status: 400 }
|
|
94
|
+
|
|
95
|
+
const resolvedRoot = resolve(root)
|
|
96
|
+
const file = resolve(resolvedRoot, relPart)
|
|
97
|
+
if (!isInside(resolvedRoot, file))
|
|
98
|
+
return { error: 'Source file is outside the project root.', status: 403 }
|
|
99
|
+
if (!existsSync(file))
|
|
100
|
+
return { error: 'Source file does not exist.', status: 404 }
|
|
101
|
+
|
|
102
|
+
const realRoot = realpathSync(resolvedRoot)
|
|
103
|
+
const realFile = realpathSync(file)
|
|
104
|
+
if (!isInside(realRoot, realFile))
|
|
105
|
+
return { error: 'Source file is outside the project root.', status: 403 }
|
|
106
|
+
|
|
107
|
+
return { file, relFile: relative(resolvedRoot, file).replaceAll('\\', '/'), line, col }
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Builds the argv array to open `loc` in `editorSpec` (supporting `{file}`/`{line}`/`{col}` templates and common editors). */
|
|
111
|
+
export function buildEditorCommand(editorSpec: string, loc: { file: string, line: number, col: number }): string[] {
|
|
112
|
+
const parts = splitEditorSpec(editorSpec.trim())
|
|
113
|
+
if (parts.length === 0)
|
|
114
|
+
return []
|
|
115
|
+
|
|
116
|
+
const lineStr = String(loc.line)
|
|
117
|
+
const colStr = String(loc.col)
|
|
118
|
+
if (parts.some(p => p.includes('{file}') || p.includes('{line}') || p.includes('{col}')))
|
|
119
|
+
return parts.map(p => p.replaceAll('{file}', loc.file).replaceAll('{line}', lineStr).replaceAll('{col}', colStr))
|
|
120
|
+
|
|
121
|
+
const rawBin = parts[0]!.split(/[\\/]/).pop() ?? ''
|
|
122
|
+
const bin = rawBin.toLowerCase().replace(BIN_EXT_RE, '')
|
|
123
|
+
const fileLineCol = `${loc.file}:${lineStr}:${colStr}`
|
|
124
|
+
|
|
125
|
+
if (VSCODE_EDITORS.has(bin))
|
|
126
|
+
return [...parts, '--goto', fileLineCol]
|
|
127
|
+
if (ZED_EDITORS.has(bin) || SUBLIME_HELIX_EDITORS.has(bin))
|
|
128
|
+
return [...parts, fileLineCol]
|
|
129
|
+
if (JETBRAINS_EDITORS.has(bin))
|
|
130
|
+
return [...parts, '--line', lineStr, '--column', colStr, loc.file]
|
|
131
|
+
if (TERMINAL_EDITORS.has(bin))
|
|
132
|
+
return [...parts, `+${lineStr}`, loc.file]
|
|
133
|
+
return [...parts, fileLineCol]
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export interface OpenEditorOptions {
|
|
137
|
+
env?: Record<string, string | undefined> | undefined
|
|
138
|
+
spawn?: ((cmd: string[]) => void) | undefined
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export function openInEditor(
|
|
142
|
+
rawSrc: string,
|
|
143
|
+
root: string,
|
|
144
|
+
options?: OpenEditorOptions,
|
|
145
|
+
): { ok: true, command: string[] } | { ok: false, status: number, error: string } {
|
|
146
|
+
const env = options?.env ?? process.env
|
|
147
|
+
const editor = env.PRUNELLE_EDITOR?.trim() || env.VISUAL?.trim()
|
|
148
|
+
if (!editor)
|
|
149
|
+
return { ok: false, status: 400, error: MISSING_EDITOR_ERROR }
|
|
150
|
+
|
|
151
|
+
const parsed = parseSourceLoc(rawSrc, root)
|
|
152
|
+
if ('error' in parsed)
|
|
153
|
+
return { ok: false, status: parsed.status, error: parsed.error }
|
|
154
|
+
|
|
155
|
+
const command = buildEditorCommand(editor, parsed)
|
|
156
|
+
if (command.length === 0)
|
|
157
|
+
return { ok: false, status: 400, error: MISSING_EDITOR_ERROR }
|
|
158
|
+
|
|
159
|
+
try {
|
|
160
|
+
if (options?.spawn !== undefined) {
|
|
161
|
+
options.spawn(command)
|
|
162
|
+
}
|
|
163
|
+
else {
|
|
164
|
+
const proc = Bun.spawn(command, { cwd: root, stdin: 'ignore', stdout: 'ignore', stderr: 'ignore' })
|
|
165
|
+
proc.unref()
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
catch (err) {
|
|
169
|
+
return {
|
|
170
|
+
ok: false,
|
|
171
|
+
status: 500,
|
|
172
|
+
error: `Failed to launch editor "${command[0]}": ${err instanceof Error ? err.message : String(err)}`,
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
return { ok: true, command }
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Handles `POST /_pru/open-editor` from the dev server's Alt-click listener: a same-origin JSON body only, so another site cannot open the editor with a form or a no-cors fetch. */
|
|
180
|
+
export async function handleOpenEditorRequest(
|
|
181
|
+
request: Request,
|
|
182
|
+
root: string,
|
|
183
|
+
options?: OpenEditorOptions,
|
|
184
|
+
): Promise<Response> {
|
|
185
|
+
if (request.method !== 'POST')
|
|
186
|
+
return Response.json({ ok: false, error: 'Method Not Allowed' }, { status: 405, headers: { allow: 'POST' } })
|
|
187
|
+
const originCheck = verifyOrigin(request)
|
|
188
|
+
if (!originCheck.ok)
|
|
189
|
+
return Response.json({ ok: false, error: originCheck.reason }, { status: 403 })
|
|
190
|
+
if (!(request.headers.get('content-type') ?? '').startsWith('application/json'))
|
|
191
|
+
return Response.json({ ok: false, error: 'Expected content-type: application/json.' }, { status: 415 })
|
|
192
|
+
|
|
193
|
+
let rawSrc = ''
|
|
194
|
+
try {
|
|
195
|
+
const body = await request.json() as unknown
|
|
196
|
+
if (body !== null && typeof body === 'object' && typeof (body as { src?: unknown }).src === 'string')
|
|
197
|
+
rawSrc = (body as { src: string }).src
|
|
198
|
+
}
|
|
199
|
+
catch {
|
|
200
|
+
return Response.json({ ok: false, error: 'Invalid JSON body; expected { "src": "file:line:col" }.' }, { status: 400 })
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
if (rawSrc.trim() === '')
|
|
204
|
+
return Response.json({ ok: false, error: 'Missing "src" location.' }, { status: 400 })
|
|
205
|
+
|
|
206
|
+
const result = openInEditor(rawSrc, root, options)
|
|
207
|
+
return Response.json(result, { status: result.ok ? 200 : result.status })
|
|
208
|
+
}
|
package/src/dev/protocol.ts
CHANGED
|
@@ -12,6 +12,9 @@ export interface DevChildOptions {
|
|
|
12
12
|
root: string
|
|
13
13
|
routesDir?: string | undefined
|
|
14
14
|
unix: string
|
|
15
|
+
/** The address the parent binds, which the app's plugins see as `api.devExposed`. */
|
|
16
|
+
hostname?: string | undefined
|
|
17
|
+
maxRequestBodySize?: number | undefined
|
|
15
18
|
maxRssMb?: number | undefined
|
|
16
19
|
}
|
|
17
20
|
|
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
|
|
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 {
|