prunelle 0.8.0 → 0.9.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 (184) hide show
  1. package/llms.txt +61 -44
  2. package/package.json +7 -2
  3. package/src/a11y/declaration.ts +6 -10
  4. package/src/a11y/index.ts +69 -125
  5. package/src/animate.ts +127 -0
  6. package/src/build/asides.ts +51 -0
  7. package/src/build/bundle.ts +88 -134
  8. package/src/build/client-entries.ts +6 -6
  9. package/src/build/client-outputs.ts +75 -0
  10. package/src/build/client-plugin.ts +9 -4
  11. package/src/build/ecoindex.ts +4 -2
  12. package/src/build/files.ts +18 -0
  13. package/src/build/graph.ts +14 -6
  14. package/src/build/index.ts +20 -10
  15. package/src/build/islands.ts +4 -1
  16. package/src/build/key-types.ts +31 -0
  17. package/src/build/manifest.ts +19 -1
  18. package/src/build/plugin-host.ts +2 -0
  19. package/src/build/prerender.ts +2 -2
  20. package/src/build/reach.ts +14 -1
  21. package/src/build/report.ts +1 -1
  22. package/src/build/route-types.ts +16 -0
  23. package/src/build/routes.ts +24 -15
  24. package/src/build/seed-ids.ts +65 -0
  25. package/src/build/seed-writes.ts +111 -0
  26. package/src/build/static-headers.ts +2 -2
  27. package/src/build/static.ts +1 -1
  28. package/src/cli/check-cache.ts +51 -0
  29. package/src/cli/check-consent.ts +95 -0
  30. package/src/cli/check-forms.ts +2 -2
  31. package/src/cli/check-links-patterns.ts +101 -0
  32. package/src/cli/check-links.ts +16 -100
  33. package/src/cli/check-regions.ts +185 -0
  34. package/src/cli/check-security.ts +50 -6
  35. package/src/cli/check.ts +40 -18
  36. package/src/cli/commands.ts +134 -14
  37. package/src/cli/docs.ts +21 -2
  38. package/src/cli/index.ts +1 -1
  39. package/src/cli/inspect.ts +2 -0
  40. package/src/cli/mcp-tools.ts +2 -2
  41. package/src/cli/new.ts +9 -5
  42. package/src/cli/upgrade-names.ts +14 -2
  43. package/src/cli/upgrade.ts +3 -0
  44. package/src/compiler/analyze.ts +2 -2
  45. package/src/compiler/cacheability.ts +24 -2
  46. package/src/compiler/compliance-contrast.ts +284 -0
  47. package/src/compiler/compliance-empty.ts +24 -0
  48. package/src/compiler/compliance-rgaa-content.ts +95 -0
  49. package/src/compiler/compliance-rgaa-criteria.ts +45 -0
  50. package/src/compiler/compliance-rgaa-pages.ts +140 -0
  51. package/src/compiler/compliance-rgaa.ts +19 -0
  52. package/src/compiler/compliance-third-party.ts +59 -0
  53. package/src/compiler/compliance-urls.ts +52 -0
  54. package/src/compiler/compliance.ts +70 -42
  55. package/src/compiler/cookie-inventory.ts +119 -0
  56. package/src/compiler/foreign-imports.ts +5 -3
  57. package/src/compiler/mistakes.ts +18 -9
  58. package/src/compiler/props-pattern.ts +211 -0
  59. package/src/compiler/props.ts +177 -346
  60. package/src/compiler/ssr-emit.ts +510 -0
  61. package/src/compiler/ssr-helpers.ts +170 -121
  62. package/src/compiler/ssr.ts +25 -440
  63. package/src/context.ts +14 -1
  64. package/src/dev/child.ts +1 -1
  65. package/src/dev/hot-islands.ts +71 -0
  66. package/src/dev/index.ts +31 -18
  67. package/src/dev/protocol.ts +1 -1
  68. package/src/dev/queue.ts +3 -2
  69. package/src/dev/reload.ts +1 -1
  70. package/src/dev/supervisor.ts +3 -1
  71. package/src/dev/watchers.ts +6 -2
  72. package/src/dom/action.ts +97 -14
  73. package/src/dom/extras.ts +2 -1
  74. package/src/dom/field-marks.ts +24 -0
  75. package/src/dom/hot.ts +9 -0
  76. package/src/dom/index.ts +25 -5
  77. package/src/dom/island-hot.ts +29 -0
  78. package/src/dom/island.ts +13 -2
  79. package/src/dom/prefetch.ts +132 -0
  80. package/src/dom/regions.ts +498 -0
  81. package/src/dom/swap.ts +245 -0
  82. package/src/dom/trusted.ts +22 -0
  83. package/src/dom/upload.ts +44 -0
  84. package/src/eco/declaration.ts +39 -40
  85. package/src/eco/index.ts +5 -5
  86. package/src/href.ts +31 -0
  87. package/src/index.ts +9 -3
  88. package/src/plugins/config.ts +1 -1
  89. package/src/plugins/context.ts +7 -1
  90. package/src/plugins/daily.ts +27 -0
  91. package/src/plugins/index.ts +3 -3
  92. package/src/plugins/order.ts +1 -1
  93. package/src/plugins/public.ts +8 -5
  94. package/src/plugins/services.ts +88 -14
  95. package/src/plugins/types.ts +120 -9
  96. package/src/reactivity/hmr.ts +90 -0
  97. package/src/reactivity/index.ts +38 -18
  98. package/src/reactivity/resource.ts +115 -0
  99. package/src/reactivity/seed.ts +39 -0
  100. package/src/reactivity/server-seed.ts +194 -0
  101. package/src/reactivity/store.ts +55 -1
  102. package/src/rgpd/draft.ts +171 -0
  103. package/src/rgpd/forms.ts +85 -0
  104. package/src/rgpd/index.ts +57 -0
  105. package/src/server/action-flash.ts +1 -0
  106. package/src/server/action-registry.ts +6 -8
  107. package/src/server/action.ts +51 -19
  108. package/src/server/app-secret.ts +14 -8
  109. package/src/server/cache-invalidation.ts +96 -0
  110. package/src/server/compress.ts +3 -1
  111. package/src/server/consent.ts +16 -2
  112. package/src/server/cookie-inventory.ts +78 -0
  113. package/src/server/cookies.ts +50 -0
  114. package/src/server/csp-report.ts +86 -0
  115. package/src/server/discard.ts +13 -0
  116. package/src/server/document.ts +2 -2
  117. package/src/server/env.ts +1 -1
  118. package/src/server/errors.ts +9 -2
  119. package/src/server/field-errors.ts +91 -0
  120. package/src/server/form-schema.ts +16 -11
  121. package/src/server/health.ts +33 -12
  122. package/src/server/http.ts +25 -10
  123. package/src/server/index.ts +101 -298
  124. package/src/server/loader.ts +1 -0
  125. package/src/server/page.ts +3 -9
  126. package/src/server/plugin-host.ts +26 -8
  127. package/src/server/public.ts +14 -3
  128. package/src/server/rate-limit.ts +39 -10
  129. package/src/server/region.ts +3 -0
  130. package/src/server/request-handler.ts +370 -0
  131. package/src/server/request-log.ts +94 -0
  132. package/src/server/route-cache.ts +41 -6
  133. package/src/server/route-input.ts +54 -0
  134. package/src/server/route-table.ts +35 -19
  135. package/src/server/routing.ts +12 -11
  136. package/src/server/sanitize-html.ts +1 -1
  137. package/src/server/security.ts +38 -8
  138. package/src/server/serve-handlers.ts +9 -5
  139. package/src/server/shared-store.ts +314 -0
  140. package/src/server/start.ts +12 -5
  141. package/src/server/static-dir.ts +14 -10
  142. package/src/server/stream.ts +2 -1
  143. package/src/server/surface.ts +39 -0
  144. package/src/server/webhook.ts +48 -0
  145. package/src/server/workers.ts +168 -0
  146. package/src/ssr/consent-banner.ts +20 -16
  147. package/src/ssr/consent-texts.ts +40 -0
  148. package/src/ssr/context.ts +26 -3
  149. package/src/ssr/cookie-table.ts +75 -0
  150. package/src/ssr/index.ts +23 -13
  151. package/src/ssr/navigation.ts +161 -14
  152. package/src/test/browser.ts +50 -22
  153. package/src/test/build-reuse.ts +70 -0
  154. package/src/test/index.ts +45 -6
  155. package/src/test/mount.ts +53 -0
  156. package/src/test/outside.ts +94 -0
  157. package/templates/_shared/AGENTS.md +1 -1
  158. package/templates/_shared/Dockerfile +22 -0
  159. package/templates/_shared/dockerignore +9 -0
  160. package/templates/_shared/gitignore +2 -0
  161. package/templates/app/.env.example +3 -1
  162. package/templates/app/compose.yaml +32 -0
  163. package/templates/app/db/migrations/001_notes.sql +7 -0
  164. package/templates/app/db/schema.ts +11 -0
  165. package/templates/app/package.json +1 -0
  166. package/templates/app/prunelle.config.ts +6 -0
  167. package/templates/app/src/actions/notes.ts +26 -0
  168. package/templates/app/src/auth.ts +4 -2
  169. package/templates/app/src/db.ts +5 -0
  170. package/templates/app/src/routes/dashboard/index.tsx +26 -1
  171. package/templates/app/src/routes/privacy.tsx +6 -2
  172. package/templates/app/tests/app.test.ts +14 -3
  173. package/templates/plugin/AGENTS.md +11 -0
  174. package/templates/plugin/CLAUDE.md +1 -0
  175. package/templates/plugin/README.md +27 -0
  176. package/templates/plugin/gitignore +2 -0
  177. package/templates/plugin/llms.txt +19 -0
  178. package/templates/plugin/package.json +33 -0
  179. package/templates/plugin/src/index.ts +40 -0
  180. package/templates/plugin/tests/fixture/prunelle.config.ts +4 -0
  181. package/templates/plugin/tests/fixture/src/routes/index.tsx +11 -0
  182. package/templates/plugin/tests/plugin.test.ts +42 -0
  183. package/templates/plugin/tsconfig.json +19 -0
  184. package/ts-plugin.cjs +3674 -2196
