@kayjs/kay 2.0.0-alpha.8 → 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.8",
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",
@@ -56,9 +56,18 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
56
56
  const embeddedAssets: string[] = []
57
57
  let assetIdx = 0
58
58
  for (const rel of manifest.assets) {
59
+ const abs = join(clientDir, rel)
59
60
  const v = `_a${assetIdx++}`
60
- 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" };`)
61
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
+ }
62
71
  }
63
72
  const embeddedPublic: string[] = []
64
73
  const embeddedPublicEtags: string[] = []
@@ -85,7 +94,7 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
85
94
  }
86
95
 
87
96
  const cfgSpread = hasConfig
88
- ? `, 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`
89
98
  : ''
90
99
 
91
100
  // Default NODE_ENV to 'production' in compiled binaries (dynamic key avoids Bun.build constant-folding).
@@ -6,7 +6,8 @@
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'
@@ -49,6 +50,8 @@ export interface BuildOptions {
49
50
  copyPublic?: boolean | undefined
50
51
  /** Compile into a single standalone executable at this path (or true -> dist/server-bin). */
51
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
52
55
  }
53
56
 
54
57
  export interface ActionManifestEntry {
@@ -161,19 +164,125 @@ function resolveImportPath(fromFile: string, specifier: string): string | undefi
161
164
  }
162
165
  }
163
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
+
164
172
  function walkRoutes(dir: string, out: string[] = []): string[] {
165
173
  if (!existsSync(dir))
166
174
  return out
167
175
  for (const entry of readdirSync(dir, { withFileTypes: true })) {
168
176
  const full = join(dir, entry.name)
169
- if (entry.isDirectory())
177
+ if (entry.isDirectory()) {
178
+ if (entry.name.startsWith('_'))
179
+ continue
170
180
  walkRoutes(full, out)
171
- 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
+ ) {
172
187
  out.push(full)
188
+ }
173
189
  }
174
190
  return out
175
191
  }
