@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
@@ -0,0 +1,39 @@
1
+ // The generic oxc AST walk every compiler pass shares, kept apart from the analyzer so the passes it calls can import it without a cycle.
2
+
3
+ import type { Node } from 'oxc-parser'
4
+ import { visitorKeys } from 'oxc-parser'
5
+
6
+ export type AstNode = Node
7
+
8
+ /** Visits `node` and its children depth first; a visitor returning `false` skips the children of that node. */
9
+ export function walk(node: unknown, visit: (node: Node) => boolean | void): void {
10
+ if (node === null || typeof node !== 'object')
11
+ return
12
+ if (Array.isArray(node)) {
13
+ for (let i = 0; i < node.length; i++)
14
+ walk(node[i], visit)
15
+ return
16
+ }
17
+ const ast = node as Node
18
+ const type = ast.type
19
+ if (typeof type !== 'string')
20
+ return
21
+ if (visit(ast) === false)
22
+ return
23
+ const keys = visitorKeys[type]
24
+ if (keys !== undefined) {
25
+ const rec = ast as unknown as Record<string, unknown>
26
+ for (let i = 0; i < keys.length; i++) {
27
+ const val = rec[keys[i]!]
28
+ if (val !== null && typeof val === 'object')
29
+ walk(val, visit)
30
+ }
31
+ return
32
+ }
33
+ for (const [key, val] of Object.entries(ast)) {
34
+ if (key === 'start' || key === 'end' || key === 'type')
35
+ continue
36
+ if (val !== null && typeof val === 'object')
37
+ walk(val, visit)
38
+ }
39
+ }
@@ -0,0 +1,233 @@
1
+ // Which top-level keys of `props.data` a page island reads, so the server sends only those.
2
+
3
+ import type { ArrowFunctionExpression, Function as OxcFunction, Node, Program } from 'oxc-parser'
4
+ import { visitorKeys } from 'oxc-parser'
5
+ import { walk } from './ast'
6
+ import { unwrapTsExpr } from './shared'
7
+ function staticPropKey(prop: Node): string | undefined {
8
+ if (prop.type !== 'Property')
9
+ return undefined
10
+ if (!prop.computed && prop.key.type === 'Identifier')
11
+ return prop.key.name
12
+ if (prop.key.type === 'Literal' && typeof prop.key.value === 'string')
13
+ return prop.key.value
14
+ return undefined
15
+ }
16
+
17
+ function extractObjectPatternKeys(pat: Node): string[] | undefined {
18
+ if (pat.type !== 'ObjectPattern')
19
+ return undefined
20
+ const keys: string[] = []
21
+ for (const prop of pat.properties) {
22
+ if (prop.type === 'RestElement')
23
+ return undefined
24
+ const k = staticPropKey(prop)
25
+ if (k === undefined)
26
+ return undefined
27
+ keys.push(k)
28
+ }
29
+ return keys
30
+ }
31
+
32
+ function memberKeyName(node: Node): string | undefined {
33
+ if (node.type !== 'MemberExpression')
34
+ return undefined
35
+ if (!node.computed && node.property.type === 'Identifier')
36
+ return node.property.name
37
+ if (node.computed && node.property.type === 'Literal' && typeof node.property.value === 'string')
38
+ return node.property.value
39
+ return undefined
40
+ }
41
+
42
+ function unwrapParamPattern(param: Node): Node {
43
+ return param.type === 'AssignmentPattern' ? param.left : param
44
+ }
45
+
46
+ function resolveDefaultFunction(
47
+ program: Program,
48
+ defaultLocal: string | undefined,
49
+ localInits: ReadonlyMap<string, Node>,
50
+ ): OxcFunction | ArrowFunctionExpression | undefined {
51
+ const localFns = new Map<string, OxcFunction>()
52
+ for (const stmt of program.body) {
53
+ if (stmt.type === 'FunctionDeclaration' && stmt.id !== null)
54
+ localFns.set(stmt.id.name, stmt)
55
+ else if (stmt.type === 'ExportNamedDeclaration' && stmt.declaration?.type === 'FunctionDeclaration' && stmt.declaration.id !== null)
56
+ localFns.set(stmt.declaration.id.name, stmt.declaration)
57
+ }
58
+
59
+ const unwrapTarget = (node: Node | undefined, depth = 0): OxcFunction | ArrowFunctionExpression | undefined => {
60
+ if (node === undefined || depth > 4)
61
+ return undefined
62
+ const inner = unwrapTsExpr(node)
63
+ if (inner.type === 'FunctionDeclaration' || inner.type === 'FunctionExpression' || inner.type === 'ArrowFunctionExpression')
64
+ return inner
65
+ if (inner.type === 'Identifier')
66
+ return localFns.get(inner.name) ?? unwrapTarget(localInits.get(inner.name), depth + 1)
67
+ return undefined
68
+ }
69
+
70
+ for (const stmt of program.body) {
71
+ if (stmt.type === 'ExportDefaultDeclaration')
72
+ return unwrapTarget(stmt.declaration)
73
+ }
74
+ if (defaultLocal !== undefined)
75
+ return localFns.get(defaultLocal) ?? unwrapTarget(localInits.get(defaultLocal))
76
+ return undefined
77
+ }
78
+
79
+ /** Statically bounds which top-level keys of `props.data` a page island reads; returns `undefined` if `data` escapes. */
80
+ export function analyzeDefaultDataKeys(
81
+ program: Program,
82
+ defaultLocal: string | undefined,
83
+ localInits: ReadonlyMap<string, Node>,
84
+ ): string[] | undefined {
85
+ const fn = resolveDefaultFunction(program, defaultLocal, localInits)
86
+ if (fn === undefined || fn.body === null)
87
+ return undefined
88
+ if (fn.params.length === 0)
89
+ return []
90
+
91
+ const firstParam = unwrapParamPattern(fn.params[0]!)
92
+ const keys = new Set<string>()
93
+ let escaped = false
94
+ let dataVar: string | undefined
95
+ let propsVar: string | undefined
96
+
97
+ if (firstParam.type === 'ObjectPattern') {
98
+ let dataProp: Node | undefined
99
+ for (const prop of firstParam.properties) {
100
+ if (prop.type === 'RestElement')
101
+ return undefined
102
+ if (staticPropKey(prop) === 'data')
103
+ dataProp = prop
104
+ }
105
+ if (dataProp === undefined || dataProp.type !== 'Property')
106
+ return []
107
+ const binding = unwrapParamPattern(dataProp.value)
108
+ if (binding.type === 'ObjectPattern') {
109
+ const nested = extractObjectPatternKeys(binding)
110
+ if (nested === undefined)
111
+ return undefined
112
+ return [...new Set(nested)].sort()
113
+ }
114
+ if (binding.type !== 'Identifier')
115
+ return undefined
116
+ dataVar = binding.name
117
+ }
118
+ else if (firstParam.type === 'Identifier') {
119
+ propsVar = firstParam.name
120
+ }
121
+ else {
122
+ return undefined
123
+ }
124
+
125
+ // Walk the function body tracking parent chains so every reference to `dataVar` or `propsVar` is verified.
126
+ const ancestors: Node[] = []
127
+ const walkWithParents = (node: unknown): void => {
128
+ if (escaped || node === null || typeof node !== 'object')
129
+ return
130
+ if (Array.isArray(node)) {
131
+ for (let i = 0; i < node.length; i++)
132
+ walkWithParents(node[i])
133
+ return
134
+ }
135
+ const ast = node as Node
136
+ const type = ast.type
137
+ if (typeof type !== 'string')
138
+ return
139
+
140
+ // Respect inner function parameters that shadow `dataVar` or `propsVar`.
141
+ if (ast !== fn && (type === 'FunctionDeclaration' || type === 'FunctionExpression' || type === 'ArrowFunctionExpression')) {
142
+ const shadowed = new Set<string>()
143
+ for (const p of (ast as OxcFunction).params) {
144
+ walk(p, (pn) => {
145
+ if (pn.type === 'Identifier')
146
+ shadowed.add(pn.name)
147
+ })
148
+ }
149
+ if ((dataVar !== undefined && shadowed.has(dataVar)) || (propsVar !== undefined && shadowed.has(propsVar)))
150
+ return
151
+ }
152
+
153
+ if (type === 'Identifier') {
154
+ const parent = ancestors[ancestors.length - 1]
155
+ const grand = ancestors[ancestors.length - 2]
156
+ const isNonRef = parent !== undefined && (
157
+ (parent.type === 'MemberExpression' && !parent.computed && parent.property === ast)
158
+ || (parent.type === 'Property' && !parent.computed && parent.key === ast && !parent.shorthand)
159
+ || (parent.type === 'VariableDeclarator' && parent.id === ast)
160
+ || (parent.type === 'LabeledStatement' && parent.label === ast)
161
+ || (parent.type === 'FunctionDeclaration' && parent.id === ast)
162
+ || (parent.type === 'FunctionExpression' && parent.id === ast)
163
+ )
164
+
165
+ if (!isNonRef && dataVar !== undefined && ast.name === dataVar) {
166
+ if (parent?.type === 'MemberExpression' && parent.object === ast) {
167
+ const k = memberKeyName(parent)
168
+ if (k === undefined)
169
+ escaped = true
170
+ else
171
+ keys.add(k)
172
+ }
173
+ else if (parent?.type === 'VariableDeclarator' && parent.init === ast) {
174
+ const nested = extractObjectPatternKeys(parent.id)
175
+ if (nested === undefined)
176
+ escaped = true
177
+ else
178
+ for (const k of nested) keys.add(k)
179
+ }
180
+ else {
181
+ escaped = true
182
+ }
183
+ }
184
+ else if (!isNonRef && propsVar !== undefined && ast.name === propsVar) {
185
+ if (parent?.type === 'MemberExpression' && parent.object === ast) {
186
+ const propName = memberKeyName(parent)
187
+ if (propName === undefined) {
188
+ escaped = true
189
+ }
190
+ else if (propName === 'data') {
191
+ const holder = grand?.type === 'ChainExpression' ? ancestors[ancestors.length - 3] : grand
192
+ const target = grand?.type === 'ChainExpression' ? grand : parent
193
+ if (holder?.type === 'MemberExpression' && holder.object === target) {
194
+ const k = memberKeyName(holder)
195
+ if (k === undefined)
196
+ escaped = true
197
+ else
198
+ keys.add(k)
199
+ }
200
+ else if (holder?.type === 'VariableDeclarator' && holder.init === target) {
201
+ const nested = extractObjectPatternKeys(holder.id)
202
+ if (nested === undefined)
203
+ escaped = true
204
+ else
205
+ for (const k of nested) keys.add(k)
206
+ }
207
+ else {
208
+ escaped = true
209
+ }
210
+ }
211
+ }
212
+ else {
213
+ escaped = true
214
+ }
215
+ }
216
+ }
217
+
218
+ ancestors.push(ast)
219
+ const childKeys = visitorKeys[type]
220
+ if (childKeys !== undefined) {
221
+ const rec = ast as unknown as Record<string, unknown>
222
+ for (let i = 0; i < childKeys.length; i++) {
223
+ const val = rec[childKeys[i]!]
224
+ if (val !== null && typeof val === 'object')
225
+ walkWithParents(val)
226
+ }
227
+ }
228
+ ancestors.pop()
229
+ }
230
+
231
+ walkWithParents(fn.body)
232
+ return escaped ? undefined : [...keys].sort()
233
+ }
@@ -14,7 +14,8 @@ import type {
14
14
  } from 'oxc-parser'
