@kayjs/kay 2.0.0-beta.0 → 2.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/package.json +1 -1
  2. package/src/attrs.ts +35 -0
  3. package/src/build/bundle.ts +615 -0
  4. package/src/build/compile.ts +32 -19
  5. package/src/build/files.ts +174 -0
  6. package/src/build/graph.ts +223 -0
  7. package/src/build/index.ts +255 -1461
  8. package/src/build/islands.ts +177 -0
  9. package/src/build/manifest.ts +227 -0
  10. package/src/build/plugin-host.ts +186 -0
  11. package/src/build/prerender.ts +94 -0
  12. package/src/build/report.ts +157 -0
  13. package/src/build/resolve.ts +51 -0
  14. package/src/build/routes.ts +163 -0
  15. package/src/build/static.ts +73 -0
  16. package/src/cli/check.ts +300 -129
  17. package/src/cli/index.ts +297 -94
  18. package/src/cli/new.ts +58 -38
  19. package/src/compiler/analyze.ts +723 -93
  20. package/src/compiler/dom.ts +848 -762
  21. package/src/compiler/mistakes.ts +354 -0
  22. package/src/compiler/patch.ts +1 -1
  23. package/src/compiler/server-only.ts +172 -23
  24. package/src/compiler/shared.ts +485 -0
  25. package/src/compiler/ssr.ts +331 -342
  26. package/src/context.ts +120 -0
  27. package/src/dev/index.ts +358 -76
  28. package/src/dom/action.ts +114 -14
  29. package/src/dom/extras.ts +121 -83
  30. package/src/dom/index.ts +122 -80
  31. package/src/dom/island.ts +71 -36
  32. package/src/dom/loop.ts +28 -20
  33. package/src/index.ts +5 -1
  34. package/src/jsx-runtime.ts +432 -93
  35. package/src/plugins/context.ts +83 -0
  36. package/src/plugins/index.ts +285 -23
  37. package/src/reactivity/index.ts +237 -213
  38. package/src/reactivity/selector.ts +11 -9
  39. package/src/reactivity/store.ts +36 -11
  40. package/src/server/action.ts +157 -79
  41. package/src/server/compress.ts +197 -104
  42. package/src/server/cookies.ts +46 -16
  43. package/src/server/env.ts +18 -13
  44. package/src/server/http.ts +189 -77
  45. package/src/server/index.ts +1024 -878
  46. package/src/server/loader.ts +138 -0
  47. package/src/server/router.ts +69 -26
  48. package/src/server/security.ts +50 -58
  49. package/src/server/standard-schema.ts +42 -11
  50. package/src/server/static-dir.ts +144 -0
  51. package/src/ssr/context.ts +95 -10
  52. package/src/ssr/index.ts +167 -66
  53. package/src/style.ts +33 -0
  54. package/src/test/index.ts +5 -15
  55. package/src/unrenderable.ts +35 -0
package/src/dev/index.ts CHANGED
@@ -1,11 +1,14 @@
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'
5
+ import type { BuildCacheStats } from '../build/graph'
4
6
  import type { KayApp } from '../server/index'
5
- import { existsSync, rmSync, statSync, watch } from 'node:fs'
6
- import { join, resolve } from 'node:path'
7
+ import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, watch, writeFileSync } from 'node:fs'
8
+ import { dirname, join, relative, resolve } from 'node:path'
9
+ import { clearBuildCache } from '../build/graph'
7
10
  import { build, createBuildCache } from '../build/index'
8
- import { loadConfig } from '../plugins/index'
11
+ import { createAppContext, loadConfig, resolvePlugins, resolveServerConfig, runWithAppContext } from '../plugins/index'
9
12
  import { DEFAULT_MAX_REQUEST_BODY_SIZE } from '../server/http'
10
13
  import { createServer, withCspHashes } from '../server/index'
11
14
 
@@ -17,31 +20,259 @@ export interface DevServerOptions {
17
20
  maxRequestBodySize?: number | undefined
18
21
  }
19
22
 
