@kayjs/kay 2.0.0-alpha.8 → 2.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/package.json +1 -1
  2. package/src/attrs.ts +35 -0
  3. package/src/build/bundle.ts +442 -0
  4. package/src/build/compile.ts +20 -11
  5. package/src/build/files.ts +136 -0
  6. package/src/build/graph.ts +158 -0
  7. package/src/build/index.ts +231 -1296
  8. package/src/build/islands.ts +177 -0
  9. package/src/build/manifest.ts +224 -0
  10. package/src/build/plugin-host.ts +184 -0
  11. package/src/build/prerender.ts +93 -0
  12. package/src/build/report.ts +157 -0
  13. package/src/build/resolve.ts +58 -0
  14. package/src/build/routes.ts +135 -0
  15. package/src/build/static.ts +73 -0
  16. package/src/cli/check.ts +228 -114
  17. package/src/cli/index.ts +298 -79
  18. package/src/cli/new.ts +67 -35
  19. package/src/compiler/analyze.ts +666 -91
  20. package/src/compiler/dom.ts +822 -629
  21. package/src/compiler/mistakes.ts +354 -0
  22. package/src/compiler/patch.ts +1 -1
  23. package/src/compiler/server-only.ts +164 -21
  24. package/src/compiler/shared.ts +442 -0
  25. package/src/compiler/ssr.ts +390 -324
  26. package/src/context.ts +120 -0
  27. package/src/dev/index.ts +291 -76
  28. package/src/dom/action.ts +23 -13
  29. package/src/dom/extras.ts +157 -84
  30. package/src/dom/index.ts +154 -33
  31. package/src/dom/island.ts +117 -39
  32. package/src/dom/loop.ts +34 -21
  33. package/src/index.ts +2 -1
  34. package/src/jsx-runtime.ts +11 -0
  35. package/src/plugins/context.ts +57 -0
  36. package/src/plugins/index.ts +120 -17
  37. package/src/reactivity/index.ts +250 -157
  38. package/src/reactivity/selector.ts +11 -9
  39. package/src/reactivity/store.ts +37 -12
  40. package/src/server/action.ts +217 -74
  41. package/src/server/compress.ts +155 -56
  42. package/src/server/cookies.ts +59 -22
  43. package/src/server/env.ts +18 -13
  44. package/src/server/http.ts +201 -33
  45. package/src/server/index.ts +964 -737
  46. package/src/server/loader.ts +120 -0
  47. package/src/server/router.ts +27 -8
  48. package/src/server/security.ts +87 -39
  49. package/src/server/standard-schema.ts +42 -11
  50. package/src/server/static-dir.ts +144 -0
  51. package/src/ssr/context.ts +96 -10
  52. package/src/ssr/index.ts +225 -56
  53. package/src/style.ts +33 -0
  54. package/src/test/index.ts +5 -0
  55. package/src/unrenderable.ts +35 -0
