@kayjs/kay 2.0.0-alpha.7 → 2.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kayjs/kay",
3
- "version": "2.0.0-alpha.7",
3
+ "version": "2.0.0-beta.0",
4
4
  "description": "Bun-native TSX web framework with zero-directive automatic islands, fine-grained signals, and single-binary deploys",
5
5
  "license": "MIT",
6
6
  "homepage": "https://kayjs.kaynooo.fr",
@@ -42,7 +42,10 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
42
42
  }
43
43
  if (manifest.errorFile) addMod(manifest.errorFile)
44
44
  if (manifest.notFoundFile) addMod(manifest.notFoundFile)
45
- for (const a of manifest.actions) addMod(a.file)
45
+ for (const a of manifest.actions) {
46
+ addMod(a.file)
47
+ for (const m of a.middlewares) addMod(m)
48
+ }
46
49
 
47
50
  const configPath = join(root, 'kay.config.ts')
48
51
  const hasConfig = existsSync(configPath)
@@ -53,9 +56,18 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
53
56
  const embeddedAssets: string[] = []
54
57
  let assetIdx = 0
55
58
  for (const rel of manifest.assets) {
59
+ const abs = join(clientDir, rel)
56
60
  const v = `_a${assetIdx++}`
57
- imports.push(`import ${v} from ${JSON.stringify(join(clientDir, rel))} with { type: "file" };`)
61
+ imports.push(`import ${v} from ${JSON.stringify(abs)} with { type: "file" };`)
58
62
  embeddedAssets.push(`${JSON.stringify(rel)}: ${v}`)
63
+ for (const ext of ['.br', '.gz'] as const) {
64
+ const sidecarAbs = `${abs}${ext}`
65
+ if (existsSync(sidecarAbs)) {
66
+ const sv = `_a${assetIdx++}`
67
+ imports.push(`import ${sv} from ${JSON.stringify(sidecarAbs)} with { type: "file" };`)
68
+ embeddedAssets.push(`${JSON.stringify(`${rel}${ext}`)}: ${sv}`)
69
+ }
70
+ }
59
71
  }
60
72
  const embeddedPublic: string[] = []
61
73
  const embeddedPublicEtags: string[] = []
@@ -82,7 +94,7 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
82
94
  }
83
95
 
84
96
  const cfgSpread = hasConfig
85
- ? `, plugins: _kayConfig?.plugins, lang: _kayConfig?.lang, security: _kayConfig?.security, trustedOrigins: _kayConfig?.trustedOrigins, compress: _kayConfig?.compress, onError: _kayConfig?.onError`
97
+ ? `, plugins: _kayConfig?.plugins, lang: _kayConfig?.lang, security: _kayConfig?.security, trustedOrigins: _kayConfig?.trustedOrigins, trustProxy: _kayConfig?.trustProxy, maxRequestBodySize: _kayConfig?.maxRequestBodySize, compress: _kayConfig?.compress, onError: _kayConfig?.onError`
86
98
  : ''
87
99
 
88
100
  // Default NODE_ENV to 'production' in compiled binaries (dynamic key avoids Bun.build constant-folding).
@@ -6,10 +6,12 @@
6
6
  import type { BunPlugin } from 'bun'
7
7
  import type { IslandBinding, ModuleAnalysis } from '../compiler/index'
8
8
  import type { BuildPluginContext, KayPlugin } from '../plugins/index'
9
- import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
9
+ import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
10
+ import { tmpdir } from 'node:os'
10
11
  import { basename, dirname, extname, isAbsolute, join, relative, resolve } from 'node:path'
11
12
  import { brotliCompressSync, constants as zlibConstants } from 'node:zlib'
12
13
  import { analyzeModule, compileDom, compileSsr } from '../compiler/index'
14
+ import { readsPrivateEnv, SERVER_ONLY_FILTER } from '../compiler/server-only'
13
15
  import { loadConfig } from '../plugins/index'
14
16
  import { actionHash } from '../server/action'
15
17
  import { compileExecutable } from './compile'
@@ -48,12 +50,16 @@ export interface BuildOptions {
48
50
  copyPublic?: boolean | undefined
49
51
  /** Compile into a single standalone executable at this path (or true -> dist/server-bin). */
50
52
  compile?: string | boolean | undefined
53
+ /** Run in development mode (keeps NODE_ENV as development and skips production client asset precompression; auto-detected via KAY_DEV=1). */
54
+ dev?: boolean | undefined
51
55
  }