20
- const DEV_RELOAD_JS = `(()=>{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();}};})();`
21
- const DEV_RELOAD_SCRIPT = `<script>${DEV_RELOAD_JS}</script>`
22
- const DEV_RELOAD_SCRIPT_HASH = `'sha256-${new Bun.CryptoHasher('sha256').update(DEV_RELOAD_JS).digest('base64')}'`
23
+ function makeDevReloadAssets(assetPrefix: string): { script: string, hash: string, eventsPath: string } {
24
+ const prefix = assetPrefix.replace(/\/$/, '')
25
+ const eventsPath = `${prefix}/dev-events`
26
+ 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();}};})();`
27
+ const hash = `'sha256-${new Bun.CryptoHasher('sha256').update(js).digest('base64')}'`
28
+ return { script: `<script>${js}</script>`, hash, eventsPath }
29
+ }
23
30
 
24
- function renderErrorOverlay(errText: string): string {
31
+ function renderErrorOverlay(errText: string, reloadScript: string): string {
25
32
  const escaped = errText
26
33
  .replaceAll('&', '&amp;')
27
34
  .replaceAll('<', '&lt;')
28
35
  .replaceAll('>', '&gt;')
29
- 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>`
36
+ 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>`
30
37
  }
31
38
 
32
- type ChangeKind = 'css' | 'full' | 'config'
39
+ type ChangeKind = 'css' | 'code' | 'full' | 'config'
40
+
41
+ // A source edit changes the bundled bytes; any other file (content, data, public/) may be read when a module loads.
42
+ const CODE_FILE_RE = /\.(?:[cm]?[jt]sx?|css)$/
43
+
44
+ function srcChangeKind(name: string): ChangeKind {
45
+ if (name.endsWith('.css') && !name.endsWith('.module.css'))
46
+ return 'css'
47
+ return CODE_FILE_RE.test(name) ? 'code' : 'full'
48
+ }
49
+
50
+ // Injects the dev reload script into an HTML response while preserving streaming (<Suspense>).
51
+ function injectReloadStream(body: ReadableStream<Uint8Array>, reloadScript: string): ReadableStream<Uint8Array> {
52
+ const decoder = new TextDecoder()
53
+ const encoder = new TextEncoder()
54
+ let injected = false
55
+ let tail = ''
56
+ const KEEP = 16 // enough to span a split `</body>` tag across chunk boundaries
57
+
58
+ return body.pipeThrough(new TransformStream<Uint8Array, Uint8Array>({
59
+ transform(chunk, controller) {
60
+ if (injected) {
61
+ controller.enqueue(chunk)
62
+ return
63
+ }
64
+ const text = tail + decoder.decode(chunk, { stream: true })
65
+ const idx = text.indexOf('</body>')
66
+ if (idx !== -1) {
67
+ injected = true
68
+ tail = ''
69
+ controller.enqueue(encoder.encode(`${text.slice(0, idx)}${reloadScript}${text.slice(idx)}`))
70
+ return
71
+ }
72
+ if (text.length > KEEP) {
73
+ const split = text.length - KEEP
74
+ controller.enqueue(encoder.encode(text.slice(0, split)))
75
+ tail = text.slice(split)
76
+ }
77
+ else {
78
+ tail = text
79
+ }
80
+ },
81
+ flush(controller) {
82
+ const rest = tail + decoder.decode()
83
+ if (injected) {
84
+ if (rest.length > 0)
85
+ controller.enqueue(encoder.encode(rest))
86
+ return
87
+ }
88
+ const idx = rest.indexOf('</body>')
89
+ if (idx !== -1)
90
+ controller.enqueue(encoder.encode(`${rest.slice(0, idx)}${reloadScript}${rest.slice(idx)}`))
91
+ else
92
+ controller.enqueue(encoder.encode(rest + reloadScript))
93
+ },
94
+ }))
95
+ }
96
+
97
+ // Bun never unloads a module, so each build's server files are copied into a generation store.
98
+ // If any non-chunk module that other entries may statically import changes (e.g. standalone actions), bump generation so static importers re-resolve cleanly.
99
+ function createModuleStore(storeRoot: string) {
100
+ const hashes = new Map<string, string>()
101
+ let generation = 0
102
+ let stale = false
103
+ const generationDir = (g: number): string => join(storeRoot, `g${g}`)
104
+ return {
105
+ reloadAll(): void {
106
+ stale = true
107
+ },
108
+ sync(serverDir: string, sharedRelFiles: ReadonlySet<string>): void {
109
+ const nextFiles = new Map<string, { bytes: Buffer, hash: string }>()
110
+ for (const entry of readdirSync(serverDir, { recursive: true, withFileTypes: true })) {
111
+ if (!entry.isFile())
112
+ continue
113
+ const from = join(entry.parentPath, entry.name)
114
+ const rel = relative(serverDir, from).replaceAll('\\', '/')
115
+ const bytes = readFileSync(from)
116
+ const hash = Bun.hash(bytes).toString(36)
117
+ nextFiles.set(rel, { bytes, hash })
118
+ }
119
+
120
+ // If an already-loaded standalone action file (statically imported by routes) changed, bump generation so static importers re-resolve cleanly.
121
+ if (!stale && hashes.size > 0) {
122
+ for (const [rel, { hash }] of nextFiles) {
123
+ const prev = hashes.get(rel)
124
+ if (prev !== undefined && prev !== hash && sharedRelFiles.has(rel)) {
125
+ stale = true
126
+ break
127
+ }
128
+ }
129
+ }
130
+
131
+ if (stale) {
132
+ stale = false
133
+ hashes.clear()
134
+ generation++
135
+ // The previous generation stays for requests the old app is still serving.
136
+ rmSync(generationDir(generation - 2), { recursive: true, force: true })
137
+ }
138
+ const storeDir = generationDir(generation)
139
+ for (const [rel, { bytes, hash }] of nextFiles) {
140
+ if (hashes.get(rel) === hash)
141
+ continue
142
+ const to = join(storeDir, rel)
143
+ mkdirSync(dirname(to), { recursive: true })
144
+ writeFileSync(to, bytes)
145
+ hashes.set(rel, hash)
146
+ }
147
+ // Prune removed chunk files from current generation to avoid unbounded disk/map growth.
148
+ for (const rel of [...hashes.keys()]) {
149
+ if (!nextFiles.has(rel)) {
150
+ hashes.delete(rel)
151
+ rmSync(join(storeDir, rel), { force: true })
152
+ }
153
+ }
154
+ },
155
+ importFrom(serverDir: string) {
156
+ const storeDir = generationDir(generation)
157
+ return async (path: string): Promise<Record<string, unknown>> => {
158
+ const rel = relative(serverDir, path).replaceAll('\\', '/')
159
+ try {
160
+ return await import(`${join(storeDir, rel)}?v=${hashes.get(rel)}`)
161
+ }
162
+ catch (err) {
163
+ stale = true
164
+ throw err
165
+ }
166
+ }
167
+ },
168
+ }
169
+ }
33
170
 
34
- export async function devServer(options: DevServerOptions): Promise<{ url: string, stop: () => void, rebuild: () => Promise<void> }> {
171
+ export async function devServer(options: DevServerOptions): Promise<{
172
+ url: string
173
+ stop: () => void
174
+ rebuild: () => Promise<void>
175
+ stats: () => BuildCacheStats
176
+ }> {
35
177
  const prevKayDev = process.env.KAY_DEV
36
178
  process.env.KAY_DEV = '1'
37
179
  const root = resolve(options.root)
38
- const srcDir = resolve(root, 'src')
39
- const publicDir = resolve(root, 'public')
40
- const configPath = join(root, 'kay.config.ts')
41
180
  const devRoot = join(root, '.kay-dev')
42
- const port = options.port ?? 3000
181
+ let initialConfigFailed = false
182
+ const initialCfg = await loadConfig(root).catch((err) => {
183
+ initialConfigFailed = true
184
+ console.warn(`[kay dev] failed to load kay.config.ts: ${err instanceof Error ? err.message : String(err)}`)
185
+ return {} as Awaited<ReturnType<typeof loadConfig>>
186
+ })
187
+ const assetPrefix = (initialCfg.assetPrefix ?? '/_kay').replace(/\/$/, '')
188
+ let reloadAssets = makeDevReloadAssets(assetPrefix)
189
+ const srcDir = resolve(root, 'src')
190
+ const routesDir = resolve(root, options.routesDir ?? initialCfg.routesDir ?? 'src/routes')
191
+ const publicDir = resolve(root, initialCfg.publicDir ?? 'public')
192
+ const port = options.port ?? initialCfg.port ?? 3000
43
193
  const hostname = options.hostname ?? '127.0.0.1'
44
194
  const buildCache = createBuildCache()
195
+ const modules = createModuleStore(join(devRoot, 'server'))
196
+ const watchers: FSWatcher[] = []
197
+ const watchedDirs = new Set<string>()
198
+ const pluginWatchers: FSWatcher[] = []
199
+ const graphWatchers = new Map<string, FSWatcher>()
200
+ let activeAssetPrefix = assetPrefix
201
+ let pluginWatchersAttached = false
202
+
203
+ const isInsideDir = (parent: string, target: string): boolean =>
204
+ target === parent || target.startsWith(`${parent}/`) || target.startsWith(`${parent}\\`)
205
+
206
+ function isCoveredByStaticWatchers(dir: string): boolean {
207
+ if (dir === root)
208
+ return false
209
+ for (const base of watchedDirs) {
210
+ if (isInsideDir(base, dir))
211
+ return true
212
+ }
213
+ return false
214
+ }
215
+
216
+ function syncBuildWatchers(watchedFiles: ReadonlySet<string>): void {
217
+ const nextDirs = new Set<string>()
218
+ let realRoot = root
219
+ try {
220
+ realRoot = realpathSync(root)
221
+ }
222
+ catch {}
223
+ for (const file of watchedFiles) {
224
+ if (file.includes('/node_modules/') || file.includes('\\node_modules\\'))
225
+ continue
226
+ if (isInsideDir(devRoot, file) || isInsideDir(join(root, '.kay-cache'), file))
227
+ continue
228
+ const dir = dirname(file)
229
+ // Root is already watched non-recursively for `kay.config.ts`; skip if it's only kay.config.ts itself.
230
+ if (dir === root || dir === realRoot) {
231
+ if (file === join(root, 'kay.config.ts') || file === join(realRoot, 'kay.config.ts'))
232
+ continue
233
+ }
234
+ if (isCoveredByStaticWatchers(dir))
235
+ continue
236
+ nextDirs.add(dir)
237
+ }
238
+ for (const [dir, watcher] of graphWatchers) {
239
+ if (!nextDirs.has(dir)) {
240
+ watcher.close()
241
+ graphWatchers.delete(dir)
242
+ }
243
+ }
244
+ for (const dir of nextDirs) {
245
+ if (graphWatchers.has(dir) || !existsSync(dir))
246
+ continue
247
+ try {
248
+ graphWatchers.set(dir, watch(dir, (_ev, filename) => {
249
+ const name = typeof filename === 'string' ? filename : ''
250
+ scheduleRebuild(srcChangeKind(name))
251
+ }))
252
+ }
253
+ catch {}
254
+ }
255
+ }
256
+
257
+ function refreshPluginWatchers(cfg: Awaited<ReturnType<typeof loadConfig>>): void {
258
+ for (const w of pluginWatchers)
259
+ w.close()
260
+ pluginWatchers.length = 0
261
+ const seen = new Set<string>(watchedDirs)
262
+ const watchCtx = createAppContext({ root, outDir: devRoot, publicDir, assetPrefix: activeAssetPrefix, site: cfg.site, dev: true })
263
+ for (const plugin of resolvePlugins(cfg.plugins)) {
264
+ const paths = runWithAppContext(watchCtx, () =>
265
+ typeof plugin.watchPaths === 'function' ? plugin.watchPaths(root) : (plugin.watchPaths ?? []))
266
+ for (const p of paths) {
267
+ const abs = resolve(root, p)
268
+ if (seen.has(abs) || !existsSync(abs))
269
+ continue
270
+ seen.add(abs)
271
+ const isDir = statSync(abs).isDirectory()
272
+ pluginWatchers.push(watch(abs, isDir ? { recursive: true } : {}, () => scheduleRebuild('full')))
273
+ }
274
+ }
275
+ }
45
276
 
46
277
  let buildNum = 0
47
278
  let currentApp: KayApp | undefined
@@ -53,13 +284,13 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
53
284
  let pending = false
54
285
  let pendingCssOnly = true
55
286
  let pendingConfigReset = false
287
+ let pendingReloadAll = false
56
288
  let inFlight: Promise<void> | undefined
57
289
 
58
290
  const clients = new Set<ReadableStreamDefaultController<Uint8Array>>()
59
291
  const encoder = new TextEncoder()
60
292
 
61
- function broadcast(payload: string): void {
62
- const chunk = encoder.encode(`data: ${payload}\n\n`)
293
+ function pushToClients(chunk: Uint8Array): void {
63
294
  for (const c of clients) {
64
295
  try {
65
296
  c.enqueue(chunk)
@@ -70,20 +301,26 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
70
301
  }
71
302
  }
72
303
 
73
- async function runSingleBuild(cssOnly: boolean, resetCache: boolean): Promise<void> {
304
+ const broadcast = (payload: string): void => pushToClients(encoder.encode(`data: ${payload}\n\n`))
305
+
306
+ async function runSingleBuild(cssOnly: boolean, resetCache: boolean, reloadAll: boolean): Promise<void> {
74
307
  if (stopped)
75
308
  return
76
- if (resetCache) {
77
- buildCache.analyses.clear()
78
- buildCache.domCompiled.clear()
79
- buildCache.ssrCompiled.clear()
80
- }
81
309
  const hadError = lastError !== undefined
82
310
  const hadApp = currentApp !== undefined
83
311
  const n = ++buildNum
84
312
  const outDir = `.kay-dev/b${n}`
85
313
  const t0 = performance.now()
86
314
  try {
315
+ if (resetCache) {
316
+ clearBuildCache(buildCache)
317
+ const freshCfg = await loadConfig(root, { fresh: true })
318
+ activeAssetPrefix = (freshCfg.assetPrefix ?? '/_kay').replace(/\/$/, '')
319
+ reloadAssets = makeDevReloadAssets(activeAssetPrefix)
320
+ refreshPluginWatchers(freshCfg)
321
+ }
322
+ if (reloadAll)
323
+ modules.reloadAll()
87
324
  const manifest = await build({
88
325
  root,
89
326
  routesDir: options.routesDir,
@@ -91,10 +328,53 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
91
328
  minify: false,
92
329
  prerender: false,
93
330
  copyPublic: false,
331
+ dev: true,
94
332
  cache: buildCache,
95
333
  })
96
- currentApp = await createServer({ root, outDir })
334
+ if (stopped) {
335
+ rmSync(join(root, outDir), { recursive: true, force: true })
336
+ return
337
+ }
338
+ const serverDir = join(root, outDir, 'server')
339
+ const routeFiles = new Set(manifest.routes.map(r => r.file.replace(/^server\//, '')))
340
+ const sharedRelFiles = new Set<string>()
341
+ if (manifest.configFile !== undefined)
342
+ sharedRelFiles.add(manifest.configFile.replace(/^server\//, ''))
343
+ for (const a of manifest.actions) {
344
+ const rel = a.file.replace(/^server\//, '')
345
+ if (!routeFiles.has(rel))
346
+ sharedRelFiles.add(rel)
347
+ }
348
+ modules.sync(serverDir, sharedRelFiles)
349
+ const nextApp = await createServer({
350
+ root,
351
+ outDir,
352
+ dev: true,
353
+ compress: false,
354
+ importModule: modules.importFrom(serverDir),
355
+ })
356
+ if (stopped) {
357
+ await nextApp.dispose?.()
358
+ rmSync(join(root, outDir), { recursive: true, force: true })
359
+ return
360
+ }
361
+ const prevApp = currentApp
362
+ currentApp = nextApp
363
+ await prevApp?.dispose?.()
97
364
  lastError = undefined
365
+ syncBuildWatchers(buildCache.watchedFiles)
366
+ if (!pluginWatchersAttached && !initialConfigFailed) {
367
+ pluginWatchersAttached = true
368
+ }
369
+ else if (initialConfigFailed) {
370
+ initialConfigFailed = false
371
+ try {
372
+ const recoveredCfg = await loadConfig(root)
373
+ refreshPluginWatchers(recoveredCfg)
374
+ pluginWatchersAttached = true
375
+ }
376
+ catch {}
377
+ }
98
378
  if (n > 2)
99
379
  rmSync(join(devRoot, `b${n - 2}`), { recursive: true, force: true })
100
380
  console.log(`[kay dev] rebuilt in ${(performance.now() - t0).toFixed(1)} ms`)
@@ -104,6 +384,8 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
104
384
  broadcast('reload')
105
385
  }
106
386
  catch (err) {
387
+ if (stopped)
388
+ return
107
389
  lastError = err instanceof Error ? err.stack ?? err.message : String(err)
108
390
  console.error(`[kay dev] build error:\n${lastError}`)
109
391
  // Push reload over SSE so open browser tabs immediately display the error overlay
@@ -111,7 +393,10 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
111
393
  }
112
394
  }
113
395
 
396
+ let timer: ReturnType<typeof setTimeout> | undefined
397
+
114
398
  function drainRebuilds(): Promise<void> {
399
+ clearTimeout(timer)
115
400
  if (building) {
116
401
  pending = true
117
402
  return inFlight ?? Promise.resolve()
@@ -120,12 +405,15 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
120
405
  const run = (async () => {
121
406
  try {
122
407
  do {
408
+ clearTimeout(timer)
123
409
  const cssOnly = pendingCssOnly
124
410
  const resetCache = pendingConfigReset
411
+ const reloadAll = pendingReloadAll
125
412
  pending = false
126
413
  pendingCssOnly = true
127
414
  pendingConfigReset = false
128
- await runSingleBuild(cssOnly, resetCache)
415
+ pendingReloadAll = false
416
+ await runSingleBuild(cssOnly, resetCache, reloadAll)
129
417
  } while (pending && !stopped)
130
418
  }
131
419
  finally {
@@ -141,67 +429,55 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
141
429
  pendingCssOnly = false
142
430
  await drainRebuilds()
143
431
 
144
- let timer: ReturnType<typeof setTimeout> | undefined
145
432
  const scheduleRebuild = (kind: ChangeKind) => {
146
433
  if (stopped)
147
434
  return
148
- if (kind === 'config') {
435
+ if (kind === 'config')
149
436
  pendingConfigReset = true
437
+ if (kind === 'config' || kind === 'full')
438
+ pendingReloadAll = true
439
+ if (kind !== 'css')
150
440
  pendingCssOnly = false
151
- }
152
- else if (kind === 'full') {
153
- pendingCssOnly = false
154
- }
155
441
  clearTimeout(timer)
156
442
  timer = setTimeout(() => {
157
443
  void drainRebuilds()
158
444
  }, 40)
159
445
  }
160
446
 
161
- const watchers: FSWatcher[] = []
162
- if (existsSync(srcDir)) {
163
- watchers.push(watch(srcDir, { recursive: true }, (_ev, filename) => {
164
- const name = typeof filename === 'string' ? filename : ''
165
- const isCss = name.endsWith('.css') && !name.endsWith('.module.css')
166
- scheduleRebuild(isCss ? 'css' : 'full')
447
+ const addDirWatch = (dir: string, handler: (filename: string) => void) => {
448
+ if (watchedDirs.has(dir) || !existsSync(dir))
449
+ return
450
+ watchedDirs.add(dir)
451
+ watchers.push(watch(dir, { recursive: true }, (_ev, filename) => {
452
+ handler(typeof filename === 'string' ? filename : '')
167
453
  }))
168
454
  }
169
- if (existsSync(publicDir))
170
- watchers.push(watch(publicDir, { recursive: true }, () => scheduleRebuild('full')))
171
- if (existsSync(configPath))
172
- watchers.push(watch(configPath, () => scheduleRebuild('config')))
173
455
 
174
- // Watch plugin-declared extra paths (e.g. content/ or messages/ directories)
456
+ addDirWatch(srcDir, name => scheduleRebuild(srcChangeKind(name)))
457
+ // If routesDir sits outside src/, watch it too!
458
+ if (!routesDir.startsWith(`${srcDir}/`) && !routesDir.startsWith(`${srcDir}\\`) && routesDir !== srcDir)
459
+ addDirWatch(routesDir, name => scheduleRebuild(srcChangeKind(name)))
460
+ addDirWatch(publicDir, () => scheduleRebuild('full'))
461
+
462
+ // Watch root (non-recursive) for kay.config.ts so atomic editor saves (temp + rename) still fire events.
463
+ watchers.push(watch(root, (_ev, filename) => {
464
+ if (filename === 'kay.config.ts')
465
+ scheduleRebuild('config')
466
+ }))
467
+
468
+ // Watch plugin-declared extra paths (e.g. content/ or messages/ directories); refreshed on kay.config.ts edits.
175
469
  try {
176
- const cfg = await loadConfig(root)
177
- const watchedExtra = new Set<string>([srcDir, publicDir, configPath])
178
- for (const plugin of cfg.plugins ?? []) {
179
- const paths = typeof plugin.watchPaths === 'function' ? plugin.watchPaths(root) : (plugin.watchPaths ?? [])
180
- for (const p of paths) {
181
- const abs = resolve(root, p)
182
- if (watchedExtra.has(abs) || !existsSync(abs))
183
- continue
184
- watchedExtra.add(abs)
185
- const isDir = statSync(abs).isDirectory()
186
- watchers.push(watch(abs, isDir ? { recursive: true } : {}, () => scheduleRebuild('full')))
187
- }
188
- }
470
+ refreshPluginWatchers(initialCfg)
471
+ }
472
+ catch (err) {
473
+ console.warn(`[kay dev] could not attach plugin watchers: ${err instanceof Error ? err.message : String(err)}`)
189
474
  }
190
- catch {}
191
475
 
192
476
  const pingChunk = encoder.encode(': ping\n\n')
193
- const pingInterval = setInterval(() => {
194
- for (const c of clients) {
195
- try {
196
- c.enqueue(pingChunk)
197
- }
198
- catch {
199
- clients.delete(c)
200
- }
201
- }
202
- }, 15_000)
477
+ const pingInterval = setInterval(() => pushToClients(pingChunk), 15_000)
203
478
 
204
- const maxRequestBodySize = options.maxRequestBodySize ?? DEFAULT_MAX_REQUEST_BODY_SIZE
479
+ const runtimeCfg = resolveServerConfig(initialCfg, { maxRequestBodySize: options.maxRequestBodySize })
480
+ const maxRequestBodySize = runtimeCfg.maxRequestBodySize ?? DEFAULT_MAX_REQUEST_BODY_SIZE
205
481
 
206
482
  const server = Bun.serve({
207
483
  port,
@@ -211,7 +487,7 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
211
487
  async fetch(request, srv) {
212
488
  const url = new URL(request.url)
213
489
 
214
- if (url.pathname === '/_kay/dev-events') {
490
+ if (url.pathname === reloadAssets.eventsPath) {
215
491
  srv.timeout(request, 0)
216
492
  let ctrl: ReadableStreamDefaultController<Uint8Array> | undefined
217
493
  const stream = new ReadableStream<Uint8Array>({
@@ -242,7 +518,7 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
242
518
  }
243
519
 
244
520
  if (lastError !== undefined) {
245
- return new Response(renderErrorOverlay(lastError), {
521
+ return new Response(renderErrorOverlay(lastError, reloadAssets.script), {
246
522
  status: 500,
247
523
  headers: { 'content-type': 'text/html; charset=utf-8' },
248
524
  })
@@ -253,16 +529,13 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
253
529
  const ct = res.headers.get('content-type') ?? ''
254
530
  if (ct.includes('text/event-stream'))
255
531
  srv.timeout(request, 0)
256
- if (ct.includes('text/html')) {
257
- const html = await res.text()
258
- const injected = html.includes('</body>')
259
- ? html.replace('</body>', `${DEV_RELOAD_SCRIPT}</body>`)
260
- : html + DEV_RELOAD_SCRIPT
532
+ if (ct.includes('text/html') && request.method !== 'HEAD' && res.body !== null && !res.headers.has('content-encoding')) {
261
533
  const headers = new Headers(res.headers)
534
+ headers.delete('content-length')
262
535
  const existingCsp = headers.get('content-security-policy')
263
536
  if (existingCsp !== null)
264
- headers.set('content-security-policy', withCspHashes(existingCsp, { scriptHashes: [DEV_RELOAD_SCRIPT_HASH] }))
265
- return new Response(injected, { status: res.status, headers })
537
+ headers.set('content-security-policy', withCspHashes(existingCsp, { scriptHashes: [reloadAssets.hash] }))
538
+ return new Response(injectReloadStream(res.body, reloadAssets.script), { status: res.status, headers })
266
539
  }
267
540
  return res
268
541
  },
@@ -278,13 +551,22 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
278
551
  pendingCssOnly = false
279
552
  return drainRebuilds()
280
553
  },
554
+ stats() {
555
+ return { ...buildCache.stats }
556
+ },
281
557
  stop() {
282
558
  stopped = true
283
559
  clearTimeout(timer)
284
560
  clearInterval(pingInterval)
285
561
  for (const w of watchers)
286
562
  w.close()
563
+ for (const w of pluginWatchers)
564
+ w.close()
565
+ for (const w of graphWatchers.values())
566
+ w.close()
567
+ graphWatchers.clear()
287
568
  server.stop(true)
569
+ void currentApp?.dispose?.()
288
570
  rmSync(devRoot, { recursive: true, force: true })
289
571
  if (prevKayDev === undefined)
290
572
  delete process.env.KAY_DEV