package/src/context.ts ADDED
@@ -0,0 +1,120 @@
1
+ // Universal component context (createContext / useContext) and hydration-safe useId().
2
+ // Browser-pure: zero Node imports. SSR wires its per-request AsyncLocalStorage bridge via registerServerContextBridge().
3
+
4
+ import type { KayChild } from './jsx-runtime'
5
+ import type { IdScope, Owner } from './reactivity/index'
6
+ import { createOwner, getOwner, runWithOwner } from './reactivity/index'
7
+
8
+ export interface ServerContextBridge {
9
+ getContext(key: symbol): { found: true, value: unknown } | undefined
10
+ runWithContext<T>(key: symbol, value: unknown, fn: () => T): T
11
+ nextId(): string | undefined
12
+ head(props: { children?: KayChild }): KayChild
13
+ suspense(props: { fallback?: KayChild, error?: KayChild | ((error: unknown) => KayChild), children?: KayChild | Promise<KayChild> }): KayChild
14
+ }
15
+
16
+ const BRIDGE_KEY = Symbol.for('kay.server.context.bridge')
17
+
18
+ function getServerBridge(): ServerContextBridge | undefined {
19
+ return (globalThis as Record<symbol, ServerContextBridge | undefined>)[BRIDGE_KEY]
20
+ }
21
+
22
+ /** Internal: registered by `kay/ssr` on the server so `Head`, `Suspense`, `useContext`, and `useId` stay request-scoped without pulling `node:async_hooks` into client bundles. */
23
+ export function registerServerContextBridge(bridge: ServerContextBridge): void {
24
+ ;(globalThis as Record<symbol, ServerContextBridge | undefined>)[BRIDGE_KEY] = bridge
25
+ }
26
+
27
+ /** Collects document `<head>` tags during SSR; no-op in the browser. */
28
+ export function Head(props: { children?: KayChild }): KayChild {
29
+ const bridge = getServerBridge()
30
+ return bridge !== undefined ? bridge.head(props) : null
31
+ }
32
+
33
+ /** Streaming SSR boundary: flushes `fallback` immediately and streams resolved async children. */
34
+ export function Suspense(props: { fallback?: KayChild, error?: KayChild | ((error: unknown) => KayChild), children?: KayChild | Promise<KayChild> }): KayChild {
35
+ const bridge = getServerBridge()
36
+ if (bridge !== undefined)
37
+ return bridge.suspense(props)
38
+ return props.children instanceof Promise ? (props.fallback ?? null) : (props.children ?? null)
39
+ }
40
+
41
+ export interface Context<T> {
42
+ readonly id: symbol
43
+ readonly defaultValue: T
44
+ Provider: (props: { value: T, children?: KayChild | (() => KayChild) }) => KayChild
45
+ }
46
+
47
+ function findOwnerContext(owner: Owner | undefined, key: symbol): { found: true, value: unknown } | undefined {
48
+ for (let o = owner; o !== undefined; o = o.o) {
49
+ if (o.cx !== undefined && o.cx.has(key))
50
+ return { found: true, value: o.cx.get(key) }
51
+ }
52
+ return undefined
53
+ }
54
+
55
+ function findOwnerIdScope(owner: Owner | undefined): IdScope | undefined {
56
+ for (let o = owner; o !== undefined; o = o.o) {
57
+ if (o.id !== undefined)
58
+ return o.id
59
+ }
60
+ return undefined
61
+ }
62
+
63
+ /** Run `fn` with `ctx` bound to `value` on both server (SSR) and browser (reactive owner tree). */
64
+ export function provideContext<T, R>(ctx: Context<T>, value: T, fn: () => R): R {
65
+ const owner = getOwner()
66
+ if (owner !== undefined) {
67
+ const scope = createOwner(owner)
68
+ ;(scope.cx ??= new Map()).set(ctx.id, value)
69
+ return runWithOwner(scope, fn)
70
+ }
71
+ const bridge = getServerBridge()
72
+ if (bridge !== undefined)
73
+ return bridge.runWithContext(ctx.id, value, fn)
74
+ return fn()
75
+ }
76
+
77
+ export function createContext<T>(defaultValue: T): Context<T> {
78
+ const id = Symbol('kay.context')
79
+ const ctx: Context<T> = {
80
+ id,
81
+ defaultValue,
82
+ Provider(props) {
83
+ return provideContext(ctx, props.value, () => {
84
+ const c = props.children
85
+ return typeof c === 'function' ? (c as () => KayChild)() : c
86
+ })
87
+ },
88
+ }
89
+ return ctx
90
+ }
91
+
92
+ export function useContext<T>(ctx: Context<T>): T {
93
+ const owner = getOwner()
94
+ if (owner !== undefined) {
95
+ const hit = findOwnerContext(owner, ctx.id)
96
+ if (hit !== undefined)
97
+ return hit.value as T
98
+ }
99
+ const bridge = getServerBridge()
100
+ if (bridge !== undefined) {
101
+ const hit = bridge.getContext(ctx.id)
102
+ if (hit !== undefined)
103
+ return hit.value as T
104
+ }
105
+ return ctx.defaultValue
106
+ }
107
+
108
+ let fallbackIdSeq = 0
109
+
110
+ /** Generates a deterministic, hydration-safe unique ID scoped to the current island or SSR request. */
111
+ export function useId(prefix = 'k'): string {
112
+ const scope = findOwnerIdScope(getOwner())
113
+ if (scope !== undefined)
114
+ return `${prefix}-${scope.p}${scope.n++}`
115
+ const bridge = getServerBridge()
116
+ const serverId = bridge?.nextId()
117
+ if (serverId !== undefined)
118
+ return `${prefix}-${serverId}`
119
+ return `${prefix}-g${fallbackIdSeq++}`
120
+ }
package/src/dev/index.ts CHANGED
@@ -1,41 +1,214 @@
1
- // kay dev: incremental cached rebuilds, serialized rebuild queue, CSS hot-swap, SSE error push, and live config reload.
1
+ // kay dev: incremental cached rebuilds, serialized rebuild queue, CSS hot-swap, streaming reload injection,
2
+ // SSE error push, and live config reload.
2
3
 
3
4
  import type { FSWatcher } from 'node:fs'
