@kayjs/kay 2.0.0-alpha.7 → 2.0.0-alpha.8

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-alpha.8",
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)
@@ -10,6 +10,7 @@ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, wri
10
10
  import { basename, dirname, extname, isAbsolute, join, relative, resolve } from 'node:path'
11
11
  import { brotliCompressSync, constants as zlibConstants } from 'node:zlib'
12
12
  import { analyzeModule, compileDom, compileSsr } from '../compiler/index'
13
+ import { readsPrivateEnv, SERVER_ONLY_FILTER } from '../compiler/server-only'
13
14
  import { loadConfig } from '../plugins/index'
14
15
  import { actionHash } from '../server/action'
15
16
  import { compileExecutable } from './compile'
@@ -54,6 +55,8 @@ export interface ActionManifestEntry {
54
55
  url: string
55
56
  file: string
56
57
  exportName: string
58
+ /** `_middleware.ts` chain of the folder declaring the action, outermost first. */
59
+ middlewares: string[]
57
60
  }
58
61
 
59
62
  export interface RouteManifestEntry {
@@ -221,6 +224,10 @@ interface IslandTarget {
221
224
  defaultHydrate: string | undefined
222
225
  }
223
226
 
227
+ function clientLeakError(leaks: Set<string>): Error {
228
+ 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.`)
229
+ }
230
+
224
231
  export async function build(options: BuildOptions): Promise<BuildManifest> {
225
232
  const root = resolve(options.root)
226
233
  const fileConfig = await loadConfig(root)
@@ -377,6 +384,7 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
377
384
 
378
385
  // Discover all island roots referenced from static pages/layouts/errors (or sync interactive pages themselves)
379
386
  const islandTargets = new Map<string, IslandTarget>()
387
+ const islandIds = new Set<string>()
380
388
  const pageIslandBindings = new Map<string, Map<string, IslandTarget>>()
381
389
 
382
390
  function registerIsland(file: string, exportName: string): IslandTarget {
@@ -387,7 +395,11 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
387
395
  const analysis = loadAnalysis(file)
388
396
  const baseName = basename(file, extname(file)).toLowerCase()
389
397
  const expLower = exportName.toLowerCase()
390
- const id = exportName === 'default' || expLower === baseName ? baseName : `${baseName}-${expLower}`
398
+ let id = exportName === 'default' || expLower === baseName ? baseName : `${baseName}-${expLower}`
399
+ // The id names the entry file and the chunk: two islands sharing a basename keep it readable and add a hash of their path.
400
+ if (islandIds.has(id))
401
+ id = `${id}-${Bun.hash(relative(root, key)).toString(36).slice(0, 6)}`
402
+ islandIds.add(id)
391
403
  const target: IslandTarget = { id, file, exportName, defaultHydrate: analysis.defaultHydrate }
392
404
  islandTargets.set(key, target)
393
405
  return target
@@ -444,6 +456,21 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
444
456
  for (const [, target] of islandTargets)
445
457
  collectIslandCss(target.file)
446
458
 
459
+ // The client compiles every module an island imports to hydrate against SSR markers, so their SSR must emit them too.
460
+ const islandReach = new Set<string>()
461
+ const reachStack = [...islandTargets.values()].map(t => t.file)
462
+ while (reachStack.length > 0) {
463
+ const file = reachStack.pop()!
464
+ if (islandReach.has(file))
465
+ continue
466
+ islandReach.add(file)
467
+ for (const imp of analyses.get(file)?.imports ?? []) {
468
+ const target = resolveImportPath(file, imp.source)
469
+ if (target !== undefined && target.endsWith('.tsx'))
470
+ reachStack.push(target)
471
+ }
472
+ }
473
+
447
474
  const standaloneCssSet = new Set<string>(pluginCssFiles)
448
475
  for (const [file, analysis] of analyses) {
449
476
  for (const imp of analysis.imports) {
@@ -518,9 +545,22 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
518
545
  islandEntryToKey.set(entryPath, key)
519
546
  }
520
547
 
548
+ const clientLeaks = new Set<string>()
549
+ const publicEnvDefines: Record<string, string> = {}
550
+ for (const [key, value] of Object.entries(process.env)) {
551
+ if (key.startsWith('PUBLIC_') && value !== undefined)
552
+ publicEnvDefines[`process.env.${key}`] = JSON.stringify(value)
553
+ }
554
+ const inlinedEnvKey = (key: string): boolean => key === 'NODE_ENV' || `process.env.${key}` in publicEnvDefines
521
555
  const clientPlugin: BunPlugin = {
522
556
  name: 'kay-v2-client',
523
557
  setup(b) {
558
+ // Bun swaps node built-ins for empty shims in a browser build, so a server-only import would ship silently.
559
+ b.onResolve({ filter: SERVER_ONLY_FILTER }, (args) => {
560
+ if (!args.importer.includes('/node_modules/'))
561
+ clientLeaks.add(`${relative(root, args.importer).replace(/\\/g, '/')} imports server-only module "${args.path}"`)
562
+ return undefined
563
+ })
524
564
  b.onResolve({ filter: /^(?:@kayjs\/)?kay(?:\/.*)?$/ }, (args) => {
525
565
  const resolved = resolveKaySpecifier(args.path)
526
566
  return resolved !== undefined ? { path: resolved } : undefined
@@ -571,14 +611,22 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
571
611
  define: {
572
612
  KAY_DEFERRED: hasDeferredHydrate ? 'true' : 'false',
573
613
  KAY_CLIENT_ONLY: hasClientOnlyHydrate ? 'true' : 'false',
614
+ ...publicEnvDefines,
574
615
  },
575
616
  plugins: [clientPlugin, ...pluginBunPlugins],
576
617
  })
577
618
  }
619
+ catch (err) {
620
+ if (clientLeaks.size > 0)
621
+ throw clientLeakError(clientLeaks)
622
+ throw err
623
+ }
578
624
  finally {
579
625
  rmSync(entriesDir, { recursive: true, force: true })
580
626
  }
581
627
 
628
+ if (clientLeaks.size > 0)
629
+ throw clientLeakError(clientLeaks)
582
630
  if (!clientResult.success) {
583
631
  const msgs = clientResult.logs.map(l => l.message).join('\n')
584
632
  throw new Error(`kay build (client) failed:\n${msgs}`)
@@ -592,10 +640,28 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
592
640
  return resolve(clientDir, p)
593
641
  }
594
642
 
643
+ // A process.env left in a chunk is a key the build did not inline: name the app module that put it there.
644
+ for (const output of clientResult.outputs) {
645
+ if (!output.path.endsWith('.js') || !(await output.text()).includes('process.env'))
646
+ continue
647
+ const relFile = relative(clientDir, output.path).replace(/\\/g, '/')
648
+ const info = clientMetafile?.outputs[relFile] ?? clientMetafile?.outputs[`./${relFile}`]
649
+ for (const [inKey, input] of Object.entries(info?.inputs ?? {})) {
650
+ const program = input.bytesInOutput > 0 ? analyses.get(resolveMetaPath(inKey))?.program : undefined
651
+ if (program !== undefined && readsPrivateEnv(program, inlinedEnvKey))
652
+ clientLeaks.add(`${relative(root, resolveMetaPath(inKey)).replace(/\\/g, '/')} reads process.env (only a process.env.PUBLIC_* set at build time is inlined)`)
653
+ }
654
+ }
655
+ if (clientLeaks.size > 0)
656
+ throw clientLeakError(clientLeaks)
657
+
595
658
  if (clientMetafile !== undefined) {
596
659
  for (const [outKey, info] of Object.entries(clientMetafile.outputs)) {
597
660
  const relOut = outKey.replace(/^\.\//, '')
598
661
  const url = `${assetPrefix}/${relOut}`
662
+ const islandKey = info.entryPoint !== undefined && relOut.endsWith('.js') ? islandEntryToKey.get(resolveMetaPath(info.entryPoint)) : undefined
663
+ if (islandKey !== undefined)
664
+ islandChunks.set(islandKey, url)
599
665
  if (relOut.endsWith('.css')) {
600
666
  if (info.entryPoint !== undefined) {
601
667
  const absEntry = resolveMetaPath(info.entryPoint)
@@ -624,16 +690,8 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
624
690
  if (relFile.endsWith('.css')) {
625
691
  styleUrls.push(url)
626
692
  }
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
- }
693
+ else if (output.kind === 'entry-point' && relFile.startsWith('runtime-')) {
694
+ runtimeScript = url
637
695
  }
638
696
  }
639
697
  }
@@ -734,7 +792,8 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
734
792
  const analysis = analyses.get(args.path)
735
793
  const rawBindings = pageIslandBindings.get(args.path)
736
794
  let islandMap: Map<string, IslandBinding> | undefined
737
- let islandKey = analysis?.isInteractive ? '1' : '0'
795
+ const inIsland = analysis?.isInteractive === true || islandReach.has(args.path)
796
+ let islandKey = inIsland ? '1' : '0'
738
797
  if (rawBindings !== undefined) {
739
798
  islandMap = new Map()
740
799
  for (const [localName, target] of rawBindings) {
@@ -757,7 +816,7 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
757
816
  const compiled = compileSsr(args.path, raw, {
758
817
  analysis,
759
818
  islands: islandMap,
760
- isIsland: analysis?.isInteractive,
819
+ isIsland: inIsland,
761
820
  })
762
821
  const outCode = applyTransforms(compiled.code, args.path, 'server')
763
822
  if (cache !== undefined && stamp !== undefined)
@@ -954,8 +1013,10 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
954
1013
  const actionEntries: ActionManifestEntry[] = []
955
1014
  for (const [srcFile, list] of actionsByFile) {
956
1015
  const outFile = toOutRel(srcFile)
1016
+ const inRoutes = !relative(routesDir, srcFile).startsWith('..')
1017
+ const middlewares = inRoutes ? ancestorFiles(routesDir, srcFile, ['_middleware.ts', '_middleware.tsx']).map(toOutRel) : []
957
1018
  for (const a of list)
958
- actionEntries.push({ url: a.url, file: outFile, exportName: a.exportName })
1019
+ actionEntries.push({ url: a.url, file: outFile, exportName: a.exportName, middlewares })
959
1020
  }
960
1021
 
961
1022
  const islandsRecord: Record<string, string> = {}
package/src/cli/check.ts CHANGED
@@ -4,6 +4,7 @@ import type { AstNode, ModuleAnalysis } from '../compiler/analyze'
4
4
  import { existsSync, readdirSync, readFileSync } from 'node:fs'
5
5
  import { basename, dirname, join, relative, resolve } from 'node:path'
6
6
  import { analyzeModule, walk } from '../compiler/analyze'
7
+ import { readsPrivateEnv, SERVER_ONLY_MODULES } from '../compiler/server-only'
7
8
  import { loadConfig } from '../plugins/index'
8
9
 
9
10
  export interface CheckResult {
@@ -12,33 +13,6 @@ export interface CheckResult {
12
13
  errors: string[]
13
14
  }
14
15
 
15
- const SERVER_ONLY_MODULES = new Set([
16
- 'kay/server',
17
- '@kayjs/kay/server',
18
- 'bun:sqlite',
19
- 'bun:ffi',
20
- 'bun:dns',
21
- 'node:fs',
22
- 'node:fs/promises',
23
- 'node:child_process',
24
- 'node:net',
25
- 'node:http',
26
- 'node:https',
27
- 'node:http2',
28
- 'node:os',
29
- 'node:worker_threads',
30
- 'node:cluster',
31
- 'node:dgram',
32
- 'node:tls',
33
- 'node:readline',
34
- 'fs',
35
- 'fs/promises',
36
- 'child_process',
37
- 'net',
38
- 'http',
39
- 'https',
40
- ])
41
-
42
16
  const SERIALIZABLE_NEW_CTORS = new Set(['Date', 'Map', 'Set', 'URL', 'RegExp'])
43
17
 
44
18
  function walkTsFiles(dir: string, out: string[] = []): string[] {
@@ -69,6 +43,42 @@ function resolveLocalModule(fromFile: string, specifier: string): string | undef
69
43
  return undefined
70
44
  }
71
45
 
46
+ // Walks the local imports of an island the way the client build follows them: a module that only declares actions is stubbed there, so its imports stop the walk.
47
+ function checkIslandReach(island: string, root: string, analyses: Map<string, ModuleAnalysis>, reported: Set<string>, errors: string[]): void {
48
+ const islandRel = relative(root, island).replace(/\\/g, '/')
49
+ const seen = new Set<string>()
50
+ const stack = [island]
51
+ while (stack.length > 0) {
52
+ const file = stack.pop()!
53
+ if (seen.has(file))
54
+ continue
55
+ seen.add(file)
56
+ const analysis = analyses.get(file)
57
+ if (analysis === undefined || (file !== island && !analysis.isInteractive && analysis.exportedActions.length > 0))
58
+ continue
59
+ const rel = relative(root, file).replace(/\\/g, '/')
60
+ const report = (key: string, message: string): void => {
61
+ if (reported.has(`${file}\0${key}`))
62
+ return
63
+ reported.add(`${file}\0${key}`)
64
+ errors.push(message)
65
+ }
66
+ for (const source of [...analysis.imports.map(i => i.source), ...analysis.reexports.map(r => r.source)]) {
67
+ if (SERVER_ONLY_MODULES.has(source)) {
68
+ report(source, file === island
69
+ ? `kay check: ${rel}: interactive island imports server-only module "${source}". Move server logic to a server action or async server component.`
70
+ : `kay check: ${rel}: imports server-only module "${source}" and is reachable from the island in ${islandRel}. Move server logic to a server action or async server component.`)
71
+ continue
72
+ }
73
+ const target = resolveLocalModule(file, source)
74
+ if (target !== undefined)
75
+ stack.push(target)
76
+ }
77
+ if (readsPrivateEnv(analysis.program))
78
+ report('process.env', `kay check: ${rel}: reads process.env and is reachable from the island in ${islandRel}. Only process.env.PUBLIC_* reaches the browser.`)
79
+ }
80
+ }
81
+
72
82
  function normalizeRouteConflictKey(routesDir: string, file: string): string {
73
83
  const rel = relative(routesDir, file).replace(/\\/g, '/').replace(/\.(tsx|ts)$/, '')
74
84
  if (rel === 'index')
@@ -118,20 +128,14 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
118
128
 
119
129
  // 3b. Static guardrails: server-only imports in islands, non-serializable island props, route conflicts, missing paths()
120
130
  const seenRoutes = new Map<string, string>()
131
+ const reported = new Set<string>()
121
132
 
122
133
  for (const [file, analysis] of analyses) {
123
134
  const rel = relative(root, file).replace(/\\/g, '/')
124
135
 
125
- // Guardrail 1: server-only imports inside interactive islands
126
- if (analysis.isInteractive) {
127
- for (const imp of analysis.imports) {
128
- if (SERVER_ONLY_MODULES.has(imp.source)) {
129
- errors.push(
130
- `kay check: ${rel}: interactive island imports server-only module "${imp.source}". Move server logic to a server action or async server component.`,
131
- )
132
- }
133
- }
134
- }
136
+ // Guardrail 1: server-only imports and private env reads in an island or any module it imports
137
+ if (analysis.isInteractive)
138
+ checkIslandReach(file, root, analyses, reported, errors)
135
139
 
136
140
  // Guardrail 2: non-serializable props (functions / unsupported class instances) passed from static server code into an island
137
141
  if (!analysis.isInteractive && file.endsWith('.tsx')) {
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.7'
18
+ const kayVersion = options.kayVersion ?? '^2.0.0-alpha.8'
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)`)
@@ -323,7 +323,8 @@ export default async function BlogIndex() {
323
323
  )
324
324
  }