15
15
  import type { ModuleAnalysis } from './analyze'
16
16
  import { visitorKeys } from 'oxc-parser'
17
- import { analyzeModule, loadDeclarations, parseTsx, walk } from './analyze'
17
+ import { analyzeModule, loadDeclarations, parseTsx } from './analyze'
18
+ import { walk } from './ast'
18
19
  import { SourceEditor } from './patch'
19
20
  import {
20
21
  classifyJsxChild,
@@ -1101,23 +1102,25 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
1101
1102
  if (isJsxNode(only))
1102
1103
  return compileRootJsx(only, scopeRewrites)
1103
1104
  if (only.type === 'JSXText')
1104
- return `document.createTextNode(${JSON.stringify(decodeHtmlEntities(cleanJsxText(only.value)))})`
1105
- if (only.type === 'JSXExpressionContainer' && only.expression.type !== 'JSXEmptyExpression') {
1106
- const exprCode = compileExpression(only.expression, scopeRewrites)
1107
- return `(() => { const _f = document.createDocumentFragment(); ${use('insert')}(_f, () => (${exprCode}), null, null); return _f; })()`
1108
- }
1105
+ return `${use('fragText')}(${JSON.stringify(decodeHtmlEntities(cleanJsxText(only.value)))})`
1106
+ if (only.type === 'JSXExpressionContainer' && only.expression.type !== 'JSXEmptyExpression')
1107
+ return `${use('fragInsert')}(() => (${compileExpression(only.expression, scopeRewrites)}))`
1109
1108
  }
