@kayjs/kay 2.0.0-alpha.6 → 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.
@@ -195,8 +195,16 @@ function rewriteFreeIdentifiers(
195
195
  visit(attr, shadowed)
196
196
  return
197
197
  }
198
+ case 'TSAsExpression':
199
+ case 'TSNonNullExpression':
200
+ case 'TSSatisfiesExpression':
201
+ case 'TSTypeAssertion':
202
+ case 'TSInstantiationExpression': {
203
+ visit(node.expression, shadowed)
204
+ return
205
+ }
198
206
  default: {
199
- // Skip TypeScript type nodes
207
+ // Skip pure TypeScript type annotation nodes
200
208
  if (typeof node.type === 'string' && node.type.startsWith('TS'))
201
209
  return
202
210
  for (const key of Object.keys(node)) {
@@ -247,48 +255,152 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
247
255
  }
248
256
  }
249
257
 
250
- function compileExpression(node: AstNode, scopeRewrites: ReadonlyMap<string, string>): string {
251
- let hasNestedJsx = false
258
+ function hasJsxDescendant(node: AstNode | null | undefined): boolean {
259
+ if (!node)
260
+ return false
261
+ let found = false
252
262
  walk(node, (child) => {
253
263
  if (child.type === 'JSXElement' || child.type === 'JSXFragment') {
254
- hasNestedJsx = true
264
+ found = true
255
265
  return false
256
266
  }
257
267
  return undefined
258
268
  })
259
- if (!hasNestedJsx)
260
- return rewriteFreeIdentifiers(code, node, scopeRewrites)
261
-
262
- // Replace nested JSX roots inside this expression
263
- const subCode = code.slice(node.start, node.end)
264
- const offset = node.start as number
265
- const sub = new SourceEditor(subCode)
269
+ return found
270
+ }
266
271
 
267
- walk(node, (child) => {
268
- if (child.type === 'JSXElement' || child.type === 'JSXFragment') {
269
- sub.replace(child.start - offset, child.end - offset, compileRootJsx(child, scopeRewrites))
272
+ function extractBlockKeyExpr(block: AstNode): AstNode | undefined {
273
+ let found: AstNode | undefined
274
+ walk(block, (child) => {
275
+ if (found !== undefined)
270
276
  return false
277
+ if (child.type === 'ArrowFunctionExpression' || child.type === 'FunctionExpression' || child.type === 'FunctionDeclaration')
278
+ return false
279
+ if (child.type === 'ReturnStatement' && child.argument) {
280
+ const arg = unwrapParens(child.argument as AstNode)
281
+ const k = extractKeyExpr(arg)
282
+ if (k !== undefined) {
283
+ found = k
284
+ return false
285
+ }
271
286
  }
272
287
  return undefined
273
288
  })
289
+ return found
290
+ }
274
291
 
275
- // Also rewrite non-JSX free identifiers by applying identifier rewrites on non-JSX spans
276
- if (scopeRewrites.size === 0)
277
- return sub.toString()
278
-
279
- // Re-parse isn't needed: rewrite free identifiers cleanly on leaf expressions inside compileRootJsx,
280
- // and for outer expressions around JSX (e.g. `cond ? <A/> : <B/>`), compile directly:
281
- if (node.type === 'ConditionalExpression') {
282
- const test = compileExpression(node.test, scopeRewrites)
283
- const cons = compileExpression(node.consequent, scopeRewrites)
284
- const alt = compileExpression(node.alternate, scopeRewrites)
285
- return `(${test} ? ${cons} : ${alt})`
286
- }
287
- if (node.type === 'LogicalExpression') {
288
- const left = compileExpression(node.left, scopeRewrites)
289
- const right = compileExpression(node.right, scopeRewrites)
290
- return `(${left} ${node.operator} ${right})`
292
+ function compileExpression(node: AstNode, scopeRewrites: ReadonlyMap<string, string>): string {
293
+ if (!hasJsxDescendant(node))
294
+ return rewriteFreeIdentifiers(code, node, scopeRewrites)
295
+
296
+ // Replace nested JSX roots AND rewrite free identifiers in all surrounding non-JSX spans (respecting shadowing)
297
+ const offset = node.start as number
298
+ const sub = new SourceEditor(code.slice(node.start, node.end))
299
+
300
+ function visitExpr(cur: AstNode | null | undefined, shadowed: Set<string>): void {
301
+ if (!cur || typeof cur !== 'object')
302
+ return
303
+
304
+ if (cur.type === 'JSXElement' || cur.type === 'JSXFragment') {
305
+ const activeRewrites = shadowed.size === 0
306
+ ? scopeRewrites
307
+ : new Map([...scopeRewrites].filter(([k]) => !shadowed.has(k)))
308
+ sub.replace(cur.start - offset, cur.end - offset, compileRootJsx(cur, activeRewrites))
309
+ return
310
+ }
311
+
312
+ switch (cur.type) {
313
+ case 'Identifier': {
314
+ const name = cur.name as string
315
+ if (!shadowed.has(name)) {
316
+ const rep = scopeRewrites.get(name)
317
+ if (rep !== undefined)
318
+ sub.replace(cur.start - offset, cur.end - offset, rep)
319
+ }
320
+ return
321
+ }
322
+ case 'MemberExpression': {
323
+ visitExpr(cur.object, shadowed)
324
+ if (cur.computed)
325
+ visitExpr(cur.property, shadowed)
326
+ return
327
+ }
328
+ case 'Property': {
329
+ if (cur.computed)
330
+ visitExpr(cur.key, shadowed)
331
+ if (cur.shorthand && cur.value?.type === 'Identifier') {
332
+ const name = cur.value.name as string
333
+ if (!shadowed.has(name) && scopeRewrites.has(name)) {
334
+ sub.replace(cur.start - offset, cur.end - offset, `${name}: ${scopeRewrites.get(name)}`)
335
+ return
336
+ }
337
+ }
338
+ visitExpr(cur.value, shadowed)
339
+ return
340
+ }
341
+ case 'ArrowFunctionExpression':
342
+ case 'FunctionExpression':
343
+ case 'FunctionDeclaration': {
344
+ const nextShadow = new Set(shadowed)
345
+ if (cur.id?.name)
346
+ nextShadow.add(cur.id.name as string)
347
+ for (const p of cur.params as AstNode[])
348
+ collectPatternNames(p, nextShadow)
349
+ visitExpr(cur.body, nextShadow)
350
+ return
351
+ }
352
+ case 'BlockStatement': {
353
+ const nextShadow = new Set(shadowed)
354
+ for (const stmt of cur.body as AstNode[]) {
355
+ if (stmt.type === 'VariableDeclaration') {
356
+ for (const d of stmt.declarations as AstNode[]) {
357
+ visitExpr(d.init, nextShadow)
358
+ collectPatternNames(d.id, nextShadow)
359
+ }
360
+ }
361
+ else if (stmt.type === 'FunctionDeclaration') {
362
+ if (stmt.id?.name)
363
+ nextShadow.add(stmt.id.name as string)
364
+ visitExpr(stmt, nextShadow)
365
+ }
366
+ else {
367
+ visitExpr(stmt, nextShadow)
368
+ }
369
+ }
370
+ return
371
+ }
372
+ case 'VariableDeclarator': {
373
+ visitExpr(cur.init, shadowed)
374
+ return
375
+ }
376
+ case 'TSAsExpression':
377
+ case 'TSNonNullExpression':
378
+ case 'TSSatisfiesExpression':
379
+ case 'TSTypeAssertion':
380
+ case 'TSInstantiationExpression': {
381
+ visitExpr(cur.expression, shadowed)
382
+ return
383
+ }
384
+ default: {
385
+ if (typeof cur.type === 'string' && cur.type.startsWith('TS'))
386
+ return
387
+ for (const key of Object.keys(cur)) {
388
+ if (key === 'start' || key === 'end' || key === 'type')
389
+ continue
390
+ const val = cur[key]
391
+ if (Array.isArray(val)) {
392
+ for (let i = 0; i < val.length; i++)
393
+ visitExpr(val[i] as AstNode, shadowed)
394
+ }
395
+ else if (val !== null && typeof val === 'object') {
396
+ visitExpr(val as AstNode, shadowed)
397
+ }
398
+ }
399
+ }
400
+ }
291
401
  }
402
+
403
+ visitExpr(node, new Set())
292
404
  return sub.toString()
293
405
  }
294
406
 
@@ -563,7 +675,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
563
675
  if (child.type === 'JSXExpressionContainer') {
564
676
  const expr = child.expression as AstNode
565
677
 
566
- // Case 1: Keyed `.map((item, idx?) => <jsx>)` → `__loop(...)`
678
+ // Case 1: Keyed `.map((item, idx?) => <jsx> | { ... return <jsx> })` → `__loop(...)`
567
679
  if (
568
680
  expr.type === 'CallExpression'
569
681
  && expr.callee?.type === 'MemberExpression'
@@ -573,9 +685,11 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
573
685
  ) {
574
686
  const cb = expr.arguments[0] as AstNode
575
687
  const cbBody = cb.body?.type === 'ParenthesizedExpression' ? cb.body.expression : cb.body
688
+ const isJsxBody = cbBody?.type === 'JSXElement' || cbBody?.type === 'JSXFragment'
689
+ const isBlockJsxBody = cbBody?.type === 'BlockStatement' && hasJsxDescendant(cbBody)
576
690
  if (
577
691
  (cb.type === 'ArrowFunctionExpression' || cb.type === 'FunctionExpression')
578
- && (cbBody?.type === 'JSXElement' || cbBody?.type === 'JSXFragment')
692
+ && (isJsxBody || isBlockJsxBody)
579
693
  ) {
580
694
  const loopSkip = domIndex
581
695
  const anchorVar = isLast ? 'null' : requestChild(elVar, domIndex)
@@ -601,12 +715,12 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
601
715
  for (const n of names)
602
716
  shadowed.delete(n)
603
717
  }
604
- const rowBody = compileRootJsx(cbBody, shadowed)
718
+ const rowBody = isJsxBody ? compileRootJsx(cbBody, shadowed) : compileExpression(cbBody, shadowed)
605
719
  ops.push(`${use('eachStatic')}(${elVar}, ${anchorVar}, ${eachCode}, (${rawParams}) => ${rowBody}${skipArg});`)
606
720
  continue
607
721
  }
608
722
 
609
- const keyAst = extractKeyExpr(cbBody)
723
+ const keyAst = isJsxBody ? extractKeyExpr(cbBody) : extractBlockKeyExpr(cbBody)
610
724
 
611
725
  const rowSig = freshVar('_r')
612
726
  const idxSig = idxParam !== undefined ? freshVar('_i') : undefined
@@ -649,7 +763,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
649
763
  if (idxParam !== undefined && idxSig !== undefined)
650
764
  rowRewrites.set(idxParam, `${idxSig}.value`)
651
765
 
652
- const rowBody = compileRootJsx(cbBody, rowRewrites)
766
+ const rowBody = isJsxBody ? compileRootJsx(cbBody, rowRewrites) : compileExpression(cbBody, rowRewrites)
653
767
  const rowParams = idxSig !== undefined ? `${rowSig}, ${idxSig}` : rowSig
654
768
  ops.push(`${use('loop')}(${elVar}, ${anchorVar}, () => ${eachCode}, ${keyFn}, (${rowParams}) => ${rowBody}${skipArg});`)
655
769
  continue
@@ -694,11 +808,11 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
694
808
  }
695
809
  }
696
810
 
697
- // Case 4: Dynamic children slot / Node insertion (`{children}` / `{props.children}`)
811
+ // Case 4: Dynamic children slot / Node insertion (`{children}`, `{props.children}`, or any expression containing JSX)
698
812
  const isChildrenExpr = (expr.type === 'Identifier' && expr.name === 'children')
699
813
  || (expr.type === 'MemberExpression' && !expr.computed && expr.property?.name === 'children')
700
814
  const exprCode = compileExpression(expr, scopeRewrites)
701
- if (isChildrenExpr) {
815
+ if (isChildrenExpr || hasJsxDescendant(expr)) {
702
816
  const anchorVar = isLast ? 'null' : requestChild(elVar, domIndex)
703
817
  if (!isLast) {
704
818
  html += '<!---->'
@@ -887,30 +1001,25 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
887
1001
  }
888
1002
  return undefined
889
1003
  })
890
- if (!stmtHasJsx) {
891
- const active = new Map<string, string>()
892
- for (const [k, v] of propRewrites) {
893
- if (!shadowed.has(k))
894
- active.set(k, v)
895
- }
896
- if (active.size > 0)
897
- editor.replace(stmt.start, stmt.end, rewriteFreeIdentifiers(code, stmt, active))
898
- }
899
- else {
900
- walk(stmt, (child) => {
901
- if (child.type === 'JSXElement' || child.type === 'JSXFragment') {
902
- editor.replace(child.start, child.end, compileRootJsx(child, propRewrites))
903
- return false
904
- }
905
- return undefined
906
- })
1004
+ const active = new Map<string, string>()
1005
+ for (const [k, v] of propRewrites) {
1006
+ if (!shadowed.has(k))
1007
+ active.set(k, v)
907
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))
908
1014
  if (stmt.type === 'VariableDeclaration') {
909
1015
  for (const d of stmt.declarations as AstNode[])
910
1016
  collectPatternNames(d.id, shadowed)
911
1017
  }
912
1018
  }
913
1019
  }
1020
+ else if (propRewrites.size > 0) {
1021
+ editor.replace(fn.body.start, fn.body.end, compileExpression(fn.body, propRewrites))
1022
+ }
914
1023
  else {
915
1024
  walk(fn.body, (child) => {
916
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
+ }
@@ -388,7 +388,22 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
388
388
  if (body.type === 'JSXElement' || body.type === 'JSXFragment') {
389
389
  const target = compileSubExpression(expr.callee.object)
390
390
  const params = (cb.params as AstNode[]).map(p => code.slice(p.start, p.end)).join(', ')
391
- return `${use('ssrLoop')}(${target}, (${params}) => ${compileJsxToStringExpr(body)})`
391
+ const rendered = `${use('ssrLoop')}(${target}, (${params}) => ${compileJsxToStringExpr(body)})`
392
+ return isIsland && !isLast ? `(${rendered}) + "<!---->"` : rendered
393
+ }
394
+ if (body.type === 'BlockStatement') {
395
+ let blockHasJsx = false
396
+ walk(body, (c) => {
397
+ if (c.type === 'JSXElement' || c.type === 'JSXFragment') {
398
+ blockHasJsx = true
399
+ return false
400
+ }
401
+ return undefined
402
+ })
403
+ if (blockHasJsx) {
404
+ const rendered = `${use('esc')}(${compileSubExpression(expr)})`
405
+ return isIsland && !isLast ? `(${rendered}) + "<!---->"` : rendered
406
+ }
392
407
  }
393
408
  }
394
409
  }
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 {
@@ -45,10 +45,18 @@ export interface ServerPluginAPI {
45
45
  rewrite(fn: (pathname: string, ctx: RequestContext) => string | undefined): void
46
46
  }
47
47
 
48
+ export interface ServerErrorInfo {
49
+ error: unknown
50
+ request: Request
51
+ source: 'route' | 'action' | 'plugin'
52
+ }
53
+
48
54
  export interface KayPlugin {
49
55
  name: string
50
56
  /** Register server routes, global middleware, or URL rewrites. */
51
57
  server?: (api: ServerPluginAPI) => void | Promise<void>
58
+ /** Error hook called whenever a route, action, or plugin handler throws an unhandled error. */
59
+ onError?: (info: ServerErrorInfo) => void
52
60
  /** Build hook run after route compilation, before prerender / --static / --compile. */
53
61
  build?: (ctx: BuildPluginContext) => void | Promise<void>
54
62
  /** Code transform run during client & server compilation. */
@@ -73,6 +81,7 @@ export interface KayPlugin {
73
81
 
74
82
  export interface KayConfig {
75
83
  lang?: string | undefined
84
+ port?: number | undefined
76
85
  routesDir?: string | undefined
77
86
  outDir?: string | undefined
78
87
  publicDir?: string | undefined
@@ -80,6 +89,7 @@ export interface KayConfig {
80
89
  security?: SecurityHeadersOptions | false | undefined
81
90
  trustedOrigins?: string[] | undefined
82
91
  compress?: boolean | undefined
92
+ onError?: ((info: ServerErrorInfo) => void) | undefined
83
93
  plugins?: KayPlugin[] | undefined
84
94
  }
85
95