prunelle 0.0.0-stage → 0.7.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.
Files changed (222) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +245 -0
  3. package/package.json +62 -4
  4. package/src/a11y/declaration.ts +373 -0
  5. package/src/a11y/index.ts +477 -0
  6. package/src/a11y/rgaa-map.ts +230 -0
  7. package/src/ambient.d.ts +6 -0
  8. package/src/attrs.ts +43 -0
  9. package/src/build/bundle.ts +661 -0
  10. package/src/build/byte-size.ts +11 -0
  11. package/src/build/carry.ts +57 -0
  12. package/src/build/client-entries.ts +107 -0
  13. package/src/build/client-plugin.ts +175 -0
  14. package/src/build/client-prune.ts +168 -0
  15. package/src/build/compile.ts +130 -0
  16. package/src/build/ecoindex.ts +238 -0
  17. package/src/build/files.ts +171 -0
  18. package/src/build/first-load.ts +235 -0
  19. package/src/build/graph.ts +237 -0
  20. package/src/build/index.ts +678 -0
  21. package/src/build/is-inside.ts +12 -0
  22. package/src/build/island-promote.ts +311 -0
  23. package/src/build/islands.ts +452 -0
  24. package/src/build/manifest.ts +204 -0
  25. package/src/build/output.ts +81 -0
  26. package/src/build/plugin-host.ts +294 -0
  27. package/src/build/precompress.ts +139 -0
  28. package/src/build/prerender.ts +288 -0
  29. package/src/build/reach.ts +200 -0
  30. package/src/build/render-rules.ts +205 -0
  31. package/src/build/report.ts +290 -0
  32. package/src/build/resolve.ts +52 -0
  33. package/src/build/routes.ts +342 -0
  34. package/src/build/server-entry.ts +38 -0
  35. package/src/build/static-headers.ts +112 -0
  36. package/src/build/static.ts +209 -0
  37. package/src/build/status-pages.ts +127 -0
  38. package/src/build/style-bundles.ts +526 -0
  39. package/src/cli/check-forms.ts +636 -0
  40. package/src/cli/check-imports.ts +31 -0
  41. package/src/cli/check-links.ts +632 -0
  42. package/src/cli/check-security.ts +64 -0
  43. package/src/cli/check.ts +409 -0
  44. package/src/cli/commands.ts +372 -0
  45. package/src/cli/docs.ts +403 -0
  46. package/src/cli/index.ts +70 -0
  47. package/src/cli/inspect.ts +406 -0
  48. package/src/cli/mcp-tools.ts +492 -0
  49. package/src/cli/mcp.ts +205 -0
  50. package/src/cli/new.ts +52 -0
  51. package/src/cli/render.ts +416 -0
  52. package/src/cli/upgrade-names.ts +209 -0
  53. package/src/cli/upgrade.ts +367 -0
  54. package/src/compiler/analyze.ts +651 -0
  55. package/src/compiler/ast.ts +82 -0
  56. package/src/compiler/browser-globals.ts +250 -0
  57. package/src/compiler/cacheability-private.ts +566 -0
  58. package/src/compiler/cacheability.ts +335 -0
  59. package/src/compiler/compliance-eco.ts +71 -0
  60. package/src/compiler/compliance-rgaa.ts +614 -0
  61. package/src/compiler/compliance-urls.ts +148 -0
  62. package/src/compiler/compliance.ts +653 -0
  63. package/src/compiler/data-keys.ts +302 -0
  64. package/src/compiler/dev-source.ts +87 -0
  65. package/src/compiler/dom-attrs.ts +452 -0
  66. package/src/compiler/dom.ts +641 -0
  67. package/src/compiler/emit.ts +131 -0
  68. package/src/compiler/expr-context.ts +587 -0
  69. package/src/compiler/foreign-imports.ts +88 -0
  70. package/src/compiler/index.ts +8 -0
  71. package/src/compiler/interactivity.ts +366 -0
  72. package/src/compiler/mistakes.ts +520 -0
  73. package/src/compiler/node-env.ts +50 -0
  74. package/src/compiler/patch.ts +97 -0
  75. package/src/compiler/props-body.ts +60 -0
  76. package/src/compiler/props.ts +511 -0
  77. package/src/compiler/scope.ts +635 -0
  78. package/src/compiler/server-only.ts +365 -0
  79. package/src/compiler/shared.ts +397 -0
  80. package/src/compiler/signal-reads.ts +246 -0
  81. package/src/compiler/slots.ts +227 -0
  82. package/src/compiler/spread-handlers.ts +295 -0
  83. package/src/compiler/ssr-helpers.ts +555 -0
  84. package/src/compiler/ssr-island.ts +90 -0
  85. package/src/compiler/ssr-prunelle-tags.ts +69 -0
  86. package/src/compiler/ssr.ts +525 -0
  87. package/src/context.ts +199 -0
  88. package/src/dev/child.ts +30 -0
  89. package/src/dev/error-log.ts +177 -0
  90. package/src/dev/host-check.ts +32 -0
  91. package/src/dev/index.ts +268 -0
  92. package/src/dev/modules.ts +68 -0
  93. package/src/dev/open-editor.ts +228 -0
  94. package/src/dev/protocol.ts +24 -0
  95. package/src/dev/queue.ts +79 -0
  96. package/src/dev/reload.ts +159 -0
  97. package/src/dev/supervisor.ts +212 -0
  98. package/src/dev/watchers.ts +276 -0
  99. package/src/dom/action.ts +187 -0
  100. package/src/dom/attrs.ts +84 -0
  101. package/src/dom/claim.ts +120 -0
  102. package/src/dom/extras.ts +579 -0
  103. package/src/dom/index.ts +329 -0
  104. package/src/dom/island.ts +318 -0
  105. package/src/dom/loop.ts +484 -0
  106. package/src/dom/revive.ts +36 -0
  107. package/src/eco/declaration.ts +328 -0
  108. package/src/eco/index.ts +69 -0
  109. package/src/index.ts +22 -0
  110. package/src/jsx-runtime.ts +566 -0
  111. package/src/plugins/config.ts +92 -0
  112. package/src/plugins/context.ts +109 -0
  113. package/src/plugins/index.ts +14 -0
  114. package/src/plugins/load.ts +90 -0
  115. package/src/plugins/order.ts +148 -0
  116. package/src/plugins/public.ts +15 -0
  117. package/src/plugins/requires.ts +47 -0
  118. package/src/plugins/services.ts +119 -0
  119. package/src/plugins/types.ts +278 -0
  120. package/src/reactivity/graph.ts +259 -0
  121. package/src/reactivity/index.ts +541 -0
  122. package/src/reactivity/selector.ts +78 -0
  123. package/src/reactivity/store.ts +252 -0
  124. package/src/server/action-flash.ts +158 -0
  125. package/src/server/action-protect.ts +199 -0
  126. package/src/server/action-registry.ts +78 -0
  127. package/src/server/action.ts +511 -0
  128. package/src/server/app-entry.ts +23 -0
  129. package/src/server/app-secret.ts +63 -0
  130. package/src/server/assets.ts +168 -0
  131. package/src/server/compress.ts +646 -0
  132. package/src/server/consent.ts +290 -0
  133. package/src/server/cookies.ts +153 -0
  134. package/src/server/document.ts +286 -0
  135. package/src/server/env.ts +47 -0
  136. package/src/server/errors.ts +396 -0
  137. package/src/server/form-schema.ts +337 -0
  138. package/src/server/health.ts +275 -0
  139. package/src/server/http.ts +588 -0
  140. package/src/server/index.ts +615 -0
  141. package/src/server/lifecycle.ts +75 -0
  142. package/src/server/loader.ts +131 -0
  143. package/src/server/page.ts +122 -0
  144. package/src/server/param-matchers.ts +112 -0
  145. package/src/server/plugin-host.ts +267 -0
  146. package/src/server/prerendered.ts +71 -0
  147. package/src/server/public.ts +20 -0
  148. package/src/server/rate-limit.ts +199 -0
  149. package/src/server/region.ts +96 -0
  150. package/src/server/request-body.ts +27 -0
  151. package/src/server/request-path.ts +73 -0
  152. package/src/server/request-scope.ts +22 -0
  153. package/src/server/route-cache.ts +541 -0
  154. package/src/server/route-table.ts +424 -0
  155. package/src/server/router.ts +261 -0
  156. package/src/server/routing.ts +388 -0
  157. package/src/server/sanitize-html.ts +309 -0
  158. package/src/server/security.ts +550 -0
  159. package/src/server/serve-handlers.ts +93 -0
  160. package/src/server/served-file.ts +128 -0
  161. package/src/server/standard-schema.ts +104 -0
  162. package/src/server/start.ts +143 -0
  163. package/src/server/static-dir.ts +246 -0
  164. package/src/server/stream.ts +233 -0
  165. package/src/ssr/consent-banner.ts +58 -0
  166. package/src/ssr/context.ts +399 -0
  167. package/src/ssr/index.ts +624 -0
  168. package/src/ssr/navigation.ts +96 -0
  169. package/src/ssr/region.ts +192 -0
  170. package/src/style.ts +96 -0
  171. package/src/test/browser.ts +201 -0
  172. package/src/test/index.ts +262 -0
  173. package/src/ts-plugin/diagnostics.ts +505 -0
  174. package/src/ts-plugin/fixes.ts +364 -0
  175. package/src/ts-plugin/index.ts +194 -0
  176. package/src/unrenderable.ts +35 -0
  177. package/templates/_shared/AGENTS.md +10 -0
  178. package/templates/_shared/CLAUDE.md +1 -0
  179. package/templates/_shared/gitignore +8 -0
  180. package/templates/_shared/mcp.json +11 -0
  181. package/templates/_shared/public/robots.txt +2 -0
  182. package/templates/_shared/src/routes/legal.tsx +22 -0
  183. package/templates/_shared/tsconfig.json +25 -0
  184. package/templates/app/.env.example +8 -0
  185. package/templates/app/package.json +22 -0
  186. package/templates/app/prunelle.config.ts +13 -0
  187. package/templates/app/src/auth.ts +12 -0
  188. package/templates/app/src/mail.ts +4 -0
  189. package/templates/app/src/routes/_layout.tsx +40 -0
  190. package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
  191. package/templates/app/src/routes/dashboard/index.tsx +47 -0
  192. package/templates/app/src/routes/index.tsx +15 -0
  193. package/templates/app/src/routes/login.tsx +53 -0
  194. package/templates/app/src/routes/privacy.tsx +25 -0
  195. package/templates/app/src/styles/app.css +14 -0
  196. package/templates/app/tests/app.test.ts +73 -0
  197. package/templates/blog/content/posts/welcome.md +9 -0
  198. package/templates/blog/package.json +22 -0
  199. package/templates/blog/prunelle.config.ts +23 -0
  200. package/templates/blog/src/posts.ts +26 -0
  201. package/templates/blog/src/routes/_layout.tsx +25 -0
  202. package/templates/blog/src/routes/blog/[slug].tsx +31 -0
  203. package/templates/blog/src/routes/index.tsx +33 -0
  204. package/templates/blog/src/styles/app.css +15 -0
  205. package/templates/fullstack/package.json +19 -0
  206. package/templates/fullstack/prunelle.config.ts +6 -0
  207. package/templates/fullstack/src/actions/greet.ts +19 -0
  208. package/templates/fullstack/src/components/Counter.tsx +10 -0
  209. package/templates/fullstack/src/components/GreetForm.tsx +28 -0
  210. package/templates/fullstack/src/routes/_layout.tsx +18 -0
  211. package/templates/fullstack/src/routes/api/health.ts +5 -0
  212. package/templates/fullstack/src/routes/index.tsx +13 -0
  213. package/templates/fullstack/src/styles/app.css +39 -0
  214. package/templates/fullstack/tests/app.test.ts +37 -0
  215. package/templates/minimal/package.json +19 -0
  216. package/templates/minimal/prunelle.config.ts +6 -0
  217. package/templates/minimal/src/components/Counter.tsx +10 -0
  218. package/templates/minimal/src/routes/_layout.tsx +18 -0
  219. package/templates/minimal/src/routes/index.tsx +11 -0
  220. package/templates/minimal/src/styles/app.css +32 -0
  221. package/ts-plugin.cjs +4277 -0
  222. package/README.md +0 -3
