@kayjs/kay 2.0.0-beta.0 → 2.0.0-beta.1

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 +442 -0
  4. package/src/build/compile.ts +10 -10
  5. package/src/build/files.ts +136 -0
  6. package/src/build/graph.ts +158 -0
  7. package/src/build/index.ts +204 -1460
  8. package/src/build/islands.ts +177 -0
  9. package/src/build/manifest.ts +224 -0
  10. package/src/build/plugin-host.ts +184 -0
  11. package/src/build/prerender.ts +93 -0
  12. package/src/build/report.ts +157 -0
  13. package/src/build/resolve.ts +58 -0
  14. package/src/build/routes.ts +135 -0
  15. package/src/build/static.ts +73 -0
  16. package/src/cli/check.ts +228 -114
  17. package/src/cli/index.ts +297 -94
  18. package/src/cli/new.ts +53 -32
  19. package/src/compiler/analyze.ts +666 -91
  20. package/src/compiler/dom.ts +808 -743
  21. package/src/compiler/mistakes.ts +354 -0
  22. package/src/compiler/patch.ts +1 -1
  23. package/src/compiler/server-only.ts +164 -21
  24. package/src/compiler/shared.ts +442 -0
  25. package/src/compiler/ssr.ts +329 -342
  26. package/src/context.ts +120 -0
  27. package/src/dev/index.ts +271 -75
  28. package/src/dom/action.ts +23 -13
  29. package/src/dom/extras.ts +121 -83
  30. package/src/dom/index.ts +114 -77
  31. package/src/dom/island.ts +71 -36
  32. package/src/dom/loop.ts +28 -20
  33. package/src/index.ts +2 -1
  34. package/src/jsx-runtime.ts +11 -0
  35. package/src/plugins/context.ts +57 -0
  36. package/src/plugins/index.ts +114 -18
  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 +147 -76
  41. package/src/server/compress.ts +116 -96
  42. package/src/server/cookies.ts +46 -16
  43. package/src/server/env.ts +18 -13
  44. package/src/server/http.ts +107 -54
  45. package/src/server/index.ts +887 -870
  46. package/src/server/loader.ts +120 -0
  47. package/src/server/router.ts +22 -8
  48. package/src/server/security.ts +48 -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 +2 -1
  55. package/src/unrenderable.ts +35 -0
package/src/cli/check.ts CHANGED
@@ -1,51 +1,48 @@
1
- // `kay check [dir]`: validates routes, Kay compiler & island rules, config, and runs TypeScript type-checking.
1
+ // `kay check [dir]`: validates routes, Kay compiler & island rules (unified with `kay build`), config, and TypeScript types.
2
2
 
3
- import type { AstNode, ModuleAnalysis } from '../compiler/analyze'
4
- import { existsSync, readdirSync, readFileSync } from 'node:fs'
5
- import { basename, dirname, join, relative, resolve } from 'node:path'
3
+ import type { ModuleAnalysis } from '../compiler/analyze'
4
+ import { existsSync, readFileSync } from 'node:fs'
5
+ import { basename, join, relative, resolve } from 'node:path'
6
+ import { isTsFile, relPosix, walkFiles, walkRoutes } from '../build/files'
7
+ import { ModuleGraph } from '../build/graph'
8
+ import { fileToRoutePath, hasRouteHandlerExport, normalizeRoutePattern, routeExportProblem, SPECIAL_ROUTE_FILES } from '../build/routes'
6
9
  import { analyzeModule, walk } from '../compiler/analyze'
7
10
  import { readsPrivateEnv, SERVER_ONLY_MODULES } from '../compiler/server-only'
8
- import { loadConfig } from '../plugins/index'
11
+ import { jsxTagName } from '../compiler/shared'
12
+ import { createAppContext, loadConfig, runWithAppContext } from '../plugins/index'
9
13
 
10
14
  export interface CheckResult {
11
15
  ok: boolean
12
16
  checkedFiles: number
13
17
  errors: string[]
18
+ warnings: string[]
14
19
  }
