@kayjs/kay 2.0.0-beta.0 → 2.0.0-beta.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 (55) hide show
  1. package/package.json +1 -1
  2. package/src/attrs.ts +35 -0
  3. package/src/build/bundle.ts +615 -0
  4. package/src/build/compile.ts +32 -19
  5. package/src/build/files.ts +174 -0
  6. package/src/build/graph.ts +223 -0
  7. package/src/build/index.ts +255 -1461
  8. package/src/build/islands.ts +177 -0
  9. package/src/build/manifest.ts +227 -0
  10. package/src/build/plugin-host.ts +186 -0
  11. package/src/build/prerender.ts +94 -0
  12. package/src/build/report.ts +157 -0
  13. package/src/build/resolve.ts +51 -0
  14. package/src/build/routes.ts +163 -0
  15. package/src/build/static.ts +73 -0
  16. package/src/cli/check.ts +300 -129
  17. package/src/cli/index.ts +297 -94
  18. package/src/cli/new.ts +58 -38
  19. package/src/compiler/analyze.ts +723 -93
  20. package/src/compiler/dom.ts +848 -762
  21. package/src/compiler/mistakes.ts +354 -0
  22. package/src/compiler/patch.ts +1 -1
  23. package/src/compiler/server-only.ts +172 -23
  24. package/src/compiler/shared.ts +485 -0
  25. package/src/compiler/ssr.ts +331 -342
  26. package/src/context.ts +120 -0
  27. package/src/dev/index.ts +358 -76
  28. package/src/dom/action.ts +114 -14
  29. package/src/dom/extras.ts +121 -83
  30. package/src/dom/index.ts +122 -80
  31. package/src/dom/island.ts +71 -36
  32. package/src/dom/loop.ts +28 -20
  33. package/src/index.ts +5 -1
  34. package/src/jsx-runtime.ts +432 -93
  35. package/src/plugins/context.ts +83 -0
  36. package/src/plugins/index.ts +285 -23
  37. package/src/reactivity/index.ts +237 -213
  38. package/src/reactivity/selector.ts +11 -9
  39. package/src/reactivity/store.ts +36 -11
  40. package/src/server/action.ts +157 -79
  41. package/src/server/compress.ts +197 -104
  42. package/src/server/cookies.ts +46 -16
  43. package/src/server/env.ts +18 -13
  44. package/src/server/http.ts +189 -77
  45. package/src/server/index.ts +1024 -878
  46. package/src/server/loader.ts +138 -0
  47. package/src/server/router.ts +69 -26
  48. package/src/server/security.ts +50 -58
  49. package/src/server/standard-schema.ts +42 -11
  50. package/src/server/static-dir.ts +144 -0
  51. package/src/ssr/context.ts +95 -10
  52. package/src/ssr/index.ts +167 -66
  53. package/src/style.ts +33 -0
  54. package/src/test/index.ts +5 -15
  55. package/src/unrenderable.ts +35 -0
@@ -5,6 +5,7 @@ import type { BunPlugin } from 'bun'
5
5
  import type { BuildManifest } from './index'
