@kayjs/kay 2.0.0-beta.3 → 2.0.0-beta.4

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 (91) hide show
  1. package/llms.txt +42 -0
  2. package/package.json +24 -13
  3. package/src/build/bundle.ts +11 -51
  4. package/src/build/client-plugin.ts +108 -0
  5. package/src/build/compile.ts +4 -2
  6. package/src/build/graph.ts +16 -3
  7. package/src/build/index.ts +23 -15
  8. package/src/build/islands.ts +28 -30
  9. package/src/build/manifest.ts +6 -3
  10. package/src/build/report.ts +82 -13
  11. package/src/build/resolve.ts +6 -7
  12. package/src/build/routes.ts +12 -21
  13. package/src/build/server-entry.ts +1 -1
  14. package/src/cli/check.ts +49 -43
  15. package/src/cli/commands.ts +224 -0
  16. package/src/cli/index.ts +46 -302
  17. package/src/cli/new.ts +15 -509
  18. package/src/cli/upgrade-plugins.ts +168 -0
  19. package/src/cli/upgrade.ts +220 -0
  20. package/src/compiler/analyze.ts +319 -565
  21. package/src/compiler/ast.ts +39 -0
  22. package/src/compiler/data-keys.ts +233 -0
  23. package/src/compiler/dom.ts +18 -15
  24. package/src/compiler/interactivity.ts +174 -0
  25. package/src/compiler/mistakes.ts +19 -1
  26. package/src/compiler/server-only.ts +4 -1
  27. package/src/compiler/shared.ts +1 -1
  28. package/src/compiler/ssr.ts +28 -28
  29. package/src/context.ts +1 -1
  30. package/src/dev/index.ts +15 -23
  31. package/src/dom/extras.ts +43 -12
  32. package/src/dom/index.ts +25 -1
  33. package/src/index.ts +0 -13
  34. package/src/jsx-runtime.ts +1 -1
  35. package/src/plugins/context.ts +8 -6
  36. package/src/plugins/index.ts +2 -2
  37. package/src/plugins/load.ts +25 -2
  38. package/src/plugins/public.ts +6 -0
  39. package/src/plugins/services.ts +15 -3
  40. package/src/plugins/types.ts +7 -11
  41. package/src/server/action-registry.ts +10 -4
  42. package/src/server/action.ts +8 -2
  43. package/src/server/document.ts +13 -1
  44. package/src/server/errors.ts +7 -5
  45. package/src/server/index.ts +9 -10
  46. package/src/server/lifecycle.ts +22 -0
  47. package/src/server/plugin-host.ts +6 -8
  48. package/src/server/public.ts +15 -0
  49. package/src/server/request-scope.ts +22 -0
  50. package/src/server/stream.ts +4 -3
  51. package/src/ssr/context.ts +25 -0
  52. package/src/ssr/index.ts +10 -7
  53. package/src/test/browser.ts +180 -0
  54. package/src/test/index.ts +4 -1
  55. package/templates/_shared/AGENTS.md +5 -0
  56. package/templates/_shared/CLAUDE.md +1 -0
  57. package/templates/_shared/public/robots.txt +2 -0
  58. package/templates/_shared/tsconfig.json +19 -0
  59. package/templates/app/.env.example +4 -0
  60. package/templates/app/kay.config.ts +11 -0
  61. package/templates/app/package.json +20 -0
  62. package/templates/app/src/auth.ts +14 -0
  63. package/templates/app/src/routes/_layout.tsx +32 -0
  64. package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
  65. package/templates/app/src/routes/dashboard/index.tsx +13 -0
  66. package/templates/app/src/routes/index.tsx +15 -0
  67. package/templates/app/src/routes/login.tsx +34 -0
  68. package/templates/app/src/styles/app.css +7 -0
  69. package/templates/blog/content/posts/welcome.md +9 -0
  70. package/templates/blog/kay.config.ts +23 -0
  71. package/templates/blog/package.json +21 -0
  72. package/templates/blog/src/posts.ts +26 -0
  73. package/templates/blog/src/routes/_layout.tsx +20 -0
  74. package/templates/blog/src/routes/blog/[slug].tsx +31 -0
  75. package/templates/blog/src/routes/index.tsx +29 -0
  76. package/templates/blog/src/styles/app.css +10 -0
  77. package/templates/fullstack/kay.config.ts +6 -0
  78. package/templates/fullstack/package.json +18 -0
  79. package/templates/fullstack/src/actions/greet.ts +19 -0
  80. package/templates/fullstack/src/components/Counter.tsx +10 -0
  81. package/templates/fullstack/src/components/GreetForm.tsx +26 -0
  82. package/templates/fullstack/src/routes/_layout.tsx +14 -0
  83. package/templates/fullstack/src/routes/api/health.ts +5 -0
  84. package/templates/fullstack/src/routes/index.tsx +13 -0
  85. package/templates/fullstack/src/styles/app.css +29 -0
  86. package/templates/minimal/kay.config.ts +6 -0
  87. package/templates/minimal/package.json +18 -0
  88. package/templates/minimal/src/components/Counter.tsx +10 -0
  89. package/templates/minimal/src/routes/_layout.tsx +14 -0
  90. package/templates/minimal/src/routes/index.tsx +11 -0
  91. package/templates/minimal/src/styles/app.css +22 -0