4
5
  import type { KayApp } from '../server/index'
5
- import { existsSync, rmSync, statSync, watch } from 'node:fs'
6
- import { join, resolve } from 'node:path'
6
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, watch, writeFileSync } from 'node:fs'
7
+ import { dirname, join, relative, resolve } from 'node:path'
8
+ import { clearBuildCache } from '../build/graph'
7
9
  import { build, createBuildCache } from '../build/index'
8
- import { loadConfig } from '../plugins/index'
9
- import { createServer } from '../server/index'
10
+ import { createAppContext, loadConfig, runWithAppContext } from '../plugins/index'
11
+ import { DEFAULT_MAX_REQUEST_BODY_SIZE } from '../server/http'
12
+ import { createServer, withCspHashes } from '../server/index'
10
13
 
11
14
  export interface DevServerOptions {
12
15
  root: string
13
16
  port?: number | undefined
17
+ hostname?: string | undefined
14
18
  routesDir?: string | undefined
19
+ maxRequestBodySize?: number | undefined
15
20
  }
16
21
 
17
- const DEV_RELOAD_SCRIPT = `<script>(()=>{const stem=u=>u.replace(/-[a-z0-9]+\\.css$/i,'');const s=new EventSource('/_kay/dev-events');s.onmessage=(e)=>{if(e.data.startsWith('css:')){const urls=JSON.parse(e.data.slice(4));const byStem=new Map(urls.map(u=>[stem(u),u]));const old=[...document.querySelectorAll('link[rel="stylesheet"][href^="/_kay/"]')];if(old.length===0){location.reload();return;}const next=[];for(const o of old){const m=byStem.get(stem(o.getAttribute('href')||''));if(m)next.push(m);}if(next.length===0){location.reload();return;}let left=next.length;for(const u of next){const l=document.createElement('link');l.rel='stylesheet';l.href=u;const done=()=>{if(--left===0)for(const o of old)o.remove();};l.onload=done;l.onerror=done;document.head.appendChild(l);}}else{location.reload();}};})();</script>`
22
+ function makeDevReloadAssets(assetPrefix: string): { script: string, hash: string, eventsPath: string } {
23
+ const prefix = assetPrefix.replace(/\/$/, '')
24
+ const eventsPath = `${prefix}/dev-events`
25
+ const js = `(()=>{const stem=u=>u.replace(/-[a-z0-9]+\\.css$/i,'');const s=new EventSource(${JSON.stringify(eventsPath)});s.onmessage=(e)=>{if(e.data.startsWith('css:')){const urls=JSON.parse(e.data.slice(4));const byStem=new Map(urls.map(u=>[stem(u),u]));const old=[...document.querySelectorAll('link[rel="stylesheet"][href^=${JSON.stringify(`${prefix}/`)}]')];if(old.length===0){location.reload();return;}const next=[];for(const o of old){const m=byStem.get(stem(o.getAttribute('href')||''));if(m)next.push(m);}if(next.length===0){location.reload();return;}let left=next.length;for(const u of next){const l=document.createElement('link');l.rel='stylesheet';l.href=u;const done=()=>{if(--left===0)for(const o of old)o.remove();};l.onload=done;l.onerror=done;document.head.appendChild(l);}}else{location.reload();}};})();`
26
+ const hash = `'sha256-${new Bun.CryptoHasher('sha256').update(js).digest('base64')}'`
27
+ return { script: `<script>${js}</script>`, hash, eventsPath }
28
+ }
18
29
 