52
56
 
53
57
  export interface ActionManifestEntry {
54
58
  url: string
55
59
  file: string
56
60
  exportName: string
61
+ /** `_middleware.ts` chain of the folder declaring the action, outermost first. */
62
+ middlewares: string[]
57
63
  }
58
64
 
59
65
  export interface RouteManifestEntry {
@@ -158,19 +164,125 @@ function resolveImportPath(fromFile: string, specifier: string): string | undefi
158
164
  }
159
165
  }
160
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
+
161
172
  function walkRoutes(dir: string, out: string[] = []): string[] {
162
173
  if (!existsSync(dir))
163
174
  return out
164
175
  for (const entry of readdirSync(dir, { withFileTypes: true })) {
165
176
  const full = join(dir, entry.name)
166
- if (entry.isDirectory())
177
+ if (entry.isDirectory()) {
178
+ if (entry.name.startsWith('_'))
179
+ continue
167
180
  walkRoutes(full, out)
168
- else if (entry.name.endsWith('.tsx') || entry.name.endsWith('.ts'))
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
+ ) {
169
187
  out.push(full)
188
+ }
170
189
  }
171
190
  return out
172
191
  }
173
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
+
174
286
  function walkAllFiles(dir: string, out: string[] = []): string[] {
175
287
  if (!existsSync(dir))
176
288
  return out
@@ -221,28 +333,56 @@ interface IslandTarget {
221
333
  defaultHydrate: string | undefined
222
334
  }
223
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.`)
338
+ }
339
+
224
340
  export async function build(options: BuildOptions): Promise<BuildManifest> {
341
+ if (options.static && options.compile) {
342
+ throw new Error('kay build: --static and --compile cannot be used together (static export produces HTML/assets without a server binary).')
343
+ }
344
+
225
345
  const root = resolve(options.root)
226
346
  const fileConfig = await loadConfig(root)
227
347
  const plugins: KayPlugin[] = options.plugins ?? fileConfig.plugins ?? []
228
348
  const routesDir = resolve(root, options.routesDir ?? fileConfig.routesDir ?? 'src/routes')
229
349
  const finalOutDir = resolve(root, options.outDir ?? fileConfig.outDir ?? 'dist')
350
+ const publicDir = resolve(root, options.publicDir ?? fileConfig.publicDir ?? 'public')
351
+
352
+ assertSafeOutDir(root, finalOutDir, routesDir, publicDir)
353
+
354
+ const isDev = options.dev ?? (process.env.KAY_DEV === '1')
230
355
  const cacheBaseDir = join(root, '.kay-cache')
231
356
  const cacheExisted = existsSync(cacheBaseDir)
357
+ const stageSuffix = `${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
232
358
  const outDir = options.static
233
- ? join(cacheBaseDir, `.static-stage-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`)
359
+ ? join(cacheBaseDir, `.static-stage-${stageSuffix}`)
234
360
  : finalOutDir
235
- const publicDir = resolve(root, options.publicDir ?? fileConfig.publicDir ?? 'public')
361
+ const staticStageDir = options.static
362
+ ? join(dirname(finalOutDir), `.${basename(finalOutDir)}.stage-${stageSuffix}`)
363
+ : undefined
236
364
  const clientDir = join(outDir, 'client')
237
365
  const serverDir = join(outDir, 'server')
238
366
  const assetPrefix = (options.assetPrefix ?? fileConfig.assetPrefix ?? '/_kay').replace(/\/$/, '')
239
367
  const minify = options.minify ?? true
240
368
 
369
+ const prevNodeEnv = process.env.NODE_ENV
370
+ if (!isDev)
371
+ process.env.NODE_ENV ??= 'production'
372
+
241
373
  try {
242
374
  return await buildInternal()
243
375
  }
244
376
  finally {
377
+ if (!isDev) {
378
+ if (prevNodeEnv !== undefined)
379
+ process.env.NODE_ENV = prevNodeEnv
380
+ else
381
+ delete process.env.NODE_ENV
382
+ }
245
383
  if (options.static) {
384
+ if (staticStageDir !== undefined && existsSync(staticStageDir))
385
+ rmSync(staticStageDir, { recursive: true, force: true })
246
386
  rmSync(outDir, { recursive: true, force: true })
247
387
  if (!cacheExisted && existsSync(cacheBaseDir) && readdirSync(cacheBaseDir).length === 0)
248
388
  rmSync(cacheBaseDir, { recursive: true, force: true })
@@ -281,8 +421,8 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
281
421
  mkdirSync(serverDir, { recursive: true })
282
422
 
283
423
  const allRouteFiles = walkRoutes(routesDir).sort()
284
- const specialFiles = allRouteFiles.filter(f => basename(f).startsWith('_'))
285
- const pageFiles = allRouteFiles.filter(f => !basename(f).startsWith('_'))
424
+ const specialFiles = allRouteFiles.filter(f => SPECIAL_ROUTE_FILES.has(basename(f)))
425
+ const candidatePageFiles = allRouteFiles.filter(f => !basename(f).startsWith('_'))
286
426
  const errorSrc = join(routesDir, '_error.tsx')
287
427
  const notFoundSrc = join(routesDir, '_404.tsx')
288
428
  const hasErrorFile = existsSync(errorSrc)
@@ -357,9 +497,28 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
357
497
  return { file, exportName }
358
498
  }
359
499
 
360
- for (const f of allRouteFiles)
500
+ for (const f of specialFiles)
501
+ loadAnalysis(f)
502
+ for (const f of candidatePageFiles)
361
503
  loadAnalysis(f)
362
504
 
505
+ // 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 })
520
+ }
521
+
363
522
  // Discover all server actions (keyed by source file -> exportName -> action URL)
364
523
  const actionsByFile = new Map<string, { exportName: string, url: string }[]>()
365
524
  for (const [file, analysis] of analyses) {
@@ -377,6 +536,7 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
377
536
 
378
537
  // Discover all island roots referenced from static pages/layouts/errors (or sync interactive pages themselves)
379
538
  const islandTargets = new Map<string, IslandTarget>()
539
+ const islandIds = new Set<string>()
380
540
  const pageIslandBindings = new Map<string, Map<string, IslandTarget>>()
381
541
 
382
542
  function registerIsland(file: string, exportName: string): IslandTarget {
@@ -387,7 +547,11 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
387
547
  const analysis = loadAnalysis(file)
388
548
  const baseName = basename(file, extname(file)).toLowerCase()
389
549
  const expLower = exportName.toLowerCase()
390
- const id = exportName === 'default' || expLower === baseName ? baseName : `${baseName}-${expLower}`
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)
391
555
  const target: IslandTarget = { id, file, exportName, defaultHydrate: analysis.defaultHydrate }
392
556
  islandTargets.set(key, target)
393
557
  return target
@@ -444,6 +608,30 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
444
608
  for (const [, target] of islandTargets)
445
609
  collectIslandCss(target.file)
446
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
+
447
635
  const standaloneCssSet = new Set<string>(pluginCssFiles)
448
636
  for (const [file, analysis] of analyses) {
449
637
  for (const imp of analysis.imports) {
@@ -518,9 +706,22 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
518
706
  islandEntryToKey.set(entryPath, key)
519
707
  }
520
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
521
716
  const clientPlugin: BunPlugin = {
522
717
  name: 'kay-v2-client',
523
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
+ })
524
725
  b.onResolve({ filter: /^(?:@kayjs\/)?kay(?:\/.*)?$/ }, (args) => {
525
726
  const resolved = resolveKaySpecifier(args.path)
526
727
  return resolved !== undefined ? { path: resolved } : undefined
@@ -571,14 +772,23 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
571
772
  define: {
572
773
  KAY_DEFERRED: hasDeferredHydrate ? 'true' : 'false',
573
774
  KAY_CLIENT_ONLY: hasClientOnlyHydrate ? 'true' : 'false',
775
+ 'process.env.NODE_ENV': JSON.stringify(isDev ? 'development' : 'production'),
776
+ ...publicEnvDefines,
574
777
  },
575
778
  plugins: [clientPlugin, ...pluginBunPlugins],
576
779
  })
577
780
  }
781
+ catch (err) {
782
+ if (clientLeaks.size > 0)
783
+ throw clientLeakError(clientLeaks)
784
+ throw err
785
+ }
578
786
  finally {
579
787
  rmSync(entriesDir, { recursive: true, force: true })
580
788
  }
581
789
 
790
+ if (clientLeaks.size > 0)
791
+ throw clientLeakError(clientLeaks)
582
792
  if (!clientResult.success) {
583
793
  const msgs = clientResult.logs.map(l => l.message).join('\n')
584
794
  throw new Error(`kay build (client) failed:\n${msgs}`)
@@ -592,10 +802,28 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
592
802
  return resolve(clientDir, p)
593
803
  }
594
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
+
595
820
  if (clientMetafile !== undefined) {
596
821
  for (const [outKey, info] of Object.entries(clientMetafile.outputs)) {
597
822
  const relOut = outKey.replace(/^\.\//, '')
598
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)
599
827
  if (relOut.endsWith('.css')) {
600
828
  if (info.entryPoint !== undefined) {
601
829
  const absEntry = resolveMetaPath(info.entryPoint)
@@ -624,21 +852,14 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
624
852
  if (relFile.endsWith('.css')) {
625
853
  styleUrls.push(url)
626
854
  }
627
- else if (output.kind === 'entry-point') {
628
- if (relFile.startsWith('runtime-')) {
629
- runtimeScript = url
630
- }
631
- else {
632
- for (const [, target] of islandTargets) {
633
- if (relFile.startsWith(`${target.id}-`))
634
- islandChunks.set(`${target.file}#${target.exportName}`, url)
635
- }
636
- }
855
+ else if (output.kind === 'entry-point' && relFile.startsWith('runtime-')) {
856
+ runtimeScript = url
637
857
  }
638
858
  }
639
859
  }
640
860
 
641
- const standaloneActionFiles = [...actionsByFile.keys()].filter(f => !allRouteFiles.includes(f))
861
+ const routeEntryFiles = new Set([...specialFiles, ...pageFiles])
862
+ const standaloneActionFiles = [...actionsByFile.keys()].filter(f => !routeEntryFiles.has(f))
642
863
  const serverEntries = [...specialFiles, ...pageFiles, ...standaloneActionFiles]
643
864
  const serverRoot = standaloneActionFiles.length > 0 ? root : routesDir
644
865
 
@@ -734,7 +955,9 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
734
955
  const analysis = analyses.get(args.path)
735
956
  const rawBindings = pageIslandBindings.get(args.path)
736
957
  let islandMap: Map<string, IslandBinding> | undefined
737
- let islandKey = analysis?.isInteractive ? '1' : '0'
958
+ const isInteractive = analysis?.isInteractive === true
959
+ const emitMarkers = isInteractive || islandReach.has(args.path)
960
+ let islandKey = `${isInteractive ? '1' : '0'}:${emitMarkers ? '1' : '0'}`
738
961
  if (rawBindings !== undefined) {
739
962
  islandMap = new Map()
740
963
  for (const [localName, target] of rawBindings) {
@@ -754,11 +977,13 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
754
977
  if (cachedSsr !== undefined && cachedSsr.mtimeMs === stamp!.mtimeMs && cachedSsr.size === stamp!.size && cachedSsr.key === islandKey)
755
978
  return { contents: cachedSsr.code, loader: 'tsx' }
756
979
  const raw = sources.get(args.path) ?? readFileSync(args.path, 'utf8')
757
- const compiled = compileSsr(args.path, raw, {
980
+ const ssrOpts = {
758
981
  analysis,
759
982
  islands: islandMap,
760
- isIsland: analysis?.isInteractive,
761
- })
983
+ isIsland: isInteractive,
984
+ emitMarkers,
985
+ } as Parameters<typeof compileSsr>[2]
986
+ const compiled = compileSsr(args.path, raw, ssrOpts)
762
987
  const outCode = applyTransforms(compiled.code, args.path, 'server')
763
988
  if (cache !== undefined && stamp !== undefined)
764
989
  cache.ssrCompiled.set(args.path, { mtimeMs: stamp.mtimeMs, size: stamp.size, key: islandKey, code: outCode })
@@ -776,6 +1001,9 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
776
1001
  splitting: true,
777
1002
  packages: 'external',
778
1003
  minify: false,
1004
+ define: {
1005
+ 'process.env.NODE_ENV': 'process.env.NODE_ENV',
1006
+ },
779
1007
  plugins: [serverPlugin, ...pluginBunPlugins],
780
1008
  })
781
1009
 
@@ -954,8 +1182,10 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
954
1182
  const actionEntries: ActionManifestEntry[] = []
955
1183
  for (const [srcFile, list] of actionsByFile) {
956
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) : []
957
1187
  for (const a of list)
958
- actionEntries.push({ url: a.url, file: outFile, exportName: a.exportName })
1188
+ actionEntries.push({ url: a.url, file: outFile, exportName: a.exportName, middlewares })
959
1189
  }
960
1190
 
961
1191
  const islandsRecord: Record<string, string> = {}
@@ -1058,6 +1288,12 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
1058
1288
  await plugin.build(buildPluginCtx)
1059
1289
  }
1060
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
+ }
1296
+
1061
1297
  const manifest: BuildManifest = {
1062
1298
  runtimeScript,
1063
1299
  styles: styleUrls,
@@ -1080,9 +1316,7 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
1080
1316
  if (prerenderRoutes.length > 0 || options.static) {
1081
1317
  const { createServer } = await import('../server/index')
1082
1318
  const app = await createServer({ root, outDir: relative(root, outDir), assetPrefix, plugins })
1083
- const prerenderDir = options.static ? finalOutDir : join(outDir, 'prerendered')
1084
- if (options.static)
1085
- rmSync(finalOutDir, { recursive: true, force: true })
1319
+ const prerenderDir = options.static ? staticStageDir! : join(outDir, 'prerendered')
1086
1320
  mkdirSync(prerenderDir, { recursive: true })
1087
1321
 
1088
1322
  const prerenderStamp = Date.now()
@@ -1095,6 +1329,9 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
1095
1329
  else if (typeof mod.paths === 'function') {
1096
1330
  urls = await mod.paths()
1097
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
+ }
1098
1335
 
1099
1336
  if (urls.length === 0)
1100
1337
  continue
@@ -1110,14 +1347,18 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
1110
1347
  const batch = urls.slice(i, i + CONCURRENCY)
1111
1348
  await Promise.all(batch.map(async (u) => {
1112
1349
  const res = await app.handle(new Request(`http://localhost${u}`))
1113
- if (res.status === 200) {
1114
- const html = await res.text()
1115
- const relHtml = u === '/' ? 'index.html' : `${u.replace(/^\//, '').replace(/\/$/, '')}/index.html`
1116
- const absHtml = join(prerenderDir, relHtml)
1117
- mkdirSync(dirname(absHtml), { recursive: true })
1118
- writeFileSync(absHtml, html)
1119
- map[u] = relative(options.static ? finalOutDir : outDir, absHtml).replace(/\\/g, '/')
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
1120
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, '/')
1121
1362
  }))
1122
1363
  }
1123
1364
  route.prerendered = map
@@ -1126,9 +1367,11 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
1126
1367
  if (options.static) {
1127
1368
  if (hasNotFoundFile) {
1128
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}.`)
1129
1372
  writeFileSync(join(prerenderDir, '404.html'), await notFoundRes.text())
1130
1373
  }
1131
- // Copy client assets into dist/_kay/... and public/ files into dist/...
1374
+ // Copy client assets into <stage>/_kay/... and public/ files into <stage>/...
1132
1375
  if (nonEmptyAssets.length > 0) {
1133
1376
  const staticAssetDir = join(prerenderDir, assetPrefix.replace(/^\//, ''))
1134
1377
  mkdirSync(staticAssetDir, { recursive: true })
@@ -1154,19 +1397,28 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
1154
1397
  writeFileSync(dst, readFileSync(join(outDir, 'public', rel)))
1155
1398
  }
1156
1399
  // Emit precompressed .br and .gz sidecars for compressible static files (>= 128 B)
1157
- const COMPRESSIBLE = new Set(['.html', '.js', '.mjs', '.css', '.svg', '.xml', '.json', '.txt', '.webmanifest'])
1158
- for (const abs of walkAllFiles(prerenderDir)) {
1159
- if (!COMPRESSIBLE.has(extname(abs).toLowerCase()))
1160
- continue
1161
- const raw = readFileSync(abs)
1162
- if (raw.byteLength < 128)
1163
- continue
1164
- const br = brotliCompressSync(raw, { params: { [zlibConstants.BROTLI_PARAM_QUALITY]: 6 } })
1165
- if (br.byteLength < raw.byteLength)
1166
- writeFileSync(`${abs}.br`, br)
1167
- const gz = Bun.gzipSync(raw, { level: 9 })
1168
- if (gz.byteLength < raw.byteLength)
1169
- writeFileSync(`${abs}.gz`, gz)
1400
+ for (const abs of walkAllFiles(prerenderDir))
1401
+ precompressFile(abs, 128)
1402
+
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)
1170
1422
  }
1171
1423
  }
1172
1424
  else {