1110
1109
 
1110
+ // Each child claims its own SSR nodes while hydrating, so the siblings after a dynamic one keep theirs (#3596).
1111
1111
  const items = meaningful.map((child) => {
1112
- if (isJsxNode(child))
1113
- return compileRootJsx(child, scopeRewrites)
1112
+ if (isJsxNode(child)) {
1113
+ // The server brackets a component or a nested fragment among siblings, so it claims that range like an expression.
1114
+ const inPlace = child.type === 'JSXElement' && !isComponentTag(jsxTagName(child.openingElement.name))
1115
+ return inPlace ? compileRootJsx(child, scopeRewrites) : `${use('fragInsert')}(() => ${compileRootJsx(child, scopeRewrites)})`
1116
+ }
1114
1117
  if (child.type === 'JSXText')
1115
- return `document.createTextNode(${JSON.stringify(decodeHtmlEntities(cleanJsxText(child.value)))})`
1118
+ return `${use('fragText')}(${JSON.stringify(decodeHtmlEntities(cleanJsxText(child.value)))})`
1116
1119
  if (child.type === 'JSXExpressionContainer' && child.expression.type !== 'JSXEmptyExpression') {
1117
1120
  const exprCode = compileExpression(child.expression, scopeRewrites)
1118
1121
  if (isNodeCapableExpr(child.expression, jsxNodes))
1119
- return `(() => { const _f = document.createDocumentFragment(); ${use('insert')}(_f, () => (${exprCode}), null, null); return _f; })()`
1120
- return `(() => { const _t = document.createTextNode(""); ${use('effect')}(() => ${use('setText')}(_t, (${exprCode}))); return _t; })()`
1122
+ return `${use('fragInsert')}(() => (${exprCode}))`
1123
+ return `(() => { const _t = ${use('fragText')}("", true); ${use('effect')}(() => ${use('setText')}(_t, (${exprCode}))); return _t; })()`
1121
1124
  }
1122
1125
  return 'document.createTextNode("")'
1123
1126
  })
