prunelle 0.0.0-stage → 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 (222) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +245 -0
  3. package/package.json +62 -4
  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/ambient.d.ts +6 -0
  8. package/src/attrs.ts +43 -0
  9. package/src/build/bundle.ts +661 -0
  10. package/src/build/byte-size.ts +11 -0
  11. package/src/build/carry.ts +57 -0
  12. package/src/build/client-entries.ts +107 -0
  13. package/src/build/client-plugin.ts +175 -0
  14. package/src/build/client-prune.ts +168 -0
  15. package/src/build/compile.ts +130 -0
  16. package/src/build/ecoindex.ts +238 -0
  17. package/src/build/files.ts +171 -0
  18. package/src/build/first-load.ts +235 -0
  19. package/src/build/graph.ts +237 -0
  20. package/src/build/index.ts +678 -0
  21. package/src/build/is-inside.ts +12 -0
  22. package/src/build/island-promote.ts +311 -0
  23. package/src/build/islands.ts +452 -0
  24. package/src/build/manifest.ts +204 -0
  25. package/src/build/output.ts +81 -0
  26. package/src/build/plugin-host.ts +294 -0
  27. package/src/build/precompress.ts +139 -0
  28. package/src/build/prerender.ts +288 -0
  29. package/src/build/reach.ts +200 -0
  30. package/src/build/render-rules.ts +205 -0
  31. package/src/build/report.ts +290 -0
  32. package/src/build/resolve.ts +52 -0
  33. package/src/build/routes.ts +342 -0
  34. package/src/build/server-entry.ts +38 -0
  35. package/src/build/static-headers.ts +112 -0
  36. package/src/build/static.ts +209 -0
  37. package/src/build/status-pages.ts +127 -0
  38. package/src/build/style-bundles.ts +526 -0
  39. package/src/cli/check-forms.ts +636 -0
  40. package/src/cli/check-imports.ts +31 -0
  41. package/src/cli/check-links.ts +632 -0
  42. package/src/cli/check-security.ts +64 -0
  43. package/src/cli/check.ts +409 -0
  44. package/src/cli/commands.ts +372 -0
  45. package/src/cli/docs.ts +403 -0
  46. package/src/cli/index.ts +70 -0
  47. package/src/cli/inspect.ts +406 -0
  48. package/src/cli/mcp-tools.ts +492 -0
  49. package/src/cli/mcp.ts +205 -0
  50. package/src/cli/new.ts +52 -0
  51. package/src/cli/render.ts +416 -0
  52. package/src/cli/upgrade-names.ts +209 -0
  53. package/src/cli/upgrade.ts +367 -0
  54. package/src/compiler/analyze.ts +651 -0
  55. package/src/compiler/ast.ts +82 -0
  56. package/src/compiler/browser-globals.ts +250 -0
  57. package/src/compiler/cacheability-private.ts +566 -0
  58. package/src/compiler/cacheability.ts +335 -0
  59. package/src/compiler/compliance-eco.ts +71 -0
  60. package/src/compiler/compliance-rgaa.ts +614 -0
  61. package/src/compiler/compliance-urls.ts +148 -0
  62. package/src/compiler/compliance.ts +653 -0
  63. package/src/compiler/data-keys.ts +302 -0
  64. package/src/compiler/dev-source.ts +87 -0
  65. package/src/compiler/dom-attrs.ts +452 -0
  66. package/src/compiler/dom.ts +641 -0
  67. package/src/compiler/emit.ts +131 -0
  68. package/src/compiler/expr-context.ts +587 -0
  69. package/src/compiler/foreign-imports.ts +88 -0
  70. package/src/compiler/index.ts +8 -0
  71. package/src/compiler/interactivity.ts +366 -0
  72. package/src/compiler/mistakes.ts +520 -0
  73. package/src/compiler/node-env.ts +50 -0
  74. package/src/compiler/patch.ts +97 -0
  75. package/src/compiler/props-body.ts +60 -0
  76. package/src/compiler/props.ts +511 -0
  77. package/src/compiler/scope.ts +635 -0
  78. package/src/compiler/server-only.ts +365 -0
  79. package/src/compiler/shared.ts +397 -0
  80. package/src/compiler/signal-reads.ts +246 -0
  81. package/src/compiler/slots.ts +227 -0
  82. package/src/compiler/spread-handlers.ts +295 -0
  83. package/src/compiler/ssr-helpers.ts +555 -0
  84. package/src/compiler/ssr-island.ts +90 -0
  85. package/src/compiler/ssr-prunelle-tags.ts +69 -0
  86. package/src/compiler/ssr.ts +525 -0
  87. package/src/context.ts +199 -0
  88. package/src/dev/child.ts +30 -0
  89. package/src/dev/error-log.ts +177 -0
  90. package/src/dev/host-check.ts +32 -0
  91. package/src/dev/index.ts +268 -0
  92. package/src/dev/modules.ts +68 -0
  93. package/src/dev/open-editor.ts +228 -0
  94. package/src/dev/protocol.ts +24 -0
  95. package/src/dev/queue.ts +79 -0
  96. package/src/dev/reload.ts +159 -0
  97. package/src/dev/supervisor.ts +212 -0
  98. package/src/dev/watchers.ts +276 -0
  99. package/src/dom/action.ts +187 -0
  100. package/src/dom/attrs.ts +84 -0
  101. package/src/dom/claim.ts +120 -0
  102. package/src/dom/extras.ts +579 -0
  103. package/src/dom/index.ts +329 -0
  104. package/src/dom/island.ts +318 -0
  105. package/src/dom/loop.ts +484 -0
  106. package/src/dom/revive.ts +36 -0
  107. package/src/eco/declaration.ts +328 -0
  108. package/src/eco/index.ts +69 -0
  109. package/src/index.ts +22 -0
  110. package/src/jsx-runtime.ts +566 -0
  111. package/src/plugins/config.ts +92 -0
  112. package/src/plugins/context.ts +109 -0
  113. package/src/plugins/index.ts +14 -0
  114. package/src/plugins/load.ts +90 -0
  115. package/src/plugins/order.ts +148 -0
  116. package/src/plugins/public.ts +15 -0
  117. package/src/plugins/requires.ts +47 -0
  118. package/src/plugins/services.ts +119 -0
  119. package/src/plugins/types.ts +278 -0
  120. package/src/reactivity/graph.ts +259 -0
  121. package/src/reactivity/index.ts +541 -0
  122. package/src/reactivity/selector.ts +78 -0
  123. package/src/reactivity/store.ts +252 -0
  124. package/src/server/action-flash.ts +158 -0
  125. package/src/server/action-protect.ts +199 -0
  126. package/src/server/action-registry.ts +78 -0
  127. package/src/server/action.ts +511 -0
  128. package/src/server/app-entry.ts +23 -0
  129. package/src/server/app-secret.ts +63 -0
  130. package/src/server/assets.ts +168 -0
  131. package/src/server/compress.ts +646 -0
  132. package/src/server/consent.ts +290 -0
  133. package/src/server/cookies.ts +153 -0
  134. package/src/server/document.ts +286 -0
  135. package/src/server/env.ts +47 -0
  136. package/src/server/errors.ts +396 -0
  137. package/src/server/form-schema.ts +337 -0
  138. package/src/server/health.ts +275 -0
  139. package/src/server/http.ts +588 -0
  140. package/src/server/index.ts +615 -0
  141. package/src/server/lifecycle.ts +75 -0
  142. package/src/server/loader.ts +131 -0
  143. package/src/server/page.ts +122 -0
  144. package/src/server/param-matchers.ts +112 -0
  145. package/src/server/plugin-host.ts +267 -0
  146. package/src/server/prerendered.ts +71 -0
  147. package/src/server/public.ts +20 -0
  148. package/src/server/rate-limit.ts +199 -0
  149. package/src/server/region.ts +96 -0
  150. package/src/server/request-body.ts +27 -0
  151. package/src/server/request-path.ts +73 -0
  152. package/src/server/request-scope.ts +22 -0
  153. package/src/server/route-cache.ts +541 -0
  154. package/src/server/route-table.ts +424 -0
  155. package/src/server/router.ts +261 -0
  156. package/src/server/routing.ts +388 -0
  157. package/src/server/sanitize-html.ts +309 -0
  158. package/src/server/security.ts +550 -0
  159. package/src/server/serve-handlers.ts +93 -0
  160. package/src/server/served-file.ts +128 -0
  161. package/src/server/standard-schema.ts +104 -0
  162. package/src/server/start.ts +143 -0
  163. package/src/server/static-dir.ts +246 -0
  164. package/src/server/stream.ts +233 -0
  165. package/src/ssr/consent-banner.ts +58 -0
  166. package/src/ssr/context.ts +399 -0
  167. package/src/ssr/index.ts +624 -0
  168. package/src/ssr/navigation.ts +96 -0
  169. package/src/ssr/region.ts +192 -0
  170. package/src/style.ts +96 -0
  171. package/src/test/browser.ts +201 -0
  172. package/src/test/index.ts +262 -0
  173. package/src/ts-plugin/diagnostics.ts +505 -0
  174. package/src/ts-plugin/fixes.ts +364 -0
  175. package/src/ts-plugin/index.ts +194 -0
  176. package/src/unrenderable.ts +35 -0
  177. package/templates/_shared/AGENTS.md +10 -0
  178. package/templates/_shared/CLAUDE.md +1 -0
  179. package/templates/_shared/gitignore +8 -0
  180. package/templates/_shared/mcp.json +11 -0
  181. package/templates/_shared/public/robots.txt +2 -0
  182. package/templates/_shared/src/routes/legal.tsx +22 -0
  183. package/templates/_shared/tsconfig.json +25 -0
  184. package/templates/app/.env.example +8 -0
  185. package/templates/app/package.json +22 -0
  186. package/templates/app/prunelle.config.ts +13 -0
  187. package/templates/app/src/auth.ts +12 -0
  188. package/templates/app/src/mail.ts +4 -0
  189. package/templates/app/src/routes/_layout.tsx +40 -0
  190. package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
  191. package/templates/app/src/routes/dashboard/index.tsx +47 -0
  192. package/templates/app/src/routes/index.tsx +15 -0
  193. package/templates/app/src/routes/login.tsx +53 -0
  194. package/templates/app/src/routes/privacy.tsx +25 -0
  195. package/templates/app/src/styles/app.css +14 -0
  196. package/templates/app/tests/app.test.ts +73 -0
  197. package/templates/blog/content/posts/welcome.md +9 -0
  198. package/templates/blog/package.json +22 -0
  199. package/templates/blog/prunelle.config.ts +23 -0
  200. package/templates/blog/src/posts.ts +26 -0
  201. package/templates/blog/src/routes/_layout.tsx +25 -0
  202. package/templates/blog/src/routes/blog/[slug].tsx +31 -0
  203. package/templates/blog/src/routes/index.tsx +33 -0
  204. package/templates/blog/src/styles/app.css +15 -0
  205. package/templates/fullstack/package.json +19 -0
  206. package/templates/fullstack/prunelle.config.ts +6 -0
  207. package/templates/fullstack/src/actions/greet.ts +19 -0
  208. package/templates/fullstack/src/components/Counter.tsx +10 -0
  209. package/templates/fullstack/src/components/GreetForm.tsx +28 -0
  210. package/templates/fullstack/src/routes/_layout.tsx +18 -0
  211. package/templates/fullstack/src/routes/api/health.ts +5 -0
  212. package/templates/fullstack/src/routes/index.tsx +13 -0
  213. package/templates/fullstack/src/styles/app.css +39 -0
  214. package/templates/fullstack/tests/app.test.ts +37 -0
  215. package/templates/minimal/package.json +19 -0
  216. package/templates/minimal/prunelle.config.ts +6 -0
  217. package/templates/minimal/src/components/Counter.tsx +10 -0
  218. package/templates/minimal/src/routes/_layout.tsx +18 -0
  219. package/templates/minimal/src/routes/index.tsx +11 -0
  220. package/templates/minimal/src/styles/app.css +32 -0
  221. package/ts-plugin.cjs +4277 -0
  222. package/README.md +0 -3