@@ -3,22 +3,27 @@
3
3
  import type { BunPlugin, PluginBuilder } from 'bun'
4
4
  import type { IslandBinding } from '../compiler/index'
5
5
  import type { BuildPluginTarget, PrunellePlugin } from '../plugins/index'
6
+ import type { Asides } from './asides'
6
7
  import type { ClientTransforms } from './client-plugin'
7
8
  import type { BuildCache, ModuleGraph } from './graph'
8
9
  import type { ActionsByFile, IslandPlan } from './islands'
9
10
  import { copyFileSync, existsSync, linkSync, mkdirSync, readdirSync, realpathSync, writeFileSync } from 'node:fs'
10
11
  import { dirname, isAbsolute, join, relative, resolve } from 'node:path'
12
+ import { pluginSetsLang } from '../compiler/compliance'
11
13
  import { compileSsr } from '../compiler/index'
12
- import { readsPrivateEnv } from '../compiler/server-only'
13
14
  import { clientPlugin, PRUNELLE_SPECIFIER_FILTER, localIslandExports, TS_FILTER } from './client-plugin'
14
- import { formatBunBuildLogs, isInNodeModules, isTsFile, relPosix } from './files'
15
+ import { buildAsides } from './asides'
16
+ import { isInNodeModules, isTsFile, relPosix, runBunBuild } from './files'
15
17
  import { isInside } from './is-inside'
16
18
  import { stampFiles, stampsMatch } from './graph'
17
19
  import { entryStaticImports, hydrateStrategies, writeClientEntries } from './client-entries'
20
+ import { recordMetafileOutputs, scanEnvLeaks } from './client-outputs'
18
21
  import { clientLeakError, islandKey } from './islands'
19
22
  import { pluginHookError } from './plugin-host'
20
23
  import { ensureCacheGitignore } from './precompress'
24
+ import { graphUsesRegion } from './reach'
21
25
  import { PRUNELLE_SRC_ROOT, resolvePrunelleSpecifier } from './resolve'
26
+ import { nameModuleState } from './seed-ids'
22
27
 