176
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
+
177
286
  function walkAllFiles(dir: string, out: string[] = []): string[] {
178
287
  if (!existsSync(dir))
179
288
  return out
@@ -229,27 +338,51 @@ function clientLeakError(leaks: Set<string>): Error {
229
338
  }
230
339
 
231
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
+
232
345
  const root = resolve(options.root)
233
346
  const fileConfig = await loadConfig(root)
234
347
  const plugins: KayPlugin[] = options.plugins ?? fileConfig.plugins ?? []
235
348
  const routesDir = resolve(root, options.routesDir ?? fileConfig.routesDir ?? 'src/routes')
236
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')
237
355
  const cacheBaseDir = join(root, '.kay-cache')
238
356
  const cacheExisted = existsSync(cacheBaseDir)
357
+ const stageSuffix = `${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
239
358
  const outDir = options.static
240
- ? join(cacheBaseDir, `.static-stage-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`)
359
+ ? join(cacheBaseDir, `.static-stage-${stageSuffix}`)
241
360
  : finalOutDir
242
- const publicDir = resolve(root, options.publicDir ?? fileConfig.publicDir ?? 'public')
361
+ const staticStageDir = options.static
362
+ ? join(dirname(finalOutDir), `.${basename(finalOutDir)}.stage-${stageSuffix}`)
363
+ : undefined
243
364
  const clientDir = join(outDir, 'client')
244
365
  const serverDir = join(outDir, 'server')
245
366
  const assetPrefix = (options.assetPrefix ?? fileConfig.assetPrefix ?? '/_kay').replace(/\/$/, '')
246
367
  const minify = options.minify ?? true
247
368
 
369
+ const prevNodeEnv = process.env.NODE_ENV
370
+ if (!isDev)
371
+ process.env.NODE_ENV ??= 'production'
372
+
248
373
  try {
249
374
  return await buildInternal()
250
375
  }
251
376
  finally {
377
+ if (!isDev) {
378
+ if (prevNodeEnv !== undefined)
379
+ process.env.NODE_ENV = prevNodeEnv
380
+ else
381
+ delete process.env.NODE_ENV
382
+ }
252
383
  if (options.static) {
384
+ if (staticStageDir !== undefined && existsSync(staticStageDir))
385
+ rmSync(staticStageDir, { recursive: true, force: true })
253
386
  rmSync(outDir, { recursive: true, force: true })
254
387
  if (!cacheExisted && existsSync(cacheBaseDir) && readdirSync(cacheBaseDir).length === 0)
255
388
  rmSync(cacheBaseDir, { recursive: true, force: true })
@@ -288,8 +421,8 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
288
421
  mkdirSync(serverDir, { recursive: true })
289
422
 
290
423
  const allRouteFiles = walkRoutes(routesDir).sort()
291
- const specialFiles = allRouteFiles.filter(f => basename(f).startsWith('_'))
292
- 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('_'))
293
426
  const errorSrc = join(routesDir, '_error.tsx')
294
427
  const notFoundSrc = join(routesDir, '_404.tsx')
295
428
  const hasErrorFile = existsSync(errorSrc)
@@ -364,8 +497,27 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
364
497
  return { file, exportName }
365
498
  }
366
499
 
367
- for (const f of allRouteFiles)
500
+ for (const f of specialFiles)
368
501
  loadAnalysis(f)
502
+ for (const f of candidatePageFiles)
503
+ loadAnalysis(f)
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
+ }
369
521
 
370
522
  // Discover all server actions (keyed by source file -> exportName -> action URL)
371
523
  const actionsByFile = new Map<string, { exportName: string, url: string }[]>()
@@ -458,15 +610,24 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
458
610
 
459
611
  // The client compiles every module an island imports to hydrate against SSR markers, so their SSR must emit them too.
460
612
  const islandReach = new Set<string>()
613
+ const reachSeen = new Set<string>()
461
614
  const reachStack = [...islandTargets.values()].map(t => t.file)
462
615
  while (reachStack.length > 0) {
463
616
  const file = reachStack.pop()!
464
- if (islandReach.has(file))
617
+ if (reachSeen.has(file))
465
618
  continue
466
- islandReach.add(file)
467
- for (const imp of analyses.get(file)?.imports ?? []) {
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 ?? []) {
468
624
  const target = resolveImportPath(file, imp.source)
469
- if (target !== undefined && target.endsWith('.tsx'))
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')))
470
631
  reachStack.push(target)
471
632
  }
472
633
  }
@@ -611,6 +772,7 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
611
772
  define: {
612
773
  KAY_DEFERRED: hasDeferredHydrate ? 'true' : 'false',
613
774
  KAY_CLIENT_ONLY: hasClientOnlyHydrate ? 'true' : 'false',
775
+ 'process.env.NODE_ENV': JSON.stringify(isDev ? 'development' : 'production'),
614
776
  ...publicEnvDefines,
615
777
  },
616
778
  plugins: [clientPlugin, ...pluginBunPlugins],
@@ -696,7 +858,8 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
696
858
  }
697
859
  }
698
860
 
699
- 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))
700
863
  const serverEntries = [...specialFiles, ...pageFiles, ...standaloneActionFiles]
701
864
  const serverRoot = standaloneActionFiles.length > 0 ? root : routesDir
702
865
 
@@ -792,8 +955,9 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
792
955
  const analysis = analyses.get(args.path)
793
956
  const rawBindings = pageIslandBindings.get(args.path)
794
957
  let islandMap: Map<string, IslandBinding> | undefined
795
- const inIsland = analysis?.isInteractive === true || islandReach.has(args.path)
796
- let islandKey = inIsland ? '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'}`
797
961
  if (rawBindings !== undefined) {
798
962
  islandMap = new Map()
799
963
  for (const [localName, target] of rawBindings) {
@@ -813,11 +977,13 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
813
977
  if (cachedSsr !== undefined && cachedSsr.mtimeMs === stamp!.mtimeMs && cachedSsr.size === stamp!.size && cachedSsr.key === islandKey)
814
978
  return { contents: cachedSsr.code, loader: 'tsx' }
815
979
  const raw = sources.get(args.path) ?? readFileSync(args.path, 'utf8')
816
- const compiled = compileSsr(args.path, raw, {
980
+ const ssrOpts = {
817
981
  analysis,
818
982
  islands: islandMap,
819
- isIsland: inIsland,
820
- })
983
+ isIsland: isInteractive,
984
+ emitMarkers,
985
+ } as Parameters<typeof compileSsr>[2]
986
+ const compiled = compileSsr(args.path, raw, ssrOpts)
821
987
  const outCode = applyTransforms(compiled.code, args.path, 'server')
822
988
  if (cache !== undefined && stamp !== undefined)
823
989
  cache.ssrCompiled.set(args.path, { mtimeMs: stamp.mtimeMs, size: stamp.size, key: islandKey, code: outCode })
@@ -835,6 +1001,9 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
835
1001
  splitting: true,
836
1002
  packages: 'external',
837
1003
  minify: false,
1004
+ define: {
1005
+ 'process.env.NODE_ENV': 'process.env.NODE_ENV',
1006
+ },
838
1007
  plugins: [serverPlugin, ...pluginBunPlugins],
839
1008
  })
840
1009
 
@@ -1119,6 +1288,12 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
1119
1288
  await plugin.build(buildPluginCtx)
1120
1289
  }
