@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
package/src/cli/check.ts CHANGED
@@ -1,51 +1,93 @@
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, routeExportProblemLocation, SPECIAL_ROUTE_FILES } from '../build/routes'
6
9
  import { analyzeModule, walk } from '../compiler/analyze'
7
- import { readsPrivateEnv, SERVER_ONLY_MODULES } from '../compiler/server-only'
8
- import { loadConfig } from '../plugins/index'
10
+ import { findPrivateEnvOffset, SERVER_ONLY_MODULES } from '../compiler/server-only'
11
+ import { DIAGNOSTIC_PREFIX_RE, formatDiagnostic, formatLoc, jsxTagName } from '../compiler/shared'
12
+ import { createAppContext, loadConfig, resolvePlugins, 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)
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
+ })
29
+ }
30
+
31
+ function sourceOf(file: string, sources: Map<string, string>): string {
32
+ let code = sources.get(file)
33
+ if (code === undefined) {
34
+ code = readFileSync(file, 'utf8')
35
+ sources.set(file, code)
36
+ }
37
+ return code
38
+ }
39
+
40
+ function analysisOf(file: string, analyses: Map<string, ModuleAnalysis>, sources: Map<string, string>, unparsable: Set<string>): ModuleAnalysis | undefined {
41
+ if (!analyses.has(file) && !unparsable.has(file) && isTsFile(file)) {
42
+ try {
43
+ analyses.set(file, analyzeModule(file, sourceOf(file, sources)))
44
+ }
45
+ catch {
46
+ unparsable.add(file)
27
47
  }
28
- else if (entry.name.endsWith('.tsx') || entry.name.endsWith('.ts')) {
29
- out.push(full)
48
+ }
49
+ return analyses.get(file)
50
+ }
51
+
52
+ function locOf(root: string, file: string, sources: Map<string, string>, offset = 0): string {
53
+ const rel = relPosix(root, file)
54
+ const code = sources.get(file)
55
+ return code !== undefined ? formatLoc(rel, code, offset) : `${rel}:1:1`
56
+ }
57
+
58
+ function findExportedConstOffset(analysis: ModuleAnalysis, name: string): number {
59
+ for (const stmt of analysis.program.body) {
60
+ if (stmt.type === 'ExportNamedDeclaration' && stmt.declaration?.type === 'VariableDeclaration') {
61
+ for (const d of stmt.declaration.declarations) {
62
+ if (d.id.type === 'Identifier' && d.id.name === name)
63
+ return d.start
64
+ }
30
65
  }
31
66
  }
32
- return out
67
+ return 0
33
68
  }
34
69
 
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
70
+ function normalizeDiagnosticPath(root: string, file: string, message: string): string {
71
+ const rel = relPosix(root, file)
72
+ if (DIAGNOSTIC_PREFIX_RE.test(message)) {
73
+ if (message.startsWith(`${file}:`))
74
+ return `${rel}${message.slice(file.length)}`
75
+ return message
42
76
  }
43
- return undefined
77
+ return formatDiagnostic(`${rel}:1:1`, message)
44
78
  }
45
79
 
46
80
  // 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, '/')
81
+ function checkIslandReach(
82
+ island: string,
83
+ root: string,
84
+ graph: ModuleGraph,
85
+ sources: Map<string, string>,
86
+ unparsable: Set<string>,
87
+ reported: Set<string>,
88
+ errors: string[],
89
+ ): void {
90
+ const islandRel = relPosix(root, island)
49
91
  const seen = new Set<string>()
50
92
  const stack = [island]
51
93
  while (stack.length > 0) {
@@ -53,202 +95,331 @@ function checkIslandReach(island: string, root: string, analyses: Map<string, Mo
53
95
  if (seen.has(file))
54
96
  continue
55
97
  seen.add(file)
56
- const analysis = analyses.get(file)
98
+ if (NODE_MODULES_RE.test(file))
99
+ continue
100
+ const analysis = analysisOf(file, graph.analyses, sources, unparsable)
57
101
  if (analysis === undefined || (file !== island && !analysis.isInteractive && analysis.exportedActions.length > 0))
58
102
  continue
59
- const rel = relative(root, file).replace(/\\/g, '/')
60
- const report = (key: string, message: string): void => {
103
+ const report = (key: string, offset: number, message: string): void => {
61
104
  if (reported.has(`${file}\0${key}`))
62
105
  return
63
106
  reported.add(`${file}\0${key}`)
64
- errors.push(message)
107
+ errors.push(formatDiagnostic(locOf(root, file, sources, offset), message))
108
+ }
109
+ for (const imp of analysis.imports) {
110
+ if (SERVER_ONLY_MODULES.has(imp.source)) {
111
+ report(imp.source, imp.start, file === island
112
+ ? `kay check: interactive island imports server-only module "${imp.source}". Move server logic to a server action or async server component.`
113
+ : `kay check: 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.`)
114
+ continue
115
+ }
116
+ const target = graph.resolve(file, imp.source)
117
+ if (target !== undefined) {
118
+ const targetAnalysis = analysisOf(target, graph.analyses, sources, unparsable)
119
+ if (targetAnalysis !== undefined && !targetAnalysis.isInteractive && targetAnalysis.exportedActions.length > 0) {
120
+ const missing = imp.specifiers.find(s => s.imported !== '*' && !targetAnalysis.exportedActions.includes(s.imported))
121
+ if (missing !== undefined)
122
+ report(`action-export:${target}:${missing.imported}`, imp.start, `kay check: imports non-action "${missing.imported}" from server action file ${relPosix(root, target)}. Move ${missing.imported} into a module without actions.`)
123
+ continue
124
+ }
125
+ stack.push(target)
126
+ }
65
127
  }
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.`)
128
+ for (const re of analysis.reexports) {
129
+ if (SERVER_ONLY_MODULES.has(re.source)) {
130
+ report(re.source, re.start, `kay check: re-exports from server-only module "${re.source}" and is reachable from the island in ${islandRel}.`)
71
131
  continue
72
132
  }
73
- const target = resolveLocalModule(file, source)
133
+ const target = graph.resolve(file, re.source)
74
134
  if (target !== undefined)
75
135
  stack.push(target)
76
136
  }
77
- if (readsPrivateEnv(analysis.program))
78
- report('process.env', `kay check: ${rel}: reads process.env and is reachable from the island in ${islandRel}. Only process.env.PUBLIC_* reaches the browser.`)
137
+ const envOffset = findPrivateEnvOffset(analysis.program)
138
+ if (envOffset !== undefined)
139
+ report('process.env', envOffset, `kay check: reads process.env and is reachable from the island in ${islandRel}. Only process.env.PUBLIC_* reaches the browser.`)
79
140
  }
80
141
  }
81
142
 
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
143
  export async function checkProject(rootDir: string, options: { skipTypecheck?: boolean } = {}): Promise<CheckResult> {
94
144
  const root = resolve(rootDir)
95
145
  const errors: string[] = []
96
146
 
97
147
  // 1. Validate kay.config.ts
98
148
  let routesDir = resolve(root, 'src/routes')
149
+ let outDir = resolve(root, 'dist')
150
+ let assetPrefix = '/_kay'
99
151
  let plugins: Awaited<ReturnType<typeof loadConfig>>['plugins'] = []
100
152
  try {
101
153
  const cfg = await loadConfig(root)
102
- plugins = cfg.plugins ?? []
154
+ plugins = resolvePlugins(cfg.plugins)
103
155
  if (cfg.routesDir !== undefined)
104
156
  routesDir = resolve(root, cfg.routesDir)
157
+ if (cfg.outDir !== undefined)
158
+ outDir = resolve(root, cfg.outDir)
159
+ if (cfg.assetPrefix !== undefined)
160
+ assetPrefix = cfg.assetPrefix.replace(/\/$/, '')
105
161
  }
106
162
  catch (err) {
107
- errors.push(`kay.config.ts: ${err instanceof Error ? err.message : String(err)}`)
163
+ errors.push(formatDiagnostic('kay.config.ts:1:1', err instanceof Error ? err.message : String(err)))
108
164
  }
109
165
 
110
166
  // 2. Validate routesDir exists
111
- if (!existsSync(routesDir))
112
- errors.push(`missing routes directory: ${relative(root, routesDir) || routesDir}`)
167
+ if (!existsSync(routesDir)) {
168
+ const relRoutes = relative(root, routesDir) || routesDir
169
+ errors.push(formatDiagnostic(`${relRoutes.replace(/\\/g, '/')}:1:1`, `kay check: missing routes directory: ${relRoutes}`))
170
+ }
113
171
 
114
- // 3. Parse & run Kay static compiler analysis across src/
172
+ // 3. Parse & run Kay static compiler analysis across src/ AND custom routesDir
115
173
  const srcDir = resolve(root, 'src')
116
- const files = walkTsFiles(existsSync(srcDir) ? srcDir : routesDir)
117
- const analyses = new Map<string, ModuleAnalysis>()
174
+ const fileSet = new Set<string>()
175
+ if (existsSync(srcDir)) {
176
+ for (const f of walkTsFiles(srcDir))
177
+ fileSet.add(f)
178
+ }
179
+ if (existsSync(routesDir)) {
180
+ for (const f of walkTsFiles(routesDir))
181
+ fileSet.add(f)
182
+ }
183
+ const files = [...fileSet].sort()
184
+ const graph = new ModuleGraph()
185
+ const { analyses } = graph
186
+ const sources = new Map<string, string>()
187
+ const unparsable = new Set<string>()
118
188
 
189
+ const warnings: string[] = []
119
190
  for (const file of files) {
120
191
  try {
121
- const code = readFileSync(file, 'utf8')
122
- analyses.set(file, analyzeModule(file, code))
192
+ const code = sourceOf(file, sources)
193
+ const analysis = analyzeModule(file, code)
194
+ analyses.set(file, analysis)
195
+ warnings.push(...analysis.warnings)
123
196
  }
124
197
  catch (err) {
125
- errors.push(err instanceof Error ? err.message : String(err))
198
+ unparsable.add(file)
199
+ const msg = err instanceof Error ? err.message : String(err)
200
+ errors.push(normalizeDiagnosticPath(root, file, msg))
201
+ }
202
+ }
203
+
204
+ // 3a. Promote components reading imported reactive state (same rule as `planIslands` in `kay build`)
205
+ for (const [file, analysis] of [...analyses]) {
206
+ if (!file.endsWith('.tsx') || analysis.isInteractive)
207
+ continue
208
+ for (const imp of analysis.imports) {
209
+ const resolved = graph.resolve(file, imp.source)
210
+ if (resolved === undefined || !isTsFile(resolved))
211
+ continue
212
+ const state = imp.specifiers.find((spec) => {
213
+ if (analysis.jsxTags.has(spec.local))
214
+ return false
215
+ try {
216
+ if (spec.imported === '*')
217
+ return (analysisOf(resolved, analyses, sources, unparsable)?.stateExports.length ?? 0) > 0
218
+ const target = graph.exportTarget(resolved, spec.imported)
219
+ return analysisOf(target.file, analyses, sources, unparsable)?.stateExports.includes(target.exportName) === true
220
+ }
221
+ catch {
222
+ return false
223
+ }
224
+ })
225
+ if (state !== undefined) {
226
+ const reason = `reads ${state.local} from '${imp.source}'`
227
+ if (analysis.hasAsyncDefault)
228
+ errors.push(formatDiagnostic(locOf(root, file, sources, imp.start), `kay check: async route component cannot use browser interactivity (${reason}).`))
229
+ else
230
+ analyses.set(file, { ...analysis, isInteractive: true, interactiveReason: reason, interactiveOffset: imp.start })
231
+ break
232
+ }
126
233
  }
127
234
  }
128
235
 
129
- // 3b. Static guardrails: server-only imports in islands, non-serializable island props, route conflicts, missing paths()
236
+ // Exact route discovery matching `kay build` (`walkRoutes` skips `_components/` dirs, `.d.ts`, `.test.ts`)
237
+ const routeFiles = existsSync(routesDir) ? walkRoutes(routesDir).sort() : []
238
+ const routeFileSet = new Set(routeFiles)
239
+
240
+ // 3b. Static guardrails: server-only imports in islands, non-serializable island props, special files, route conflicts, missing paths()
130
241
  const seenRoutes = new Map<string, string>()
131
242
  const reported = new Set<string>()
132
243
 
133
- for (const [file, analysis] of analyses) {
134
- const rel = relative(root, file).replace(/\\/g, '/')
244
+ for (const [file, analysis] of [...analyses]) {
245
+ const rel = relPosix(root, file)
246
+
247
+ // Special route files (`_layout.tsx`, `_error.tsx`, `_404.tsx`) cannot be interactive
248
+ if (routeFileSet.has(file) && SPECIAL_ROUTE_FILES.has(basename(file)) && analysis.isInteractive) {
249
+ errors.push(formatDiagnostic(
250
+ locOf(root, file, sources, analysis.interactiveOffset ?? 0),
251
+ `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}.`,
252
+ ))
253
+ }
135
254
 
136
255
  // Guardrail 1: server-only imports and private env reads in an island or any module it imports
137
256
  if (analysis.isInteractive)
138
- checkIslandReach(file, root, analyses, reported, errors)
257
+ checkIslandReach(file, root, graph, sources, unparsable, reported, errors)
139
258
 
140
- // Guardrail 2: non-serializable props (functions / unsupported class instances) passed from static server code into an island
259
+ // Guardrail 2: non-serializable props passed from static server code into an island (including barrels & namespaces)
141
260
  if (!analysis.isInteractive && file.endsWith('.tsx')) {
142
261
  const islandTags = new Set<string>()
262
+ const islandNamespaces = new Map<string, string>() // localNs -> resolved file
143
263
  for (const imp of analysis.imports) {
144
- const target = resolveLocalModule(file, imp.source)
145
- if (target === undefined)
264
+ const resolved = graph.resolve(file, imp.source)
265
+ if (resolved === undefined || !isTsFile(resolved))
146
266
  continue
147
- const targetAnalysis = analyses.get(target)
148
- if (targetAnalysis?.isInteractive) {
149
- for (const spec of imp.specifiers)
150
- islandTags.add(spec.local)
267
+ for (const spec of imp.specifiers) {
268
+ if (spec.imported === '*') {
269
+ islandNamespaces.set(spec.local, resolved)
270
+ continue
271
+ }
272
+ try {
273
+ const target = graph.exportTarget(resolved, spec.imported)
274
+ if (analysisOf(target.file, analyses, sources, unparsable)?.isInteractive)
275
+ islandTags.add(spec.local)
276
+ }
277
+ catch {}
278
+ }
279
+ }
280
+
281
+ const isIslandTag = (tag: string): boolean => {
282
+ if (islandTags.has(tag))
283
+ return true
284
+ if (tag.includes('.')) {
285
+ const [ns, member] = tag.split('.')
286
+ const nsFile = ns !== undefined ? islandNamespaces.get(ns) : undefined
287
+ if (nsFile !== undefined && member !== undefined) {
288
+ try {
289
+ const target = graph.exportTarget(nsFile, member)
290
+ return analysisOf(target.file, analyses, sources, unparsable)?.isInteractive === true
291
+ }
292
+ catch {}
293
+ }
151
294
  }
295
+ return false
152
296
  }
153
297
 
154
- if (islandTags.size > 0) {
155
- walk(analysis.program, (node: AstNode) => {
156
- if (node.type !== 'JSXOpeningElement' || node.name?.type !== 'JSXIdentifier')
298
+ if (islandTags.size > 0 || islandNamespaces.size > 0) {
299
+ walk(analysis.program, (node) => {
300
+ if (node.type !== 'JSXOpeningElement')
157
301
  return
158
- const tag = node.name.name as string
159
- if (!islandTags.has(tag))
302
+ const tag = jsxTagName(node.name)
303
+ if (!isIslandTag(tag))
160
304
  return
161
- for (const attr of (node.attributes ?? []) as AstNode[]) {
162
- if (attr.type !== 'JSXAttribute' || attr.name?.type !== 'JSXIdentifier')
305
+ for (const attr of node.attributes) {
306
+ if (attr.type !== 'JSXAttribute' || attr.name.type !== 'JSXIdentifier')
163
307
  continue
164
- const attrName = attr.name.name as string
308
+ const attrName = attr.name.name
165
309
  if (attrName === 'key' || attrName === '$hydrate')
166
310
  continue
167
- if (attr.value?.type !== 'JSXExpressionContainer')
168
- continue
169
- const expr = attr.value.expression as AstNode | undefined
170
- if (expr === undefined)
311
+ if (attr.value?.type !== 'JSXExpressionContainer' || attr.value.expression.type === 'JSXEmptyExpression')
171
312
  continue
313
+ const expr = attr.value.expression
172
314
  if (expr.type === 'ArrowFunctionExpression' || expr.type === 'FunctionExpression') {
173
- errors.push(
174
- `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
- )
315
+ errors.push(formatDiagnostic(
316
+ locOf(root, file, sources, attr.start),
317
+ `kay check: cannot pass function prop "${attrName}" from a server component into island <${tag}>. Define the handler inside the island or pass serializable data.`,
318
+ ))
176
319
  }
177
- else if (expr.type === 'NewExpression' && expr.callee?.type === 'Identifier' && !SERIALIZABLE_NEW_CTORS.has(expr.callee.name as string)) {
178
- errors.push(
179
- `kay check: ${rel}: cannot pass non-serializable \`new ${expr.callee.name}()\` prop "${attrName}" into island <${tag}>.`,
180
- )
320
+ else if (expr.type === 'NewExpression' && expr.callee.type === 'Identifier' && !SERIALIZABLE_NEW_CTORS.has(expr.callee.name)) {
321
+ errors.push(formatDiagnostic(
322
+ locOf(root, file, sources, expr.start),
323
+ `kay check: cannot pass non-serializable \`new ${expr.callee.name}()\` prop "${attrName}" into island <${tag}>.`,
324
+ ))
181
325
  }
182
326
  }
183
327
  })