@@ -0,0 +1,288 @@
1
+ // Build-time rendering: routes exporting `prerender = true` (and every route in a static export) are rendered through the real server and written as HTML.
2
+
3
+ import type { PrunellePlugin } from '../plugins/index'
4
+ import type { RouteManifestEntry } from './manifest'
5
+ import { existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'
6
+ import { dirname, extname, join, resolve } from 'node:path'
7
+ import { FORM_TIMESTAMP_FIELD } from '../server/action-protect'
8
+ import { prerenderOrigin } from '../server/prerendered'
9
+ import { decodeRequestPath } from '../server/request-path'
10
+ import { inlineStyleHashes, injectMetaCsp } from '../server/security'
11
+ import { relPosix } from './files'
12
+ import { runPluginHook } from './plugin-host'
13
+ import { assertPathUrls } from './routes'
14
+
15
+ const CONCURRENCY = 8
16
+ const SLASH_EDGES_RE = /^\/|\/$/g
17
+ const TRAILING_SLASHES_RE = /\/+$/
18
+
19
+ const CONTENT_TYPE_EXT: Record<string, string> = {
20
+ 'application/json': '.json',
21
+ 'application/xml': '.xml',
22
+ 'text/xml': '.xml',
23
+ 'application/rss+xml': '.rss',
24
+ 'application/atom+xml': '.atom',
25
+ 'text/plain': '.txt',
26
+ 'image/svg+xml': '.svg',
27
+ 'text/calendar': '.ics',
28
+ 'text/csv': '.csv',
29
+ }
30
+
31
+ function extForContentType(contentType: string | null): string {
32
+ if (contentType === null)
33
+ return ''
34
+ const semi = contentType.indexOf(';')
35
+ const mime = (semi === -1 ? contentType : contentType.slice(0, semi)).trim().toLowerCase()
36
+ return CONTENT_TYPE_EXT[mime] ?? ''
37
+ }
38
+
39
+ function assertSafePrerenderPath(raw: string, original: string): string {
40
+ const decoded = decodeRequestPath(raw)
41
+ if (decoded?.staticPath === undefined)
42
+ throw new Error(`prunelle build: unsafe or malformed prerender path "${original}".`)
43
+ if (decoded.staticPath.split('/').some(seg => seg === '..' || seg.includes('\\') || seg.includes('\0')))
44
+ throw new Error(`prunelle build: prerender path "${original}" escapes output directory.`)
45
+ return decoded.staticPath
46
+ }
47
+
48
+ function normalizePrerenderUrl(urlStr: string): string {
49
+ assertSafePrerenderPath(urlStr.split(/[?#]/, 1)[0] ?? '', urlStr)
50
+ let pathname: string
51
+ try {
52
+ pathname = new URL(urlStr, 'http://localhost').pathname
53
+ }
54
+ catch {
55
+ throw new Error(`prunelle build: invalid prerender path "${urlStr}".`)
56
+ }
57
+ const staticPath = assertSafePrerenderPath(pathname, urlStr)
58
+ return staticPath.length > 1 && staticPath.endsWith('/') ? (staticPath.replace(TRAILING_SLASHES_RE, '') || '/') : staticPath
59
+ }
60
+
61
+ function encodeUrlPath(pathname: string): string {
62
+ return pathname.split('/').map(encodeURIComponent).join('/')
63
+ }
64
+
65
+ function resolvePrerenderPath(prerenderDir: string, pathname: string, isStatic: boolean, contentType: string | null): string {
66
+ const trimmed = pathname.replace(SLASH_EDGES_RE, '')
67
+ if (trimmed.split('/').some(seg => seg === '..' || seg.includes('\\') || seg.includes('\0')))
68
+ throw new Error(`prunelle build: prerender path "${pathname}" escapes output directory.`)
69
+ const lastSeg = trimmed.slice(trimmed.lastIndexOf('/') + 1)
70
+ const ext = extname(lastSeg).toLowerCase()
71
+ const isHtml = (contentType ?? '').toLowerCase().includes('text/html')
72
+ const inferredExt = !isStatic && !isHtml && ext === '' ? extForContentType(contentType) : ''
73
+ const preserveFile = ext !== '' && (ext === '.html' || ext === '.htm' || !isHtml)
74
+ const rel = pathname === '/'
75
+ ? 'index.html'
76
+ : (isStatic && pathname === '/404')
77
+ ? '404.html'
78
+ : preserveFile
79
+ ? trimmed
80
+ : inferredExt !== ''
81
+ ? `${trimmed}${inferredExt}`
82
+ : `${trimmed}/index.html`
83
+ const absRoot = resolve(prerenderDir)
84
+ const abs = resolve(absRoot, rel)
85
+ if (!abs.startsWith(`${absRoot}/`) && !abs.startsWith(`${absRoot}\\`))
86
+ throw new Error(`prunelle build: prerender path "${pathname}" escapes output directory.`)
87
+ return abs
88
+ }
89
+
90
+ export interface PrerenderOptions {
91
+ root: string
92
+ outDir: string
93
+ assetPrefix: string
94
+ site?: string | undefined
95
+ plugins: PrunellePlugin[]
96
+ /** Plugins passed to `build()` itself, which the app runs with in place of its bundled config's. */
97
+ pluginOverride?: PrunellePlugin[] | undefined
98
+ isDev: boolean
99
+ nodeEnv?: string | undefined
100
+ isStatic: boolean
101
+ /** Where the HTML lands: the static stage dir, or `<outDir>/prerendered`. */
102
+ prerenderDir: string
103
+ routes: RouteManifestEntry[]
104
+ /** The app's routes folder, to name a route's source file in messages. */
105
+ routesDir: string
106
+ }
107
+
108
+ const ROUTE_SOURCE_EXTENSIONS = ['.tsx', '.ts', '.jsx', '.js', '.mdx', '.md']
109
+
110
+ // The source file of a built route module (`server/posts/[slug].js` is `src/routes/posts/[slug].tsx`), as messages name it.
111
+ function routeSource(options: PrerenderOptions, route: RouteManifestEntry): string {
112
+ const stem = join(options.routesDir, route.file.replace(/^server\//, '').replace(/\.js$/, ''))
113
+ const source = ROUTE_SOURCE_EXTENSIONS.map(ext => `${stem}${ext}`).find(file => existsSync(file))
114
+ return source === undefined ? route.file : relPosix(options.root, source)
115
+ }
116
+
117
+ // The build fails through the CLI, which prints only the message: the page's own error and its stack go in it.
118
+ export function pageFailure(head: string, error: unknown): Error {
119
+ if (error === undefined)
120
+ return new Error(`${head}.`)
121
+ if (!(error instanceof Error))
122
+ return new Error(`${head}: ${String(error)}`, { cause: error })
123
+ const title = `${error.name}: ${error.message}`
124
+ const stack = error.stack ?? ''
125
+ const frames = stack.startsWith(title) ? stack.slice(title.length) : `\n${stack}`
126
+ return new Error(`${head}: ${error.message}${frames}`, { cause: error })
127
+ }
128
+
129
+ const TIMESTAMP_INPUT = `name="${FORM_TIMESTAMP_FIELD}"`
130
+
131
+ interface RenderTask {
132
+ route: RouteManifestEntry
133
+ url: string
134
+ relOut?: string | undefined
135
+ hashes?: string[] | undefined
136
+ /** The page holds a `protect.minTime` form, whose token must be signed per request. */
137
+ signsTimestamp?: boolean | undefined
138
+ }
139
+
140
+ // A route's paths(), whose throw names the route it came from.
141
+ async function namedPathsError(route: RouteManifestEntry, source: string, paths: () => Promise<string[]> | string[]): Promise<unknown> {
142
+ try {
143
+ return await paths()
144
+ }
145
+ catch (error) {
146
+ throw new Error(`prunelle build: paths() of "${route.path}" (${source}) threw: ${error instanceof Error ? error.message : String(error)}`, { cause: error })
147
+ }
148
+ }
149
+
150
+ /** The URLs to render for each route: its own path, or what its `paths()` and the plugins' `prerenderPaths` return. */
151
+ async function planRoutes(options: PrerenderOptions, modules: Record<string, unknown> | undefined): Promise<{ route: RouteManifestEntry, tasks: RenderTask[] }[]> {
152
+ const routePlans: { route: RouteManifestEntry, tasks: RenderTask[] }[] = []
153
+ for (const route of options.routes) {
154
+ let urls: string[] = []
155
+ let hasPathsFn = false
156
+ if (!route.path.includes(':') && !route.path.includes('*')) {
157
+ urls = [route.path]
158
+ }
159
+ else {
160
+ const mod = modules?.[route.file] as { paths?: () => Promise<string[]> | string[] } | undefined ?? {}
161
+ if (typeof mod.paths === 'function') {
162
+ hasPathsFn = true
163
+ const source = routeSource(options, route)
164
+ const returned: unknown = await namedPathsError(route, source, mod.paths)
165
+ assertPathUrls(returned, source)
166
+ urls = returned
167
+ }
168
+ else {
169
+ console.warn(`prunelle build${options.isStatic ? ' --static' : ''}: skipping dynamic route "${route.path}" (${routeSource(options, route)}) because it does not export a paths() function.`)
170
+ }
171
+ }
172
+
173
+ for (const plugin of options.plugins) {
174
+ if (plugin.prerenderPaths !== undefined && (urls.length > 0 || hasPathsFn))
175
+ urls = await runPluginHook(plugin, 'prerenderPaths', () => plugin.prerenderPaths!(urls, route))
176
+ }
177
+
178
+ urls = [...new Set(urls.map(normalizePrerenderUrl))]
179
+
180
+ if (urls.length === 0) {
181
+ if (hasPathsFn)
182
+ route.prerendered = {}
183
+ continue
184
+ }
185
+
186
+ routePlans.push({ route, tasks: urls.map(url => ({ route, url })) })
187
+ }
188
+ return routePlans
189
+ }
190
+
191
+ /** Renders every route to HTML, records `route.prerendered`, and returns the server and entry the pages were rendered with. */
192
+ export async function prerender(options: PrerenderOptions) {
193
+ const { root, outDir, prerenderDir, isStatic } = options
194
+ // Pages render with the runtime's own plugin instances, from the bundled config; `options.plugins` are the build's native ones.
195
+ const { startBuiltApp } = await import('../server/loader')
196
+ const pageErrors = new Map<string, unknown>()
197
+ const errorSink = ({ error, request }: { error: unknown, request: Request }): void => {
198
+ if (!pageErrors.has(request.url))
199
+ pageErrors.set(request.url, error)
200
+ }
201
+ const { app, entry } = await startBuiltApp({ root, outDir: relPosix(root, outDir), assetPrefix: options.assetPrefix, site: options.site, plugins: options.pluginOverride, dev: options.isDev, nodeEnv: options.nodeEnv, errorSink, prerender: true, static: isStatic })
202
+ const origin = prerenderOrigin(options.site)
203
+ mkdirSync(prerenderDir, { recursive: true })
204
+
205
+ try {
206
+ const routePlans = await planRoutes(options, entry?.modules)
207
+ const allTasks = routePlans.flatMap(plan => plan.tasks)
208
+ let nextIdx = 0
209
+ let failed = false
210
+ const runWorker = async (): Promise<void> => {
211
+ while (!failed) {
212
+ const idx = nextIdx++
213
+ if (idx >= allTasks.length)
214
+ return
215
+ const task = allTasks[idx]!
216
+ const u = task.url
217
+ const request = new Request(`${origin}${encodeUrlPath(u)}`)
218
+ const res = await app.handle(request)
219
+ const isExplicit404 = u === '/404' && res.status === 404
220
+ if (res.status !== 200 && !isExplicit404) {
221
+ if (isStatic || res.status >= 500) {
222
+ failed = true
223
+ throw pageFailure(`prunelle build: prerender route "${u}" answered HTTP ${res.status}`, pageErrors.get(request.url))
224
+ }
225
+ // A page prunelle chose to prerender by itself falls back to request time quietly; one the app asked for is told.
226
+ if (task.route.autoPrerender !== true) {
227
+ const isStaticRoute = !task.route.path.includes(':') && !task.route.path.includes('*')
228
+ console.warn(`prunelle build: prerender route "${u}" (${routeSource(options, task.route)}) answered HTTP ${res.status}, ${isStaticRoute ? 'so it renders at request time instead: drop `prerender = true`' : 'so it is not prerendered and answers 404 in production: leave it out of paths()'}, or have it answer 200.`)
229
+ }
230
+ continue
231
+ }
232
+ const ct = res.headers.get('content-type')
233
+ const absOut = resolvePrerenderPath(prerenderDir, u, isStatic, ct)
234
+ mkdirSync(dirname(absOut), { recursive: true })
235
+ if ((ct ?? '').toLowerCase().includes('text/html')) {
236
+ const html = await res.text()
237
+ if (html.includes(TIMESTAMP_INPUT)) {
238
+ if (task.route.autoPrerender === true) {
239
+ task.signsTimestamp = true
240
+ continue
241
+ }
242
+ failed = true
243
+ throw new Error(`prunelle build${isStatic ? ' --static' : ''}: "${u}" renders a form whose action uses protect.minTime, so its signed timestamp would be fixed at build time: every submit is refused 24 h later and bots pass minTime at once. Serve the page from the server${isStatic ? ' instead of a static export' : ' (drop prerender = true)'}, or drop minTime and keep honeypot and rateLimit.`)
244
+ }
245
+ writeFileSync(absOut, isStatic ? injectMetaCsp(html, res.headers.get('content-security-policy')) : html)
246
+ const hashes = inlineStyleHashes(html)
247
+ if (hashes.length > 0)
248
+ task.hashes = hashes
249
+ }
250
+ else {
251
+ writeFileSync(absOut, new Uint8Array(await res.arrayBuffer()))
252
+ }
253
+ task.relOut = relPosix(isStatic ? prerenderDir : outDir, absOut)
254
+ }
255
+ }
256
+
257
+ const workers = Math.min(CONCURRENCY, allTasks.length)
258
+ await Promise.all(Array.from({ length: workers }, () => runWorker()))
259
+
260
+ for (const { route, tasks } of routePlans) {
261
+ if (tasks.some(task => task.signsTimestamp === true)) {
262
+ // A protect.minTime form signs its timestamp on each request: the whole route renders at request time.
263
+ for (const task of tasks) {
264
+ if (task.relOut !== undefined)
265
+ rmSync(join(outDir, task.relOut), { force: true })
266
+ }
267
+ route.prerender = false
268
+ route.autoPrerender = undefined
269
+ continue
270
+ }
271
+ const map: Record<string, string> = {}
272
+ const styleHashes: Record<string, string[]> = {}
273
+ for (const task of tasks) {
274
+ if (task.relOut !== undefined)
275
+ map[task.url] = task.relOut
276
+ if (task.hashes !== undefined)
277
+ styleHashes[task.url] = task.hashes
278
+ }
279
+ route.prerendered = map
280
+ route.prerenderedStyleHashes = Object.keys(styleHashes).length > 0 ? styleHashes : undefined
281
+ }
282
+ }
283
+ catch (err) {
284
+ await app.dispose?.()
285
+ throw err
286
+ }
287
+ return { app, entry, errorFor: (url: string) => pageErrors.get(url) }
288
+ }
@@ -0,0 +1,200 @@
1
+ // What a page reaches through its imports and the islands it renders: island chunks, stylesheets, files, render-context and region use.
2
+
3
+ import type { ModuleAnalysis } from '../compiler/index'
4
+ import type { ModuleGraph } from './graph'
5
+ import type { IslandPlan, IslandTarget } from './islands'
6
+ import { islandKey } from './islands'
7
+
8
+ const REGION_SOURCES = new Set(['prunelle', 'prunelle/internal/ssr'])
9
+
10
+ interface ModuleEdge {
11
+ source: string
12
+ specifiers?: readonly { local: string, imported: string }[] | undefined
13
+ start: number
14
+ }
15
+
16
+ function orderedEdges(analysis: ModuleAnalysis): readonly ModuleEdge[] {
17
+ const reexports = analysis.reexports
18
+ if (reexports === undefined || reexports.length === 0)
19
+ return analysis.imports
20
+ return [...analysis.imports, ...reexports].sort((a, b) => a.start - b.start)
21
+ }
22
+
23
+ function edgeBindings(edge: ModuleEdge, bindings: ReadonlyMap<string, IslandTarget> | undefined): IslandTarget[] {
24
+ if (bindings === undefined || edge.specifiers === undefined)
25
+ return []
26
+ const matched: IslandTarget[] = []
27
+ for (const spec of edge.specifiers) {
28
+ if (spec.imported === '*') {
29
+ const prefix = `${spec.local}.`
30
+ for (const [tag, target] of bindings) {
31
+ if (tag.startsWith(prefix))
32
+ matched.push(target)
33
+ }
34
+ }
35
+ else {
36
+ const target = bindings.get(spec.local)
37
+ if (target !== undefined)
38
+ matched.push(target)
39
+ }
40
+ }
41
+ return matched
42
+ }
43
+
44
+ export interface FileReach {
45
+ /** Island chunks reachable from the file, and the subset loaded eagerly. */
46
+ chunks: Set<string>
47
+ eager: Set<string>
48
+ styles: Set<string>
49
+ /** All reachable source files (`.ts`/`.tsx`) walked from this file. */
50
+ files: Set<string>
51
+ usesRenderContext: boolean
52
+ usesRegion: boolean
53
+ }
54
+
55
+ // How far a visit reaches. Level 0 follows imports, stopping at an island that renders nothing static (its imports ship inside it): island chunks.
56
+ // Level 1 follows every import: render-context and region use. Level 2 also follows the islands a module renders: files and styles.
57
+ // Each level reaches a superset of the one before, so a visit at a level also counts for the levels after it.
58
+ const ISLANDS = 0
59
+ const IMPORTS = 1
60
+ const RENDERED = 2
61
+
62
+ /** Walks what a module renders and imports to find the island chunks, stylesheets and render-context use behind it, in one pass per page. */
63
+ export function createReachWalker(graph: ModuleGraph, islands: IslandPlan, islandChunks: Map<string, string>, srcCssToUrl: Map<string, string>, islandCssUrl: Map<string, string>) {
64
+ const { analyses } = graph
65
+ const depsMemo = new Map<string, string[]>()
66
+ const depsOf = (file: string): string[] => {
67
+ let deps = depsMemo.get(file)
68
+ if (deps === undefined) {
69
+ deps = graph.localDeps(file)
70
+ depsMemo.set(file, deps)
71
+ }
72
+ return deps
73
+ }
74
+
75
+ /** Adds the island chunks of a file reached at level 0; true when its imports ship inside the island and the level stops there. */
76
+ function addIslandChunks(file: string, isRoot: boolean, analysis: ModuleAnalysis, reach: FileReach): boolean {
77
+ if (analysis.isInteractive) {
78
+ if (isRoot) {
79
+ const chunk = islandChunks.get(`${file}#default`)
80
+ if (chunk !== undefined) {
81
+ reach.chunks.add(chunk)
82
+ if (analysis.defaultHydrate === undefined || analysis.defaultHydrate === 'load')
83
+ reach.eager.add(chunk)
84
+ }
85
+ }
86
+ // Imports rendered only inside the module's islands ship within them; a static component beside an island renders its own.
87
+ if (analysis.staticJsxTags.size === 0)
88
+ return true
89
+ }
90
+ for (const [localName, target] of islands.pageBindings.get(file) ?? []) {
91
+ const chunk = islandChunks.get(islandKey(target))
92
+ if (chunk === undefined)
93
+ continue
94
+ reach.chunks.add(chunk)
95
+ const isDeferred = analysis.deferredIslandTags.has(localName)
96
+ || (target.defaultHydrate !== undefined && target.defaultHydrate !== 'load')
97
+ if (!isDeferred)
98
+ reach.eager.add(chunk)
99
+ }
100
+ return false
101
+ }
102
+
103
+ function walk(root: string): FileReach {
104
+ const reach: FileReach = { chunks: new Set(), eager: new Set(), styles: new Set(), files: new Set(), usesRenderContext: false, usesRegion: false }
105
+ const seen = [new Set<string>(), new Set<string>(), new Set<string>()]
106
+
107
+ function visit(file: string, level: number): void {
108
+ const atIslands = level === ISLANDS && !seen[ISLANDS]!.has(file)
109
+ const atImports = level <= IMPORTS && !seen[IMPORTS]!.has(file)
110
+ const atRendered = !seen[RENDERED]!.has(file)
111
+ if (!atIslands && !atImports && !atRendered)
112
+ return
113
+ if (atIslands)
114
+ seen[ISLANDS]!.add(file)
115
+ if (atImports)
116
+ seen[IMPORTS]!.add(file)
117
+ if (atRendered)
118
+ seen[RENDERED]!.add(file)
119
+ const analysis = analyses.get(file)
120
+ if (atRendered)
121
+ reach.files.add(file)
122
+ if (analysis === undefined)
123
+ return
124
+
125
+ let pruned = false
126
+ if (atIslands)
127
+ pruned = addIslandChunks(file, file === root, analysis, reach)
128
+ if (atImports && !reach.usesRenderContext && analysis.usesRenderContext)
129
+ reach.usesRenderContext = true
130
+ if (atImports && !reach.usesRegion && analysis.imports.some(imp => REGION_SOURCES.has(imp.source) && imp.specifiers.some(s => s.imported === 'Region' || s.imported === '*')))
131
+ reach.usesRegion = true
132
+
133
+ // The imports follow at the lowest level this visit newly covers; a pruned island's imports are still walked for the levels after it.
134
+ const next = atIslands ? (pruned ? IMPORTS : ISLANDS) : atImports ? IMPORTS : RENDERED
135
+ const deps = depsOf(file)
136
+ if (!atRendered) {
137
+ for (const dep of deps)
138
+ visit(dep, next)
139
+ return
140
+ }
141
+
142
+ const depSet = new Set(deps)
143
+ const visitedDeps = new Set<string>()
144
+ const bindings = islands.pageBindings.get(file)
145
+ const visitedBindings = new Set<IslandTarget>()
146
+ const addTargetStyle = (target: IslandTarget): void => {
147
+ if (visitedBindings.has(target))
148
+ return
149
+ visitedBindings.add(target)
150
+ visit(target.file, RENDERED)
151
+ const islCss = islandCssUrl.get(islandKey(target))
152
+ if (islCss !== undefined)
153
+ reach.styles.add(islCss)
154
+ }
155
+
156
+ // Walk imports and re-exports in source order so dependency CSS lands before the importer's CSS (#159).
157
+ for (const edge of orderedEdges(analysis)) {
158
+ const resolved = graph.resolve(file, edge.source)
159
+ if (resolved === undefined)
160
+ continue
161
+ const cssUrl = srcCssToUrl.get(resolved)
162
+ if (cssUrl !== undefined) {
163
+ reach.styles.add(cssUrl)
164
+ continue
165
+ }
166
+ if (depSet.has(resolved)) {
167
+ visitedDeps.add(resolved)
168
+ visit(resolved, next)
169
+ }
170
+ for (const target of edgeBindings(edge, bindings))
171
+ addTargetStyle(target)
172
+ }
173
+ for (const dep of deps) {
174
+ if (!visitedDeps.has(dep))
175
+ visit(dep, next)
176
+ }
177
+ for (const target of bindings?.values() ?? [])
178
+ addTargetStyle(target)
179
+ if (file === root && analysis.isInteractive) {
180
+ const islCss = islandCssUrl.get(`${file}#default`)
181
+ if (islCss !== undefined)
182
+ reach.styles.add(islCss)
183
+ }
184
+ }
185
+
186
+ visit(root, ISLANDS)
187
+ return reach
188
+ }
189
+
190
+ // Layouts are shared by many routes, so each file is walked once.
191
+ const memo = new Map<string, FileReach>()
192
+ return (file: string): FileReach => {
193
+ let reach = memo.get(file)
194
+ if (reach === undefined) {
195
+ reach = walk(file)
196
+ memo.set(file, reach)
197
+ }
198
+ return reach
199
+ }
200
+ }