23
28
  export interface BundleEnv {
24
29
  root: string
@@ -93,14 +98,14 @@ function reuseDirFiles(srcDir: string, dstDir: string, relFiles?: readonly strin
93
98
  }
94
99
 
95
100
  const PRUNELLE_SCOPE_RE = /^@prunellejs\//
96
- const LEADING_DOT_SLASH_RE = /^\.\//
97
101
  const EXTERNAL_PRUNELLE_SPECIFIERS = new Set(['prunelle/build', 'prunelle/test'])
98
102
 
99
103
  export function pluginBunPlugins(env: Pick<BundleEnv, 'plugins' | 'root' | 'assetPrefix' | 'minify' | 'lang'>, target: BuildPluginTarget): BunPlugin[] {
100
104
  const { root, assetPrefix, minify, lang } = env
105
+ const multiLocale = pluginSetsLang(env.plugins)
101
106
  return env.plugins.flatMap((p) => {
102
107
  const bp = p.bunPlugins
103
- return typeof bp === 'function' ? bp({ root, assetPrefix, minify, target, lang }) : bp ?? []
108
+ return typeof bp === 'function' ? bp({ root, assetPrefix, minify, target, lang, multiLocale }) : bp ?? []
104
109
  })
105
110
  }
106
111
 
@@ -131,23 +136,6 @@ function pluginTransforms(plugins: PrunellePlugin[]): ClientTransforms {
131
136
  return transforms
132
137
  }
133
138
 
134
- /** Runs Bun.build, failing first with what `ownFailure` throws (a leak, a plugin hook), then with Bun's own logs. */
135
- async function runBunBuild(side: 'client' | 'server', root: string, ownFailure: () => void, config: Parameters<typeof Bun.build>[0]): Promise<Awaited<ReturnType<typeof Bun.build>>> {
136
- let result: Awaited<ReturnType<typeof Bun.build>>
137
- try {
138
- result = await Bun.build(config)
139
- }
140
- catch (err) {
141
- ownFailure()
142
- if (err instanceof AggregateError && err.errors.length > 0)
143
- throw new Error(`prunelle build (${side}) failed:\n${formatBunBuildLogs(err.errors, root)}`)
144
- throw err
145
- }
146
- ownFailure()
147
- if (!result.success)
148
- throw new Error(`prunelle build (${side}) failed:\n${formatBunBuildLogs(result.logs, root)}`)
149
- return result
150
- }
151
139
 
152
140
  /** CSS files imported outside islands (plus the plugins' own), built as standalone stylesheets. */
153
141
  export function standaloneCssFiles(graph: ModuleGraph, pluginCss: string[], islandCss: Set<string>): string[] {
@@ -180,19 +168,6 @@ export interface ClientBuild {
180
168
  metafile: Bun.BuildOutput['metafile']
181
169
  }
182
170
 
183
- /** 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. */
184
- async function buildReviver(env: BundleEnv): Promise<{ url: string, file: string }> {
185
- const built = await runBunBuild('client', env.root, () => {}, {
186
- entrypoints: [join(PRUNELLE_SRC_ROOT, 'dom/revive.ts')],
187
- outdir: env.clientDir,
188
- target: 'browser',
189
- format: 'esm',
190
- minify: env.minify,
191
- naming: '[name]-[hash].[ext]',
192
- })
193
- const file = relPosix(env.clientDir, built.outputs[0]!.path)
194
- return { url: `${env.assetPrefix}/${file}`, file }
195
- }
196
171
 
197
172
  function publicEnvDefines(): Record<string, string> {
198
173
  const defines: Record<string, string> = {}
@@ -208,7 +183,7 @@ function buildClientSignature(
208
183
  env: BundleEnv,
209
184
  standaloneCss: readonly string[],
210
185
  pluginClientEntries: readonly string[],
211
- regionClientEntries: readonly string[],
186
+ hasRegions: boolean,
212
187
  transformsKey: string,
213
188
  strategies: ReturnType<typeof hydrateStrategies>['strategies'],
214
189
  hasClientOnlyHydrate: boolean,
@@ -218,14 +193,15 @@ function buildClientSignature(
218
193
  return ''
219
194
  return JSON.stringify({
220
195
  minify: env.minify,
221
- assetPrefix: env.assetPrefix, lang: env.lang,
196
+ assetPrefix: env.assetPrefix, lang: env.lang, multiLocale: pluginSetsLang(env.plugins),
222
197
  isDev: env.isDev,
198
+ seeds: env.islands.seedsModuleState,
223
199
  nodeEnv: env.nodeEnv ?? (env.isDev ? 'development' : 'production'),
224
200
  transforms: transformsKey,
225
201
  strategies,
226
202
  hasClientOnlyHydrate,
227
203
  pluginClientEntries,
228
- regionClientEntries,
204
+ hasRegions,
229
205
  standaloneCss: [...standaloneCss].sort(),
230
206
  islands: [...env.islands.targets.entries()]
231
207
  .sort(([a], [b]) => a.localeCompare(b))
@@ -235,11 +211,14 @@ function buildClientSignature(
235
211
  .map(([f, list]) => [f, list.map(a => `${a.exportName}=${a.url}`)]),
236
212
  envDefines: Object.entries(envDefines).sort(([a], [b]) => a.localeCompare(b)),
237
213
  bunPlugins: env.plugins.filter(p => p.bunPlugins !== undefined).map(p => p.name),
214
+ cssSources: env.plugins.some(p => p.affectsClientCss === true)
215
+ ? [...env.graph.analyses.keys()].filter(f => !isInNodeModules(f)).sort()
216
+ : [],
238
217
  })
239
218
  }
240
219
 
241
220
  export async function buildClient(env: BundleEnv, standaloneCss: string[]): Promise<ClientBuild> {
242
- const { root, clientDir, assetPrefix, graph, cache, actionsByFile, islands } = env
221
+ const { root, clientDir, graph, cache, actionsByFile, islands } = env
243
222
  const result: ClientBuild = {
244
223
  islandChunks: new Map(),
245
224
  srcCssToUrl: new Map(),
@@ -253,8 +232,8 @@ export async function buildClient(env: BundleEnv, standaloneCss: string[]): Prom
253
232
  metafile: undefined,
254
233
  }
255
234
  const pluginClientEntries = env.plugins.map(p => p.clientEntry).filter((e): e is string => Boolean(e))
256
- const regionClientEntries = env.plugins.map(p => p.regionClientEntry).filter((e): e is string => Boolean(e))
257
- if (islands.targets.size === 0 && pluginClientEntries.length === 0 && regionClientEntries.length === 0 && standaloneCss.length === 0) {
235
+ const hasRegions = graphUsesRegion(graph)
236
+ if (islands.targets.size === 0 && pluginClientEntries.length === 0 && !hasRegions && standaloneCss.length === 0) {
258
237
  if (cache !== undefined) {
259
238
  cache.lastClient = undefined
260
239
  prunedClientCss.delete(cache)
@@ -266,42 +245,22 @@ export async function buildClient(env: BundleEnv, standaloneCss: string[]): Prom
266
245
  const { strategies, hasClientOnlyHydrate } = hydrateStrategies(graph.analyses.values())
267
246
 
268
247
  const envDefines = publicEnvDefines()
269
- const clientSignature = buildClientSignature(env, standaloneCss, pluginClientEntries, regionClientEntries, transforms.key, strategies, hasClientOnlyHydrate, envDefines)
248
+ const clientSignature = buildClientSignature(env, standaloneCss, pluginClientEntries, hasRegions, transforms.key, strategies, hasClientOnlyHydrate, envDefines)
270
249
 
271
- if (
272
- cache !== undefined
273
- && !env.analyze
274
- && cache.lastClient !== undefined
275
- && cache.lastClient.signature === clientSignature
276
- && stampsMatch(cache.lastClient.inputStamps)
277
- && reuseDirFiles(cache.lastClient.clientDir, clientDir, cache.lastClient.assetFiles, prunedClientCss.get(cache))
278
- ) {
279
- cache.stats.clientSkips++
280
- cache.lastClient.clientDir = clientDir
281
- return {
282
- islandChunks: new Map(cache.lastClient.islandChunks),
283
- srcCssToUrl: new Map(cache.lastClient.srcCssToUrl),
284
- islandCssUrl: new Map(cache.lastClient.islandCssUrl),
285
- assetFiles: [...cache.lastClient.assetFiles],
286
- styleUrls: [...cache.lastClient.styleUrls],
287
- runtimeScript: cache.lastClient.runtimeScript,
288
- regionScript: cache.lastClient.regionScript,
289
- reviveScript: cache.lastClient.reviveScript,
290
- chunkImports: cache.lastClient.chunkImports,
291
- metafile: undefined,
292
- }
293
- }
250
+ const reused = reuseClientBuild(env, clientSignature)
251
+ if (reused !== undefined)
252
+ return reused
294
253
 
295
254
  // 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.
296
255
  const entriesDir = join(root, '.prunelle-cache/entries')
297
256
  mkdirSync(entriesDir, { recursive: true })
298
257
  ensureCacheGitignore(dirname(entriesDir))
299
- const { entryPoints, islandEntryToKey, runtimeEntryPath, regionEntryPath } = writeClientEntries(env, entriesDir, { pluginClientEntries, regionClientEntries, hasClientOnlyHydrate, standaloneCss })
258
+ const { entryPoints, islandEntryToKey, runtimeEntryPath, regionEntryPath } = writeClientEntries(env, entriesDir, { pluginClientEntries, hasRegions, hasClientOnlyHydrate, standaloneCss })
300
259
 
301
260
  const clientLeaks = new Set<string>()
302
261
  const inlinedEnvKey = (key: string): boolean => key === 'NODE_ENV' || `process.env.${key}` in envDefines
303
- const plugin = clientPlugin({ root, isDev: env.isDev, graph, cache, actionsByFile, transforms, leaks: clientLeaks, localExports: localIslandExports(islands.targets.values()), clientKeep: islands.clientKeep })
304
- const reviver = islands.targets.size > 0 ? await buildReviver(env) : undefined
262
+ const plugin = clientPlugin({ root, isDev: env.isDev, graph, cache, actionsByFile, transforms, leaks: clientLeaks, localExports: localIslandExports(islands.targets.values()), clientKeep: islands.clientKeep, seedsModuleState: islands.seedsModuleState })
263
+ const asides = await buildAsides(env, islands.targets.size > 0)
305
264
 
306
265
  const clientResult = await runBunBuild('client', env.root, () => {
307
266
  if (clientLeaks.size > 0)
@@ -317,9 +276,9 @@ export async function buildClient(env: BundleEnv, standaloneCss: string[]): Prom
317
276
  minify: env.minify,
318
277
  metafile: true,
319
278
  naming: '[name]-[hash].[ext]',
320
- external: reviver === undefined ? [] : [reviver.url],
279
+ external: asides.external,
321
280
  define: {
322
- ...(reviver === undefined ? {} : { PRUNELLE_REVIVE: JSON.stringify(reviver.url) }),
281
+ ...asides.define,
323
282
  PRUNELLE_VISIBLE: String(strategies.visible),
324
283
  PRUNELLE_IDLE: String(strategies.idle),
325
284
  PRUNELLE_INTERACTION: String(strategies.interaction),
@@ -345,62 +304,53 @@ export async function buildClient(env: BundleEnv, standaloneCss: string[]): Prom
345
304
  return abs
346
305
  }
347
306
 
348
- // 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.
349
- for (const output of clientResult.outputs) {
350
- if (!output.path.endsWith('.js'))
351
- continue
352
- const js = await output.text()
353
- if (!js.includes('process.env') && !js.includes('Bun.env'))
354
- continue
355
- const relFile = relPosix(clientDir, output.path)
356
- const info = metafile?.outputs[relFile] ?? metafile?.outputs[`./${relFile}`]
357
- for (const [inKey, input] of Object.entries(info?.inputs ?? {})) {
358
- if (input.bytesInOutput <= 0)
359
- continue
360
- const abs = resolveMetaPath(inKey)
361
- let program = graph.analyses.get(abs)?.program
362
- if (program === undefined && existsSync(abs) && isTsFile(abs) && !isInNodeModules(abs))
363
- program = graph.load(abs).program
364
- if (program !== undefined && readsPrivateEnv(program, inlinedEnvKey))
365
- clientLeaks.add(`${relPosix(root, abs)} reads process.env or Bun.env (only a process.env.PUBLIC_* set at build time is inlined)`)
366
- }
367
- }
307
+ await scanEnvLeaks(clientResult.outputs, metafile, env, resolveMetaPath, inlinedEnvKey, clientLeaks)
368
308
  if (clientLeaks.size > 0)
369
309
  throw clientLeakError(clientLeaks)
370
310
 
371
- for (const [outKey, info] of Object.entries(metafile?.outputs ?? {})) {
372
- const relOut = outKey.replace(LEADING_DOT_SLASH_RE, '')
373
- const url = `${assetPrefix}/${relOut}`
374
- const entry = info.entryPoint === undefined ? undefined : resolveMetaPath(info.entryPoint)
375
- if (entry !== undefined && entry === runtimeEntryPath && relOut.endsWith('.js'))
376
- result.runtimeScript = url
377
- if (entry !== undefined && entry === regionEntryPath && relOut.endsWith('.js'))
378
- result.regionScript = url
379
- const entryKey = entry === undefined ? undefined : islandEntryToKey.get(entry)
380
- if (entryKey !== undefined && relOut.endsWith('.js'))
381
- result.islandChunks.set(entryKey, url)
382
- if (relOut.endsWith('.css')) {
383
- if (entry?.endsWith('.css'))
384
- result.srcCssToUrl.set(entry, url)
385
- for (const inKey of Object.keys(info.inputs ?? {})) {
386
- if (inKey.endsWith('.css'))
387
- result.srcCssToUrl.set(resolveMetaPath(inKey), url)
388
- }
389
- }
390
- const cssBundle = (info as { cssBundle?: string }).cssBundle
391
- if (cssBundle !== undefined && entryKey !== undefined)
392
- result.islandCssUrl.set(entryKey, `${assetPrefix}/${cssBundle.replace(LEADING_DOT_SLASH_RE, '')}`)
393
- }
311
+ recordMetafileOutputs(result, metafile, env, islandEntryToKey, runtimeEntryPath, regionEntryPath, resolveMetaPath)
394
312
 
395
- recordClientFiles(result, clientResult.outputs, env, reviver)
313
+ recordClientFiles(result, clientResult.outputs, env, asides)
396
314
 
397
- if (cache !== undefined)
398
- rememberClientBuild(cache, result, { signature: clientSignature, clientDir, inputFiles: [...standaloneCss, ...pluginClientEntries, ...regionClientEntries], entriesDir, actionsByFile, graph, resolveMetaPath })
315
+ if (cache !== undefined) {
316
+ const affectsClientCss = env.plugins.some(p => p.affectsClientCss === true)
317
+ const cssSourceFiles = affectsClientCss ? [...graph.analyses.keys()].filter(f => !isInNodeModules(f)) : []
318
+ rememberClientBuild(cache, result, { signature: clientSignature, clientDir, inputFiles: [...standaloneCss, ...pluginClientEntries, ...cssSourceFiles], entriesDir, actionsByFile, graph, resolveMetaPath })
319
+ }
399
320
  return result
400
321
  }
401
322
 
402
- /** The emitted files, the stylesheets, each entry's static imports and the revivers, into the client build's result. */
403
- function recordClientFiles(result: ClientBuild, outputs: readonly Bun.BuildArtifact[], env: BundleEnv, reviver: { url: string, file: string } | undefined): void {
323
+ // The last client build, when nothing it read changed: its files are linked into the new dir and its result handed back.
324
+ function reuseClientBuild(env: BundleEnv, clientSignature: string): ClientBuild | undefined {
325
+ const { clientDir, cache } = env
326
+ if (
327
+ cache === undefined
328
+ || env.analyze
329
+ || cache.lastClient === undefined
330
+ || cache.lastClient.signature !== clientSignature
331
+ || !stampsMatch(cache.lastClient.inputStamps)
332
+ || !reuseDirFiles(cache.lastClient.clientDir, clientDir, cache.lastClient.assetFiles, prunedClientCss.get(cache))
333
+ ) {
334
+ return undefined
335
+ }
336
+ cache.stats.clientSkips++
337
+ cache.lastClient.clientDir = clientDir
338
+ return {
339
+ islandChunks: new Map(cache.lastClient.islandChunks),
340
+ srcCssToUrl: new Map(cache.lastClient.srcCssToUrl),
341
+ islandCssUrl: new Map(cache.lastClient.islandCssUrl),
342
+ assetFiles: [...cache.lastClient.assetFiles],
343
+ styleUrls: [...cache.lastClient.styleUrls],
344
+ runtimeScript: cache.lastClient.runtimeScript,
345
+ regionScript: cache.lastClient.regionScript,
346
+ reviveScript: cache.lastClient.reviveScript,
347
+ chunkImports: cache.lastClient.chunkImports,
348
+ metafile: undefined,
349
+ }
350
+ }
351
+
352
+ /** The emitted files, the stylesheets, each entry's static imports and the modules built aside, into the client build's result. */
353
+ function recordClientFiles(result: ClientBuild, outputs: readonly Bun.BuildArtifact[], env: BundleEnv, asides: Asides): void {
404
354
  for (const output of outputs) {
405
355
  const relFile = relPosix(env.clientDir, output.path)
406
356
  result.assetFiles.push(relFile)
@@ -408,10 +358,8 @@ function recordClientFiles(result: ClientBuild, outputs: readonly Bun.BuildArtif
408
358
  result.styleUrls.push(`${env.assetPrefix}/${relFile}`)
409
359
  }
410
360
  result.chunkImports = entryStaticImports(result.metafile, env.assetPrefix)
411
- if (reviver !== undefined) {
412
- result.reviveScript = reviver.url
413
- result.assetFiles.push(reviver.file)
414
- }
361
+ result.reviveScript = asides.reviveScript
362
+ result.assetFiles.push(...asides.files)
415
363
  }
416
364
 
417
365
  /** Keeps what a client build produced, so the next build with the same signature and unchanged inputs reuses its files. */
@@ -449,6 +397,16 @@ function rememberClientBuild(
449
397
  }
450
398
  }
451
399
 
400
+ // A path under node_modules that a link leads to app sources, such as a workspace package.
401
+ function isLinkedSource(resolved: string): boolean {
402
+ try {
403
+ return !isInNodeModules(realpathSync(resolved))
404
+ }
405
+ catch {
406
+ return false
407
+ }
408
+ }
409
+
452
410
  // Where the server build takes each import from: `prunelle` from its source, packages that render components bundled for the SSR compiler, the rest external.
453
411
  // 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.
454
412
  function resolveServerImports(b: PluginBuilder, isDev: boolean, root: string, reachesTsx: (file: string) => boolean, externalOutDir: boolean): void {
@@ -491,14 +449,8 @@ function resolveServerImports(b: PluginBuilder, isDev: boolean, root: string, re
491
449
  if (isTsFile(resolved)) {
492
450
  if (!isInNodeModules(resolved))
493
451
  return { path: resolved }
494
- if (isDev) {
495
- try {
496
- const real = realpathSync(resolved)
497
- if (!isInNodeModules(real))
498
- return { path: resolved }
499
- }
500
- catch {}
501
- }
452
+ if (isDev && isLinkedSource(resolved))
453
+ return { path: resolved }
502
454
  }
503
455
  if (externalOutDir)
504
456
  return { path: resolved, external: true }
@@ -515,8 +467,9 @@ export async function buildServer(env: BundleEnv, entries: string[], serverRoot:
515
467
  const serverSignature = cache !== undefined
516
468
  ? JSON.stringify({
517
469
  serverRoot,
518
- assetPrefix: env.assetPrefix, lang: env.lang,
470
+ assetPrefix: env.assetPrefix, lang: env.lang, multiLocale: pluginSetsLang(env.plugins),
519
471
  isDev: env.isDev,
472
+ seeds: islands.seedsModuleState,
520
473
  transforms: transforms.key,
521
474
  entries: [...entries].sort(),
522
475
  islandChunks: [...islandChunks.entries()].sort(([a], [b]) => a.localeCompare(b)),
@@ -575,10 +528,11 @@ export async function buildServer(env: BundleEnv, entries: string[], serverRoot:
575
528
  resolveServerImports(b, env.isDev, root, reachesTsx, externalOutDir)
576
529
  b.onLoad({ filter: TS_FILTER }, (args) => {
577
530
  if (!args.path.endsWith('.tsx')) {
578
- if (!transforms.active || isInNodeModules(args.path))
531
+ if (isInNodeModules(args.path))
579
532
  return undefined
580
533
  const raw = graph.source(args.path)
581
- const transformed = transforms.apply(raw, args.path, 'server')
534
+ const named = islands.seedsModuleState ? nameModuleState(raw, args.path, relPosix(root, args.path), 'server') : raw
535
+ const transformed = transforms.active ? transforms.apply(named, args.path, 'server') : named
582
536
  return transformed !== raw ? { contents: transformed, loader: 'ts' } : undefined
583
537
  }
584
538
  const analysis = graph.analyses.get(args.path)
@@ -587,7 +541,7 @@ export async function buildServer(env: BundleEnv, entries: string[], serverRoot:
587
541
  // Island code of another module may render any component of a module it imports; in its own module, only the code an island reaches.
588
542
  const emitMarkers = islands.reach.has(args.path) || (isInteractive && analysis.browserSpans)
589
543
  let islandMap: Map<string, IslandBinding> | undefined
590
- let key = `${env.isDev ? 'd:' : ''}${isInteractive ? '1' : '0'}:${emitMarkers === true ? '1' : emitMarkers === false ? '0' : 's'}|t=${transforms.key}`
544
+ let key = `${env.isDev ? 'd:' : ''}${islands.seedsModuleState ? 'n' : ''}${isInteractive ? '1' : '0'}:${emitMarkers === true ? '1' : emitMarkers === false ? '0' : 's'}|t=${transforms.key}`
591
545
  if (rawBindings !== undefined) {
592
546
  islandMap = new Map()
593
547
  for (const [localName, target] of rawBindings) {
@@ -609,7 +563,7 @@ export async function buildServer(env: BundleEnv, entries: string[], serverRoot:
609
563
  emitMarkers,
610
564
  devSourceRoot: env.isDev ? root : undefined,
611
565
  } as Parameters<typeof compileSsr>[2])
612
- const code = transforms.apply(compiled.code, args.path, 'server')
566
+ const code = transforms.apply(islands.seedsModuleState ? nameModuleState(compiled.code, args.path, relPosix(root, args.path), 'server') : compiled.code, args.path, 'server')
613
567
  if (cache !== undefined && stamp !== undefined)
614
568
  cache.ssrCompiled.set(args.path, { mtimeMs: stamp.mtimeMs, size: stamp.size, key, code })
615
569
  return { contents: code, loader: 'tsx' }
@@ -36,12 +36,12 @@ export interface ClientEntryFiles {
36
36
  entryPoints: string[]
37
37
  islandEntryToKey: Map<string, string>
38
38
  runtimeEntryPath: string | undefined
39
- /** The plugins' `regionClientEntry` modules, bundled apart so only the routes that render a `<Region>` load them. */
39
+ /** The core `<Region>` client bundle, built apart so only the routes that render a `<Region>` load it. */
40
40
  regionEntryPath: string | undefined
41
41
  }
42
42
 
43
- export function writeClientEntries(env: BundleEnv, entriesDir: string, options: { pluginClientEntries: string[], regionClientEntries: string[], hasClientOnlyHydrate: boolean, standaloneCss: string[] }): ClientEntryFiles {
44
- const { pluginClientEntries, regionClientEntries, hasClientOnlyHydrate } = options
43
+ export function writeClientEntries(env: BundleEnv, entriesDir: string, options: { pluginClientEntries: string[], hasRegions: boolean, hasClientOnlyHydrate: boolean, standaloneCss: string[] }): ClientEntryFiles {
44
+ const { pluginClientEntries, hasRegions, hasClientOnlyHydrate } = options
45
45
  const out: ClientEntryFiles = { entryPoints: [], islandEntryToKey: new Map(), runtimeEntryPath: undefined, regionEntryPath: undefined }
46
46
  if (env.islands.targets.size > 0 || pluginClientEntries.length > 0) {
47
47
  const runtimeLines: string[] = []
@@ -55,16 +55,16 @@ export function writeClientEntries(env: BundleEnv, entriesDir: string, options:
55
55
  writeEntry(out.runtimeEntryPath, `${runtimeLines.join('\n')}\n`)
56
56
  out.entryPoints.push(out.runtimeEntryPath)
57
57
  }
58
- if (regionClientEntries.length > 0) {
58
+ if (hasRegions) {
59
59
  out.regionEntryPath = join(entriesDir, 'regions.ts')
60
- writeEntry(out.regionEntryPath, `${regionClientEntries.map(pe => `import ${JSON.stringify(pe)};`).join('\n')}\n`)
60
+ writeEntry(out.regionEntryPath, `import { initRegions } from 'prunelle/internal/regions';\ninitRegions();\n`)
61
61
  out.entryPoints.push(out.regionEntryPath)
62
62
  }
63
63
 
64
64
  out.entryPoints.push(...options.standaloneCss)
65
65
 
66
66
  // Each island hands the loader the DOM runtime its chunk imports anyway, so a page whose islands all wait downloads the loader alone.
67
- const domExports = `export { hydrate${hasClientOnlyHydrate ? ', mount' : ''} } from 'prunelle/internal/dom';\n`
67
+ const domExports = `export { hydrate${hasClientOnlyHydrate ? ', mount' : ''} } from 'prunelle/internal/dom';\n${env.isDev ? `export { hotMount } from 'prunelle/internal/hot';\n` : ''}`
68
68
  for (const [key, target] of env.islands.targets) {
69
69
  const entryPath = join(entriesDir, `${target.id}.ts`)
70
70
  const exportStmt = target.exportName === 'default'
@@ -0,0 +1,75 @@
1
+ // What the client build's metafile and chunks are read for: env keys left un-inlined, and the files each entry emitted.
2
+
3
+ import type { BundleEnv, ClientBuild } from './bundle'
4
+ import { existsSync } from 'node:fs'
5
+ import { readsPrivateEnv } from '../compiler/server-only'
6
+ import { isInNodeModules, isTsFile, relPosix } from './files'
7
+
8
+ const LEADING_DOT_SLASH_RE = /^\.\//
9
+
10
+ // 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.
11
+ export async function scanEnvLeaks(
12
+ outputs: readonly Bun.BuildArtifact[],
13
+ metafile: ClientBuild['metafile'],
14
+ env: BundleEnv,
15
+ resolveMetaPath: (p: string) => string,
16
+ inlinedEnvKey: (key: string) => boolean,
17
+ clientLeaks: Set<string>,
18
+ ): Promise<void> {
19
+ const { root, clientDir, graph } = env
20
+ for (const output of outputs) {
21
+ if (!output.path.endsWith('.js'))
22
+ continue
23
+ const js = await output.text()
24
+ if (!js.includes('process.env') && !js.includes('Bun.env'))
25
+ continue
26
+ const relFile = relPosix(clientDir, output.path)
27
+ const info = metafile?.outputs[relFile] ?? metafile?.outputs[`./${relFile}`]
28
+ for (const [inKey, input] of Object.entries(info?.inputs ?? {})) {
29
+ if (input.bytesInOutput <= 0)
30
+ continue
31
+ const abs = resolveMetaPath(inKey)
32
+ let program = graph.analyses.get(abs)?.program
33
+ if (program === undefined && existsSync(abs) && isTsFile(abs) && !isInNodeModules(abs))
34
+ program = graph.load(abs).program
35
+ if (program !== undefined && readsPrivateEnv(program, inlinedEnvKey))
36
+ clientLeaks.add(`${relPosix(root, abs)} reads process.env or Bun.env (only a process.env.PUBLIC_* set at build time is inlined)`)
37
+ }
38
+ }
39
+ }
40
+
41
+ // Each emitted file of the metafile into the result: the runtime and region scripts, the island chunks and the stylesheets.
42
+ export function recordMetafileOutputs(
43
+ result: ClientBuild,
44
+ metafile: ClientBuild['metafile'],
45
+ env: BundleEnv,
46
+ islandEntryToKey: ReadonlyMap<string, string>,
47
+ runtimeEntryPath: string | undefined,
48
+ regionEntryPath: string | undefined,
49
+ resolveMetaPath: (p: string) => string,
50
+ ): void {
51
+ const { assetPrefix } = env
52
+ for (const [outKey, info] of Object.entries(metafile?.outputs ?? {})) {
53
+ const relOut = outKey.replace(LEADING_DOT_SLASH_RE, '')
54
+ const url = `${assetPrefix}/${relOut}`
55
+ const entry = info.entryPoint === undefined ? undefined : resolveMetaPath(info.entryPoint)
56
+ if (entry !== undefined && entry === runtimeEntryPath && relOut.endsWith('.js'))
57
+ result.runtimeScript = url
58
+ if (entry !== undefined && entry === regionEntryPath && relOut.endsWith('.js'))
59
+ result.regionScript = url
60
+ const entryKey = entry === undefined ? undefined : islandEntryToKey.get(entry)
61
+ if (entryKey !== undefined && relOut.endsWith('.js'))
62
+ result.islandChunks.set(entryKey, url)
63
+ if (relOut.endsWith('.css')) {
64
+ if (entry?.endsWith('.css'))
65
+ result.srcCssToUrl.set(entry, url)
66
+ for (const inKey of Object.keys(info.inputs ?? {})) {
67
+ if (inKey.endsWith('.css'))
68
+ result.srcCssToUrl.set(resolveMetaPath(inKey), url)
69
+ }
70
+ }
71
+ const cssBundle = (info as { cssBundle?: string }).cssBundle
72
+ if (cssBundle !== undefined && entryKey !== undefined)
73
+ result.islandCssUrl.set(entryKey, `${assetPrefix}/${cssBundle.replace(LEADING_DOT_SLASH_RE, '')}`)
74
+ }
75
+ }
@@ -9,6 +9,7 @@ import { SERVER_ONLY_FILTER } from '../compiler/server-only'
9
9
  import { pruneForClient } from './client-prune'
10
10
  import { isInNodeModules, relPosix } from './files'
11
11
  import { resolvePrunelleSpecifier } from './resolve'
12
+ import { nameModuleState } from './seed-ids'
12
13
 
13
14
  export const PRUNELLE_SPECIFIER_FILTER = /^prunelle(?:\/.*)?$/
14
15
  export const TS_FILTER = /\.(?:ts|tsx)$/
@@ -36,6 +37,8 @@ export interface ClientPluginEnv {
36
37
  localExports: ReadonlyMap<string, string>
37
38
  /** Per file the browser loads only for its own islands, the top-level names its client copy keeps. */
38
39
  clientKeep: ReadonlyMap<string, ReadonlySet<string>>
40
+ /** Some module could write module state while an island renders, so the module's signals and stores are named for the page to seed. */
41
+ seedsModuleState: boolean
39
42
  }
40
43
 
41
44
  /** The `export { … }` statement each file needs so the client entry can import the islands the file does not export. */
@@ -117,7 +120,7 @@ export function directPrunelleImports(code: string, graph: ModuleGraph, filename
117
120
  }
118
121
 
119
122
  export function clientPlugin(env: ClientPluginEnv): BunPlugin {
120
- const { root, isDev, graph, cache, actionsByFile, transforms, leaks, localExports, clientKeep } = env
123
+ const { root, isDev, graph, cache, actionsByFile, transforms, leaks, localExports, clientKeep, seedsModuleState } = env
121
124
  return {
122
125
  name: 'prunelle-client',
123
126
  setup(b) {
@@ -146,7 +149,8 @@ export function clientPlugin(env: ClientPluginEnv): BunPlugin {
146
149
 
147
150
  if (!args.path.endsWith('.tsx')) {
148
151
  const raw = graph.source(args.path)
149
- const own = transforms.active && !isInNodeModules(args.path) ? transforms.apply(raw, args.path, 'client') : raw
152
+ const named = isInNodeModules(args.path) || !seedsModuleState ? raw : nameModuleState(raw, args.path, relPosix(root, args.path), 'client')
153
+ const own = transforms.active && !isInNodeModules(args.path) ? transforms.apply(named, args.path, 'client') : named
150
154
  const direct = directPrunelleImports(own, graph, args.path)
151
155
  return direct !== raw ? { contents: direct, loader: 'ts' } : undefined
152
156
  }
@@ -154,7 +158,7 @@ export function clientPlugin(env: ClientPluginEnv): BunPlugin {
154
158
  const stamp = graph.stamp(args.path)
155
159
  const extraExports = localExports.get(args.path) ?? ''
156
160
  const keep = clientKeep.get(args.path)
157
- const key = `${isDev ? 'd:' : ''}${transforms.key}${extraExports}${keep === undefined ? '' : `|keep=${[...keep].sort().join(',')}`}`
161
+ const key = `${isDev ? 'd:' : ''}${seedsModuleState ? 'n:' : ''}${transforms.key}${extraExports}${keep === undefined ? '' : `|keep=${[...keep].sort().join(',')}`}`
158
162
  const cachedDom = stamp !== undefined ? cache?.domCompiled.get(args.path) : undefined
159
163
  if (cachedDom !== undefined && cachedDom.mtimeMs === stamp!.mtimeMs && cachedDom.size === stamp!.size && (cachedDom.key ?? '') === key)
160
164
  return { contents: cachedDom.code, loader: 'tsx' }
@@ -165,7 +169,8 @@ export function clientPlugin(env: ClientPluginEnv): BunPlugin {
165
169
  ...(clientSource === source ? { analysis } : {}),
166
170
  devSourceRoot: isDev ? root : undefined,
167
171
  })
168
- const compiled = directPrunelleImports(transforms.apply(dom.code, args.path, 'client'), graph, args.path) + extraExports
172
+ const named = isInNodeModules(args.path) || !seedsModuleState ? dom.code : nameModuleState(dom.code, args.path, relPosix(root, args.path), 'client')
173
+ const compiled = directPrunelleImports(transforms.apply(named, args.path, 'client'), graph, args.path) + extraExports
169
174
  if (cache !== undefined && stamp !== undefined)
170
175
  cache.domCompiled.set(args.path, { mtimeMs: stamp.mtimeMs, size: stamp.size, key, code: compiled })
171
176
  return { contents: compiled, loader: 'tsx' }
@@ -175,10 +175,12 @@ export function computeEcoIndex(inputs: EcoIndexInputs): Omit<RouteEcoIndex, 'ur
175
175
  const qReq = computeQuantile(QUANTILES_REQ, requests)
176
176
  const qSize = computeQuantile(QUANTILES_SIZE, weightBytes / 1000)
177
177
  const raw = 100 - (5 * (3 * qDom + 2 * qReq + qSize)) / 6
178
- const score = Math.round(Math.min(100, Math.max(0, raw)))
178
+ const exact = Math.min(100, Math.max(0, raw))
179
+ const score = Math.round(exact)
179
180
  const ghgGrams = Math.round((2 + (2 * (50 - score)) / 100) * 100) / 100
180
181
  const waterCl = Math.round((3 + (3 * (50 - score)) / 100) * 100) / 100
181
- return { grade: gradeForScore(score), score, dom, requests, weightBytes, ghgGrams, waterCl }
182
+ // The reference grades the unrounded score: 80.2 shows as 80 and is still an A.
183
+ return { grade: gradeForScore(exact), score, dom, requests, weightBytes, ghgGrams, waterCl }
182
184
  }
183
185
 
184
186
  function htmlServedSize(abs: string, raw: Uint8Array): number {
@@ -169,3 +169,21 @@ export function isHiddenPublicPath(rel: string): boolean {
169
169
  const segments = rel.split(/[\\/]/).filter(s => s !== '')
170
170
  return segments.some((s, i) => s.startsWith('.') && !(i === 0 && s === '.well-known'))
171
171
  }
172
+
173
+ /** Runs Bun.build, failing first with what `ownFailure` throws (a leak, a plugin hook), then with Bun's own logs. */
174
+ export async function runBunBuild(side: 'client' | 'server', root: string, ownFailure: () => void, config: Parameters<typeof Bun.build>[0]): Promise<Awaited<ReturnType<typeof Bun.build>>> {
175
+ let result: Awaited<ReturnType<typeof Bun.build>>
176
+ try {
177
+ result = await Bun.build(config)
178
+ }
179
+ catch (err) {
180
+ ownFailure()
181
+ if (err instanceof AggregateError && err.errors.length > 0)
182
+ throw new Error(`prunelle build (${side}) failed:\n${formatBunBuildLogs(err.errors, root)}`)
183
+ throw err
184
+ }
185
+ ownFailure()
186
+ if (!result.success)
187
+ throw new Error(`prunelle build (${side}) failed:\n${formatBunBuildLogs(result.logs, root)}`)
188
+ return result
189
+ }
@@ -1,6 +1,7 @@
1
1
  // The module graph of one build: every .ts/.tsx file reachable from the routes, analyzed once (and reused across `prunelle dev` rebuilds while mtime and size match).
2
2
 
3
3
  import type { ModuleAnalysis } from '../compiler/index'
4
+ import type { Stats } from 'node:fs'
4
5
  import { existsSync, readFileSync, statSync } from 'node:fs'
5
6
  import { parseTsx } from '../compiler/analyze'
6
7
  import { computeJsxNodes } from '../compiler/ast'
@@ -98,16 +99,23 @@ export function stampFiles(files: Iterable<string>): Map<string, FileStamp> {
98
99
  for (const file of files) {
99
100
  if (out.has(file))
100
101
  continue
101
- try {
102
- const st = statSync(file)
103
- if (st.isFile())
104
- out.set(file, { mtimeMs: st.mtimeMs, size: st.size })
105
- }
106
- catch {}
102
+ const st = statOrUndefined(file)
103
+ if (st?.isFile())
104
+ out.set(file, { mtimeMs: st.mtimeMs, size: st.size })
107
105
  }
108
106
  return out
109
107
  }
110
108
 
109
+ /** A file that vanished or cannot be read has no stamp: the caller treats it as missing. */
110
+ function statOrUndefined(file: string): Stats | undefined {
111
+ try {
112
+ return statSync(file)
113
+ }
114
+ catch {
115
+ return undefined
116
+ }
117
+ }
118
+
111
119
  export function stampsMatch(inputStamps: ReadonlyMap<string, FileStamp>): boolean {
112
120
  for (const [file, prev] of inputStamps) {
113
121
  if (!existsSync(file))