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,247 @@
1
+ // The `--analyze` report and the `--max-js` budget: eager JS and CSS weight per route, from the manifest and the client metafile (or the chunks' own imports), and the islands behind it.
2
+
3
+ import type { ModuleGraph } from './graph'
4
+ import type { IslandPlan } from './islands'
5
+ import type { BuildManifest } from './manifest'
6
+ import { existsSync, readFileSync } from 'node:fs'
7
+ import { join, posix } from 'node:path'
8
+ import { relPosix } from './files'
9
+ import { distLocator, firstLoadUrls, measureFirstLoad, STATIC_CHUNK_IMPORT_RE } from './first-load'
10
+
11
+ export interface IslandOrigin {
12
+ /** The component's export name, `default` for a page or a default export. */
13
+ name: string
14
+ /** Root-relative source file. */
15
+ file: string
16
+ /** Why prunelle runs it in the browser, e.g. `uses onClick`. */
17
+ reason: string
18
+ }
19
+
20
+ export interface RouteIsland extends IslandOrigin {
21
+ /** Loaded with the page, so counted in the route's eager JS. */
22
+ eager: boolean
23
+ }
24
+
25
+ export interface RouteBundleMetrics {
26
+ path: string
27
+ jsRaw: number
28
+ jsGzip: number
29
+ cssRaw: number
30
+ cssGzip: number
31
+ jsFiles: number
32
+ cssFiles: number
33
+ /** Fonts the page preloads or its stylesheets declare, brotli. */
34
+ fonts: number
35
+ /** Everything a first visit fetches except the HTML (CSS, eager JS and its imports, fonts, images, icons), brotli. */
36
+ firstLoad: number
37
+ islands: RouteIsland[]
38
+ }
39
+
40
+ export interface BundleReport {
41
+ routes: RouteBundleMetrics[]
42
+ totalJsGzip: number
43
+ totalCssGzip: number
44
+ topModules: { path: string, bytes: number }[]
45
+ }
46
+
47
+ /** Each island chunk URL, mapped to the component it hydrates and why that component became an island. */
48
+ export function islandOrigins(islands: IslandPlan, islandChunks: Map<string, string>, graph: ModuleGraph, root: string): Map<string, IslandOrigin> {
49
+ const origins = new Map<string, IslandOrigin>()
50
+ for (const [key, target] of islands.targets) {
51
+ const url = islandChunks.get(key)
52
+ if (url === undefined)
53
+ continue
54
+ const analysis = graph.load(target.file)
55
+ const reason = target.local === undefined ? analysis.exports.get(target.exportName)?.reason : analysis.localIslands.get(target.local)?.reason
56
+ origins.set(url, { name: target.local ?? target.exportName, file: relPosix(root, target.file), reason: reason ?? 'is interactive' })
57
+ }
58
+ return origins
59
+ }
60
+
61
+ export function analyzeBundleWeights(
62
+ manifest: BuildManifest,
63
+ clientDir: string,
64
+ assetPrefix = '/_pru',
65
+ metafile?: Bun.BuildOutput['metafile'],
66
+ origins = new Map<string, IslandOrigin>(),
67
+ publicDirs: readonly string[] = [],
68
+ ): BundleReport {
69
+ const locate = distLocator({ clientDir, assetPrefix, publicDirs })
70
+ const prefix = `${assetPrefix.replace(/\/$/, '')}/`
71
+ const sizeCache = new Map<string, { raw: number, gzip: number }>()
72
+
73
+ const getSize = (url: string): { raw: number, gzip: number } => {
74
+ const cached = sizeCache.get(url)
75
+ if (cached !== undefined)
76
+ return cached
77
+ if (!url.startsWith(prefix))
78
+ return { raw: 0, gzip: 0 }
79
+ const abs = join(clientDir, url.slice(prefix.length))
80
+ if (!existsSync(abs))
81
+ return { raw: 0, gzip: 0 }
82
+ const buf = readFileSync(abs)
83
+ const entry = { raw: buf.byteLength, gzip: Bun.gzipSync(buf, { level: 9 }).byteLength }
84
+ sizeCache.set(url, entry)
85
+ return entry
86
+ }
87
+
88
+ // Collect transitive JS chunk imports from metafile so eager JS includes shared runtime chunks!
89
+ const jsDeps = new Map<string, string[]>()
90
+ const moduleBytes = new Map<string, number>()
91
+ if (metafile !== undefined) {
92
+ for (const [outKey, info] of Object.entries(metafile.outputs)) {
93
+ const rel = outKey.replace(/^\.\//, '')
94
+ const url = `${prefix}${rel}`
95
+ if (rel.endsWith('.js')) {
96
+ const deps: string[] = []
97
+ for (const imp of info.imports ?? []) {
98
+ if (imp.kind === 'import-statement')
99
+ deps.push(`${prefix}${imp.path.replace(/^\.\//, '')}`)
100
+ }
101
+ jsDeps.set(url, deps)
102
+ }
103
+ for (const [inPath, inInfo] of Object.entries(info.inputs ?? {}))
104
+ moduleBytes.set(inPath, (moduleBytes.get(inPath) ?? 0) + inInfo.bytesInOutput)
105
+ }
106
+ }
107
+
108
+ // Without the metafile, a chunk's static imports are read from the emitted file itself.
109
+ const depsOf = (url: string): readonly string[] => {
110
+ const known = jsDeps.get(url)
111
+ if (known !== undefined || metafile !== undefined || !url.startsWith(prefix))
112
+ return known ?? []
113
+ const abs = join(clientDir, url.slice(prefix.length))
114
+ const deps = existsSync(abs) ? [...readFileSync(abs, 'utf8').matchAll(STATIC_CHUNK_IMPORT_RE)].map(m => posix.join(posix.dirname(url), m[1]!)) : []
115
+ jsDeps.set(url, deps)
116
+ return deps
117
+ }
118
+
119
+ const collectTransitiveJs = (urls: readonly string[]): Set<string> => {
120
+ const seen = new Set<string>()
121
+ const stack = [...urls]
122
+ while (stack.length > 0) {
123
+ const cur = stack.pop()!
124
+ if (seen.has(cur))
125
+ continue
126
+ seen.add(cur)
127
+ for (const dep of depsOf(cur))
128
+ stack.push(dep)
129
+ }
130
+ return seen
131
+ }
132
+
133
+ const routes: RouteBundleMetrics[] = manifest.routes.map((r) => {
134
+ const eagerJsRoots: string[] = []
135
+ if ((r.islandChunks.length > 0 || manifest.runtimeOnEveryPage === true) && manifest.runtimeScript !== undefined)
136
+ eagerJsRoots.push(manifest.runtimeScript)
137
+ if (r.usesRegion === true && manifest.regionScript !== undefined)
138
+ eagerJsRoots.push(manifest.regionScript)
139
+ const eager = r.eagerIslandChunks ?? r.islandChunks
140
+ for (const c of eager)
141
+ eagerJsRoots.push(c)
142
+ const islands: RouteIsland[] = []
143
+ for (const chunk of r.islandChunks) {
144
+ const origin = origins.get(chunk)
145
+ if (origin !== undefined)
146
+ islands.push({ ...origin, eager: eager.includes(chunk) })
147
+ }
148
+
149
+ const jsSet = collectTransitiveJs(eagerJsRoots)
150
+ let jsRaw = 0
151
+ let jsGzip = 0
152
+ for (const u of jsSet) {
153
+ const s = getSize(u)
154
+ jsRaw += s.raw
155
+ jsGzip += s.gzip
156
+ }
157
+
158
+ const cssList = r.styles ?? manifest.styles
159
+ let cssRaw = 0
160
+ let cssGzip = 0
161
+ for (const u of cssList) {
162
+ const s = getSize(u)
163
+ cssRaw += s.raw
164
+ cssGzip += s.gzip
165
+ }
166
+
167
+ const headUrls = firstLoadUrls([...manifest.headTags ?? [], ...r.headTags ?? []].join(''))
168
+ const load = measureFirstLoad([...cssList, ...eagerJsRoots, ...headUrls], locate)
169
+
170
+ return {
171
+ path: r.path,
172
+ fonts: load.fonts,
173
+ firstLoad: load.total,
174
+ jsRaw,
175
+ jsGzip,
176
+ cssRaw,
177
+ cssGzip,
178
+ jsFiles: jsSet.size,
179
+ cssFiles: cssList.length,
180
+ islands,
181
+ }
182
+ })
183
+
184
+ let totalJsGzip = 0
185
+ let totalCssGzip = 0
186
+ for (const rel of manifest.assets) {
187
+ const s = getSize(`${prefix}${rel}`)
188
+ if (rel.endsWith('.js'))
189
+ totalJsGzip += s.gzip
190
+ else if (rel.endsWith('.css'))
191
+ totalCssGzip += s.gzip
192
+ }
193
+
194
+ const topModules = [...moduleBytes.entries()]
195
+ .map(([path, bytes]) => ({ path, bytes }))
196
+ .sort((a, b) => b.bytes - a.bytes)
197
+ .slice(0, 10)
198
+
199
+ return { routes, totalJsGzip, totalCssGzip, topModules }
200
+ }
201
+
202
+ const kb = (b: number): string => `${(b / 1024).toFixed(2)} KB`
203
+ const islandLine = (island: RouteIsland): string => `${island.name} (${island.file}) ${island.reason}`
204
+
205
+ export function formatBundleReport(report: BundleReport): string {
206
+ const lines = [
207
+ '\n=== PRUNELLE BUNDLE WEIGHT REPORT ===',
208
+ `Total emitted: JS ${kb(report.totalJsGzip)} gz | CSS ${kb(report.totalCssGzip)} gz`,
209
+ '',
210
+ 'Route'.padEnd(28) + 'Eager JS (gz)'.padStart(16) + 'CSS (gz)'.padStart(14) + 'Fonts (br)'.padStart(14) + 'First load (br)'.padStart(18) + 'Files'.padStart(10),
211
+ ]
212
+ for (const r of report.routes) {
213
+ lines.push(
214
+ r.path.padEnd(28)
215
+ + kb(r.jsGzip).padStart(16)
216
+ + kb(r.cssGzip).padStart(14)
217
+ + kb(r.fonts).padStart(14)
218
+ + kb(r.firstLoad).padStart(18)
219
+ + `${r.jsFiles}j/${r.cssFiles}c`.padStart(10),
220
+ )
221
+ for (const island of r.islands)
222
+ lines.push(` ${island.eager ? 'island' : 'island, deferred'}: ${islandLine(island)}`)
223
+ }
224
+ lines.push('', 'First load is what a first visit downloads besides the page\'s HTML: CSS, eager JS and its imports, fonts, images and icons, brotli.')
225
+ if (report.topModules.length > 0) {
226
+ lines.push('', 'Top modules (minified output bytes):')
227
+ for (const m of report.topModules.slice(0, 8))
228
+ lines.push(` ${kb(m.bytes).padStart(9)} ${m.path}`)
229
+ }
230
+ return lines.join('\n')
231
+ }
232
+
233
+ export function formatBundleReportJson(report: BundleReport): string {
234
+ return JSON.stringify(report, null, 2)
235
+ }
236
+
237
+ /** Throws naming each route whose eager JS, gzipped, is over `maxBytes`, with the islands it loads with the page. */
238
+ export function checkJsBudget(report: BundleReport, maxBytes: number): void {
239
+ const over = report.routes.filter(r => r.jsGzip > maxBytes)
240
+ if (over.length === 0)
241
+ return
242
+ const lines = over.map((r) => {
243
+ const eager = r.islands.filter(island => island.eager).map(islandLine)
244
+ return ` ${r.path} ships ${kb(r.jsGzip)} of eager JS: ${eager.length > 0 ? eager.join('; ') : 'the prunelle runtime alone'}`
245
+ })
246
+ throw new Error(`prunelle build: eager JS over --max-js ${kb(maxBytes)} (gzip) on ${over.length === 1 ? 'one route' : `${over.length} routes`}:\n${lines.join('\n')}\nDefer an island with export const hydrate = 'visible', move its state into fewer components, or raise --max-js.`)
247
+ }
@@ -0,0 +1,50 @@
1
+ // Resolves an import the way prunelle build follows it: relative files, then packages through Bun's resolver; prunelle, node:, bun and ~ aliases stay unresolved.
2
+
3
+ import { statSync } from 'node:fs'
4
+ import { dirname, join, resolve } from 'node:path'
5
+ import pkg from '../../package.json' with { type: 'json' }
6
+
7
+ export const PRUNELLE_SRC_ROOT = resolve(import.meta.dir, '..')
8
+
9
+
10
+ export function resolveImportPath(fromFile: string, specifier: string): string | undefined {
11
+ if (specifier.startsWith('.')) {
12
+ const base = resolve(dirname(fromFile), specifier)
13
+ const candidates = [base, `${base}.tsx`, `${base}.ts`, join(base, 'index.tsx'), join(base, 'index.ts')]
14
+ for (const c of candidates) {
15
+ if (statSync(c, { throwIfNoEntry: false })?.isFile())
16
+ return c
17
+ }
18
+ return undefined
19
+ }
20
+ if (
21
+ specifier === 'prunelle'
22
+ || specifier.startsWith('prunelle/')
23
+ || specifier.startsWith('node:')
24
+ || specifier === 'bun'
25
+ || specifier.startsWith('bun:')
26
+ || specifier.startsWith('~')
27
+ ) {
28
+ return undefined
29
+ }
30
+ try {
31
+ const resolved = Bun.resolveSync(specifier, dirname(fromFile))
32
+ return resolved.endsWith('.tsx') || resolved.endsWith('.ts') ? resolved : undefined
33
+ }
34
+ catch {
35
+ return undefined
36
+ }
37
+ }
38
+
39
+ const PRUNELLE_SPECIFIER_FILES = new Map<string, string>(
40
+ Object.entries(pkg.exports as Record<string, string>).map(([subpath, target]) => [
41
+ subpath === '.' ? 'prunelle' : `prunelle/${subpath.slice(2)}`,
42
+ target.replace(/^\.\/src\//, ''),
43
+ ]),
44
+ )
45
+
46
+ /** Maps `prunelle` and its subpaths to their source file. */
47
+ export function resolvePrunelleSpecifier(specifier: string): string | undefined {
48
+ const file = PRUNELLE_SPECIFIER_FILES.get(specifier)
49
+ return file === undefined ? undefined : join(PRUNELLE_SRC_ROOT, file)
50
+ }
@@ -0,0 +1,338 @@
1
+ // Route files: their URL patterns, groups, param matchers, conflicts, and the `_layout`/`_middleware` chain that wraps them.
2
+
3
+ import type { ModuleAnalysis } from '../compiler/index'
4
+ import { existsSync } from 'node:fs'
5
+ import { basename, dirname, join, relative } from 'node:path'
6
+ import { BUILTIN_PARAM_MATCHER_NAMES, extractPatternMatchers, isBuiltinMatcher, parsePatternSegment } from '../server/param-matchers'
7
+ import { relPosix } from './files'
8
+
9
+ export const SPECIAL_ROUTE_FILES = new Set([
10
+ '_layout.tsx',
11
+ '_middleware.ts',
12
+ '_middleware.tsx',
13
+ '_error.tsx',
14
+ '_404.tsx',
15
+ '_401.tsx',
16
+ '_403.tsx',
17
+ '_429.tsx',
18
+ '_503.tsx',
19
+ ])
20
+ export const MIDDLEWARE_NAMES = ['_middleware.ts', '_middleware.tsx']
21
+ const ROUTE_EXPORTS = new Set(['default', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'])
22
+ const TS_EXT_RE = /\.(?:tsx|ts)$/
23
+ const ROUTE_GROUP_RE = /^\(([^/()]+)\)$/
24
+ const OPTIONAL_PARAM_SEG_RE = /^\[\[([^\[\]]+)\]\]$/
25
+ const CATCH_ALL_SEG_RE = /^\[\.\.\.([^\[\]]+)\]$/
26
+ const PARAM_SEG_RE = /^\[([^\[\]]+)\]$/
27
+ const CATCH_ALL_RE = /\[\.\.\.([^\]]+)\]/g
28
+ const PARAM_RE = /\[([^\]]+)\]/g
29
+ const PATH_SEPARATOR_RE = /[/\\]/
30
+
31
+ /** True when a route folder segment is a route group such as `(marketing)` or `(admin)`. */
32
+ export function isRouteGroupSegment(segment: string): boolean {
33
+ return ROUTE_GROUP_RE.test(segment)
34
+ }
35
+
36
+ /** True when a relative POSIX directory path contains any `(group)` segment. */
37
+ export function hasRouteGroupInRel(relDir: string): boolean {
38
+ if (relDir === '' || relDir === '.')
39
+ return false
40
+ return relDir.split('/').some(isRouteGroupSegment)
41
+ }
42
+
43
+ /** Returns the `(group)` folder names wrapping `file` under `routesDir`, outermost first. */
44
+ export function routeGroupsOf(routesDir: string, file: string): string[] {
45
+ const relDir = relPosix(routesDir, dirname(file))
46
+ if (relDir === '' || relDir === '.')
47
+ return []
48
+ const groups: string[] = []
49
+ for (const part of relDir.split('/')) {
50
+ const match = ROUTE_GROUP_RE.exec(part)
51
+ if (match !== null)
52
+ groups.push(match[1]!)
53
+ }
54
+ return groups
55
+ }
56
+
57
+ /** Converts one file-system route segment (`about`, `[id=integer]`, `[[lang]]`, `[...path=slug]`) into a router pattern segment. */
58
+ export function convertRouteSegment(segment: string): string {
59
+ const opt = OPTIONAL_PARAM_SEG_RE.exec(segment)
60
+ if (opt !== null)
61
+ return `:${opt[1]}?`
62
+ const catchAll = CATCH_ALL_SEG_RE.exec(segment)
63
+ if (catchAll !== null)
64
+ return `*${catchAll[1]}`
65
+ const param = PARAM_SEG_RE.exec(segment)
66
+ if (param !== null)
67
+ return `:${param[1]}`
68
+ return segment.replace(CATCH_ALL_RE, '*$1').replace(PARAM_RE, ':$1')
69
+ }
70
+
71
+ /** Converts a relative POSIX directory path under `routesDir` into a URL folder pattern, stripping `(group)` folders. */
72
+ export function dirToRoutePatternFromRel(relDir: string): string {
73
+ if (relDir === '' || relDir === '.')
74
+ return '/'
75
+ const parts = relDir.split('/').filter(p => p !== '' && !isRouteGroupSegment(p))
76
+ if (parts.length === 0)
77
+ return '/'
78
+ return `/${parts.map(convertRouteSegment).join('/')}`
79
+ }
80
+
81
+ /** A file in routes/ is a route when it exports a default component or an HTTP method handler, directly or through `export { ... }`. */
82
+ export function hasRouteHandlerExport(analysis: ModuleAnalysis): boolean {
83
+ return analysis.exportedNames.some(name => ROUTE_EXPORTS.has(name))
84
+ }
85
+
86
+ const SPECIAL_FILE_DEFAULTS = new Map([
87
+ ['_layout', 'layout component'],
88
+ ['_middleware', 'middleware function'],
89
+ ['_error', 'error page component'],
90
+ ['_404', 'not-found page component'],
91
+ ['_401', '401 status page component'],
92
+ ['_403', '403 status page component'],
93
+ ['_429', '429 status page component'],
94
+ ['_503', '503 status page component'],
95
+ ])
96
+
97
+ /** For a route file or a special route file (`_layout`, `_middleware`, `_error`, `_404`, `_401`, `_403`, `_429`, `_503`), reports missing default export or non-route files. */
98
+ export function routeFileProblem(analysis: ModuleAnalysis, file: string, routesRel: string): string | undefined {
99
+ const name = basename(file)
100
+ if (SPECIAL_ROUTE_FILES.has(name))
101
+ return analysis.exportedNames.includes('default') ? undefined : `${file} has no default export: export default its ${SPECIAL_FILE_DEFAULTS.get(name.replace(TS_EXT_RE, ''))}.`
102
+ return hasRouteHandlerExport(analysis) || analysis.exportedActions.length > 0 ? undefined : `${file} exports no route; move it out of ${routesRel} or prefix it with _.`
103
+ }
104
+
105
+ const LOAD_FIX = 'prunelle never calls it; export async function load() and read its data with the page\'s load prop'
106
+ const PATHS_FIX = 'prunelle never calls it; export function paths() returning URL strings such as "/posts/a"'
107
+ const HEAD_FIX = 'prunelle never reads it; render <Head> in the page'
108
+ // Exports other frameworks read from a route file, and what prunelle wants instead.
109
+ const FOREIGN_ROUTE_EXPORTS = new Map([
110
+ ['getStaticProps', LOAD_FIX],
111
+ ['getServerSideProps', LOAD_FIX],
112
+ ['getInitialProps', LOAD_FIX],
113
+ ['loader', LOAD_FIX],
114
+ ['clientLoader', LOAD_FIX],
115
+ ['getStaticPaths', PATHS_FIX],
116
+ ['generateStaticParams', PATHS_FIX],
117
+ ['metadata', HEAD_FIX],
118
+ ['generateMetadata', HEAD_FIX],
119
+ ['meta', HEAD_FIX],
120
+ ...['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'all'].map(m => [m, `prunelle never calls it; export function ${m === 'all' ? 'GET(), POST() or another method' : `${m.toUpperCase()}()`}`] as const),
121
+ ])
122
+
123
+ function findExportOffset(analysis: ModuleAnalysis, exportName: string): number {
124
+ for (const stmt of analysis.program.body) {
125
+ if (stmt.type !== 'ExportNamedDeclaration')
126
+ continue
127
+ if (stmt.declaration?.type === 'FunctionDeclaration' && stmt.declaration.id?.name === exportName)
128
+ return stmt.start
129
+ if (stmt.declaration?.type === 'ClassDeclaration' && stmt.declaration.id?.name === exportName)
130
+ return stmt.start
131
+ if (stmt.declaration?.type === 'VariableDeclaration') {
132
+ for (const d of stmt.declaration.declarations) {
133
+ if (d.id.type === 'Identifier' && d.id.name === exportName)
134
+ return d.start
135
+ }
136
+ }
137
+ for (const spec of stmt.specifiers) {
138
+ const exp = spec.exported.type === 'Identifier' ? spec.exported.name : spec.exported.value
139
+ if (exp === exportName)
140
+ return spec.start
141
+ }
142
+ }
143
+ return 0
144
+ }
145
+
146
+ /** Returns the first route export problem together with its byte offset in the module source. */
147
+ export function routeExportProblemLocation(analysis: ModuleAnalysis, file: string): { message: string, offset: number } | undefined {
148
+ for (const name of analysis.exportedNames) {
149
+ const fix = FOREIGN_ROUTE_EXPORTS.get(name)
150
+ if (fix !== undefined)
151
+ return { message: `export ${name} in ${file}: ${fix}.`, offset: findExportOffset(analysis, name) }
152
+ }
153
+ for (const stmt of analysis.program.body) {
154
+ if (stmt.type !== 'ExportNamedDeclaration' || stmt.declaration?.type !== 'VariableDeclaration')
155
+ continue
156
+ for (const d of stmt.declaration.declarations) {
157
+ const name = d.id.type === 'Identifier' ? d.id.name : undefined
158
+ const init = d.init
159
+ if (name === 'paths' && init !== null && init.type !== 'ArrowFunctionExpression' && init.type !== 'FunctionExpression')
160
+ return { message: `export const paths in ${file}: export function paths() returning the URLs, such as () => ['/posts/a'].`, offset: d.start }
161
+ if (name === 'prerender' && !(init?.type === 'Literal' && typeof init.value === 'boolean'))
162
+ return { message: `${init?.type === 'Literal' ? `prerender = ${init.raw ?? String(init.value)}` : 'prerender set at runtime'} in ${file}: write prerender = true or prerender = false.`, offset: d.start }
163
+ }
164
+ }
165
+ return undefined
166
+ }
167
+
168
+ /** The first route export prunelle never reads (Next, Remix and Astro names), `paths` that is not a function, or `prerender` that is not literally `true` or `false`, worded for `prunelle build` and `prunelle check` to prefix. */
169
+ export function routeExportProblem(analysis: ModuleAnalysis, file: string): string | undefined {
170
+ return routeExportProblemLocation(analysis, file)?.message
171
+ }
172
+
173
+ /** Throws unless a route's `paths()` gave an array of URL paths starting with `/`. */
174
+ function exportedConstOffset(analysis: ModuleAnalysis, name: string): number {
175
+ for (const stmt of analysis.program.body) {
176
+ if (stmt.type === 'ExportNamedDeclaration' && stmt.declaration?.type === 'VariableDeclaration') {
177
+ for (const d of stmt.declaration.declarations) {
178
+ if (d.id.type === 'Identifier' && d.id.name === name)
179
+ return d.start
180
+ }
181
+ }
182
+ }
183
+ return 0
184
+ }
185
+
186
+ /** A dynamic route (`pattern` holds `:` or `*`) that is prerendered, by `prerender = true` or by `--static` for a page, yet exports no `paths()`, so its pages would silently not exist. */
187
+ export function missingPathsProblem(analysis: ModuleAnalysis, pattern: string, isStatic: boolean): { offset: number, message: string } | undefined {
188
+ if (analysis.hasPaths || (!pattern.includes(':') && !pattern.includes('*')))
189
+ return undefined
190
+ if (analysis.hasPrerender)
191
+ return { offset: exportedConstOffset(analysis, 'prerender'), message: 'dynamic route exports `prerender = true` without exporting `paths()`: export `paths()` returning the URLs to prerender, or drop `prerender`.' }
192
+ if (isStatic && analysis.exportedNames.includes('default'))
193
+ return { offset: 0, message: 'dynamic route has no `paths()`, so `prunelle build --static` cannot export it: export `paths()` returning its URLs.' }
194
+ return undefined
195
+ }
196
+
197
+ export function assertPathUrls(urls: unknown, file: string): asserts urls is string[] {
198
+ if (!Array.isArray(urls))
199
+ throw new Error(`prunelle build: paths() in ${file} returned ${JSON.stringify(urls)}: return an array of URL paths such as ["/posts/a"].`)
200
+ for (const url of urls) {
201
+ if (typeof url !== 'string' || !url.startsWith('/'))
202
+ throw new Error(`prunelle build: paths() in ${file} returned ${JSON.stringify(url)}: return URL paths such as "/posts/a".`)
203
+ }
204
+ }
205
+
206
+ export function fileToRoutePath(routesDir: string, file: string): string {
207
+ const rel = relPosix(routesDir, file).replace(TS_EXT_RE, '')
208
+ const rawParts = rel.split('/')
209
+ const filePart = rawParts.pop()!
210
+ const urlParts = rawParts.filter(part => !isRouteGroupSegment(part))
211
+ if (filePart !== 'index')
212
+ urlParts.push(filePart)
213
+ if (urlParts.length === 0)
214
+ return '/'
215
+ return `/${urlParts.map(convertRouteSegment).join('/')}`
216
+ }
217
+
218
+ /** The shape two route paths conflict on: parameter names do not matter, but optionality and matcher names do. */
219
+ export function normalizeRoutePattern(routePath: string): string {
220
+ return routePath
221
+ .split('/')
222
+ .map((seg) => {
223
+ if (seg === '')
224
+ return ''
225
+ const parsed = parsePatternSegment(seg)
226
+ const matcher = parsed.matcherName !== undefined ? `=${parsed.matcherName}` : ''
227
+ if (parsed.kind === 'catchall')
228
+ return `*${matcher}`
229
+ if (parsed.kind === 'optional')
230
+ return `:${matcher}?`
231
+ if (parsed.kind === 'param')
232
+ return `:${matcher}`
233
+ return parsed.value
234
+ })
235
+ .join('/')
236
+ }
237
+
238
+ /** Throws on two route files that serve one pattern (about.tsx vs about/index.tsx, (a)/about.tsx vs (b)/about.tsx, [id].tsx vs [slug].tsx). */
239
+ export function assertNoRouteConflicts(root: string, routesDir: string, pageFiles: string[]): void {
240
+ const seen = new Map<string, { file: string, path: string }>()
241
+ for (const file of pageFiles) {
242
+ const routePath = fileToRoutePath(routesDir, file)
243
+ const normalized = normalizeRoutePattern(routePath)
244
+ const existing = seen.get(normalized)
245
+ if (existing !== undefined)
246
+ throw new Error(`prunelle build: conflicting routes for pattern "${routePath}": "${relPosix(root, existing.file)}" (${existing.path}) and "${relPosix(root, file)}" (${routePath})`)
247
+ seen.set(normalized, { file, path: routePath })
248
+ }
249
+ }
250
+
251
+ /** Resolves an app-defined param matcher file (`src/params/<name>.ts` or `.tsx`, or `<routesDir>/../params/<name>.ts`). */
252
+ export function findCustomMatcherFile(root: string, routesDir: string, matcherName: string): string | undefined {
253
+ const candidates = [
254
+ join(root, 'src/params', `${matcherName}.ts`),
255
+ join(root, 'src/params', `${matcherName}.tsx`),
256
+ join(dirname(routesDir), 'params', `${matcherName}.ts`),
257
+ join(dirname(routesDir), 'params', `${matcherName}.tsx`),
258
+ ]
259
+ for (const candidate of candidates) {
260
+ if (existsSync(candidate))
261
+ return candidate
262
+ }
263
+ return undefined
264
+ }
265
+
266
+ export interface MatcherDiscoveryResult {
267
+ /** Custom (non-built-in) matcher name -> absolute source file path. */
268
+ customFiles: Map<string, string>
269
+ /** Missing or invalid matcher diagnostics. */
270
+ problems: { file: string, message: string }[]
271
+ }
272
+
273
+ /** Discovers and validates every param matcher referenced by route patterns (and directory patterns of middleware/status pages). */
274
+ export function discoverRouteMatchers(options: {
275
+ root: string
276
+ routesDir: string
277
+ routeFiles: readonly string[]
278
+ loadAnalysis: (file: string) => ModuleAnalysis | undefined
279
+ }): MatcherDiscoveryResult {
280
+ const { root, routesDir, routeFiles, loadAnalysis } = options
281
+ const customFiles = new Map<string, string>()
282
+ const problems: { file: string, message: string }[] = []
283
+ const validatedCustom = new Set<string>()
284
+ const builtinList = BUILTIN_PARAM_MATCHER_NAMES.join(', ')
285
+
286
+ for (const file of routeFiles) {
287
+ const pattern = basename(file).startsWith('_')
288
+ ? dirToRoutePatternFromRel(relPosix(routesDir, dirname(file)))
289
+ : fileToRoutePath(routesDir, file)
290
+ const refs = extractPatternMatchers(pattern)
291
+ if (refs.length === 0)
292
+ continue
293
+ const rel = relPosix(root, file)
294
+ for (const { matcher } of refs) {
295
+ if (isBuiltinMatcher(matcher))
296
+ continue
297
+ const found = findCustomMatcherFile(root, routesDir, matcher)
298
+ if (found === undefined) {
299
+ problems.push({
300
+ file,
301
+ message: `unknown param matcher "${matcher}" in ${rel}: use a built-in matcher (${builtinList}) or create src/params/${matcher}.ts exporting match(value: string): boolean (or a default function).`,
302
+ })
303
+ continue
304
+ }
305
+ customFiles.set(matcher, found)
306
+ if (!validatedCustom.has(found)) {
307
+ validatedCustom.add(found)
308
+ const analysis = loadAnalysis(found)
309
+ if (analysis !== undefined && !analysis.exportedNames.includes('match') && !analysis.exportedNames.includes('default')) {
310
+ problems.push({
311
+ file: found,
312
+ message: `${relPosix(root, found)} exports no param matcher: export function match(value: string): boolean (or export default).`,
313
+ })
314
+ }
315
+ }
316
+ }
317
+ }
318
+
319
+ return { customFiles, problems }
320
+ }
321
+
322
+ /** Finds all ancestor files named one of `names` from routesDir down to dirname(routeFile), outermost first. */
323
+ export function ancestorFiles(routesDir: string, routeFile: string, names: string[]): string[] {
324
+ const result: string[] = []
325
+ const relDir = relative(routesDir, dirname(routeFile))
326
+ const parts = relDir === '' ? [] : relDir.split(PATH_SEPARATOR_RE)
327
+ let cur = routesDir
328
+ for (let i = 0; i <= parts.length; i++) {
329
+ if (i > 0)
330
+ cur = join(cur, parts[i - 1]!)
331
+ for (const name of names) {
332
+ const candidate = join(cur, name)
333
+ if (existsSync(candidate))
334
+ result.push(candidate)
335
+ }
336
+ }
337
+ return result
338
+ }
@@ -0,0 +1,38 @@
1
+ // The generated server entry (`dist/server/_entry.js`): the one module that assembles an app from its bundled config, routes and actions.
2
+
3
+ /** The entry's path under the server bundle root, and so under `dist/server/`. An underscore file is never a route. */
4
+ export const SERVER_ENTRY_FILE = '_entry.js'
5
+
6
+ export interface ServerEntryModule {
7
+ /** Absolute source path, bundled in the same pass as the entry. */
8
+ file: string
9
+ /** The module's manifest key (`server/index.js`). */
10
+ key: string
11
+ /** Root-relative source path, read by `testApp().import()`. */
12
+ source: string
13
+ }
14
+
15
+ export interface ServerEntryOptions {
16
+ modules: readonly ServerEntryModule[]
17
+ /** `prunelle.config.ts`, when the app has one. */
18
+ config?: { file: string, source: string } | undefined
19
+ /** Absolute path of prunelle's `server/app-entry.ts`, bundled from source like the app's own `prunelle/server` imports. */
20
+ assembler: string
21
+ }
22
+
23
+ export function serverEntrySource(options: ServerEntryOptions): string {
24
+ const lines: string[] = []
25
+ const { config } = options
26
+ if (config !== undefined)
27
+ lines.push(`import * as configModule from ${JSON.stringify(config.file)}`)
28
+ options.modules.forEach((m, i) => lines.push(`import * as m${i} from ${JSON.stringify(m.file)}`))
29
+ lines.push(`import { createAppFromEntry } from ${JSON.stringify(options.assembler)}`)
30
+ lines.push(`export const prunelleConfig = ${config !== undefined ? 'configModule.default ?? {}' : '{}'}`)
31
+ lines.push(`export const modules = {${options.modules.map((m, i) => ` ${JSON.stringify(m.key)}: m${i},`).join('')} }`)
32
+ const sources = options.modules.map((m, i) => ` ${JSON.stringify(m.source)}: m${i},`)
33
+ if (config !== undefined)
34
+ sources.push(` ${JSON.stringify(config.source)}: configModule,`)
35
+ lines.push(`export const sources = {${sources.join('')} }`)
36
+ lines.push('export function createApp(options) { return createAppFromEntry(prunelleConfig, modules, options) }')
37
+ return `${lines.join('\n')}\n`
38
+ }