prunelle 0.1.1 → 0.7.2

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 (177) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +137 -40
  3. package/package.json +11 -2
  4. package/src/a11y/declaration.ts +373 -0
  5. package/src/a11y/index.ts +477 -0
  6. package/src/a11y/rgaa-map.ts +230 -0
  7. package/src/attrs.ts +11 -3
  8. package/src/build/bundle.ts +89 -41
  9. package/src/build/byte-size.ts +11 -0
  10. package/src/build/client-entries.ts +3 -2
  11. package/src/build/client-plugin.ts +11 -5
  12. package/src/build/client-prune.ts +56 -6
  13. package/src/build/compile.ts +13 -10
  14. package/src/build/ecoindex.ts +238 -0
  15. package/src/build/files.ts +15 -0
  16. package/src/build/first-load.ts +85 -14
  17. package/src/build/graph.ts +29 -39
  18. package/src/build/index.ts +225 -122
  19. package/src/build/island-promote.ts +311 -0
  20. package/src/build/islands.ts +14 -203
  21. package/src/build/manifest.ts +56 -116
  22. package/src/build/output.ts +3 -6
  23. package/src/build/plugin-host.ts +115 -41
  24. package/src/build/precompress.ts +16 -3
  25. package/src/build/prerender.ts +177 -39
  26. package/src/build/reach.ts +200 -0
  27. package/src/build/render-rules.ts +2 -2
  28. package/src/build/report.ts +48 -5
  29. package/src/build/resolve.ts +8 -6
  30. package/src/build/routes.ts +175 -10
  31. package/src/build/static-headers.ts +112 -0
  32. package/src/build/static.ts +139 -39
  33. package/src/build/status-pages.ts +127 -0
  34. package/src/build/style-bundles.ts +526 -0
  35. package/src/cli/check-forms.ts +636 -0
  36. package/src/cli/check-imports.ts +31 -0
  37. package/src/cli/check-links.ts +632 -0
  38. package/src/cli/check-security.ts +64 -0
  39. package/src/cli/check.ts +101 -26
  40. package/src/cli/commands.ts +120 -11
  41. package/src/cli/docs.ts +403 -0
  42. package/src/cli/inspect.ts +105 -15
  43. package/src/cli/mcp-tools.ts +492 -0
  44. package/src/cli/mcp.ts +205 -0
  45. package/src/cli/new.ts +16 -5
  46. package/src/cli/render.ts +416 -0
  47. package/src/cli/upgrade-names.ts +73 -13
  48. package/src/cli/upgrade.ts +156 -22
  49. package/src/compiler/analyze.ts +87 -54
  50. package/src/compiler/browser-globals.ts +140 -17
  51. package/src/compiler/cacheability-private.ts +566 -0
  52. package/src/compiler/cacheability.ts +335 -0
  53. package/src/compiler/compliance-eco.ts +71 -0
  54. package/src/compiler/compliance-rgaa.ts +614 -0
  55. package/src/compiler/compliance-urls.ts +148 -0
  56. package/src/compiler/compliance.ts +407 -352
  57. package/src/compiler/data-keys.ts +199 -192
  58. package/src/compiler/dev-source.ts +87 -0
  59. package/src/compiler/dom-attrs.ts +138 -65
  60. package/src/compiler/dom.ts +517 -442
  61. package/src/compiler/expr-context.ts +260 -81
  62. package/src/compiler/foreign-imports.ts +88 -0
  63. package/src/compiler/mistakes.ts +23 -2
  64. package/src/compiler/props-body.ts +60 -0
  65. package/src/compiler/props.ts +87 -36
  66. package/src/compiler/scope.ts +400 -333
  67. package/src/compiler/server-only.ts +190 -151
  68. package/src/compiler/shared.ts +42 -14
  69. package/src/compiler/signal-reads.ts +6 -2
  70. package/src/compiler/spread-handlers.ts +295 -0
  71. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  72. package/src/compiler/ssr.ts +220 -89
  73. package/src/context.ts +34 -0
  74. package/src/dev/error-log.ts +177 -0
  75. package/src/dev/host-check.ts +32 -0
  76. package/src/dev/index.ts +94 -34
  77. package/src/dev/open-editor.ts +228 -0
  78. package/src/dev/protocol.ts +3 -0
  79. package/src/dev/reload.ts +5 -3
  80. package/src/dev/supervisor.ts +50 -25
  81. package/src/dev/watchers.ts +74 -13
  82. package/src/dom/action.ts +47 -21
  83. package/src/dom/attrs.ts +15 -3
  84. package/src/dom/extras.ts +57 -40
  85. package/src/dom/index.ts +54 -14
  86. package/src/dom/island.ts +102 -68
  87. package/src/dom/loop.ts +66 -32
  88. package/src/eco/declaration.ts +328 -0
  89. package/src/eco/index.ts +69 -0
  90. package/src/index.ts +2 -2
  91. package/src/jsx-runtime.ts +2 -2
  92. package/src/plugins/config.ts +18 -12
  93. package/src/plugins/context.ts +44 -1
  94. package/src/plugins/index.ts +2 -2
  95. package/src/plugins/load.ts +30 -10
  96. package/src/plugins/order.ts +38 -1
  97. package/src/plugins/public.ts +6 -3
  98. package/src/plugins/services.ts +84 -0
  99. package/src/plugins/types.ts +51 -2
  100. package/src/reactivity/graph.ts +10 -0
  101. package/src/reactivity/index.ts +24 -16
  102. package/src/reactivity/selector.ts +31 -4
  103. package/src/reactivity/store.ts +64 -20
  104. package/src/server/action-flash.ts +158 -0
  105. package/src/server/action-protect.ts +199 -0
  106. package/src/server/action-registry.ts +1 -1
  107. package/src/server/action.ts +188 -152
  108. package/src/server/app-secret.ts +63 -0
  109. package/src/server/assets.ts +34 -2
  110. package/src/server/compress.ts +96 -10
  111. package/src/server/consent.ts +59 -22
  112. package/src/server/cookies.ts +16 -2
  113. package/src/server/document.ts +25 -10
  114. package/src/server/env.ts +14 -0
  115. package/src/server/errors.ts +308 -65
  116. package/src/server/form-schema.ts +337 -0
  117. package/src/server/health.ts +275 -0
  118. package/src/server/http.ts +186 -39
  119. package/src/server/index.ts +272 -273
  120. package/src/server/loader.ts +15 -2
  121. package/src/server/page.ts +15 -0
  122. package/src/server/param-matchers.ts +112 -0
  123. package/src/server/plugin-host.ts +125 -88
  124. package/src/server/public.ts +6 -5
  125. package/src/server/rate-limit.ts +102 -36
  126. package/src/server/request-body.ts +1 -1
  127. package/src/server/route-cache.ts +541 -0
  128. package/src/server/route-table.ts +356 -11
  129. package/src/server/router.ts +125 -40
  130. package/src/server/routing.ts +112 -63
  131. package/src/server/sanitize-html.ts +309 -0
  132. package/src/server/security.ts +279 -52
  133. package/src/server/serve-handlers.ts +31 -7
  134. package/src/server/standard-schema.ts +17 -0
  135. package/src/server/start.ts +60 -16
  136. package/src/server/static-dir.ts +91 -12
  137. package/src/server/stream.ts +68 -27
  138. package/src/ssr/consent-banner.ts +58 -0
  139. package/src/ssr/context.ts +106 -8
  140. package/src/ssr/index.ts +151 -4
  141. package/src/ssr/navigation.ts +2 -2
  142. package/src/ssr/region.ts +40 -19
  143. package/src/style.ts +64 -1
  144. package/src/test/browser.ts +28 -13
  145. package/src/test/index.ts +97 -12
  146. package/src/ts-plugin/diagnostics.ts +505 -0
  147. package/src/ts-plugin/fixes.ts +364 -0
  148. package/src/ts-plugin/index.ts +194 -0
  149. package/templates/_shared/AGENTS.md +2 -2
  150. package/templates/_shared/gitignore +5 -0
  151. package/templates/_shared/mcp.json +11 -0
  152. package/templates/_shared/src/routes/legal.tsx +15 -1
  153. package/templates/_shared/tsconfig.json +5 -0
  154. package/templates/app/.env.example +4 -0
  155. package/templates/app/package.json +2 -1
  156. package/templates/app/prunelle.config.ts +2 -0
  157. package/templates/app/src/auth.ts +4 -6
  158. package/templates/app/src/mail.ts +4 -0
  159. package/templates/app/src/routes/_layout.tsx +9 -1
  160. package/templates/app/src/routes/dashboard/index.tsx +42 -8
  161. package/templates/app/src/routes/login.tsx +49 -30
  162. package/templates/app/src/routes/privacy.tsx +25 -0
  163. package/templates/app/src/styles/app.css +8 -1
  164. package/templates/app/tests/app.test.ts +44 -3
  165. package/templates/blog/package.json +1 -1
  166. package/templates/blog/prunelle.config.ts +1 -1
  167. package/templates/blog/src/routes/_layout.tsx +6 -1
  168. package/templates/blog/src/routes/index.tsx +5 -1
  169. package/templates/blog/src/styles/app.css +6 -1
  170. package/templates/fullstack/package.json +1 -1
  171. package/templates/fullstack/src/components/GreetForm.tsx +2 -1
  172. package/templates/fullstack/src/routes/_layout.tsx +4 -0
  173. package/templates/fullstack/src/styles/app.css +11 -1
  174. package/templates/minimal/package.json +1 -1
  175. package/templates/minimal/src/routes/_layout.tsx +4 -0
  176. package/templates/minimal/src/styles/app.css +11 -1
  177. package/ts-plugin.cjs +4277 -0