325
325
  `
326
- files['src/routes/blog/[slug].tsx'] = `import { Button, Stack } from '@kayjs/ui'
326
+ files['src/routes/blog/[slug].tsx'] = `import type { RequestContext } from 'kay/server'
327
+ import { Button, Stack } from '@kayjs/ui'
327
328
  import { Head } from 'kay'
328
329
  import { posts } from '../../posts'
329
330
 
@@ -332,11 +333,15 @@ export function paths() {
332
333
  return posts.paths('/blog')
333
334
  }
334
335
 
335
- export default async function PostPage({ params }: { params: { slug: string } }) {
336
- const post = posts.get(params.slug)
336
+ export async function load(ctx: RequestContext) {
337
+ const post = posts.get(ctx.params.slug ?? '')
337
338
  if (!post)
338
- return <p>Post not found.</p>
339
+ return new Response('Not found', { status: 404 })
340
+ return { post }
341
+ }
339
342
 
343
+ export default function PostPage({ data }: { data: { post: NonNullable<ReturnType<typeof posts.get>> } }) {
344
+ const { post } = data
340
345
  return (
341
346
  <Stack gap="1.25rem">
342
347
  <Head><title>{post.data.title}</title></Head>
@@ -1001,30 +1001,25 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
1001
1001
  }
1002
1002
  return undefined
1003
1003
  })
1004
- if (!stmtHasJsx) {
1005
- const active = new Map<string, string>()
1006
- for (const [k, v] of propRewrites) {
1007
- if (!shadowed.has(k))
1008
- active.set(k, v)
1009
- }
1010
- if (active.size > 0)
1011
- editor.replace(stmt.start, stmt.end, rewriteFreeIdentifiers(code, stmt, active))
1012
- }
1013
- else {
1014
- walk(stmt, (child) => {
1015
- if (child.type === 'JSXElement' || child.type === 'JSXFragment') {
1016
- editor.replace(child.start, child.end, compileRootJsx(child, propRewrites))
1017
- return false
1018
- }
1019
- return undefined
1020
- })
1004
+ const active = new Map<string, string>()
1005
+ for (const [k, v] of propRewrites) {
1006
+ if (!shadowed.has(k))
1007
+ active.set(k, v)
1021
1008
  }
1009
+ // A statement holding JSX also reads props around it (`if (on) return <b/>`): compile both in one pass.
1010
+ if (stmtHasJsx)
1011
+ editor.replace(stmt.start, stmt.end, compileExpression(stmt, active))
1012
+ else if (active.size > 0)
1013
+ editor.replace(stmt.start, stmt.end, rewriteFreeIdentifiers(code, stmt, active))
1022
1014
  if (stmt.type === 'VariableDeclaration') {
1023
1015
  for (const d of stmt.declarations as AstNode[])
1024
1016
  collectPatternNames(d.id, shadowed)
1025
1017
  }
1026
1018
  }
1027
1019
  }
1020
+ else if (propRewrites.size > 0) {
1021
+ editor.replace(fn.body.start, fn.body.end, compileExpression(fn.body, propRewrites))
1022
+ }
1028
1023
  else {
1029
1024
  walk(fn.body, (child) => {
1030
1025
  if (child.type === 'JSXElement' || child.type === 'JSXFragment') {
@@ -0,0 +1,62 @@
1
+ // What must never reach a browser bundle, shared by `kay build` and `kay check`.
2
+
3
+ import type { AstNode } from './analyze'
4
+ import { walk } from './analyze'
5
+
6
+ export const SERVER_ONLY_MODULES = new Set([
7
+ 'kay/server',
8
+ '@kayjs/kay/server',
9
+ 'bun:sqlite',
10
+ 'bun:ffi',
11
+ 'bun:dns',
12
+ 'node:fs',
13
+ 'node:fs/promises',
14
+ 'node:child_process',
15
+ 'node:net',
16
+ 'node:http',
17
+ 'node:https',
18
+ 'node:http2',
19
+ 'node:os',
20
+ 'node:worker_threads',
21
+ 'node:cluster',
22
+ 'node:dgram',
23
+ 'node:tls',
24
+ 'node:readline',
25
+ 'fs',
26
+ 'fs/promises',
27
+ 'child_process',
28
+ 'net',
29
+ 'http',
30
+ 'https',
31
+ ])
32
+
33
+ export const SERVER_ONLY_FILTER = new RegExp(`^(?:${[...SERVER_ONLY_MODULES].map(m => m.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&')).join('|')})$`)
34
+
35
+ // The client build inlines PUBLIC_* (from its own environment) and NODE_ENV; any other read ships a server variable name and crashes in the browser.
36
+ const CLIENT_ENV_KEY = /^(?:PUBLIC_\w*|NODE_ENV)$/
37
+
38
+ function isProcessEnv(node: AstNode | null | undefined): boolean {
39
+ return node?.type === 'MemberExpression' && !node.computed && node.object?.type === 'Identifier' && node.object.name === 'process' && node.property?.name === 'env'
40
+ }
41
+
42
+ /** True when the module reads `process.env` outside its `load()` (stripped from client code) for a key the client build does not inline. */
43
+ export function readsPrivateEnv(program: AstNode, isInlined: (key: string) => boolean = key => CLIENT_ENV_KEY.test(key)): boolean {
44
+ let found = false
45
+ walk(program, (node) => {
46
+ if (found)
47
+ return false
48
+ if (node.type === 'ExportNamedDeclaration' && node.declaration?.type === 'FunctionDeclaration' && node.declaration.id?.name === 'load')
49
+ return false
50
+ if (node.type === 'MemberExpression' && isProcessEnv(node.object)) {
51
+ const key = node.computed ? node.property?.value : node.property?.name
52
+ found = typeof key !== 'string' || !isInlined(key)
53
+ return false
54
+ }
55
+ if (isProcessEnv(node)) {
56
+ found = true
57
+ return false
58
+ }
59
+ return undefined
60
+ })
61
+ return found
62
+ }
package/src/dom/extras.ts CHANGED
@@ -140,6 +140,11 @@ export function insert(parent: Node, value: () => unknown, marker: Node | null =
140
140
  marker = res.marker
141
141
  const next = res.result
142
142
 
143
+ if (next == null && res.nodes !== undefined) {
144
+ current = res.nodes
145
+ return
146
+ }
147
+
143
148
  if (next == null || typeof next === 'boolean') {
144
149
  clearInserted(current)
145
150
  current = null
@@ -259,8 +264,10 @@ export function show(
259
264
  const res = claimInsert(parent, marker, () => untrack(() => runWithOwner(owner, fn)))
260
265
  marker = res.marker
261
266
  const rendered = res.result
262
- if (rendered == null || typeof rendered === 'boolean')
267
+ if (rendered == null || typeof rendered === 'boolean') {
268
+ nodes = res.nodes ?? []
263
269
  return
270
+ }
264
271
 
265
272
  if (typeof rendered === 'string' || typeof rendered === 'number') {
266
273
  const str = String(rendered)
package/src/dom/index.ts CHANGED
@@ -27,29 +27,38 @@ export function claimLoop(parent: Node, fn: () => void, skip = 0): boolean {
27
27
  return true
28
28
  }
29
29
 
30
- export function claimInsert<T>(parent: Node, marker: Node | null, fn: () => T): { result: T, marker: Node | null, claimed: Node | null } {
30
+ // `nodes` is the SSR range the render claimed through template() (a fragment hydrates to null, so the caller learns its nodes here).
31
+ export function claimInsert<T>(parent: Node, marker: Node | null, fn: () => T): { result: T, marker: Node | null, claimed: Node | null, nodes: Node[] | undefined } {
31
32
  if (!hydrating)
32
- return { result: fn(), marker, claimed: null }
33
+ return { result: fn(), marker, claimed: null, nodes: undefined }
33
34
 
34
- let claimed: Node | null = marker !== null ? marker : parent.lastChild
35
- let nextMarker = marker
36
- if (marker !== null && marker.nodeType !== 8) {
37
- const anchor = document.createComment('')
38
- ;(anchor as unknown as { __kayAnchor?: boolean }).__kayAnchor = true
39
- parent.insertBefore(anchor, marker.nextSibling)
40
- nextMarker = anchor
41
- }
42
- else if (marker !== null) {
43
- claimed = null
44
- }
35
+ const claimed: Node | null = marker === null ? parent.lastChild : marker.nodeType === 8 ? null : marker
45
36
  const prevNode = hydrateNode
46
37
  hydrateNode = claimed
38
+ let result: T
39
+ let end: Node | null
47
40
  try {
48
- return { result: fn(), marker: nextMarker, claimed }
41
+ result = fn()
42
+ end = hydrateNode
49
43
  }
50
44
  finally {
51
45
  hydrateNode = prevNode
52
46
  }
47
+ if (marker === null || claimed === null)
48
+ return { result, marker, claimed, nodes: undefined }
49
+
50
+ // The anchor goes after the claimed range; a text value or a nested insert moves no cursor and claims the one node.
51
+ const consumed = end !== claimed
52
+ const anchor = document.createComment('')
53
+ ;(anchor as unknown as { __kayAnchor?: boolean }).__kayAnchor = true
54
+ parent.insertBefore(anchor, consumed ? end : claimed.nextSibling)
55
+ let nodes: Node[] | undefined
56
+ if (consumed) {
57
+ nodes = []
58
+ for (let n: Node | null = claimed; n !== null && n !== anchor; n = n.nextSibling)
59
+ nodes.push(n)
60
+ }
61
+ return { result, marker: anchor, claimed, nodes }
53
62
  }
54
63
 
55
64
  export function hydrate(container: Element, render: () => Node | DocumentFragment | null): () => void {
@@ -38,7 +38,7 @@ interface SubNode {
38
38
  c: Link | undefined // cursor
39
39
  no: SubNode | undefined // nextOwned
40
40
  nq: SubNode | undefined // nextQueued
41
- cl: (() => void) | undefined // effect cleanup
41
+ k: (() => void) | undefined // cleanup returned by the effect
42
42
  o: Owner | undefined // owner
43
43
  r(): void // run
44
44
  }
@@ -211,10 +211,12 @@ function propagate(dep: DepNode, flag: number): void {
211
211
  }
212
212
  }
213
213
 
214
+ // One effect throwing must not strand the rest of the queue: every node still runs, then a lone error is rethrown as is and several as one AggregateError.
214
215
  function flush(): void {
215
216
  if (flushing || batchDepth > 0)
216
217
  return
217
218
  flushing = true
219
+ const errors: unknown[] = []
218
220
  try {
219
221
  let rounds = 0
220
222
  while (qHead !== undefined) {
@@ -226,16 +228,32 @@ function flush(): void {
226
228
  const next: SubNode | undefined = node.nq
227
229
  node.nq = undefined
228
230
  node.f &= ~QUEUED
229
- if (!(node.f & DISPOSED) && shouldRun(node))
230
- node.r()
231
+ try {
232
+ if (!(node.f & DISPOSED) && shouldRun(node))
233
+ node.r()
234
+ }
235
+ catch (err) {
236
+ errors.push(err)
237
+ }
231
238
  node = next
232
239
  }
233
240
  }
234
241
  }
235
242
  finally {
236
243
  flushing = false
244
+ let left = qHead
237
245
  qHead = qTail = undefined
246
+ while (left !== undefined) {
247
+ const next: SubNode | undefined = left.nq
248
+ left.nq = undefined
249
+ left.f &= ~QUEUED
250
+ left = next
251
+ }
238
252
  }
253
+ if (errors.length === 1)
254
+ throw errors[0]
255
+ if (errors.length > 1)
256
+ throw new AggregateError(errors, `kay: ${errors.length} effects threw`)
239
257
  }
240
258
 
241
259
  function shouldRun(sub: SubNode): boolean {
@@ -309,7 +327,7 @@ class ComputedNode<T> implements DepNode, SubNode, ReadonlySignal<T> {
309
327
  c: Link | undefined = undefined
310
328
  no: SubNode | undefined = undefined
311
329
  nq: SubNode | undefined = undefined
312
- cl: (() => void) | undefined = undefined
330
+ k: (() => void) | undefined = undefined
313
331
  o: Owner | undefined = undefined
314
332
  _f: () => T
315
333
  _v!: T
@@ -360,7 +378,8 @@ class ComputedNode<T> implements DepNode, SubNode, ReadonlySignal<T> {
360
378
  }
361
379
  }
362
380
 
363
- class EffectNode implements SubNode {
381
+ // An effect is also the owner of what its run creates (effects, onCleanup), released before the next run.
382
+ class EffectNode implements SubNode, Owner {
364
383
  f = EFFECT | DIRTY
365
384
  e = -1
366
385
  d: Link | undefined = undefined
@@ -368,13 +387,19 @@ class EffectNode implements SubNode {
368
387
  c: Link | undefined = undefined
369
388
  no: SubNode | undefined = undefined
370
389
  nq: SubNode | undefined = undefined
371
- cl: (() => void) | undefined = undefined
390
+ k: (() => void) | undefined = undefined
372
391
  o: Owner | undefined
392
+ p: Owner | undefined
393
+ fc: Owner | undefined = undefined
394
+ ns: Owner | undefined = undefined
395
+ fs: SubNode | undefined = undefined
396
+ cl: (() => void)[] | undefined = undefined
397
+ x = false
373
398
  _f: () => void | (() => void)
374
399
 
375
400
  constructor(fn: () => void | (() => void), owner: Owner | undefined) {
376
401
  this._f = fn
377
- this.o = owner
402
+ this.o = this.p = owner
378
403
  if (owner !== undefined) {
379
404
  this.no = owner.fs
380
405
  owner.fs = this
@@ -384,9 +409,10 @@ class EffectNode implements SubNode {
384
409
  r(): void {
385
410
  if (this.f & DISPOSED)
386
411
  return
387
- if (this.cl !== undefined) {
388
- const fn = this.cl
389
- this.cl = undefined
412
+ releaseOwned(this)
413
+ if (this.k !== undefined) {
414
+ const fn = this.k
415
+ this.k = undefined
390
416
  fn()
391
417
  }
392
418
  const prevSub = currentSub
@@ -395,11 +421,15 @@ class EffectNode implements SubNode {
395
421
  this.e = ++globalEpoch
396
422
  this.c = this.d
397
423
  currentSub = this
398
- currentOwner = this.o
424
+ currentOwner = this
399
425
  try {
400
426
  const ret = (this._f)()
401
- if (typeof ret === 'function')
402
- this.cl = ret
427
+ if (typeof ret === 'function') {
428
+ if (this.f & DISPOSED)
429
+ ret()
430
+ else
431
+ this.k = ret
432
+ }
403
433
  }
404
434
  finally {
405
435
  unlinkRemaining(this)
@@ -430,7 +460,22 @@ export function disposeOwner(owner: Owner): void {
430
460
  if (owner.x)
431
461
  return
432
462
  owner.x = true
463
+ releaseOwned(owner)
464
+ }
433
465
 
466
+ function disposeSub(sub: SubNode): void {
467
+ sub.f |= DISPOSED
468
+ unlinkAll(sub)
469
+ if (sub.f & EFFECT)
470
+ disposeOwner(sub as EffectNode)
471
+ if (sub.k !== undefined) {
472
+ const fn = sub.k
473
+ sub.k = undefined
474
+ fn()
475
+ }
476
+ }
477
+
478
+ function releaseOwned(owner: Owner): void {
434
479
  let child = owner.fc
435
480
  owner.fc = undefined
436
481
  while (child !== undefined) {
@@ -445,13 +490,7 @@ export function disposeOwner(owner: Owner): void {
445
490
  while (sub !== undefined) {
446
491
  const next = sub.no
447
492
  sub.no = undefined
448
- sub.f |= DISPOSED
449
- unlinkAll(sub)
450
- if (sub.cl !== undefined) {
451
- const fn = sub.cl
452
- sub.cl = undefined
453
- fn()
454
- }
493
+ disposeSub(sub)
455
494
  sub = next
456
495
  }
457
496
 
@@ -498,15 +537,8 @@ export function effect(fn: () => void | (() => void)): () => void {
498
537
  const node = new EffectNode(fn, currentOwner)
499
538
  node.r()
500
539
  return () => {
501
- if (node.f & DISPOSED)
502
- return
503
- node.f |= DISPOSED
504
- unlinkAll(node)
505
- if (node.cl !== undefined) {
506
- const cb = node.cl
507
- node.cl = undefined
508
- cb()
509
- }
540
+ if (!(node.f & DISPOSED))
541
+ disposeSub(node)
510
542
  }
511
543
  }
512
544
 
@@ -57,12 +57,16 @@ function wrap<T extends object>(target: T): T {
57
57
  : value
58
58
  const had = Object.prototype.hasOwnProperty.call(obj, key)
59
59
  const prev = Reflect.get(obj, key, receiver)
60
+ const prevLength = Array.isArray(obj) ? obj.length : 0
60
61
  const ok = Reflect.set(obj, key, rawValue, receiver)
61
62
  if (!had || !Object.is(prev, rawValue)) {
62
63
  notifyKey(obj, key)
63
64
  if (!had || Array.isArray(obj))
64
65
  notifyKey(obj, OWN_KEYS)
65
66
  }
67
+ // Writing past the end grows the array without a later `length` write that differs, so readers of length are told here.
68
+ if (Array.isArray(obj) && key !== 'length' && obj.length !== prevLength)
69
+ notifyKey(obj, 'length')
66
70
  return ok
67
71
  },
68
72
  deleteProperty(obj, key) {
@@ -291,13 +291,14 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
291
291
  }
292
292
 
293
293
  // Register server actions and assign their live URLs
294
- const actionHandlers = new Map<string, ServerAction<unknown, unknown>>()
294
+ const actionHandlers = new Map<string, { act: ServerAction<unknown, unknown>, middlewares: Middleware[] }>()
295
295
  for (const entry of manifest.actions) {
296
296
  const mod = modules[entry.file] as Record<string, unknown> | undefined
297
297
  const act = mod?.[entry.exportName]
298
298
  if (isServerAction(act)) {
299
299
  ;(act as { url: string }).url = entry.url
300
- actionHandlers.set(entry.url, act)
300
+ const middlewares = entry.middlewares.map(m => (modules[m] as LoadedMiddlewareModule).default)
301
+ actionHandlers.set(entry.url, { act, middlewares: [...globalMiddlewares, ...middlewares] })
301
302
  }
302
303
  }
303
304
 
@@ -629,10 +630,11 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
629
630
  return servePublic(request, pathname, pub)
630
631
  }
631
632
 
632
- // 2. Server actions (POST /_kay/action/<id>) — run global plugin middlewares first so ctx.locals (e.g. auth user) is populated
633
+ // 2. Server actions (POST /_kay/action/<id>): global plugin middlewares, then the _middleware.ts chain of the action's folder
633
634
  if (request.method === 'POST') {
634
- const act = actionHandlers.get(pathname)
635
- if (act !== undefined) {
635
+ const handler = actionHandlers.get(pathname)
636
+ if (handler !== undefined) {
637
+ const { act, middlewares } = handler
636
638
  const { ctx, cookieStore } = makeRequestContext(request, {})
637
639
  const runAction = async (): Promise<Response> => {
638
640
  const actionCtx: ActionContext = {
@@ -646,17 +648,13 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
646
648
  }
647
649
  return executeAction(act, request, actionCtx, trustedOrigins)
648
650
  }
649
- if (globalMiddlewares.length === 0) {
650
- const res = await runAction()
651
- return finalizeResponse(res, cookieStore, securityEntries)
652
- }
653
651
  let index = -1
654
652
  const dispatch = async (i: number): Promise<Response> => {
655
653
  if (i <= index)
656
654
  throw new Error('kay: middleware called next() multiple times')
657
655
  index = i
658
- if (i < globalMiddlewares.length)
659
- return globalMiddlewares[i]!(ctx, () => dispatch(i + 1))
656
+ if (i < middlewares.length)
657
+ return middlewares[i]!(ctx, () => dispatch(i + 1))
660
658
  return runAction()
661
659
  }
662
660
  try {
@@ -958,7 +956,10 @@ export async function createServer(options: ServerOptions): Promise<KayApp> {
958
956
  }
959
957
  if (manifest.errorFile) await loadMod(manifest.errorFile)
960
958
  if (manifest.notFoundFile) await loadMod(manifest.notFoundFile)
961
- for (const a of manifest.actions) await loadMod(a.file)
959
+ for (const a of manifest.actions) {
960
+ await loadMod(a.file)
961
+ for (const m of a.middlewares) await loadMod(m)
962
+ }
962
963
 
963
964
  return createServerFromEmbedded({
964
965
  manifest,