1121
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
+
1122
1297
  const manifest: BuildManifest = {
1123
1298
  runtimeScript,
1124
1299
  styles: styleUrls,
@@ -1141,9 +1316,7 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
1141
1316
  if (prerenderRoutes.length > 0 || options.static) {
1142
1317
  const { createServer } = await import('../server/index')
1143
1318
  const app = await createServer({ root, outDir: relative(root, outDir), assetPrefix, plugins })
1144
- const prerenderDir = options.static ? finalOutDir : join(outDir, 'prerendered')
1145
- if (options.static)
1146
- rmSync(finalOutDir, { recursive: true, force: true })
1319
+ const prerenderDir = options.static ? staticStageDir! : join(outDir, 'prerendered')
1147
1320
  mkdirSync(prerenderDir, { recursive: true })
1148
1321
 
1149
1322
  const prerenderStamp = Date.now()
@@ -1156,6 +1329,9 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
1156
1329
  else if (typeof mod.paths === 'function') {
1157
1330
  urls = await mod.paths()
1158
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
+ }
1159
1335
 
1160
1336
  if (urls.length === 0)
1161
1337
  continue
@@ -1171,14 +1347,18 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
1171
1347
  const batch = urls.slice(i, i + CONCURRENCY)
1172
1348
  await Promise.all(batch.map(async (u) => {
1173
1349
  const res = await app.handle(new Request(`http://localhost${u}`))
1174
- if (res.status === 200) {
1175
- const html = await res.text()
1176
- const relHtml = u === '/' ? 'index.html' : `${u.replace(/^\//, '').replace(/\/$/, '')}/index.html`
1177
- const absHtml = join(prerenderDir, relHtml)
1178
- mkdirSync(dirname(absHtml), { recursive: true })
1179
- writeFileSync(absHtml, html)
1180
- 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
1181
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, '/')
1182
1362
  }))
1183
1363
  }
1184
1364
  route.prerendered = map
@@ -1187,9 +1367,11 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
1187
1367
  if (options.static) {
1188
1368
  if (hasNotFoundFile) {
1189
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}.`)
1190
1372
  writeFileSync(join(prerenderDir, '404.html'), await notFoundRes.text())
1191
1373
  }
1192
- // Copy client assets into dist/_kay/... and public/ files into dist/...
1374
+ // Copy client assets into <stage>/_kay/... and public/ files into <stage>/...
1193
1375
  if (nonEmptyAssets.length > 0) {
1194
1376
  const staticAssetDir = join(prerenderDir, assetPrefix.replace(/^\//, ''))
1195
1377
  mkdirSync(staticAssetDir, { recursive: true })
@@ -1215,19 +1397,28 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
1215
1397
  writeFileSync(dst, readFileSync(join(outDir, 'public', rel)))
1216
1398
  }
1217
1399
  // Emit precompressed .br and .gz sidecars for compressible static files (>= 128 B)
1218
- const COMPRESSIBLE = new Set(['.html', '.js', '.mjs', '.css', '.svg', '.xml', '.json', '.txt', '.webmanifest'])
1219
- for (const abs of walkAllFiles(prerenderDir)) {
1220
- if (!COMPRESSIBLE.has(extname(abs).toLowerCase()))
1221
- continue
1222
- const raw = readFileSync(abs)
1223
- if (raw.byteLength < 128)
1224
- continue
1225
- const br = brotliCompressSync(raw, { params: { [zlibConstants.BROTLI_PARAM_QUALITY]: 6 } })
1226
- if (br.byteLength < raw.byteLength)
1227
- writeFileSync(`${abs}.br`, br)
1228
- const gz = Bun.gzipSync(raw, { level: 9 })
1229
- if (gz.byteLength < raw.byteLength)
1230
- 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)
1231
1422
  }
1232
1423
  }
1233
1424
  else {
package/src/cli/index.ts CHANGED
@@ -13,22 +13,35 @@ const args = Bun.argv.slice(2)
13
13
  const cmd = args[0]
14
14
 
15
15
  function flagValue(name: string): string | undefined {
16
- const idx = args.indexOf(name)
17
- if (idx === -1)
18
- return undefined
19
- const next = args[idx + 1]
20
- return next !== undefined && !next.startsWith('-') ? next : ''
16
+ const prefix = `${name}=`
17
+ for (let i = 0; i < args.length; i++) {
18
+ const a = args[i]!
19
+ if (a.startsWith(prefix))
20
+ return a.slice(prefix.length)
21
+ if (a === name) {
22
+ const next = args[i + 1]
23
+ return next !== undefined && !next.startsWith('-') ? next : ''
24
+ }
25
+ }
26
+ return undefined
21
27
  }
22
28
 
23
29
  function hasFlag(name: string): boolean {
24
30
  return args.includes(name)
25
31
  }
26
32
 
33
+ function resolveHostname(): string {
34
+ const hostFlag = flagValue('--host')
35
+ if (hostFlag !== undefined)
36
+ return hostFlag === '' ? '0.0.0.0' : hostFlag
37
+ return process.env.HOST || '127.0.0.1'
38
+ }
39
+
27
40
  const dirArg = args.slice(1).find((a, i, arr) => {
28
41
  if (a.startsWith('-'))
29
42
  return false
30
43
  const prev = arr[i - 1]
31
- if (prev === '--port' || prev === '--compile' || prev === '--template')
44
+ if (prev === '--port' || prev === '--host' || prev === '--compile' || prev === '--template')
32
45
  return false
33
46
  return true
34
47
  })
@@ -72,14 +85,15 @@ else if (cmd === 'start') {
72
85
  process.env.NODE_ENV ??= 'production'
73
86
  const config = await loadConfig(root)
74
87
  const port = Number(flagValue('--port') || process.env.PORT || config.port || 3000)
75
- const hostname = process.env.HOST || undefined
88
+ const hostname = resolveHostname()
76
89
  const app = await createServer({ root })
77
90
  const server = app.serve(port, hostname)
78
- console.log(`kay server listening on http://${hostname ?? 'localhost'}:${server.port}`)
91
+ console.log(`kay server listening on http://${hostname}:${server.port}`)
79
92
  }
80
93
  else if (cmd === 'dev') {
81
94
  const port = Number(flagValue('--port') || process.env.PORT || 3000)
82
- await devServer({ root, port })
95
+ const hostname = resolveHostname()
96
+ await devServer({ root, port, hostname })
83
97
  }
84
98
  else {
85
99
  // Check plugin-registered CLI commands from kay.config.ts
@@ -98,10 +112,12 @@ Commands:
98
112
  kay new <dir> [--template minimal|fullstack|blog|app] [--force]
99
113
  Scaffold a new Kay project
100
114
  kay check [dir] Validate routes, compiler rules, and TypeScript types
101
- kay dev [dir] [--port 3000] Run dev server with fast reload
115
+ kay dev [dir] [--port 3000] [--host [addr]]
116
+ Run dev server with fast reload (binds 127.0.0.1 by default)
102
117
  kay build [dir] [--static] [--compile [out]]
103
118
  Build production app, static site, or single executable
104
- kay start [dir] [--port 3000] Serve the built production app`)
119
+ kay start [dir] [--port 3000] [--host [addr]]
120
+ Serve the built production app (binds 127.0.0.1 by default)`)
105
121
  process.exit(cmd === '--help' || cmd === '-h' || cmd === undefined ? 0 : 1)
106
122
  }