184
328
  }
185
329
  }
186
330
 
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
- }
331
+ // Route-specific guardrails (only real route files matching `kay build`)
332
+ if (routeFileSet.has(file) && !basename(file).startsWith('_')) {
333
+ const problem = routeExportProblemLocation(analysis, rel)
334
+ if (problem !== undefined)
335
+ errors.push(formatDiagnostic(locOf(root, file, sources, problem.offset), `kay check: ${problem.message}`))
336
+
337
+ if (hasRouteHandlerExport(analysis)) {
338
+ const conflictKey = normalizeRoutePattern(fileToRoutePath(routesDir, file))
339
+ const prev = seenRoutes.get(conflictKey)
340
+ if (prev !== undefined) {
341
+ errors.push(formatDiagnostic(`${rel}:1:1`, `kay check: conflicting routes "${prev}" and "${rel}" both match "${conflictKey}".`))
342
+ }
343
+ else {
344
+ seenRoutes.set(conflictKey, rel)
345
+ }
199
346
 
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()\`.`)
347
+ // Guardrail 4: dynamic prerender = true route missing paths()
348
+ if (analysis.hasPrerender && (conflictKey.includes(':') || conflictKey.includes('*')) && !analysis.hasPaths) {
349
+ const offset = findExportedConstOffset(analysis, 'prerender')
350
+ errors.push(formatDiagnostic(locOf(root, file, sources, offset), `kay check: dynamic route exports \`prerender = true\` without exporting \`paths()\`.`))
351
+ }
203
352
  }
