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