@@ -1266,7 +1269,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
1266
1269
 
1267
1270
  if (used.size > 0) {
1268
1271
  const hasLoop = used.delete('loop')
1269
- const EXTRA_HELPERS = ['insert', 'mergeProps', 'omit', 'setInnerHtml', 'show', 'spread']
1272
+ const EXTRA_HELPERS = ['fragInsert', 'insert', 'mergeProps', 'omit', 'setInnerHtml', 'show', 'spread']
1270
1273
  const usedExtras: string[] = []
1271
1274
  for (const name of EXTRA_HELPERS) {
1272
1275
  if (used.delete(name))
@@ -1274,14 +1277,14 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
1274
1277
  }
1275
1278
  if (used.size > 0) {
1276
1279
  const specifiers = [...used].sort().map(name => `${name} as __${name}`).join(', ')
1277
- header += `import { ${specifiers} } from 'kay/dom';\n`
1280
+ header += `import { ${specifiers} } from '@kayjs/kay/internal/dom';\n`
1278
1281
  }
1279
1282
  if (usedExtras.length > 0) {
1280
1283
  const specifiers = usedExtras.map(name => `${name} as __${name}`).join(', ')
1281
- header += `import { ${specifiers} } from 'kay/dom-extras';\n`
1284
+ header += `import { ${specifiers} } from '@kayjs/kay/internal/dom-extras';\n`
1282
1285
  }
1283
1286
  if (hasLoop)
1284
- header += `import { loop as __loop } from 'kay/dom-loop';\n`
1287
+ header += `import { loop as __loop } from '@kayjs/kay/internal/dom-loop';\n`
1285
1288
  }