204
353
  }
205
354
  }
206
355
 
207
- // 3c. Run plugin check(ctx) hooks
356
+ // 3c. Run plugin check(ctx) hooks inside a real AppRuntimeContext
208
357
  if (plugins && plugins.length > 0) {
358
+ const appCtx = createAppContext({
359
+ root,
360
+ outDir,
361
+ publicDir: join(outDir, 'public'),
362
+ assetPrefix,
363
+ dev: false,
364
+ })
209
365
  const pluginCtx = {
210
366
  root,
211
367
  routesDir,
212
368
  error(message: string) {
213
- errors.push(message)
369
+ errors.push(DIAGNOSTIC_PREFIX_RE.test(message) ? message : formatDiagnostic('kay.config.ts:1:1', message))
214
370
  },
215
371
  }
216
372
  for (const plugin of plugins) {
217
373
  if (plugin.check !== undefined) {
218
374
  try {
219
- await plugin.check(pluginCtx)
375
+ await runWithAppContext(appCtx, () => plugin.check!(pluginCtx))
220
376
  }
221
377
  catch (err) {
222
- errors.push(`${plugin.name}: ${err instanceof Error ? err.message : String(err)}`)
378
+ const msg = `${plugin.name}: ${err instanceof Error ? err.message : String(err)}`
379
+ errors.push(DIAGNOSTIC_PREFIX_RE.test(msg) ? msg : formatDiagnostic('kay.config.ts:1:1', msg))
223
380
  }
224
381
  }
225
382
  }
226
383
  }