6
6
  import { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
7
7
  import { join } from 'node:path'
8
+ import { formatBunBuildLogs } from './files'
8
9
 
9
10
  export interface CompileExecutableOptions {
10
11
  root: string
@@ -21,7 +22,10 @@ export interface CompileExecutableOptions {
21
22
  export async function compileExecutable(opts: CompileExecutableOptions): Promise<void> {
22
23
  const { root, outDir, clientDir, manifest, assetPrefix, outfile, kaySrcRoot, resolveKaySpecifier, bunPlugins = [] } = opts
23
24
  const entryPath = join(outDir, '__compile_entry.ts')
24
- const imports: string[] = []
25
+ const prodEnvPath = join(outDir, '__compile_prod_env.ts')
26
+ // Evaluated first via ESM static import order so `kay.config.ts` and route modules see NODE_ENV=production!
27
+ writeFileSync(prodEnvPath, `const _envKey = 'NODE_ENV';\nprocess.env[_envKey] ??= 'production';\n`)
28
+ const imports: string[] = [`import ${JSON.stringify(prodEnvPath)};`]
25
29
  const modEntries: string[] = []
26
30
  const seenFiles = new Set<string>()
27
31
  let idx = 0
@@ -40,6 +44,7 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
40
44
  for (const l of r.layouts) addMod(l)
41
45
  for (const m of r.middlewares) addMod(m)
42
46
  }
47
+ if (manifest.rootLayoutFile) addMod(manifest.rootLayoutFile)
43
48
  if (manifest.errorFile) addMod(manifest.errorFile)
44
49
  if (manifest.notFoundFile) addMod(manifest.notFoundFile)
45
50
  for (const a of manifest.actions) {
@@ -47,7 +52,9 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
47
52
  for (const m of a.middlewares) addMod(m)
48
53
  }
49
54
 
50
- const configPath = join(root, 'kay.config.ts')
55
+ const configPath = manifest.configFile !== undefined
56
+ ? join(outDir, manifest.configFile)
57
+ : join(root, 'kay.config.ts')
51
58
  const hasConfig = existsSync(configPath)
52
59
  if (hasConfig)
53
60
  imports.push(`import _kayConfig from ${JSON.stringify(configPath)};`)
@@ -93,26 +100,23 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
93
100
  }
94
101
  }
95
102
 
96
- const cfgSpread = hasConfig
97
- ? `, plugins: _kayConfig?.plugins, lang: _kayConfig?.lang, security: _kayConfig?.security, trustedOrigins: _kayConfig?.trustedOrigins, trustProxy: _kayConfig?.trustProxy, maxRequestBodySize: _kayConfig?.maxRequestBodySize, compress: _kayConfig?.compress, onError: _kayConfig?.onError`
98
- : ''
103
+ const cfgExpr = hasConfig
104
+ ? `resolveServerConfig(_kayConfig, { assetPrefix: ${JSON.stringify(assetPrefix)} })`
105
+ : `{ assetPrefix: ${JSON.stringify(assetPrefix)} }`
99
106
 
100
- // Default NODE_ENV to 'production' in compiled binaries (dynamic key avoids Bun.build constant-folding).
101
107
  const code = [
102
- `import { createServerFromEmbedded } from ${JSON.stringify(join(kaySrcRoot, 'server/index.ts'))};`,
103
108
  ...imports,
104
- `const _envKey = 'NODE_ENV'; process.env[_envKey] ??= 'production';`,
109
+ `import { createServerFromEmbedded, resolveServerConfig } from ${JSON.stringify(join(kaySrcRoot, 'server/index.ts'))};`,
105
110
  `const manifest = ${JSON.stringify(manifest)};`,
106
111
  `const modules = { ${modEntries.join(', ')} };`,
107
112
  `const assets = { ${embeddedAssets.join(', ')} };`,
108
113
  `const publicAssets = { ${embeddedPublic.join(', ')} };`,
109
114
  `const publicEtags = { ${embeddedPublicEtags.join(', ')} };`,
110
- `const prerendered = {};`,
111
115
  `const prerenderedFiles = { ${embeddedPrerenderedFiles.join(', ')} };`,
112
- `const port = Number(process.env.PORT ?? ${hasConfig ? '_kayConfig?.port ?? ' : ''}3000);`,
116
+ `const port = Number(process.env.PORT || ${hasConfig ? '_kayConfig?.port || ' : ''}3000);`,
113
117
  `const hostname = process.env.HOST || undefined;`,
114
- `if (Bun.argv.includes('--health')) { const r = await fetch(\`http://\${hostname ?? '127.0.0.1'}:\${port}/\`).catch(() => null); process.exit(r && r.status < 500 ? 0 : 1); }`,
115
- `const app = await createServerFromEmbedded({ manifest, modules, assets, publicAssets, publicEtags, prerendered, prerenderedFiles, assetPrefix: ${JSON.stringify(assetPrefix)}${cfgSpread} });`,
118
+ `if (Bun.argv.includes('--health')) { const probeHost = !hostname || hostname === '0.0.0.0' || hostname === '::' ? '127.0.0.1' : hostname; const r = await fetch(\`http://\${probeHost}:\${port}/\`).catch(() => null); process.exit(r && r.status < 500 ? 0 : 1); }`,
119
+ `const app = await createServerFromEmbedded({ ...${cfgExpr}, manifest, modules, assets, publicAssets, publicEtags, prerenderedFiles });`,
116
120
  `const server = app.serve(port, hostname);`,
117
121
  `console.log(\`kay server listening on http://\${hostname ?? 'localhost'}:\${server.port}\`);`,
118
122
  ].join('\n')
@@ -128,18 +132,27 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
128
132
  })