19
- function renderErrorOverlay(errText: string): string {
30
+ function renderErrorOverlay(errText: string, reloadScript: string): string {
20
31
  const escaped = errText
21
32
  .replaceAll('&', '&amp;')
22
33
  .replaceAll('<', '&lt;')
23
34
  .replaceAll('>', '&gt;')
24
- return `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>Kay Dev Error</title><style>body{margin:0;min-height:100vh;background:#0d1117;color:#e6edf3;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;display:grid;place-items:center;padding:2rem}main{max-width:56rem;width:100%;background:#161b22;border:1px solid #f85149;border-radius:10px;padding:1.5rem 2rem;box-shadow:0 16px 48px rgba(0,0,0,.45)}h1{margin:0 0 1rem;color:#ff7b72;font-size:1.15rem}pre{margin:0;white-space:pre-wrap;word-break:break-word;line-height:1.5;font-size:.9rem;color:#ffa198}p{margin:1rem 0 0;font-size:.8rem;color:#8b949e}</style></head><body><main><h1>Kay Dev Build Error</h1><pre>${escaped}</pre><p>Save a fix to auto-reload.</p></main>${DEV_RELOAD_SCRIPT}</body></html>`
35
+ return `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>Kay Dev Error</title><style>body{margin:0;min-height:100vh;background:#0d1117;color:#e6edf3;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;display:grid;place-items:center;padding:2rem}main{max-width:56rem;width:100%;background:#161b22;border:1px solid #f85149;border-radius:10px;padding:1.5rem 2rem;box-shadow:0 16px 48px rgba(0,0,0,.45)}h1{margin:0 0 1rem;color:#ff7b72;font-size:1.15rem}pre{margin:0;white-space:pre-wrap;word-break:break-word;line-height:1.5;font-size:.9rem;color:#ffa198}p{margin:1rem 0 0;font-size:.8rem;color:#8b949e}</style></head><body><main><h1>Kay Dev Build Error</h1><pre>${escaped}</pre><p>Save a fix to auto-reload.</p></main>${reloadScript}</body></html>`
36
+ }
37
+
38
+ type ChangeKind = 'css' | 'code' | 'full' | 'config'
39
+
40
+ // A source edit changes the bundled bytes; any other file (content, data, public/) may be read when a module loads.
41
+ const CODE_FILE_RE = /\.(?:[cm]?[jt]sx?|css)$/
42
+
43
+ function srcChangeKind(name: string): ChangeKind {
44
+ if (name.endsWith('.css') && !name.endsWith('.module.css'))
45
+ return 'css'
46
+ return CODE_FILE_RE.test(name) ? 'code' : 'full'
25
47
  }
26
48
 
27
- type ChangeKind = 'css' | 'full' | 'config'
49
+ // Injects the dev reload script into an HTML response while preserving streaming (<Suspense>).
50
+ function injectReloadStream(body: ReadableStream<Uint8Array>, reloadScript: string): ReadableStream<Uint8Array> {
51
+ const decoder = new TextDecoder()
52
+ const encoder = new TextEncoder()
53
+ let injected = false
54
+ let tail = ''
55
+ const KEEP = 16 // enough to span a split `</body>` tag across chunk boundaries
56
+
57
+ return body.pipeThrough(new TransformStream<Uint8Array, Uint8Array>({
58
+ transform(chunk, controller) {
59
+ if (injected) {
60
+ controller.enqueue(chunk)
61
+ return
62
+ }
63
+ const text = tail + decoder.decode(chunk, { stream: true })
64
+ const idx = text.indexOf('</body>')
65
+ if (idx !== -1) {
66
+ injected = true
67
+ tail = ''
68
+ controller.enqueue(encoder.encode(`${text.slice(0, idx)}${reloadScript}${text.slice(idx)}`))
69
+ return
70
+ }
71
+ if (text.length > KEEP) {
72
+ const split = text.length - KEEP
73
+ controller.enqueue(encoder.encode(text.slice(0, split)))
74
+ tail = text.slice(split)
75
+ }
76
+ else {
77
+ tail = text
78
+ }
79
+ },
80
+ flush(controller) {
81
+ const rest = tail + decoder.decode()
82
+ if (injected) {
83
+ if (rest.length > 0)
84
+ controller.enqueue(encoder.encode(rest))
85
+ return
86
+ }
87
+ const idx = rest.indexOf('</body>')
88
+ if (idx !== -1)
89
+ controller.enqueue(encoder.encode(`${rest.slice(0, idx)}${reloadScript}${rest.slice(idx)}`))
90
+ else
91
+ controller.enqueue(encoder.encode(rest + reloadScript))
92
+ },
93
+ }))
94
+ }
95
+
96
+ // Bun never unloads a module, so each build's server files are copied into a generation store.
97
+ // If any non-chunk module that other entries may statically import changes (e.g. standalone actions), bump generation so static importers re-resolve cleanly.
98
+ function createModuleStore(storeRoot: string) {
99
+ const hashes = new Map<string, string>()
100
+ let generation = 0
101
+ let stale = false
102
+ const generationDir = (g: number): string => join(storeRoot, `g${g}`)
103
+ return {
104
+ reloadAll(): void {
105
+ stale = true
106
+ },
107
+ sync(serverDir: string, sharedRelFiles: ReadonlySet<string>): void {
108
+ const nextFiles = new Map<string, { bytes: Buffer, hash: string }>()
109
+ for (const entry of readdirSync(serverDir, { recursive: true, withFileTypes: true })) {
110
+ if (!entry.isFile())
111
+ continue
112
+ const from = join(entry.parentPath, entry.name)
113
+ const rel = relative(serverDir, from).replaceAll('\\', '/')
114
+ const bytes = readFileSync(from)
115
+ const hash = Bun.hash(bytes).toString(36)
116
+ nextFiles.set(rel, { bytes, hash })
117
+ }
118
+
119
+ // If an already-loaded standalone action file (statically imported by routes) changed, bump generation so static importers re-resolve cleanly.
120
+ if (!stale && hashes.size > 0) {
121
+ for (const [rel, { hash }] of nextFiles) {
122
+ const prev = hashes.get(rel)
123
+ if (prev !== undefined && prev !== hash && sharedRelFiles.has(rel)) {
124
+ stale = true
125
+ break
126
+ }
127
+ }
128
+ }
129
+
130
+ if (stale) {
131
+ stale = false
132
+ hashes.clear()
133
+ generation++
134
+ // The previous generation stays for requests the old app is still serving.
135
+ rmSync(generationDir(generation - 2), { recursive: true, force: true })
136
+ }
137
+ const storeDir = generationDir(generation)
138
+ for (const [rel, { bytes, hash }] of nextFiles) {
139
+ if (hashes.get(rel) === hash)
140
+ continue
141
+ const to = join(storeDir, rel)
142
+ mkdirSync(dirname(to), { recursive: true })
143
+ writeFileSync(to, bytes)
144
+ hashes.set(rel, hash)
145
+ }
146
+ // Prune removed chunk files from current generation to avoid unbounded disk/map growth.
147
+ for (const rel of [...hashes.keys()]) {
148
+ if (!nextFiles.has(rel)) {
149
+ hashes.delete(rel)
150
+ rmSync(join(storeDir, rel), { force: true })
151
+ }
152
+ }
153
+ },
154
+ importFrom(serverDir: string) {
155
+ const storeDir = generationDir(generation)
156
+ return async (path: string): Promise<Record<string, unknown>> => {
157
+ const rel = relative(serverDir, path).replaceAll('\\', '/')
158
+ try {
159
+ return await import(`${join(storeDir, rel)}?v=${hashes.get(rel)}`)
160
+ }
161
+ catch (err) {
162
+ stale = true
163
+ throw err
164
+ }
165
+ }
166
+ },
167
+ }
168
+ }
28
169
 
29
170
  export async function devServer(options: DevServerOptions): Promise<{ url: string, stop: () => void, rebuild: () => Promise<void> }> {
30
171
  const prevKayDev = process.env.KAY_DEV
31
172
  process.env.KAY_DEV = '1'
32
173
  const root = resolve(options.root)
33
- const srcDir = resolve(root, 'src')
34
- const publicDir = resolve(root, 'public')
35
- const configPath = join(root, 'kay.config.ts')
36
174
  const devRoot = join(root, '.kay-dev')
37
- const port = options.port ?? 3000
175
+ const initialCfg = await loadConfig(root).catch((err) => {
176
+ console.warn(`[kay dev] failed to load kay.config.ts: ${err instanceof Error ? err.message : String(err)}`)
177
+ return {} as Awaited<ReturnType<typeof loadConfig>>
178
+ })
179
+ const assetPrefix = (initialCfg.assetPrefix ?? '/_kay').replace(/\/$/, '')
180
+ let reloadAssets = makeDevReloadAssets(assetPrefix)
181
+ const srcDir = resolve(root, 'src')
182
+ const routesDir = resolve(root, options.routesDir ?? initialCfg.routesDir ?? 'src/routes')
183
+ const publicDir = resolve(root, initialCfg.publicDir ?? 'public')
184
+ const port = options.port ?? initialCfg.port ?? 3000
185
+ const hostname = options.hostname ?? '127.0.0.1'
38
186
  const buildCache = createBuildCache()
187
+ const modules = createModuleStore(join(devRoot, 'server'))
188
+ const watchers: FSWatcher[] = []
189
+ const watchedDirs = new Set<string>()
190
+ const pluginWatchers: FSWatcher[] = []
191
+ let activeAssetPrefix = assetPrefix
192
+
193
+ function refreshPluginWatchers(cfg: Awaited<ReturnType<typeof loadConfig>>): void {
194
+ for (const w of pluginWatchers)
195
+ w.close()
196
+ pluginWatchers.length = 0
197
+ const seen = new Set<string>(watchedDirs)
198
+ const watchCtx = createAppContext({ root, outDir: devRoot, publicDir, assetPrefix: activeAssetPrefix, dev: true })
199
+ for (const plugin of cfg.plugins ?? []) {
200
+ const paths = runWithAppContext(watchCtx, () =>
201
+ typeof plugin.watchPaths === 'function' ? plugin.watchPaths(root) : (plugin.watchPaths ?? []))
202
+ for (const p of paths) {
203
+ const abs = resolve(root, p)
204
+ if (seen.has(abs) || !existsSync(abs))
205
+ continue
206
+ seen.add(abs)
207
+ const isDir = statSync(abs).isDirectory()
208
+ pluginWatchers.push(watch(abs, isDir ? { recursive: true } : {}, () => scheduleRebuild('full')))
209
+ }
210
+ }
211
+ }
39
212
 
40
213
  let buildNum = 0
41
214
  let currentApp: KayApp | undefined
@@ -47,13 +220,13 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
47
220
  let pending = false
48
221
  let pendingCssOnly = true
49
222
  let pendingConfigReset = false
223
+ let pendingReloadAll = false
50
224
  let inFlight: Promise<void> | undefined
51
225
 
52
226
  const clients = new Set<ReadableStreamDefaultController<Uint8Array>>()
53
227
  const encoder = new TextEncoder()
54
228
 
55
- function broadcast(payload: string): void {
56
- const chunk = encoder.encode(`data: ${payload}\n\n`)
229
+ function pushToClients(chunk: Uint8Array): void {
57
230
  for (const c of clients) {
58
231
  try {
59
232
  c.enqueue(chunk)
@@ -64,20 +237,26 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
64
237
  }
65
238
  }
66
239
 
67
- async function runSingleBuild(cssOnly: boolean, resetCache: boolean): Promise<void> {
240
+ const broadcast = (payload: string): void => pushToClients(encoder.encode(`data: ${payload}\n\n`))
241
+
242
+ async function runSingleBuild(cssOnly: boolean, resetCache: boolean, reloadAll: boolean): Promise<void> {
68
243
  if (stopped)
69
244
  return
70
- if (resetCache) {
71
- buildCache.analyses.clear()
72
- buildCache.domCompiled.clear()
73
- buildCache.ssrCompiled.clear()
74
- }
75
245
  const hadError = lastError !== undefined
76
246
  const hadApp = currentApp !== undefined
77
247
  const n = ++buildNum
78
248
  const outDir = `.kay-dev/b${n}`
79
249
  const t0 = performance.now()
80
250
  try {
251
+ if (resetCache) {
252
+ clearBuildCache(buildCache)
253
+ const freshCfg = await loadConfig(root, { fresh: true })
254
+ activeAssetPrefix = (freshCfg.assetPrefix ?? '/_kay').replace(/\/$/, '')
255
+ reloadAssets = makeDevReloadAssets(activeAssetPrefix)
256
+ refreshPluginWatchers(freshCfg)
257
+ }
258
+ if (reloadAll)
259
+ modules.reloadAll()
81
260
  const manifest = await build({
82
261
  root,
83
262
  routesDir: options.routesDir,
@@ -85,9 +264,37 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
85
264
  minify: false,
86
265
  prerender: false,
87
266
  copyPublic: false,
267
+ dev: true,
88
268
  cache: buildCache,
89
269
  })
90
- currentApp = await createServer({ root, outDir })
270
+ if (stopped) {
271
+ rmSync(join(root, outDir), { recursive: true, force: true })
272
+ return
273
+ }
274
+ const serverDir = join(root, outDir, 'server')
275
+ const routeFiles = new Set(manifest.routes.map(r => r.file.replace(/^server\//, '')))
276
+ const sharedRelFiles = new Set<string>()
277
+ for (const a of manifest.actions) {
278
+ const rel = a.file.replace(/^server\//, '')
279
+ if (!routeFiles.has(rel))
280
+ sharedRelFiles.add(rel)
281
+ }
282
+ modules.sync(serverDir, sharedRelFiles)
283
+ const nextApp = await createServer({
284
+ root,
285
+ outDir,
286
+ dev: true,
287
+ compress: false,
288
+ importModule: modules.importFrom(serverDir),
289
+ })
290
+ if (stopped) {
291
+ await nextApp.dispose?.()
292
+ rmSync(join(root, outDir), { recursive: true, force: true })
293
+ return
294
+ }
295
+ const prevApp = currentApp
296
+ currentApp = nextApp
297
+ void prevApp?.dispose?.()
91
298
  lastError = undefined
92
299
  if (n > 2)
93
300
  rmSync(join(devRoot, `b${n - 2}`), { recursive: true, force: true })
@@ -98,6 +305,8 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
98
305
  broadcast('reload')
99
306
  }
100
307
  catch (err) {
308
+ if (stopped)
309
+ return
101
310
  lastError = err instanceof Error ? err.stack ?? err.message : String(err)
102
311
  console.error(`[kay dev] build error:\n${lastError}`)
103
312
  // Push reload over SSE so open browser tabs immediately display the error overlay
@@ -105,7 +314,10 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
105
314
  }
106
315
  }
107
316
 
317
+ let timer: ReturnType<typeof setTimeout> | undefined
318
+
108
319
  function drainRebuilds(): Promise<void> {
320
+ clearTimeout(timer)
109
321
  if (building) {
110
322
  pending = true
111
323
  return inFlight ?? Promise.resolve()
@@ -114,12 +326,15 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
114
326
  const run = (async () => {
115
327
  try {
116
328
  do {
329
+ clearTimeout(timer)
117
330
  const cssOnly = pendingCssOnly
118
331
  const resetCache = pendingConfigReset
332
+ const reloadAll = pendingReloadAll
119
333
  pending = false
120
334
  pendingCssOnly = true
121
335
  pendingConfigReset = false
122
- await runSingleBuild(cssOnly, resetCache)
336
+ pendingReloadAll = false
337
+ await runSingleBuild(cssOnly, resetCache, reloadAll)
123
338
  } while (pending && !stopped)
124
339
  }
125
340
  finally {
@@ -135,73 +350,65 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
135
350
  pendingCssOnly = false
136
351
  await drainRebuilds()
137
352
 
138
- let timer: ReturnType<typeof setTimeout> | undefined
139
353
  const scheduleRebuild = (kind: ChangeKind) => {
140
354
  if (stopped)
141
355
  return
142
- if (kind === 'config') {
356
+ if (kind === 'config')
143
357
  pendingConfigReset = true
358
+ if (kind === 'config' || kind === 'full')
359
+ pendingReloadAll = true
360
+ if (kind !== 'css')
144
361
  pendingCssOnly = false
145
- }
146
- else if (kind === 'full') {
147
- pendingCssOnly = false
148
- }
149
362
  clearTimeout(timer)
150
363
  timer = setTimeout(() => {
151
364
  void drainRebuilds()
152
365
  }, 40)
153
366
  }
154
367
 
155
- const watchers: FSWatcher[] = []
156
- if (existsSync(srcDir)) {
157
- watchers.push(watch(srcDir, { recursive: true }, (_ev, filename) => {
158
- const name = typeof filename === 'string' ? filename : ''
159
- const isCss = name.endsWith('.css') && !name.endsWith('.module.css')
160
- scheduleRebuild(isCss ? 'css' : 'full')
368
+ const addDirWatch = (dir: string, handler: (filename: string) => void) => {
369
+ if (watchedDirs.has(dir) || !existsSync(dir))
370
+ return
371
+ watchedDirs.add(dir)
372
+ watchers.push(watch(dir, { recursive: true }, (_ev, filename) => {
373
+ handler(typeof filename === 'string' ? filename : '')
161
374
  }))
162
375
  }
163
- if (existsSync(publicDir))
164
- watchers.push(watch(publicDir, { recursive: true }, () => scheduleRebuild('full')))
165
- if (existsSync(configPath))
166
- watchers.push(watch(configPath, () => scheduleRebuild('config')))
167
376
 
168
- // Watch plugin-declared extra paths (e.g. content/ or messages/ directories)
377
+ addDirWatch(srcDir, name => scheduleRebuild(srcChangeKind(name)))
378
+ // If routesDir sits outside src/, watch it too!
379
+ if (!routesDir.startsWith(`${srcDir}/`) && !routesDir.startsWith(`${srcDir}\\`) && routesDir !== srcDir)
380
+ addDirWatch(routesDir, name => scheduleRebuild(srcChangeKind(name)))
381
+ addDirWatch(publicDir, () => scheduleRebuild('full'))
382
+
383
+ // Watch root (non-recursive) for kay.config.ts so atomic editor saves (temp + rename) still fire events.
384
+ watchers.push(watch(root, (_ev, filename) => {
385
+ if (filename === 'kay.config.ts')
386
+ scheduleRebuild('config')
387
+ }))
388
+
389
+ // Watch plugin-declared extra paths (e.g. content/ or messages/ directories); refreshed on kay.config.ts edits.
169
390
  try {
170
- const cfg = await loadConfig(root)
171
- const watchedExtra = new Set<string>([srcDir, publicDir, configPath])
172
- for (const plugin of cfg.plugins ?? []) {
173
- const paths = typeof plugin.watchPaths === 'function' ? plugin.watchPaths(root) : (plugin.watchPaths ?? [])
174
- for (const p of paths) {
175
- const abs = resolve(root, p)
176
- if (watchedExtra.has(abs) || !existsSync(abs))
177
- continue
178
- watchedExtra.add(abs)
179
- const isDir = statSync(abs).isDirectory()
180
- watchers.push(watch(abs, isDir ? { recursive: true } : {}, () => scheduleRebuild('full')))
181
- }
182
- }
391
+ refreshPluginWatchers(initialCfg)
392
+ }
393
+ catch (err) {
394
+ console.warn(`[kay dev] could not attach plugin watchers: ${err instanceof Error ? err.message : String(err)}`)
183
395
  }
184
- catch {}
185
396
 
186
397
  const pingChunk = encoder.encode(': ping\n\n')
187
- const pingInterval = setInterval(() => {
188
- for (const c of clients) {
189
- try {
190
- c.enqueue(pingChunk)
191
- }
192
- catch {
193
- clients.delete(c)
194
- }
195
- }
196
- }, 15_000)
398
+ const pingInterval = setInterval(() => pushToClients(pingChunk), 15_000)
399
+
400
+ const maxRequestBodySize = options.maxRequestBodySize ?? initialCfg.maxRequestBodySize ?? DEFAULT_MAX_REQUEST_BODY_SIZE
197
401
 
198
402
  const server = Bun.serve({
199
403
  port,
200
- idleTimeout: 0,
201
- async fetch(request) {
404
+ hostname,
405
+ idleTimeout: 30,
406
+ maxRequestBodySize,
407
+ async fetch(request, srv) {
202
408
  const url = new URL(request.url)
203
409
 
204
- if (url.pathname === '/_kay/dev-events') {
410
+ if (url.pathname === reloadAssets.eventsPath) {
411
+ srv.timeout(request, 0)
205
412
  let ctrl: ReadableStreamDefaultController<Uint8Array> | undefined
206
413
  const stream = new ReadableStream<Uint8Array>({
207
414
  start(controller) {
@@ -231,26 +438,31 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
231
438
  }
232
439
 
233
440
  if (lastError !== undefined) {
234
- return new Response(renderErrorOverlay(lastError), {
441
+ return new Response(renderErrorOverlay(lastError, reloadAssets.script), {
235
442
  status: 500,
236
443
  headers: { 'content-type': 'text/html; charset=utf-8' },
237
444
  })
238
445
  }
239
446
 
240
- const res = await currentApp!.handle(request)
447
+ const remoteIp = srv.requestIP(request)?.address
448
+ const res = await currentApp!.handle(request, remoteIp)
241
449
  const ct = res.headers.get('content-type') ?? ''
242
- if (ct.includes('text/html')) {
243
- const html = await res.text()
244
- const injected = html.includes('</body>')
245
- ? html.replace('</body>', `${DEV_RELOAD_SCRIPT}</body>`)
246
- : html + DEV_RELOAD_SCRIPT
247
- return new Response(injected, { status: res.status, headers: res.headers })
450
+ if (ct.includes('text/event-stream'))
451
+ srv.timeout(request, 0)
452
+ if (ct.includes('text/html') && request.method !== 'HEAD' && res.body !== null) {
453
+ const headers = new Headers(res.headers)
454
+ headers.delete('content-length')
455
+ const existingCsp = headers.get('content-security-policy')
456
+ if (existingCsp !== null)
457
+ headers.set('content-security-policy', withCspHashes(existingCsp, { scriptHashes: [reloadAssets.hash] }))
458
+ return new Response(injectReloadStream(res.body, reloadAssets.script), { status: res.status, headers })
248
459
  }
249
460
  return res
250
461
  },
251
462
  })
252
463
 
253
- const url = `http://localhost:${server.port}`
464
+ const displayHost = hostname === '0.0.0.0' ? '127.0.0.1' : hostname
465
+ const url = `http://${displayHost}:${server.port}`
254
466
  console.log(`[kay dev] listening on ${url}`)
255
467
 
256
468
  return {
@@ -265,7 +477,10 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
265
477
  clearInterval(pingInterval)
266
478
  for (const w of watchers)
267
479
  w.close()
480
+ for (const w of pluginWatchers)
481
+ w.close()
268
482
  server.stop(true)
483
+ void currentApp?.dispose?.()
269
484
  rmSync(devRoot, { recursive: true, force: true })
270
485
  if (prevKayDev === undefined)
271
486
  delete process.env.KAY_DEV