1286
1289
  for (const t of templates)
1287
1290
  header += `const ${t.name} = __template(${JSON.stringify(t.html)}${t.isSvg ? ', true' : ''});\n`
@@ -0,0 +1,174 @@
1
+ // Which exports of a module run in the browser: facts gathered per top-level binding, spread through the local calls and tags between them.
2
+
3
+ import type { ImportInfo } from './analyze'
4
+
5
+ export interface Fact {
6
+ reason: string
7
+ offset: number
8
+ }
9
+
10
+ export interface BindingFacts {
11
+ /** The top-level name, `default` for an anonymous default export, or '' for module-level code. */
12
+ name: string
13
+ start: number
14
+ end: number
15
+ /** The first thing its own code does that needs the browser. */
16
+ fact: Fact | undefined
17
+ /** Top-level bindings and imports its code names, each at its first use. */
18
+ refs: Map<string, number>
19
+ /** Component tags it renders, `NS.Tag` included. */
20
+ tags: Set<string>
21
+ /** The first `<Head>` or `<Suspense>` it renders. */
22
+ serverOnlyTag: string | undefined
23
+ }
24
+
25
+ export interface ExportFacts {
26
+ interactive: boolean
27
+ /** Why it runs in the browser, e.g. `uses onClick`. */
28
+ reason?: string | undefined
29
+ offset?: number | undefined
30
+ }
31
+
32
+ export interface Interactivity {
33
+ /** Some binding or module-level code runs in the browser. */
34
+ isInteractive: boolean
35
+ /** The first reason in source order. */
36
+ interactiveReason: string | undefined
37
+ interactiveOffset: number | undefined
38
+ exports: Map<string, ExportFacts>
39
+ /** Component tags rendered by code that runs on the server: the ones an imported island can stand for. */
40
+ staticJsxTags: Set<string>
41
+ /** Spans of code that only runs inside an island, where an imported island is part of the outer one. */
42
+ islandSpans: [number, number][]
43
+ /** An island rendering `<Head>` or `<Suspense>`, itself or through a local component. */
44
+ serverOnly: ServerOnlyInIsland | undefined
45
+ }
46
+
47
+ export interface ServerOnlyInIsland {
48
+ tag: string
49
+ /** The island's name, `the default export` or `the module` when it has none. */
50
+ island: string
51
+ reason: string
52
+ offset: number
53
+ }
54
+
55
+ /** `reads` maps imported locals to a reason, `reads count from './store'` for reactive state another module exports. */
56
+ export function resolveInteractivity(bindings: readonly BindingFacts[], exportLocals: ReadonlyMap<string, string>, reads: ReadonlyMap<string, string> = new Map()): Interactivity {
57
+ const named = new Map<string, BindingFacts>()
58
+ for (const b of bindings) {
59
+ if (b.name !== '')
60
+ named.set(b.name, b)
61
+ }
62
+ const facts = spreadFacts(bindings, named, reads)
63
+
64
+ const exported = new Set(exportLocals.values())
65
+ const serverSide = new Set<BindingFacts>()
66
+ const stack = bindings.filter(b => !facts.has(b) && (b.name === '' || exported.has(b.name)))
67
+ for (let b = stack.pop(); b !== undefined; b = stack.pop()) {
68
+ if (serverSide.has(b))
69
+ continue
70
+ serverSide.add(b)
71
+ for (const ref of b.refs.keys()) {
72
+ const dep = named.get(ref)
73
+ if (dep !== undefined && !facts.has(dep))
74
+ stack.push(dep)
75
+ }
76
+ }
77
+
78
+ const exports = new Map<string, ExportFacts>()
79
+ for (const [name, local] of exportLocals) {
80
+ const binding = named.get(local)
81
+ const fact = binding === undefined ? undefined : facts.get(binding)
82
+ exports.set(name, fact === undefined ? { interactive: false } : { interactive: true, reason: fact.reason, offset: fact.offset })
83
+ }
84
+ const first = bindings.find(b => facts.has(b))
85
+ const firstFact = first === undefined ? undefined : facts.get(first)
86
+ return {
87
+ isInteractive: facts.size > 0,
88
+ interactiveReason: firstFact?.reason,
89
+ interactiveOffset: firstFact?.offset,
90
+ exports,
91
+ staticJsxTags: new Set([...serverSide].flatMap(b => [...b.tags])),
92
+ islandSpans: bindings.filter(b => !serverSide.has(b)).map(b => [b.start, b.end]),
93
+ serverOnly: serverOnlyInIsland(bindings, named, facts),
94
+ }
95
+ }
96
+
97
+ function spreadFacts(bindings: readonly BindingFacts[], named: ReadonlyMap<string, BindingFacts>, reads: ReadonlyMap<string, string>): Map<BindingFacts, Fact> {
98
+ const facts = new Map<BindingFacts, Fact>()
99
+ let moduleFact: Fact | undefined
100
+ for (const b of bindings) {
101
+ let own = b.fact
102
+ for (const [ref, offset] of b.refs) {
103
+ const reason = own === undefined ? reads.get(ref) : undefined
104
+ if (reason !== undefined)
105
+ own = { reason, offset }
106
+ }
107
+ if (own !== undefined)
108
+ facts.set(b, own)
109
+ if (b.name === '')
110
+ moduleFact ??= own
111
+ }
112
+ // Module-level code that needs the browser runs with every island of the module, so every binding gets its reason.
113
+ if (moduleFact !== undefined) {
114
+ for (const b of named.values()) {
115
+ if (!facts.has(b))
116
+ facts.set(b, moduleFact)
117
+ }
118
+ }
119
+ // A binding calling or rendering an interactive one runs in the browser too; repeat until nothing changes.
120
+ for (let changed = true; changed;) {
121
+ changed = false
122
+ for (const b of named.values()) {
123
+ if (facts.has(b))
124
+ continue
125
+ for (const [ref, offset] of b.refs) {
126
+ const dep = named.get(ref)
127
+ const depFact = dep === undefined ? undefined : facts.get(dep)
128
+ if (depFact !== undefined) {
129
+ facts.set(b, { reason: `uses ${ref}, which ${depFact.reason}`, offset })
130
+ changed = true
131
+ break
132
+ }
133
+ }
134
+ }
135
+ }
136
+ return facts
137
+ }
138
+
139
+ function serverOnlyInIsland(bindings: readonly BindingFacts[], named: ReadonlyMap<string, BindingFacts>, facts: ReadonlyMap<BindingFacts, Fact>): Interactivity['serverOnly'] {
140
+ for (const island of bindings) {
141
+ const fact = facts.get(island)
142
+ if (fact === undefined)
143
+ continue
144
+ const seen = new Set<BindingFacts>()
145
+ const stack = [island]
146
+ for (let b = stack.pop(); b !== undefined; b = stack.pop()) {
147
+ if (seen.has(b))
148
+ continue
149
+ seen.add(b)
150
+ if (b.serverOnlyTag !== undefined) {
151
+ const name = island.name === '' ? 'the module' : island.name === 'default' ? 'the default export' : island.name
152
+ return { tag: b.serverOnlyTag, island: name, reason: fact.reason, offset: fact.offset }
153
+ }
154
+ for (const ref of b.refs.keys()) {
155
+ const dep = named.get(ref)
156
+ if (dep !== undefined)
157
+ stack.push(dep)
158
+ }
159
+ }
160
+ }
161
+ return undefined
162
+ }
163
+
164
+ /** The module re-resolved once its imports of other modules' reactive state are known, or `undefined` when it imports none. */
165
+ export function withStateReads(analysis: { imports: ImportInfo[], jsxTags: Set<string>, bindings: BindingFacts[], exportLocals: Map<string, string> }, isState: (imp: ImportInfo, imported: string) => boolean): Interactivity | undefined {
166
+ const reads = new Map<string, string>()
167
+ for (const imp of analysis.imports) {
168
+ for (const spec of imp.specifiers) {
169
+ if (!analysis.jsxTags.has(spec.local) && isState(imp, spec.imported))
170
+ reads.set(spec.local, `reads ${spec.local} from '${imp.source}'`)
171
+ }
172
+ }
173
+ return reads.size === 0 ? undefined : resolveInteractivity(analysis.bindings, analysis.exportLocals, reads)
174
+ }
@@ -1,7 +1,8 @@
1
1
  // Refuses JSX that compiles but does the wrong thing, mostly habits from React, Solid and Astro, with an error naming the fix.
