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,164 @@
1
+ // What a first visit downloads, as served: the page, the files it links, and the files those pull in (a script's static imports, a stylesheet's `url()`s), each counted once. The docs footer and `prunelle build --analyze` both measure with this.
2
+
3
+ import { existsSync, readFileSync, statSync } from 'node:fs'
4
+ import { extname, join, posix } from 'node:path'
5
+ import { appBrotliCacheDir, brotliSync } from './precompress'
6
+
7
+ // A static `import ... from "./x.js"` or `import "./x.js"` of an emitted chunk; `import("./x.js")` stays lazy and is left out.
8
+ export const STATIC_CHUNK_IMPORT_RE = /\b(?:import|export)\s*(?:[^"'();]*?\bfrom\s*)?["'](\.\.?\/[^"']+\.js)["']/g
9
+
10
+ const TAG_RE = /<(img|script|link)\b[^>]*>/g
11
+ const SRC_RE = /\bsrc="([^"]+)"/
12
+ const HREF_RE = /\bhref="([^"]+)"/
13
+ const REL_RE = /\brel="([^"]+)"/
14
+ const TYPE_RE = /\btype="([^"]+)"/
15
+ const LAZY_RE = /\bloading="lazy"/
16
+ const FONT_FACE_RE = /@font-face\s*\{[^}]*\}/g
17
+ const CSS_URL_RE = /url\(\s*(["']?)([^)"']+)\1\s*\)/g
18
+ const CSS_IMPORT_RE = /@import\s+(?:url\(\s*)?["']([^"']+)["']/g
19
+ const FETCHED_RELS = new Set(['stylesheet', 'modulepreload', 'preload'])
20
+ const COMPRESSED_EXTS = new Set(['.html', '.js', '.mjs', '.css', '.svg', '.xml', '.json', '.txt', '.webmanifest'])
21
+ const FONT_EXTS = new Set(['.woff2', '.woff', '.ttf', '.otf'])
22
+ const IMAGE_EXTS = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp', '.avif', '.svg', '.ico'])
23
+ const SKIPPED_URL_RE = /^(?:[a-z][a-z0-9+.-]*:|\/\/|#)/i
24
+
25
+ export interface FirstLoad {
26
+ /** The page's own HTML, brotli, as given by the caller. */
27
+ html: number
28
+ css: number
29
+ js: number
30
+ fonts: number
31
+ images: number
32
+ other: number
33
+ total: number
34
+ /** The part of `total` a browser keeps in its cache for the next page: the files `cacheable` accepts. */
35
+ cached: number
36
+ /** Files counted besides the page. */
37
+ files: number
38
+ }
39
+
40
+ /** Turns a URL the page links into the file that serves it, or `undefined` when no file does. */
41
+ export type Locate = (url: string) => string | undefined
42
+
43
+ /** The URLs a browser fetches from this markup: stylesheets, preloads, scripts, one icon, and images that are not lazy. */
44
+ export function firstLoadUrls(html: string): string[] {
45
+ const urls = new Set<string>()
46
+ const icons: string[] = []
47
+ let svgIcon: string | undefined
48
+ for (const [element, name] of html.matchAll(TAG_RE)) {
49
+ if (name === 'link') {
50
+ const url = HREF_RE.exec(element)?.[1]
51
+ const relation = REL_RE.exec(element)?.[1] ?? ''
52
+ if (url === undefined)
53
+ continue
54
+ if (relation === 'icon') {
55
+ icons.push(url)
56
+ svgIcon ??= TYPE_RE.exec(element)?.[1] === 'image/svg+xml' ? url : undefined
57
+ }
58
+ else if (FETCHED_RELS.has(relation)) {
59
+ urls.add(url)
60
+ }
61
+ continue
62
+ }
63
+ const url = SRC_RE.exec(element)?.[1]
64
+ if (url !== undefined && !LAZY_RE.test(element))
65
+ urls.add(url)
66
+ }
67
+ // A browser that draws SVG icons fetches that one alone; the others are for browsers that do not.
68
+ for (const icon of svgIcon === undefined ? icons : [svgIcon])
69
+ urls.add(icon)
70
+ return [...urls]
71
+ }
72
+
73
+ /** The locator for a build's output: `/_pru/x` is `clientDir/x`, anything else is looked up in each public dir. */
74
+ export function distLocator(options: { clientDir: string, assetPrefix: string, publicDirs: readonly string[] }): Locate {
75
+ const prefix = `${options.assetPrefix.replace(/\/$/, '')}/`
76
+ return (url) => {
77
+ const path = url.split(/[?#]/)[0]!
78
+ if (path.startsWith(prefix)) {
79
+ const file = join(options.clientDir, path.slice(prefix.length))
80
+ return existsSync(file) ? file : undefined
81
+ }
82
+ if (!path.startsWith('/'))
83
+ return undefined
84
+ return options.publicDirs.map(dir => join(dir, path.slice(1))).find(file => existsSync(file))
85
+ }
86
+ }
87
+
88
+ const brotliCache = new Map<string, number>()
89
+
90
+ /** Bytes on the wire: the `.br` sidecar prunelle wrote, else brotli of a compressible file, else the file as it is. */
91
+ function servedSize(file: string): number {
92
+ const sidecar = `${file}.br`
93
+ if (existsSync(sidecar))
94
+ return statSync(sidecar).size
95
+ const raw = readFileSync(file)
96
+ if (!COMPRESSED_EXTS.has(extname(file).toLowerCase()))
97
+ return raw.byteLength
98
+ const key = `${file}:${raw.byteLength}`
99
+ let packed = brotliCache.get(key)
100
+ if (packed === undefined) {
101
+ packed = brotliSync(raw, appBrotliCacheDir()).byteLength
102
+ brotliCache.set(key, packed)
103
+ }
104
+ return Math.min(packed, raw.byteLength)
105
+ }
106
+
107
+ // A browser takes the first source of an @font-face it can use, so only that one is fetched; every other url() is.
108
+ function cssUrls(css: string): string[] {
109
+ const urls: string[] = []
110
+ const rest = css.replace(FONT_FACE_RE, (face) => {
111
+ const first = new RegExp(CSS_URL_RE.source).exec(face)?.[2]
112
+ if (first !== undefined)
113
+ urls.push(first)
114
+ return ''
115
+ })
116
+ for (const match of rest.matchAll(CSS_URL_RE))
117
+ urls.push(match[2]!)
118
+ for (const match of rest.matchAll(CSS_IMPORT_RE))
119
+ urls.push(match[1]!)
120
+ return urls.filter(url => !SKIPPED_URL_RE.test(url))
121
+ }
122
+
123
+ /** What a file pulls in beside itself: a script's static imports and a stylesheet's `url()`s, as URLs. */
124
+ function dependenciesOf(url: string, file: string): string[] {
125
+ const ext = extname(file).toLowerCase()
126
+ if (ext !== '.js' && ext !== '.css')
127
+ return []
128
+ const text = readFileSync(file, 'utf8')
129
+ const base = posix.dirname(url.split(/[?#]/)[0]!)
130
+ const raw = ext === '.js' ? [...text.matchAll(STATIC_CHUNK_IMPORT_RE)].map(m => m[1]!) : cssUrls(text)
131
+ return raw.map(dep => (dep.startsWith('/') ? dep : posix.join(base, dep)))
132
+ }
133
+
134
+ /** Adds up what a first visit fetches from these root URLs and what they pull in; `htmlBytes` is the page itself, brotli; `cacheable` names the URLs served for long caching (prunelle's hashed assets). */
135
+ export function measureFirstLoad(roots: Iterable<string>, locate: Locate, htmlBytes = 0, cacheable: (url: string) => boolean = () => false): FirstLoad {
136
+ const result: FirstLoad = { html: htmlBytes, css: 0, js: 0, fonts: 0, images: 0, other: 0, total: htmlBytes, cached: 0, files: 0 }
137
+ const seen = new Set<string>()
138
+ const stack = [...roots]
139
+ while (stack.length > 0) {
140
+ const url = stack.pop()!
141
+ const file = locate(url)
142
+ if (file === undefined || seen.has(file))
143
+ continue
144
+ seen.add(file)
145
+ const ext = extname(file).toLowerCase()
146
+ const size = servedSize(file)
147
+ if (ext === '.css')
148
+ result.css += size
149
+ else if (ext === '.js' || ext === '.mjs')
150
+ result.js += size
151
+ else if (FONT_EXTS.has(ext))
152
+ result.fonts += size
153
+ else if (IMAGE_EXTS.has(ext))
154
+ result.images += size
155
+ else
156
+ result.other += size
157
+ result.total += size
158
+ if (cacheable(url))
159
+ result.cached += size
160
+ result.files++
161
+ stack.push(...dependenciesOf(url, file))
162
+ }
163
+ return result
164
+ }
@@ -0,0 +1,247 @@
1
+ // The module graph of one build: every .ts/.tsx file reachable from the routes, analyzed once (and reused across `prunelle dev` rebuilds while mtime and size match).
2
+
3
+ import type { ModuleAnalysis } from '../compiler/index'
4
+ import { existsSync, readFileSync, statSync } from 'node:fs'
5
+ import { analyzeModule } from '../compiler/index'
6
+ import { PrunelleMistake } from '../compiler/mistakes'
7
+ import { formatCodeFrame, formatDiagnostic, formatLoc } from '../compiler/shared'
8
+ import { isTsFile, relPosix } from './files'
9
+ import { resolveImportPath } from './resolve'
10
+
11
+ export interface FileStamp {
12
+ mtimeMs: number
13
+ size: number
14
+ }
15
+
16
+ export interface CachedClientBuild {
17
+ signature: string
18
+ clientDir: string
19
+ inputStamps: Map<string, FileStamp>
20
+ islandChunks: Map<string, string>
21
+ srcCssToUrl: Map<string, string>
22
+ islandCssUrl: Map<string, string>
23
+ assetFiles: string[]
24
+ styleUrls: string[]
25
+ runtimeScript: string | undefined
26
+ regionScript: string | undefined
27
+ reviveScript: string | undefined
28
+ chunkImports: Record<string, string[]>
29
+ }
30
+
31
+ export interface CachedServerBuild {
32
+ signature: string
33
+ serverDir: string
34
+ inputStamps: Map<string, FileStamp>
35
+ }
36
+
37
+ export interface BuildCacheStats {
38
+ clientBuilds: number
39
+ clientSkips: number
40
+ serverBuilds: number
41
+ serverSkips: number
42
+ }
43
+
44
+ export interface BuildCache {
45
+ analyses: Map<string, FileStamp & { code: string, analysis: ModuleAnalysis }>
46
+ domCompiled: Map<string, FileStamp & { key?: string | undefined, code: string }>
47
+ ssrCompiled: Map<string, FileStamp & { key: string, code: string }>
48
+ lastClient?: CachedClientBuild | undefined
49
+ lastServer?: CachedServerBuild | undefined
50
+ watchedFiles: Set<string>
51
+ stats: BuildCacheStats
52
+ }
53
+
54
+ export function createBuildCache(): BuildCache {
55
+ return {
56
+ analyses: new Map(),
57
+ domCompiled: new Map(),
58
+ ssrCompiled: new Map(),
59
+ watchedFiles: new Set(),
60
+ stats: { clientBuilds: 0, clientSkips: 0, serverBuilds: 0, serverSkips: 0 },
61
+ }
62
+ }
63
+
64
+ export function clearBuildCache(cache: BuildCache): void {
65
+ cache.analyses.clear()
66
+ cache.domCompiled.clear()
67
+ cache.ssrCompiled.clear()
68
+ cache.lastClient = undefined
69
+ cache.lastServer = undefined
70
+ cache.watchedFiles.clear()
71
+ }
72
+
73
+ export function stampFiles(files: Iterable<string>): Map<string, FileStamp> {
74
+ const out = new Map<string, FileStamp>()
75
+ for (const file of files) {
76
+ if (out.has(file))
77
+ continue
78
+ try {
79
+ const st = statSync(file)
80
+ if (st.isFile())
81
+ out.set(file, { mtimeMs: st.mtimeMs, size: st.size })
82
+ }
83
+ catch {}
84
+ }
85
+ return out
86
+ }
87
+
88
+ export function stampsMatch(inputStamps: ReadonlyMap<string, FileStamp>): boolean {
89
+ for (const [file, prev] of inputStamps) {
90
+ if (!existsSync(file))
91
+ return false
92
+ try {
93
+ const st = statSync(file)
94
+ if (st.mtimeMs !== prev.mtimeMs || st.size !== prev.size)
95
+ return false
96
+ }
97
+ catch {
98
+ return false
99
+ }
100
+ }
101
+ return true
102
+ }
103
+
104
+ const MAX_REEXPORT_DEPTH = 8
105
+
106
+ export class ModuleGraph {
107
+ readonly analyses = new Map<string, ModuleAnalysis>()
108
+ private readonly sources = new Map<string, string>()
109
+ private readonly stamps = new Map<string, FileStamp>()
110
+ private readonly resolved = new Map<string, string | undefined>()
111
+ private readonly deps = new Map<string, string[]>()
112
+
113
+ /** `root` is the app's folder, for the root-relative paths in errors. */
114
+ constructor(private readonly root: string, private readonly cache?: BuildCache) {}
115
+
116
+ /** The file's mtime and size; only tracked when a cache is in use. */
117
+ stamp(file: string): FileStamp | undefined {
118
+ const known = this.stamps.get(file)
119
+ if (known !== undefined || this.cache === undefined)
120
+ return known
121
+ try {
122
+ const st = statSync(file)
123
+ const stamp = { mtimeMs: st.mtimeMs, size: st.size }
124
+ this.stamps.set(file, stamp)
125
+ return stamp
126
+ }
127
+ catch {
128
+ return undefined
129
+ }
130
+ }
131
+
132
+ /** The text of a file, read once per build. */
133
+ source(file: string): string {
134
+ let code = this.sources.get(file)
135
+ if (code === undefined) {
136
+ code = readFileSync(file, 'utf8')
137
+ this.sources.set(file, code)
138
+ }
139
+ return code
140
+ }
141
+
142
+ /** `resolveImportPath`, remembered for the build. */
143
+ resolve(from: string, specifier: string): string | undefined {
144
+ const key = `${from}\0${specifier}`
145
+ if (this.resolved.has(key))
146
+ return this.resolved.get(key)
147
+ const target = resolveImportPath(from, specifier)
148
+ this.resolved.set(key, target)
149
+ return target
150
+ }
151
+
152
+ /** The .ts/.tsx modules a loaded file imports or re-exports from. */
153
+ localDeps(file: string): string[] {
154
+ let list = this.deps.get(file)
155
+ if (list === undefined) {
156
+ list = []
157
+ const analysis = this.analyses.get(file)
158
+ for (const { source } of [...(analysis?.imports ?? []), ...(analysis?.reexports ?? [])]) {
159
+ const target = this.resolve(file, source)
160
+ if (target !== undefined && isTsFile(target))
161
+ list.push(target)
162
+ }
163
+ if (analysis !== undefined)
164
+ this.deps.set(file, list)
165
+ }
166
+ return list
167
+ }
168
+
169
+ /** Analyzes `file` and everything it imports. */
170
+ load(file: string): ModuleAnalysis {
171
+ const existing = this.analyses.get(file)
172
+ if (existing !== undefined)
173
+ return existing
174
+ const stamp = this.stamp(file)
175
+ const cached = stamp === undefined ? undefined : this.cache?.analyses.get(file)
176
+ let analysis: ModuleAnalysis
177
+ if (cached !== undefined && cached.mtimeMs === stamp!.mtimeMs && cached.size === stamp!.size) {
178
+ analysis = cached.analysis
179
+ this.sources.set(file, cached.code)
180
+ }
181
+ else {
182
+ const code = this.source(file)
183
+ analysis = this.analyze(file, code)
184
+ if (this.cache !== undefined && stamp !== undefined)
185
+ this.cache.analyses.set(file, { mtimeMs: stamp.mtimeMs, size: stamp.size, code, analysis })
186
+ }
187
+ this.analyses.set(file, analysis)
188
+ for (const dep of this.localDeps(file))
189
+ this.load(dep)
190
+ return analysis
191
+ }
192
+
193
+ /** `analyzeModule`, its errors naming the file from the app's root, a mistake at its line with a code frame as a syntax error has. */
194
+ private analyze(file: string, code: string): ModuleAnalysis {
195
+ try {
196
+ return analyzeModule(file, code)
197
+ }
198
+ catch (err) {
199
+ if (!(err instanceof Error))
200
+ throw err
201
+ const rel = relPosix(this.root, file)
202
+ err.message = err.message.replaceAll(file, rel)
203
+ if (err instanceof PrunelleMistake && err.start !== undefined) {
204
+ const frame = formatCodeFrame(code, err.start)
205
+ err.message = `${formatDiagnostic(formatLoc(rel, code, err.start), err.message)}${frame === '' ? '' : `\n${frame}`}`
206
+ }
207
+ throw err
208
+ }
209
+ }
210
+
211
+ /** Follows `export { x } from './y'` and `export * from './y'` chains to the module that declares the export. */
212
+ exportTarget(file: string, exportName: string, depth = 0, seen = new Set<string>()): { file: string, exportName: string } {
213
+ if (depth > MAX_REEXPORT_DEPTH)
214
+ return { file, exportName }
215
+ const key = `${file}\0${exportName}`
216
+ if (seen.has(key))
217
+ return { file, exportName }
218
+ seen.add(key)
219
+
220
+ const analysis = this.load(file)
221
+ const direct = analysis.reexports.find(r => r.exported === exportName)
222
+ if (direct !== undefined) {
223
+ const next = this.resolve(file, direct.source)
224
+ if (next !== undefined && isTsFile(next))
225
+ return this.exportTarget(next, direct.local, depth + 1, seen)
226
+ }
227
+
228
+ if (analysis.exportedNames.includes(exportName))
229
+ return { file, exportName }
230
+
231
+ // Follow `export * from './y'` barrel re-exports (named exports only, per ESM spec `export *` never re-exports `default`).
232
+ if (exportName !== 'default') {
233
+ for (const re of analysis.reexports) {
234
+ if (re.exported !== '*')
235
+ continue
236
+ const next = this.resolve(file, re.source)
237
+ if (next === undefined || !isTsFile(next))
238
+ continue
239
+ const candidate = this.exportTarget(next, exportName, depth + 1, seen)
240
+ if (this.load(candidate.file).exportedNames.includes(candidate.exportName))
241
+ return candidate
242
+ }
243
+ }
244
+
245
+ return { file, exportName }
246
+ }
247
+ }