@@ -9,7 +9,8 @@ import type {
9
9
  Node,
10
10
  } from 'oxc-parser'
11
11
  import type { ModuleAnalysis } from './analyze'
12
- import { analyzeModule, parseTsx, walk } from './analyze'
12
+ import { analyzeModule, parseTsx } from './analyze'
13
+ import { walk } from './ast'
13
14
  import { mistake } from './mistakes'
14
15
  import { SourceEditor } from './patch'
15
16
  import {
@@ -247,7 +248,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
247
248
  // Emits JSX directly into a string accumulator variable `_out` (zero closures on nested `.map()` loops!)
248
249
  function emitIntoBuffer(node: JSXElement | JSXFragment, bufVar: string, parts: StringParts, flushParts: () => void, pushStmt: (stmt: string) => void): void {
249
250
  if (node.type === 'JSXFragment') {
250
- emitChildrenIntoBuffer(node.children, bufVar, parts, flushParts, pushStmt)
251
+ emitChildrenIntoBuffer(node.children, bufVar, parts, flushParts, pushStmt, undefined, emitMarkers, true)
251
252
  return
252
253
  }
253
254
 
@@ -327,10 +328,13 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
327
328
  pushStmt: (stmt: string) => void,
328
329
  rawTextTag?: 'style' | 'script',
329
330
  slotMarkers = emitMarkers,
331
+ inFragment = false,
330
332
  ): void {
331
333
  const meaningful = filterMeaningfulChildren(children)
332
334
  const slots = meaningful.map(c => ({ child: c, slot: classifyJsxChild(c, jsxNodes) })).filter(s => s.slot !== undefined)
333
335
  const hasSiblings = slots.length > 1
336
+ // A fragment may sit inside another range, so its dynamic slots are bracketed even alone and always closed, for the markers to balance (#3596).
337
+ const bracketed = slotMarkers && (hasSiblings || inFragment)
334
338
  let hadVariableRange = false
335
339
 
336
340
  for (let i = 0; i < slots.length; i++) {
@@ -370,7 +374,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
370
374
  if (slotMarkers && hasSiblings) {
371
375
  parts.pushStatic('<!--k[-->')
372
376
  emitIntoBuffer(slot.node, bufVar, parts, flushParts, pushStmt)
373
- if (!isLast)
377
+ if (!isLast || inFragment)
374
378
  parts.pushStatic('<!--k]-->')
375
379
  }
376
380
  else {
@@ -382,7 +386,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
382
386
 
383
387
  if (slot.kind === 'loop') {
384
388
  const { match } = slot
385
- const needsBracket = slotMarkers && (!isLast || hadVariableRange)
389
+ const needsBracket = slotMarkers && (inFragment || !isLast || hadVariableRange)
386
390
  if (needsBracket)
387
391
  parts.pushStatic('<!--k[-->')
388
392
 
@@ -428,7 +432,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
428
432
  if (slot.kind === 'and-show') {
429
433
  const left = compileSubExpression(slot.expr.left)
430
434
  const right = compileJsxToStringExpr(slot.right)
431
- if (slotMarkers && hasSiblings) {
435
+ if (bracketed) {
432
436
  parts.pushStatic('<!--k[-->')
433
437
  parts.pushExpr(`((${left}) ? (${right}) : "")`)
434
438
  parts.pushStatic('<!--k]-->')
@@ -444,7 +448,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
444
448
  const test = compileSubExpression(slot.expr.test)
445
449
  const cons = compileExpressionAsString(slot.cons)
446
450
  const alt = compileExpressionAsString(slot.alt)
447
- if (slotMarkers && hasSiblings) {
451
+ if (bracketed) {
448
452
  parts.pushStatic('<!--k[-->')
449
453
  parts.pushExpr(`((${test}) ? (${cons}) : (${alt}))`)
450
454
  parts.pushStatic('<!--k]-->')
@@ -460,10 +464,10 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
460
464
  const exprCode = compileSubExpression(slot.expr)
461
465
  const rendered = `${use('esc')}(${exprCode})`
462
466
  if (isNodeCapableExpr(slot.expr, jsxNodes)) {
463
- if (slotMarkers && hasSiblings) {
467
+ if (bracketed) {
464
468
  parts.pushStatic('<!--k[-->')
465
469
  parts.pushExpr(rendered)
466
- if (!isLast)
470
+ if (!isLast || inFragment)
467
471
  parts.pushStatic('<!--k]-->')
468
472
  }
469
473
  else {
@@ -471,10 +475,10 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
471
475
  }
472
476
  hadVariableRange = true
473
477
  }
474
- else if (slotMarkers && hasSiblings) {
478
+ else if (bracketed) {
475
479
  parts.pushStatic('<!---->')
476
480
  parts.pushExpr(rendered)
477
- if (!isLast)
481
+ if (!isLast || inFragment)
478
482
  parts.pushStatic('<!---->')
479
483
  }
480
484
  else {
@@ -542,9 +546,11 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
542
546
 
543
547
  if (islandInfo !== undefined) {
544
548
  const propsCode = `{ ${propEntries.join(', ')} }`
545
- const callPropsCode = hasChildren
546
- ? `{ ${[...propEntries, `children: ${use('raw')}("<kay-slot>" + (${childExpr}) + "</kay-slot>")`].join(', ')} }`
547
- : propsCode
549
+ // The server children an island is handed render before it, outside its contexts and ids, as the browser never re-renders them.
550
+ const slotVar = hasChildren ? `_c${loopCounter++}` : undefined
551
+ const slotProp = slotVar === undefined ? '' : `children: ${use('raw')}("<kay-slot>" + ${slotVar} + "</kay-slot>")`
552
+ const callPropsCode = slotVar === undefined ? propsCode : `{ ${[...propEntries, slotProp].join(', ')} }`
553
+ const withSlot = (expr: string): string => slotVar === undefined ? expr : `((${slotVar}) => ${expr})(${childExpr})`
548
554
  const resolvedHydrate = staticHydrate ?? (hydrateExpr === undefined ? islandInfo.defaultHydrate : undefined)
549
555
 
550
556
  // Compile-time static island props fast path (only when not inside an island-reachable component and children don't contain direct `await`):
@@ -561,15 +567,14 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
561
567
  const renderArg = resolvedHydrate === 'client'
562
568
  ? 'undefined'
563
569
  : `() => ${use('ssrChild')}(${tag}(${callPropsCode}))`
564
- parts.pushExpr(`${use('ssrIslandStatic')}(${JSON.stringify(islandInfo.chunk)}, ${JSON.stringify(openTag)}, ${renderArg}, ${hydrateArg})`)
570
+ const expr = `${use('ssrIslandStatic')}(${JSON.stringify(islandInfo.chunk)}, ${JSON.stringify(openTag)}, ${renderArg}, ${hydrateArg}, ${JSON.stringify(tag)})`
571
+ parts.pushExpr(resolvedHydrate === 'client' ? expr : withSlot(expr))
565
572
  return
566
573
  }
567
574
 
568
575
  const hydrateArg = hydrateExpr ?? (islandInfo.defaultHydrate !== undefined ? JSON.stringify(islandInfo.defaultHydrate) : 'undefined')
569
576
  if (!childrenHaveAwait && allStaticProps && (hydrateExpr === undefined || staticHydrate !== undefined)) {
570
- parts.pushExpr(
571
- `${use('ssrIsland')}(${JSON.stringify(islandInfo.chunk)}, () => ${use('ssrChild')}(${tag}(${callPropsCode})), ${propsCode}, ${hydrateArg})`,
572
- )
577
+ parts.pushExpr(withSlot(`${use('ssrIsland')}(${JSON.stringify(islandInfo.chunk)}, () => ${use('ssrChild')}(${tag}(${callPropsCode})), ${propsCode}, ${hydrateArg}, false, ${JSON.stringify(tag)})`))
573
578
  return
574
579
  }
575
580
 
@@ -578,15 +583,10 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
578
583
  const argNames = [pVar]
579
584
  const argExprs = [propsCode]
580
585
  let callArg = pVar
581
- if (hasChildren) {
582
- let childSlotVal = childExpr
583
- if (childrenHaveAwait) {
584
- const cVar = `_c${loopCounter++}`
585
- argNames.push(cVar)
586
- argExprs.push(childExpr)
587
- childSlotVal = cVar
588
- }
589
- callArg = `{ ...${pVar}, children: ${use('raw')}("<kay-slot>" + (${childSlotVal}) + "</kay-slot>") }`
586
+ if (slotVar !== undefined) {
587
+ argNames.push(slotVar)
588
+ argExprs.push(childExpr)
589
+ callArg = `{ ...${pVar}, ${slotProp} }`
590
590
  }
591
591
  let hArg = hydrateArg
592
592
  if (hydrateExpr !== undefined && staticHydrate === undefined) {
@@ -596,7 +596,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
596
596
  hArg = hVar
597
597
  }
598
598
  parts.pushExpr(
599
- `((${argNames.join(', ')}) => ${use('ssrIsland')}(${JSON.stringify(islandInfo.chunk)}, () => ${use('ssrChild')}(${tag}(${callArg})), ${pVar}, ${hArg}))(${argExprs.join(', ')})`,
599
+ `((${argNames.join(', ')}) => ${use('ssrIsland')}(${JSON.stringify(islandInfo.chunk)}, () => ${use('ssrChild')}(${tag}(${callArg})), ${pVar}, ${hArg}, false, ${JSON.stringify(tag)}))(${argExprs.join(', ')})`,
600
600
  )
601
601
  return
602
602
  }
@@ -668,7 +668,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
668
668
 
669
669
  if (used.size > 0) {
670
670
  const specifiers = [...used].sort().map(name => `${name} as __${name}`).join(', ')
671
- editor.prepend(`import { ${specifiers} } from 'kay/ssr';\n`)
671
+ editor.prepend(`import { ${specifiers} } from '@kayjs/kay/internal/ssr';\n`)
672
672
  }
673
673
 
674
674
  return { code: editor.toString(), analysis }
package/src/context.ts CHANGED
@@ -19,7 +19,7 @@ function getServerBridge(): ServerContextBridge | undefined {
19
19
  return (globalThis as Record<symbol, ServerContextBridge | undefined>)[BRIDGE_KEY]
20
20
  }
21
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. */
22
+ /** Internal: registered by kay's SSR runtime on the server so `Head`, `Suspense`, `useContext`, and `useId` stay request-scoped without pulling `node:async_hooks` into client bundles. */
23
23
  export function registerServerContextBridge(bridge: ServerContextBridge): void {
24
24
  ;(globalThis as Record<symbol, ServerContextBridge | undefined>)[BRIDGE_KEY] = bridge
25
25
  }
package/src/dev/index.ts CHANGED
@@ -165,15 +165,23 @@ export async function devServer(options: DevServerOptions): Promise<{
165
165
  stats: () => BuildCacheStats
166
166
  }> {
167
167
  const prevKayDev = process.env.KAY_DEV
168
+ const restoreKayDev = (): void => {
169
+ if (prevKayDev === undefined)
170
+ delete process.env.KAY_DEV
171
+ else
172
+ process.env.KAY_DEV = prevKayDev
173
+ }
168
174
  process.env.KAY_DEV = '1'
169
175
  const root = resolve(options.root)
170
176
  const devRoot = join(root, '.kay-dev')
171
- let initialConfigFailed = false
172
- const initialCfg = await loadConfig(root).catch((err) => {
173
- initialConfigFailed = true
174
- console.warn(`[kay dev] failed to load kay.config.ts: ${err instanceof Error ? err.message : String(err)}`)
175
- return {} as Awaited<ReturnType<typeof loadConfig>>
176
- })
177
+ let initialCfg: Awaited<ReturnType<typeof loadConfig>>
178
+ try {
179
+ initialCfg = await loadConfig(root)
180
+ }
181
+ catch (error) {
182
+ restoreKayDev()
183
+ throw error
184
+ }
177
185
  const assetPrefix = (initialCfg.assetPrefix ?? '/_kay').replace(/\/$/, '')
178
186
  let reloadAssets = makeDevReloadAssets(assetPrefix)
179
187
  const srcDir = resolve(root, 'src')
@@ -188,7 +196,6 @@ export async function devServer(options: DevServerOptions): Promise<{
188
196
  const pluginWatchers: FSWatcher[] = []
189
197
  const graphWatchers = new Map<string, FSWatcher>()
190
198
  let activeAssetPrefix = assetPrefix
191
- let pluginWatchersAttached = false
192
199
 
193
200
  const isInsideDir = (parent: string, target: string): boolean =>
194
201
  target === parent || target.startsWith(`${parent}/`) || target.startsWith(`${parent}\\`)
@@ -344,18 +351,6 @@ export async function devServer(options: DevServerOptions): Promise<{
344
351
  await prevApp?.dispose?.()
345
352
  lastError = undefined
346
353
  syncBuildWatchers(buildCache.watchedFiles)
347
- if (!pluginWatchersAttached && !initialConfigFailed) {
348
- pluginWatchersAttached = true
349
- }
350
- else if (initialConfigFailed) {
351
- initialConfigFailed = false
352
- try {
353
- const recoveredCfg = await loadConfig(root)
354
- refreshPluginWatchers(recoveredCfg)
355
- pluginWatchersAttached = true
356
- }
357
- catch {}
358
- }
359
354
  if (n > 2)
360
355
  rmSync(join(devRoot, `b${n - 2}`), { recursive: true, force: true })
361
356
  console.log(`[kay dev] rebuilt in ${(performance.now() - t0).toFixed(1)} ms`)
@@ -549,10 +544,7 @@ export async function devServer(options: DevServerOptions): Promise<{
549
544
  server.stop(true)
550
545
  void currentApp?.dispose?.()
551
546
  rmSync(devRoot, { recursive: true, force: true })
552
- if (prevKayDev === undefined)
553
- delete process.env.KAY_DEV
554
- else
555
- process.env.KAY_DEV = prevKayDev
547
+ restoreKayDev()
556
548
  },
557
549
  }
558
550
  }
package/src/dom/extras.ts CHANGED
@@ -5,7 +5,7 @@ import type { Owner } from '../reactivity/index'
5
5
  import { DOM_PROPS } from '../attrs'
6
6
  import { batch, createOwner, disposeOwner, effect, getOwner, onCleanup, runWithOwner, untrack } from '../reactivity/index'
7
7
  import { assertRenderable } from '../unrenderable'
8
- import { claimInsert, isBlockedAttr, setAttr, setClass, setProp, setStyle, skipRange } from './index'
8
+ import { claimInsert, claimRange, isBlockedAttr, setAttr, setClass, setProp, setStyle, skipRange } from './index'
9
9
 
10
10
  const RAW_HTML = Symbol.for('kay.html')
11
11
 
@@ -147,6 +147,23 @@ export function spread(el: Element, getProps: () => Record<string, unknown> | nu
147
147
  })
148
148
  }
149
149
 
150
+ // Removes rendered nodes; an array is a run of siblings, removed whole with what inner inserts added between its ends since.
151
+ function clearRendered(current: Node | Node[] | null): void {
152
+ if (Array.isArray(current) && current.length > 1) {
153
+ const last = current[current.length - 1]!
154
+ let node: Node | null = current[0]!
155
+ if (last.parentNode !== null && node.parentNode === last.parentNode) {
156
+ while (node !== null) {
157
+ const next: Node | null = node === last ? null : node.nextSibling
158
+ node.parentNode!.removeChild(node)
159
+ node = next
160
+ }
161
+ return
162
+ }
163
+ }
164
+ clearInserted(current)
165
+ }
166
+
150
167
  function clearInserted(current: Node | Node[] | null): void {
151
168
  if (current === null)
152
169
  return
@@ -218,6 +235,8 @@ export function insert(parent: Node, value: () => unknown, marker: Node | null =
218
235
  }
219
236
  const next = res.result
220
237
  const ssrNodes = res.nodes
238
+ // An insert born in a fragment follows its marker into the parent the fragment was appended to.
239
+ const host = marker?.parentNode ?? parent
221
240
 
222
241
  if (next == null && ssrNodes !== undefined) {
223
242
  current = ssrNodes
@@ -225,7 +244,7 @@ export function insert(parent: Node, value: () => unknown, marker: Node | null =
225
244
  }
226
245
 
227
246
  if (next == null || typeof next === 'boolean') {
228
- clearInserted(current)
247
+ clearRendered(current)
229
248
  if (ssrNodes !== undefined)
230
249
  clearInserted(ssrNodes)
231
250
  current = null
@@ -237,7 +256,7 @@ export function insert(parent: Node, value: () => unknown, marker: Node | null =
237
256
  if (typeof next === 'string' || typeof next === 'number') {
238
257
  const str = String(next)
239
258
  if (current !== null) {
240
- clearInserted(current)
259
+ clearRendered(current)
241
260
  current = null
242
261
  }
243
262
  if (textNode === undefined) {
@@ -251,7 +270,7 @@ export function insert(parent: Node, value: () => unknown, marker: Node | null =
251
270
  if (ssrNodes !== undefined)
252
271
  clearInserted(ssrNodes)
253
272
  textNode = document.createTextNode(str)
254
- parent.insertBefore(textNode, marker)
273
+ host.insertBefore(textNode, marker)
255
274
  }
256
275
  }
257
276
  else if (textNode.data !== str) {
@@ -274,38 +293,51 @@ export function insert(parent: Node, value: () => unknown, marker: Node | null =
274
293
  if (next instanceof Node) {
275
294
  if (current === next)
276
295
  return
277
- if (current === null && next.parentNode === parent) {
296
+ if (current === null && next.parentNode === host) {
278
297
  if (ssrNodes !== undefined)
279
298
  clearInserted(ssrNodes.filter(n => n !== next))
280
299
  current = next
281
300
  return
282
301
  }
283
- clearInserted(current)
302
+ clearRendered(current)
284
303
  if (ssrNodes !== undefined)
285
304
  clearInserted(ssrNodes)
286
305
  if (next.nodeType === 11) {
287
306
  const nodes = Array.from(next.childNodes)
288
- parent.insertBefore(next, marker)
307
+ host.insertBefore(next, marker)
289
308
  current = nodes
290
309
  }
291
310
  else {
292
- parent.insertBefore(next, marker)
311
+ host.insertBefore(next, marker)
293
312
  current = next
294
313
  }
295
314
  return
296
315
  }
297
316
 
298
317
  if (Array.isArray(next)) {
299
- clearInserted(current)
318
+ clearRendered(current)
300
319
  if (ssrNodes !== undefined) {
301
320
  const kept = new Set(next)
302
321
  clearInserted(ssrNodes.filter(n => !kept.has(n)))
303
322
  }
304
- current = insertAll(parent, marker, next)
323
+ current = insertAll(host, marker, next)
305
324
  }
306
325
  })
307
326
  }
308
327
 
328
+ // A dynamic child of a root fragment: hydrates against its SSR range, or renders between two comments that travel with the fragment, so whoever removes the fragment's nodes removes what it renders later.
329
+ export function fragInsert(value: () => unknown): Node | null {
330
+ const start = claimRange()
331
+ if (start !== null) {
332
+ insert(start.parentNode!, value, skipRange(start), start)
333
+ return null
334
+ }
335
+ const f = document.createDocumentFragment()
336
+ f.appendChild(document.createComment(''))
337
+ insert(f, value, f.appendChild(document.createComment('')))
338
+ return f
339
+ }
340
+
309
341
  export function show(
310
342
  parent: Node,
311
343
  marker: Node | null,
@@ -324,8 +356,7 @@ export function show(
324
356
  disposeOwner(owner)
325
357
  owner = undefined
326
358
  }
327
- for (let i = 0; i < nodes.length; i++)
328
- nodes[i]!.parentNode?.removeChild(nodes[i]!)
359
+ clearRendered(nodes)
329
360
  nodes = []
330
361
  }
331
362
 
package/src/dom/index.ts CHANGED
@@ -1,4 +1,4 @@
1
- // Kay v2 minimal DOM & hydration core (loop -> kay/dom-loop, extras -> kay/dom-extras for fine-grained chunk splitting).
1
+ // Kay v2 minimal DOM & hydration core (loop -> @kayjs/kay/internal/dom-loop, extras -> @kayjs/kay/internal/dom-extras for fine-grained chunk splitting).
2
2
 
3
3
  import { isBlockedAttr, isStringBoolAttr, isUnsafeUrlAttr } from '../attrs'
4
4
  import { batch, createOwner, disposeOwner, runWithOwner } from '../reactivity/index'
@@ -188,6 +188,30 @@ export function template(html: string, isSvg?: boolean): () => Node {
188
188
  }
189
189
  }
190
190
 
191
+ // Moves the hydration cursor past the SSR range of a root fragment's dynamic child (`<!--k[-->...<!--k]-->` or `<!---->text<!---->`) and returns its opening marker; null when not hydrating.
192
+ export function claimRange(): Node | null {
193
+ const start = hydrating ? hydrateNode : null
194
+ if (start === null || start.nodeType !== 8)
195
+ return null
196
+ hydrateNode = skipRange(start)?.nextSibling ?? null
197
+ return start
198
+ }
199
+
200
+ // A text child of a root fragment, claimed from the SSR markup while hydrating; a dynamic one sits between `<!---->` markers.
201
+ export function fragText(data: string, dynamic?: boolean): Text {
202
+ if (dynamic) {
203
+ const start = claimRange()
204
+ if (start !== null)
205
+ return textAfter(start)
206
+ }
207
+ else if (hydrating && hydrateNode !== null && hydrateNode.nodeType === 3) {
208
+ const text = hydrateNode as Text
209
+ hydrateNode = text.nextSibling
210
+ return text
211
+ }
212
+ return document.createTextNode(data)
213
+ }
214
+
191
215
  export function frag(...nodes: Node[]): Node | null {
192
216
  if (hydrating)
193
217
  return null
package/src/index.ts CHANGED
@@ -20,16 +20,3 @@ export type { ActionForm, ClientAction, UseActionOptions } from './dom/action'
20
20
  export type { Component, Html, HydrateStrategy, KayChild } from './jsx-runtime'
21
21
  export type { ExtractRouteParams, KayLocals, LayoutProps, LoaderData, LoaderFn, NotFoundResult, PageProps, RouteContext } from './server/index'
22
22
 
23
- import type { Component, HydrateStrategy } from './jsx-runtime'
24
-
25
- export interface IslandOptions {
26
- hydrate?: HydrateStrategy | undefined
27
- }
28
-
29
- /** Optional component-level hydration metadata helper. */
30
- export function island<P>(component: Component<P>, options: IslandOptions = {}): Component<P> & { $hydrate?: HydrateStrategy } {
31
- const tagged = component as Component<P> & { $hydrate?: HydrateStrategy }
32
- if (options.hydrate !== undefined)
33
- tagged.$hydrate = options.hydrate
34
- return tagged
35
- }
@@ -509,7 +509,7 @@ export namespace JSX {
509
509
  export interface ElementChildrenAttribute {
510
510
  children: object
511
511
  }
512
- /** Augment this interface via `declare module 'kay/jsx-runtime'` to register custom elements (`<my-widget>`). */
512
+ /** Augment this interface via `declare module '@kayjs/kay/jsx-runtime'` to register custom elements (`<my-widget>`). */
513
513
  export interface CustomElements {}
514
514
  export interface IntrinsicElements extends HtmlIntrinsicElements, SvgIntrinsicElements, CustomElements {}
515
515
  }
@@ -1,5 +1,6 @@
1
1
  // Per-build / per-server scoped runtime context (AsyncLocalStorage-backed, zero mutable process globals).
2
2
 
3
+ import type { ServiceKey } from './services'
3
4
  import { AsyncLocalStorage } from 'node:async_hooks'
4
5
 
5
6
  export interface AppRuntimeContext {
@@ -9,8 +10,8 @@ export interface AppRuntimeContext {
9
10
  readonly assetPrefix: string
10
11
  readonly site?: string | undefined
11
12
  readonly dev: boolean
12
- provide<T>(key: string, value: T): void
13
- inject<T>(key: string): T | undefined
13
+ provide<T>(key: ServiceKey<T>, value: T): void
14
+ inject<T>(key: ServiceKey<T>): T | undefined
14
15
  registerPublicFile(relPath: string): void
15
16
  }
16
17
 
@@ -40,11 +41,12 @@ export function createAppContext(options: CreateAppContextOptions): AppRuntimeCo
40
41
  assetPrefix: options.assetPrefix,
41
42
  ...(site !== undefined && site !== '' ? { site } : {}),
42
43
  dev: options.dev,
43
- provide<T>(key: string, value: T): void {
44
- services.set(key, value)
44
+ // Keyed by name: the natively loaded config and the bundled app each hold their own key object.
45
+ provide<T>(key: ServiceKey<T>, value: T): void {
46
+ services.set(key.name, value)
45
47
  },
46
- inject<T>(key: string): T | undefined {
47
- return services.get(key) as T | undefined
48
+ inject<T>(key: ServiceKey<T>): T | undefined {
49
+ return services.get(key.name) as T | undefined
48
50
  },
49
51
  registerPublicFile(relPath: string): void {
50
52
  options.onRegisterPublicFile?.(relPath)
@@ -7,6 +7,6 @@ export { createAppContext, getAppContext, runWithAppContext } from './context'
7
7
  export type { AppRuntimeContext, CreateAppContextOptions } from './context'
8
8
  export { loadConfig } from './load'
9
9
  export { resolvePlugins } from './order'
10
- export { CONTENT_IMAGE_RESOLVER_SERVICE, I18N_CONFIG_SERVICE } from './services'
11
- export type { ActiveI18nConfig, ContentImageResolver, ContentImageResult } from './services'
10
+ export { CONTENT_IMAGE_RESOLVER_SERVICE, I18N_CONFIG_SERVICE, serviceKey } from './services'
11
+ export type { ActiveI18nConfig, ContentImageResolver, ContentImageResult, ServiceKey } from './services'
12
12
  export type { BuildPluginContext, BuildPluginTarget, CheckPluginContext, DocumentHeadContext, FinalizeBuildContext, KayConfig, KayPlugin, MiddlewareOptions, PluginRouteOptions, ServerErrorInfo, ServerPluginAPI, ServerRuntimeConfig } from './types'
@@ -3,7 +3,7 @@
3
3
  import type { AppRuntimeContext } from './context'
4
4
  import type { KayConfig } from './types'
5
5
  import { existsSync, readFileSync } from 'node:fs'
6
- import { join, resolve } from 'node:path'
6
+ import { join, relative, resolve } from 'node:path'
7
7
  import { createAppContext, getAppContext, runWithAppContext } from './context'
8
8
 
9
9
  let configReloadSeq = 0
@@ -33,6 +33,29 @@ export async function loadConfig(root: string, options?: { fresh?: boolean, appC
33
33
  assetPrefix: '/_kay',
34
34
  dev: process.env.KAY_DEV === '1',
35
35
  })
36
- const mod = await runWithAppContext(ctx, () => import(spec)) as { default?: KayConfig }
36
+ let mod: { default?: KayConfig }
37
+ try {
38
+ mod = await runWithAppContext(ctx, () => import(spec)) as { default?: KayConfig }
39
+ }
40
+ catch (error) {
41
+ // Several syntax errors arrive together; the first one names the line to fix.
42
+ const first: unknown = (error as AggregateError).errors?.[0] ?? error
43
+ throw new Error(`kay: ${configErrorLocation(first, configPath, absRoot)}: ${first instanceof Error ? first.message : String(first)}`, { cause: error })
44
+ }
37
45
  return mod.default ?? {}
38
46
  }
47
+
48
+ const STACK_LOCATION_RE = /:(\d+):(\d+)\)?$/
49
+
50
+ // Where a config failed: the syntax error's position, else the config's own frame in the stack, which names the line calling a throwing plugin factory.
51
+ function configErrorLocation(error: unknown, configPath: string, root: string): string {
52
+ const position = (error as { position?: { file?: string, line: number, column: number } }).position
53
+ if (position?.file !== undefined)
54
+ return `${relative(root, position.file)}:${position.line}:${position.column}`
55
+ for (const frame of String((error as Error).stack ?? '').split('\n')) {
56
+ const match = frame.includes(configPath) ? STACK_LOCATION_RE.exec(frame) : null
57
+ if (match !== null)
58
+ return `kay.config.ts:${match[1]}:${match[2]}`
59
+ }
60
+ return 'kay.config.ts'
61
+ }
@@ -0,0 +1,6 @@
1
+ // `@kayjs/kay/config`: what `kay.config.ts` and plugin packages use.
2
+
3
+ export { defineConfig, definePlugin } from './config'
4
+ export { CONTENT_IMAGE_RESOLVER_SERVICE, I18N_CONFIG_SERVICE, serviceKey } from './services'
5
+ export type { ActiveI18nConfig, ContentImageResolver, ContentImageResult, ServiceKey } from './services'
6
+ export type { BuildPluginContext, BuildPluginTarget, CheckPluginContext, DocumentHeadContext, FinalizeBuildContext, KayConfig, KayPlugin, MiddlewareOptions, PluginRouteOptions, ServerErrorInfo, ServerPluginAPI, ServerRuntimeConfig } from './types'
@@ -1,4 +1,16 @@
1
- // Service keys shared between two plugins, kept in core as contracts so neither plugin depends on the other.
1
+ // Service keys: `serviceKey` for any plugin, and the keys shared between two plugins, kept in core as contracts so neither depends on the other.
2
+
3
+ declare const SERVICE_TYPE: unique symbol
4
+
5
+ /** Names a service and the type of its value; `provide` and `inject` take one instead of a string. */
6
+ export interface ServiceKey<T> {
7
+ readonly name: string
8
+ readonly [SERVICE_TYPE]?: T
9
+ }
10
+
11
+ export function serviceKey<T>(name: string): ServiceKey<T> {
12
+ return { name }
13
+ }
2
14
 
3
15
  export interface ActiveI18nConfig {
4
16
  readonly locales: readonly string[]
@@ -6,7 +18,7 @@ export interface ActiveI18nConfig {
6
18
  readonly prefixDefault: boolean
7
19
  }
8
20
 
9
- export const I18N_CONFIG_SERVICE = 'kay.i18n.config'
21
+ export const I18N_CONFIG_SERVICE = serviceKey<ActiveI18nConfig>('kay.i18n.config')
10
22
 
11
23
  export interface ContentImageResult {
12
24
  src: string
@@ -20,4 +32,4 @@ export interface ContentImageResult {
20
32
 
21
33
  export type ContentImageResolver = (src: string, file: string | undefined) => ContentImageResult | string | undefined
22
34
 
23
- export const CONTENT_IMAGE_RESOLVER_SERVICE = 'kay.content.imageResolver'
35
+ export const CONTENT_IMAGE_RESOLVER_SERVICE = serviceKey<ContentImageResolver>('kay.content.imageResolver')
@@ -2,9 +2,9 @@
2
2
 
3
3
  import type { BunPlugin } from 'bun'
4
4
  import type { RouteManifestEntry } from '../build/index'
5
- import type { ActionResult, ServerAction } from '../server/action'
6
5
  import type { Middleware, RequestContext } from '../server/index'
7
6
  import type { SecurityHeadersOptions, TrustProxy } from '../server/security'
7
+ import type { ServiceKey } from './services'
8
8
 
9
9
  export type BuildPluginTarget = 'client' | 'server' | 'compile'
10
10
 
@@ -30,9 +30,9 @@ export interface BuildPluginContext {
30
30
  /** Add raw HTML to <head> on a specific route path only. */
31
31
  addRouteHead(routePath: string, html: string): void
32
32
  /** Register an explicit build-scoped service for other plugins or render-time helpers. */
33
- provide<T>(key: string, value: T): void
33
+ provide<T>(key: ServiceKey<T>, value: T): void
34
34
  /** Look up a build-scoped service registered by another plugin. */
35
- inject<T>(key: string): T | undefined
35
+ inject<T>(key: ServiceKey<T>): T | undefined
36
36
  /** Persist JSON-serializable build data into `manifest.pluginData[plugin.name]` for cold-start servers and `--compile`. */
37
37
  setData(data: Record<string, unknown>): void
38
38
  }
@@ -54,9 +54,9 @@ export interface FinalizeBuildContext {
54
54
  /** Emit a static file into dist/public/<relPath> served at `/<relPath>` (included in `--static` and `--compile`). */
55
55
  emitPublic(relPath: string, content: string | Uint8Array): string
56
56
  /** Register a build-scoped service. */
57
- provide<T>(key: string, value: T): void
57
+ provide<T>(key: ServiceKey<T>, value: T): void
58
58
  /** Look up a build-scoped service. */
59
- inject<T>(key: string): T | undefined
59
+ inject<T>(key: ServiceKey<T>): T | undefined
60
60
  /** Merge/persist JSON-serializable build data into `manifest.pluginData[plugin.name]`. */
61
61
  setData(data: Record<string, unknown>): void
62
62
  }
@@ -100,15 +100,13 @@ export interface ServerPluginAPI {
100
100
  /** Rewrite an incoming pathname before route matching (e.g. strip /fr locale prefix). */
101
101
  rewrite(fn: (pathname: string, ctx: RequestContext) => string | undefined): void
102
102
  /** Register a server-scoped service for other plugins or render-time helpers (isolated per server instance). */
103
- provide<T>(key: string, value: T): void
103
+ provide<T>(key: ServiceKey<T>, value: T): void
104
104
  /** Look up a server-scoped service registered by another plugin. */
105
- inject<T>(key: string): T | undefined
105
+ inject<T>(key: ServiceKey<T>): T | undefined
106
106
  /** Read persisted build data from `manifest.pluginData` (defaults to the current plugin's name). */
107
107
  getBuildData<T = Record<string, unknown>>(pluginName?: string): T | undefined
108
108
  /** Register a shutdown cleanup callback run when `app.dispose()` is called (dev reloads, tests, graceful exit). */
109
109
  onShutdown(fn: () => void | Promise<void>): void
110
- /** Invoke a ServerAction with Standard Schema validation and directory-scoped `_middleware.ts` checks. */
111
- invokeAction<I, O>(action: ServerAction<I, O>, input: I, ctx: RequestContext): Promise<ActionResult<O>>
112
110
  }
113
111
 
114
112
  export interface ServerErrorInfo {
@@ -142,8 +140,6 @@ export interface KayPlugin {
142
140
  readsLocals?: readonly string[] | undefined
143
141
  /** Register server routes, global middleware, URL rewrites, or runtime services. */
144
142
  server?: (api: ServerPluginAPI) => void | Promise<void>
145
- /** Optional cleanup hook called when a server instance is disposed (dev reloads, tests, graceful shutdown). */
146
- dispose?: () => void | Promise<void>
147
143
  /** Error hook called whenever a route, action, or plugin handler throws an unhandled error. */
148
144
  onError?: (info: ServerErrorInfo) => void
149
145
  /** Build hook run after route compilation, before prerender / --static / --compile. */