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.
Files changed (200) hide show
  1. package/llms.txt +152 -0
  2. package/package.json +59 -4
  3. package/src/a11y/declaration.ts +335 -0
  4. package/src/a11y/index.ts +446 -0
  5. package/src/a11y/rgaa-map.ts +184 -0
  6. package/src/ambient.d.ts +6 -0
  7. package/src/attrs.ts +43 -0
  8. package/src/build/bundle.ts +657 -0
  9. package/src/build/carry.ts +57 -0
  10. package/src/build/client-entries.ts +107 -0
  11. package/src/build/client-plugin.ts +173 -0
  12. package/src/build/client-prune.ts +168 -0
  13. package/src/build/compile.ts +129 -0
  14. package/src/build/ecoindex.ts +229 -0
  15. package/src/build/files.ts +156 -0
  16. package/src/build/first-load.ts +164 -0
  17. package/src/build/graph.ts +247 -0
  18. package/src/build/index.ts +641 -0
  19. package/src/build/is-inside.ts +12 -0
  20. package/src/build/islands.ts +641 -0
  21. package/src/build/manifest.ts +325 -0
  22. package/src/build/output.ts +84 -0
  23. package/src/build/plugin-host.ts +278 -0
  24. package/src/build/precompress.ts +139 -0
  25. package/src/build/prerender.ts +232 -0
  26. package/src/build/render-rules.ts +205 -0
  27. package/src/build/report.ts +268 -0
  28. package/src/build/resolve.ts +52 -0
  29. package/src/build/routes.ts +342 -0
  30. package/src/build/server-entry.ts +38 -0
  31. package/src/build/static.ts +207 -0
  32. package/src/build/status-pages.ts +127 -0
  33. package/src/build/style-bundles.ts +526 -0
  34. package/src/cli/check-forms.ts +654 -0
  35. package/src/cli/check-links.ts +619 -0
  36. package/src/cli/check.ts +381 -0
  37. package/src/cli/commands.ts +345 -0
  38. package/src/cli/docs.ts +402 -0
  39. package/src/cli/index.ts +70 -0
  40. package/src/cli/inspect.ts +345 -0
  41. package/src/cli/mcp-tools.ts +480 -0
  42. package/src/cli/mcp.ts +205 -0
  43. package/src/cli/new.ts +41 -0
  44. package/src/cli/render.ts +261 -0
  45. package/src/cli/upgrade-names.ts +209 -0
  46. package/src/cli/upgrade.ts +354 -0
  47. package/src/compiler/analyze.ts +632 -0
  48. package/src/compiler/ast.ts +82 -0
  49. package/src/compiler/browser-globals.ts +127 -0
  50. package/src/compiler/cacheability.ts +592 -0
  51. package/src/compiler/compliance-rgaa.ts +502 -0
  52. package/src/compiler/compliance.ts +497 -0
  53. package/src/compiler/data-keys.ts +295 -0
  54. package/src/compiler/dev-source.ts +87 -0
  55. package/src/compiler/dom-attrs.ts +452 -0
  56. package/src/compiler/dom.ts +567 -0
  57. package/src/compiler/emit.ts +131 -0
  58. package/src/compiler/expr-context.ts +518 -0
  59. package/src/compiler/index.ts +8 -0
  60. package/src/compiler/interactivity.ts +366 -0
  61. package/src/compiler/mistakes.ts +499 -0
  62. package/src/compiler/node-env.ts +50 -0
  63. package/src/compiler/patch.ts +97 -0
  64. package/src/compiler/props.ts +511 -0
  65. package/src/compiler/scope.ts +607 -0
  66. package/src/compiler/server-only.ts +326 -0
  67. package/src/compiler/shared.ts +369 -0
  68. package/src/compiler/signal-reads.ts +242 -0
  69. package/src/compiler/slots.ts +227 -0
  70. package/src/compiler/ssr-helpers.ts +555 -0
  71. package/src/compiler/ssr-island.ts +90 -0
  72. package/src/compiler/ssr-prunelle-tags.ts +69 -0
  73. package/src/compiler/ssr.ts +526 -0
  74. package/src/context.ts +165 -0
  75. package/src/dev/child.ts +30 -0
  76. package/src/dev/error-log.ts +151 -0
  77. package/src/dev/index.ts +258 -0
  78. package/src/dev/modules.ts +68 -0
  79. package/src/dev/open-editor.ts +204 -0
  80. package/src/dev/protocol.ts +22 -0
  81. package/src/dev/queue.ts +79 -0
  82. package/src/dev/reload.ts +159 -0
  83. package/src/dev/supervisor.ts +204 -0
  84. package/src/dev/watchers.ts +251 -0
  85. package/src/dom/action.ts +164 -0
  86. package/src/dom/attrs.ts +84 -0
  87. package/src/dom/claim.ts +120 -0
  88. package/src/dom/extras.ts +562 -0
  89. package/src/dom/index.ts +289 -0
  90. package/src/dom/island.ts +285 -0
  91. package/src/dom/loop.ts +450 -0
  92. package/src/dom/revive.ts +36 -0
  93. package/src/index.ts +22 -0
  94. package/src/jsx-runtime.ts +566 -0
  95. package/src/plugins/config.ts +86 -0
  96. package/src/plugins/context.ts +66 -0
  97. package/src/plugins/index.ts +14 -0
  98. package/src/plugins/load.ts +70 -0
  99. package/src/plugins/order.ts +111 -0
  100. package/src/plugins/public.ts +15 -0
  101. package/src/plugins/requires.ts +47 -0
  102. package/src/plugins/services.ts +97 -0
  103. package/src/plugins/types.ts +261 -0
  104. package/src/reactivity/graph.ts +249 -0
  105. package/src/reactivity/index.ts +533 -0
  106. package/src/reactivity/selector.ts +51 -0
  107. package/src/reactivity/store.ts +208 -0
  108. package/src/server/action-protect.ts +198 -0
  109. package/src/server/action-registry.ts +78 -0
  110. package/src/server/action.ts +530 -0
  111. package/src/server/app-entry.ts +23 -0
  112. package/src/server/assets.ts +168 -0
  113. package/src/server/compress.ts +642 -0
  114. package/src/server/consent.ts +253 -0
  115. package/src/server/cookies.ts +139 -0
  116. package/src/server/document.ts +271 -0
  117. package/src/server/env.ts +33 -0
  118. package/src/server/errors.ts +391 -0
  119. package/src/server/form-schema.ts +343 -0
  120. package/src/server/health.ts +244 -0
  121. package/src/server/http.ts +538 -0
  122. package/src/server/index.ts +586 -0
  123. package/src/server/lifecycle.ts +75 -0
  124. package/src/server/loader.ts +123 -0
  125. package/src/server/page.ts +107 -0
  126. package/src/server/param-matchers.ts +112 -0
  127. package/src/server/plugin-host.ts +265 -0
  128. package/src/server/prerendered.ts +71 -0
  129. package/src/server/public.ts +19 -0
  130. package/src/server/rate-limit.ts +156 -0
  131. package/src/server/region.ts +96 -0
  132. package/src/server/request-body.ts +27 -0
  133. package/src/server/request-path.ts +73 -0
  134. package/src/server/request-scope.ts +22 -0
  135. package/src/server/route-cache.ts +423 -0
  136. package/src/server/route-table.ts +410 -0
  137. package/src/server/router.ts +261 -0
  138. package/src/server/routing.ts +472 -0
  139. package/src/server/security.ts +499 -0
  140. package/src/server/serve-handlers.ts +83 -0
  141. package/src/server/served-file.ts +128 -0
  142. package/src/server/standard-schema.ts +87 -0
  143. package/src/server/start.ts +143 -0
  144. package/src/server/static-dir.ts +220 -0
  145. package/src/server/stream.ts +211 -0
  146. package/src/ssr/context.ts +383 -0
  147. package/src/ssr/index.ts +596 -0
  148. package/src/ssr/navigation.ts +96 -0
  149. package/src/ssr/region.ts +183 -0
  150. package/src/style.ts +33 -0
  151. package/src/test/browser.ts +192 -0
  152. package/src/test/index.ts +191 -0
  153. package/src/ts-plugin/diagnostics.ts +378 -0
  154. package/src/ts-plugin/fixes.ts +364 -0
  155. package/src/ts-plugin/index.ts +194 -0
  156. package/src/unrenderable.ts +35 -0
  157. package/templates/_shared/AGENTS.md +10 -0
  158. package/templates/_shared/CLAUDE.md +1 -0
  159. package/templates/_shared/gitignore +3 -0
  160. package/templates/_shared/mcp.json +11 -0
  161. package/templates/_shared/public/robots.txt +2 -0
  162. package/templates/_shared/src/routes/legal.tsx +13 -0
  163. package/templates/_shared/tsconfig.json +25 -0
  164. package/templates/app/.env.example +4 -0
  165. package/templates/app/package.json +21 -0
  166. package/templates/app/prunelle.config.ts +11 -0
  167. package/templates/app/src/auth.ts +14 -0
  168. package/templates/app/src/routes/_layout.tsx +32 -0
  169. package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
  170. package/templates/app/src/routes/dashboard/index.tsx +13 -0
  171. package/templates/app/src/routes/index.tsx +15 -0
  172. package/templates/app/src/routes/login.tsx +34 -0
  173. package/templates/app/src/styles/app.css +7 -0
  174. package/templates/app/tests/app.test.ts +32 -0
  175. package/templates/blog/content/posts/welcome.md +9 -0
  176. package/templates/blog/package.json +22 -0
  177. package/templates/blog/prunelle.config.ts +23 -0
  178. package/templates/blog/src/posts.ts +26 -0
  179. package/templates/blog/src/routes/_layout.tsx +20 -0
  180. package/templates/blog/src/routes/blog/[slug].tsx +31 -0
  181. package/templates/blog/src/routes/index.tsx +33 -0
  182. package/templates/blog/src/styles/app.css +10 -0
  183. package/templates/fullstack/package.json +19 -0
  184. package/templates/fullstack/prunelle.config.ts +6 -0
  185. package/templates/fullstack/src/actions/greet.ts +19 -0
  186. package/templates/fullstack/src/components/Counter.tsx +10 -0
  187. package/templates/fullstack/src/components/GreetForm.tsx +27 -0
  188. package/templates/fullstack/src/routes/_layout.tsx +14 -0
  189. package/templates/fullstack/src/routes/api/health.ts +5 -0
  190. package/templates/fullstack/src/routes/index.tsx +13 -0
  191. package/templates/fullstack/src/styles/app.css +29 -0
  192. package/templates/fullstack/tests/app.test.ts +37 -0
  193. package/templates/minimal/package.json +19 -0
  194. package/templates/minimal/prunelle.config.ts +6 -0
  195. package/templates/minimal/src/components/Counter.tsx +10 -0
  196. package/templates/minimal/src/routes/_layout.tsx +14 -0
  197. package/templates/minimal/src/routes/index.tsx +11 -0
  198. package/templates/minimal/src/styles/app.css +22 -0
  199. package/ts-plugin.cjs +4277 -0
  200. package/README.md +0 -3