107
123
  }
package/src/cli/new.ts CHANGED
@@ -15,7 +15,7 @@ export function scaffoldProject(targetDir: string, options: ScaffoldOptions = {}
15
15
  const root = resolve(targetDir)
16
16
  const name = basename(root).toLowerCase().replace(/[^a-z0-9-_]/g, '-') || 'kay-app'
17
17
  const template: ScaffoldTemplate = options.template ?? 'minimal'
18
- const kayVersion = options.kayVersion ?? '^2.0.0-alpha.8'
18
+ const kayVersion = options.kayVersion ?? '^2.0.0-beta.0'
19
19
 
20
20
  if (existsSync(root) && readdirSync(root).length > 0 && !options.force)
21
21
  throw new Error(`kay new: directory "${root}" is not empty (pass --force to overwrite)`)
@@ -360,14 +360,25 @@ export default function PostPage({ data }: { data: { post: NonNullable<ReturnTyp
360
360
  delete files['src/styles/app.css']
361
361
  delete files['src/components/Counter.tsx']
362
362
 
363
- files['src/auth.ts'] = `import { createAuth } from '@kayjs/auth'
363
+ files['src/auth.ts'] = `import { join } from 'node:path'
364
+ import { createAuth } from '@kayjs/auth'
364
365
  import { sqliteAuthStore } from '@kayjs/auth/sqlite'
365
366
 
367
+ // Set AUTH_SECRET (at least 32 bytes) in production — see .env.example.
368
+ const defaultDb = import.meta.dir.startsWith('/$bunfs')
369
+ ? './data/auth.sqlite'
370
+ : join(import.meta.dir, '../data/auth.sqlite')
371
+
366
372
  export const auth = createAuth({
367
- store: sqliteAuthStore(process.env.AUTH_DB || ':memory:'),
368
- secret: process.env.AUTH_SECRET || 'dev-secret-change-in-production',
373
+ store: sqliteAuthStore(process.env.AUTH_DB || defaultDb),
374
+ secret: process.env.AUTH_SECRET || undefined,
369
375
  defaultRedirect: '/dashboard',
370
376
  })
377
+ `
378
+ files['.env.example'] = `# Generate a 32+ byte secret for production, e.g.:
379
+ # openssl rand -base64 32
380
+ AUTH_SECRET=
381
+ AUTH_DB=./data/auth.sqlite
371
382
  `
372
383
  files['kay.config.ts'] = `import { ui } from '@kayjs/ui/plugin'
373
384
  import { defineConfig } from 'kay/server'