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,614 @@
1
+ // Prunelle single-pass builder:
2
+ // - Discovers file routes, nested _layout.tsx, _middleware.ts, _error.tsx, _404.tsx, actions, and automatic islands
3
+ // - Builds client (1 pass, minimal runtime + island chunks + action stubs) and server (1 pass)
4
+ // - Supports hybrid prerender, --static export, and --compile single-executable builds
5
+
6
+ import type { ComplianceConfig } from '../compiler/compliance'
7
+ import type { AppRuntimeContext } from '../plugins/context'
8
+ import type { PrunellePlugin } from '../plugins/index'
9
+ import type { BuildCache } from './graph'
10
+ import type { ActionsByFile } from './islands'
11
+ import type { BuildManifest } from './manifest'
12
+ import type { PublicFiles } from './plugin-host'
13
+ import { copyFileSync, existsSync, mkdirSync, readdirSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
14
+ import { basename, dirname, join, relative, resolve } from 'node:path'
15
+ import { checkAppForms } from '../cli/check-forms'
16
+ import { collectProjectComplianceWarnings, shouldEmitWarning } from '../compiler/compliance'
17
+ import { formatCodeFrame, formatDiagnostic, formatLoc } from '../compiler/shared'
18
+ import { createAppContext, loadConfig, resolvePlugins, runWithAppContext } from '../plugins/index'
19
+ import { actionHash } from '../server/action'
20
+ import { buildClient, buildServer, linkOrCopyFile, pluginBunPlugins, standaloneCssFiles } from './bundle'
21
+ import { compileExecutable } from './compile'
22
+ import { assertSafeOutDir, fileSize, isInNodeModules, relPosix, walkAllFiles, walkRoutes } from './files'
23
+ import { isInside } from './is-inside'
24
+ import { ModuleGraph } from './graph'
25
+ import { nodeEnvWarning, renderProblems, serverNodeEnvReads } from './render-rules'
26
+ import { planIslands } from './islands'
27
+ import { buildActionEntries, buildRouteEntries } from './manifest'
28
+ import { createPluginHost, createPublicFiles } from './plugin-host'
29
+ import { carryPreviousAssets } from './carry'
30
+ import { assertOwnOutDir, processSuffix, removeDeadProcessDirs, removeStaleStages, stageDirFor, swapStage } from './output'
31
+ import { prerender } from './prerender'
32
+ import { analyzeBundleWeights, checkJsBudget, formatBundleReport, formatBundleReportJson, islandOrigins } from './report'
33
+ import { SERVER_ENTRY_FILE, serverEntrySource } from './server-entry'
34
+ import { PRUNELLE_SRC_ROOT, resolvePrunelleSpecifier } from './resolve'
35
+ import { assertNoRouteConflicts, discoverRouteMatchers, fileToRoutePath, hasRouteHandlerExport, missingPathsProblem, normalizeRoutePattern, routeExportProblem, routeFileProblem, SPECIAL_ROUTE_FILES } from './routes'
36
+ import { exportStatic } from './static'
37
+ import { findUnknownStatusPages } from './status-pages'
38
+
39
+ export type { BuildCache } from './graph'
40
+ export { createBuildCache } from './graph'
41
+ export type { ActionManifestEntry, BuildManifest, RouteManifestEntry, StatusPageKind, StatusPageManifestEntry } from './manifest'
42
+ export { analyzeBundleWeights, checkJsBudget, formatBundleReport, formatBundleReportJson } from './report'
43
+ export type { BundleReport, RouteBundleMetrics, RouteIsland } from './report'
44
+ export { resolvePrunelleSpecifier } from './resolve'
45
+
46
+ export interface BuildOptions {
47
+ root: string
48
+ routesDir?: string | undefined
49
+ outDir?: string | undefined
50
+ publicDir?: string | undefined
51
+ minify?: boolean | undefined
52
+ assetPrefix?: string | undefined
53
+ site?: string | undefined
54
+ plugins?: PrunellePlugin[] | undefined
55
+ /** Reusable incremental cache for `prunelle dev` (skips re-parsing/re-compiling unchanged files). */
56
+ cache?: BuildCache | undefined
57
+ /** Print a per-route JS/CSS bundle weight report using Bun.build's metafile. */
58
+ analyze?: boolean | undefined
59
+ /** Print the `--analyze` bundle weight report as JSON instead of a human-readable table. */
60
+ analyzeJson?: boolean | undefined
61
+ /** Fail the build when a route's eager JS, gzipped, is over this many bytes, naming the route and its islands. */
62
+ maxJs?: number | undefined
63
+ /** Export a static site directly into outDir (dist/) with no server/ folder left behind. */
64
+ static?: boolean | undefined
65
+ /** Run build-time prerendering for routes exporting `prerender = true` (default: true; disabled in `prunelle dev`). */
66
+ prerender?: boolean | undefined
67
+ /** Copy `public/` files into `outDir/public` (default: true; disabled in `prunelle dev` where `public/` is served directly). */
68
+ copyPublic?: boolean | undefined
69
+ /** Compile into a single standalone executable at this path (or true -> dist/server-bin). */
70
+ compile?: string | boolean | undefined
71
+ /** Run in development mode (keeps NODE_ENV as development and skips production client asset precompression; auto-detected via PRUNELLE_DEV=1). */
72
+ dev?: boolean | undefined
73
+ /** Explicit NODE_ENV threaded through AppRuntimeContext and client defines without mutating process.env. */
74
+ nodeEnv?: string | undefined
75
+ }
76
+
77
+ const cachedPluginAssets = new WeakMap<BuildCache, { clientDir: string, files: string[] }>()
78
+
79
+ function restoreCachedPluginAssets(cache: BuildCache | undefined, clientDir: string, assets: string[], anyPassSkipped: boolean): void {
80
+ if (cache === undefined || !anyPassSkipped)
81
+ return
82
+ const prev = cachedPluginAssets.get(cache)
83
+ if (prev === undefined || prev.clientDir === clientDir)
84
+ return
85
+ const existing = new Set(assets)
86
+ for (const rel of prev.files) {
87
+ if (existing.has(rel))
88
+ continue
89
+ const from = join(prev.clientDir, rel)
90
+ if (!existsSync(from))
91
+ continue
92
+ linkOrCopyFile(from, join(clientDir, rel))
93
+ existing.add(rel)
94
+ assets.push(rel)
95
+ }
96
+ }
97
+
98
+ function recordCachedPluginAssets(cache: BuildCache | undefined, clientDir: string, assets: readonly string[], builtClientAssets: ReadonlySet<string>): void {
99
+ if (cache === undefined)
100
+ return
101
+ const files = assets.filter(rel => !builtClientAssets.has(rel))
102
+ if (files.length > 0)
103
+ cachedPluginAssets.set(cache, { clientDir, files })
104
+ else
105
+ cachedPluginAssets.delete(cache)
106
+ }
107
+
108
+ /** The server build a static export renders its pages from, under `.prunelle-cache/`. */
109
+ const STATIC_STAGE_PREFIX = '.static-stage-'
110
+
111
+ /** Everything one build run needs, resolved once from the options and `prunelle.config.ts`. */
112
+ interface BuildRun {
113
+ options: BuildOptions
114
+ root: string
115
+ plugins: PrunellePlugin[]
116
+ routesDir: string
117
+ publicDir: string
118
+ finalOutDir: string
119
+ /** The folder swapped in as `finalOutDir` once every step passed. */
120
+ stageDir: string
121
+ /** Where the build writes: `stageDir`, or for a static export a server build in `.prunelle-cache/` that `stageDir` takes pages from. */
122
+ outDir: string
123
+ stageSuffix: string
124
+ assetPrefix: string
125
+ site: string | undefined
126
+ compliance: ComplianceConfig | undefined
127
+ minify: boolean
128
+ isDev: boolean
129
+ nodeEnv: string | undefined
130
+ appCtx: AppRuntimeContext
131
+ publicFiles: PublicFiles
132
+ }
133
+
134
+ export async function build(options: BuildOptions): Promise<BuildManifest> {
135
+ if (options.static && options.compile) {
136
+ throw new Error('prunelle build: --static and --compile cannot be used together (static export produces HTML/assets without a server binary).')
137
+ }
138
+
139
+ const root = resolve(options.root)
140
+ const isDev = options.dev ?? (process.env.PRUNELLE_DEV === '1')
141
+ const effectiveNodeEnv = options.nodeEnv ?? (isDev ? undefined : (process.env.NODE_ENV ?? 'production'))
142
+ const fileConfig = await loadConfig(root, { dev: isDev, nodeEnv: effectiveNodeEnv })
143
+ const routesDir = resolve(root, options.routesDir ?? fileConfig.routesDir ?? 'src/routes')
144
+ const finalOutDir = resolve(root, options.outDir ?? fileConfig.outDir ?? 'dist')
145
+ const publicDir = resolve(root, options.publicDir ?? fileConfig.publicDir ?? 'public')
146
+
147
+ assertSafeOutDir(root, finalOutDir, routesDir, publicDir)
148
+
149
+ const cacheBaseDir = join(root, '.prunelle-cache')
150
+ const cacheExisted = existsSync(cacheBaseDir)
151
+ const stageSuffix = processSuffix()
152
+ const stageDir = stageDirFor(finalOutDir, stageSuffix)
153
+ const outDir = options.static ? join(cacheBaseDir, `${STATIC_STAGE_PREFIX}${stageSuffix}`) : stageDir
154
+ const assetPrefix = (options.assetPrefix ?? fileConfig.assetPrefix ?? '/_pru').replace(/\/$/, '')
155
+ assertOwnOutDir(root, finalOutDir, assetPrefix)
156
+ removeStaleStages(finalOutDir)
157
+ removeDeadProcessDirs(cacheBaseDir, STATIC_STAGE_PREFIX)
158
+ const site = (options.site ?? fileConfig.site)?.replace(/\/$/, '') || undefined
159
+ const publicFiles = createPublicFiles()
160
+ const appCtx = createAppContext({
161
+ root,
162
+ outDir,
163
+ publicDir: join(outDir, 'public'),
164
+ assetPrefix,
165
+ site,
166
+ dev: isDev,
167
+ nodeEnv: effectiveNodeEnv,
168
+ onRegisterPublicFile: publicFiles.register,
169
+ })
170
+
171
+ try {
172
+ return await runWithAppContext(appCtx, () => runBuild({
173
+ options,
174
+ root,
175
+ plugins: resolvePlugins(options.plugins ?? fileConfig.plugins),
176
+ routesDir,
177
+ publicDir,
178
+ finalOutDir,
179
+ stageDir,
180
+ outDir,
181
+ stageSuffix,
182
+ assetPrefix,
183
+ site,
184
+ compliance: fileConfig.compliance,
185
+ minify: options.minify ?? true,
186
+ isDev,
187
+ nodeEnv: effectiveNodeEnv,
188
+ appCtx,
189
+ publicFiles,
190
+ }))
191
+ }
192
+ finally {
193
+ rmSync(stageDir, { recursive: true, force: true })
194
+ if (options.static) {
195
+ rmSync(outDir, { recursive: true, force: true })
196
+ if (!cacheExisted && existsSync(cacheBaseDir) && readdirSync(cacheBaseDir).length === 0)
197
+ rmSync(cacheBaseDir, { recursive: true, force: true })
198
+ }
199
+ }
200
+ }
201
+
202
+ function emitBuildWarnings(run: BuildRun, graph: ModuleGraph, routeFiles: readonly string[]): void {
203
+ for (const [file, analysis] of graph.analyses) {
204
+ const rel = relPosix(run.root, file)
205
+ for (const warning of analysis.warnings) {
206
+ if (!shouldEmitWarning(warning, run.compliance, run.site))
207
+ continue
208
+ const loc = formatLoc(rel, graph.source(file), warning.start)
209
+ console.warn(formatDiagnostic(loc, warning.message.replaceAll(file, rel), 'warning'))
210
+ }
211
+ }
212
+ if (!run.isDev) {
213
+ const projectWarnings = collectProjectComplianceWarnings({
214
+ root: run.root,
215
+ srcDir: join(run.root, 'src'),
216
+ routesDir: run.routesDir,
217
+ routeFiles,
218
+ analyses: graph.analyses,
219
+ compliance: run.compliance,
220
+ site: run.site,
221
+ })
222
+ for (const warning of projectWarnings)
223
+ console.warn(warning)
224
+ }
225
+ }
226
+
227
+
228
+ /** Plans the islands, then runs the rules `prunelle check` also runs on the whole graph: what server code renders wrong, and dynamic prerendered routes with no `paths()`. Throws them all at once, each placed with a code frame. */
229
+ function planCheckedIslands(root: string, routesDir: string, graph: ModuleGraph, pageFiles: string[], specialFiles: string[], isStatic: boolean): ReturnType<typeof planIslands> {
230
+ const islands = planIslands(graph, root, pageFiles, specialFiles)
231
+ const placed: string[] = []
232
+ const place = (file: string, offset: number, message: string): void => {
233
+ const source = graph.source(file)
234
+ placed.push(`${formatDiagnostic(formatLoc(relPosix(root, file), source, offset), message)}\n${formatCodeFrame(source, offset)}`)
235
+ }
236
+ const configFile = join(root, 'prunelle.config.ts')
237
+ for (const [file, analysis] of graph.analyses) {
238
+ const rel = relPosix(root, file)
239
+ for (const offset of file === configFile ? [] : serverNodeEnvReads(analysis, islands, file))
240
+ console.warn(formatDiagnostic(formatLoc(rel, graph.source(file), offset), nodeEnvWarning(rel), 'warning'))
241
+ if (!file.endsWith('.tsx') || isInNodeModules(file))
242
+ continue
243
+ for (const problem of renderProblems(analysis, islands, file, rel, 'prunelle build'))
244
+ place(file, problem.offset, problem.message)
245
+ }
246
+ for (const file of pageFiles) {
247
+ const missing = missingPathsProblem(graph.analyses.get(file)!, normalizeRoutePattern(fileToRoutePath(routesDir, file)), isStatic)
248
+ if (missing !== undefined)
249
+ place(file, missing.offset, `prunelle build: ${missing.message}`)
250
+ }
251
+ if (placed.length > 0)
252
+ throw new Error(placed.join('\n\n'))
253
+ return islands
254
+ }
255
+
256
+ /** Lists the files `prunelle dev` watches for the next rebuild, and drops the cached compiles of deleted files so a long session stays flat in memory. */
257
+ function refreshCacheWatches(cache: BuildCache, graph: ModuleGraph, extraFiles: readonly string[]): void {
258
+ const watched = cache.watchedFiles
259
+ watched.clear()
260
+ const recordWatched = (file: string) => {
261
+ if (!existsSync(file))
262
+ return
263
+ let real = file
264
+ try {
265
+ real = realpathSync(file)
266
+ }
267
+ catch {}
268
+ watched.add(real)
269
+ }
270
+ for (const f of graph.analyses.keys())
271
+ recordWatched(f)
272
+ for (const f of cache.lastClient?.inputStamps.keys() ?? [])
273
+ recordWatched(f)
274
+ for (const f of cache.lastServer?.inputStamps.keys() ?? [])
275
+ recordWatched(f)
276
+ for (const f of extraFiles)
277
+ recordWatched(f)
278
+ for (const compiled of [cache.analyses, cache.domCompiled, cache.ssrCompiled]) {
279
+ for (const f of [...compiled.keys()]) {
280
+ if (!existsSync(f))
281
+ compiled.delete(f)
282
+ }
283
+ }
284
+ }
285
+
286
+ function validateRoutesAndMatchers(root: string, routesDir: string, allRouteFiles: readonly string[], specialFiles: readonly string[], candidateFiles: readonly string[], graph: ModuleGraph): { pageFiles: string[], customMatchers: Map<string, string> } {
287
+ const unknownStatus = findUnknownStatusPages(root, allRouteFiles)
288
+ if (unknownStatus.length > 0)
289
+ throw new Error(`prunelle build: ${unknownStatus[0]!.message}`)
290
+ const routesRel = relPosix(root, routesDir)
291
+ for (const f of [...specialFiles, ...candidateFiles]) {
292
+ const analysis = graph.analyses.get(f)!
293
+ const problem = routeFileProblem(analysis, relPosix(root, f), routesRel) ?? routeExportProblem(analysis, relPosix(root, f))
294
+ if (problem !== undefined)
295
+ throw new Error(`prunelle build: ${problem}`)
296
+ }
297
+ // A file exporting only actions stays in routes/ for its folder's middleware.
298
+ const pageFiles = candidateFiles.filter(f => hasRouteHandlerExport(graph.analyses.get(f)!))
299
+ assertNoRouteConflicts(root, routesDir, pageFiles)
300
+ const { customFiles, problems } = discoverRouteMatchers({
301
+ root,
302
+ routesDir,
303
+ routeFiles: [...specialFiles, ...pageFiles],
304
+ loadAnalysis: file => graph.load(file),
305
+ })
306
+ if (problems.length > 0)
307
+ throw new Error(`prunelle build: ${problems[0]!.message}`)
308
+ return { pageFiles, customMatchers: customFiles }
309
+ }
310
+
311
+ function collectActionsByFile(graph: ModuleGraph, root: string, assetPrefix: string): ActionsByFile {
312
+ const actionsByFile: ActionsByFile = new Map()
313
+ for (const [file, analysis] of graph.analyses) {
314
+ if (analysis.exportedActions.length > 0) {
315
+ const rel = relPosix(root, file)
316
+ actionsByFile.set(file, analysis.exportedActions.map(exportName => ({
317
+ exportName,
318
+ url: `${assetPrefix}/action/${actionHash(rel, exportName)}`,
319
+ })))
320
+ }
321
+ }
322
+ return actionsByFile
323
+ }
324
+
325
+ async function validateAppForms(root: string, routesDir: string, routeFiles: readonly string[], graph: ModuleGraph, isDev: boolean): Promise<void> {
326
+ const formCheck = await checkAppForms({ root, routesDir, routeFiles, graph })
327
+ if (formCheck.errors.length > 0)
328
+ throw new Error(formCheck.errors.join('\n'))
329
+ if (!isDev) {
330
+ for (const warning of formCheck.warnings)
331
+ console.warn(warning)
332
+ }
333
+ }
334
+
335
+ async function runBuild(run: BuildRun): Promise<BuildManifest> {
336
+ const { options, root, plugins, routesDir, outDir, assetPrefix, isDev, publicFiles } = run
337
+ const clientDir = join(outDir, 'client')
338
+ const serverDir = join(outDir, 'server')
339
+ const isStatic = options.static === true
340
+
341
+ const allRouteFiles = walkRoutes(routesDir).sort()
342
+ const specialFiles = allRouteFiles.filter(f => SPECIAL_ROUTE_FILES.has(basename(f)))
343
+ const candidateFiles = allRouteFiles.filter(f => !basename(f).startsWith('_'))
344
+ const rootLayoutSrc = join(routesDir, '_layout.tsx')
345
+ const errorSrc = join(routesDir, '_error.tsx')
346
+ const notFoundSrc = join(routesDir, '_404.tsx')
347
+ const hasRootLayout = existsSync(rootLayoutSrc)
348
+ const hasErrorFile = existsSync(errorSrc)
349
+ const hasNotFoundFile = existsSync(notFoundSrc)
350
+
351
+ // Every reachable .ts/.tsx file is analyzed & validated BEFORE wiping outDir, so build errors keep the last working dist/.
352
+ // prunelle.config.ts enters the graph too, so an action or component reached only from it is analyzed and gets its URL.
353
+ const configSrc = join(root, 'prunelle.config.ts')
354
+ const hasConfigFile = existsSync(configSrc)
355
+ const graph = new ModuleGraph(root, options.cache)
356
+ for (const f of [...specialFiles, ...candidateFiles, ...(hasConfigFile ? [configSrc] : [])])
357
+ graph.load(f)
358
+ emitBuildWarnings(run, graph, allRouteFiles)
359
+
360
+ const { pageFiles, customMatchers } = validateRoutesAndMatchers(root, routesDir, allRouteFiles, specialFiles, candidateFiles, graph)
361
+ const customMatcherFiles = [...new Set(customMatchers.values())]
362
+
363
+ const actionsByFile = collectActionsByFile(graph, root, assetPrefix)
364
+ const islands = planCheckedIslands(root, routesDir, graph, pageFiles, specialFiles, isStatic)
365
+ await validateAppForms(root, routesDir, allRouteFiles, graph, isDev)
366
+
367
+ mkdirSync(clientDir, { recursive: true })
368
+ mkdirSync(serverDir, { recursive: true })
369
+ const pluginCssFiles = plugins
370
+ .flatMap(p => p.css ?? [])
371
+ .map(c => resolve(root, c))
372
+ .filter(c => existsSync(c))
373
+ const env = { root, outDir, clientDir, serverDir, assetPrefix, minify: run.minify, isDev, nodeEnv: run.nodeEnv, analyze: options.analyze === true || options.analyzeJson === true || options.maxJs !== undefined, graph, cache: options.cache, plugins, actionsByFile, islands }
374
+
375
+ const routeEntryFiles = new Set([...specialFiles, ...pageFiles])
376
+ const standaloneActionFiles = [...actionsByFile.keys()].filter(f => !routeEntryFiles.has(f))
377
+ // `_entry.js` imports all of these; each stays an entrypoint so its code lands in a content-named chunk that `prunelle dev` keeps loaded while it is unchanged.
378
+ const bundledModules = [...specialFiles, ...pageFiles, ...standaloneActionFiles, ...customMatcherFiles]
379
+ const serverEntries = [...bundledModules, ...(hasConfigFile ? [configSrc] : [])]
380
+ const serverRoot = standaloneActionFiles.length > 0 || customMatcherFiles.length > 0 || hasConfigFile ? root : routesDir
381
+ const toOutRel = (srcFile: string): string =>
382
+ relPosix(outDir, join(serverDir, relative(serverRoot, srcFile).replace(/\.(tsx|ts)$/, '.js')))
383
+ const serverEntry = {
384
+ file: join(serverRoot, SERVER_ENTRY_FILE),
385
+ source: serverEntrySource({
386
+ modules: bundledModules.map(file => ({ file, key: toOutRel(file), source: relPosix(root, file) })),
387
+ config: hasConfigFile ? { file: configSrc, source: relPosix(root, configSrc) } : undefined,
388
+ assembler: join(PRUNELLE_SRC_ROOT, 'server/app-entry.ts'),
389
+ }),
390
+ }
391
+ if (existsSync(serverEntry.file))
392
+ throw new Error(`prunelle build: ${relPosix(root, serverEntry.file)} is the path of prunelle's server entry; rename that file.`)
393
+
394
+ // The server compiles against the island chunk URLs, so islands build first; without islands both passes run in parallel.
395
+ const clientSkipsBefore = options.cache?.stats.clientSkips ?? 0
396
+ const serverSkipsBefore = options.cache?.stats.serverSkips ?? 0
397
+ const clientPass = () => buildClient(env, standaloneCssFiles(graph, pluginCssFiles, islands.cssFiles))
398
+ let client: Awaited<ReturnType<typeof clientPass>>
399
+ if (islands.targets.size === 0) {
400
+ const [built] = await Promise.all([clientPass(), buildServer(env, serverEntries, serverRoot, new Map(), serverEntry)])
401
+ client = built
402
+ }
403
+ else {
404
+ client = await clientPass()
405
+ await buildServer(env, serverEntries, serverRoot, client.islandChunks, serverEntry)
406
+ }
407
+ const anyPassSkipped = options.cache !== undefined
408
+ && (options.cache.stats.clientSkips > clientSkipsBefore || options.cache.stats.serverSkips > serverSkipsBefore)
409
+
410
+ if (options.cache !== undefined)
411
+ refreshCacheWatches(options.cache, graph, [...pluginCssFiles, ...(hasConfigFile ? [configSrc] : [])])
412
+
413
+ const assets: string[] = []
414
+ for (const rel of client.assetFiles) {
415
+ const abs = join(clientDir, rel)
416
+ const size = fileSize(abs)
417
+ if (size === 0)
418
+ rmSync(abs, { force: true })
419
+ else if (size !== undefined)
420
+ assets.push(rel)
421
+ }
422
+ const builtClientAssets = new Set(assets)
423
+
424
+ const { routes, statusPages, globalStyles } = buildRouteEntries({
425
+ graph,
426
+ islands,
427
+ islandChunks: client.islandChunks,
428
+ srcCssToUrl: client.srcCssToUrl,
429
+ islandCssUrl: client.islandCssUrl,
430
+ routesDir,
431
+ pageFiles,
432
+ specialFiles,
433
+ pluginCssFiles,
434
+ isStatic,
435
+ toOutRel,
436
+ })
437
+ const paramMatchers = customMatchers.size > 0
438
+ ? Object.fromEntries([...customMatchers.entries()].map(([name, file]) => [name, toOutRel(file)]))
439
+ : undefined
440
+
441
+ // public/ files are listed in the manifest and copied into outDir/public (`prunelle dev` serves public/ directly instead)
442
+ const outPublicDir = join(outDir, 'public')
443
+ for (const abs of walkAllFiles(run.publicDir).sort()) {
444
+ const rel = publicFiles.register(relative(run.publicDir, abs))
445
+ if (options.copyPublic !== false) {
446
+ mkdirSync(dirname(join(outPublicDir, rel)), { recursive: true })
447
+ copyFileSync(abs, join(outPublicDir, rel))
448
+ }
449
+ }
450
+
451
+ const host = createPluginHost({
452
+ plugins,
453
+ appCtx: run.appCtx,
454
+ root,
455
+ outDir,
456
+ clientDir,
457
+ outPublicDir,
458
+ assetPrefix,
459
+ site: run.site,
460
+ minify: run.minify,
461
+ isStatic,
462
+ isDev,
463
+ routes,
464
+ publicFiles,
465
+ assets,
466
+ styleUrls: client.styleUrls,
467
+ globalStyles,
468
+ })
469
+ await host.runBuild()
470
+ restoreCachedPluginAssets(options.cache, clientDir, assets, anyPassSkipped)
471
+ await host.precompressOutput()
472
+
473
+ const manifest: BuildManifest = {
474
+ runtimeScript: client.runtimeScript, regionScript: client.regionScript, reviveScript: client.reviveScript, chunkImports: client.chunkImports, runtimeOnEveryPage: plugins.some(p => Boolean(p.clientEntry)),
475
+ styles: client.styleUrls,
476
+ globalStyles,
477
+ ...(host.headTags.length > 0 ? { headTags: host.headTags } : {}),
478
+ routes,
479
+ ...(hasRootLayout ? { rootLayoutFile: toOutRel(rootLayoutSrc) } : {}),
480
+ errorFile: hasErrorFile ? toOutRel(errorSrc) : undefined,
481
+ notFoundFile: hasNotFoundFile ? toOutRel(notFoundSrc) : undefined,
482
+ ...(statusPages.length > 0 ? { statusPages } : {}),
483
+ ...(paramMatchers !== undefined ? { paramMatchers } : {}),
484
+ actions: buildActionEntries(actionsByFile, routesDir, toOutRel),
485
+ islands: Object.fromEntries(client.islandChunks),
486
+ assets,
487
+ publicFiles: publicFiles.files,
488
+ ...(Object.keys(host.pluginData).length > 0 ? { pluginData: host.pluginData } : {}),
489
+ }
490
+ const writeManifest = (): void => writeFileSync(join(outDir, 'manifest.json'), JSON.stringify(manifest, null, 2))
491
+ writeManifest()
492
+ if (options.analyze === true || options.analyzeJson === true || options.maxJs !== undefined) {
493
+ const report = analyzeBundleWeights(manifest, clientDir, assetPrefix, client.metafile, islandOrigins(islands, client.islandChunks, graph, root), [outPublicDir, run.publicDir])
494
+ if (options.analyzeJson === true)
495
+ console.log(formatBundleReportJson(report))
496
+ else if (options.analyze === true)
497
+ console.log(formatBundleReport(report))
498
+ if (options.maxJs !== undefined)
499
+ checkJsBudget(report, options.maxJs)
500
+ }
501
+
502
+ await landBuild(run, { manifest, writeManifest, host, env, assets, builtClientAssets, hasNotFoundFile })
503
+ return manifest
504
+ }
505
+
506
+ interface BuiltOutput {
507
+ manifest: BuildManifest
508
+ writeManifest: () => void
509
+ host: ReturnType<typeof createPluginHost>
510
+ env: Parameters<typeof pluginBunPlugins>[0]
511
+ assets: string[]
512
+ builtClientAssets: ReadonlySet<string>
513
+ hasNotFoundFile: boolean
514
+ }
515
+
516
+ /** Prerenders, runs the plugins' after-prerender hooks, exports or carries the previous build's dropped files, compiles, then swaps the stage in. */
517
+ async function landBuild(run: BuildRun, built: BuiltOutput): Promise<void> {
518
+ const { options, root, plugins, outDir, assetPrefix, isDev, publicFiles } = run
519
+ const { manifest, writeManifest, host, env, assets, builtClientAssets, hasNotFoundFile } = built
520
+ const clientDir = join(outDir, 'client')
521
+ const isStatic = options.static === true
522
+
523
+ // Hybrid prerendering / static export (skipped in `prunelle dev`, where routes render on-demand)
524
+ const prerenderRoutes = options.prerender !== false || isStatic ? manifest.routes.filter(r => r.prerender) : []
525
+ const prerenderDir = isStatic ? run.stageDir : join(outDir, 'prerendered')
526
+ const prerendered = prerenderRoutes.length > 0 || isStatic
527
+ ? await prerender({ root, outDir, assetPrefix, site: run.site, plugins, pluginOverride: options.plugins, isDev, nodeEnv: run.nodeEnv, isStatic, prerenderDir, routes: prerenderRoutes })
528
+ : undefined
529
+
530
+ try {
531
+ const ranAfterPrerender = await host.runAfterPrerender()
532
+ recordCachedPluginAssets(options.cache, clientDir, assets, builtClientAssets)
533
+ await host.precompressOutput()
534
+ if (Object.keys(host.pluginData).length > 0)
535
+ manifest.pluginData = host.pluginData
536
+
537
+ if (isStatic) {
538
+ await exportStatic({
539
+ root: run.root,
540
+ stageDir: prerenderDir,
541
+ finalOutDir: run.finalOutDir,
542
+ outDir,
543
+ clientDir,
544
+ assetPrefix,
545
+ site: run.site,
546
+ isDev,
547
+ manifest,
548
+ entry: prerendered?.entry,
549
+ pluginOverride: options.plugins,
550
+ assets,
551
+ publicFiles,
552
+ app: prerendered?.app,
553
+ hasNotFoundFile,
554
+ stageSuffix: run.stageSuffix,
555
+ })
556
+ }
557
+ else if (prerenderRoutes.length > 0 || ranAfterPrerender) {
558
+ writeManifest()
559
+ }
560
+ }
561
+ finally {
562
+ await prerendered?.app?.dispose?.()
563
+ }
564
+
565
+ if (!isStatic && !isDev) {
566
+ const carried = carryPreviousAssets(run.finalOutDir, outDir, 'client', manifest.assets)
567
+ if (carried.length > 0) {
568
+ manifest.carriedAssets = carried
569
+ writeManifest()
570
+ }
571
+ }
572
+
573
+ if (options.compile) {
574
+ await compileExecutable({
575
+ root,
576
+ outDir,
577
+ clientDir,
578
+ manifest,
579
+ assetPrefix,
580
+ site: options.site !== undefined ? run.site : undefined,
581
+ outfile: compileOutfile(options.compile, root, outDir, run.finalOutDir),
582
+
583
+ resolvePrunelleSpecifier,
584
+ bunPlugins: pluginBunPlugins(env, 'compile'),
585
+ })
586
+ }
587
+
588
+ if (!isStatic) {
589
+ swapStage(outDir, run.finalOutDir, run.stageSuffix)
590
+ relocateCache(options.cache, outDir, run.finalOutDir)
591
+ }
592
+ }
593
+
594
+ /** Where `--compile` writes the binary: a path inside the output folder goes into the stage, so the swap keeps it. */
595
+ function compileOutfile(compile: string | true, root: string, stageDir: string, finalOutDir: string): string {
596
+ if (compile === true)
597
+ return join(stageDir, 'server-bin')
598
+ const outfile = resolve(root, compile)
599
+ return isInside(finalOutDir, outfile) ? join(stageDir, relative(finalOutDir, outfile)) : outfile
600
+ }
601
+
602
+ /** Points the cache's reusable folders at where the swap moved them, so the next build links from there. */
603
+ function relocateCache(cache: BuildCache | undefined, from: string, to: string): void {
604
+ if (cache === undefined)
605
+ return
606
+ const moved = (dir: string): string => dir.startsWith(from) ? to + dir.slice(from.length) : dir
607
+ if (cache.lastClient !== undefined)
608
+ cache.lastClient.clientDir = moved(cache.lastClient.clientDir)
609
+ if (cache.lastServer !== undefined)
610
+ cache.lastServer.serverDir = moved(cache.lastServer.serverDir)
611
+ const assets = cachedPluginAssets.get(cache)
612
+ if (assets !== undefined)
613
+ assets.clientDir = moved(assets.clientDir)
614
+ }
@@ -0,0 +1,12 @@
1
+ // Path confinement, on its own so the server can check a path without loading the build's file helpers and `node:zlib` with them.
2
+
3
+ import { isAbsolute, relative } from 'node:path'
4
+
5
+ /** Whether `target` lies under `dir`, or is `dir` itself with `orSame`. Paths are compared as written: realpath both first to follow symlinks. */
6
+ export function isInside(dir: string, target: string, options: { orSame?: boolean } = {}): boolean {
7
+ const rel = relative(dir, target)
8
+ if (rel === '')
9
+ return options.orSame === true
10
+ // `..x` is a name inside `dir`; only `..` itself, as a whole segment, leaves it.
11
+ return rel !== '..' && !rel.startsWith('../') && !rel.startsWith('..\\') && !isAbsolute(rel)
12
+ }