129
133
  },
130
134
  }
131
- const res = await Bun.build({
132
- entrypoints: [entryPath],
133
- compile: { outfile },
134
- minify: true,
135
- plugins: [kayResolvePlugin, ...bunPlugins],
136
- })
135
+ let res: Awaited<ReturnType<typeof Bun.build>>
136
+ try {
137
+ res = await Bun.build({
138
+ entrypoints: [entryPath],
139
+ compile: { outfile },
140
+ minify: true,
141
+ plugins: [kayResolvePlugin, ...bunPlugins],
142
+ })
143
+ }
144
+ catch (err) {
145
+ if (err instanceof AggregateError && err.errors.length > 0)
146
+ throw new Error(`kay build --compile failed:\n${formatBunBuildLogs(err.errors, root)}`)
147
+ throw err
148
+ }
137
149
  if (!res.success) {
138
- const msgs = res.logs.map(l => l.message).join('\n')
150
+ const msgs = formatBunBuildLogs(res.logs, root)
139
151
  throw new Error(`kay build --compile failed:\n${msgs}`)
140
152
  }
141
153
  }
142
154
  finally {
143
155
  rmSync(entryPath, { force: true })
156
+ rmSync(prodEnvPath, { force: true })
144
157
  }
145
158
  }
@@ -0,0 +1,174 @@
1
+ // File-system helpers of the build: directory walks, the outDir safety check, and precompressed sidecars.
2
+
3
+ import type { Dirent } from 'node:fs'
4
+ import { existsSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync } from 'node:fs'
5
+ import { tmpdir } from 'node:os'
6
+ import { dirname, extname, isAbsolute, join, relative, resolve } from 'node:path'
7
+ import { brotliCompressSync, constants as zlibConstants } from 'node:zlib'
8
+
9
+ const TEST_FILE_RE = /\.(?:test|spec)\.(?:tsx|ts)$/
10
+ const BACKSLASH_RE = /\\/g
11
+ const COMPRESSIBLE_EXTS = new Set(['.html', '.js', '.mjs', '.css', '.svg', '.xml', '.json', '.txt', '.webmanifest', '.wasm'])
12
+
13
+ /** `relative(from, to)` with forward slashes, the form manifests and messages use. */
14
+ export function relPosix(from: string, to: string): string {
15
+ return relative(from, to).replace(BACKSLASH_RE, '/')
16
+ }
17
+
18
+ export function isTsFile(file: string): boolean {
19
+ return file.endsWith('.tsx') || file.endsWith('.ts')
20
+ }
21
+
22
+ /** The size of a file in bytes, or undefined when it does not exist. */
23
+ export function fileSize(file: string): number | undefined {
24
+ try {
25
+ return statSync(file).size
26
+ }
27
+ catch {
28
+ return undefined
29
+ }
30
+ }
31
+
32
+ interface WalkOptions {
33
+ skipDir?: (name: string) => boolean
34
+ keep?: (entry: Dirent) => boolean
35
+ }
36
+
37
+ /** Every kept file under `dir`, depth first; a missing `dir` is empty. */
38
+ export function walkFiles(dir: string, options: WalkOptions = {}, out: string[] = []): string[] {
39
+ if (!existsSync(dir))
40
+ return out
41
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
42
+ const full = join(dir, entry.name)
43
+ if (entry.isDirectory()) {
44
+ if (options.skipDir?.(entry.name) !== true)
45
+ walkFiles(full, options, out)
46
+ }
47
+ else if (options.keep === undefined || options.keep(entry)) {
48
+ out.push(full)
49
+ }
50
+ }
51
+ return out
52
+ }
53
+
54
+ /** Route sources: `.ts`/`.tsx` outside `_`-prefixed folders, without declarations and tests. */
55
+ export function walkRoutes(dir: string): string[] {
56
+ return walkFiles(dir, {
57
+ skipDir: name => name.startsWith('_'),
58
+ keep: entry => isTsFile(entry.name) && !entry.name.endsWith('.d.ts') && !TEST_FILE_RE.test(entry.name),
59
+ })
60
+ }
61
+
62
+ export function walkAllFiles(dir: string): string[] {
63
+ return walkFiles(dir, { keep: entry => entry.isFile() })
64
+ }
65
+
66
+ function isOutside(base: string, target: string): boolean {
67
+ const rel = relative(base, target)
68
+ return rel === '..' || rel.startsWith('../') || rel.startsWith('..\\') || isAbsolute(rel)
69
+ }
70
+
71
+ function isStrictDescendant(base: string, target: string): boolean {
72
+ return relative(base, target) !== '' && !isOutside(base, target)
73
+ }
74
+
75
+ export function isOutsideRoot(root: string, outDir: string): boolean {
76
+ const rel = relative(root, outDir)
77
+ return rel !== '' && (rel.startsWith('..') || isAbsolute(rel))
78
+ }
79
+
80
+ export function assertSafeOutDir(root: string, outDir: string, routesDir: string, publicDir: string): void {
81
+ // Refuse filesystem root, home dir, tmpdir root, or root/ancestors of root
82
+ if (dirname(outDir) === outDir || outDir === tmpdir() || outDir === resolve(process.env.HOME ?? '\0')) {
83
+ throw new Error(`kay build: refusing unsafe outDir "${outDir}" — cannot wipe a root or shared system directory.`)
84
+ }
85
+ if (!isOutside(outDir, root)) {
86
+ throw new Error(`kay build: refusing unsafe outDir "${outDir}" — outDir cannot be or contain project root "${root}".`)
87
+ }
88
+ if (existsSync(outDir)) {
89
+ try {
90
+ const realRoot = realpathSync(root)
91
+ const realOut = realpathSync(outDir)
92
+ if (dirname(realOut) === realOut || !isOutside(realOut, realRoot)) {
93
+ throw new Error(`kay build: refusing unsafe outDir "${outDir}" — resolved target "${realOut}" is or contains project root "${realRoot}".`)
94
+ }
95
+ }
96
+ catch (err) {
97
+ if (err instanceof Error && err.message.startsWith('kay build: refusing unsafe outDir'))
98
+ throw err
99
+ }
100
+ }
101
+ const protectedTargets: [string, string][] = [
102
+ ['src', resolve(root, 'src')],
103
+ ['routesDir', routesDir],
104
+ ['publicDir', publicDir],
105
+ ['kay.config.ts', resolve(root, 'kay.config.ts')],
106
+ ['package.json', resolve(root, 'package.json')],
107
+ ]
108
+ for (const [label, target] of protectedTargets) {
109
+ if (!isOutside(outDir, target)) {
110
+ throw new Error(`kay build: refusing unsafe outDir "${outDir}" — it equals or contains protected path ${label} ("${target}").`)
111
+ }
112
+ }
113
+ // If outDir is outside root (e.g. an external temp build dir), refuse it if it looks like another project directory.
114
+ if (!isStrictDescendant(root, outDir) && existsSync(outDir)) {
115
+ for (const marker of ['package.json', 'kay.config.ts', 'src']) {
116
+ if (existsSync(join(outDir, marker))) {
117
+ throw new Error(`kay build: refusing unsafe external outDir "${outDir}" — it contains "${marker}".`)
118
+ }
119
+ }
120
+ }
121
+ }
122
+
123
+ /** Writes `.br` and `.gz` sidecars next to a compressible file of at least `minBytes`, when they come out smaller. */
124
+ export function precompressFile(abs: string, minBytes: number): void {
125
+ if (!COMPRESSIBLE_EXTS.has(extname(abs).toLowerCase()))
126
+ return
127
+ const raw = readFileSync(abs)
128
+ if (raw.byteLength < minBytes)
129
+ return
130
+ const br = brotliCompressSync(raw, { params: { [zlibConstants.BROTLI_PARAM_QUALITY]: 6 } })
131
+ if (br.byteLength < raw.byteLength)
132
+ writeFileSync(`${abs}.br`, br)
133
+ const gz = Bun.gzipSync(raw, { level: 9 })
134
+ if (gz.byteLength < raw.byteLength)
135
+ writeFileSync(`${abs}.gz`, gz)
136
+ }
137
+
138
+ export interface BunBuildLogLike {
139
+ message?: string | undefined
140
+ level?: string | undefined
141
+ position?: {
142
+ file?: string | undefined
143
+ line?: number | undefined
144
+ column?: number | undefined
145
+ length?: number | undefined
146
+ lineText?: string | undefined
147
+ } | null | undefined
148
+ }
149
+
150
+ /** Formats Bun `BuildMessage` / `ResolveMessage` logs with `file:line:col: error|warning: <message>` and a source line frame. */
151
+ export function formatBunBuildLogs(logs: readonly unknown[], root?: string): string {
152
+ return logs.map((raw) => {
153
+ if (raw === null || typeof raw !== 'object')
154
+ return String(raw)
155
+ const log = raw as BunBuildLogLike
156
+ const msg = typeof log.message === 'string' && log.message.length > 0 ? log.message : String(raw)
157
+ const pos = log.position
158
+ if (pos && typeof pos.file === 'string' && pos.file.length > 0 && typeof pos.line === 'number') {
159
+ const file = root !== undefined && isAbsolute(pos.file) ? relPosix(root, pos.file) : pos.file
160
+ const col = typeof pos.column === 'number' && pos.column > 0 ? pos.column : 1
161
+ const severity = log.level === 'warning' ? 'warning' : 'error'
162
+ const header = `${file}:${pos.line}:${col}: ${severity}: ${msg}`
163
+ if (typeof pos.lineText === 'string') {
164
+ const lineStr = String(pos.line)
165
+ const pad = ' '.repeat(lineStr.length)
166
+ const maxSpan = Math.max(1, pos.lineText.length - (col - 1))
167
+ const len = typeof pos.length === 'number' && pos.length > 0 ? Math.min(pos.length, maxSpan) : 1
168
+ return `${header}\n ${lineStr} | ${pos.lineText}\n ${pad} | ${' '.repeat(Math.max(0, col - 1))}${'^'.repeat(len)}`
169
+ }
170
+ return header
171
+ }
172
+ return msg
173
+ }).join('\n')
174
+ }
@@ -0,0 +1,223 @@
1
+ // The module graph of one build: every .ts/.tsx file reachable from the routes, analyzed once (and reused across `kay 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 { isTsFile } from './files'
7
+ import { resolveImportPath } from './resolve'
8
+
9
+ export interface FileStamp {
10
+ mtimeMs: number
11
+ size: number
12
+ }
13
+
14
+ export interface CachedClientBuild {
15
+ signature: string
16
+ clientDir: string
17
+ inputStamps: Map<string, FileStamp>
18
+ islandChunks: Map<string, string>
19
+ srcCssToUrl: Map<string, string>
20
+ islandCssUrl: Map<string, string>
21
+ assetFiles: string[]
22
+ styleUrls: string[]
23
+ runtimeScript: string | undefined
24
+ }
25
+
26
+ export interface CachedServerBuild {
27
+ signature: string
28
+ serverDir: string
29
+ inputStamps: Map<string, FileStamp>
30
+ }
31
+
32
+ export interface BuildCacheStats {
33
+ clientBuilds: number
34
+ clientSkips: number
35
+ serverBuilds: number
36
+ serverSkips: number
37
+ }
38
+
39
+ export interface BuildCache {
40
+ analyses: Map<string, FileStamp & { code: string, analysis: ModuleAnalysis }>
41
+ domCompiled: Map<string, FileStamp & { key?: string | undefined, code: string }>
42
+ ssrCompiled: Map<string, FileStamp & { key: string, code: string }>
43
+ lastClient?: CachedClientBuild | undefined
44
+ lastServer?: CachedServerBuild | undefined
45
+ watchedFiles: Set<string>
46
+ stats: BuildCacheStats
47
+ }
48
+
49
+ export function createBuildCache(): BuildCache {
50
+ return {
51
+ analyses: new Map(),
52
+ domCompiled: new Map(),
53
+ ssrCompiled: new Map(),
54
+ watchedFiles: new Set(),
55
+ stats: { clientBuilds: 0, clientSkips: 0, serverBuilds: 0, serverSkips: 0 },
56
+ }
57
+ }
58
+
59
+ export function clearBuildCache(cache: BuildCache): void {
60
+ cache.analyses.clear()
61
+ cache.domCompiled.clear()
62
+ cache.ssrCompiled.clear()
63
+ cache.lastClient = undefined
64
+ cache.lastServer = undefined
65
+ cache.watchedFiles.clear()
66
+ }
67
+
68
+ export function stampFiles(files: Iterable<string>): Map<string, FileStamp> {
69
+ const out = new Map<string, FileStamp>()
70
+ for (const file of files) {
71
+ if (out.has(file))
72
+ continue
73
+ try {
74
+ const st = statSync(file)
75
+ if (st.isFile())
76
+ out.set(file, { mtimeMs: st.mtimeMs, size: st.size })
77
+ }
78
+ catch {}
79
+ }
80
+ return out
81
+ }
82
+
83
+ export function stampsMatch(inputStamps: ReadonlyMap<string, FileStamp>): boolean {
84
+ for (const [file, prev] of inputStamps) {
85
+ if (!existsSync(file))
86
+ return false
87
+ try {
88
+ const st = statSync(file)
89
+ if (st.mtimeMs !== prev.mtimeMs || st.size !== prev.size)
90
+ return false
91
+ }
92
+ catch {
93
+ return false
94
+ }
95
+ }
96
+ return true
97
+ }
98
+
99
+ const MAX_REEXPORT_DEPTH = 8
100
+
101
+ export class ModuleGraph {
102
+ readonly analyses = new Map<string, ModuleAnalysis>()
103
+ private readonly sources = new Map<string, string>()
104
+ private readonly stamps = new Map<string, FileStamp>()
105
+ private readonly resolved = new Map<string, string | undefined>()
106
+ private readonly deps = new Map<string, string[]>()
107
+
108
+ constructor(private readonly cache?: BuildCache) {}
109
+
110
+ /** The file's mtime and size; only tracked when a cache is in use. */
111
+ stamp(file: string): FileStamp | undefined {
112
+ const known = this.stamps.get(file)
113
+ if (known !== undefined || this.cache === undefined)
114
+ return known
115
+ try {
116
+ const st = statSync(file)
117
+ const stamp = { mtimeMs: st.mtimeMs, size: st.size }
118
+ this.stamps.set(file, stamp)
119
+ return stamp
120
+ }
121
+ catch {
122
+ return undefined
123
+ }
124
+ }
125
+
126
+ /** The text of a file, read once per build. */
127
+ source(file: string): string {
128
+ let code = this.sources.get(file)
129
+ if (code === undefined) {
130
+ code = readFileSync(file, 'utf8')
131
+ this.sources.set(file, code)
132
+ }
133
+ return code
134
+ }
135
+
136
+ /** `resolveImportPath`, remembered for the build. */
137
+ resolve(from: string, specifier: string): string | undefined {
138
+ const key = `${from}\0${specifier}`
139
+ if (this.resolved.has(key))
140
+ return this.resolved.get(key)
141
+ const target = resolveImportPath(from, specifier)
142
+ this.resolved.set(key, target)
143
+ return target
144
+ }
145
+
146
+ /** The .ts/.tsx modules a loaded file imports or re-exports from. */
147
+ localDeps(file: string): string[] {
148
+ let list = this.deps.get(file)
149
+ if (list === undefined) {
150
+ list = []
151
+ const analysis = this.analyses.get(file)
152
+ for (const { source } of [...(analysis?.imports ?? []), ...(analysis?.reexports ?? [])]) {
153
+ const target = this.resolve(file, source)
154
+ if (target !== undefined && isTsFile(target))
155
+ list.push(target)
156
+ }
157
+ if (analysis !== undefined)
158
+ this.deps.set(file, list)
159
+ }
160
+ return list
161
+ }
162
+
163
+ /** Analyzes `file` and everything it imports. */
164
+ load(file: string): ModuleAnalysis {
165
+ const existing = this.analyses.get(file)
166
+ if (existing !== undefined)
167
+ return existing
168
+ const stamp = this.stamp(file)
169
+ const cached = stamp === undefined ? undefined : this.cache?.analyses.get(file)
170
+ let analysis: ModuleAnalysis
171
+ if (cached !== undefined && cached.mtimeMs === stamp!.mtimeMs && cached.size === stamp!.size) {
172
+ analysis = cached.analysis
173
+ this.sources.set(file, cached.code)
174
+ }
175
+ else {
176
+ const code = this.source(file)
177
+ analysis = analyzeModule(file, code)
178
+ if (this.cache !== undefined && stamp !== undefined)
179
+ this.cache.analyses.set(file, { mtimeMs: stamp.mtimeMs, size: stamp.size, code, analysis })
180
+ }
181
+ this.analyses.set(file, analysis)
182
+ for (const dep of this.localDeps(file))
183
+ this.load(dep)
184
+ return analysis
185
+ }
186
+
187
+ /** Follows `export { x } from './y'` and `export * from './y'` chains to the module that declares the export. */
188
+ exportTarget(file: string, exportName: string, depth = 0, seen = new Set<string>()): { file: string, exportName: string } {
189
+ if (depth > MAX_REEXPORT_DEPTH)
190
+ return { file, exportName }
191
+ const key = `${file}\0${exportName}`
192
+ if (seen.has(key))
193
+ return { file, exportName }
194
+ seen.add(key)
195
+
196
+ const analysis = this.load(file)
197
+ const direct = analysis.reexports.find(r => r.exported === exportName)
198
+ if (direct !== undefined) {
199
+ const next = this.resolve(file, direct.source)
200
+ if (next !== undefined && isTsFile(next))
201
+ return this.exportTarget(next, direct.local, depth + 1, seen)
202
+ }
203
+
204
+ if (analysis.exportedNames.includes(exportName))
205
+ return { file, exportName }
206
+
207
+ // Follow `export * from './y'` barrel re-exports (named exports only, per ESM spec `export *` never re-exports `default`).
208
+ if (exportName !== 'default') {
209
+ for (const re of analysis.reexports) {
210
+ if (re.exported !== '*')
211
+ continue
212
+ const next = this.resolve(file, re.source)
213
+ if (next === undefined || !isTsFile(next))
214
+ continue
215
+ const candidate = this.exportTarget(next, exportName, depth + 1, seen)
216
+ if (this.load(candidate.file).exportedNames.includes(candidate.exportName))
217
+ return candidate
218
+ }
219
+ }
220
+
221
+ return { file, exportName }
222
+ }
223
+ }