@@ -0,0 +1,268 @@
1
+ // prunelle dev: incremental cached rebuilds, serialized rebuild queue, CSS hot-swap, streaming reload injection,
2
+ // SSE error push, and live config reload.
3
+
4
+ import type { Server } from 'bun'
5
+ import type { BuildCacheStats } from '../build/graph'
6
+ import type { PrunelleApp } from '../server/index'
7
+ import type { TrustProxy } from '../server/security'
8
+ import type { RecycleReason } from './protocol'
9
+ import type { PendingBuild } from './queue'
10
+ import { existsSync, readdirSync, rmSync } from 'node:fs'
11
+ import { join, resolve } from 'node:path'
12
+ import { clearBuildCache } from '../build/graph'
13
+ import { build, createBuildCache } from '../build/index'
14
+ import { loadConfig, resolveServerConfig } from '../plugins/index'
15
+ import { DEFAULT_MAX_REQUEST_BODY_SIZE } from '../server/http'
16
+ import { createServer } from '../server/index'
17
+ import { createDevRuntimeErrorSink, recordDevBuildError } from './error-log'
18
+ import { createModuleStore } from './modules'
19
+ import { createDevHostCheck } from './host-check'
20
+ import { handleOpenEditorRequest } from './open-editor'
21
+ import { DEV_CLIENT_IP_HEADER } from './protocol'
22
+ import { createRebuildQueue } from './queue'
23
+ import { buildErrorResponse, createReloadHub, makeDevReloadAssets, withReloadScript } from './reload'
24
+ import { createDevWatchers } from './watchers'
25
+
26
+
27
+ export interface DevServerOptions {
28
+ root: string
29
+ port?: number | undefined
30
+ hostname?: string | undefined
31
+ routesDir?: string | undefined
32
+ maxRequestBodySize?: number | undefined
33
+ /** Listens on this Unix socket instead of a port, behind a parent that keeps the port and sets {@link DEV_CLIENT_IP_HEADER}. */
34
+ unix?: string | undefined
35
+ /** Receives each reload event instead of a stream this server serves. */
36
+ broadcast?: ((payload: string) => void) | undefined
37
+ /** Called instead of reloading `prunelle.config.ts` in place, on an edit to it or to a file it imports, and once the RSS passes `maxRssMb` after a build. */
38
+ recycle?: ((reason: RecycleReason) => void) | undefined
39
+ maxRssMb?: number | undefined
40
+ }
41
+
42
+ const errorText = (err: unknown): string => err instanceof Error ? err.stack ?? err.message : String(err)
43
+
44
+ /** Removes stale dev build folders (`b*`, `server/`) while keeping `.prunelle-dev/last-errors.jsonl` intact across child recycles. */
45
+ function cleanDevArtifacts(devRoot: string): void {
46
+ if (!existsSync(devRoot))
47
+ return
48
+ for (const entry of readdirSync(devRoot)) {
49
+ if (entry !== 'last-errors.jsonl')
50
+ rmSync(join(devRoot, entry), { recursive: true, force: true })
51
+ }
52
+ }
53
+
54
+ function startDevHttpServer(
55
+ options: DevServerOptions,
56
+ maxRequestBodySize: number,
57
+ configPort: number | undefined,
58
+ onFetch: (request: Request, srv: Server<undefined>) => Promise<Response>,
59
+ ): { server: Server<undefined>, url: string } {
60
+ const hostname = options.hostname ?? '127.0.0.1'
61
+ const serveOptions = { maxRequestBodySize, fetch: onFetch }
62
+ const server = options.unix !== undefined
63
+ ? Bun.serve({ ...serveOptions, unix: options.unix })
64
+ : Bun.serve({ ...serveOptions, port: options.port ?? configPort ?? 3000, hostname, idleTimeout: 30 })
65
+ // `0.0.0.0` is printed as the loopback address a browser on this machine opens.
66
+ const url = options.unix !== undefined ? `unix:${options.unix}` : `http://${hostname === '0.0.0.0' ? '127.0.0.1' : hostname}:${server.port}`
67
+ if (options.unix === undefined)
68
+ console.log(`[prunelle dev] listening on ${url}`)
69
+ return { server, url }
70
+ }
71
+
72
+ async function handleAppFetch(
73
+ request: Request,
74
+ srv: Server<undefined>,
75
+ state: {
76
+ root: string
77
+ unix: string | undefined
78
+ checkHost: ((request: Request) => Response | undefined) | undefined
79
+ hub: ReturnType<typeof createReloadHub> | undefined
80
+ reloadAssets: ReturnType<typeof makeDevReloadAssets>
81
+ lastError: string | undefined
82
+ app: PrunelleApp | undefined
83
+ trustedOrigins: readonly string[] | undefined
84
+ trustProxy: TrustProxy | undefined
85
+ },
86
+ ): Promise<Response> {
87
+ const refused = state.checkHost?.(request)
88
+ if (refused !== undefined)
89
+ return refused
90
+ const { pathname } = new URL(request.url)
91
+ if (state.hub !== undefined && pathname === state.reloadAssets.eventsPath) {
92
+ srv.timeout(request, 0)
93
+ return state.hub.events(request)
94
+ }
95
+ const remoteIp = state.unix !== undefined ? request.headers.get(DEV_CLIENT_IP_HEADER) ?? undefined : srv.requestIP(request)?.address
96
+ if (pathname === state.reloadAssets.openEditorPath)
97
+ return handleOpenEditorRequest(request, state.root, { trustedOrigins: state.trustedOrigins, trustProxy: state.trustProxy, remoteIp: remoteIp ?? '' })
98
+ if (state.lastError !== undefined)
99
+ return buildErrorResponse(request, state.lastError, state.reloadAssets.script)
100
+
101
+ const res = await state.app!.handle(request, remoteIp)
102
+ const ct = res.headers.get('content-type') ?? ''
103
+ const isStreamedHtml = ct.includes('text/html') && request.method !== 'HEAD' && res.body !== null && !res.headers.has('content-length')
104
+ if (ct.includes('text/event-stream') || isStreamedHtml)
105
+ srv.timeout(request, 0)
106
+ return withReloadScript(request, res, state.reloadAssets)
107
+ }
108
+
109
+ export async function devServer(options: DevServerOptions): Promise<{
110
+ url: string
111
+ assetPrefix: string
112
+ stop: () => Promise<void>
113
+ rebuild: () => Promise<void>
114
+ stats: () => BuildCacheStats
115
+ }> {
116
+ const root = resolve(options.root)
117
+ const devRoot = join(root, '.prunelle-dev')
118
+ const initialCfg = await loadConfig(root, { dev: true })
119
+ // Clean stale build folders left behind by a previously killed or recycled dev process, preserving last-errors.jsonl.
120
+ cleanDevArtifacts(devRoot)
121
+ let activeCfg = initialCfg
122
+ let activeAssetPrefix = (initialCfg.assetPrefix ?? '/_pru').replace(/\/$/, '')
123
+ let reloadAssets = makeDevReloadAssets(activeAssetPrefix)
124
+ const buildCache = createBuildCache()
125
+ const modules = createModuleStore(join(devRoot, 'server'))
126
+ const hub = options.broadcast === undefined ? createReloadHub() : undefined
127
+ const broadcast = options.broadcast ?? hub!.broadcast
128
+ let recycled = false
129
+ const recycle = options.recycle === undefined
130
+ ? undefined
131
+ : (reason: RecycleReason) => {
132
+ recycled = true
133
+ options.recycle!(reason)
134
+ }
135
+ const queue = createRebuildQueue(runSingleBuild)
136
+ const watchers = createDevWatchers({
137
+ root,
138
+ devRoot,
139
+ srcDir: resolve(root, 'src'),
140
+ routesDir: options.routesDir,
141
+ schedule: kind => kind === 'config' && recycle !== undefined ? recycle('config') : queue.schedule(kind),
142
+ })
143
+ const serverOptions = { root, dev: true, devHost: options.hostname ?? '127.0.0.1', compress: false, errorSink: createDevRuntimeErrorSink(root), ...(options.maxRequestBodySize !== undefined ? { maxRequestBodySize: options.maxRequestBodySize } : {}) }
144
+
145
+ let buildNum = 0
146
+ let current: { app: PrunelleApp, outDir: string } | undefined
147
+ let lastError: string | undefined
148
+ let stopped = false
149
+
150
+ async function swapApp(outDir: string): Promise<void> {
151
+ const nextApp = await createServer({ ...serverOptions, outDir, importModule: modules.importFrom(join(root, outDir, 'server')) })
152
+ if (stopped) {
153
+ await nextApp.dispose?.()
154
+ return
155
+ }
156
+ const prev = current?.app
157
+ current = { app: nextApp, outDir }
158
+ await prev?.dispose?.()
159
+ }
160
+
161
+ async function runSingleBuild({ cssOnly, publicOnly, resetCache, reloadAll }: PendingBuild): Promise<void> {
162
+ if (stopped)
163
+ return
164
+ const hadError = lastError !== undefined
165
+ const hadApp = current !== undefined
166
+ const n = buildNum + 1
167
+ const outDir = `.prunelle-dev/b${n}`
168
+ const t0 = performance.now()
169
+ try {
170
+ // An edited `public/` file only needs the app's file table, and its ETag, built again.
171
+ if (publicOnly && current !== undefined && !hadError) {
172
+ await swapApp(current.outDir)
173
+ broadcast('reload')
174
+ return
175
+ }
176
+ buildNum = n
177
+ if (resetCache) {
178
+ clearBuildCache(buildCache)
179
+ activeCfg = await loadConfig(root, { fresh: true, dev: true })
180
+ activeAssetPrefix = (activeCfg.assetPrefix ?? '/_pru').replace(/\/$/, '')
181
+ reloadAssets = makeDevReloadAssets(activeAssetPrefix)
182
+ watchers.syncStatic(activeCfg)
183
+ watchers.refreshPlugins(activeCfg, activeAssetPrefix)
184
+ }
185
+ if (reloadAll)
186
+ modules.reloadAll()
187
+ const manifest = await build({ root, routesDir: options.routesDir, outDir, minify: false, prerender: false, copyPublic: false, dev: true, cache: buildCache })
188
+ if (!stopped) {
189
+ modules.sync(join(root, outDir, 'server'))
190
+ await swapApp(outDir)
191
+ }
192
+ if (stopped) {
193
+ rmSync(join(root, outDir), { recursive: true, force: true })
194
+ return
195
+ }
196
+ lastError = undefined
197
+ recordDevBuildError(root, undefined)
198
+ watchers.syncBuild(buildCache.watchedFiles, manifest.publicFiles)
199
+ if (n > 2)
200
+ rmSync(join(devRoot, `b${n - 2}`), { recursive: true, force: true })
201
+ console.log(`[prunelle dev] rebuilt in ${(performance.now() - t0).toFixed(1)} ms`)
202
+ broadcast(cssOnly && hadApp && !hadError && manifest.styles.length > 0 ? `css:${JSON.stringify(manifest.styles)}` : 'reload')
203
+ if (n > 1 && recycle !== undefined && options.maxRssMb !== undefined && process.memoryUsage().rss > options.maxRssMb * 1024 * 1024)
204
+ recycle('memory')
205
+ }
206
+ catch (err) {
207
+ if (stopped)
208
+ return
209
+ lastError = errorText(err)
210
+ recordDevBuildError(root, lastError)
211
+ console.error(`[prunelle dev] build error:\n${lastError}`)
212
+ // Push reload over SSE so open browser tabs immediately display the error overlay
213
+ broadcast('reload')
214
+ }
215
+ }
216
+
217
+ await queue.now()
218
+
219
+ watchers.syncStatic(initialCfg)
220
+ watchers.watchRoot(() => activeCfg, recycle !== undefined)
221
+ // Plugin-declared extra paths (e.g. content/ or messages/ directories); refreshed on prunelle.config.ts edits.
222
+ try {
223
+ watchers.refreshPlugins(initialCfg, activeAssetPrefix)
224
+ }
225
+ catch (err) {
226
+ console.warn(`[prunelle dev] could not attach plugin watchers: ${err instanceof Error ? err.message : String(err)}`)
227
+ }
228
+
229
+ const runtimeCfg = resolveServerConfig(initialCfg, { maxRequestBodySize: options.maxRequestBodySize })
230
+ // Behind the supervisor's socket, the supervisor has checked the Host already.
231
+ const checkHost = options.unix === undefined ? createDevHostCheck(options.hostname, [initialCfg.site, ...initialCfg.trustedOrigins ?? []]) : undefined
232
+ const { server, url } = startDevHttpServer(
233
+ options,
234
+ runtimeCfg.maxRequestBodySize ?? DEFAULT_MAX_REQUEST_BODY_SIZE,
235
+ initialCfg.port,
236
+ (request, srv) => handleAppFetch(request, srv, { root, unix: options.unix, checkHost, hub, reloadAssets, lastError, app: current?.app, trustedOrigins: activeCfg.trustedOrigins, trustProxy: activeCfg.trustProxy }),
237
+ )
238
+ let stopPromise: Promise<void> | undefined
239
+
240
+ return {
241
+ url,
242
+ assetPrefix: activeAssetPrefix,
243
+ rebuild: () => queue.now(),
244
+ stats: () => ({ ...buildCache.stats }),
245
+ stop() {
246
+ if (stopPromise !== undefined)
247
+ return stopPromise
248
+ stopped = true
249
+ hub?.close()
250
+ watchers.close()
251
+ server.stop(true)
252
+ stopPromise = (async () => {
253
+ await queue.stop()
254
+ try {
255
+ await current?.app.dispose?.()
256
+ }
257
+ catch (err) {
258
+ console.warn(`[prunelle dev] the app failed to dispose: ${errorText(err)}`)
259
+ }
260
+ if (recycled)
261
+ cleanDevArtifacts(devRoot)
262
+ else
263
+ rmSync(devRoot, { recursive: true, force: true })
264
+ })()
265
+ return stopPromise
266
+ },
267
+ }
268
+ }
@@ -0,0 +1,68 @@
1
+ // prunelle dev's module store: each build's server files, copied so an unchanged chunk keeps its loaded instance.
2
+
3
+ import { mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
4
+ import { dirname, join, relative } from 'node:path'
5
+
6
+ // Bun never unloads a module, so each build's server files are copied into a generation store.
7
+ // Only `_entry.js` is imported, with its hash: the code lives in content-named chunks, so an unchanged chunk keeps its loaded instance across saves.
8
+ // A failed import starts a new generation, since Bun keeps a module that failed to evaluate.
9
+ export function createModuleStore(storeRoot: string) {
10
+ const hashes = new Map<string, string>()
11
+ let generation = 0
12
+ let stale = false
13
+ const generationDir = (g: number): string => join(storeRoot, `g${g}`)
14
+ return {
15
+ reloadAll(): void {
16
+ stale = true
17
+ },
18
+ sync(serverDir: string): void {
19
+ const nextFiles = new Map<string, { bytes: Buffer, hash: string }>()
20
+ for (const entry of readdirSync(serverDir, { recursive: true, withFileTypes: true })) {
21
+ if (!entry.isFile())
22
+ continue
23
+ const from = join(entry.parentPath, entry.name)
24
+ const rel = relative(serverDir, from).replaceAll('\\', '/')
25
+ const bytes = readFileSync(from)
26
+ const hash = Bun.hash(bytes).toString(36)
27
+ nextFiles.set(rel, { bytes, hash })
28
+ }
29
+
30
+ if (stale) {
31
+ stale = false
32
+ hashes.clear()
33
+ generation++
34
+ // The previous generation stays for requests the old app is still serving.
35
+ rmSync(generationDir(generation - 2), { recursive: true, force: true })
36
+ }
37
+ const storeDir = generationDir(generation)
38
+ for (const [rel, { bytes, hash }] of nextFiles) {
39
+ if (hashes.get(rel) === hash)
40
+ continue
41
+ const to = join(storeDir, rel)
42
+ mkdirSync(dirname(to), { recursive: true })
43
+ writeFileSync(to, bytes)
44
+ hashes.set(rel, hash)
45
+ }
46
+ // Prune removed chunk files from current generation to avoid unbounded disk/map growth.
47
+ for (const rel of [...hashes.keys()]) {
48
+ if (!nextFiles.has(rel)) {
49
+ hashes.delete(rel)
50
+ rmSync(join(storeDir, rel), { force: true })
51
+ }
52
+ }
53
+ },
54
+ importFrom(serverDir: string) {
55
+ const storeDir = generationDir(generation)
56
+ return async (path: string): Promise<Record<string, unknown>> => {
57
+ const rel = relative(serverDir, path).replaceAll('\\', '/')
58
+ try {
59
+ return await import(`${join(storeDir, rel)}?v=${hashes.get(rel)}`)
60
+ }
61
+ catch (err) {
62
+ stale = true
63
+ throw err
64
+ }
65
+ }
66
+ },
67
+ }
68
+ }
@@ -0,0 +1,228 @@
1
+ // Opens a project source file at `line:col` in `$PRUNELLE_EDITOR` or `$VISUAL` on Alt-click in `prunelle dev`.
2
+
3
+ import type { TrustProxy } from '../server/security'
4
+ import { existsSync, realpathSync } from 'node:fs'
5
+ import { relative, resolve } from 'node:path'
6
+ import { isInside } from '../build/is-inside'
7
+ import { verifyOrigin } from '../server/security'
8
+
9
+ export const OPEN_EDITOR_SUBPATH = 'open-editor'
10
+
11
+ export interface ParsedSourceLoc {
12
+ file: string
13
+ relFile: string
14
+ line: number
15
+ col: number
16
+ }
17
+
18
+ const POSITIVE_INT_RE = /^\d+$/
19
+ const BIN_EXT_RE = /\.(?:exe|cmd|bat)$/i
20
+ const MISSING_EDITOR_ERROR = 'Set PRUNELLE_EDITOR or VISUAL to open files on Alt-click.'
21
+
22
+ const VSCODE_EDITORS = new Set(['code', 'code-insiders', 'codium', 'vscodium', 'cursor', 'windsurf'])
23
+ const ZED_EDITORS = new Set(['zed', 'zeditor'])
24
+ const JETBRAINS_EDITORS = new Set(['idea', 'webstorm', 'phpstorm', 'pycharm', 'goland', 'rubymine', 'rider', 'clion', 'datagrip', 'fleet', 'studio'])
25
+ const SUBLIME_HELIX_EDITORS = new Set(['subl', 'sublime_text', 'hx'])
26
+ const TERMINAL_EDITORS = new Set(['vim', 'nvim', 'vi', 'nano', 'emacs', 'emacsclient'])
27
+
28
+ /** Splits an editor command string into argv tokens, honoring single/double quotes without invoking a shell. */
29
+ function splitEditorSpec(spec: string): string[] {
30
+ const tokens: string[] = []
31
+ let current = ''
32
+ let quote: '\'' | '"' | undefined
33
+ let hasToken = false
34
+
35
+ for (let i = 0; i < spec.length; i++) {
36
+ const ch = spec[i]!
37
+ if (quote !== undefined) {
38
+ if (ch === '\\' && quote === '"' && i + 1 < spec.length && (spec[i + 1] === '"' || spec[i + 1] === '\\')) {
39
+ current += spec[++i]!
40
+ }
41
+ else if (ch === quote) {
42
+ quote = undefined
43
+ }
44
+ else {
45
+ current += ch
46
+ }
47
+ continue
48
+ }
49
+
50
+ if (ch === '\'' || ch === '"') {
51
+ quote = ch
52
+ hasToken = true
53
+ continue
54
+ }
55
+ if (ch === '\\' && i + 1 < spec.length && /\s/.test(spec[i + 1]!)) {
56
+ current += spec[++i]!
57
+ hasToken = true
58
+ continue
59
+ }
60
+ if (/\s/.test(ch)) {
61
+ if (hasToken) {
62
+ tokens.push(current)
63
+ current = ''
64
+ hasToken = false
65
+ }
66
+ continue
67
+ }
68
+ current += ch
69
+ hasToken = true
70
+ }
71
+
72
+ if (hasToken)
73
+ tokens.push(current)
74
+ return tokens
75
+ }
76
+
77
+ /** Parses and validates a `relPath:line:col` location, confining it strictly inside `root`. */
78
+ export function parseSourceLoc(raw: string, root: string): ParsedSourceLoc | { error: string, status: 400 | 403 | 404 } {
79
+ const trimmed = raw.trim()
80
+ const lastColon = trimmed.lastIndexOf(':')
81
+ const prevColon = lastColon > 0 ? trimmed.lastIndexOf(':', lastColon - 1) : -1
82
+ if (lastColon <= 0 || prevColon <= 0)
83
+ return { error: 'Invalid source location; expected file:line:col.', status: 400 }
84
+
85
+ const relPart = trimmed.slice(0, prevColon)
86
+ const lineStr = trimmed.slice(prevColon + 1, lastColon)
87
+ const colStr = trimmed.slice(lastColon + 1)
88
+ if (relPart === '' || relPart.includes('\0') || !POSITIVE_INT_RE.test(lineStr) || !POSITIVE_INT_RE.test(colStr))
89
+ return { error: 'Invalid source location; expected file:line:col.', status: 400 }
90
+
91
+ const line = Number.parseInt(lineStr, 10)
92
+ const col = Number.parseInt(colStr, 10)
93
+ if (!Number.isSafeInteger(line) || line < 1 || !Number.isSafeInteger(col) || col < 1)
94
+ return { error: 'Line and column must be positive integers.', status: 400 }
95
+
96
+ const resolvedRoot = resolve(root)
97
+ const file = resolve(resolvedRoot, relPart)
98
+ if (!isInside(resolvedRoot, file))
99
+ return { error: 'Source file is outside the project root.', status: 403 }
100
+ if (!existsSync(file))
101
+ return { error: 'Source file does not exist.', status: 404 }
102
+
103
+ const realRoot = realpathSync(resolvedRoot)
104
+ const realFile = realpathSync(file)
105
+ if (!isInside(realRoot, realFile))
106
+ return { error: 'Source file is outside the project root.', status: 403 }
107
+
108
+ return { file, relFile: relative(resolvedRoot, file).replaceAll('\\', '/'), line, col }
109
+ }
110
+
111
+ /** Builds the argv array to open `loc` in `editorSpec` (supporting `{file}`/`{line}`/`{col}` templates and common editors). */
112
+ export function buildEditorCommand(editorSpec: string, loc: { file: string, line: number, col: number }): string[] {
113
+ const parts = splitEditorSpec(editorSpec.trim())
114
+ if (parts.length === 0)
115
+ return []
116
+
117
+ const lineStr = String(loc.line)
118
+ const colStr = String(loc.col)
119
+ if (parts.some(p => p.includes('{file}') || p.includes('{line}') || p.includes('{col}')))
120
+ return parts.map(p => p.replaceAll('{file}', loc.file).replaceAll('{line}', lineStr).replaceAll('{col}', colStr))
121
+
122
+ const rawBin = parts[0]!.split(/[\\/]/).pop() ?? ''
123
+ const bin = rawBin.toLowerCase().replace(BIN_EXT_RE, '')
124
+ const fileLineCol = `${loc.file}:${lineStr}:${colStr}`
125
+
126
+ if (VSCODE_EDITORS.has(bin))
127
+ return [...parts, '--goto', fileLineCol]
128
+ if (ZED_EDITORS.has(bin) || SUBLIME_HELIX_EDITORS.has(bin))
129
+ return [...parts, fileLineCol]
130
+ if (JETBRAINS_EDITORS.has(bin))
131
+ return [...parts, '--line', lineStr, '--column', colStr, loc.file]
132
+ if (TERMINAL_EDITORS.has(bin))
133
+ return [...parts, `+${lineStr}`, loc.file]
134
+ return [...parts, fileLineCol]
135
+ }
136
+
137
+ export interface OpenEditorOptions {
138
+ env?: Record<string, string | undefined> | undefined
139
+ spawn?: ((cmd: string[]) => void) | undefined
140
+ trustedOrigins?: ReadonlySet<string> | readonly string[] | undefined
141
+ trustProxy?: TrustProxy | undefined
142
+ remoteIp?: string | undefined
143
+ }
144
+
145
+ const IPV4_LOOPBACK_RE = /^127(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}$/
146
+
147
+ function isLoopbackIp(ip: string): boolean {
148
+ const bare = ip.trim().toLowerCase().replace(/^\[|\]$/g, '')
149
+ const unmapped = bare.startsWith('::ffff:') ? bare.slice(7) : bare
150
+ return unmapped === '::1' || unmapped === '0:0:0:0:0:0:0:1' || IPV4_LOOPBACK_RE.test(unmapped)
151
+ }
152
+
153
+ export function openInEditor(
154
+ rawSrc: string,
155
+ root: string,
156
+ options?: OpenEditorOptions,
157
+ ): { ok: true, command: string[] } | { ok: false, status: number, error: string } {
158
+ const env = options?.env ?? process.env
159
+ const editor = env.PRUNELLE_EDITOR?.trim() || env.VISUAL?.trim()
160
+ if (!editor)
161
+ return { ok: false, status: 400, error: MISSING_EDITOR_ERROR }
162
+
163
+ const parsed = parseSourceLoc(rawSrc, root)
164
+ if ('error' in parsed)
165
+ return { ok: false, status: parsed.status, error: parsed.error }
166
+
167
+ const command = buildEditorCommand(editor, parsed)
168
+ if (command.length === 0)
169
+ return { ok: false, status: 400, error: MISSING_EDITOR_ERROR }
170
+
171
+ try {
172
+ if (options?.spawn !== undefined) {
173
+ options.spawn(command)
174
+ }
175
+ else {
176
+ const proc = Bun.spawn(command, { cwd: root, stdin: 'ignore', stdout: 'ignore', stderr: 'ignore' })
177
+ proc.unref()
178
+ }
179
+ }
180
+ catch (err) {
181
+ return {
182
+ ok: false,
183
+ status: 500,
184
+ error: `Failed to launch editor "${command[0]}": ${err instanceof Error ? err.message : String(err)}`,
185
+ }
186
+ }
187
+
188
+ return { ok: true, command }
189
+ }
190
+
191
+ /** 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. */
192
+ export async function handleOpenEditorRequest(
193
+ request: Request,
194
+ root: string,
195
+ options?: OpenEditorOptions,
196
+ ): Promise<Response> {
197
+ if (request.method !== 'POST')
198
+ return Response.json({ ok: false, error: 'Method Not Allowed' }, { status: 405, headers: { allow: 'POST' } })
199
+ if (options?.remoteIp !== undefined && !isLoopbackIp(options.remoteIp))
200
+ return Response.json({ ok: false, error: 'Open-editor is only available from loopback addresses.' }, { status: 403 })
201
+ const trusted = options?.trustedOrigins === undefined
202
+ ? undefined
203
+ : options.trustedOrigins instanceof Set
204
+ ? options.trustedOrigins
205
+ : new Set(options.trustedOrigins)
206
+ const originCheck = verifyOrigin(request, trusted, options?.trustProxy ?? false)
207
+ if (!originCheck.ok)
208
+ return Response.json({ ok: false, error: originCheck.reason }, { status: 403 })
209
+ const mediaType = (request.headers.get('content-type') ?? '').split(';', 1)[0]!.trim().toLowerCase()
210
+ if (mediaType !== 'application/json')
211
+ return Response.json({ ok: false, error: 'Expected content-type: application/json.' }, { status: 415 })
212
+
213
+ let rawSrc = ''
214
+ try {
215
+ const body = await request.json() as unknown
216
+ if (body !== null && typeof body === 'object' && typeof (body as { src?: unknown }).src === 'string')
217
+ rawSrc = (body as { src: string }).src
218
+ }
219
+ catch {
220
+ return Response.json({ ok: false, error: 'Invalid JSON body; expected { "src": "file:line:col" }.' }, { status: 400 })
221
+ }
222
+
223
+ if (rawSrc.trim() === '')
224
+ return Response.json({ ok: false, error: 'Missing "src" location.' }, { status: 400 })
225
+
226
+ const result = openInEditor(rawSrc, root, options)
227
+ return Response.json(result, { status: result.ok ? 200 : result.status })
228
+ }
@@ -0,0 +1,24 @@
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
+ /** The address the parent binds, which the app's plugins see as `api.devExposed`. */
16
+ hostname?: string | undefined
17
+ maxRequestBodySize?: number | undefined
18
+ maxRssMb?: number | undefined
19
+ }
20
+
21
+ export type DevChildMessage =
22
+ | { t: 'ready', assetPrefix: string }
23
+ | { t: 'event', payload: string }
24
+ | { t: 'recycle', reason: RecycleReason }
@@ -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
+ }