15
20
 
16
21
  const SERIALIZABLE_NEW_CTORS = new Set(['Date', 'Map', 'Set', 'URL', 'RegExp'])
22
+ const NODE_MODULES_RE = /[\\/]node_modules[\\/]/
17
23
 
18
- function walkTsFiles(dir: string, out: string[] = []): string[] {
19
- if (!existsSync(dir))
20
- return out
21
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
22
- const full = join(dir, entry.name)
23
- if (entry.isDirectory()) {
24
- if (entry.name === 'node_modules' || entry.name === 'dist' || entry.name.startsWith('.'))
25
- continue
26
- walkTsFiles(full, out)
27
- }
28
- else if (entry.name.endsWith('.tsx') || entry.name.endsWith('.ts')) {
29
- out.push(full)
30
- }
31
- }
32
- return out
24
+ function walkTsFiles(dir: string): string[] {
25
+ return walkFiles(dir, {
26
+ skipDir: name => name === 'node_modules' || name === 'dist' || name.startsWith('.'),
27
+ keep: entry => isTsFile(entry.name),
28
+ })
33
29
  }
34
30
 
35
- function resolveLocalModule(fromFile: string, specifier: string): string | undefined {
36
- if (!specifier.startsWith('.'))
37
- return undefined
38
- const base = resolve(dirname(fromFile), specifier)
39
- for (const c of [base, `${base}.tsx`, `${base}.ts`, join(base, 'index.tsx'), join(base, 'index.ts')]) {
40
- if (existsSync(c))
41
- return c
31
+ function analysisOf(file: string, analyses: Map<string, ModuleAnalysis>, unparsable: Set<string>): ModuleAnalysis | undefined {
32
+ if (!analyses.has(file) && !unparsable.has(file) && isTsFile(file)) {
33
+ try {
34
+ analyses.set(file, analyzeModule(file, readFileSync(file, 'utf8')))
35
+ }
36
+ catch {
37
+ unparsable.add(file)
38
+ }
42
39
  }
43
- return undefined
40
+ return analyses.get(file)
44
41
  }
45
42
 
46
43
  // Walks the local imports of an island the way the client build follows them: a module that only declares actions is stubbed there, so its imports stop the walk.
47
- function checkIslandReach(island: string, root: string, analyses: Map<string, ModuleAnalysis>, reported: Set<string>, errors: string[]): void {
48
- const islandRel = relative(root, island).replace(/\\/g, '/')
44
+ function checkIslandReach(island: string, root: string, graph: ModuleGraph, unparsable: Set<string>, reported: Set<string>, errors: string[]): void {
45
+ const islandRel = relPosix(root, island)
49
46
  const seen = new Set<string>()
50
47
  const stack = [island]
51
48
  while (stack.length > 0) {
@@ -53,24 +50,43 @@ function checkIslandReach(island: string, root: string, analyses: Map<string, Mo
53
50
  if (seen.has(file))
54
51
  continue
55
52
  seen.add(file)
56
- const analysis = analyses.get(file)
53
+ if (NODE_MODULES_RE.test(file))
54
+ continue
55
+ const analysis = analysisOf(file, graph.analyses, unparsable)
57
56
  if (analysis === undefined || (file !== island && !analysis.isInteractive && analysis.exportedActions.length > 0))
58
57
  continue
59
- const rel = relative(root, file).replace(/\\/g, '/')
58
+ const rel = relPosix(root, file)
60
59
  const report = (key: string, message: string): void => {
61
60
  if (reported.has(`${file}\0${key}`))
62
61
  return
63
62
  reported.add(`${file}\0${key}`)
64
63
  errors.push(message)
65
64
  }
66
- for (const source of [...analysis.imports.map(i => i.source), ...analysis.reexports.map(r => r.source)]) {
67
- if (SERVER_ONLY_MODULES.has(source)) {
68
- report(source, file === island
69
- ? `kay check: ${rel}: interactive island imports server-only module "${source}". Move server logic to a server action or async server component.`
70
- : `kay check: ${rel}: imports server-only module "${source}" and is reachable from the island in ${islandRel}. Move server logic to a server action or async server component.`)
65
+ for (const imp of analysis.imports) {
66
+ if (SERVER_ONLY_MODULES.has(imp.source)) {
67
+ report(imp.source, file === island
68
+ ? `kay check: ${rel}: interactive island imports server-only module "${imp.source}". Move server logic to a server action or async server component.`
69
+ : `kay check: ${rel}: imports server-only module "${imp.source}" and is reachable from the island in ${islandRel}. Move server logic to a server action or async server component.`)
70
+ continue
71
+ }
72
+ const target = graph.resolve(file, imp.source)
73
+ if (target !== undefined) {
74
+ const targetAnalysis = analysisOf(target, graph.analyses, unparsable)
75
+ if (targetAnalysis !== undefined && !targetAnalysis.isInteractive && targetAnalysis.exportedActions.length > 0) {
76
+ const missing = imp.specifiers.find(s => s.imported !== '*' && !targetAnalysis.exportedActions.includes(s.imported))
77
+ if (missing !== undefined)
78
+ report(`action-export:${target}:${missing.imported}`, `kay check: ${rel}: imports non-action "${missing.imported}" from server action file ${relPosix(root, target)}. Move ${missing.imported} into a module without actions.`)
79
+ continue
80
+ }
81
+ stack.push(target)
82
+ }
83
+ }
84
+ for (const re of analysis.reexports) {
85
+ if (SERVER_ONLY_MODULES.has(re.source)) {
86
+ report(re.source, `kay check: ${rel}: re-exports from server-only module "${re.source}" and is reachable from the island in ${islandRel}.`)
71
87
  continue
72
88
  }
73
- const target = resolveLocalModule(file, source)
89
+ const target = graph.resolve(file, re.source)
74
90
  if (target !== undefined)
75
91
  stack.push(target)
76
92
  }
@@ -79,29 +95,24 @@ function checkIslandReach(island: string, root: string, analyses: Map<string, Mo
79
95
  }
80
96
  }
81
97
 
82
- function normalizeRouteConflictKey(routesDir: string, file: string): string {
83
- const rel = relative(routesDir, file).replace(/\\/g, '/').replace(/\.(tsx|ts)$/, '')
84
- if (rel === 'index')
85
- return '/'
86
- const clean = rel.endsWith('/index') ? rel.slice(0, -'/index'.length) : rel
87
- const norm = clean
88
- .replace(/\[\.\.\.[^\]]+\]/g, '*')
89
- .replace(/\[[^\]]+\]/g, ':')
90
- return `/${norm}`
91
- }
92
-
93
98
  export async function checkProject(rootDir: string, options: { skipTypecheck?: boolean } = {}): Promise<CheckResult> {
94
99
  const root = resolve(rootDir)
95
100
  const errors: string[] = []
96
101
 
97
102
  // 1. Validate kay.config.ts
98
103
  let routesDir = resolve(root, 'src/routes')
104
+ let outDir = resolve(root, 'dist')
105
+ let assetPrefix = '/_kay'
99
106
  let plugins: Awaited<ReturnType<typeof loadConfig>>['plugins'] = []
100
107
  try {
101
108
  const cfg = await loadConfig(root)
102
109
  plugins = cfg.plugins ?? []
103
110
  if (cfg.routesDir !== undefined)
104
111
  routesDir = resolve(root, cfg.routesDir)
112
+ if (cfg.outDir !== undefined)
113
+ outDir = resolve(root, cfg.outDir)
114
+ if (cfg.assetPrefix !== undefined)
115
+ assetPrefix = cfg.assetPrefix.replace(/\/$/, '')
105
116
  }
106
117
  catch (err) {
107
118
  errors.push(`kay.config.ts: ${err instanceof Error ? err.message : String(err)}`)
@@ -111,70 +122,148 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
111
122
  if (!existsSync(routesDir))
112
123
  errors.push(`missing routes directory: ${relative(root, routesDir) || routesDir}`)
113
124
 
114
- // 3. Parse & run Kay static compiler analysis across src/
125
+ // 3. Parse & run Kay static compiler analysis across src/ AND custom routesDir
115
126
  const srcDir = resolve(root, 'src')
116
- const files = walkTsFiles(existsSync(srcDir) ? srcDir : routesDir)
117
- const analyses = new Map<string, ModuleAnalysis>()
127
+ const fileSet = new Set<string>()
128
+ if (existsSync(srcDir)) {
129
+ for (const f of walkTsFiles(srcDir))
130
+ fileSet.add(f)
131
+ }
132
+ if (existsSync(routesDir)) {
133
+ for (const f of walkTsFiles(routesDir))
134
+ fileSet.add(f)
135
+ }
136
+ const files = [...fileSet].sort()
137
+ const graph = new ModuleGraph()
138
+ const { analyses } = graph
139
+ const unparsable = new Set<string>()
118
140
 
141
+ const warnings: string[] = []
119
142
  for (const file of files) {
120
143
  try {
121
- const code = readFileSync(file, 'utf8')
122
- analyses.set(file, analyzeModule(file, code))
144
+ const analysis = analyzeModule(file, readFileSync(file, 'utf8'))
145
+ analyses.set(file, analysis)
146
+ warnings.push(...analysis.warnings)
123
147
  }
124
148
  catch (err) {
149
+ unparsable.add(file)
125
150
  errors.push(err instanceof Error ? err.message : String(err))
126
151
  }
127
152
  }
128
153
 
129
- // 3b. Static guardrails: server-only imports in islands, non-serializable island props, route conflicts, missing paths()
154
+ // 3a. Promote components reading imported reactive state (same rule as `planIslands` in `kay build`)
155
+ for (const [file, analysis] of [...analyses]) {
156
+ if (!file.endsWith('.tsx') || analysis.isInteractive)
157
+ continue
158
+ for (const imp of analysis.imports) {
159
+ const resolved = graph.resolve(file, imp.source)
160
+ if (resolved === undefined || !isTsFile(resolved))
161
+ continue
162
+ const state = imp.specifiers.find((spec) => {
163
+ if (analysis.jsxTags.has(spec.local))
164
+ return false
165
+ try {
166
+ if (spec.imported === '*')
167
+ return (analysisOf(resolved, analyses, unparsable)?.stateExports.length ?? 0) > 0
168
+ const target = graph.exportTarget(resolved, spec.imported)
169
+ return analysisOf(target.file, analyses, unparsable)?.stateExports.includes(target.exportName) === true
170
+ }
171
+ catch {
172
+ return false
173
+ }
174
+ })
175
+ if (state !== undefined) {
176
+ const reason = `reads ${state.local} from '${imp.source}'`
177
+ if (analysis.hasAsyncDefault)
178
+ errors.push(`kay check: async route component in ${relPosix(root, file)} cannot use browser interactivity (${reason}).`)
179
+ else
180
+ analyses.set(file, { ...analysis, isInteractive: true, interactiveReason: reason })
181
+ break
182
+ }
183
+ }
184
+ }
185
+
186
+ // Exact route discovery matching `kay build` (`walkRoutes` skips `_components/` dirs, `.d.ts`, `.test.ts`)
187
+ const routeFiles = existsSync(routesDir) ? walkRoutes(routesDir).sort() : []
188
+ const routeFileSet = new Set(routeFiles)
189
+
190
+ // 3b. Static guardrails: server-only imports in islands, non-serializable island props, special files, route conflicts, missing paths()
130
191
  const seenRoutes = new Map<string, string>()
131
192
  const reported = new Set<string>()
132
193
 
133
- for (const [file, analysis] of analyses) {
134
- const rel = relative(root, file).replace(/\\/g, '/')
194
+ for (const [file, analysis] of [...analyses]) {
195
+ const rel = relPosix(root, file)
196
+
197
+ // Special route files (`_layout.tsx`, `_error.tsx`, `_404.tsx`) cannot be interactive
198
+ if (routeFileSet.has(file) && SPECIAL_ROUTE_FILES.has(basename(file)) && analysis.isInteractive) {
199
+ errors.push(`kay check: ${rel} uses browser interactivity (${analysis.interactiveReason}), but it renders on the server only. Move the interactive part into a component and render that component from ${rel}.`)
200
+ }
135
201
 
136
202
  // Guardrail 1: server-only imports and private env reads in an island or any module it imports
137
203
  if (analysis.isInteractive)
138
- checkIslandReach(file, root, analyses, reported, errors)
204
+ checkIslandReach(file, root, graph, unparsable, reported, errors)
139
205
 
140
- // Guardrail 2: non-serializable props (functions / unsupported class instances) passed from static server code into an island
206
+ // Guardrail 2: non-serializable props passed from static server code into an island (including barrels & namespaces)
141
207
  if (!analysis.isInteractive && file.endsWith('.tsx')) {
142
208
  const islandTags = new Set<string>()
209
+ const islandNamespaces = new Map<string, string>() // localNs -> resolved file
143
210
  for (const imp of analysis.imports) {
144
- const target = resolveLocalModule(file, imp.source)
145
- if (target === undefined)
211
+ const resolved = graph.resolve(file, imp.source)
212
+ if (resolved === undefined || !isTsFile(resolved))
146
213
  continue
147
- const targetAnalysis = analyses.get(target)
148
- if (targetAnalysis?.isInteractive) {
149
- for (const spec of imp.specifiers)
150
- islandTags.add(spec.local)
214
+ for (const spec of imp.specifiers) {
215
+ if (spec.imported === '*') {
216
+ islandNamespaces.set(spec.local, resolved)
217
+ continue
218
+ }
219
+ try {
220
+ const target = graph.exportTarget(resolved, spec.imported)
221
+ if (analysisOf(target.file, analyses, unparsable)?.isInteractive)
222
+ islandTags.add(spec.local)
223
+ }
224
+ catch {}
225
+ }
226
+ }
227
+
228
+ const isIslandTag = (tag: string): boolean => {
229
+ if (islandTags.has(tag))
230
+ return true
231
+ if (tag.includes('.')) {
232
+ const [ns, member] = tag.split('.')
233
+ const nsFile = ns !== undefined ? islandNamespaces.get(ns) : undefined
234
+ if (nsFile !== undefined && member !== undefined) {
235
+ try {
236
+ const target = graph.exportTarget(nsFile, member)
237
+ return analysisOf(target.file, analyses, unparsable)?.isInteractive === true
238
+ }
239
+ catch {}
240
+ }
151
241
  }
242
+ return false
152
243
  }
153
244
 
154
- if (islandTags.size > 0) {
155
- walk(analysis.program, (node: AstNode) => {
156
- if (node.type !== 'JSXOpeningElement' || node.name?.type !== 'JSXIdentifier')
245
+ if (islandTags.size > 0 || islandNamespaces.size > 0) {
246
+ walk(analysis.program, (node) => {
247
+ if (node.type !== 'JSXOpeningElement')
157
248
  return
158
- const tag = node.name.name as string
159
- if (!islandTags.has(tag))
249
+ const tag = jsxTagName(node.name)
250
+ if (!isIslandTag(tag))
160
251
  return
161
- for (const attr of (node.attributes ?? []) as AstNode[]) {
162
- if (attr.type !== 'JSXAttribute' || attr.name?.type !== 'JSXIdentifier')
252
+ for (const attr of node.attributes) {
253
+ if (attr.type !== 'JSXAttribute' || attr.name.type !== 'JSXIdentifier')
163
254
  continue
164
- const attrName = attr.name.name as string
255
+ const attrName = attr.name.name
165
256
  if (attrName === 'key' || attrName === '$hydrate')
166
257
  continue
167
- if (attr.value?.type !== 'JSXExpressionContainer')
168
- continue
169
- const expr = attr.value.expression as AstNode | undefined
170
- if (expr === undefined)
258
+ if (attr.value?.type !== 'JSXExpressionContainer' || attr.value.expression.type === 'JSXEmptyExpression')
171
259
  continue
260
+ const expr = attr.value.expression
172
261
  if (expr.type === 'ArrowFunctionExpression' || expr.type === 'FunctionExpression') {
173
262
  errors.push(
174
263
  `kay check: ${rel}: cannot pass function prop "${attrName}" from a server component into island <${tag}>. Define the handler inside the island or pass serializable data.`,
175
264
  )
176
265
  }
177
- else if (expr.type === 'NewExpression' && expr.callee?.type === 'Identifier' && !SERIALIZABLE_NEW_CTORS.has(expr.callee.name as string)) {
266
+ else if (expr.type === 'NewExpression' && expr.callee.type === 'Identifier' && !SERIALIZABLE_NEW_CTORS.has(expr.callee.name)) {
178
267
  errors.push(
179
268
  `kay check: ${rel}: cannot pass non-serializable \`new ${expr.callee.name}()\` prop "${attrName}" into island <${tag}>.`,
180
269
  )
@@ -184,28 +273,39 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
184
273
  }
185
274
  }
186
275
 
187
- // Route-specific guardrails
188
- const relFromRoutes = relative(routesDir, file)
189
- const isRouteFile = !relFromRoutes.startsWith('..') && !basename(file).startsWith('_')
190
- if (isRouteFile) {
191
- const conflictKey = normalizeRouteConflictKey(routesDir, file)
192
- const prev = seenRoutes.get(conflictKey)
193
- if (prev !== undefined) {
194
- errors.push(`kay check: conflicting routes "${prev}" and "${rel}" both match "${conflictKey}".`)
195
- }
196
- else {
197
- seenRoutes.set(conflictKey, rel)
198
- }
276
+ // Route-specific guardrails (only real route files matching `kay build`)
277
+ if (routeFileSet.has(file) && !basename(file).startsWith('_')) {
278
+ const problem = routeExportProblem(analysis, rel)
279
+ if (problem !== undefined)
280
+ errors.push(`kay check: ${problem}`)
281
+
282
+ if (hasRouteHandlerExport(analysis)) {
283
+ const conflictKey = normalizeRoutePattern(fileToRoutePath(routesDir, file))
284
+ const prev = seenRoutes.get(conflictKey)
285
+ if (prev !== undefined) {
286
+ errors.push(`kay check: conflicting routes "${prev}" and "${rel}" both match "${conflictKey}".`)
287
+ }
288
+ else {
289
+ seenRoutes.set(conflictKey, rel)
290
+ }
199
291
 
200
- // Guardrail 4: dynamic prerender = true route missing paths()
201
- if (analysis.hasPrerender && (conflictKey.includes(':') || conflictKey.includes('*')) && !analysis.hasPaths) {
202
- errors.push(`kay check: ${rel}: dynamic route exports \`prerender = true\` without exporting \`paths()\`.`)
292
+ // Guardrail 4: dynamic prerender = true route missing paths()
293
+ if (analysis.hasPrerender && (conflictKey.includes(':') || conflictKey.includes('*')) && !analysis.hasPaths) {
294
+ errors.push(`kay check: ${rel}: dynamic route exports \`prerender = true\` without exporting \`paths()\`.`)
295
+ }
203
296
  }
204
297
  }
205
298
  }
206
299
 
207
- // 3c. Run plugin check(ctx) hooks
300
+ // 3c. Run plugin check(ctx) hooks inside a real AppRuntimeContext
208
301
  if (plugins && plugins.length > 0) {
302
+ const appCtx = createAppContext({
303
+ root,
304
+ outDir,
305
+ publicDir: join(outDir, 'public'),
306
+ assetPrefix,
307
+ dev: false,
308
+ })
209
309
  const pluginCtx = {
210
310
  root,
211
311
  routesDir,
@@ -216,7 +316,7 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
216
316
  for (const plugin of plugins) {
217
317
  if (plugin.check !== undefined) {
218
318
  try {
219
- await plugin.check(pluginCtx)
319
+ await runWithAppContext(appCtx, () => plugin.check!(pluginCtx))
220
320
  }
221
321
  catch (err) {
222
322
  errors.push(`${plugin.name}: ${err instanceof Error ? err.message : String(err)}`)
@@ -225,30 +325,44 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
225
325
  }
226
326
  }
227
327
 
228
- // 4. Run TypeScript check (`tsgo` preferred, fallback to `tsc`) when tsconfig.json exists
328
+ // 4. Run TypeScript check (`bun check` preferred, fallback to `tsgo` then `tsc`) when tsconfig.json exists
229
329
  const tsconfigPath = join(root, 'tsconfig.json')
230
330
  if (!options.skipTypecheck && existsSync(tsconfigPath)) {
231
- const candidates = [
232
- join(root, 'node_modules/.bin/tsgo'),
233
- join(root, 'node_modules/.bin/tsc'),
234
- 'tsgo',
235
- 'tsc',
236
- ]
237
- let bin: string | undefined
238
- for (const c of candidates) {
239
- if (c.includes('/') ? existsSync(c) : Bun.which(c) !== null) {
240
- bin = c
241
- break
242
- }
331
+ const bunCheck = Bun.spawnSync([process.execPath, 'check', '--no-script', '-p', tsconfigPath], { cwd: root })
332
+ if (bunCheck.exitCode === 0) {
333
+ // Typecheck passed via built-in `bun check`
243
334
  }
244
- if (bin !== undefined) {
245
- const proc = Bun.spawnSync([bin, '--noEmit', '-p', tsconfigPath], { cwd: root })
246
- if (proc.exitCode !== 0) {
247
- const out = (proc.stdout.toString() + proc.stderr.toString()).trim()
248
- errors.push(out || `${bin} exited with code ${proc.exitCode}`)
335
+ else {
336
+ const bunOut = (bunCheck.stdout.toString() + bunCheck.stderr.toString()).trim()
337
+ // Only fall back to tsgo/tsc if this Bun binary does not support `bun check`
338
+ const unsupported = bunOut.includes('Script not found "check"') || bunOut.includes('Unknown command')
339
+ if (!unsupported) {
340
+ errors.push(bunOut || `bun check exited with code ${bunCheck.exitCode}`)
341
+ }
342
+ else {
343
+ const candidates = [
344
+ join(root, 'node_modules/.bin/tsgo'),
345
+ join(root, 'node_modules/.bin/tsc'),
346
+ 'tsgo',
347
+ 'tsc',
348
+ ]
349
+ let bin: string | undefined
350
+ for (const c of candidates) {
351
+ if (c.includes('/') ? existsSync(c) : Bun.which(c) !== null) {
352
+ bin = c
353
+ break
354
+ }
355
+ }
356
+ if (bin !== undefined) {
357
+ const proc = Bun.spawnSync([bin, '--noEmit', '-p', tsconfigPath], { cwd: root })
358
+ if (proc.exitCode !== 0) {
359
+ const out = (proc.stdout.toString() + proc.stderr.toString()).trim()
360
+ errors.push(out || `${bin} exited with code ${proc.exitCode}`)
361
+ }
362
+ }
249
363
  }
250
364
  }
251
365
  }
252
366
 
253
- return { ok: errors.length === 0, checkedFiles: files.length, errors }
367
+ return { ok: errors.length === 0, checkedFiles: files.length, errors, warnings }
254
368
  }