@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
@@ -3,32 +3,35 @@
3
3
  // - Builds client (1 pass, minimal runtime + island chunks + action stubs) and server (1 pass)
4
4
  // - Supports hybrid prerender, --static export, and --compile single-executable builds
5
5
 
6
- import type { BunPlugin } from 'bun'
7
- import type { IslandBinding, ModuleAnalysis } from '../compiler/index'
8
- import type { BuildPluginContext, KayPlugin } from '../plugins/index'
9
- import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
10
- import { tmpdir } from 'node:os'
11
- import { basename, dirname, extname, isAbsolute, join, relative, resolve } from 'node:path'
12
- import { brotliCompressSync, constants as zlibConstants } from 'node:zlib'
13
- import { analyzeModule, compileDom, compileSsr } from '../compiler/index'
14
- import { readsPrivateEnv, SERVER_ONLY_FILTER } from '../compiler/server-only'
15
- import { loadConfig } from '../plugins/index'
6
+ import type { AppRuntimeContext } from '../plugins/context'
7
+ import type { KayPlugin } from '../plugins/index'
8
+ import type { BuildCache } from './graph'
9
+ import type { ActionsByFile } from './islands'
10
+ import type { BuildManifest } from './manifest'
11
+ import type { PublicFiles } from './plugin-host'
12
+ import { copyFileSync, existsSync, mkdirSync, readdirSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
13
+ import { basename, dirname, join, relative, resolve } from 'node:path'
14
+ import { createAppContext, loadConfig, resolvePlugins, runWithAppContext } from '../plugins/index'
16
15
  import { actionHash } from '../server/action'
16
+ import { buildClient, buildServer, pluginBunPlugins, standaloneCssFiles } from './bundle'
17
17
  import { compileExecutable } from './compile'
18
-
19
- export interface BuildCache {
20
- analyses: Map<string, { mtimeMs: number, size: number, code: string, analysis: ModuleAnalysis }>
21
- domCompiled: Map<string, { mtimeMs: number, size: number, code: string }>
22
- ssrCompiled: Map<string, { mtimeMs: number, size: number, key: string, code: string }>
23
- }
24
-
25
- export function createBuildCache(): BuildCache {
26
- return {
27
- analyses: new Map(),
28
- domCompiled: new Map(),
29
- ssrCompiled: new Map(),
30
- }
31
- }
18
+ import { assertSafeOutDir, fileSize, relPosix, walkAllFiles, walkRoutes } from './files'
19
+ import { ModuleGraph } from './graph'
20
+ import { planIslands } from './islands'
21
+ import { buildActionEntries, buildRouteEntries } from './manifest'
22
+ import { createPluginHost, createPublicFiles } from './plugin-host'
23
+ import { prerender } from './prerender'
24
+ import { formatBundleReport } from './report'
25
+ import { KAY_SRC_ROOT, resolveKaySpecifier } from './resolve'
26
+ import { assertNoRouteConflicts, hasRouteHandlerExport, routeExportProblem, SPECIAL_ROUTE_FILES } from './routes'
27
+ import { exportStatic } from './static'
28
+
29
+ export type { BuildCache } from './graph'
30
+ export { createBuildCache } from './graph'
31
+ export type { ActionManifestEntry, BuildManifest, RouteManifestEntry } from './manifest'
32
+ export { analyzeBundleWeights, formatBundleReport } from './report'
33
+ export type { RouteBundleMetrics } from './report'
34
+ export { resolveKaySpecifier } from './resolve'
32
35
 
33
36
  export interface BuildOptions {
34
37
  root: string
@@ -37,6 +40,7 @@ export interface BuildOptions {
37
40
  publicDir?: string | undefined
38
41
  minify?: boolean | undefined
39
42
  assetPrefix?: string | undefined
43
+ site?: string | undefined
40
44
  plugins?: KayPlugin[] | undefined
41
45
  /** Reusable incremental cache for `kay dev` (skips re-parsing/re-compiling unchanged files). */
42
46
  cache?: BuildCache | undefined
@@ -54,287 +58,24 @@ export interface BuildOptions {
54
58
  dev?: boolean | undefined
55
59
  }
56
60
 
57
- export interface ActionManifestEntry {
58
- url: string
59
- file: string
60
- exportName: string
61
- /** `_middleware.ts` chain of the folder declaring the action, outermost first. */
62
- middlewares: string[]
63
- }
64
-
65
- export interface RouteManifestEntry {
66
- path: string
67
- file: string
68
- layouts: string[]
69
- middlewares: string[]
70
- hasLoad?: boolean | undefined
71
- isIsland?: boolean | undefined
72
- islandChunk?: string | undefined
73
- islandHydrate?: string | undefined
74
- islandChunks: string[]
75
- eagerIslandChunks?: string[] | undefined
76
- /** Per-route stylesheets (global plugin styles + CSS imported by this route, its layouts, and its islands). */
77
- styles?: string[] | undefined
78
- /** Per-route raw <head> HTML tags injected by plugins via `ctx.addRouteHead()`. */
79
- headTags?: string[] | undefined
80
- usesRenderContext?: boolean | undefined
81
- prerender?: boolean | undefined
82
- prerendered?: Record<string, string> | undefined
83
- }
84
-
85
- export interface BuildManifest {
86
- runtimeScript: string | undefined
87
- styles: string[]
88
- /** Stylesheets applied globally (plugin CSS, ctx.addStyle, and root layout CSS) — used by _error/_404. */
89
- globalStyles?: string[] | undefined
90
- headTags?: string[] | undefined
91
- routes: RouteManifestEntry[]
92
- errorFile?: string | undefined
93
- notFoundFile?: string | undefined
94
- actions: ActionManifestEntry[]
95
- islands: Record<string, string>
96
- assets: string[]
97
- publicFiles: string[]
98
- }
99
-
100
- const KAY_SRC_ROOT = resolve(import.meta.dir, '..')
101
-
102
- export function resolveKaySpecifier(specifier: string): string | undefined {
103
- if (specifier === 'kay' || specifier === '@kayjs/kay')
104
- return join(KAY_SRC_ROOT, 'index.ts')
105
- if (specifier === 'kay/dom' || specifier === '@kayjs/kay/dom')
106
- return join(KAY_SRC_ROOT, 'dom/index.ts')
107
- if (specifier === 'kay/dom-extras' || specifier === '@kayjs/kay/dom-extras')
108
- return join(KAY_SRC_ROOT, 'dom/extras.ts')
109
- if (specifier === 'kay/dom-loop' || specifier === '@kayjs/kay/dom-loop')
110
- return join(KAY_SRC_ROOT, 'dom/loop.ts')
111
- if (specifier === 'kay/action' || specifier === '@kayjs/kay/action')
112
- return join(KAY_SRC_ROOT, 'dom/action.ts')
113
- if (specifier === 'kay/island' || specifier === '@kayjs/kay/island')
114
- return join(KAY_SRC_ROOT, 'dom/island.ts')
115
- if (specifier === 'kay/ssr' || specifier === '@kayjs/kay/ssr')
116
- return join(KAY_SRC_ROOT, 'ssr/index.ts')
117
- if (specifier === 'kay/server' || specifier === '@kayjs/kay/server')
118
- return join(KAY_SRC_ROOT, 'server/index.ts')
119
- if (specifier === 'kay/compiler' || specifier === '@kayjs/kay/compiler')
120
- return join(KAY_SRC_ROOT, 'compiler/index.ts')
121
- if (specifier === 'kay/build' || specifier === '@kayjs/kay/build')
122
- return join(KAY_SRC_ROOT, 'build/index.ts')
123
- if (specifier === 'kay/dev' || specifier === '@kayjs/kay/dev')
124
- return join(KAY_SRC_ROOT, 'dev/index.ts')
125
- if (specifier === 'kay/test' || specifier === '@kayjs/kay/test')
126
- return join(KAY_SRC_ROOT, 'test/index.ts')
127
- if (
128
- specifier === 'kay/jsx-runtime'
129
- || specifier === 'kay/jsx-dev-runtime'
130
- || specifier === '@kayjs/kay/jsx-runtime'
131
- || specifier === '@kayjs/kay/jsx-dev-runtime'
132
- ) {
133
- return join(KAY_SRC_ROOT, 'jsx-runtime.ts')
134
- }
135
- return undefined
136
- }
137
-
138
- function resolveImportPath(fromFile: string, specifier: string): string | undefined {
139
- if (specifier.startsWith('.')) {
140
- const base = resolve(dirname(fromFile), specifier)
141
- const candidates = [base, `${base}.tsx`, `${base}.ts`, join(base, 'index.tsx'), join(base, 'index.ts')]
142
- for (const c of candidates) {
143
- if (existsSync(c))
144
- return c
145
- }
146
- return undefined
147
- }
148
- if (
149
- specifier === 'kay'
150
- || specifier.startsWith('kay/')
151
- || specifier.startsWith('@kayjs/kay')
152
- || specifier.startsWith('node:')
153
- || specifier.startsWith('bun')
154
- || specifier.startsWith('~')
155
- ) {
156
- return undefined
157
- }
158
- try {
159
- const resolved = Bun.resolveSync(specifier, dirname(fromFile))
160
- return resolved.endsWith('.tsx') || resolved.endsWith('.ts') ? resolved : undefined
161
- }
162
- catch {
163
- return undefined
164
- }
165
- }
166
-
167
- const SPECIAL_ROUTE_FILES = new Set(['_layout.tsx', '_middleware.ts', '_middleware.tsx', '_error.tsx', '_404.tsx'])
168
- const ROUTE_EXPORTS = new Set(['default', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'])
169
- const TEST_FILE_RE = /\.(?:test|spec)\.(?:tsx|ts)$/
170
- const COMPRESSIBLE_EXTS = new Set(['.html', '.js', '.mjs', '.css', '.svg', '.xml', '.json', '.txt', '.webmanifest', '.wasm'])
171
-
172
- function walkRoutes(dir: string, out: string[] = []): string[] {
173
- if (!existsSync(dir))
174
- return out
175
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
176
- const full = join(dir, entry.name)
177
- if (entry.isDirectory()) {
178
- if (entry.name.startsWith('_'))
179
- continue
180
- walkRoutes(full, out)
181
- }
182
- else if (
183
- (entry.name.endsWith('.tsx') || entry.name.endsWith('.ts'))
184
- && !entry.name.endsWith('.d.ts')
185
- && !TEST_FILE_RE.test(entry.name)
186
- ) {
187
- out.push(full)
188
- }
189
- }
190
- return out
191
- }
192
-
193
- function hasRouteHandlerExport(analysis: ModuleAnalysis): boolean {
194
- for (const name of analysis.exportedNames) {
195
- if (ROUTE_EXPORTS.has(name))
196
- return true
197
- }
198
- for (const stmt of analysis.program.body as { type: string, exportKind?: string, specifiers?: { exportKind?: string, exported?: { name?: string, value?: string } }[] }[]) {
199
- if (stmt.type === 'ExportNamedDeclaration' && stmt.exportKind !== 'type' && stmt.specifiers !== undefined) {
200
- for (const spec of stmt.specifiers) {
201
- if (spec.exportKind === 'type')
202
- continue
203
- const exported = spec.exported?.name ?? spec.exported?.value
204
- if (exported !== undefined && ROUTE_EXPORTS.has(exported))
205
- return true
206
- }
207
- }
208
- }
209
- return false
210
- }
211
-
212
- function normalizeRoutePattern(routePath: string): string {
213
- return routePath
214
- .split('/')
215
- .map(seg => (seg.startsWith(':') ? ':' : seg.startsWith('*') ? '*' : seg))
216
- .join('/')
217
- }
218
-
219
- function isOutside(base: string, target: string): boolean {
220
- const rel = relative(base, target)
221
- return rel === '..' || rel.startsWith('../') || rel.startsWith('..\\') || isAbsolute(rel)
222
- }
223
-
224
- function isStrictDescendant(base: string, target: string): boolean {
225
- const rel = relative(base, target)
226
- return rel !== '' && rel !== '..' && !rel.startsWith('../') && !rel.startsWith('..\\') && !isAbsolute(rel)
227
- }
228
-
229
- function assertSafeOutDir(root: string, outDir: string, routesDir: string, publicDir: string): void {
230
- // Refuse filesystem root, home dir, tmpdir root, or root/ancestors of root
231
- if (dirname(outDir) === outDir || outDir === tmpdir() || outDir === resolve(process.env.HOME ?? '\0')) {
232
- throw new Error(`kay build: refusing unsafe outDir "${outDir}" — cannot wipe a root or shared system directory.`)
233
- }
234
- if (!isOutside(outDir, root)) {
235
- throw new Error(`kay build: refusing unsafe outDir "${outDir}" — outDir cannot be or contain project root "${root}".`)
236
- }
237
- if (existsSync(outDir)) {
238
- try {
239
- const realRoot = realpathSync(root)
240
- const realOut = realpathSync(outDir)
241
- if (dirname(realOut) === realOut || !isOutside(realOut, realRoot)) {
242
- throw new Error(`kay build: refusing unsafe outDir "${outDir}" — resolved target "${realOut}" is or contains project root "${realRoot}".`)
243
- }
244
- }
245
- catch (err) {
246
- if (err instanceof Error && err.message.startsWith('kay build: refusing unsafe outDir'))
247
- throw err
248
- }
249
- }
250
- const protectedTargets: [string, string][] = [
251
- ['src', resolve(root, 'src')],
252
- ['routesDir', routesDir],
253
- ['publicDir', publicDir],
254
- ['kay.config.ts', resolve(root, 'kay.config.ts')],
255
- ['package.json', resolve(root, 'package.json')],
256
- ]
257
- for (const [label, target] of protectedTargets) {
258
- if (!isOutside(outDir, target)) {
259
- throw new Error(`kay build: refusing unsafe outDir "${outDir}" — it equals or contains protected path ${label} ("${target}").`)
260
- }
261
- }
262
- // If outDir is outside root (e.g. an external temp build dir), refuse it if it looks like another project directory.
263
- if (!isStrictDescendant(root, outDir) && existsSync(outDir)) {
264
- for (const marker of ['package.json', 'kay.config.ts', 'src']) {
265
- if (existsSync(join(outDir, marker))) {
266
- throw new Error(`kay build: refusing unsafe external outDir "${outDir}" — it contains "${marker}".`)
267
- }
268
- }
269
- }
270
- }
271
-
272
- function precompressFile(abs: string, minBytes: number): void {
273
- if (!COMPRESSIBLE_EXTS.has(extname(abs).toLowerCase()))
274
- return
275
- const raw = readFileSync(abs)
276
- if (raw.byteLength < minBytes)
277
- return
278
- const br = brotliCompressSync(raw, { params: { [zlibConstants.BROTLI_PARAM_QUALITY]: 6 } })
279
- if (br.byteLength < raw.byteLength)
280
- writeFileSync(`${abs}.br`, br)
281
- const gz = Bun.gzipSync(raw, { level: 9 })
282
- if (gz.byteLength < raw.byteLength)
283
- writeFileSync(`${abs}.gz`, gz)
284
- }
285
-
286
- function walkAllFiles(dir: string, out: string[] = []): string[] {
287
- if (!existsSync(dir))
288
- return out
289
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
290
- const full = join(dir, entry.name)
291
- if (entry.isDirectory())
292
- walkAllFiles(full, out)
293
- else if (entry.isFile())
294
- out.push(full)
295
- }
296
- return out
297
- }
298
-
299
- function fileToRoutePath(routesDir: string, file: string): string {
300
- const rel = relative(routesDir, file).replace(/\\/g, '/').replace(/\.(tsx|ts)$/, '')
301
- if (rel === 'index')
302
- return '/'
303
- const clean = rel.endsWith('/index') ? rel.slice(0, -'/index'.length) : rel
304
- const pattern = clean
305
- .replace(/\[\.\.\.([^\]]+)\]/g, '*$1')
306
- .replace(/\[([^\]]+)\]/g, ':$1')
307
- return `/${pattern}`
308
- }
309
-
310
- /** Finds all ancestor files named `specialName` from routesDir down to dirname(routeFile), outermost first. */
311
- function ancestorFiles(routesDir: string, routeFile: string, specialNames: string[]): string[] {
312
- const result: string[] = []
313
- const relDir = relative(routesDir, dirname(routeFile))
314
- const parts = relDir === '' ? [] : relDir.split(/[/\\]/)
315
- let cur = routesDir
316
-
317
- for (let i = 0; i <= parts.length; i++) {
318
- if (i > 0)
319
- cur = join(cur, parts[i - 1]!)
320
- for (const name of specialNames) {
321
- const candidate = join(cur, name)
322
- if (existsSync(candidate))
323
- result.push(candidate)
324
- }
325
- }
326
- return result
327
- }
328
-
329
- interface IslandTarget {
330
- id: string
331
- file: string
332
- exportName: string
333
- defaultHydrate: string | undefined
334
- }
335
-
336
- function clientLeakError(leaks: Set<string>): Error {
337
- return new Error(`kay build (client): server code is reachable from an island:\n${[...leaks].map(l => ` ${l}`).join('\n')}\nMove server logic to a server action or async server component.`)
61
+ /** Everything one build run needs, resolved once from the options and `kay.config.ts`. */
62
+ interface BuildRun {
63
+ options: BuildOptions
64
+ root: string
65
+ plugins: KayPlugin[]
66
+ routesDir: string
67
+ publicDir: string
68
+ finalOutDir: string
69
+ /** Where the build writes: `finalOutDir`, or a stage folder for a static export. */
70
+ outDir: string
71
+ staticStageDir: string | undefined
72
+ stageSuffix: string
73
+ assetPrefix: string
74
+ site: string | undefined
75
+ minify: boolean
76
+ isDev: boolean
77
+ appCtx: AppRuntimeContext
78
+ publicFiles: PublicFiles
338
79
  }
339
80
 
340
81
  export async function build(options: BuildOptions): Promise<BuildManifest> {
@@ -344,7 +85,6 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
344
85
 
345
86
  const root = resolve(options.root)
346
87
  const fileConfig = await loadConfig(root)
347
- const plugins: KayPlugin[] = options.plugins ?? fileConfig.plugins ?? []
348
88
  const routesDir = resolve(root, options.routesDir ?? fileConfig.routesDir ?? 'src/routes')
349
89
  const finalOutDir = resolve(root, options.outDir ?? fileConfig.outDir ?? 'dist')
350
90
  const publicDir = resolve(root, options.publicDir ?? fileConfig.publicDir ?? 'public')
@@ -355,23 +95,43 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
355
95
  const cacheBaseDir = join(root, '.kay-cache')
356
96
  const cacheExisted = existsSync(cacheBaseDir)
357
97
  const stageSuffix = `${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
358
- const outDir = options.static
359
- ? join(cacheBaseDir, `.static-stage-${stageSuffix}`)
360
- : finalOutDir
361
- const staticStageDir = options.static
362
- ? join(dirname(finalOutDir), `.${basename(finalOutDir)}.stage-${stageSuffix}`)
363
- : undefined
364
- const clientDir = join(outDir, 'client')
365
- const serverDir = join(outDir, 'server')
98
+ const outDir = options.static ? join(cacheBaseDir, `.static-stage-${stageSuffix}`) : finalOutDir
99
+ const staticStageDir = options.static ? join(dirname(finalOutDir), `.${basename(finalOutDir)}.stage-${stageSuffix}`) : undefined
366
100
  const assetPrefix = (options.assetPrefix ?? fileConfig.assetPrefix ?? '/_kay').replace(/\/$/, '')
367
- const minify = options.minify ?? true
101
+ const site = (options.site ?? fileConfig.site)?.replace(/\/$/, '') || undefined
102
+ const publicFiles = createPublicFiles()
103
+ const appCtx = createAppContext({
104
+ root,
105
+ outDir,
106
+ publicDir: join(outDir, 'public'),
107
+ assetPrefix,
108
+ site,
109
+ dev: isDev,
110
+ onRegisterPublicFile: publicFiles.register,
111
+ })
368
112
 
369
113
  const prevNodeEnv = process.env.NODE_ENV
370
114
  if (!isDev)
371
115
  process.env.NODE_ENV ??= 'production'
372
116
 
373
117
  try {
374
- return await buildInternal()
118
+ return await runWithAppContext(appCtx, () => runBuild({
119
+ options,
120
+ root,
121
+ plugins: resolvePlugins(options.plugins ?? fileConfig.plugins),
122
+ routesDir,
123
+ publicDir,
124
+ finalOutDir,
125
+ outDir,
126
+ staticStageDir,
127
+ stageSuffix,
128
+ assetPrefix,
129
+ site,
130
+ minify: options.minify ?? true,
131
+ isDev,
132
+ appCtx,
133
+ publicFiles,
134
+ }))
375
135
  }
376
136
  finally {
377
137
  if (!isDev) {
@@ -381,1222 +141,256 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
381
141
  delete process.env.NODE_ENV
382
142
  }
383
143
  if (options.static) {
384
- if (staticStageDir !== undefined && existsSync(staticStageDir))
144
+ if (staticStageDir !== undefined)
385
145
  rmSync(staticStageDir, { recursive: true, force: true })
386
146
  rmSync(outDir, { recursive: true, force: true })
387
147
  if (!cacheExisted && existsSync(cacheBaseDir) && readdirSync(cacheBaseDir).length === 0)
388
148
  rmSync(cacheBaseDir, { recursive: true, force: true })
389
149
  }
390
150
  }
151
+ }
391
152
 
392
- async function buildInternal(): Promise<BuildManifest> {
393
-
394
- const pluginBunPlugins = plugins.flatMap((p) => {
395
- const bp = p.bunPlugins
396
- if (typeof bp === 'function')
397
- return bp({ root, assetPrefix, minify })
398
- return bp ?? []
399
- })
400
- const pluginClientEntries = plugins.map(p => p.clientEntry).filter((e): e is string => Boolean(e))
401
- const pluginCssFiles = plugins
402
- .flatMap(p => p.css ?? [])
403
- .map(c => resolve(root, c))
404
- .filter(c => existsSync(c))
405
-
406
- function applyTransforms(code: string, id: string, target: 'server' | 'client'): string {
407
- let cur = code
408
- for (let i = 0; i < plugins.length; i++) {
409
- const fn = plugins[i]!.transform
410
- if (fn !== undefined) {
411
- const next = fn(cur, id, target)
412
- if (typeof next === 'string')
413
- cur = next
414
- }
415
- }
416
- return cur
417
- }
418
-
419
- rmSync(outDir, { recursive: true, force: true })
420
- mkdirSync(clientDir, { recursive: true })
421
- mkdirSync(serverDir, { recursive: true })
153
+ async function runBuild(run: BuildRun): Promise<BuildManifest> {
154
+ const { options, root, plugins, routesDir, outDir, assetPrefix, isDev, publicFiles } = run
155
+ const clientDir = join(outDir, 'client')
156
+ const serverDir = join(outDir, 'server')
157
+ const isStatic = options.static === true
422
158
 
423
159
  const allRouteFiles = walkRoutes(routesDir).sort()
424
160
  const specialFiles = allRouteFiles.filter(f => SPECIAL_ROUTE_FILES.has(basename(f)))
425
161
  const candidatePageFiles = allRouteFiles.filter(f => !basename(f).startsWith('_'))
162
+ const rootLayoutSrc = join(routesDir, '_layout.tsx')
426
163
  const errorSrc = join(routesDir, '_error.tsx')
427
164
  const notFoundSrc = join(routesDir, '_404.tsx')
165
+ const hasRootLayout = existsSync(rootLayoutSrc)
428
166
  const hasErrorFile = existsSync(errorSrc)
429
167
  const hasNotFoundFile = existsSync(notFoundSrc)
430
168
 
431
- // Analyze every reachable .tsx and .ts file once (reusing BuildCache across `kay dev` rebuilds when mtime+size match)
432
- const cache = options.cache
433
- const analyses = new Map<string, ModuleAnalysis>()
434
- const sources = new Map<string, string>()
435
- const fileStamps = new Map<string, { mtimeMs: number, size: number }>()
436
-
437
- function getFileStamp(file: string): { mtimeMs: number, size: number } | undefined {
438
- const existing = fileStamps.get(file)
439
- if (existing !== undefined)
440
- return existing
441
- if (cache === undefined)
442
- return undefined
443
- try {
444
- const st = statSync(file)
445
- const stamp = { mtimeMs: st.mtimeMs, size: st.size }
446
- fileStamps.set(file, stamp)
447
- return stamp
448
- }
449
- catch {
450
- return undefined
451
- }
169
+ // Every reachable .ts/.tsx file is analyzed & validated BEFORE wiping outDir, so build errors keep the last working dist/.
170
+ const graph = new ModuleGraph(options.cache)
171
+ for (const f of [...specialFiles, ...candidatePageFiles])
172
+ graph.load(f)
173
+ for (const analysis of graph.analyses.values()) {
174
+ for (const warning of analysis.warnings)
175
+ console.warn(warning)
452
176
  }
453
177
 
454
- function loadAnalysis(file: string): ModuleAnalysis {
455
- const existing = analyses.get(file)
456
- if (existing !== undefined)
457
- return existing
458
- const stamp = getFileStamp(file)
459
- const cached = stamp !== undefined ? cache?.analyses.get(file) : undefined
460
- let code: string
461
- let analysis: ModuleAnalysis
462
- if (cached !== undefined && cached.mtimeMs === stamp!.mtimeMs && cached.size === stamp!.size) {
463
- code = cached.code
464
- analysis = cached.analysis
465
- }
466
- else {
467
- code = readFileSync(file, 'utf8')
468
- analysis = analyzeModule(file, code)
469
- if (cache !== undefined && stamp !== undefined)
470
- cache.analyses.set(file, { mtimeMs: stamp.mtimeMs, size: stamp.size, code, analysis })
471
- }
472
- sources.set(file, code)
473
- analyses.set(file, analysis)
474
- for (const imp of analysis.imports) {
475
- const target = resolveImportPath(file, imp.source)
476
- if (target !== undefined && (target.endsWith('.tsx') || target.endsWith('.ts')))
477
- loadAnalysis(target)
478
- }
479
- for (const re of analysis.reexports) {
480
- const target = resolveImportPath(file, re.source)
481
- if (target !== undefined && (target.endsWith('.tsx') || target.endsWith('.ts')))
482
- loadAnalysis(target)
483
- }
484
- return analysis
485
- }
486
-
487
- function resolveExportTarget(file: string, exportName: string, depth = 0): { file: string, exportName: string } {
488
- if (depth > 8)
489
- return { file, exportName }
490
- const analysis = loadAnalysis(file)
491
- const re = analysis.reexports.find(r => r.exported === exportName)
492
- if (re !== undefined) {
493
- const next = resolveImportPath(file, re.source)
494
- if (next !== undefined)
495
- return resolveExportTarget(next, re.local, depth + 1)
496
- }
497
- return { file, exportName }
498
- }
499
-
500
- for (const f of specialFiles)
501
- loadAnalysis(f)
502
- for (const f of candidatePageFiles)
503
- loadAnalysis(f)
504
-
505
178
  // Skip helper files inside routes/ that export neither a default component nor an HTTP method handler
506
- const pageFiles = candidatePageFiles.filter(f => hasRouteHandlerExport(analyses.get(f)!))
507
-
508
- // Detect conflicting route patterns at build time (e.g. about.tsx vs about/index.tsx, [id].tsx vs [slug].tsx)
509
- const seenRoutePatterns = new Map<string, { file: string, path: string }>()
510
- for (const file of pageFiles) {
511
- const routePath = fileToRoutePath(routesDir, file)
512
- const normalized = normalizeRoutePattern(routePath)
513
- const existing = seenRoutePatterns.get(normalized)
514
- if (existing !== undefined) {
515
- const relA = relative(root, existing.file).replace(/\\/g, '/')
516
- const relB = relative(root, file).replace(/\\/g, '/')
517
- throw new Error(`kay build: conflicting routes for pattern "${routePath}": "${relA}" (${existing.path}) and "${relB}" (${routePath})`)
518
- }
519
- seenRoutePatterns.set(normalized, { file, path: routePath })
179
+ for (const f of candidatePageFiles) {
180
+ const problem = routeExportProblem(graph.analyses.get(f)!, relPosix(root, f))
181
+ if (problem !== undefined)
182
+ throw new Error(`kay build: ${problem}`)
520
183
  }
184
+ const pageFiles = candidatePageFiles.filter(f => hasRouteHandlerExport(graph.analyses.get(f)!))
185
+ assertNoRouteConflicts(root, routesDir, pageFiles)
521
186
 
522
- // Discover all server actions (keyed by source file -> exportName -> action URL)
523
- const actionsByFile = new Map<string, { exportName: string, url: string }[]>()
524
- for (const [file, analysis] of analyses) {
187
+ // Server actions, keyed by source file
188
+ const actionsByFile: ActionsByFile = new Map()
189
+ for (const [file, analysis] of graph.analyses) {
525
190
  if (analysis.exportedActions.length > 0) {
526
- const rel = relative(root, file).replace(/\\/g, '/')
527
- actionsByFile.set(
528
- file,
529
- analysis.exportedActions.map(exportName => ({
530
- exportName,
531
- url: `${assetPrefix}/action/${actionHash(rel, exportName)}`,
532
- })),
533
- )
534
- }
535
- }
536
-
537
- // Discover all island roots referenced from static pages/layouts/errors (or sync interactive pages themselves)
538
- const islandTargets = new Map<string, IslandTarget>()
539
- const islandIds = new Set<string>()
540
- const pageIslandBindings = new Map<string, Map<string, IslandTarget>>()
541
-
542
- function registerIsland(file: string, exportName: string): IslandTarget {
543
- const key = `${file}#${exportName}`
544
- const existing = islandTargets.get(key)
545
- if (existing !== undefined)
546
- return existing
547
- const analysis = loadAnalysis(file)
548
- const baseName = basename(file, extname(file)).toLowerCase()
549
- const expLower = exportName.toLowerCase()
550
- let id = exportName === 'default' || expLower === baseName ? baseName : `${baseName}-${expLower}`
551
- // The id names the entry file and the chunk: two islands sharing a basename keep it readable and add a hash of their path.
552
- if (islandIds.has(id))
553
- id = `${id}-${Bun.hash(relative(root, key)).toString(36).slice(0, 6)}`
554
- islandIds.add(id)
555
- const target: IslandTarget = { id, file, exportName, defaultHydrate: analysis.defaultHydrate }
556
- islandTargets.set(key, target)
557
- return target
558
- }
559
-
560
- for (const [file, analysis] of analyses) {
561
- if (!file.endsWith('.tsx'))
562
- continue
563
- if (analysis.isInteractive) {
564
- if (pageFiles.includes(file))
565
- registerIsland(file, 'default')
566
- continue
191
+ const rel = relPosix(root, file)
192
+ actionsByFile.set(file, analysis.exportedActions.map(exportName => ({
193
+ exportName,
194
+ url: `${assetPrefix}/action/${actionHash(rel, exportName)}`,
195
+ })))
567
196
  }
568
-
569
- const bindings = new Map<string, IslandTarget>()
570
- for (const imp of analysis.imports) {
571
- const resolved = resolveImportPath(file, imp.source)
572
- if (resolved === undefined || (!resolved.endsWith('.tsx') && !resolved.endsWith('.ts')))
573
- continue
574
- for (const spec of imp.specifiers) {
575
- if (spec.imported === '*')
576
- continue
577
- const target = resolveExportTarget(resolved, spec.imported)
578
- if (!target.file.endsWith('.tsx'))
579
- continue
580
- const targetAnalysis = loadAnalysis(target.file)
581
- if (targetAnalysis.isInteractive)
582
- bindings.set(spec.local, registerIsland(target.file, target.exportName))
583
- }
584
- }
585
- if (bindings.size > 0)
586
- pageIslandBindings.set(file, bindings)
587
197
  }
588
198
 
589
- // Collect component/page CSS & CSS Module imports from static modules (island CSS is bundled via island entrypoints)
590
- const islandCssFiles = new Set<string>()
591
- const collectIslandCss = (file: string, seen = new Set<string>()) => {
592
- if (seen.has(file))
593
- return
594
- seen.add(file)
595
- const analysis = analyses.get(file)
596
- if (analysis === undefined)
597
- return
598
- for (const imp of analysis.imports) {
599
- const target = resolveImportPath(file, imp.source)
600
- if (target === undefined)
601
- continue
602
- if (target.endsWith('.css'))
603
- islandCssFiles.add(target)
604
- else if (target.endsWith('.tsx') || target.endsWith('.ts'))
605
- collectIslandCss(target, seen)
606
- }
607
- }
608
- for (const [, target] of islandTargets)
609
- collectIslandCss(target.file)
610
-
611
- // The client compiles every module an island imports to hydrate against SSR markers, so their SSR must emit them too.
612
- const islandReach = new Set<string>()
613
- const reachSeen = new Set<string>()
614
- const reachStack = [...islandTargets.values()].map(t => t.file)
615
- while (reachStack.length > 0) {
616
- const file = reachStack.pop()!
617
- if (reachSeen.has(file))
618
- continue
619
- reachSeen.add(file)
620
- if (file.endsWith('.tsx'))
621
- islandReach.add(file)
622
- const analysis = analyses.get(file)
623
- for (const imp of analysis?.imports ?? []) {
624
- const target = resolveImportPath(file, imp.source)
625
- if (target !== undefined && (target.endsWith('.tsx') || target.endsWith('.ts')))
626
- reachStack.push(target)
627
- }
628
- for (const re of analysis?.reexports ?? []) {
629
- const target = resolveImportPath(file, re.source)
630
- if (target !== undefined && (target.endsWith('.tsx') || target.endsWith('.ts')))
631
- reachStack.push(target)
632
- }
633
- }
634
-
635
- const standaloneCssSet = new Set<string>(pluginCssFiles)
636
- for (const [file, analysis] of analyses) {
637
- for (const imp of analysis.imports) {
638
- const target = resolveImportPath(file, imp.source)
639
- if (target !== undefined && target.endsWith('.css') && !islandCssFiles.has(target))
640
- standaloneCssSet.add(target)
641
- }
642
- }
643
- const allStandaloneCss = [...standaloneCssSet]
644
-
645
- // Step 1 & Step 2: Single-pass Client + Server Builds
646
- // When there are no islands (e.g. static sites, blogs, docs), run client CSS and server builds in parallel!
647
- const islandChunks = new Map<string, string>()
648
- const srcCssToUrl = new Map<string, string>()
649
- const islandCssUrl = new Map<string, string>()
650
- const assetFiles: string[] = []
651
- const styleUrls: string[] = []
652
- let runtimeScript: string | undefined
653
- let clientMetafile: Bun.BuildOutput['metafile']
654
-
655
- const needsClientBuild = islandTargets.size > 0 || pluginClientEntries.length > 0 || allStandaloneCss.length > 0
199
+ const islands = planIslands(graph, root, pageFiles, specialFiles, actionsByFile)
656
200
 
657
- const runClientBuild = async (): Promise<void> => {
658
- if (!needsClientBuild)
659
- return
660
- const entriesDir = join(outDir, '.entries')
661
- mkdirSync(entriesDir, { recursive: true })
662
- const entryPoints: string[] = []
663
- const islandEntryToKey = new Map<string, string>()
664
-
665
- const compiledDomCache = new Map<string, string>()
666
- let hasDeferredHydrate = false
667
- let hasClientOnlyHydrate = false
668
-
669
- for (const [, analysis] of analyses) {
670
- if (analysis.defaultHydrate === 'client')
671
- hasClientOnlyHydrate = true
672
- else if (analysis.defaultHydrate !== undefined && analysis.defaultHydrate !== 'load')
673
- hasDeferredHydrate = true
674
- }
675
- for (const [, raw] of sources) {
676
- if (/\$hydrate\s*=\s*["'](?:visible|idle|interaction|media\()/.test(raw))
677
- hasDeferredHydrate = true
678
- if (/\$hydrate\s*=\s*["']client["']/.test(raw))
679
- hasClientOnlyHydrate = true
680
- }
681
-
682
- const runtimeEntryPath = join(entriesDir, 'runtime.ts')
683
- if (islandTargets.size > 0 || pluginClientEntries.length > 0) {
684
- const runtimeLines: string[] = []
685
- if (islandTargets.size > 0) {
686
- runtimeLines.push(`import { defineIslandElement } from 'kay/island';`)
687
- runtimeLines.push(`export { hydrate${hasClientOnlyHydrate ? ', mount' : ''} } from 'kay/dom';`)
688
- runtimeLines.push(`defineIslandElement();`)
689
- }
690
- for (const pe of pluginClientEntries)
691
- runtimeLines.push(`import ${JSON.stringify(pe)};`)
692
- writeFileSync(runtimeEntryPath, `${runtimeLines.join('\n')}\n`)
693
- entryPoints.push(runtimeEntryPath)
694
- }
695
-
696
- for (const cssFile of allStandaloneCss)
697
- entryPoints.push(cssFile)
698
-
699
- for (const [key, target] of islandTargets) {
700
- const entryPath = join(entriesDir, `${target.id}.ts`)
701
- const exportStmt = target.exportName === 'default'
702
- ? `export { default } from ${JSON.stringify(target.file)};\n`
703
- : `export { ${target.exportName} as default } from ${JSON.stringify(target.file)};\n`
704
- writeFileSync(entryPath, exportStmt)
705
- entryPoints.push(entryPath)
706
- islandEntryToKey.set(entryPath, key)
707
- }
708
-
709
- const clientLeaks = new Set<string>()
710
- const publicEnvDefines: Record<string, string> = {}
711
- for (const [key, value] of Object.entries(process.env)) {
712
- if (key.startsWith('PUBLIC_') && value !== undefined)
713
- publicEnvDefines[`process.env.${key}`] = JSON.stringify(value)
714
- }
715
- const inlinedEnvKey = (key: string): boolean => key === 'NODE_ENV' || `process.env.${key}` in publicEnvDefines
716
- const clientPlugin: BunPlugin = {
717
- name: 'kay-v2-client',
718
- setup(b) {
719
- // Bun swaps node built-ins for empty shims in a browser build, so a server-only import would ship silently.
720
- b.onResolve({ filter: SERVER_ONLY_FILTER }, (args) => {
721
- if (!args.importer.includes('/node_modules/'))
722
- clientLeaks.add(`${relative(root, args.importer).replace(/\\/g, '/')} imports server-only module "${args.path}"`)
723
- return undefined
724
- })
725
- b.onResolve({ filter: /^(?:@kayjs\/)?kay(?:\/.*)?$/ }, (args) => {
726
- const resolved = resolveKaySpecifier(args.path)
727
- return resolved !== undefined ? { path: resolved } : undefined
728
- })
729
- b.onLoad({ filter: /\.(?:ts|tsx)$/ }, (args) => {
730
- const actions = actionsByFile.get(args.path)
731
- if (actions !== undefined && !analyses.get(args.path)?.isInteractive) {
732
- const lines = [`import { actionStub } from 'kay/action';`]
733
- for (const a of actions)
734
- lines.push(`export const ${a.exportName} = actionStub(${JSON.stringify(a.url)});`)
735
- return { contents: `${lines.join('\n')}\n`, loader: 'ts' }
736
- }
737
-
738
- if (!args.path.endsWith('.tsx'))
739
- return undefined
740
-
741
- let compiled = compiledDomCache.get(args.path)
742
- if (compiled === undefined) {
743
- const stamp = getFileStamp(args.path)
744
- const cachedDom = stamp !== undefined ? cache?.domCompiled.get(args.path) : undefined
745
- if (cachedDom !== undefined && cachedDom.mtimeMs === stamp!.mtimeMs && cachedDom.size === stamp!.size) {
746
- compiled = cachedDom.code
747
- }
748
- else {
749
- const raw = sources.get(args.path) ?? readFileSync(args.path, 'utf8')
750
- compiled = applyTransforms(compileDom(args.path, raw, { analysis: analyses.get(args.path) }).code, args.path, 'client')
751
- if (cache !== undefined && stamp !== undefined)
752
- cache.domCompiled.set(args.path, { mtimeMs: stamp.mtimeMs, size: stamp.size, code: compiled })
753
- }
754
- compiledDomCache.set(args.path, compiled)
755
- }
756
- return { contents: compiled, loader: 'tsx' }
757
- })
758
- },
759
- }
760
-
761
- let clientResult: Awaited<ReturnType<typeof Bun.build>>
762
- try {
763
- clientResult = await Bun.build({
764
- entrypoints: entryPoints,
765
- outdir: clientDir,
766
- target: 'browser',
767
- format: 'esm',
768
- splitting: true,
769
- minify,
770
- metafile: true,
771
- naming: '[name]-[hash].[ext]',
772
- define: {
773
- KAY_DEFERRED: hasDeferredHydrate ? 'true' : 'false',
774
- KAY_CLIENT_ONLY: hasClientOnlyHydrate ? 'true' : 'false',
775
- 'process.env.NODE_ENV': JSON.stringify(isDev ? 'development' : 'production'),
776
- ...publicEnvDefines,
777
- },
778
- plugins: [clientPlugin, ...pluginBunPlugins],
779
- })
780
- }
781
- catch (err) {
782
- if (clientLeaks.size > 0)
783
- throw clientLeakError(clientLeaks)
784
- throw err
785
- }
786
- finally {
787
- rmSync(entriesDir, { recursive: true, force: true })
788
- }
789
-
790
- if (clientLeaks.size > 0)
791
- throw clientLeakError(clientLeaks)
792
- if (!clientResult.success) {
793
- const msgs = clientResult.logs.map(l => l.message).join('\n')
794
- throw new Error(`kay build (client) failed:\n${msgs}`)
795
- }
796
-
797
- clientMetafile = clientResult.metafile
798
- const resolveMetaPath = (p: string): string => {
799
- const fromCwd = resolve(process.cwd(), p)
800
- if (existsSync(fromCwd) || islandEntryToKey.has(fromCwd))
801
- return fromCwd
802
- return resolve(clientDir, p)
803
- }
804
-
805
- // A process.env left in a chunk is a key the build did not inline: name the app module that put it there.
806
- for (const output of clientResult.outputs) {
807
- if (!output.path.endsWith('.js') || !(await output.text()).includes('process.env'))
808
- continue
809
- const relFile = relative(clientDir, output.path).replace(/\\/g, '/')
810
- const info = clientMetafile?.outputs[relFile] ?? clientMetafile?.outputs[`./${relFile}`]
811
- for (const [inKey, input] of Object.entries(info?.inputs ?? {})) {
812
- const program = input.bytesInOutput > 0 ? analyses.get(resolveMetaPath(inKey))?.program : undefined
813
- if (program !== undefined && readsPrivateEnv(program, inlinedEnvKey))
814
- clientLeaks.add(`${relative(root, resolveMetaPath(inKey)).replace(/\\/g, '/')} reads process.env (only a process.env.PUBLIC_* set at build time is inlined)`)
815
- }
816
- }
817
- if (clientLeaks.size > 0)
818
- throw clientLeakError(clientLeaks)
819
-
820
- if (clientMetafile !== undefined) {
821
- for (const [outKey, info] of Object.entries(clientMetafile.outputs)) {
822
- const relOut = outKey.replace(/^\.\//, '')
823
- const url = `${assetPrefix}/${relOut}`
824
- const islandKey = info.entryPoint !== undefined && relOut.endsWith('.js') ? islandEntryToKey.get(resolveMetaPath(info.entryPoint)) : undefined
825
- if (islandKey !== undefined)
826
- islandChunks.set(islandKey, url)
827
- if (relOut.endsWith('.css')) {
828
- if (info.entryPoint !== undefined) {
829
- const absEntry = resolveMetaPath(info.entryPoint)
830
- if (absEntry.endsWith('.css'))
831
- srcCssToUrl.set(absEntry, url)
832
- }
833
- for (const inKey of Object.keys(info.inputs ?? {})) {
834
- if (inKey.endsWith('.css'))
835
- srcCssToUrl.set(resolveMetaPath(inKey), url)
836
- }
837
- }
838
- const cssBundle = (info as { cssBundle?: string }).cssBundle
839
- if (cssBundle !== undefined && info.entryPoint !== undefined) {
840
- const absEntry = resolveMetaPath(info.entryPoint)
841
- const islandKey = islandEntryToKey.get(absEntry)
842
- if (islandKey !== undefined)
843
- islandCssUrl.set(islandKey, `${assetPrefix}/${cssBundle.replace(/^\.\//, '')}`)
844
- }
845
- }
846
- }
847
-
848
- for (const output of clientResult.outputs) {
849
- const relFile = relative(clientDir, output.path).replace(/\\/g, '/')
850
- assetFiles.push(relFile)
851
- const url = `${assetPrefix}/${relFile}`
852
- if (relFile.endsWith('.css')) {
853
- styleUrls.push(url)
854
- }
855
- else if (output.kind === 'entry-point' && relFile.startsWith('runtime-')) {
856
- runtimeScript = url
857
- }
858
- }
859
- }
201
+ rmSync(outDir, { recursive: true, force: true })
202
+ mkdirSync(clientDir, { recursive: true })
203
+ mkdirSync(serverDir, { recursive: true })
204
+ const pluginCssFiles = plugins
205
+ .flatMap(p => p.css ?? [])
206
+ .map(c => resolve(root, c))
207
+ .filter(c => existsSync(c))
208
+ const env = { root, outDir, clientDir, serverDir, assetPrefix, minify: run.minify, isDev, analyze: options.analyze === true, graph, cache: options.cache, plugins, actionsByFile, islands }
860
209
 
210
+ const configSrc = join(root, 'kay.config.ts')
211
+ const hasConfigFile = existsSync(configSrc)
861
212
  const routeEntryFiles = new Set([...specialFiles, ...pageFiles])
862
213
  const standaloneActionFiles = [...actionsByFile.keys()].filter(f => !routeEntryFiles.has(f))
863
- const serverEntries = [...specialFiles, ...pageFiles, ...standaloneActionFiles]
864
- const serverRoot = standaloneActionFiles.length > 0 ? root : routesDir
865
-
866
- const relOut = relative(root, outDir)
867
- const outDirOutsideRoot = relOut !== '' && (relOut.startsWith('..') || isAbsolute(relOut))
868
- const EXTERNAL_KAY_SUBPATHS = new Set([
869
- 'kay/build',
870
- '@kayjs/kay/build',
871
- 'kay/compiler',
872
- '@kayjs/kay/compiler',
873
- 'kay/dev',
874
- '@kayjs/kay/dev',
875
- 'kay/test',
876
- '@kayjs/kay/test',
877
- ])
214
+ const serverEntries = [...specialFiles, ...pageFiles, ...standaloneActionFiles, ...(hasConfigFile ? [configSrc] : [])]
215
+ const serverRoot = standaloneActionFiles.length > 0 || hasConfigFile ? root : routesDir
878
216
 
879
- const reachesTsxCache = new Map<string, boolean>()
880
- function reachesTsx(file: string, stack = new Set<string>()): boolean {
881
- const cached = reachesTsxCache.get(file)
882
- if (cached !== undefined)
883
- return cached
884
- if (file.endsWith('.tsx')) {
885
- reachesTsxCache.set(file, true)
886
- return true
887
- }
888
- if (stack.has(file))
889
- return false
890
- stack.add(file)
891
- const analysis = analyses.get(file)
892
- if (analysis === undefined) {
893
- reachesTsxCache.set(file, false)
894
- return false
895
- }
896
- for (const imp of analysis.imports) {
897
- const target = resolveImportPath(file, imp.source)
898
- if (target !== undefined && reachesTsx(target, stack)) {
899
- reachesTsxCache.set(file, true)
900
- return true
901
- }
902
- }
903
- for (const re of analysis.reexports) {
904
- const target = resolveImportPath(file, re.source)
905
- if (target !== undefined && reachesTsx(target, stack)) {
906
- reachesTsxCache.set(file, true)
907
- return true
908
- }
909
- }
910
- reachesTsxCache.set(file, false)
911
- return false
217
+ // The server compiles against the island chunk URLs, so islands build first; without islands both passes run in parallel.
218
+ const clientPass = () => buildClient(env, standaloneCssFiles(graph, pluginCssFiles, islands.cssFiles))
219
+ let client: Awaited<ReturnType<typeof clientPass>>
220
+ if (islands.targets.size === 0) {
221
+ const [built] = await Promise.all([clientPass(), buildServer(env, serverEntries, serverRoot, new Map())])
222
+ client = built
912
223
  }
913
-
914
- const runServerBuild = async (): Promise<void> => {
915
- const serverPlugin: BunPlugin = {
916
- name: 'kay-v2-server',
917
- setup(b) {
918
- b.onResolve({ filter: /^(?:@kayjs\/)?kay(?:\/.*)?$/ }, (args) => {
919
- const resolved = resolveKaySpecifier(args.path)
920
- if (resolved === undefined)
921
- return undefined
922
- return EXTERNAL_KAY_SUBPATHS.has(args.path) ? { path: resolved, external: true } : { path: resolved }
923
- })
924
- b.onResolve({ filter: /^@kayjs\// }, (args) => {
925
- try {
926
- return { path: Bun.resolveSync(args.path, args.resolveDir || root) }
927
- }
928
- catch {
929
- return undefined
930
- }
931
- })
932
- b.onResolve({ filter: /^[^./]/ }, (args) => {
933
- if (args.path === 'bun' || args.path.startsWith('bun:') || args.path.startsWith('node:') || args.path.startsWith('~') || isAbsolute(args.path))
934
- return undefined
935
- let resolved: string | undefined
936
- try {
937
- resolved = Bun.resolveSync(args.path, args.resolveDir || root)
938
- }
939
- catch {
940
- try {
941
- resolved = Bun.resolveSync(args.path, root)
942
- }
943
- catch {
944
- return undefined
945
- }
946
- }
947
- // Bundle any package that exports/re-exports .tsx components so Kay's SSR compiler transforms them.
948
- if (resolved.endsWith('.tsx') || reachesTsx(resolved))
949
- return { path: resolved }
950
- if (outDirOutsideRoot)
951
- return { path: resolved, external: true }
952
- return undefined
953
- })
954
- b.onLoad({ filter: /\.tsx$/ }, (args) => {
955
- const analysis = analyses.get(args.path)
956
- const rawBindings = pageIslandBindings.get(args.path)
957
- let islandMap: Map<string, IslandBinding> | undefined
958
- const isInteractive = analysis?.isInteractive === true
959
- const emitMarkers = isInteractive || islandReach.has(args.path)
960
- let islandKey = `${isInteractive ? '1' : '0'}:${emitMarkers ? '1' : '0'}`
961
- if (rawBindings !== undefined) {
962
- islandMap = new Map()
963
- for (const [localName, target] of rawBindings) {
964
- const chunk = islandChunks.get(`${target.file}#${target.exportName}`)
965
- if (chunk !== undefined) {
966
- islandMap.set(localName, {
967
- id: target.id,
968
- chunk,
969
- defaultHydrate: target.defaultHydrate,
970
- })
971
- islandKey += `|${localName}=${chunk}:${target.defaultHydrate ?? ''}`
972
- }
973
- }
974
- }
975
- const stamp = getFileStamp(args.path)
976
- const cachedSsr = stamp !== undefined ? cache?.ssrCompiled.get(args.path) : undefined
977
- if (cachedSsr !== undefined && cachedSsr.mtimeMs === stamp!.mtimeMs && cachedSsr.size === stamp!.size && cachedSsr.key === islandKey)
978
- return { contents: cachedSsr.code, loader: 'tsx' }
979
- const raw = sources.get(args.path) ?? readFileSync(args.path, 'utf8')
980
- const ssrOpts = {
981
- analysis,
982
- islands: islandMap,
983
- isIsland: isInteractive,
984
- emitMarkers,
985
- } as Parameters<typeof compileSsr>[2]
986
- const compiled = compileSsr(args.path, raw, ssrOpts)
987
- const outCode = applyTransforms(compiled.code, args.path, 'server')
988
- if (cache !== undefined && stamp !== undefined)
989
- cache.ssrCompiled.set(args.path, { mtimeMs: stamp.mtimeMs, size: stamp.size, key: islandKey, code: outCode })
990
- return { contents: outCode, loader: 'tsx' }
991
- })
992
- },
993
- }
994
-
995
- const serverResult = await Bun.build({
996
- entrypoints: serverEntries,
997
- outdir: serverDir,
998
- root: serverRoot,
999
- target: 'bun',
1000
- format: 'esm',
1001
- splitting: true,
1002
- packages: 'external',
1003
- minify: false,
1004
- define: {
1005
- 'process.env.NODE_ENV': 'process.env.NODE_ENV',
1006
- },
1007
- plugins: [serverPlugin, ...pluginBunPlugins],
1008
- })
1009
-
1010
- if (!serverResult.success) {
1011
- const msgs = serverResult.logs.map(l => l.message).join('\n')
1012
- throw new Error(`kay build (server) failed:\n${msgs}`)
1013
- }
224
+ else {
225
+ client = await clientPass()
226
+ await buildServer(env, serverEntries, serverRoot, client.islandChunks)
1014
227
  }
1015
228
 
1016
- if (islandTargets.size === 0) {
1017
- await Promise.all([runClientBuild(), runServerBuild()])
1018
- }
1019
- else {
1020
- await runClientBuild()
1021
- await runServerBuild()
229
+ if (options.cache !== undefined) {
230
+ const watched = options.cache.watchedFiles
231
+ watched.clear()
232
+ const recordWatched = (file: string) => {
233
+ if (!existsSync(file))
234
+ return
235
+ let real = file
236
+ try {
237
+ real = realpathSync(file)
238
+ }
239
+ catch {}
240
+ watched.add(real)
241
+ }
242
+ for (const f of graph.analyses.keys())
243
+ recordWatched(f)
244
+ for (const f of options.cache.lastClient?.inputStamps.keys() ?? [])
245
+ recordWatched(f)
246
+ for (const f of options.cache.lastServer?.inputStamps.keys() ?? [])
247
+ recordWatched(f)
248
+ for (const f of pluginCssFiles)
249
+ recordWatched(f)
250
+ if (hasConfigFile)
251
+ recordWatched(configSrc)
252
+ // Prune deleted files from caches so long-lived dev sessions stay flat in memory.
253
+ for (const f of [...options.cache.analyses.keys()]) {
254
+ if (!existsSync(f))
255
+ options.cache.analyses.delete(f)
256
+ }
257
+ for (const f of [...options.cache.domCompiled.keys()]) {
258
+ if (!existsSync(f))
259
+ options.cache.domCompiled.delete(f)
260
+ }
261
+ for (const f of [...options.cache.ssrCompiled.keys()]) {
262
+ if (!existsSync(f))
263
+ options.cache.ssrCompiled.delete(f)
264
+ }
1022
265
  }
1023
266
 
1024
267
  const toOutRel = (srcFile: string): string =>
1025
- relative(outDir, join(serverDir, relative(serverRoot, srcFile).replace(/\.(tsx|ts)$/, '.js'))).replace(/\\/g, '/')
268
+ relPosix(outDir, join(serverDir, relative(serverRoot, srcFile).replace(/\.(tsx|ts)$/, '.js')))
1026
269
 
1027
- const nonEmptyAssets = assetFiles.filter((rel) => {
270
+ const assets: string[] = []
271
+ for (const rel of client.assetFiles) {
1028
272
  const abs = join(clientDir, rel)
1029
- if (!existsSync(abs))
1030
- return false
1031
- if (readFileSync(abs).length === 0) {
273
+ const size = fileSize(abs)
274
+ if (size === 0)
1032
275
  rmSync(abs, { force: true })
1033
- return false
1034
- }
1035
- return true
1036
- })
1037
-
1038
- function collectRouteIslands(file: string, seen = new Set<string>(), all = new Set<string>(), eager = new Set<string>()): void {
1039
- if (seen.has(file))
1040
- return
1041
- seen.add(file)
1042
- const analysis = analyses.get(file)
1043
- if (analysis === undefined)
1044
- return
1045
- if (analysis.isInteractive) {
1046
- const chunk = islandChunks.get(`${file}#default`)
1047
- if (chunk !== undefined) {
1048
- all.add(chunk)
1049
- if (analysis.defaultHydrate === undefined || analysis.defaultHydrate === 'load')
1050
- eager.add(chunk)
1051
- }
1052
- return
1053
- }
1054
- const bindings = pageIslandBindings.get(file)
1055
- if (bindings !== undefined) {
1056
- for (const [localName, target] of bindings) {
1057
- const chunk = islandChunks.get(`${target.file}#${target.exportName}`)
1058
- if (chunk !== undefined) {
1059
- all.add(chunk)
1060
- const isDeferred = analysis.deferredIslandTags.has(localName)
1061
- || (target.defaultHydrate !== undefined && target.defaultHydrate !== 'load')
1062
- if (!isDeferred)
1063
- eager.add(chunk)
1064
- }
1065
- }
1066
- }
1067
- for (const imp of analysis.imports) {
1068
- const target = resolveImportPath(file, imp.source)
1069
- if (target !== undefined && target.endsWith('.tsx'))
1070
- collectRouteIslands(target, seen, all, eager)
1071
- }
1072
- }
1073
-
1074
- function collectUsesRenderContext(file: string, seen = new Set<string>()): boolean {
1075
- if (seen.has(file))
1076
- return false
1077
- seen.add(file)
1078
- const analysis = analyses.get(file)
1079
- if (analysis === undefined)
1080
- return false
1081
- if (analysis.usesRenderContext)
1082
- return true
1083
- for (const imp of analysis.imports) {
1084
- const target = resolveImportPath(file, imp.source)
1085
- if (target !== undefined && target.endsWith('.tsx') && collectUsesRenderContext(target, seen))
1086
- return true
1087
- }
1088
- return false
1089
- }
1090
-
1091
- function collectRouteStyles(file: string, seen = new Set<string>(), out = new Set<string>()): void {
1092
- if (seen.has(file))
1093
- return
1094
- seen.add(file)
1095
- const analysis = analyses.get(file)
1096
- if (analysis === undefined)
1097
- return
1098
- if (analysis.isInteractive) {
1099
- const islCss = islandCssUrl.get(`${file}#default`)
1100
- if (islCss !== undefined)
1101
- out.add(islCss)
1102
- }
1103
- const bindings = pageIslandBindings.get(file)
1104
- if (bindings !== undefined) {
1105
- for (const [, target] of bindings) {
1106
- const islCss = islandCssUrl.get(`${target.file}#${target.exportName}`)
1107
- if (islCss !== undefined)
1108
- out.add(islCss)
1109
- collectRouteStyles(target.file, seen, out)
1110
- }
1111
- }
1112
- for (const imp of analysis.imports) {
1113
- const target = resolveImportPath(file, imp.source)
1114
- if (target === undefined)
1115
- continue
1116
- if (target.endsWith('.css')) {
1117
- const cssUrl = srcCssToUrl.get(target)
1118
- if (cssUrl !== undefined)
1119
- out.add(cssUrl)
1120
- }
1121
- else if (target.endsWith('.tsx') || target.endsWith('.ts')) {
1122
- collectRouteStyles(target, seen, out)
1123
- }
1124
- }
1125
- }
1126
-
1127
- const globalPluginStyles: string[] = []
1128
- for (const cssFile of pluginCssFiles) {
1129
- const url = srcCssToUrl.get(cssFile)
1130
- if (url !== undefined && !globalPluginStyles.includes(url))
1131
- globalPluginStyles.push(url)
1132
- }
1133
-
1134
- const rootLayoutSrc = join(routesDir, '_layout.tsx')
1135
- const globalStyleSet = new Set<string>(globalPluginStyles)
1136
- if (existsSync(rootLayoutSrc))
1137
- collectRouteStyles(rootLayoutSrc, new Set(), globalStyleSet)
1138
- const globalStyles = [...globalStyleSet]
1139
-
1140
- const routeEntries: RouteManifestEntry[] = pageFiles.map((file) => {
1141
- const analysis = analyses.get(file)
1142
- const layoutSrcs = ancestorFiles(routesDir, file, ['_layout.tsx'])
1143
- const middlewareSrcs = ancestorFiles(routesDir, file, ['_middleware.ts', '_middleware.tsx'])
1144
- const chunks = new Set<string>()
1145
- const eagerChunks = new Set<string>()
1146
- const routeStyles = new Set<string>(globalPluginStyles)
1147
- for (const lf of layoutSrcs) {
1148
- collectRouteIslands(lf, new Set(), chunks, eagerChunks)
1149
- collectRouteStyles(lf, new Set(), routeStyles)
1150
- }
1151
- collectRouteIslands(file, new Set(), chunks, eagerChunks)
1152
- collectRouteStyles(file, new Set(), routeStyles)
1153
-
1154
- let usesRenderContext = collectUsesRenderContext(file)
1155
- if (!usesRenderContext) {
1156
- for (const lf of layoutSrcs) {
1157
- if (collectUsesRenderContext(lf)) {
1158
- usesRenderContext = true
1159
- break
1160
- }
1161
- }
1162
- }
1163
-
1164
- const islandKey = `${file}#default`
1165
- return {
1166
- path: fileToRoutePath(routesDir, file),
1167
- file: toOutRel(file),
1168
- layouts: layoutSrcs.map(toOutRel),
1169
- middlewares: middlewareSrcs.map(toOutRel),
1170
- hasLoad: analysis?.hasLoadExport,
1171
- isIsland: analysis?.isInteractive,
1172
- islandChunk: islandChunks.get(islandKey),
1173
- islandHydrate: analysis?.defaultHydrate,
1174
- islandChunks: [...chunks],
1175
- eagerIslandChunks: [...eagerChunks],
1176
- styles: [...routeStyles],
1177
- usesRenderContext,
1178
- prerender: analysis?.hasPrerender || options.static === true,
1179
- }
276
+ else if (size !== undefined)
277
+ assets.push(rel)
278
+ }
279
+
280
+ const { routes, globalStyles } = buildRouteEntries({
281
+ graph,
282
+ islands,
283
+ islandChunks: client.islandChunks,
284
+ srcCssToUrl: client.srcCssToUrl,
285
+ islandCssUrl: client.islandCssUrl,
286
+ routesDir,
287
+ pageFiles,
288
+ pluginCssFiles,
289
+ isStatic,
290
+ toOutRel,
1180
291
  })
1181
292
 
1182
- const actionEntries: ActionManifestEntry[] = []
1183
- for (const [srcFile, list] of actionsByFile) {
1184
- const outFile = toOutRel(srcFile)
1185
- const inRoutes = !relative(routesDir, srcFile).startsWith('..')
1186
- const middlewares = inRoutes ? ancestorFiles(routesDir, srcFile, ['_middleware.ts', '_middleware.tsx']).map(toOutRel) : []
1187
- for (const a of list)
1188
- actionEntries.push({ url: a.url, file: outFile, exportName: a.exportName, middlewares })
1189
- }
1190
-
1191
- const islandsRecord: Record<string, string> = {}
1192
- for (const [k, v] of islandChunks)
1193
- islandsRecord[k] = v
1194
-
1195
- // Copy public/ static files into dist/public (skipped in `kay dev`, where createServer streams directly from public/)
1196
- const publicFiles: string[] = []
293
+ // public/ files are listed in the manifest and copied into outDir/public (`kay dev` serves public/ directly instead)
1197
294
  const outPublicDir = join(outDir, 'public')
1198
- const shouldCopyPublic = options.copyPublic !== false
1199
- if (existsSync(publicDir)) {
1200
- for (const abs of walkAllFiles(publicDir).sort()) {
1201
- const rel = relative(publicDir, abs).replace(/\\/g, '/')
1202
- publicFiles.push(rel)
1203
- if (shouldCopyPublic) {
1204
- const dst = join(outPublicDir, rel)
1205
- mkdirSync(dirname(dst), { recursive: true })
1206
- writeFileSync(dst, readFileSync(abs))
1207
- }
295
+ for (const abs of walkAllFiles(run.publicDir).sort()) {
296
+ const rel = publicFiles.register(relative(run.publicDir, abs))
297
+ if (options.copyPublic !== false) {
298
+ mkdirSync(dirname(join(outPublicDir, rel)), { recursive: true })
299
+ copyFileSync(abs, join(outPublicDir, rel))
1208
300
  }
1209
301
  }
1210
302
 
1211
- // Run plugin build(ctx) hooks so plugins can emit hashed assets, public files, styles, or <head> tags
1212
- const headTags: string[] = []
1213
- const assetSet = new Set(nonEmptyAssets)
1214
- const publicSet = new Set(publicFiles)
1215
- const styleSet = new Set(styleUrls)
1216
-
1217
- const buildPluginCtx: BuildPluginContext = {
303
+ const host = createPluginHost({
304
+ plugins,
305
+ appCtx: run.appCtx,
1218
306
  root,
1219
307
  outDir,
308
+ clientDir,
309
+ outPublicDir,
1220
310
  assetPrefix,
1221
- minify,
1222
- routes: routeEntries,
1223
- emitAsset(relPath, content) {
1224
- const clean = relPath.replace(/^\/+/, '').replace(/\\/g, '/')
1225
- const dst = join(clientDir, clean)
1226
- mkdirSync(dirname(dst), { recursive: true })
1227
- writeFileSync(dst, content)
1228
- if (!assetSet.has(clean)) {
1229
- assetSet.add(clean)
1230
- nonEmptyAssets.push(clean)
1231
- }
1232
- return `${assetPrefix}/${clean}`
1233
- },
1234
- emitPublic(relPath, content) {
1235
- const clean = relPath.replace(/^\/+/, '').replace(/\\/g, '/')
1236
- const dst = join(outPublicDir, clean)
1237
- mkdirSync(dirname(dst), { recursive: true })
1238
- writeFileSync(dst, content)
1239
- if (!publicSet.has(clean)) {
1240
- publicSet.add(clean)
1241
- publicFiles.push(clean)
1242
- }
1243
- return `/${clean}`
1244
- },
1245
- addStyle(href) {
1246
- if (!styleSet.has(href)) {
1247
- styleSet.add(href)
1248
- styleUrls.push(href)
1249
- }
1250
- if (!globalStyleSet.has(href)) {
1251
- globalStyleSet.add(href)
1252
- globalStyles.push(href)
1253
- }
1254
- for (const r of routeEntries) {
1255
- if (r.styles !== undefined && !r.styles.includes(href))
1256
- r.styles.push(href)
1257
- }
1258
- },
1259
- addRouteStyle(routePath, href) {
1260
- if (!styleSet.has(href)) {
1261
- styleSet.add(href)
1262
- styleUrls.push(href)
1263
- }
1264
- const route = routeEntries.find(r => r.path === routePath)
1265
- if (route !== undefined) {
1266
- route.styles ??= [...globalStyles]
1267
- if (!route.styles.includes(href))
1268
- route.styles.push(href)
1269
- }
1270
- },
1271
- addHead(html) {
1272
- if (html !== '')
1273
- headTags.push(html)
1274
- },
1275
- addRouteHead(routePath, html) {
1276
- if (html === '')
1277
- return
1278
- const route = routeEntries.find(r => r.path === routePath)
1279
- if (route !== undefined) {
1280
- route.headTags ??= []
1281
- route.headTags.push(html)
1282
- }
1283
- },
1284
- }
1285
-
1286
- for (const plugin of plugins) {
1287
- if (plugin.build !== undefined)
1288
- await plugin.build(buildPluginCtx)
1289
- }
1290
-
1291
- // Precompress hashed client assets (.br / .gz sidecars) for production server builds (skip in dev & --static, which compresses its own output)
1292
- if (!isDev && !options.static) {
1293
- for (const rel of nonEmptyAssets)
1294
- precompressFile(join(clientDir, rel), 256)
1295
- }
311
+ site: run.site,
312
+ minify: run.minify,
313
+ isStatic,
314
+ isDev,
315
+ routes,
316
+ publicFiles,
317
+ assets,
318
+ styleUrls: client.styleUrls,
319
+ globalStyles,
320
+ })
321
+ await host.runBuild()
322
+ host.precompressAssets()
1296
323
 
1297
324
  const manifest: BuildManifest = {
1298
- runtimeScript,
1299
- styles: styleUrls,
325
+ runtimeScript: client.runtimeScript,
326
+ styles: client.styleUrls,
1300
327
  globalStyles,
1301
- ...(headTags.length > 0 ? { headTags } : {}),
1302
- routes: routeEntries,
328
+ ...(host.headTags.length > 0 ? { headTags: host.headTags } : {}),
329
+ routes,
330
+ ...(hasConfigFile ? { configFile: toOutRel(configSrc) } : {}),
331
+ ...(hasRootLayout ? { rootLayoutFile: toOutRel(rootLayoutSrc) } : {}),
1303
332
  errorFile: hasErrorFile ? toOutRel(errorSrc) : undefined,
1304
333
  notFoundFile: hasNotFoundFile ? toOutRel(notFoundSrc) : undefined,
1305
- actions: actionEntries,
1306
- islands: islandsRecord,
1307
- assets: nonEmptyAssets,
1308
- publicFiles,
1309
- }
1310
-
1311
- writeFileSync(join(outDir, 'manifest.json'), JSON.stringify(manifest, null, 2))
1312
-
1313
- // Step 3: Hybrid Prerendering / Static Export (skipped in `kay dev` where routes render on-demand)
1314
- const shouldPrerender = options.prerender !== false || options.static === true
1315
- const prerenderRoutes = shouldPrerender ? routeEntries.filter(r => r.prerender) : []
1316
- if (prerenderRoutes.length > 0 || options.static) {
1317
- const { createServer } = await import('../server/index')
1318
- const app = await createServer({ root, outDir: relative(root, outDir), assetPrefix, plugins })
1319
- const prerenderDir = options.static ? staticStageDir! : join(outDir, 'prerendered')
1320
- mkdirSync(prerenderDir, { recursive: true })
1321
-
1322
- const prerenderStamp = Date.now()
1323
- for (const route of prerenderRoutes) {
1324
- const mod = await import(`${join(outDir, route.file)}?v=${prerenderStamp}`) as { paths?: () => Promise<string[]> | string[] }
1325
- let urls: string[] = []
1326
- if (!route.path.includes(':') && !route.path.includes('*')) {
1327
- urls = [route.path]
1328
- }
1329
- else if (typeof mod.paths === 'function') {
1330
- urls = await mod.paths()
1331
- }
1332
- else if (options.static) {
1333
- console.warn(`kay build --static: skipping dynamic route "${route.path}" (${route.file}) because it does not export a paths() function.`)
1334
- }
1335
-
1336
- if (urls.length === 0)
1337
- continue
1338
-
1339
- for (const plugin of plugins) {
1340
- if (plugin.prerenderPaths !== undefined)
1341
- urls = await plugin.prerenderPaths(urls, route)
1342
- }
1343
-
1344
- const map: Record<string, string> = {}
1345
- const CONCURRENCY = 8
1346
- for (let i = 0; i < urls.length; i += CONCURRENCY) {
1347
- const batch = urls.slice(i, i + CONCURRENCY)
1348
- await Promise.all(batch.map(async (u) => {
1349
- const res = await app.handle(new Request(`http://localhost${u}`))
1350
- const isExplicit404 = u === '/404' && res.status === 404
1351
- if (res.status !== 200 && !isExplicit404) {
1352
- if (options.static)
1353
- throw new Error(`kay build --static: route "${u}" returned HTTP ${res.status} (expected 200).`)
1354
- return
1355
- }
1356
- const html = await res.text()
1357
- const relHtml = u === '/' ? 'index.html' : `${u.replace(/^\//, '').replace(/\/$/, '')}/index.html`
1358
- const absHtml = join(prerenderDir, relHtml)
1359
- mkdirSync(dirname(absHtml), { recursive: true })
1360
- writeFileSync(absHtml, html)
1361
- map[u] = relative(options.static ? prerenderDir : outDir, absHtml).replace(/\\/g, '/')
1362
- }))
1363
- }
1364
- route.prerendered = map
1365
- }
1366
-
1367
- if (options.static) {
1368
- if (hasNotFoundFile) {
1369
- const notFoundRes = await app.handle(new Request('http://localhost/__kay_404__'))
1370
- if (notFoundRes.status >= 500)
1371
- throw new Error(`kay build --static: _404 page returned HTTP ${notFoundRes.status}.`)
1372
- writeFileSync(join(prerenderDir, '404.html'), await notFoundRes.text())
1373
- }
1374
- // Copy client assets into <stage>/_kay/... and public/ files into <stage>/...
1375
- if (nonEmptyAssets.length > 0) {
1376
- const staticAssetDir = join(prerenderDir, assetPrefix.replace(/^\//, ''))
1377
- mkdirSync(staticAssetDir, { recursive: true })
1378
- for (const rel of nonEmptyAssets) {
1379
- const dst = join(staticAssetDir, rel)
1380
- mkdirSync(dirname(dst), { recursive: true })
1381
- writeFileSync(dst, readFileSync(join(clientDir, rel)))
1382
- }
1383
- }
1384
- // Re-scan outPublicDir so any assets emitted during prerender (e.g. OG share cards, optimized MD images) are included in --static
1385
- if (existsSync(outPublicDir)) {
1386
- for (const abs of walkAllFiles(outPublicDir)) {
1387
- const rel = relative(outPublicDir, abs).replace(/\\/g, '/')
1388
- if (!publicSet.has(rel)) {
1389
- publicSet.add(rel)
1390
- publicFiles.push(rel)
1391
- }
1392
- }
1393
- }
1394
- for (const rel of publicFiles) {
1395
- const dst = join(prerenderDir, rel)
1396
- mkdirSync(dirname(dst), { recursive: true })
1397
- writeFileSync(dst, readFileSync(join(outDir, 'public', rel)))
1398
- }
1399
- // Emit precompressed .br and .gz sidecars for compressible static files (>= 128 B)
1400
- for (const abs of walkAllFiles(prerenderDir))
1401
- precompressFile(abs, 128)
334
+ actions: buildActionEntries(actionsByFile, routesDir, toOutRel),
335
+ islands: Object.fromEntries(client.islandChunks),
336
+ assets,
337
+ publicFiles: publicFiles.files,
338
+ ...(Object.keys(host.pluginData).length > 0 ? { pluginData: host.pluginData } : {}),
339
+ }
340
+ const writeManifest = (): void => writeFileSync(join(outDir, 'manifest.json'), JSON.stringify(manifest, null, 2))
341
+ writeManifest()
342
+
343
+ // Hybrid prerendering / static export (skipped in `kay dev`, where routes render on-demand)
344
+ const prerenderRoutes = options.prerender !== false || isStatic ? routes.filter(r => r.prerender) : []
345
+ const prerenderDir = isStatic ? run.staticStageDir! : join(outDir, 'prerendered')
346
+ const app = prerenderRoutes.length > 0 || isStatic
347
+ ? await prerender({ root, outDir, assetPrefix, site: run.site, plugins, isDev, isStatic, prerenderDir, routes: prerenderRoutes })
348
+ : undefined
1402
349
 
1403
- // Atomically swap staged static output into finalOutDir only after every page and asset succeeded
1404
- if (existsSync(finalOutDir)) {
1405
- const backupDir = join(dirname(finalOutDir), `.${basename(finalOutDir)}.prev-${stageSuffix}`)
1406
- renameSync(finalOutDir, backupDir)
1407
- try {
1408
- renameSync(prerenderDir, finalOutDir)
1409
- }
1410
- catch (err) {
1411
- try {
1412
- renameSync(backupDir, finalOutDir)
1413
- }
1414
- catch {}
1415
- throw err
1416
- }
1417
- rmSync(backupDir, { recursive: true, force: true })
1418
- }
1419
- else {
1420
- mkdirSync(dirname(finalOutDir), { recursive: true })
1421
- renameSync(prerenderDir, finalOutDir)
1422
- }
350
+ try {
351
+ const ranAfterPrerender = await host.runAfterPrerender()
352
+ host.precompressAssets()
353
+ if (Object.keys(host.pluginData).length > 0)
354
+ manifest.pluginData = host.pluginData
355
+
356
+ if (isStatic) {
357
+ await exportStatic({
358
+ stageDir: prerenderDir,
359
+ finalOutDir: run.finalOutDir,
360
+ outDir,
361
+ clientDir,
362
+ assetPrefix,
363
+ assets,
364
+ publicFiles,
365
+ app,
366
+ hasNotFoundFile,
367
+ stageSuffix: run.stageSuffix,
368
+ })
1423
369
  }
1424
- else {
1425
- writeFileSync(join(outDir, 'manifest.json'), JSON.stringify(manifest, null, 2))
370
+ else if (prerenderRoutes.length > 0 || ranAfterPrerender) {
371
+ writeManifest()
1426
372
  }
1427
373
  }
374
+ finally {
375
+ await app?.dispose?.()
376
+ }
1428
377
 
1429
- // Step 4: Single-Executable Compile (`kay build --compile [outfile]`)
1430
378
  if (options.compile) {
1431
- const outfile = typeof options.compile === 'string' ? resolve(root, options.compile) : join(outDir, 'server-bin')
1432
379
  await compileExecutable({
1433
380
  root,
1434
381
  outDir,
1435
382
  clientDir,
1436
383
  manifest,
1437
384
  assetPrefix,
1438
- outfile,
385
+ outfile: typeof options.compile === 'string' ? resolve(root, options.compile) : join(outDir, 'server-bin'),
1439
386
  kaySrcRoot: KAY_SRC_ROOT,
1440
387
  resolveKaySpecifier,
1441
- bunPlugins: pluginBunPlugins,
388
+ bunPlugins: pluginBunPlugins(env, 'compile'),
1442
389
  })
1443
390
  }
1444
391
 
1445
392
  if (options.analyze)
1446
- console.log(formatBundleReport(manifest, clientDir, assetPrefix, clientMetafile))
393
+ console.log(formatBundleReport(manifest, clientDir, assetPrefix, client.metafile))
1447
394
 
1448
395
  return manifest
1449
- }
1450
- }
1451
-
1452
- export interface RouteBundleMetrics {
1453
- path: string
1454
- jsRaw: number
1455
- jsGzip: number
1456
- cssRaw: number
1457
- cssGzip: number
1458
- jsFiles: number
1459
- cssFiles: number
1460
- }
1461
-
1462
- export function analyzeBundleWeights(
1463
- manifest: BuildManifest,
1464
- clientDir: string,
1465
- assetPrefix = '/_kay',
1466
- metafile?: Bun.BuildOutput['metafile'],
1467
- ): { routes: RouteBundleMetrics[], totalJsGzip: number, totalCssGzip: number, topModules: { path: string, bytes: number }[] } {
1468
- const prefix = `${assetPrefix.replace(/\/$/, '')}/`
1469
- const sizeCache = new Map<string, { raw: number, gzip: number }>()
1470
-
1471
- const getSize = (url: string): { raw: number, gzip: number } => {
1472
- const cached = sizeCache.get(url)
1473
- if (cached !== undefined)
1474
- return cached
1475
- if (!url.startsWith(prefix))
1476
- return { raw: 0, gzip: 0 }
1477
- const abs = join(clientDir, url.slice(prefix.length))
1478
- if (!existsSync(abs))
1479
- return { raw: 0, gzip: 0 }
1480
- const buf = readFileSync(abs)
1481
- const entry = { raw: buf.byteLength, gzip: Bun.gzipSync(buf, { level: 9 }).byteLength }
1482
- sizeCache.set(url, entry)
1483
- return entry
1484
- }
1485
-
1486
- // Collect transitive JS chunk imports from metafile so eager JS includes shared runtime chunks!
1487
- const jsDeps = new Map<string, string[]>()
1488
- const moduleBytes = new Map<string, number>()
1489
- if (metafile !== undefined) {
1490
- for (const [outKey, info] of Object.entries(metafile.outputs)) {
1491
- const rel = outKey.replace(/^\.\//, '')
1492
- const url = `${prefix}${rel}`
1493
- if (rel.endsWith('.js')) {
1494
- const deps: string[] = []
1495
- for (const imp of info.imports ?? []) {
1496
- if (imp.kind === 'import-statement')
1497
- deps.push(`${prefix}${imp.path.replace(/^\.\//, '')}`)
1498
- }
1499
- jsDeps.set(url, deps)
1500
- }
1501
- for (const [inPath, inInfo] of Object.entries(info.inputs ?? {}))
1502
- moduleBytes.set(inPath, (moduleBytes.get(inPath) ?? 0) + inInfo.bytesInOutput)
1503
- }
1504
- }
1505
-
1506
- const collectTransitiveJs = (urls: readonly string[]): Set<string> => {
1507
- const seen = new Set<string>()
1508
- const stack = [...urls]
1509
- while (stack.length > 0) {
1510
- const cur = stack.pop()!
1511
- if (seen.has(cur))
1512
- continue
1513
- seen.add(cur)
1514
- for (const dep of jsDeps.get(cur) ?? [])
1515
- stack.push(dep)
1516
- }
1517
- return seen
1518
- }
1519
-
1520
- const routes: RouteBundleMetrics[] = manifest.routes.map((r) => {
1521
- const eagerJsRoots: string[] = []
1522
- if (r.islandChunks.length > 0 && manifest.runtimeScript !== undefined)
1523
- eagerJsRoots.push(manifest.runtimeScript)
1524
- for (const c of r.eagerIslandChunks ?? r.islandChunks)
1525
- eagerJsRoots.push(c)
1526
-
1527
- const jsSet = collectTransitiveJs(eagerJsRoots)
1528
- let jsRaw = 0
1529
- let jsGzip = 0
1530
- for (const u of jsSet) {
1531
- const s = getSize(u)
1532
- jsRaw += s.raw
1533
- jsGzip += s.gzip
1534
- }
1535
-
1536
- const cssList = r.styles ?? manifest.styles
1537
- let cssRaw = 0
1538
- let cssGzip = 0
1539
- for (const u of cssList) {
1540
- const s = getSize(u)
1541
- cssRaw += s.raw
1542
- cssGzip += s.gzip
1543
- }
1544
-
1545
- return {
1546
- path: r.path,
1547
- jsRaw,
1548
- jsGzip,
1549
- cssRaw,
1550
- cssGzip,
1551
- jsFiles: jsSet.size,
1552
- cssFiles: cssList.length,
1553
- }
1554
- })
1555
-
1556
- let totalJsGzip = 0
1557
- let totalCssGzip = 0
1558
- for (const rel of manifest.assets) {
1559
- const s = getSize(`${prefix}${rel}`)
1560
- if (rel.endsWith('.js'))
1561
- totalJsGzip += s.gzip
1562
- else if (rel.endsWith('.css'))
1563
- totalCssGzip += s.gzip
1564
- }
1565
-
1566
- const topModules = [...moduleBytes.entries()]
1567
- .map(([path, bytes]) => ({ path, bytes }))
1568
- .sort((a, b) => b.bytes - a.bytes)
1569
- .slice(0, 10)
1570
-
1571
- return { routes, totalJsGzip, totalCssGzip, topModules }
1572
- }
1573
-
1574
- export function formatBundleReport(
1575
- manifest: BuildManifest,
1576
- clientDir: string,
1577
- assetPrefix = '/_kay',
1578
- metafile?: Bun.BuildOutput['metafile'],
1579
- ): string {
1580
- const report = analyzeBundleWeights(manifest, clientDir, assetPrefix, metafile)
1581
- const kb = (b: number) => `${(b / 1024).toFixed(2)} KB`
1582
- const lines = [
1583
- '\n=== KAY BUNDLE WEIGHT REPORT ===',
1584
- `Total emitted: JS ${kb(report.totalJsGzip)} gz | CSS ${kb(report.totalCssGzip)} gz`,
1585
- '',
1586
- 'Route'.padEnd(28) + 'Eager JS (gz)'.padStart(16) + 'CSS (gz)'.padStart(14) + 'Files'.padStart(10),
1587
- ]
1588
- for (const r of report.routes) {
1589
- lines.push(
1590
- r.path.padEnd(28)
1591
- + kb(r.jsGzip).padStart(16)
1592
- + kb(r.cssGzip).padStart(14)
1593
- + `${r.jsFiles}j/${r.cssFiles}c`.padStart(10),
1594
- )
1595
- }
1596
- if (report.topModules.length > 0) {
1597
- lines.push('', 'Top modules (minified output bytes):')
1598
- for (const m of report.topModules.slice(0, 8))
1599
- lines.push(` ${kb(m.bytes).padStart(9)} ${m.path}`)
1600
- }
1601
- return lines.join('\n')
1602
396
  }