227
384
 
228
- // 4. Run TypeScript check (`tsgo` preferred, fallback to `tsc`) when tsconfig.json exists
385
+ // 4. Run TypeScript check (`bun check` preferred, fallback to `tsgo` then `tsc`) when tsconfig.json exists
229
386
  const tsconfigPath = join(root, 'tsconfig.json')
230
387
  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
- }
388
+ const bunCheck = Bun.spawnSync([process.execPath, 'check', '--no-script', '-p', tsconfigPath], { cwd: root })
389
+ if (bunCheck.exitCode === 0) {
390
+ // Typecheck passed via built-in `bun check`
243
391
  }
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}`)
392
+ else {
393
+ const bunOut = (bunCheck.stdout.toString() + bunCheck.stderr.toString()).trim()
394
+ // Only fall back to tsgo/tsc if this Bun binary does not support `bun check`
395
+ const unsupported = bunOut.includes('Script not found "check"') || bunOut.includes('Unknown command')
396
+ if (!unsupported) {
397
+ errors.push(bunOut || `bun check exited with code ${bunCheck.exitCode}`)
398
+ }
399
+ else {
400
+ const candidates = [
401
+ join(root, 'node_modules/.bin/tsgo'),
402
+ join(root, 'node_modules/.bin/tsc'),
403
+ 'tsgo',
404
+ 'tsc',
405
+ ]
406
+ let bin: string | undefined
407
+ for (const c of candidates) {
408
+ if (c.includes('/') ? existsSync(c) : Bun.which(c) !== null) {
409
+ bin = c
410
+ break
411
+ }
412
+ }
413
+ if (bin !== undefined) {
414
+ const proc = Bun.spawnSync([bin, '--noEmit', '-p', tsconfigPath], { cwd: root })
415
+ if (proc.exitCode !== 0) {
416
+ const out = (proc.stdout.toString() + proc.stderr.toString()).trim()
417
+ errors.push(out || `${bin} exited with code ${proc.exitCode}`)
418
+ }
419
+ }
249
420
  }
250
421
  }
251
422
  }
252
423
 
253
- return { ok: errors.length === 0, checkedFiles: files.length, errors }
424
+ return { ok: errors.length === 0, checkedFiles: files.length, errors, warnings }
254
425
  }