@@ -0,0 +1,657 @@
1
+ // The two Bun.build passes: the client (runtime + island chunks + standalone CSS) and the server (routes compiled for SSR).
2
+
3
+ import type { BunPlugin, PluginBuilder } from 'bun'
4
+ import type { IslandBinding } from '../compiler/index'
5
+ import type { BuildPluginTarget, PrunellePlugin } from '../plugins/index'
6
+ import type { ClientTransforms } from './client-plugin'
7
+ import type { BuildCache, ModuleGraph } from './graph'
8
+ import type { ActionsByFile, IslandPlan } from './islands'
9
+ import { copyFileSync, existsSync, linkSync, mkdirSync, readdirSync, realpathSync, writeFileSync } from 'node:fs'
10
+ import { dirname, isAbsolute, join, relative, resolve } from 'node:path'
11
+ import { compileSsr } from '../compiler/index'
12
+ import { readsPrivateEnv } from '../compiler/server-only'
13
+ import { clientPlugin, PRUNELLE_SPECIFIER_FILTER, localIslandExports, TS_FILTER } from './client-plugin'
14
+ import { formatBunBuildLogs, isInNodeModules, isTsFile, relPosix } from './files'
15
+ import { isInside } from './is-inside'
16
+ import { stampFiles, stampsMatch } from './graph'
17
+ import { entryStaticImports, hydrateStrategies, writeClientEntries } from './client-entries'
18
+ import { clientLeakError, islandKey } from './islands'
19
+ import { pluginHookError } from './plugin-host'
20
+ import { PRUNELLE_SRC_ROOT, resolvePrunelleSpecifier } from './resolve'
21
+
22
+ export interface BundleEnv {
23
+ root: string
24
+ outDir: string
25
+ clientDir: string
26
+ serverDir: string
27
+ assetPrefix: string
28
+ minify: boolean
29
+ isDev: boolean
30
+ nodeEnv?: string | undefined
31
+ analyze?: boolean | undefined
32
+ graph: ModuleGraph
33
+ cache: BuildCache | undefined
34
+ plugins: PrunellePlugin[]
35
+ actionsByFile: ActionsByFile
36
+ islands: IslandPlan
37
+ }
38
+
39
+ export function linkOrCopyFile(src: string, dst: string): void {
40
+ mkdirSync(dirname(dst), { recursive: true })
41
+ try {
42
+ linkSync(src, dst)
43
+ }
44
+ catch {
45
+ copyFileSync(src, dst)
46
+ }
47
+ }
48
+
49
+ const prunedClientCss = new WeakMap<BuildCache, Map<string, Uint8Array>>()
50
+
51
+ /** Keeps intermediate CSS bytes pruned by stylesheet consolidation so the next `buildClient` cache hit can restore them before consolidating again. */
52
+ export function setPrunedClientCss(cache: BuildCache | undefined, files: Map<string, Uint8Array>): void {
53
+ if (cache === undefined)
54
+ return
55
+ if (files.size > 0)
56
+ prunedClientCss.set(cache, files)
57
+ else
58
+ prunedClientCss.delete(cache)
59
+ }
60
+
61
+ function reuseDirFiles(srcDir: string, dstDir: string, relFiles?: readonly string[], fallbackFiles?: ReadonlyMap<string, Uint8Array>): boolean {
62
+ if (!existsSync(srcDir))
63
+ return false
64
+ if (relFiles !== undefined) {
65
+ for (const rel of relFiles) {
66
+ const from = join(srcDir, rel)
67
+ const to = join(dstDir, rel)
68
+ if (existsSync(from)) {
69
+ linkOrCopyFile(from, to)
70
+ continue
71
+ }
72
+ const bytes = fallbackFiles?.get(rel)
73
+ if (bytes === undefined)
74
+ return false
75
+ mkdirSync(dirname(to), { recursive: true })
76
+ writeFileSync(to, bytes)
77
+ }
78
+ return true
79
+ }
80
+ let count = 0
81
+ for (const ent of readdirSync(srcDir, { recursive: true, withFileTypes: true })) {
82
+ if (!ent.isFile())
83
+ continue
84
+ const from = join(ent.parentPath, ent.name)
85
+ const rel = relative(srcDir, from)
86
+ linkOrCopyFile(from, join(dstDir, rel))
87
+ count++
88
+ }
89
+ return count > 0
90
+ }
91
+
92
+ const PRUNELLE_SCOPE_RE = /^@prunellejs\//
93
+ const LEADING_DOT_SLASH_RE = /^\.\//
94
+ const EXTERNAL_PRUNELLE_SPECIFIERS = new Set(['prunelle/build', 'prunelle/test'])
95
+
96
+ export function pluginBunPlugins(env: Pick<BundleEnv, 'plugins' | 'root' | 'assetPrefix' | 'minify'>, target: BuildPluginTarget): BunPlugin[] {
97
+ const { root, assetPrefix, minify } = env
98
+ return env.plugins.flatMap((p) => {
99
+ const bp = p.bunPlugins
100
+ return typeof bp === 'function' ? bp({ root, assetPrefix, minify, target }) : bp ?? []
101
+ })
102
+ }
103
+
104
+ /** Plugin `transform` hooks, applied in order to every module the bundles load. The first throw is kept in `failure`, since Bun turns it into a log line. */
105
+ function pluginTransforms(plugins: PrunellePlugin[]): ClientTransforms {
106
+ const list = plugins.filter(p => typeof p.transform === 'function')
107
+ const transforms: ClientTransforms = {
108
+ active: list.length > 0,
109
+ key: list.map(p => p.name).join(','),
110
+ failure: undefined,
111
+ apply(code, id, target) {
112
+ let cur = code
113
+ for (const plugin of list) {
114
+ let next: string | void
115
+ try {
116
+ next = plugin.transform!(cur, id, target)
117
+ }
118
+ catch (error) {
119
+ transforms.failure ??= pluginHookError(plugin, 'transform', error)
120
+ throw transforms.failure
121
+ }
122
+ if (typeof next === 'string')
123
+ cur = next
124
+ }
125
+ return cur
126
+ },
127
+ }
128
+ return transforms
129
+ }
130
+
131
+ /** Runs Bun.build, failing first with what `ownFailure` throws (a leak, a plugin hook), then with Bun's own logs. */
132
+ async function runBunBuild(side: 'client' | 'server', root: string, ownFailure: () => void, config: Parameters<typeof Bun.build>[0]): Promise<Awaited<ReturnType<typeof Bun.build>>> {
133
+ let result: Awaited<ReturnType<typeof Bun.build>>
134
+ try {
135
+ result = await Bun.build(config)
136
+ }
137
+ catch (err) {
138
+ ownFailure()
139
+ if (err instanceof AggregateError && err.errors.length > 0)
140
+ throw new Error(`prunelle build (${side}) failed:\n${formatBunBuildLogs(err.errors, root)}`)
141
+ throw err
142
+ }
143
+ ownFailure()
144
+ if (!result.success)
145
+ throw new Error(`prunelle build (${side}) failed:\n${formatBunBuildLogs(result.logs, root)}`)
146
+ return result
147
+ }
148
+
149
+ /** CSS files imported outside islands (plus the plugins' own), built as standalone stylesheets. */
150
+ export function standaloneCssFiles(graph: ModuleGraph, pluginCss: string[], islandCss: Set<string>): string[] {
151
+ const out = new Set(pluginCss)
152
+ for (const [file, analysis] of graph.analyses) {
153
+ for (const { source } of [...analysis.imports, ...analysis.reexports]) {
154
+ const target = graph.resolve(file, source)
155
+ if (target !== undefined && target.endsWith('.css') && !islandCss.has(target))
156
+ out.add(target)
157
+ }
158
+ }
159
+ return [...out]
160
+ }
161
+
162
+ export interface ClientBuild {
163
+ /** Island key to the URL of its chunk. */
164
+ islandChunks: Map<string, string>
165
+ srcCssToUrl: Map<string, string>
166
+ /** Island key to the URL of the CSS bundled with it. */
167
+ islandCssUrl: Map<string, string>
168
+ /** Emitted files, relative to the client dir. */
169
+ assetFiles: string[]
170
+ styleUrls: string[]
171
+ runtimeScript: string | undefined
172
+ regionScript: string | undefined
173
+ /** The prop revivers, which the loader imports for an island whose props hold a Date, Map, Set or another tagged value. */
174
+ reviveScript: string | undefined
175
+ /** Entry URL to the chunks it imports statically, transitively, for the page's preloads. */
176
+ chunkImports: Record<string, string[]>
177
+ metafile: Bun.BuildOutput['metafile']
178
+ }
179
+
180
+ /** Builds the prop revivers on their own, so the loader names the file through `PRUNELLE_REVIVE` and imports it only for the props that need it. */
181
+ async function buildReviver(env: BundleEnv): Promise<{ url: string, file: string }> {
182
+ const built = await runBunBuild('client', env.root, () => {}, {
183
+ entrypoints: [join(PRUNELLE_SRC_ROOT, 'dom/revive.ts')],
184
+ outdir: env.clientDir,
185
+ target: 'browser',
186
+ format: 'esm',
187
+ minify: env.minify,
188
+ naming: '[name]-[hash].[ext]',
189
+ })
190
+ const file = relPosix(env.clientDir, built.outputs[0]!.path)
191
+ return { url: `${env.assetPrefix}/${file}`, file }
192
+ }
193
+
194
+ function publicEnvDefines(): Record<string, string> {
195
+ const defines: Record<string, string> = {}
196
+ for (const [key, value] of Object.entries(process.env)) {
197
+ if (key.startsWith('PUBLIC_') && value !== undefined)
198
+ defines[`process.env.${key}`] = JSON.stringify(value)
199
+ }
200
+ return defines
201
+ }
202
+
203
+
204
+ function buildClientSignature(
205
+ env: BundleEnv,
206
+ standaloneCss: readonly string[],
207
+ pluginClientEntries: readonly string[],
208
+ regionClientEntries: readonly string[],
209
+ transformsKey: string,
210
+ strategies: ReturnType<typeof hydrateStrategies>['strategies'],
211
+ hasClientOnlyHydrate: boolean,
212
+ envDefines: Readonly<Record<string, string>>,
213
+ ): string {
214
+ if (env.cache === undefined)
215
+ return ''
216
+ return JSON.stringify({
217
+ minify: env.minify,
218
+ assetPrefix: env.assetPrefix,
219
+ isDev: env.isDev,
220
+ nodeEnv: env.nodeEnv ?? (env.isDev ? 'development' : 'production'),
221
+ transforms: transformsKey,
222
+ strategies,
223
+ hasClientOnlyHydrate,
224
+ pluginClientEntries,
225
+ regionClientEntries,
226
+ standaloneCss: [...standaloneCss].sort(),
227
+ islands: [...env.islands.targets.entries()]
228
+ .sort(([a], [b]) => a.localeCompare(b))
229
+ .map(([k, t]) => [k, t.id, t.file, t.exportName, t.defaultHydrate ?? '']),
230
+ actions: [...env.actionsByFile.entries()]
231
+ .sort(([a], [b]) => a.localeCompare(b))
232
+ .map(([f, list]) => [f, list.map(a => `${a.exportName}=${a.url}`)]),
233
+ envDefines: Object.entries(envDefines).sort(([a], [b]) => a.localeCompare(b)),
234
+ bunPlugins: env.plugins.filter(p => p.bunPlugins !== undefined).map(p => p.name),
235
+ })
236
+ }
237
+
238
+ export async function buildClient(env: BundleEnv, standaloneCss: string[]): Promise<ClientBuild> {
239
+ const { root, clientDir, assetPrefix, graph, cache, actionsByFile, islands } = env
240
+ const result: ClientBuild = {
241
+ islandChunks: new Map(),
242
+ srcCssToUrl: new Map(),
243
+ islandCssUrl: new Map(),
244
+ assetFiles: [],
245
+ styleUrls: [],
246
+ runtimeScript: undefined,
247
+ regionScript: undefined,
248
+ reviveScript: undefined,
249
+ chunkImports: {},
250
+ metafile: undefined,
251
+ }
252
+ const pluginClientEntries = env.plugins.map(p => p.clientEntry).filter((e): e is string => Boolean(e))
253
+ const regionClientEntries = env.plugins.map(p => p.regionClientEntry).filter((e): e is string => Boolean(e))
254
+ if (islands.targets.size === 0 && pluginClientEntries.length === 0 && regionClientEntries.length === 0 && standaloneCss.length === 0) {
255
+ if (cache !== undefined) {
256
+ cache.lastClient = undefined
257
+ prunedClientCss.delete(cache)
258
+ }
259
+ return result
260
+ }
261
+
262
+ const transforms = pluginTransforms(env.plugins)
263
+ const { strategies, hasClientOnlyHydrate } = hydrateStrategies(graph.analyses.values())
264
+
265
+ const envDefines = publicEnvDefines()
266
+ const clientSignature = buildClientSignature(env, standaloneCss, pluginClientEntries, regionClientEntries, transforms.key, strategies, hasClientOnlyHydrate, envDefines)
267
+
268
+ if (
269
+ cache !== undefined
270
+ && !env.analyze
271
+ && cache.lastClient !== undefined
272
+ && cache.lastClient.signature === clientSignature
273
+ && stampsMatch(cache.lastClient.inputStamps)
274
+ && reuseDirFiles(cache.lastClient.clientDir, clientDir, cache.lastClient.assetFiles, prunedClientCss.get(cache))
275
+ ) {
276
+ cache.stats.clientSkips++
277
+ cache.lastClient.clientDir = clientDir
278
+ return {
279
+ islandChunks: new Map(cache.lastClient.islandChunks),
280
+ srcCssToUrl: new Map(cache.lastClient.srcCssToUrl),
281
+ islandCssUrl: new Map(cache.lastClient.islandCssUrl),
282
+ assetFiles: [...cache.lastClient.assetFiles],
283
+ styleUrls: [...cache.lastClient.styleUrls],
284
+ runtimeScript: cache.lastClient.runtimeScript,
285
+ regionScript: cache.lastClient.regionScript,
286
+ reviveScript: cache.lastClient.reviveScript,
287
+ chunkImports: cache.lastClient.chunkImports,
288
+ metafile: undefined,
289
+ }
290
+ }
291
+
292
+ // Bun hashes an entry's path into its chunk name, so the entries sit at one path per app: a dev rebuild or a static stage then keeps every unchanged chunk name.
293
+ const entriesDir = join(root, 'node_modules/.cache/prunelle/entries')
294
+ mkdirSync(entriesDir, { recursive: true })
295
+ const { entryPoints, islandEntryToKey, runtimeEntryPath, regionEntryPath } = writeClientEntries(env, entriesDir, { pluginClientEntries, regionClientEntries, hasClientOnlyHydrate, standaloneCss })
296
+
297
+ const clientLeaks = new Set<string>()
298
+ const inlinedEnvKey = (key: string): boolean => key === 'NODE_ENV' || `process.env.${key}` in envDefines
299
+ const plugin = clientPlugin({ root, isDev: env.isDev, graph, cache, actionsByFile, transforms, leaks: clientLeaks, localExports: localIslandExports(islands.targets.values()), clientKeep: islands.clientKeep })
300
+ const reviver = islands.targets.size > 0 ? await buildReviver(env) : undefined
301
+
302
+ const clientResult = await runBunBuild('client', env.root, () => {
303
+ if (clientLeaks.size > 0)
304
+ throw clientLeakError(clientLeaks)
305
+ if (transforms.failure !== undefined)
306
+ throw transforms.failure
307
+ }, {
308
+ entrypoints: entryPoints,
309
+ outdir: clientDir,
310
+ target: 'browser',
311
+ format: 'esm',
312
+ splitting: true,
313
+ minify: env.minify,
314
+ metafile: true,
315
+ naming: '[name]-[hash].[ext]',
316
+ external: reviver === undefined ? [] : [reviver.url],
317
+ define: {
318
+ ...(reviver === undefined ? {} : { PRUNELLE_REVIVE: JSON.stringify(reviver.url) }),
319
+ PRUNELLE_VISIBLE: String(strategies.visible),
320
+ PRUNELLE_IDLE: String(strategies.idle),
321
+ PRUNELLE_INTERACTION: String(strategies.interaction),
322
+ PRUNELLE_MEDIA: String(strategies.media),
323
+ PRUNELLE_CLIENT_ONLY: hasClientOnlyHydrate ? 'true' : 'false',
324
+ PRUNELLE_BROWSER: 'true',
325
+ 'process.env.NODE_ENV': JSON.stringify(env.nodeEnv ?? (env.isDev ? 'development' : 'production')),
326
+ ...envDefines,
327
+ },
328
+ plugins: [plugin, ...pluginBunPlugins(env, 'client')],
329
+ })
330
+
331
+ const { metafile } = clientResult
332
+ result.metafile = metafile
333
+ const metaPaths = new Map<string, string>()
334
+ const resolveMetaPath = (p: string): string => {
335
+ let abs = metaPaths.get(p)
336
+ if (abs === undefined) {
337
+ const fromCwd = resolve(process.cwd(), p)
338
+ abs = existsSync(fromCwd) || islandEntryToKey.has(fromCwd) || fromCwd === runtimeEntryPath || fromCwd === regionEntryPath ? fromCwd : resolve(clientDir, p)
339
+ metaPaths.set(p, abs)
340
+ }
341
+ return abs
342
+ }
343
+
344
+ // A process.env or Bun.env left in a chunk is a key the build did not inline: name the app module that put it there.
345
+ for (const output of clientResult.outputs) {
346
+ if (!output.path.endsWith('.js'))
347
+ continue
348
+ const js = await output.text()
349
+ if (!js.includes('process.env') && !js.includes('Bun.env'))
350
+ continue
351
+ const relFile = relPosix(clientDir, output.path)
352
+ const info = metafile?.outputs[relFile] ?? metafile?.outputs[`./${relFile}`]
353
+ for (const [inKey, input] of Object.entries(info?.inputs ?? {})) {
354
+ if (input.bytesInOutput <= 0)
355
+ continue
356
+ const abs = resolveMetaPath(inKey)
357
+ let program = graph.analyses.get(abs)?.program
358
+ if (program === undefined && existsSync(abs) && isTsFile(abs) && !isInNodeModules(abs))
359
+ program = graph.load(abs).program
360
+ if (program !== undefined && readsPrivateEnv(program, inlinedEnvKey))
361
+ clientLeaks.add(`${relPosix(root, abs)} reads process.env or Bun.env (only a process.env.PUBLIC_* set at build time is inlined)`)
362
+ }
363
+ }
364
+ if (clientLeaks.size > 0)
365
+ throw clientLeakError(clientLeaks)
366
+
367
+ for (const [outKey, info] of Object.entries(metafile?.outputs ?? {})) {
368
+ const relOut = outKey.replace(LEADING_DOT_SLASH_RE, '')
369
+ const url = `${assetPrefix}/${relOut}`
370
+ const entry = info.entryPoint === undefined ? undefined : resolveMetaPath(info.entryPoint)
371
+ if (entry !== undefined && entry === runtimeEntryPath && relOut.endsWith('.js'))
372
+ result.runtimeScript = url
373
+ if (entry !== undefined && entry === regionEntryPath && relOut.endsWith('.js'))
374
+ result.regionScript = url
375
+ const entryKey = entry === undefined ? undefined : islandEntryToKey.get(entry)
376
+ if (entryKey !== undefined && relOut.endsWith('.js'))
377
+ result.islandChunks.set(entryKey, url)
378
+ if (relOut.endsWith('.css')) {
379
+ if (entry?.endsWith('.css'))
380
+ result.srcCssToUrl.set(entry, url)
381
+ for (const inKey of Object.keys(info.inputs ?? {})) {
382
+ if (inKey.endsWith('.css'))
383
+ result.srcCssToUrl.set(resolveMetaPath(inKey), url)
384
+ }
385
+ }
386
+ const cssBundle = (info as { cssBundle?: string }).cssBundle
387
+ if (cssBundle !== undefined && entryKey !== undefined)
388
+ result.islandCssUrl.set(entryKey, `${assetPrefix}/${cssBundle.replace(LEADING_DOT_SLASH_RE, '')}`)
389
+ }
390
+
391
+ recordClientFiles(result, clientResult.outputs, env, reviver)
392
+
393
+ if (cache !== undefined)
394
+ rememberClientBuild(cache, result, { signature: clientSignature, clientDir, inputFiles: [...standaloneCss, ...pluginClientEntries, ...regionClientEntries], entriesDir, actionsByFile, graph, resolveMetaPath })
395
+ return result
396
+ }
397
+
398
+ /** The emitted files, the stylesheets, each entry's static imports and the revivers, into the client build's result. */
399
+ function recordClientFiles(result: ClientBuild, outputs: readonly Bun.BuildArtifact[], env: BundleEnv, reviver: { url: string, file: string } | undefined): void {
400
+ for (const output of outputs) {
401
+ const relFile = relPosix(env.clientDir, output.path)
402
+ result.assetFiles.push(relFile)
403
+ if (relFile.endsWith('.css'))
404
+ result.styleUrls.push(`${env.assetPrefix}/${relFile}`)
405
+ }
406
+ result.chunkImports = entryStaticImports(result.metafile, env.assetPrefix)
407
+ if (reviver !== undefined) {
408
+ result.reviveScript = reviver.url
409
+ result.assetFiles.push(reviver.file)
410
+ }
411
+ }
412
+
413
+ /** Keeps what a client build produced, so the next build with the same signature and unchanged inputs reuses its files. */
414
+ function rememberClientBuild(
415
+ cache: BuildCache,
416
+ result: ClientBuild,
417
+ options: { signature: string, clientDir: string, inputFiles: string[], entriesDir: string, actionsByFile: ActionsByFile, graph: ModuleGraph, resolveMetaPath: (p: string) => string },
418
+ ): void {
419
+ const { signature, clientDir, entriesDir, actionsByFile, graph, resolveMetaPath } = options
420
+ cache.stats.clientBuilds++
421
+ prunedClientCss.delete(cache)
422
+ const inputFiles = new Set<string>(options.inputFiles)
423
+ for (const inKey of Object.keys(result.metafile?.inputs ?? {})) {
424
+ const abs = resolveMetaPath(inKey)
425
+ // Skip generated entry shims and stubbed action files (whose signature tracks exported action names/URLs, not server body).
426
+ if (abs.startsWith(entriesDir))
427
+ continue
428
+ if (actionsByFile.has(abs) && !graph.analyses.get(abs)?.isInteractive)
429
+ continue
430
+ inputFiles.add(abs)
431
+ }
432
+ cache.lastClient = {
433
+ signature,
434
+ clientDir,
435
+ inputStamps: stampFiles(inputFiles),
436
+ islandChunks: new Map(result.islandChunks),
437
+ srcCssToUrl: new Map(result.srcCssToUrl),
438
+ islandCssUrl: new Map(result.islandCssUrl),
439
+ assetFiles: [...result.assetFiles],
440
+ styleUrls: [...result.styleUrls],
441
+ runtimeScript: result.runtimeScript,
442
+ regionScript: result.regionScript,
443
+ reviveScript: result.reviveScript,
444
+ chunkImports: result.chunkImports,
445
+ }
446
+ }
447
+
448
+ // Where the server build takes each import from: `prunelle` from its source, packages that render components bundled for the SSR compiler, the rest external.
449
+ // In dev prunelle's own source stays external too: Bun never unloads a module, so a bundled copy of prunelle's runtime was evaluated again and kept on every save.
450
+ function resolveServerImports(b: PluginBuilder, isDev: boolean, root: string, reachesTsx: (file: string) => boolean, externalOutDir: boolean): void {
451
+ b.onResolve({ filter: PRUNELLE_SPECIFIER_FILTER }, (args) => {
452
+ const resolved = resolvePrunelleSpecifier(args.path)
453
+ if (resolved === undefined)
454
+ return undefined
455
+ return EXTERNAL_PRUNELLE_SPECIFIERS.has(args.path) || isDev ? { path: resolved, external: true } : { path: resolved }
456
+ })
457
+ if (isDev)
458
+ b.onResolve({ filter: new RegExp(`^${RegExp.escape(`${PRUNELLE_SRC_ROOT}/`)}`) }, args => ({ path: args.path, external: true }))
459
+ b.onResolve({ filter: PRUNELLE_SCOPE_RE }, (args) => {
460
+ try {
461
+ return { path: Bun.resolveSync(args.path, args.resolveDir || root) }
462
+ }
463
+ catch {
464
+ return undefined
465
+ }
466
+ })
467
+ b.onLoad({ filter: /.*/, namespace: 'prunelle-server-css' }, () => ({ contents: '', loader: 'js' }))
468
+ b.onResolve({ filter: /^[^./]/ }, (args) => {
469
+ if (args.path === 'bun' || args.path.startsWith('bun:') || args.path.startsWith('node:') || args.path.startsWith('~icons/') || args.path.startsWith('virtual:') || isAbsolute(args.path))
470
+ return undefined
471
+ let resolved: string | undefined
472
+ try {
473
+ resolved = Bun.resolveSync(args.path, args.resolveDir || root)
474
+ }
475
+ catch {
476
+ try {
477
+ resolved = Bun.resolveSync(args.path, root)
478
+ }
479
+ catch {
480
+ return undefined
481
+ }
482
+ }
483
+ if (resolved.endsWith('.css'))
484
+ return resolved.endsWith('.module.css') ? { path: resolved } : { path: resolved, namespace: 'prunelle-server-css' }
485
+ if (resolved.endsWith('.tsx') || reachesTsx(resolved))
486
+ return { path: resolved }
487
+ if (isTsFile(resolved)) {
488
+ if (!isInNodeModules(resolved))
489
+ return { path: resolved }
490
+ if (isDev) {
491
+ try {
492
+ const real = realpathSync(resolved)
493
+ if (!isInNodeModules(real))
494
+ return { path: resolved }
495
+ }
496
+ catch {}
497
+ }
498
+ }
499
+ if (externalOutDir)
500
+ return { path: resolved, external: true }
501
+ return undefined
502
+ })
503
+ }
504
+
505
+ /** `entry` is the generated `_entry.js`, an in-memory file bundled beside `entries` so it shares their chunks. */
506
+ export async function buildServer(env: BundleEnv, entries: string[], serverRoot: string, islandChunks: Map<string, string>, entry: { file: string, source: string }): Promise<void> {
507
+ const { root, outDir, serverDir, graph, cache, islands } = env
508
+ const transforms = pluginTransforms(env.plugins)
509
+ const externalOutDir = !isInside(root, outDir, { orSame: true })
510
+
511
+ const serverSignature = cache !== undefined
512
+ ? JSON.stringify({
513
+ serverRoot,
514
+ assetPrefix: env.assetPrefix,
515
+ isDev: env.isDev,
516
+ transforms: transforms.key,
517
+ entries: [...entries].sort(),
518
+ islandChunks: [...islandChunks.entries()].sort(([a], [b]) => a.localeCompare(b)),
519
+ reach: [...islands.reach].sort(),
520
+ bindings: [...islands.pageBindings.entries()]
521
+ .sort(([a], [b]) => a.localeCompare(b))
522
+ .map(([f, map]) => [f, [...map.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([l, t]) => [l, t.id, t.defaultHydrate ?? ''])]),
523
+ bunPlugins: env.plugins.filter(p => p.bunPlugins !== undefined).map(p => p.name),
524
+ })
525
+ : ''
526
+
527
+ if (
528
+ cache !== undefined
529
+ && cache.lastServer !== undefined
530
+ && cache.lastServer.signature === serverSignature
531
+ && stampsMatch(cache.lastServer.inputStamps)
532
+ && reuseDirFiles(cache.lastServer.serverDir, serverDir)
533
+ ) {
534
+ cache.stats.serverSkips++
535
+ cache.lastServer.serverDir = serverDir
536
+ return
537
+ }
538
+
539
+ // Whether a file renders components, directly or through what it imports: such packages are bundled so Prunelle's SSR compiler transforms them.
540
+ const tsxReach = new Map<string, boolean>()
541
+ const reachesTsx = (start: string): boolean => {
542
+ const known = tsxReach.get(start)
543
+ if (known !== undefined)
544
+ return known
545
+ if (start.endsWith('.tsx')) {
546
+ tsxReach.set(start, true)
547
+ return true
548
+ }
549
+ const seen = new Set<string>([start])
550
+ const stack = [start]
551
+ while (stack.length > 0) {
552
+ for (const dep of graph.localDeps(stack.pop()!)) {
553
+ if (dep.endsWith('.tsx') || tsxReach.get(dep) === true) {
554
+ tsxReach.set(start, true)
555
+ return true
556
+ }
557
+ if (tsxReach.get(dep) === false || seen.has(dep))
558
+ continue
559
+ seen.add(dep)
560
+ stack.push(dep)
561
+ }
562
+ }
563
+ for (const node of seen)
564
+ tsxReach.set(node, false)
565
+ return false
566
+ }
567
+
568
+ const serverPlugin: BunPlugin = {
569
+ name: 'prunelle-server',
570
+ setup(b) {
571
+ resolveServerImports(b, env.isDev, root, reachesTsx, externalOutDir)
572
+ b.onLoad({ filter: TS_FILTER }, (args) => {
573
+ if (!args.path.endsWith('.tsx')) {
574
+ if (!transforms.active || isInNodeModules(args.path))
575
+ return undefined
576
+ const raw = graph.source(args.path)
577
+ const transformed = transforms.apply(raw, args.path, 'server')
578
+ return transformed !== raw ? { contents: transformed, loader: 'ts' } : undefined
579
+ }
580
+ const analysis = graph.analyses.get(args.path)
581
+ const rawBindings = islands.pageBindings.get(args.path)
582
+ const isInteractive = analysis?.isInteractive === true
583
+ // Island code of another module may render any component of a module it imports; in its own module, only the code an island reaches.
584
+ const emitMarkers = islands.reach.has(args.path) || (isInteractive && analysis.browserSpans)
585
+ let islandMap: Map<string, IslandBinding> | undefined
586
+ let key = `${env.isDev ? 'd:' : ''}${isInteractive ? '1' : '0'}:${emitMarkers === true ? '1' : emitMarkers === false ? '0' : 's'}|t=${transforms.key}`
587
+ if (rawBindings !== undefined) {
588
+ islandMap = new Map()
589
+ for (const [localName, target] of rawBindings) {
590
+ const chunk = islandChunks.get(islandKey(target))
591
+ if (chunk !== undefined) {
592
+ islandMap.set(localName, { id: target.id, chunk, defaultHydrate: target.defaultHydrate })
593
+ key += `|${localName}=${chunk}:${target.defaultHydrate ?? ''}`
594
+ }
595
+ }
596
+ }
597
+ const stamp = graph.stamp(args.path)
598
+ const cachedSsr = stamp !== undefined ? cache?.ssrCompiled.get(args.path) : undefined
599
+ if (cachedSsr !== undefined && cachedSsr.mtimeMs === stamp!.mtimeMs && cachedSsr.size === stamp!.size && cachedSsr.key === key)
600
+ return { contents: cachedSsr.code, loader: 'tsx' }
601
+ const compiled = compileSsr(args.path, graph.source(args.path), {
602
+ analysis,
603
+ islands: islandMap,
604
+ isIsland: isInteractive,
605
+ emitMarkers,
606
+ devSourceRoot: env.isDev ? root : undefined,
607
+ } as Parameters<typeof compileSsr>[2])
608
+ const code = transforms.apply(compiled.code, args.path, 'server')
609
+ if (cache !== undefined && stamp !== undefined)
610
+ cache.ssrCompiled.set(args.path, { mtimeMs: stamp.mtimeMs, size: stamp.size, key, code })
611
+ return { contents: code, loader: 'tsx' }
612
+ })
613
+ },
614
+ }
615
+
616
+ const serverResult = await runBunBuild('server', env.root, () => {
617
+ if (transforms.failure !== undefined)
618
+ throw transforms.failure
619
+ }, {
620
+ entrypoints: [...entries, entry.file],
621
+ files: { [entry.file]: entry.source },
622
+ outdir: serverDir,
623
+ root: serverRoot,
624
+ target: 'bun',
625
+ format: 'esm',
626
+ splitting: true,
627
+ packages: 'external',
628
+ minify: false,
629
+ // A stack trace names the source file and line: Bun reads the map beside each chunk.
630
+ sourcemap: 'linked',
631
+ metafile: cache !== undefined,
632
+ define: {
633
+ 'process.env.NODE_ENV': 'process.env.NODE_ENV',
634
+ },
635
+ plugins: [serverPlugin, ...pluginBunPlugins(env, 'server')],
636
+ })
637
+
638
+ if (cache !== undefined) {
639
+ cache.stats.serverBuilds++
640
+ const inputFiles = new Set<string>(entries)
641
+ for (const inKey of Object.keys(serverResult.metafile?.inputs ?? {})) {
642
+ const fromCwd = resolve(process.cwd(), inKey)
643
+ const abs = existsSync(fromCwd) ? fromCwd : resolve(serverDir, inKey)
644
+ if (!existsSync(abs))
645
+ continue
646
+ // Plain `.css` stylesheets are bundled exclusively by `buildClient`; CSS edits must not trigger a server rebuild.
647
+ if (abs.endsWith('.css') && !abs.endsWith('.module.css'))
648
+ continue
649
+ inputFiles.add(abs)
650
+ }
651
+ cache.lastServer = {
652
+ signature: serverSignature,
653
+ serverDir,
654
+ inputStamps: stampFiles(inputFiles),
655
+ }
656
+ }
657
+ }