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,641 @@
1
+ // Island discovery & reachability: which exports run in the browser, which modules render them, and the checks that keep server code out of them.
2
+
3
+ import type { ModuleAnalysis } from '../compiler/analyze'
4
+ import type { ServerOnlyInIsland } from '../compiler/interactivity'
5
+ import type { ModuleGraph } from './graph'
6
+ import { basename, extname } from 'node:path'
7
+ import { asyncInteractiveError } from '../compiler/analyze'
8
+ import { findCrossFileServerOnly, withStateReads } from '../compiler/interactivity'
9
+ import { collectMistakes, serverOnlyTagError } from '../compiler/mistakes'
10
+ import { findPrivateEnv, isServerOnlyModule } from '../compiler/server-only'
11
+ import { checkBareSignals } from '../compiler/signal-reads'
12
+ import { clientNeeds, clientView } from './client-prune'
13
+ import { isInNodeModules, isTsFile, relPosix } from './files'
14
+
15
+ /** A component that is not an island, as a module renders it. */
16
+ export interface StaticTag { async: boolean }
17
+
18
+ export interface IslandTarget {
19
+ id: string
20
+ file: string
21
+ exportName: string
22
+ /** A component of the file it does not export under `exportName`: the client build adds `export { local as exportName }`. */
23
+ local?: string | undefined
24
+ defaultHydrate: string | undefined
25
+ }
26
+
27
+ export type ActionsByFile = Map<string, { exportName: string, url: string }[]>
28
+
29
+ export type IslandIssue
30
+ = | { kind: 'async-interactive', file: string, offset: number, reason: string | undefined }
31
+ | { kind: 'server-only-tag', file: string, serverOnly: ServerOnlyInIsland }
32
+ | { kind: 'special-interactive', file: string, offset: number, reason: string | undefined }
33
+ | { kind: 'interactive-action', file: string, name: string, offset: number, reason: string | undefined }
34
+ | { kind: 'action-export', file: string, target: string, name: string, offset: number, reexport: boolean }
35
+ | { kind: 'server-only-import', file: string, island: string, source: string, offset: number, reexport: boolean }
36
+ | { kind: 'private-env', file: string, island: string, offset: number, envKind: 'process' | 'bun' }
37
+ | { kind: 'compiler-mistake', file: string, offset: number, message: string }
38
+
39
+ export interface IslandPlan {
40
+ /** Island roots keyed `file#exportName`. */
41
+ targets: Map<string, IslandTarget>
42
+ /** Per static module, the island each rendered tag stands for. */
43
+ pageBindings: Map<string, Map<string, IslandTarget>>
44
+ /** Per static module, the imported components its server code renders that are not islands, each with whether it is async. */
45
+ staticTags: Map<string, Map<string, StaticTag>>
46
+ /** CSS files imported (transitively) by an island: bundled with it, not as standalone styles. */
47
+ cssFiles: Set<string>
48
+ /** Modules island code imports from another module, whose SSR emits hydration markers everywhere. */
49
+ reach: Set<string>
50
+ /** Every module the browser loads for an island, the island roots included. */
51
+ clientFiles: Set<string>
52
+ /** Per module the browser loads only for the islands declared in it, the top-level names its client copy keeps (`pruneForClient`). */
53
+ clientKeep: Map<string, Set<string>>
54
+ /** Island and reachability issues found during analysis. */
55
+ issues: IslandIssue[]
56
+ }
57
+
58
+ export interface AnalyzeIslandsOptions {
59
+ graph: ModuleGraph
60
+ root: string
61
+ pageFiles: readonly string[]
62
+ specialFiles: readonly string[]
63
+ /** Custom module loader (e.g. `prunelle check` collects parse errors and returns `undefined` on unparsable files). */
64
+ load?: ((file: string) => ModuleAnalysis | undefined) | undefined
65
+ /** Also walk reachability from every interactive module in `graph.analyses`, even if no route renders it yet. */
66
+ includeAllInteractive?: boolean | undefined
67
+ /** Check server-only module imports and private `process.env`/`Bun.env` reads during the static reachability walk. */
68
+ checkLeaks?: boolean | undefined
69
+ }
70
+
71
+ type LoadModule = (file: string) => ModuleAnalysis | undefined
72
+
73
+ const MAX_REEXPORT_DEPTH = 8
74
+
75
+ export function islandKey(target: { file: string, exportName: string }): string {
76
+ return `${target.file}#${target.exportName}`
77
+ }
78
+
79
+ /** A non-interactive module with exported actions is replaced by action stubs in the browser bundle. */
80
+ export function isStubbedActionFile(analysis: ModuleAnalysis | undefined): boolean {
81
+ return analysis !== undefined && !analysis.isInteractive && analysis.exportedActions.length > 0
82
+ }
83
+
84
+ export function clientLeakError(leaks: Set<string>): Error {
85
+ return new Error(`prunelle build (client): server code is reachable from an island:\n${[...leaks].map(l => ` ${l}`).join('\n')}\nMove server logic to a server action or async server component.`)
86
+ }
87
+
88
+ /** Follows `export { x } from './y'` and `export * from './y'` chains using `load` so parse errors are never swallowed. */
89
+ function resolveExportTarget(
90
+ graph: ModuleGraph,
91
+ load: LoadModule,
92
+ file: string,
93
+ exportName: string,
94
+ depth = 0,
95
+ seen = new Set<string>(),
96
+ ): { file: string, exportName: string } | undefined {
97
+ if (depth > MAX_REEXPORT_DEPTH)
98
+ return { file, exportName }
99
+ const key = `${file}\0${exportName}`
100
+ if (seen.has(key))
101
+ return { file, exportName }
102
+ seen.add(key)
103
+
104
+ const analysis = load(file)
105
+ if (analysis === undefined)
106
+ return undefined
107
+ const direct = analysis.reexports.find(r => r.exported === exportName)
108
+ if (direct !== undefined) {
109
+ const next = graph.resolve(file, direct.source)
110
+ if (next !== undefined && isTsFile(next))
111
+ return resolveExportTarget(graph, load, next, direct.local, depth + 1, seen)
112
+ }
113
+
114
+ if (analysis.exportedNames.includes(exportName))
115
+ return { file, exportName }
116
+
117
+ // Follow `export * from './y'` barrel re-exports (named exports only, per ESM spec `export *` never re-exports `default`).
118
+ if (exportName !== 'default') {
119
+ for (const re of analysis.reexports) {
120
+ if (re.exported !== '*')
121
+ continue
122
+ const next = graph.resolve(file, re.source)
123
+ if (next === undefined || !isTsFile(next))
124
+ continue
125
+ const candidate = resolveExportTarget(graph, load, next, exportName, depth + 1, seen)
126
+ if (candidate !== undefined && load(candidate.file)?.exportedNames.includes(candidate.exportName))
127
+ return candidate
128
+ }
129
+ }
130
+
131
+ return { file, exportName }
132
+ }
133
+
134
+ const EMPTY_SET = new Set<string>()
135
+
136
+ function moduleHasInteractiveExport(graph: ModuleGraph, load: LoadModule, file: string, seen = new Set<string>()): boolean {
137
+ if (seen.has(file))
138
+ return false
139
+ seen.add(file)
140
+ const analysis = graph.analyses.get(file) ?? load(file)
141
+ if (analysis === undefined)
142
+ return false
143
+ if (analysis.stateExports.length > 0 || [...analysis.exports.values()].some(e => e.interactive))
144
+ return true
145
+ for (const re of analysis.reexports) {
146
+ const next = graph.resolve(file, re.source)
147
+ if (next === undefined || !isTsFile(next))
148
+ continue
149
+ if (re.exported === '*') {
150
+ if (moduleHasInteractiveExport(graph, load, next, seen))
151
+ return true
152
+ }
153
+ else {
154
+ const target = resolveExportTarget(graph, load, next, re.local)
155
+ const targetAnalysis = target === undefined ? undefined : (graph.analyses.get(target.file) ?? load(target.file))
156
+ if (target !== undefined && (targetAnalysis?.stateExports.includes(target.exportName) === true || targetAnalysis?.exports.get(target.exportName)?.interactive === true))
157
+ return true
158
+ }
159
+ }
160
+ return false
161
+ }
162
+
163
+ function collectExportedSignals(graph: ModuleGraph, load: LoadModule, file: string, out: Set<string>, seen = new Set<string>()): void {
164
+ if (seen.has(file))
165
+ return
166
+ seen.add(file)
167
+ const analysis = graph.analyses.get(file) ?? load(file)
168
+ if (analysis === undefined)
169
+ return
170
+ for (const name of analysis.signalExports)
171
+ out.add(name)
172
+ for (const re of analysis.reexports) {
173
+ const next = graph.resolve(file, re.source)
174
+ if (next === undefined || !isTsFile(next))
175
+ continue
176
+ if (re.exported === '*') {
177
+ collectExportedSignals(graph, load, next, out, seen)
178
+ }
179
+ else {
180
+ const target = resolveExportTarget(graph, load, next, re.local)
181
+ if (target !== undefined && (graph.analyses.get(target.file) ?? load(target.file))?.signalExports.includes(target.exportName) === true)
182
+ out.add(re.exported)
183
+ }
184
+ }
185
+ }
186
+
187
+ function interactivityChanged(prev: ModuleAnalysis, next: { isInteractive: boolean, exports: Map<string, { interactive: boolean }>, localIslands: Map<string, unknown> }): boolean {
188
+ if (prev.isInteractive !== next.isInteractive)
189
+ return true
190
+ for (const [name, fact] of next.exports) {
191
+ if (prev.exports.get(name)?.interactive !== fact.interactive)
192
+ return true
193
+ }
194
+ return next.localIslands.size !== prev.localIslands.size || [...next.localIslands.keys()].some(name => !prev.localIslands.has(name))
195
+ }
196
+
197
+ function createPromoter(graph: ModuleGraph, load: LoadModule, issues: IslandIssue[]): { promoteAll: () => void, loadPromoted: LoadModule } {
198
+ const initialAsyncInteractive = new Set<string>()
199
+ const initialServerOnly = new Set<string>()
200
+ const reportedAsync = new Set<string>()
201
+ const reportedServerOnly = new Set<string>()
202
+
203
+ const recordInitial = (file: string, a: ModuleAnalysis): void => {
204
+ if (a.hasAsyncDefault && a.exports.get('default')?.interactive === true)
205
+ initialAsyncInteractive.add(file)
206
+ if (a.serverOnly !== undefined)
207
+ initialServerOnly.add(file)
208
+ }
209
+ for (const [file, a] of graph.analyses)
210
+ recordInitial(file, a)
211
+
212
+ const isInteractiveTarget = (file: string, source: string, imported: string): boolean => {
213
+ const resolved = graph.resolve(file, source)
214
+ if (resolved === undefined || !isTsFile(resolved))
215
+ return false
216
+ if (imported === '*')
217
+ return moduleHasInteractiveExport(graph, load, resolved)
218
+ const target = resolveExportTarget(graph, load, resolved, imported)
219
+ if (target === undefined)
220
+ return false
221
+ const targetAnalysis = graph.analyses.get(target.file) ?? load(target.file)
222
+ return targetAnalysis?.stateExports.includes(target.exportName) === true
223
+ || targetAnalysis?.exports.get(target.exportName)?.interactive === true
224
+ }
225
+
226
+ const promoteOne = (file: string): boolean => {
227
+ if (isInNodeModules(file) || !isTsFile(file))
228
+ return false
229
+ const analysis = graph.analyses.get(file)
230
+ if (analysis === undefined)
231
+ return false
232
+ const promoted = withStateReads(analysis, (imp, imported) => isInteractiveTarget(file, imp.source, imported))
233
+ if (promoted === undefined)
234
+ return false
235
+ const page = promoted.exports.get('default')
236
+ if (analysis.hasAsyncDefault && page?.interactive === true) {
237
+ if (!initialAsyncInteractive.has(file) && !reportedAsync.has(file)) {
238
+ reportedAsync.add(file)
239
+ issues.push({ kind: 'async-interactive', file, offset: page.offset ?? 0, reason: page.reason })
240
+ }
241
+ return false
242
+ }
243
+ if (promoted.serverOnly !== undefined) {
244
+ if (!initialServerOnly.has(file) && !reportedServerOnly.has(file)) {
245
+ reportedServerOnly.add(file)
246
+ issues.push({ kind: 'server-only-tag', file, serverOnly: promoted.serverOnly })
247
+ }
248
+ return false
249
+ }
250
+ if (!interactivityChanged(analysis, promoted))
251
+ return false
252
+ graph.analyses.set(file, { ...analysis, ...promoted })
253
+ return true
254
+ }
255
+
256
+ const promoteAll = (): void => {
257
+ for (let pass = 0; pass < MAX_REEXPORT_DEPTH; pass++) {
258
+ let changed = false
259
+ for (const file of [...graph.analyses.keys()]) {
260
+ if (promoteOne(file))
261
+ changed = true
262
+ }
263
+ if (!changed)
264
+ break
265
+ }
266
+ }
267
+
268
+ const loadPromoted: LoadModule = (file: string): ModuleAnalysis | undefined => {
269
+ const existed = graph.analyses.has(file)
270
+ const analysis = graph.analyses.get(file) ?? load(file)
271
+ if (analysis === undefined)
272
+ return undefined
273
+ if (!existed) {
274
+ recordInitial(file, analysis)
275
+ promoteAll()
276
+ }
277
+ return graph.analyses.get(file) ?? analysis
278
+ }
279
+
280
+ return { promoteAll, loadPromoted }
281
+ }
282
+
283
+ function checkImportedBareSignals(graph: ModuleGraph, load: LoadModule, root: string, issues: IslandIssue[]): void {
284
+ for (const [file, analysis] of [...graph.analyses]) {
285
+ if (isInNodeModules(file) || !isTsFile(file))
286
+ continue
287
+ const importedSignals = new Set<string>()
288
+ const importedSignalMembers = new Map<string, Set<string>>()
289
+ for (const imp of analysis.imports) {
290
+ const resolved = graph.resolve(file, imp.source)
291
+ if (resolved === undefined || !isTsFile(resolved))
292
+ continue
293
+ for (const spec of imp.specifiers) {
294
+ if (spec.imported === '*') {
295
+ const members = new Set<string>()
296
+ collectExportedSignals(graph, load, resolved, members)
297
+ if (members.size > 0)
298
+ importedSignalMembers.set(spec.local, members)
299
+ }
300
+ else {
301
+ const target = resolveExportTarget(graph, load, resolved, spec.imported)
302
+ if (target !== undefined && (graph.analyses.get(target.file) ?? load(target.file))?.signalExports.includes(target.exportName) === true)
303
+ importedSignals.add(spec.local)
304
+ }
305
+ }
306
+ }
307
+ if (importedSignals.size === 0 && importedSignalMembers.size === 0)
308
+ continue
309
+ const { mistakes } = collectMistakes(() => checkBareSignals(analysis.program, EMPTY_SET, relPosix(root, file), importedSignals, importedSignalMembers))
310
+ for (const m of mistakes)
311
+ issues.push({ kind: 'compiler-mistake', file, offset: m.start ?? 0, message: m.message })
312
+ }
313
+ }
314
+
315
+ function checkCrossFileServerOnlyTags(graph: ModuleGraph, load: LoadModule, issues: IslandIssue[]): void {
316
+ const loadMod = (f: string): ModuleAnalysis | undefined => graph.analyses.get(f) ?? load(f)
317
+ const resolveTarget = (fromFile: string, source: string, exportName: string): { file: string, exportName: string } | undefined => {
318
+ const resolved = graph.resolve(fromFile, source)
319
+ return resolved !== undefined && isTsFile(resolved) ? resolveExportTarget(graph, load, resolved, exportName) : undefined
320
+ }
321
+ for (const [file, analysis] of [...graph.analyses]) {
322
+ if (isInNodeModules(file) || !analysis.isInteractive)
323
+ continue
324
+ const serverOnly = findCrossFileServerOnly(file, analysis, loadMod, resolveTarget)
325
+ if (serverOnly !== undefined)
326
+ issues.push({ kind: 'server-only-tag', file, serverOnly })
327
+ }
328
+ }
329
+
330
+ function discoverBindings(
331
+ graph: ModuleGraph,
332
+ load: LoadModule,
333
+ loadPromoted: LoadModule,
334
+ pageSet: ReadonlySet<string>,
335
+ registerIsland: (file: string, exportName: string, local?: string) => IslandTarget,
336
+ ): Pick<IslandPlan, 'pageBindings' | 'staticTags'> {
337
+ const pageBindings = new Map<string, Map<string, IslandTarget>>()
338
+ const staticTags = new Map<string, Map<string, StaticTag>>()
339
+ for (const file of [...graph.analyses.keys()]) {
340
+ if (!file.endsWith('.tsx'))
341
+ continue
342
+ const analysis = graph.analyses.get(file)!
343
+ if (analysis.exports.get('default')?.interactive === true && pageSet.has(file)) {
344
+ registerIsland(file, 'default')
345
+ if (analysis.staticJsxTags.size === 0)
346
+ continue
347
+ }
348
+ if (analysis.staticJsxTags.size === 0)
349
+ continue
350
+
351
+ // Only names rendered as tags from server-side code become islands: `<Counter />`, or `<UI.Counter />` through a namespace import.
352
+ const bindings = new Map<string, IslandTarget>()
353
+ const statics = new Map<string, StaticTag>()
354
+ for (const imp of analysis.imports) {
355
+ const resolved = graph.resolve(file, imp.source)
356
+ if (resolved === undefined || !isTsFile(resolved))
357
+ continue
358
+ for (const spec of imp.specifiers) {
359
+ const tags = spec.imported === '*'
360
+ ? [...analysis.staticJsxTags].filter(tag => tag.startsWith(`${spec.local}.`) && !tag.slice(spec.local.length + 1).includes('.')).map(tag => [tag, tag.slice(spec.local.length + 1)] as const)
361
+ : analysis.staticJsxTags.has(spec.local) ? [[spec.local, spec.imported] as const] : []
362
+ for (const [tag, exportName] of tags) {
363
+ const target = resolveExportTarget(graph, load, resolved, exportName)
364
+ const component = target?.file.endsWith('.tsx') === true ? loadPromoted(target.file) : undefined
365
+ if (target === undefined || component === undefined)
366
+ continue
367
+ if (component.exports.get(target.exportName)?.interactive === true)
368
+ bindings.set(tag, registerIsland(target.file, target.exportName))
369
+ else
370
+ statics.set(tag, { async: component.asyncLocals.has(component.exportLocals.get(target.exportName) ?? target.exportName) })
371
+ }
372
+ }
373
+ }
374
+ // A component of the same file that runs in the browser, rendered as a tag from its server code, is an island of its own.
375
+ for (const local of analysis.localIslands.keys()) {
376
+ const exportName = [...analysis.exportLocals].find(([, l]) => l === local)?.[0]
377
+ if (exportName !== undefined)
378
+ bindings.set(local, registerIsland(file, exportName))
379
+ else
380
+ bindings.set(local, registerIsland(file, analysis.exportLocals.has(local) ? `${local}$island` : local, local))
381
+ }
382
+ if (bindings.size > 0)
383
+ pageBindings.set(file, bindings)
384
+ if (statics.size > 0)
385
+ staticTags.set(file, statics)
386
+ }
387
+ return { pageBindings, staticTags }
388
+ }
389
+
390
+ function checkReachEdges(
391
+ graph: ModuleGraph,
392
+ load: LoadModule,
393
+ file: string,
394
+ island: string,
395
+ analysis: ModuleAnalysis,
396
+ checkFileLeaks: boolean,
397
+ cssFiles: Set<string>,
398
+ issues: IslandIssue[],
399
+ enqueue: (target: string, island: string) => void,
400
+ ): void {
401
+ const reported = new Set<string>()
402
+ const loadTarget = (target: string): ModuleAnalysis | undefined =>
403
+ isInNodeModules(target) ? graph.analyses.get(target) : load(target)
404
+
405
+ const reportActionExport = (target: string, name: string, offset: number, reexport: boolean): void => {
406
+ const key = `action:${target}:${name}`
407
+ if (!reported.has(key)) {
408
+ reported.add(key)
409
+ issues.push({ kind: 'action-export', file, target, name, offset, reexport })
410
+ }
411
+ }
412
+
413
+ const checkSpecifiers = (target: string, targetAnalysis: ModuleAnalysis | undefined, names: readonly string[], offset: number, reexport: boolean): boolean => {
414
+ if (isStubbedActionFile(targetAnalysis)) {
415
+ for (const name of names) {
416
+ if (name !== '*' && !targetAnalysis!.exportedActions.includes(name))
417
+ reportActionExport(target, name, offset, reexport)
418
+ }
419
+ return true
420
+ }
421
+ // Check wildcard-barrel re-exports (`export * from './actions'`), leaving explicit named re-exports to the barrel itself.
422
+ for (const name of names) {
423
+ if (name === '*' || targetAnalysis?.reexports.some(r => r.exported === name) === true)
424
+ continue
425
+ const resolvedTarget = resolveExportTarget(graph, load, target, name)
426
+ if (resolvedTarget !== undefined && resolvedTarget.file !== target) {
427
+ const finalAnalysis = loadTarget(resolvedTarget.file)
428
+ if (isStubbedActionFile(finalAnalysis) && !finalAnalysis!.exportedActions.includes(resolvedTarget.exportName))
429
+ reportActionExport(resolvedTarget.file, resolvedTarget.exportName, offset, reexport)
430
+ }
431
+ }
432
+ return false
433
+ }
434
+
435
+ const visitEdge = (source: string, offset: number, reexport: boolean, names: readonly string[]): void => {
436
+ if (isServerOnlyModule(source)) {
437
+ if (checkFileLeaks && !reported.has(source)) {
438
+ reported.add(source)
439
+ issues.push({ kind: 'server-only-import', file, island, source, offset, reexport })
440
+ }
441
+ return
442
+ }
443
+ const target = graph.resolve(file, source)
444
+ if (target === undefined)
445
+ return
446
+ if (target.endsWith('.css')) {
447
+ cssFiles.add(target)
448
+ return
449
+ }
450
+ if (!isTsFile(target))
451
+ return
452
+ if (!checkSpecifiers(target, loadTarget(target), names, offset, reexport))
453
+ enqueue(target, island)
454
+ }
455
+
456
+ for (const imp of analysis.imports)
457
+ visitEdge(imp.source, imp.start, false, imp.specifiers.map(s => s.imported))
458
+ for (const re of analysis.reexports)
459
+ visitEdge(re.source, re.start, true, [re.local])
460
+ for (const dyn of analysis.dynamicImports)
461
+ visitEdge(dyn.source, dyn.start, false, [])
462
+ }
463
+
464
+ /** Walks what the browser loads from the island roots. A root no other island code imports is walked as its client copy, the code its islands reach, so the server code beside them stays out. */
465
+ function walkIslandReach(
466
+ graph: ModuleGraph,
467
+ load: LoadModule,
468
+ roots: readonly string[],
469
+ clientKeep: Map<string, Set<string>>,
470
+ checkLeaks: boolean,
471
+ issues: IslandIssue[],
472
+ ): { reach: Set<string>, clientFiles: Set<string>, cssFiles: Set<string> } {
473
+ const reach = new Set<string>()
474
+ const cssFiles = new Set<string>()
475
+ const visited = new Set<string>()
476
+ const queue: { file: string, island: string }[] = []
477
+
478
+ const enqueue = (file: string, island: string): void => {
479
+ if (file !== island) {
480
+ if (file.endsWith('.tsx'))
481
+ reach.add(file)
482
+ // Imported by other island code, the module ships whole: walk it again if only its client copy was.
483
+ if (clientKeep.delete(file) && visited.has(file)) {
484
+ queue.push({ file, island })
485
+ return
486
+ }
487
+ }
488
+ if (visited.has(file))
489
+ return
490
+ visited.add(file)
491
+ queue.push({ file, island })
492
+ }
493
+
494
+ for (const root of roots)
495
+ enqueue(root, root)
496
+
497
+ for (let i = 0; i < queue.length; i++) {
498
+ const { file, island } = queue[i]!
499
+ const inNodeModules = isInNodeModules(file)
500
+ const keep = clientKeep.get(file)
501
+ const full = inNodeModules ? graph.analyses.get(file) : load(file)
502
+ const analysis = keep === undefined || full === undefined ? full : clientView(full, graph.source(file), keep)
503
+ if (analysis === undefined)
504
+ continue
505
+ if (file !== island && isStubbedActionFile(analysis))
506
+ continue
507
+ // Already reported as `interactive-action`; skip reach checks so we don't emit a contradictory "Move server logic to a server action" error.
508
+ if (!inNodeModules && analysis.isInteractive && analysis.exportedActions.length > 0)
509
+ continue
510
+
511
+ const checkFileLeaks = checkLeaks && !inNodeModules
512
+ checkReachEdges(graph, load, file, island, analysis, checkFileLeaks, cssFiles, issues, enqueue)
513
+ if (checkFileLeaks) {
514
+ const envMatch = findPrivateEnv(analysis.program)
515
+ if (envMatch !== undefined)
516
+ issues.push({ kind: 'private-env', file, island, offset: envMatch.offset, envKind: envMatch.kind })
517
+ }
518
+ }
519
+
520
+ return { reach, clientFiles: visited, cssFiles }
521
+ }
522
+
523
+ /** Shared island planning and reachability analyzer used by both `prunelle build` and `prunelle check`. */
524
+ export function analyzeIslands(options: AnalyzeIslandsOptions): IslandPlan {
525
+ const { graph, root, pageFiles, specialFiles } = options
526
+ const load: LoadModule = options.load ?? (file => graph.load(file))
527
+ const issues: IslandIssue[] = []
528
+ const targets = new Map<string, IslandTarget>()
529
+ // Reserve 'runtime' so an island named Runtime.tsx never overwrites entriesDir/runtime.ts.
530
+ const usedIds = new Set<string>(['runtime'])
531
+ const pageSet = new Set(pageFiles)
532
+
533
+ function registerIsland(file: string, exportName: string, local?: string): IslandTarget {
534
+ const key = islandKey({ file, exportName })
535
+ const existing = targets.get(key)
536
+ if (existing !== undefined)
537
+ return existing
538
+ const baseName = basename(file, extname(file)).toLowerCase()
539
+ const expLower = exportName.toLowerCase()
540
+ let id = exportName === 'default' || expLower === baseName ? baseName : `${baseName}-${expLower}`
541
+ // The id names the entry file and the chunk: two islands sharing a basename (or 'runtime') keep it readable and add a hash of their path.
542
+ if (usedIds.has(id))
543
+ id = `${id}-${Bun.hash(relPosix(root, key)).toString(36).slice(0, 6)}`
544
+ let suffix = 2
545
+ while (usedIds.has(id))
546
+ id = `${id}-${suffix++}`
547
+ usedIds.add(id)
548
+ const target: IslandTarget = { id, file, exportName, local, defaultHydrate: load(file)?.defaultHydrate }
549
+ targets.set(key, target)
550
+ return target
551
+ }
552
+
553
+ // A component or hook reading reactive state or calling an interactive hook runs in the browser too. The promoted analysis lives in this run's map only, so the cached one still reflects the file alone.
554
+ const { promoteAll, loadPromoted } = createPromoter(graph, load, issues)
555
+ promoteAll()
556
+ checkImportedBareSignals(graph, load, root, issues)
557
+ checkCrossFileServerOnlyTags(graph, load, issues)
558
+
559
+ const { pageBindings, staticTags } = discoverBindings(graph, load, loadPromoted, pageSet, registerIsland)
560
+
561
+ // A layout, error or 404 page renders on the server only, so interactivity written in it would never run.
562
+ for (const file of specialFiles) {
563
+ const page = graph.analyses.get(file)?.exports.get('default')
564
+ if (page?.interactive === true)
565
+ issues.push({ kind: 'special-interactive', file, offset: page.offset ?? 0, reason: page.reason })
566
+ }
567
+
568
+ // An interactive module ships to the browser, so co-locating `action()` in it would bundle server action code into the client.
569
+ for (const [file, analysis] of graph.analyses) {
570
+ if (isInNodeModules(file) || !analysis.isInteractive || analysis.exportedActions.length === 0)
571
+ continue
572
+ const name = analysis.exportedActions[0]!
573
+ const offset = analysis.bindings.find(b => b.name === name)?.start ?? 0
574
+ const reason = [...analysis.exports.values()].find(e => e.interactive)?.reason
575
+ ?? analysis.bindings.find(b => b.fact !== undefined)?.fact?.reason
576
+ issues.push({ kind: 'interactive-action', file, name, offset, reason })
577
+ }
578
+
579
+ const rootFiles = new Set<string>([...targets.values()].map(t => t.file))
580
+ const clientKeep = clientKeepOf(targets.values(), load)
581
+ if (options.includeAllInteractive) {
582
+ // A module no route renders yet is walked as the client copy its islands would get.
583
+ for (const [file, analysis] of graph.analyses) {
584
+ if (!analysis.isInteractive || rootFiles.has(file))
585
+ continue
586
+ rootFiles.add(file)
587
+ if (!isInNodeModules(file)) {
588
+ const exported = [...analysis.exports].filter(([, e]) => e.interactive).map(([name]) => analysis.exportLocals.get(name) ?? name)
589
+ clientKeep.set(file, clientNeeds(analysis, [...exported, ...analysis.localIslands.keys()]))
590
+ }
591
+ }
592
+ }
593
+
594
+ const { reach, clientFiles, cssFiles } = walkIslandReach(graph, load, [...rootFiles], clientKeep, options.checkLeaks === true, issues)
595
+ return { targets, pageBindings, staticTags, cssFiles, reach, clientFiles, clientKeep, issues }
596
+ }
597
+
598
+ function clientKeepOf(targets: Iterable<IslandTarget>, load: LoadModule): Map<string, Set<string>> {
599
+ const locals = new Map<string, string[]>()
600
+ for (const t of targets) {
601
+ const list = locals.get(t.file) ?? []
602
+ list.push(t.local ?? load(t.file)?.exportLocals.get(t.exportName) ?? t.exportName)
603
+ locals.set(t.file, list)
604
+ }
605
+ const keep = new Map<string, Set<string>>()
606
+ for (const [file, names] of locals) {
607
+ const analysis = load(file)
608
+ if (analysis !== undefined && !isInNodeModules(file))
609
+ keep.set(file, clientNeeds(analysis, names))
610
+ }
611
+ return keep
612
+ }
613
+
614
+ export function planIslands(graph: ModuleGraph, root: string, pageFiles: string[], specialFiles: string[]): IslandPlan {
615
+ const plan = analyzeIslands({ graph, root, pageFiles, specialFiles, checkLeaks: true })
616
+ const leaks = new Set<string>()
617
+ for (const issue of plan.issues) {
618
+ const rel = relPosix(root, issue.file)
619
+ if (issue.kind === 'async-interactive')
620
+ throw asyncInteractiveError(issue.file, issue.reason)
621
+ if (issue.kind === 'server-only-tag')
622
+ throw serverOnlyTagError(rel, issue.serverOnly)
623
+ if (issue.kind === 'special-interactive')
624
+ throw new Error(`prunelle build: ${rel} uses browser interactivity (${issue.reason}), but it renders on the server only. Move the interactive part into a component and render that component from ${rel}.`)
625
+ if (issue.kind === 'interactive-action')
626
+ throw new Error(`prunelle build: ${rel} exports server action "${issue.name}" and also uses browser interactivity${issue.reason ? ` (${issue.reason})` : ''}: server action code would leak into the browser bundle. Move "${issue.name}" into a separate non-interactive file (e.g. a .ts actions module).`)
627
+ if (issue.kind === 'action-export') {
628
+ const verb = issue.reexport ? 're-exports' : 'imports'
629
+ throw new Error(`prunelle build: ${rel} runs in the browser and ${verb} ${issue.name} from ${relPosix(root, issue.target)}, a file of server actions: the browser only gets its actions. Move ${issue.name} into a module without actions.`)
630
+ }
631
+ if (issue.kind === 'server-only-import')
632
+ leaks.add(issue.reexport ? `${rel} re-exports from server-only module "${issue.source}"` : `${rel} imports server-only module "${issue.source}"`)
633
+ if (issue.kind === 'compiler-mistake')
634
+ throw new Error(issue.message)
635
+ if (issue.kind === 'private-env')
636
+ leaks.add(`${rel} reads process.env or Bun.env (only a process.env.PUBLIC_* set at build time is inlined)`)
637
+ }
638
+ if (leaks.size > 0)
639
+ throw clientLeakError(leaks)
640
+ return plan
641
+ }