@@ -1,13 +1,18 @@
1
1
  // The build manifest: its shape, and the per-route entries (islands, styles, layouts, middlewares) computed from the module graph.
2
2
 
3
+ import type { RouteCacheSpec } from '../server/route-cache'
3
4
  import type { ModuleGraph } from './graph'
4
5
  import type { IslandPlan } from './islands'
6
+ import type { StatusPageManifestEntry } from './status-pages'
5
7
  import { join } from 'node:path'
8
+ import { isRouteCacheable } from '../compiler/cacheability'
6
9
  import { isInside } from './is-inside'
7
- import { islandKey } from './islands'
10
+ import { createReachWalker } from './reach'
8
11
  import { ancestorFiles, fileToRoutePath, MIDDLEWARE_NAMES } from './routes'
12
+ import { buildStatusPageEntries } from './status-pages'
13
+
14
+ export type { StatusPageKind, StatusPageManifestEntry } from './status-pages'
9
15
 
10
- const REGION_SOURCES = new Set(['prunelle', 'prunelle/internal/ssr'])
11
16
 
12
17
  export interface ActionManifestEntry {
13
18
  url: string
@@ -38,6 +43,12 @@ export interface RouteManifestEntry {
38
43
  /** The route, a layout or a component it renders imports `<Region>`. */
39
44
  usesRegion?: boolean | undefined
40
45
  prerender?: boolean | undefined
46
+ /** Prerendered only because `autoPrerender` found it static, so the build may render it at request time instead. */
47
+ autoPrerender?: boolean | undefined
48
+ /** Route response cache policy from `export const cache = ...`. */
49
+ cache?: RouteCacheSpec | undefined
50
+ /** True when static analysis proves the page reads nothing from the request or clock. */
51
+ cacheable?: boolean | undefined
41
52
  prerendered?: Record<string, string> | undefined
42
53
  /** CSP hashes of the app's `<style>` blocks per prerendered URL, for the pages that have any. */
43
54
  prerenderedStyleHashes?: Record<string, string[]> | undefined
@@ -63,6 +74,10 @@ export interface BuildManifest {
63
74
  rootLayoutFile?: string | undefined
64
75
  errorFile?: string | undefined
65
76
  notFoundFile?: string | undefined
77
+ /** Discovered status/error pages (`_401`, `_403`, `_404`, `_429`, `_503`, `_error`), root and nested. */
78
+ statusPages?: StatusPageManifestEntry[] | undefined
79
+ /** Custom app param matchers (`src/params/<name>.ts`), mapping matcher name to compiled module key. */
80
+ paramMatchers?: Record<string, string> | undefined
66
81
  actions: ActionManifestEntry[]
67
82
  islands: Record<string, string>
68
83
  assets: string[]
@@ -73,122 +88,17 @@ export interface BuildManifest {
73
88
  pluginData?: Record<string, Record<string, unknown>> | undefined
74
89
  }
75
90
 
76
- interface FileReach {
77
- /** Island chunks reachable from the file, and the subset loaded eagerly. */
78
- chunks: Set<string>
79
- eager: Set<string>
80
- styles: Set<string>
81
- usesRenderContext: boolean
82
- usesRegion: boolean
83
- }
84
-
85
- /** Walks what a module renders and imports to find the island chunks, stylesheets and render-context use behind it. */
86
- function createReachWalker(graph: ModuleGraph, islands: IslandPlan, islandChunks: Map<string, string>, srcCssToUrl: Map<string, string>, islandCssUrl: Map<string, string>) {
87
- const { analyses } = graph
88
-
89
- function walkIslands(file: string, seen: Set<string>, reach: FileReach): void {
90
- if (seen.has(file))
91
- return
92
- seen.add(file)
93
- const analysis = analyses.get(file)
94
- if (analysis === undefined)
95
- return
96
- if (analysis.isInteractive) {
97
- const chunk = islandChunks.get(`${file}#default`)
98
- if (chunk !== undefined) {
99
- reach.chunks.add(chunk)
100
- if (analysis.defaultHydrate === undefined || analysis.defaultHydrate === 'load')
101
- reach.eager.add(chunk)
102
- }
103
- // Imports rendered only inside the module's islands ship within them; a static component beside an island renders its own.
104
- if (analysis.staticJsxTags.size === 0)
105
- return
106
- }
107
- for (const [localName, target] of islands.pageBindings.get(file) ?? []) {
108
- const chunk = islandChunks.get(islandKey(target))
109
- if (chunk === undefined)
110
- continue
111
- reach.chunks.add(chunk)
112
- const isDeferred = analysis.deferredIslandTags.has(localName)
113
- || (target.defaultHydrate !== undefined && target.defaultHydrate !== 'load')
114
- if (!isDeferred)
115
- reach.eager.add(chunk)
116
- }
117
- for (const dep of graph.localDeps(file))
118
- walkIslands(dep, seen, reach)
119
- }
120
-
121
- function walkStyles(file: string, seen: Set<string>, out: Set<string>): void {
122
- if (seen.has(file))
123
- return
124
- seen.add(file)
125
- const analysis = analyses.get(file)
126
- if (analysis === undefined)
127
- return
128
- if (analysis.isInteractive) {
129
- const islCss = islandCssUrl.get(`${file}#default`)
130
- if (islCss !== undefined)
131
- out.add(islCss)
132
- }
133
- for (const target of islands.pageBindings.get(file)?.values() ?? []) {
134
- const islCss = islandCssUrl.get(islandKey(target))
135
- if (islCss !== undefined)
136
- out.add(islCss)
137
- walkStyles(target.file, seen, out)
138
- }
139
- for (const imp of analysis.imports) {
140
- const cssUrl = srcCssToUrl.get(graph.resolve(file, imp.source) ?? '')
141
- if (cssUrl !== undefined)
142
- out.add(cssUrl)
143
- }
144
- for (const dep of graph.localDeps(file))
145
- walkStyles(dep, seen, out)
146
- }
147
-
148
- function walkRenderContext(file: string, seen: Set<string>): boolean {
149
- if (seen.has(file))
150
- return false
151
- seen.add(file)
152
- const analysis = analyses.get(file)
153
- if (analysis === undefined)
154
- return false
155
- return analysis.usesRenderContext || graph.localDeps(file).some(dep => walkRenderContext(dep, seen))
156
- }
157
-
158
- // A namespace import of prunelle may render `NS.Region`, so it counts.
159
- function walkRegion(file: string, seen: Set<string>): boolean {
160
- if (seen.has(file))
161
- return false
162
- seen.add(file)
163
- const analysis = analyses.get(file)
164
- if (analysis === undefined)
165
- return false
166
- return analysis.imports.some(imp => REGION_SOURCES.has(imp.source) && imp.specifiers.some(s => s.imported === 'Region' || s.imported === '*'))
167
- || graph.localDeps(file).some(dep => walkRegion(dep, seen))
168
- }
169
-
170
- // Layouts are shared by many routes, so each file is walked once.
171
- const memo = new Map<string, FileReach>()
172
- return (file: string): FileReach => {
173
- let reach = memo.get(file)
174
- if (reach === undefined) {
175
- reach = { chunks: new Set(), eager: new Set(), styles: new Set(), usesRenderContext: false, usesRegion: false }
176
- walkIslands(file, new Set(), reach)
177
- walkStyles(file, new Set(), reach.styles)
178
- reach.usesRenderContext = walkRenderContext(file, new Set())
179
- reach.usesRegion = walkRegion(file, new Set())
180
- memo.set(file, reach)
181
- }
182
- return reach
183
- }
184
- }
185
-
186
91
  export interface RouteEntries {
187
92
  routes: RouteManifestEntry[]
93
+ statusPages: StatusPageManifestEntry[]
188
94
  /** Stylesheets of every page: the plugins' CSS, then the root layout's. */
189
95
  globalStyles: string[]
190
96
  /** The plugins' CSS alone. */
191
97
  globalPluginStyles: string[]
98
+ /** Reachable source files for each route path (layouts + page + islands + local deps). */
99
+ routeSourceFiles: Map<string, string[]>
100
+ /** Reachable source files of the root layout and status/error pages. */
101
+ globalSourceFiles: string[]
192
102
  }
193
103
 
194
104
  export function buildRouteEntries(options: {
@@ -199,8 +109,11 @@ export function buildRouteEntries(options: {
199
109
  islandCssUrl: Map<string, string>
200
110
  routesDir: string
201
111
  pageFiles: string[]
112
+ specialFiles?: readonly string[] | undefined
202
113
  pluginCssFiles: string[]
203
114
  isStatic: boolean
115
+ /** Automatically prerender static cacheable pages (no middleware, not `prerender = false`, no `cache` export). */
116
+ autoPrerender?: boolean | undefined
204
117
  /** Maps a source file to its compiled module, relative to the out dir. */
205
118
  toOutRel: (srcFile: string) => string
206
119
  }): RouteEntries {
@@ -210,6 +123,8 @@ export function buildRouteEntries(options: {
210
123
  const globalPluginStyles = [...new Set(options.pluginCssFiles.map(css => options.srcCssToUrl.get(css)).filter((url): url is string => url !== undefined))]
211
124
  const rootLayout = join(routesDir, '_layout.tsx')
212
125
  const globalStyles = [...new Set([...globalPluginStyles, ...(graph.analyses.has(rootLayout) ? reachOf(rootLayout).styles : [])])]
126
+ const routeSourceFiles = new Map<string, string[]>()
127
+ const globalSourceSet = new Set<string>(graph.analyses.has(rootLayout) ? reachOf(rootLayout).files : [])
213
128
 
214
129
  const routes = options.pageFiles.map((file): RouteManifestEntry => {
215
130
  const analysis = graph.analyses.get(file)
@@ -218,6 +133,7 @@ export function buildRouteEntries(options: {
218
133
  const chunks = new Set<string>()
219
134
  const eagerChunks = new Set<string>()
220
135
  const styles = new Set<string>(globalPluginStyles)
136
+ const reachableFiles = new Set<string>()
221
137
  let usesRenderContext = false
222
138
  let usesRegion = false
223
139
  for (const src of [...layoutSrcs, file]) {
@@ -228,14 +144,22 @@ export function buildRouteEntries(options: {
228
144
  eagerChunks.add(chunk)
229
145
  for (const style of reach.styles)
230
146
  styles.add(style)
147
+ for (const f of reach.files)
148
+ reachableFiles.add(f)
231
149
  usesRenderContext ||= reach.usesRenderContext
232
150
  usesRegion ||= reach.usesRegion
233
151
  }
152
+ const routePath = fileToRoutePath(routesDir, file)
153
+ routeSourceFiles.set(routePath, [...reachableFiles])
154
+ const middlewareSrcs = ancestorFiles(routesDir, file, MIDDLEWARE_NAMES)
155
+ const cacheable = isRouteCacheable({ graph, islands, file, layoutSrcs, middlewareCount: middlewareSrcs.length, routePath })
156
+ const cache = analysis?.cache
157
+ const autoPre = options.autoPrerender === true && cacheable && cache === undefined
234
158
  return {
235
- path: fileToRoutePath(routesDir, file),
159
+ path: routePath,
236
160
  file: toOutRel(file),
237
161
  layouts: layoutSrcs.map(toOutRel),
238
- middlewares: ancestorFiles(routesDir, file, MIDDLEWARE_NAMES).map(toOutRel),
162
+ middlewares: middlewareSrcs.map(toOutRel),
239
163
  hasLoad: analysis?.hasLoadExport,
240
164
  isIsland: page?.interactive,
241
165
  islandChunk: islandChunks.get(`${file}#default`),
@@ -246,10 +170,26 @@ export function buildRouteEntries(options: {
246
170
  styles: [...styles],
247
171
  usesRenderContext,
248
172
  usesRegion,
249
- prerender: analysis?.hasPrerender || options.isStatic,
173
+ prerender: analysis?.hasPrerender || options.isStatic || autoPre,
174
+ ...(autoPre && analysis?.hasPrerender !== true && !options.isStatic ? { autoPrerender: true } : {}),
175
+ ...(cache !== undefined ? { cache } : {}),
176
+ ...(cacheable ? { cacheable: true } : {}),
250
177
  }
251
178
  })
252
- return { routes, globalStyles, globalPluginStyles }
179
+ for (const special of options.specialFiles ?? []) {
180
+ if (graph.analyses.has(special)) {
181
+ for (const f of reachOf(special).files)
182
+ globalSourceSet.add(f)
183
+ }
184
+ }
185
+ const statusPages = buildStatusPageEntries({
186
+ routesDir,
187
+ specialFiles: options.specialFiles ?? [],
188
+ globalPluginStyles,
189
+ reachOf,
190
+ toOutRel,
191
+ })
192
+ return { routes, statusPages, globalStyles, globalPluginStyles, routeSourceFiles, globalSourceFiles: [...globalSourceSet] }
253
193
  }
254
194
 
255
195
  export function buildActionEntries(actionsByFile: Map<string, { exportName: string, url: string }[]>, routesDir: string, toOutRel: (srcFile: string) => string): ActionManifestEntry[] {
@@ -7,18 +7,15 @@ import { relPosix } from './files'
7
7
  /** The file prunelle writes into each folder it builds, so a later build knows the folder is its own to replace. */
8
8
  export const OUTPUT_MARKER = '.prunelle-output'
9
9
 
10
- const LEADING_SLASH_RE = /^\/+/
11
-
12
10
  /** 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 {
11
+ export function assertOwnOutDir(root: string, outDir: string, _assetPrefix?: string): void {
14
12
  if (!existsSync(outDir))
15
13
  return
16
14
  const names = new Set(readdirSync(outDir))
17
15
  if (names.size === 0 || names.has(OUTPUT_MARKER))
18
16
  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.
20
- const assetDir = assetPrefix.replace(LEADING_SLASH_RE, '').split('/')[0] ?? ''
21
- if ((names.has('manifest.json') && names.has('server')) || (assetDir !== '' && names.has(assetDir)))
17
+ // A build made before the marker existed: a server build's manifest beside its server/ folder, or a static export's default `_pru/` (or kay v2's `_kay/`) folder.
18
+ if ((names.has('manifest.json') && names.has('server')) || names.has('_pru') || names.has('_kay'))
22
19
  return
23
20
  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
21
  }
@@ -2,9 +2,11 @@
2
2
 
3
3
  import type { AppRuntimeContext } from '../plugins/context'
4
4
  import type { BuildPluginContext, FinalizeBuildContext, PrunellePlugin } from '../plugins/index'
5
- import type { RouteManifestEntry } from './manifest'
5
+ import type { RouteManifestEntry, StatusPageManifestEntry } from './manifest'
6
6
  import { existsSync, mkdirSync, writeFileSync } from 'node:fs'
7
- import { dirname, join } from 'node:path'
7
+ import { dirname, join, resolve } from 'node:path'
8
+ import { relPosix } from './files'
9
+ import { isInside } from './is-inside'
8
10
  import { precompressFiles } from './precompress'
9
11
 
10
12
  const LEADING_SLASHES_RE = /^\/+/
@@ -14,6 +16,15 @@ function cleanRel(relPath: string): string {
14
16
  return relPath.replace(LEADING_SLASHES_RE, '').replace(BACKSLASH_RE, '/')
15
17
  }
16
18
 
19
+ /** The clean relative path of a file a plugin writes under `base`, or a throw naming the plugin when it climbs out of `base`. */
20
+ function confinedRel(plugin: string, what: string, base: string, relPath: string): string {
21
+ const clean = cleanRel(relPath)
22
+ const target = resolve(base, clean)
23
+ if (!isInside(base, target))
24
+ throw new Error(`prunelle build: plugin "${plugin}" ${what}("${relPath}") leaves the output folder: use a relative path without "..".`)
25
+ return relPosix(base, target)
26
+ }
27
+
17
28
  export interface PublicFiles {
18
29
  /** Public files known so far, as relative paths in registration order. */
19
30
  files: string[]
@@ -66,6 +77,9 @@ export interface PluginHostOptions {
66
77
  isStatic: boolean
67
78
  isDev: boolean
68
79
  routes: RouteManifestEntry[]
80
+ statusPages?: StatusPageManifestEntry[] | undefined
81
+ routeSourceFiles?: ReadonlyMap<string, readonly string[]> | undefined
82
+ globalSourceFiles?: readonly string[] | undefined
69
83
  publicFiles: PublicFiles
70
84
  /** Client files already emitted, relative to the client dir. */
71
85
  assets: string[]
@@ -73,17 +87,91 @@ export interface PluginHostOptions {
73
87
  globalStyles: string[]
74
88
  }
75
89
 
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)
90
+ function createStyleMutators(
91
+ styleUrls: string[],
92
+ globalStyles: string[],
93
+ routes: RouteManifestEntry[],
94
+ statusPages: StatusPageManifestEntry[],
95
+ ) {
79
96
  const styleSet = new Set(styleUrls)
80
97
  const globalStyleSet = new Set(globalStyles)
98
+ let prependedGlobalCount = 0
99
+
100
+ const addStyleUrl = (href: string): void => {
101
+ if (!styleSet.has(href)) {
102
+ styleSet.add(href)
103
+ styleUrls.push(href)
104
+ }
105
+ }
106
+
107
+ return {
108
+ addStyle(href: string) {
109
+ addStyleUrl(href)
110
+ if (!globalStyleSet.has(href)) {
111
+ globalStyleSet.add(href)
112
+ globalStyles.push(href)
113
+ }
114
+ for (const r of routes) {
115
+ if (r.styles !== undefined && !r.styles.includes(href))
116
+ r.styles.push(href)
117
+ }
118
+ for (const sp of statusPages) {
119
+ if (!sp.styles.includes(href))
120
+ sp.styles.push(href)
121
+ }
122
+ },
123
+ prependStyle(href: string) {
124
+ addStyleUrl(href)
125
+ const insertAt = prependedGlobalCount
126
+ if (!globalStyleSet.has(href)) {
127
+ globalStyleSet.add(href)
128
+ globalStyles.splice(insertAt, 0, href)
129
+ prependedGlobalCount++
130
+ }
131
+ for (const r of routes) {
132
+ if (r.styles !== undefined && !r.styles.includes(href))
133
+ r.styles.splice(Math.min(insertAt, r.styles.length), 0, href)
134
+ }
135
+ for (const sp of statusPages) {
136
+ if (!sp.styles.includes(href))
137
+ sp.styles.splice(Math.min(insertAt, sp.styles.length), 0, href)
138
+ }
139
+ },
140
+ addRouteStyle(routePath: string, href: string) {
141
+ addStyleUrl(href)
142
+ const route = routes.find(r => r.path === routePath)
143
+ if (route !== undefined) {
144
+ route.styles ??= [...globalStyles]
145
+ if (!route.styles.includes(href))
146
+ route.styles.push(href)
147
+ }
148
+ },
149
+ prependRouteStyle(routePath: string, href: string) {
150
+ addStyleUrl(href)
151
+ const route = routes.find(r => r.path === routePath)
152
+ if (route !== undefined) {
153
+ route.styles ??= [...globalStyles]
154
+ if (!route.styles.includes(href)) {
155
+ let idx = 0
156
+ while (idx < route.styles.length && globalStyleSet.has(route.styles[idx]!))
157
+ idx++
158
+ route.styles.splice(idx, 0, href)
159
+ }
160
+ }
161
+ },
162
+ }
163
+ }
164
+
165
+ export function createPluginHost(options: PluginHostOptions) {
166
+ const { plugins, appCtx, outDir, clientDir, outPublicDir, assetPrefix, routes, statusPages = [], assets, styleUrls, globalStyles } = options
167
+ const assetSet = new Set(assets)
81
168
  const headTags: string[] = []
82
169
  const pluginData: Record<string, Record<string, unknown>> = {}
83
170
  const precompressed = new Set<string>()
171
+ const styles = createStyleMutators(styleUrls, globalStyles, routes, statusPages)
84
172
 
85
- function emitAsset(relPath: string, content: string | Uint8Array): string {
86
- const clean = cleanRel(relPath)
173
+ function emitAsset(plugin: string, relPath: string, content: string | Uint8Array): string {
174
+ const clean = confinedRel(plugin, 'emitAsset', clientDir, relPath)
87
175
  const dst = join(clientDir, clean)
88
176
  mkdirSync(dirname(dst), { recursive: true })
89
177
  writeFileSync(dst, content)
@@ -94,21 +182,14 @@ export function createPluginHost(options: PluginHostOptions) {
94
182
  return `${assetPrefix}/${clean}`
95
183
  }
96
184
 
97
- function emitPublic(relPath: string, content: string | Uint8Array): string {
98
- const clean = options.publicFiles.register(relPath)
185
+ function emitPublic(plugin: string, relPath: string, content: string | Uint8Array): string {
186
+ const clean = options.publicFiles.register(confinedRel(plugin, 'emitPublic', outPublicDir, relPath))
99
187
  const dst = join(outPublicDir, clean)
100
188
  mkdirSync(dirname(dst), { recursive: true })
101
189
  writeFileSync(dst, content)
102
190
  return `/${clean}`
103
191
  }
104
192
 
105
- function addStyleUrl(href: string): void {
106
- if (!styleSet.has(href)) {
107
- styleSet.add(href)
108
- styleUrls.push(href)
109
- }
110
- }
111
-
112
193
  // resolvePlugins() refuses two plugins sharing a name, so each name has one owner.
113
194
  const setDataFor = (plugin: PrunellePlugin) => (data: Record<string, unknown>): void => {
114
195
  pluginData[plugin.name] = { ...pluginData[plugin.name], ...data }
@@ -123,34 +204,20 @@ export function createPluginHost(options: PluginHostOptions) {
123
204
  isStatic: options.isStatic,
124
205
  dev: options.isDev,
125
206
  routes,
126
- emitAsset,
127
- emitPublic,
128
207
  provide: appCtx.provide,
129
208
  inject: appCtx.inject,
130
209
  }
131
210
 
211
+ const emittersFor = (plugin: PrunellePlugin) => ({
212
+ emitAsset: (relPath: string, content: string | Uint8Array) => emitAsset(plugin.name, relPath, content),
213
+ emitPublic: (relPath: string, content: string | Uint8Array) => emitPublic(plugin.name, relPath, content),
214
+ })
215
+
132
216
  const buildCtx = {
133
217
  ...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
- },
218
+ ...(options.routeSourceFiles !== undefined ? { routeSourceFiles: options.routeSourceFiles } : {}),
219
+ ...(options.globalSourceFiles !== undefined ? { globalSourceFiles: options.globalSourceFiles } : {}),
220
+ ...styles,
154
221
  addHead(html: string) {
155
222
  if (html !== '')
156
223
  headTags.push(html)
@@ -169,19 +236,26 @@ export function createPluginHost(options: PluginHostOptions) {
169
236
  async runBuild(): Promise<void> {
170
237
  for (const plugin of plugins) {
171
238
  if (plugin.build !== undefined) {
172
- const ctx: BuildPluginContext = { ...buildCtx, setData: setDataFor(plugin) }
239
+ const ctx: BuildPluginContext = { ...buildCtx, ...emittersFor(plugin), setData: setDataFor(plugin) }
173
240
  await runPluginHook(plugin, 'build', () => plugin.build!(ctx))
174
241
  }
175
242
  }
176
243
  },
177
244
 
178
245
  /** Runs every plugin's `afterPrerender(ctx)`, once `route.prerendered` and prerender-emitted public files are known. */
179
- async runAfterPrerender(): Promise<boolean> {
246
+ async runAfterPrerender(prerenderDir?: string): Promise<boolean> {
180
247
  let ran = false
181
248
  for (const plugin of plugins) {
182
249
  if (plugin.afterPrerender !== undefined) {
183
250
  ran = true
184
- const ctx: FinalizeBuildContext = { ...shared, publicFiles: options.publicFiles.files, setData: setDataFor(plugin) }
251
+ const ctx: FinalizeBuildContext = {
252
+ ...shared,
253
+ ...emittersFor(plugin),
254
+ ...(prerenderDir !== undefined ? { prerenderDir } : {}),
255
+ publicFiles: options.publicFiles.files,
256
+ assets,
257
+ setData: setDataFor(plugin),
258
+ }
185
259
  await runPluginHook(plugin, 'afterPrerender', () => plugin.afterPrerender!(ctx))
186
260
  }
187
261
  }
@@ -2,7 +2,7 @@
2
2
 
3
3
  import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, utimesSync, writeFileSync } from 'node:fs'
4
4
  import { availableParallelism } from 'node:os'
5
- import { dirname, extname, join } from 'node:path'
5
+ import { basename, dirname, extname, join } from 'node:path'
6
6
  import { promisify } from 'node:util'
7
7
  import { brotliCompress, brotliCompressSync, constants as zlibConstants } from 'node:zlib'
8
8
  import { getAppContext } from '../plugins/context'
@@ -10,7 +10,7 @@ import { getAppContext } from '../plugins/context'
10
10
  /** Brotli quality of the sidecars: written once per build, downloaded by every visitor, so the smallest the encoder makes. */
11
11
  export const BROTLI_QUALITY = 11
12
12
 
13
- const COMPRESSIBLE_EXTS = new Set(['.html', '.js', '.mjs', '.css', '.svg', '.xml', '.json', '.txt', '.webmanifest', '.wasm'])
13
+ export const COMPRESSIBLE_EXTS = new Set(['.html', '.js', '.mjs', '.css', '.svg', '.xml', '.json', '.txt', '.webmanifest', '.wasm', '.ttf', '.otf', '.ico'])
14
14
  const STALE_MS = 7 * 86_400_000
15
15
 
16
16
  const compress = promisify(brotliCompress)
@@ -46,9 +46,22 @@ function readEntry(file: string): Buffer | undefined {
46
46
  }
47
47
  }
48
48
 
49
+ /** Writes a self-ignoring `.gitignore` inside `.prunelle-cache/` so git never lists cached files as untracked (#39). */
50
+ export function ensureCacheGitignore(cacheRoot: string): void {
51
+ const file = join(cacheRoot, '.gitignore')
52
+ if (existsSync(file))
53
+ return
54
+ mkdirSync(cacheRoot, { recursive: true })
55
+ writeFileSync(file, '*\n')
56
+ }
57
+
49
58
  // Renamed into place, so a build running beside this one never reads half an entry.
50
59
  function writeEntry(file: string, packed: Uint8Array): void {
51
- mkdirSync(dirname(file), { recursive: true })
60
+ const dir = dirname(file)
61
+ mkdirSync(dir, { recursive: true })
62
+ const parent = dirname(dir)
63
+ if (basename(parent) === '.prunelle-cache')
64
+ ensureCacheGitignore(parent)
52
65
  const tmp = `${file}.${process.pid}-${tmpCount++}.tmp`
53
66
  writeFileSync(tmp, packed)
54
67
  renameSync(tmp, file)