2
2
 
3
3
  import type { JSXAttribute, JSXAttributeItem, JSXElement, Node, Program } from 'oxc-parser'
4
- import { walk } from './analyze'
4
+ import type { ServerOnlyInIsland } from './interactivity'
5
+ import { walk } from './ast'
5
6
  import { EVENT_ATTR, filterMeaningfulChildren, isComponentTag, jsxTagName, unwrapParens, VOID_ELEMENTS } from './shared'
6
7
 
7
8
  // The kay prop for each DOM event, keyed by the event name kay binds (`onKeyDown` binds `keydown`).
@@ -50,6 +51,23 @@ export function mistake(what: string, filename: string, fix: string): Error {
50
51
  return new Error(`kay compiler: ${what} in ${filename}: ${fix}.`)
51
52
  }
52
53
 
54
+ export function islandRemoved(filename: string): Error {
55
+ return mistake('island()', filename, 'it is gone; write export const hydrate = \'visible\' in the component\'s file, or set $hydrate where it renders')
56
+ }
57
+
58
+ // `<Head>` and `<Suspense>` run during server rendering only, so in an island they never update.
59
+ export function serverOnlyTagError(filename: string, { tag, island, reason }: ServerOnlyInIsland): Error {
60
+ return mistake(`<${tag}> in an island`, filename, `${island} is an island because it ${reason}; move <${tag}> to the page or a layout, outside any component with state or handlers`)
61
+ }
62
+
63
+ const BARE_KAY_RE = /^kay(?:\/|$)/
64
+
65
+ /** Refuses the bare `kay` spelling kay v1 used: v2 is imported as `@kayjs/kay`. */
66
+ export function assertScopedKayImport(source: string, filename: string): void {
67
+ if (BARE_KAY_RE.test(source))
68
+ throw mistake(`import from '${source}'`, filename, `write '@kayjs/${source}' (kay upgrade rewrites every import)`)
69
+ }
70
+
53
71
  const HYDRATE_MODES = new Set(['load', 'visible', 'idle', 'interaction', 'client'])
54
72
  const MEDIA_MODE = /^media\(.+\)$/
55
73
 
@@ -5,8 +5,11 @@ import { loadDeclarations } from './analyze'
5
5
  import { collectPatternNames } from './shared'
6
6
 
7
7
  export const SERVER_ONLY_MODULES = new Set([
8
- 'kay/server',
9
8
  '@kayjs/kay/server',
9
+ '@kayjs/kay/config',
10
+ '@kayjs/kay/internal/server',
11
+ '@kayjs/kay/build',
12
+ '@kayjs/kay/test',
10
13
  'bun',
11
14
  'bun:sqlite',
12
15
  'bun:sql',
@@ -18,7 +18,7 @@ import type {
18
18
  ParamPattern,
19
19
  Program,
20
20
  } from 'oxc-parser'
21
- import { walk } from './analyze'
21
+ import { walk } from './ast'
22
22
 
23
23
  export { DOM_PROPS, isBlockedAttr, isStringBoolAttr, isUnsafeUrlAttr } from '../attrs'
24
24