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,281 @@
1
+ // The build manifest: its shape, and the per-route entries (islands, styles, layouts, middlewares) computed from the module graph.
2
+
3
+ import type { ModuleGraph } from './graph'
4
+ import type { IslandPlan } from './islands'
5
+ import type { StatusPageManifestEntry } from './status-pages'
6
+ import { join } from 'node:path'
7
+ import { isInside } from './is-inside'
8
+ import { islandKey } from './islands'
9
+ import { ancestorFiles, fileToRoutePath, MIDDLEWARE_NAMES } from './routes'
10
+ import { buildStatusPageEntries } from './status-pages'
11
+
12
+ export type { StatusPageKind, StatusPageManifestEntry } from './status-pages'
13
+
14
+ const REGION_SOURCES = new Set(['prunelle', 'prunelle/internal/ssr'])
15
+
16
+ export interface ActionManifestEntry {
17
+ url: string
18
+ file: string
19
+ exportName: string
20
+ /** `_middleware.ts` chain of the folder declaring the action, outermost first. */
21
+ middlewares: string[]
22
+ }
23
+
24
+ export interface RouteManifestEntry {
25
+ path: string
26
+ file: string
27
+ layouts: string[]
28
+ middlewares: string[]
29
+ hasLoad?: boolean | undefined
30
+ isIsland?: boolean | undefined
31
+ islandChunk?: string | undefined
32
+ islandHydrate?: string | undefined
33
+ /** Top-level keys of `load()` data statically read by a page island (`undefined` when `data` escapes). */
34
+ islandDataKeys?: string[] | undefined
35
+ islandChunks: string[]
36
+ eagerIslandChunks?: string[] | undefined
37
+ /** Per-route stylesheets (global plugin styles + CSS imported by this route, its layouts, and its islands). */
38
+ styles?: string[] | undefined
39
+ /** Per-route raw <head> HTML tags injected by plugins via `ctx.addRouteHead()`. */
40
+ headTags?: string[] | undefined
41
+ usesRenderContext?: boolean | undefined
42
+ /** The route, a layout or a component it renders imports `<Region>`. */
43
+ usesRegion?: boolean | undefined
44
+ prerender?: boolean | undefined
45
+ prerendered?: Record<string, string> | undefined
46
+ /** CSP hashes of the app's `<style>` blocks per prerendered URL, for the pages that have any. */
47
+ prerenderedStyleHashes?: Record<string, string[]> | undefined
48
+ }
49
+
50
+ export interface BuildManifest {
51
+ runtimeScript: string | undefined
52
+ /** The plugins' `regionClientEntry`, loaded by the routes with `usesRegion`. */
53
+ regionScript?: string | undefined
54
+ /** The prop revivers, preloaded by a page whose island props hold a Date, Map, Set or another tagged value. */
55
+ reviveScript?: string | undefined
56
+ /** Entry URL (runtime, island, region bundle) to the chunks it imports statically, transitively: a page preloads them with the entry. */
57
+ chunkImports?: Record<string, string[]> | undefined
58
+ /** A plugin's `clientEntry` is in the runtime, so every page loads it, islands or not. */
59
+ runtimeOnEveryPage?: boolean | undefined
60
+ styles: string[]
61
+ /** Stylesheets applied globally (plugin CSS, ctx.addStyle, and root layout CSS) — used by _error/_404. */
62
+ globalStyles?: string[] | undefined
63
+ headTags?: string[] | undefined
64
+ routes: RouteManifestEntry[]
65
+
66
+ /** Explicit root `_layout.tsx` compiled module path (never inferred from subdirectory layouts). */
67
+ rootLayoutFile?: string | undefined
68
+ errorFile?: string | undefined
69
+ notFoundFile?: string | undefined
70
+ /** Discovered status/error pages (`_401`, `_403`, `_404`, `_429`, `_503`, `_error`), root and nested. */
71
+ statusPages?: StatusPageManifestEntry[] | undefined
72
+ /** Custom app param matchers (`src/params/<name>.ts`), mapping matcher name to compiled module key. */
73
+ paramMatchers?: Record<string, string> | undefined
74
+ actions: ActionManifestEntry[]
75
+ islands: Record<string, string>
76
+ assets: string[]
77
+ /** The previous build's client files this one dropped, kept one more deploy for pages loaded before it (#3663); never linked from a page. */
78
+ carriedAssets?: string[] | undefined
79
+ publicFiles: string[]
80
+ /** Serializable build-time metadata persisted by plugins via `ctx.setData()`, read via `api.getBuildData()`. */
81
+ pluginData?: Record<string, Record<string, unknown>> | undefined
82
+ }
83
+
84
+ interface FileReach {
85
+ /** Island chunks reachable from the file, and the subset loaded eagerly. */
86
+ chunks: Set<string>
87
+ eager: Set<string>
88
+ styles: Set<string>
89
+ usesRenderContext: boolean
90
+ usesRegion: boolean
91
+ }
92
+
93
+ /** Walks what a module renders and imports to find the island chunks, stylesheets and render-context use behind it. */
94
+ function createReachWalker(graph: ModuleGraph, islands: IslandPlan, islandChunks: Map<string, string>, srcCssToUrl: Map<string, string>, islandCssUrl: Map<string, string>) {
95
+ const { analyses } = graph
96
+
97
+ function walkIslands(file: string, seen: Set<string>, reach: FileReach): void {
98
+ if (seen.has(file))
99
+ return
100
+ seen.add(file)
101
+ const analysis = analyses.get(file)
102
+ if (analysis === undefined)
103
+ return
104
+ if (analysis.isInteractive) {
105
+ const chunk = islandChunks.get(`${file}#default`)
106
+ if (chunk !== undefined) {
107
+ reach.chunks.add(chunk)
108
+ if (analysis.defaultHydrate === undefined || analysis.defaultHydrate === 'load')
109
+ reach.eager.add(chunk)
110
+ }
111
+ // Imports rendered only inside the module's islands ship within them; a static component beside an island renders its own.
112
+ if (analysis.staticJsxTags.size === 0)
113
+ return
114
+ }
115
+ for (const [localName, target] of islands.pageBindings.get(file) ?? []) {
116
+ const chunk = islandChunks.get(islandKey(target))
117
+ if (chunk === undefined)
118
+ continue
119
+ reach.chunks.add(chunk)
120
+ const isDeferred = analysis.deferredIslandTags.has(localName)
121
+ || (target.defaultHydrate !== undefined && target.defaultHydrate !== 'load')
122
+ if (!isDeferred)
123
+ reach.eager.add(chunk)
124
+ }
125
+ for (const dep of graph.localDeps(file))
126
+ walkIslands(dep, seen, reach)
127
+ }
128
+
129
+ function walkStyles(file: string, seen: Set<string>, out: Set<string>): void {
130
+ if (seen.has(file))
131
+ return
132
+ seen.add(file)
133
+ const analysis = analyses.get(file)
134
+ if (analysis === undefined)
135
+ return
136
+ if (analysis.isInteractive) {
137
+ const islCss = islandCssUrl.get(`${file}#default`)
138
+ if (islCss !== undefined)
139
+ out.add(islCss)
140
+ }
141
+ for (const target of islands.pageBindings.get(file)?.values() ?? []) {
142
+ const islCss = islandCssUrl.get(islandKey(target))
143
+ if (islCss !== undefined)
144
+ out.add(islCss)
145
+ walkStyles(target.file, seen, out)
146
+ }
147
+ for (const imp of analysis.imports) {
148
+ const cssUrl = srcCssToUrl.get(graph.resolve(file, imp.source) ?? '')
149
+ if (cssUrl !== undefined)
150
+ out.add(cssUrl)
151
+ }
152
+ for (const dep of graph.localDeps(file))
153
+ walkStyles(dep, seen, out)
154
+ }
155
+
156
+ function walkRenderContext(file: string, seen: Set<string>): boolean {
157
+ if (seen.has(file))
158
+ return false
159
+ seen.add(file)
160
+ const analysis = analyses.get(file)
161
+ if (analysis === undefined)
162
+ return false
163
+ return analysis.usesRenderContext || graph.localDeps(file).some(dep => walkRenderContext(dep, seen))
164
+ }
165
+
166
+ // A namespace import of prunelle may render `NS.Region`, so it counts.
167
+ function walkRegion(file: string, seen: Set<string>): boolean {
168
+ if (seen.has(file))
169
+ return false
170
+ seen.add(file)
171
+ const analysis = analyses.get(file)
172
+ if (analysis === undefined)
173
+ return false
174
+ return analysis.imports.some(imp => REGION_SOURCES.has(imp.source) && imp.specifiers.some(s => s.imported === 'Region' || s.imported === '*'))
175
+ || graph.localDeps(file).some(dep => walkRegion(dep, seen))
176
+ }
177
+
178
+ // Layouts are shared by many routes, so each file is walked once.
179
+ const memo = new Map<string, FileReach>()
180
+ return (file: string): FileReach => {
181
+ let reach = memo.get(file)
182
+ if (reach === undefined) {
183
+ reach = { chunks: new Set(), eager: new Set(), styles: new Set(), usesRenderContext: false, usesRegion: false }
184
+ walkIslands(file, new Set(), reach)
185
+ walkStyles(file, new Set(), reach.styles)
186
+ reach.usesRenderContext = walkRenderContext(file, new Set())
187
+ reach.usesRegion = walkRegion(file, new Set())
188
+ memo.set(file, reach)
189
+ }
190
+ return reach
191
+ }
192
+ }
193
+
194
+ export interface RouteEntries {
195
+ routes: RouteManifestEntry[]
196
+ statusPages: StatusPageManifestEntry[]
197
+ /** Stylesheets of every page: the plugins' CSS, then the root layout's. */
198
+ globalStyles: string[]
199
+ /** The plugins' CSS alone. */
200
+ globalPluginStyles: string[]
201
+ }
202
+
203
+ export function buildRouteEntries(options: {
204
+ graph: ModuleGraph
205
+ islands: IslandPlan
206
+ islandChunks: Map<string, string>
207
+ srcCssToUrl: Map<string, string>
208
+ islandCssUrl: Map<string, string>
209
+ routesDir: string
210
+ pageFiles: string[]
211
+ specialFiles?: readonly string[] | undefined
212
+ pluginCssFiles: string[]
213
+ isStatic: boolean
214
+ /** Maps a source file to its compiled module, relative to the out dir. */
215
+ toOutRel: (srcFile: string) => string
216
+ }): RouteEntries {
217
+ const { graph, islands, islandChunks, routesDir, toOutRel } = options
218
+ const reachOf = createReachWalker(graph, islands, islandChunks, options.srcCssToUrl, options.islandCssUrl)
219
+
220
+ const globalPluginStyles = [...new Set(options.pluginCssFiles.map(css => options.srcCssToUrl.get(css)).filter((url): url is string => url !== undefined))]
221
+ const rootLayout = join(routesDir, '_layout.tsx')
222
+ const globalStyles = [...new Set([...globalPluginStyles, ...(graph.analyses.has(rootLayout) ? reachOf(rootLayout).styles : [])])]
223
+
224
+ const routes = options.pageFiles.map((file): RouteManifestEntry => {
225
+ const analysis = graph.analyses.get(file)
226
+ const page = analysis?.exports.get('default')
227
+ const layoutSrcs = ancestorFiles(routesDir, file, ['_layout.tsx'])
228
+ const chunks = new Set<string>()
229
+ const eagerChunks = new Set<string>()
230
+ const styles = new Set<string>(globalPluginStyles)
231
+ let usesRenderContext = false
232
+ let usesRegion = false
233
+ for (const src of [...layoutSrcs, file]) {
234
+ const reach = reachOf(src)
235
+ for (const chunk of reach.chunks)
236
+ chunks.add(chunk)
237
+ for (const chunk of reach.eager)
238
+ eagerChunks.add(chunk)
239
+ for (const style of reach.styles)
240
+ styles.add(style)
241
+ usesRenderContext ||= reach.usesRenderContext
242
+ usesRegion ||= reach.usesRegion
243
+ }
244
+ return {
245
+ path: fileToRoutePath(routesDir, file),
246
+ file: toOutRel(file),
247
+ layouts: layoutSrcs.map(toOutRel),
248
+ middlewares: ancestorFiles(routesDir, file, MIDDLEWARE_NAMES).map(toOutRel),
249
+ hasLoad: analysis?.hasLoadExport,
250
+ isIsland: page?.interactive,
251
+ islandChunk: islandChunks.get(`${file}#default`),
252
+ islandHydrate: analysis?.defaultHydrate,
253
+ islandDataKeys: page?.interactive === true && analysis?.hasLoadExport === true ? analysis.defaultDataKeys : undefined,
254
+ islandChunks: [...chunks],
255
+ eagerIslandChunks: [...eagerChunks],
256
+ styles: [...styles],
257
+ usesRenderContext,
258
+ usesRegion,
259
+ prerender: analysis?.hasPrerender || options.isStatic,
260
+ }
261
+ })
262
+ const statusPages = buildStatusPageEntries({
263
+ routesDir,
264
+ specialFiles: options.specialFiles ?? [],
265
+ globalPluginStyles,
266
+ reachOf,
267
+ toOutRel,
268
+ })
269
+ return { routes, statusPages, globalStyles, globalPluginStyles }
270
+ }
271
+
272
+ export function buildActionEntries(actionsByFile: Map<string, { exportName: string, url: string }[]>, routesDir: string, toOutRel: (srcFile: string) => string): ActionManifestEntry[] {
273
+ const entries: ActionManifestEntry[] = []
274
+ for (const [srcFile, list] of actionsByFile) {
275
+ const inRoutes = isInside(routesDir, srcFile, { orSame: true })
276
+ const middlewares = inRoutes ? ancestorFiles(routesDir, srcFile, MIDDLEWARE_NAMES).map(toOutRel) : []
277
+ for (const a of list)
278
+ entries.push({ url: a.url, file: toOutRel(srcFile), exportName: a.exportName, middlewares })
279
+ }
280
+ return entries
281
+ }
@@ -0,0 +1,84 @@
1
+ // The output folder's life: a build writes into a stage beside it, and swaps the stage in only once every step passed.
2
+
3
+ import { existsSync, mkdirSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs'
4
+ import { basename, dirname, join } from 'node:path'
5
+ import { relPosix } from './files'
6
+
7
+ /** The file prunelle writes into each folder it builds, so a later build knows the folder is its own to replace. */
8
+ export const OUTPUT_MARKER = '.prunelle-output'
9
+
10
+ const LEADING_SLASH_RE = /^\/+/
11
+
12
+ /** Throws unless `outDir` is missing, empty, or a folder prunelle built: replacing it must never delete someone's files. */
13
+ export function assertOwnOutDir(root: string, outDir: string, assetPrefix: string): void {
14
+ if (!existsSync(outDir))
15
+ return
16
+ const names = new Set(readdirSync(outDir))
17
+ if (names.size === 0 || names.has(OUTPUT_MARKER))
18
+ return
19
+ // A build made before the marker existed: a server build's manifest beside its server/ folder, or a static export's asset folder (including a kay v2 export's `_kay/`).
20
+ const assetDir = assetPrefix.replace(LEADING_SLASH_RE, '').split('/')[0] ?? ''
21
+ if ((names.has('manifest.json') && names.has('server')) || (assetDir !== '' && names.has(assetDir)) || names.has('_kay'))
22
+ return
23
+ throw new Error(`prunelle build: refusing to replace "${relPosix(root, outDir)}": it holds files prunelle did not build. Delete it, or set \`outDir\` in prunelle.config.ts to a folder of its own.`)
24
+ }
25
+
26
+ /** The stage folder a build writes into, beside `finalOutDir` so a rename swaps it in. */
27
+ export function stageDirFor(finalOutDir: string, suffix: string): string {
28
+ return join(dirname(finalOutDir), `.${basename(finalOutDir)}.stage-${suffix}`)
29
+ }
30
+
31
+ /** A suffix naming the running process first, so a later build can tell a dead build's leftovers from a live one's. */
32
+ export function processSuffix(): string {
33
+ return `${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
34
+ }
35
+
36
+ function isAlive(pid: number): boolean {
37
+ try {
38
+ process.kill(pid, 0)
39
+ return true
40
+ }
41
+ catch (err) {
42
+ return err instanceof Error && 'code' in err && err.code === 'EPERM'
43
+ }
44
+ }
45
+
46
+ /** Removes the folders under `parent` whose name is `prefix` then a process suffix, when that process has died. */
47
+ export function removeDeadProcessDirs(parent: string, prefix: string): void {
48
+ if (!existsSync(parent))
49
+ return
50
+ for (const name of readdirSync(parent)) {
51
+ if (!name.startsWith(prefix))
52
+ continue
53
+ const pid = Number.parseInt(name.slice(prefix.length), 10)
54
+ if (Number.isInteger(pid) && pid !== process.pid && !isAlive(pid))
55
+ rmSync(join(parent, name), { recursive: true, force: true })
56
+ }
57
+ }
58
+
59
+ /** Removes the stage and backup folders a killed build left beside `finalOutDir`. */
60
+ export function removeStaleStages(finalOutDir: string): void {
61
+ const parent = dirname(finalOutDir)
62
+ removeDeadProcessDirs(parent, `.${basename(finalOutDir)}.stage-`)
63
+ removeDeadProcessDirs(parent, `.${basename(finalOutDir)}.prev-`)
64
+ }
65
+
66
+ /** Marks `stageDir` as prunelle's output and renames it to `finalOutDir`, putting the previous folder back if the rename fails. */
67
+ export function swapStage(stageDir: string, finalOutDir: string, suffix: string): void {
68
+ writeFileSync(join(stageDir, OUTPUT_MARKER), 'Built by prunelle. The next prunelle build replaces this folder.\n')
69
+ if (!existsSync(finalOutDir)) {
70
+ mkdirSync(dirname(finalOutDir), { recursive: true })
71
+ renameSync(stageDir, finalOutDir)
72
+ return
73
+ }
74
+ const backupDir = join(dirname(finalOutDir), `.${basename(finalOutDir)}.prev-${suffix}`)
75
+ renameSync(finalOutDir, backupDir)
76
+ try {
77
+ renameSync(stageDir, finalOutDir)
78
+ }
79
+ catch (err) {
80
+ renameSync(backupDir, finalOutDir)
81
+ throw err
82
+ }
83
+ rmSync(backupDir, { recursive: true, force: true })
84
+ }
@@ -0,0 +1,220 @@
1
+ // What plugins see of a build: the `build(ctx)` and `afterPrerender(ctx)` hooks, and the shared lists (assets, styles, head tags, public files) those hooks add to.
2
+
3
+ import type { AppRuntimeContext } from '../plugins/context'
4
+ import type { BuildPluginContext, FinalizeBuildContext, PrunellePlugin } from '../plugins/index'
5
+ import type { RouteManifestEntry } from './manifest'
6
+ import { existsSync, mkdirSync, writeFileSync } from 'node:fs'
7
+ import { dirname, join } from 'node:path'
8
+ import { precompressFiles } from './precompress'
9
+
10
+ const LEADING_SLASHES_RE = /^\/+/
11
+ const BACKSLASH_RE = /\\/g
12
+
13
+ function cleanRel(relPath: string): string {
14
+ return relPath.replace(LEADING_SLASHES_RE, '').replace(BACKSLASH_RE, '/')
15
+ }
16
+
17
+ export interface PublicFiles {
18
+ /** Public files known so far, as relative paths in registration order. */
19
+ files: string[]
20
+ /** Records a public file and returns its normalized relative path. */
21
+ register: (relPath: string) => string
22
+ }
23
+
24
+ /** A plugin hook's throw, renamed `prunelle build: plugin "<name>" <hook> failed: <message>` with the original as `cause`. */
25
+ export function pluginHookError(plugin: Pick<PrunellePlugin, 'name'>, hook: string, error: unknown): Error {
26
+ const message = error instanceof Error ? error.message : String(error)
27
+ return new Error(`prunelle build: plugin "${plugin.name}" ${hook} failed: ${message}`, { cause: error })
28
+ }
29
+
30
+ /** Runs one plugin hook, so a throw names the plugin and the hook. */
31
+ export async function runPluginHook<T>(plugin: Pick<PrunellePlugin, 'name'>, hook: string, run: () => T | Promise<T>): Promise<T> {
32
+ try {
33
+ return await run()
34
+ }
35
+ catch (error) {
36
+ throw pluginHookError(plugin, hook, error)
37
+ }
38
+ }
39
+
40
+ export function createPublicFiles(): PublicFiles {
41
+ const files: string[] = []
42
+ const seen = new Set<string>()
43
+ return {
44
+ files,
45
+ register(relPath) {
46
+ const clean = cleanRel(relPath)
47
+ if (clean !== '' && !seen.has(clean)) {
48
+ seen.add(clean)
49
+ files.push(clean)
50
+ }
51
+ return clean
52
+ },
53
+ }
54
+ }
55
+
56
+ export interface PluginHostOptions {
57
+ plugins: PrunellePlugin[]
58
+ appCtx: AppRuntimeContext
59
+ root: string
60
+ outDir: string
61
+ clientDir: string
62
+ outPublicDir: string
63
+ assetPrefix: string
64
+ site?: string | undefined
65
+ minify: boolean
66
+ isStatic: boolean
67
+ isDev: boolean
68
+ routes: RouteManifestEntry[]
69
+ publicFiles: PublicFiles
70
+ /** Client files already emitted, relative to the client dir. */
71
+ assets: string[]
72
+ styleUrls: string[]
73
+ globalStyles: string[]
74
+ }
75
+
76
+ export function createPluginHost(options: PluginHostOptions) {
77
+ const { plugins, appCtx, outDir, clientDir, outPublicDir, assetPrefix, routes, assets, styleUrls, globalStyles } = options
78
+ const assetSet = new Set(assets)
79
+ const styleSet = new Set(styleUrls)
80
+ const globalStyleSet = new Set(globalStyles)
81
+ const headTags: string[] = []
82
+ const pluginData: Record<string, Record<string, unknown>> = {}
83
+ const precompressed = new Set<string>()
84
+
85
+ function emitAsset(relPath: string, content: string | Uint8Array): string {
86
+ const clean = cleanRel(relPath)
87
+ const dst = join(clientDir, clean)
88
+ mkdirSync(dirname(dst), { recursive: true })
89
+ writeFileSync(dst, content)
90
+ if (!assetSet.has(clean)) {
91
+ assetSet.add(clean)
92
+ assets.push(clean)
93
+ }
94
+ return `${assetPrefix}/${clean}`
95
+ }
96
+
97
+ function emitPublic(relPath: string, content: string | Uint8Array): string {
98
+ const clean = options.publicFiles.register(relPath)
99
+ const dst = join(outPublicDir, clean)
100
+ mkdirSync(dirname(dst), { recursive: true })
101
+ writeFileSync(dst, content)
102
+ return `/${clean}`
103
+ }
104
+
105
+ function addStyleUrl(href: string): void {
106
+ if (!styleSet.has(href)) {
107
+ styleSet.add(href)
108
+ styleUrls.push(href)
109
+ }
110
+ }
111
+
112
+ // resolvePlugins() refuses two plugins sharing a name, so each name has one owner.
113
+ const setDataFor = (plugin: PrunellePlugin) => (data: Record<string, unknown>): void => {
114
+ pluginData[plugin.name] = { ...pluginData[plugin.name], ...data }
115
+ }
116
+
117
+ const shared = {
118
+ root: options.root,
119
+ outDir,
120
+ assetPrefix,
121
+ ...(options.site !== undefined ? { site: options.site } : {}),
122
+ minify: options.minify,
123
+ isStatic: options.isStatic,
124
+ dev: options.isDev,
125
+ routes,
126
+ emitAsset,
127
+ emitPublic,
128
+ provide: appCtx.provide,
129
+ inject: appCtx.inject,
130
+ }
131
+
132
+ const buildCtx = {
133
+ ...shared,
134
+ addStyle(href: string) {
135
+ addStyleUrl(href)
136
+ if (!globalStyleSet.has(href)) {
137
+ globalStyleSet.add(href)
138
+ globalStyles.push(href)
139
+ }
140
+ for (const r of routes) {
141
+ if (r.styles !== undefined && !r.styles.includes(href))
142
+ r.styles.push(href)
143
+ }
144
+ },
145
+ addRouteStyle(routePath: string, href: string) {
146
+ addStyleUrl(href)
147
+ const route = routes.find(r => r.path === routePath)
148
+ if (route !== undefined) {
149
+ route.styles ??= [...globalStyles]
150
+ if (!route.styles.includes(href))
151
+ route.styles.push(href)
152
+ }
153
+ },
154
+ addHead(html: string) {
155
+ if (html !== '')
156
+ headTags.push(html)
157
+ },
158
+ addRouteHead(routePath: string, html: string) {
159
+ const route = html === '' ? undefined : routes.find(r => r.path === routePath)
160
+ if (route !== undefined)
161
+ (route.headTags ??= []).push(html)
162
+ },
163
+ }
164
+
165
+ return {
166
+ headTags,
167
+ pluginData,
168
+ /** Runs every plugin's `build(ctx)`, so plugins can emit hashed assets, public files, styles, <head> tags, or services. */
169
+ async runBuild(): Promise<void> {
170
+ for (const plugin of plugins) {
171
+ if (plugin.build !== undefined) {
172
+ const ctx: BuildPluginContext = { ...buildCtx, setData: setDataFor(plugin) }
173
+ await runPluginHook(plugin, 'build', () => plugin.build!(ctx))
174
+ }
175
+ }
176
+ },
177
+
178
+ /** Runs every plugin's `afterPrerender(ctx)`, once `route.prerendered` and prerender-emitted public files are known. */
179
+ async runAfterPrerender(): Promise<boolean> {
180
+ let ran = false
181
+ for (const plugin of plugins) {
182
+ if (plugin.afterPrerender !== undefined) {
183
+ ran = true
184
+ const ctx: FinalizeBuildContext = { ...shared, publicFiles: options.publicFiles.files, setData: setDataFor(plugin) }
185
+ await runPluginHook(plugin, 'afterPrerender', () => plugin.afterPrerender!(ctx))
186
+ }
187
+ }
188
+ return ran
189
+ },
190
+
191
+ /**
192
+ * Writes `.br`/`.gz` sidecars for the client assets, public files and prerendered pages not compressed yet, so the server never compresses them itself.
193
+ * Production server builds only: `--static` compresses its own output. A public file the app ships with its own sidecar keeps it.
194
+ */
195
+ async precompressOutput(): Promise<void> {
196
+ if (options.isDev || options.isStatic)
197
+ return
198
+ const pending: string[] = []
199
+ const once = (abs: string): void => {
200
+ if (!precompressed.has(abs)) {
201
+ precompressed.add(abs)
202
+ pending.push(abs)
203
+ }
204
+ }
205
+ for (const rel of assets)
206
+ once(join(clientDir, rel))
207
+ const listed = new Set(options.publicFiles.files)
208
+ for (const rel of listed) {
209
+ const abs = join(outPublicDir, rel)
210
+ if (!listed.has(`${rel}.br`) && !listed.has(`${rel}.gz`) && existsSync(abs))
211
+ once(abs)
212
+ }
213
+ for (const route of routes) {
214
+ for (const rel of Object.values(route.prerendered ?? {}))
215
+ once(join(outDir, rel))
216
+ }
217
+ await precompressFiles(pending, 256, options.root)
218
+ },
219
+ }
220
+ }