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

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 (69) hide show
  1. package/package.json +1 -1
  2. package/src/attrs.ts +35 -0
  3. package/src/build/bundle.ts +617 -0
  4. package/src/build/compile.ts +27 -51
  5. package/src/build/files.ts +174 -0
  6. package/src/build/graph.ts +223 -0
  7. package/src/build/index.ts +272 -1466
  8. package/src/build/islands.ts +177 -0
  9. package/src/build/manifest.ts +229 -0
  10. package/src/build/plugin-host.ts +186 -0
  11. package/src/build/prerender.ts +102 -0
  12. package/src/build/report.ts +157 -0
  13. package/src/build/resolve.ts +51 -0
  14. package/src/build/routes.ts +163 -0
  15. package/src/build/server-entry.ts +38 -0
  16. package/src/build/static.ts +73 -0
  17. package/src/cli/check.ts +300 -129
  18. package/src/cli/index.ts +297 -94
  19. package/src/cli/new.ts +58 -38
  20. package/src/compiler/analyze.ts +723 -93
  21. package/src/compiler/dom.ts +848 -762
  22. package/src/compiler/mistakes.ts +354 -0
  23. package/src/compiler/patch.ts +1 -1
  24. package/src/compiler/server-only.ts +172 -23
  25. package/src/compiler/shared.ts +485 -0
  26. package/src/compiler/ssr.ts +331 -342
  27. package/src/context.ts +120 -0
  28. package/src/dev/index.ts +339 -76
  29. package/src/dom/action.ts +114 -14
  30. package/src/dom/extras.ts +121 -83
  31. package/src/dom/index.ts +122 -80
  32. package/src/dom/island.ts +71 -36
  33. package/src/dom/loop.ts +28 -20
  34. package/src/index.ts +5 -1
  35. package/src/jsx-runtime.ts +432 -93
  36. package/src/plugins/config.ts +49 -0
  37. package/src/plugins/context.ts +61 -0
  38. package/src/plugins/index.ts +10 -123
  39. package/src/plugins/load.ts +38 -0
  40. package/src/plugins/order.ts +107 -0
  41. package/src/plugins/services.ts +23 -0
  42. package/src/plugins/types.ts +197 -0
  43. package/src/reactivity/index.ts +237 -213
  44. package/src/reactivity/selector.ts +11 -9
  45. package/src/reactivity/store.ts +36 -11
  46. package/src/server/action-registry.ts +72 -0
  47. package/src/server/action.ts +157 -79
  48. package/src/server/app-entry.ts +23 -0
  49. package/src/server/assets.ts +182 -0
  50. package/src/server/compress.ts +197 -104
  51. package/src/server/cookies.ts +46 -16
  52. package/src/server/document.ts +192 -0
  53. package/src/server/env.ts +18 -13
  54. package/src/server/errors.ts +123 -0
  55. package/src/server/http.ts +203 -77
  56. package/src/server/index.ts +420 -973
  57. package/src/server/loader.ts +113 -0
  58. package/src/server/page.ts +107 -0
  59. package/src/server/plugin-host.ts +167 -0
  60. package/src/server/router.ts +69 -26
  61. package/src/server/security.ts +90 -59
  62. package/src/server/standard-schema.ts +42 -11
  63. package/src/server/static-dir.ts +163 -0
  64. package/src/server/stream.ts +94 -0
  65. package/src/ssr/context.ts +95 -10
  66. package/src/ssr/index.ts +167 -66
  67. package/src/style.ts +33 -0
  68. package/src/test/index.ts +24 -18
  69. package/src/unrenderable.ts +35 -0
@@ -1,9 +1,20 @@
1
1
  // OXC-based static analysis for TSX/TS files: automatic island detection, actions, prerender, Head/Suspense.
2
2
 
3
- import { parseSync } from 'oxc-parser'
3
+ import type {
4
+ ArrowFunctionExpression,
5
+ CallExpression,
6
+ ExportNamedDeclaration,
7
+ Function as OxcFunction,
8
+ Node,
9
+ Program,
10
+ Statement,
11
+ VariableDeclaration,
12
+ } from 'oxc-parser'
13
+ import { parseSync, visitorKeys } from 'oxc-parser'
14
+ import { checkBareSignals, checkHydrateMode, checkMistakes, mistake } from './mistakes'
15
+ import { EVENT_ATTR, formatCodeFrame, formatDiagnostic, formatLoc, isComponentTag, isJsxNode, jsxTagName, unwrapTsExpr } from './shared'
4
16
 
5
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
6
- export type AstNode = Record<string, any>
17
+ export type AstNode = Node
7
18
 
8
19
  const REACTIVE_IMPORTS = new Set([
9
20
  'signal',
@@ -14,9 +25,15 @@ const REACTIVE_IMPORTS = new Set([
14
25
  'selector',
15
26
  'store',
16
27
  'island',
28
+ 'useAction',
17
29
  ])
18
30
 
19
- const EVENT_ATTR = /^on[A-Z]/
31
+ // Primitives whose result is reactive state another module can import and read.
32
+ const STATE_PRIMITIVES = new Set(['signal', 'computed', 'selector', 'store'])
33
+ const KAY_SOURCES = new Set(['kay', '@kayjs/kay'])
34
+ const KAY_SSR_SOURCES = new Set(['kay', '@kayjs/kay', 'kay/ssr', '@kayjs/kay/ssr'])
35
+ const KAY_SERVER_SOURCES = new Set(['kay/server', '@kayjs/kay/server'])
36
+ const RENDER_CONTEXT_IMPORTS = new Set(['Head', 'Suspense', 'createContext', 'provideContext', 'useContext', 'useId'])
20
37
 
21
38
  export interface ImportInfo {
22
39
  source: string
@@ -29,28 +46,85 @@ export interface ReexportInfo {
29
46
  exported: string
30
47
  local: string
31
48
  source: string
49
+ start: number
32
50
  }
33
51
 
34
52
  export interface ModuleAnalysis {
35
53
  filename: string
36
- program: AstNode
54
+ program: Program
37
55
  isInteractive: boolean
38
56
  interactiveReason: string | undefined
57
+ interactiveOffset?: number | undefined
39
58
  hasAsyncDefault: boolean
40
59
  hasLoadExport: boolean
41
60
  hasJsx: boolean
61
+ /** Precomputed set of AST nodes containing JSX (itself included), for O(1) subtree checks during codegen. */
62
+ jsxNodes: WeakSet<Node>
42
63
  hasPrerender: boolean
43
64
  hasPaths: boolean
44
65
  usesRenderContext: boolean
45
66
  defaultHydrate: string | undefined
46
67
  deferredIslandTags: Set<string>
68
+ /** `$hydrate` modes the module writes; `*` stands for one computed at runtime. */
69
+ hydrateModes: Set<string>
70
+ /** Component tags the module renders, `NS.Tag` included. */
71
+ jsxTags: Set<string>
72
+ /** Exported names bound to reactive state (`export const count = signal(0)`). */
73
+ stateExports: string[]
74
+ /** Static top-level keys of `data` read by the default export (when statically bounded; `undefined` if `data` escapes). */
75
+ defaultDataKeys?: string[] | undefined
47
76
  exportedActions: string[]
48
77
  imports: ImportInfo[]
49
78
  reexports: ReexportInfo[]
50
79
  exportedNames: string[]
80
+ /** Code that compiles but usually means something else, worded for build and `kay check` to print. */
81
+ warnings: string[]
51
82
  }
52
83
 
53
- export function walk(node: unknown, visit: (node: AstNode) => boolean | void): void {
84
+ export function computeJsxNodes(program: Program): WeakSet<Node> {
85
+ const jsxNodes = new WeakSet<Node>()
86
+ const visit = (node: unknown): boolean => {
87
+ if (node === null || typeof node !== 'object')
88
+ return false
89
+ if (Array.isArray(node)) {
90
+ let any = false
91
+ for (let i = 0; i < node.length; i++) {
92
+ if (visit(node[i]))
93
+ any = true
94
+ }
95
+ return any
96
+ }
97
+ const ast = node as Node
98
+ const type = ast.type
99
+ if (typeof type !== 'string')
100
+ return false
101
+ let found = isJsxNode(ast)
102
+ const keys = visitorKeys[type]
103
+ if (keys !== undefined) {
104
+ const rec = ast as unknown as Record<string, unknown>
105
+ for (let i = 0; i < keys.length; i++) {
106
+ const val = rec[keys[i]!]
107
+ if (val !== null && typeof val === 'object' && visit(val))
108
+ found = true
109
+ }
110
+ }
111
+ else {
112
+ for (const [key, val] of Object.entries(ast)) {
113
+ if (key === 'start' || key === 'end' || key === 'type')
114
+ continue
115
+ if (val !== null && typeof val === 'object' && visit(val))
116
+ found = true
117
+ }
118
+ }
119
+ if (found)
120
+ jsxNodes.add(ast)
121
+ return found
122
+ }
123
+ visit(program)
124
+ return jsxNodes
125
+ }
126
+
127
+ export function walk(node: unknown, visit: (node: Node) => boolean | void): void {
54
128
  if (node === null || typeof node !== 'object')
55
129
  return
56
130
  if (Array.isArray(node)) {
@@ -58,32 +132,394 @@ export function walk(node: unknown, visit: (node: AstNode) => boolean | void): v
58
132
  walk(node[i], visit)
59
133
  return
60
134
  }
61
- const ast = node as AstNode
62
- if (typeof ast.type === 'string') {
63
- if (visit(ast) === false)
64
- return
135
+ const ast = node as Node
136
+ const type = ast.type
137
+ if (typeof type !== 'string')
138
+ return
139
+ if (visit(ast) === false)
140
+ return
141
+ const keys = visitorKeys[type]
142
+ if (keys !== undefined) {
143
+ const rec = ast as unknown as Record<string, unknown>
144
+ for (let i = 0; i < keys.length; i++) {
145
+ const val = rec[keys[i]!]
146
+ if (val !== null && typeof val === 'object')
147
+ walk(val, visit)
148
+ }
149
+ return
65
150
  }
66
- for (const key of Object.keys(ast)) {
151
+ for (const [key, val] of Object.entries(ast)) {
67
152
  if (key === 'start' || key === 'end' || key === 'type')
68
153
  continue
69
- const val = ast[key]
70
154
  if (val !== null && typeof val === 'object')
71
155
  walk(val, visit)
72
156
  }
73
157
  }
74
158
 
75
- export function parseTsx(filename: string, code: string): AstNode {
76
- const result = parseSync(filename, code, { lang: filename.endsWith('.ts') ? 'ts' : 'tsx', sourceType: 'module' })
159
+ function exportedName(node: { type: string, name?: string, value?: string }): string | undefined {
160
+ return node.type === 'Identifier' ? node.name : node.value
161
+ }
162
+
163
+ // The server-only code behind a module's `load` / `clientData` exports: a function declaration or declarator initialiser, in any export form.
164
+ export function loadDeclarations(program: Program): Node[] {
165
+ const SERVER_ROUTE_EXPORTS = new Set(['load', 'clientData'])
166
+ const localNames = new Set<string>()
167
+ const found: Node[] = []
168
+ const collect = (stmt: Statement | ExportNamedDeclaration['declaration'], names: Set<string>): void => {
169
+ if (stmt === null)
170
+ return
171
+ if (stmt.type === 'FunctionDeclaration' && stmt.id !== null && names.has(stmt.id.name)) {
172
+ found.push(stmt)
173
+ }
174
+ else if (stmt.type === 'VariableDeclaration') {
175
+ for (const d of stmt.declarations) {
176
+ if (d.id.type === 'Identifier' && names.has(d.id.name) && d.init !== null)
177
+ found.push(d.init)
178
+ }
179
+ }
180
+ }
181
+ for (const stmt of program.body) {
182
+ if (stmt.type !== 'ExportNamedDeclaration' || stmt.source !== null)
183
+ continue
184
+ if (stmt.declaration !== null)
185
+ collect(stmt.declaration, SERVER_ROUTE_EXPORTS)
186
+ for (const spec of stmt.specifiers) {
187
+ const exp = exportedName(spec.exported)
188
+ if (exp !== undefined && SERVER_ROUTE_EXPORTS.has(exp) && spec.local.type === 'Identifier')
189
+ localNames.add(spec.local.name)
190
+ }
191
+ }
192
+ if (localNames.size > 0) {
193
+ for (const stmt of program.body)
194
+ collect(stmt, localNames)
195
+ }
196
+ return found
197
+ }
198
+
199
+ function staticPropKey(prop: Node): string | undefined {
200
+ if (prop.type !== 'Property')
201
+ return undefined
202
+ if (!prop.computed && prop.key.type === 'Identifier')
203
+ return prop.key.name
204
+ if (prop.key.type === 'Literal' && typeof prop.key.value === 'string')
205
+ return prop.key.value
206
+ return undefined
207
+ }
208
+
209
+ function extractObjectPatternKeys(pat: Node): string[] | undefined {
210
+ if (pat.type !== 'ObjectPattern')
211
+ return undefined
212
+ const keys: string[] = []
213
+ for (const prop of pat.properties) {
214
+ if (prop.type === 'RestElement')
215
+ return undefined
216
+ const k = staticPropKey(prop)
217
+ if (k === undefined)
218
+ return undefined
219
+ keys.push(k)
220
+ }
221
+ return keys
222
+ }
223
+
224
+ function memberKeyName(node: Node): string | undefined {
225
+ if (node.type !== 'MemberExpression')
226
+ return undefined
227
+ if (!node.computed && node.property.type === 'Identifier')
228
+ return node.property.name
229
+ if (node.computed && node.property.type === 'Literal' && typeof node.property.value === 'string')
230
+ return node.property.value
231
+ return undefined
232
+ }
233
+
234
+ function unwrapParamPattern(param: Node): Node {
235
+ return param.type === 'AssignmentPattern' ? param.left : param
236
+ }
237
+
238
+ function resolveDefaultFunction(
239
+ program: Program,
240
+ defaultLocal: string | undefined,
241
+ localInits: ReadonlyMap<string, Node>,
242
+ islandLocalName: string | undefined,
243
+ kayNamespaces: ReadonlySet<string>,
244
+ ): OxcFunction | ArrowFunctionExpression | undefined {
245
+ const localFns = new Map<string, OxcFunction>()
246
+ for (const stmt of program.body) {
247
+ if (stmt.type === 'FunctionDeclaration' && stmt.id !== null)
248
+ localFns.set(stmt.id.name, stmt)
249
+ else if (stmt.type === 'ExportNamedDeclaration' && stmt.declaration?.type === 'FunctionDeclaration' && stmt.declaration.id !== null)
250
+ localFns.set(stmt.declaration.id.name, stmt.declaration)
251
+ }
252
+
253
+ const unwrapTarget = (node: Node | undefined, depth = 0): OxcFunction | ArrowFunctionExpression | undefined => {
254
+ if (node === undefined || depth > 4)
255
+ return undefined
256
+ const inner = unwrapTsExpr(node)
257
+ if (inner.type === 'FunctionDeclaration' || inner.type === 'FunctionExpression' || inner.type === 'ArrowFunctionExpression')
258
+ return inner
259
+ if (isIslandCall(inner, islandLocalName, kayNamespaces))
260
+ return unwrapTarget(inner.arguments[0], depth + 1)
261
+ if (inner.type === 'Identifier')
262
+ return localFns.get(inner.name) ?? unwrapTarget(localInits.get(inner.name), depth + 1)
263
+ return undefined
264
+ }
265
+
266
+ for (const stmt of program.body) {
267
+ if (stmt.type === 'ExportDefaultDeclaration')
268
+ return unwrapTarget(stmt.declaration)
269
+ }
270
+ if (defaultLocal !== undefined)
271
+ return localFns.get(defaultLocal) ?? unwrapTarget(localInits.get(defaultLocal))
272
+ return undefined
273
+ }
274
+
275
+ /** Statically bounds which top-level keys of `props.data` a page island reads; returns `undefined` if `data` escapes. */
276
+ function analyzeDefaultDataKeys(
277
+ program: Program,
278
+ defaultLocal: string | undefined,
279
+ localInits: ReadonlyMap<string, Node>,
280
+ islandLocalName: string | undefined,
281
+ kayNamespaces: ReadonlySet<string>,
282
+ ): string[] | undefined {
283
+ const fn = resolveDefaultFunction(program, defaultLocal, localInits, islandLocalName, kayNamespaces)
284
+ if (fn === undefined || fn.body === null)
285
+ return undefined
286
+ if (fn.params.length === 0)
287
+ return []
288
+
289
+ const firstParam = unwrapParamPattern(fn.params[0]!)
290
+ const keys = new Set<string>()
291
+ let escaped = false
292
+ let dataVar: string | undefined
293
+ let propsVar: string | undefined
294
+
295
+ if (firstParam.type === 'ObjectPattern') {
296
+ let dataProp: Node | undefined
297
+ for (const prop of firstParam.properties) {
298
+ if (prop.type === 'RestElement')
299
+ return undefined
300
+ if (staticPropKey(prop) === 'data')
301
+ dataProp = prop
302
+ }
303
+ if (dataProp === undefined || dataProp.type !== 'Property')
304
+ return []
305
+ const binding = unwrapParamPattern(dataProp.value)
306
+ if (binding.type === 'ObjectPattern') {
307
+ const nested = extractObjectPatternKeys(binding)
308
+ if (nested === undefined)
309
+ return undefined
310
+ return [...new Set(nested)].sort()
311
+ }
312
+ if (binding.type !== 'Identifier')
313
+ return undefined
314
+ dataVar = binding.name
315
+ }
316
+ else if (firstParam.type === 'Identifier') {
317
+ propsVar = firstParam.name
318
+ }
319
+ else {
320
+ return undefined
321
+ }
322
+
323
+ // Walk the function body tracking parent chains so every reference to `dataVar` or `propsVar` is verified.
324
+ const ancestors: Node[] = []
325
+ const walkWithParents = (node: unknown): void => {
326
+ if (escaped || node === null || typeof node !== 'object')
327
+ return
328
+ if (Array.isArray(node)) {
329
+ for (let i = 0; i < node.length; i++)
330
+ walkWithParents(node[i])
331
+ return
332
+ }
333
+ const ast = node as Node
334
+ const type = ast.type
335
+ if (typeof type !== 'string')
336
+ return
337
+
338
+ // Respect inner function parameters that shadow `dataVar` or `propsVar`.
339
+ if (ast !== fn && (type === 'FunctionDeclaration' || type === 'FunctionExpression' || type === 'ArrowFunctionExpression')) {
340
+ const shadowed = new Set<string>()
341
+ for (const p of (ast as OxcFunction).params) {
342
+ walk(p, (pn) => {
343
+ if (pn.type === 'Identifier')
344
+ shadowed.add(pn.name)
345
+ })
346
+ }
347
+ if ((dataVar !== undefined && shadowed.has(dataVar)) || (propsVar !== undefined && shadowed.has(propsVar)))
348
+ return
349
+ }
350
+
351
+ if (type === 'Identifier') {
352
+ const parent = ancestors[ancestors.length - 1]
353
+ const grand = ancestors[ancestors.length - 2]
354
+ const isNonRef = parent !== undefined && (
355
+ (parent.type === 'MemberExpression' && !parent.computed && parent.property === ast)
356
+ || (parent.type === 'Property' && !parent.computed && parent.key === ast && !parent.shorthand)
357
+ || (parent.type === 'VariableDeclarator' && parent.id === ast)
358
+ || (parent.type === 'LabeledStatement' && parent.label === ast)
359
+ || (parent.type === 'FunctionDeclaration' && parent.id === ast)
360
+ || (parent.type === 'FunctionExpression' && parent.id === ast)
361
+ )
362
+
363
+ if (!isNonRef && dataVar !== undefined && ast.name === dataVar) {
364
+ if (parent?.type === 'MemberExpression' && parent.object === ast) {
365
+ const k = memberKeyName(parent)
366
+ if (k === undefined)
367
+ escaped = true
368
+ else
369
+ keys.add(k)
370
+ }
371
+ else if (parent?.type === 'VariableDeclarator' && parent.init === ast) {
372
+ const nested = extractObjectPatternKeys(parent.id)
373
+ if (nested === undefined)
374
+ escaped = true
375
+ else
376
+ for (const k of nested) keys.add(k)
377
+ }
378
+ else {
379
+ escaped = true
380
+ }
381
+ }
382
+ else if (!isNonRef && propsVar !== undefined && ast.name === propsVar) {
383
+ if (parent?.type === 'MemberExpression' && parent.object === ast) {
384
+ const propName = memberKeyName(parent)
385
+ if (propName === undefined) {
386
+ escaped = true
387
+ }
388
+ else if (propName === 'data') {
389
+ const holder = grand?.type === 'ChainExpression' ? ancestors[ancestors.length - 3] : grand
390
+ const target = grand?.type === 'ChainExpression' ? grand : parent
391
+ if (holder?.type === 'MemberExpression' && holder.object === target) {
392
+ const k = memberKeyName(holder)
393
+ if (k === undefined)
394
+ escaped = true
395
+ else
396
+ keys.add(k)
397
+ }
398
+ else if (holder?.type === 'VariableDeclarator' && holder.init === target) {
399
+ const nested = extractObjectPatternKeys(holder.id)
400
+ if (nested === undefined)
401
+ escaped = true
402
+ else
403
+ for (const k of nested) keys.add(k)
404
+ }
405
+ else {
406
+ escaped = true
407
+ }
408
+ }
409
+ }
410
+ else {
411
+ escaped = true
412
+ }
413
+ }
414
+ }
415
+
416
+ ancestors.push(ast)
417
+ const childKeys = visitorKeys[type]
418
+ if (childKeys !== undefined) {
419
+ const rec = ast as unknown as Record<string, unknown>
420
+ for (let i = 0; i < childKeys.length; i++) {
421
+ const val = rec[childKeys[i]!]
422
+ if (val !== null && typeof val === 'object')
423
+ walkWithParents(val)
424
+ }
425
+ }
426
+ ancestors.pop()
427
+ }
428
+
429
+ walkWithParents(fn.body)
430
+ return escaped ? undefined : [...keys].sort()
431
+ }
432
+
433
+ export function parseTsx(filename: string, code: string): Program {
434
+ const lang = /\.[cm]?ts$/i.test(filename) ? 'ts' : 'tsx'
435
+ const result = parseSync(filename, code, { lang, sourceType: 'module' })
77
436
  if (result.errors.length > 0) {
78
437
  const first = result.errors[0]!
79
- throw new Error(`kay compiler: syntax error in ${filename}: ${first.message}`)
438
+ const label = first.labels?.[0]
439
+ const offset = label?.start ?? 0
440
+ const loc = formatLoc(filename, code, offset)
441
+ const frame = formatCodeFrame(code, offset, label?.end)
442
+ const header = formatDiagnostic(loc, `kay compiler: syntax error: ${first.message}`)
443
+ throw new Error(frame ? `${header}\n${frame}` : header)
80
444
  }
81
- return result.program as AstNode
445
+ return result.program
82
446
  }
83
447
 
84
- export function analyzeModule(filename: string, code: string, program: AstNode = parseTsx(filename, code)): ModuleAnalysis {
448
+ export function asyncInteractiveError(filename: string, reason: string | undefined): Error {
449
+ return new Error(`kay compiler: async route component in ${filename} cannot use browser interactivity (${reason}). Move interactive state/handlers into a non-async component and render it from the async page.`)
450
+ }
451
+
452
+ function isAsyncFunction(node: Node | null | undefined): boolean {
453
+ if (node === null || node === undefined)
454
+ return false
455
+ const inner = unwrapTsExpr(node)
456
+ return (inner.type === 'FunctionDeclaration' || inner.type === 'FunctionExpression' || inner.type === 'ArrowFunctionExpression') && inner.async === true
457
+ }
458
+
459
+ // The variable an action() call is assigned to (`const save = action(...)`), to name it in an error.
460
+ function actionVariable(program: Program, call: CallExpression): string | undefined {
461
+ let name: string | undefined
462
+ walk(program, (node) => {
463
+ if (node.type === 'VariableDeclarator' && node.init === call && node.id.type === 'Identifier')
464
+ name = node.id.name
465
+ return name === undefined ? undefined : false
466
+ })
467
+ return name
468
+ }
469
+
470
+ // The mode a `$hydrate` attribute names: its string, or `*` when an expression picks it at runtime.
471
+ function hydrateMode(value: Node | null | undefined): string {
472
+ const raw = value?.type === 'JSXExpressionContainer' ? value.expression : value
473
+ if (raw === null || raw === undefined)
474
+ return '*'
475
+ const node = unwrapTsExpr(raw)
476
+ if (node.type === 'Literal' && typeof node.value === 'string')
477
+ return node.value
478
+ if (node.type === 'TemplateLiteral' && node.expressions.length === 0)
479
+ return node.quasis[0]?.value.cooked ?? '*'
480
+ return '*'
481
+ }
482
+
483
+ function isActionCall(node: Node, actionLocalName: string | undefined, serverNamespaces: ReadonlySet<string>): node is CallExpression {
484
+ if (node.type !== 'CallExpression')
485
+ return false
486
+ if (actionLocalName !== undefined && node.callee.type === 'Identifier' && node.callee.name === actionLocalName)
487
+ return true
488
+ if (
489
+ node.callee.type === 'MemberExpression'
490
+ && !node.callee.computed
491
+ && node.callee.object.type === 'Identifier'
492
+ && serverNamespaces.has(node.callee.object.name)
493
+ && node.callee.property.type === 'Identifier'
494
+ && node.callee.property.name === 'action'
495
+ ) {
496
+ return true
497
+ }
498
+ return false
499
+ }
500
+
501
+ function isIslandCall(node: Node, islandLocalName: string | undefined, kayNamespaces: ReadonlySet<string>): node is CallExpression {
502
+ if (node.type !== 'CallExpression')
503
+ return false
504
+ if (islandLocalName !== undefined && node.callee.type === 'Identifier' && node.callee.name === islandLocalName)
505
+ return true
506
+ if (
507
+ node.callee.type === 'MemberExpression'
508
+ && !node.callee.computed
509
+ && node.callee.object.type === 'Identifier'
510
+ && kayNamespaces.has(node.callee.object.name)
511
+ && node.callee.property.type === 'Identifier'
512
+ && node.callee.property.name === 'island'
513
+ ) {
514
+ return true
515
+ }
516
+ return false
517
+ }
518
+
519
+ export function analyzeModule(filename: string, code: string, program: Program = parseTsx(filename, code)): ModuleAnalysis {
85
520
  let isInteractive = false
86
521
  let interactiveReason: string | undefined
522
+ let interactiveOffset: number | undefined
87
523
  let hasAsyncDefault = false
88
524
  let hasLoadExport = false
89
525
  let hasJsx = false
@@ -92,151 +528,345 @@ export function analyzeModule(filename: string, code: string, program: AstNode =
92
528
  let usesRenderContext = false
93
529
  let defaultHydrate: string | undefined
94
530
  const deferredIslandTags = new Set<string>()
531
+ const jsxTags = new Set<string>()
532
+ const hydrateModes = new Set<string>()
533
+ const kayNamespaces = new Set<string>()
534
+ const serverNamespaces = new Set<string>()
535
+ const stateCallees = new Set<string>()
536
+ const warnings: string[] = []
537
+ const signalCallees = new Set<string>()
538
+ const asyncLocals = new Set<string>()
539
+ const localInits = new Map<string, Node>()
540
+ const localExports = new Map<string, string>()
541
+ let defaultLocal: string | undefined
95
542
  const exportedActions: string[] = []
96
543
  const imports: ImportInfo[] = []
97
544
  const reexports: ReexportInfo[] = []
98
545
  const exportedNames: string[] = []
99
- let actionLocalName = 'action'
546
+ let actionLocalName: string | undefined
547
+ let islandLocalName: string | undefined
548
+ // The action() calls kay gives a URL to: the initialisers of top-level `export const`s.
549
+ const registeredActions = new Set<Node>()
100
550
 
101
- const markInteractive = (reason: string) => {
551
+ const markInteractive = (reason: string, offset?: number) => {
102
552
  if (!isInteractive) {
103
553
  isInteractive = true
104
554
  interactiveReason = reason
555
+ interactiveOffset = offset
105
556
  }
106
557
  }
107
558
 
108
- for (const stmt of program.body as AstNode[]) {
109
- if (stmt.type === 'ImportDeclaration') {
110
- const source = stmt.source.value as string
111
- const specifiers: { local: string, imported: string }[] = []
559
+ const collectInits = (decl: VariableDeclaration): void => {
560
+ for (const d of decl.declarations) {
561
+ if (d.id.type === 'Identifier' && d.init !== null)
562
+ localInits.set(d.id.name, d.init)
563
+ }
564
+ }
112
565
 
113
- for (const spec of stmt.specifiers as AstNode[]) {
566
+ // Pass 1: hoist all runtime imports first so import order relative to exports never matters.
567
+ for (const stmt of program.body) {
568
+ if (stmt.type !== 'ImportDeclaration')
569
+ continue
570
+ // Entire `import type { ... } from '...'` declarations have zero runtime effect.
571
+ if (stmt.importKind === 'type')
572
+ continue
573
+ const source = stmt.source.value
574
+ const specifiers: { local: string, imported: string }[] = []
575
+
576
+ for (const spec of stmt.specifiers) {
577
+ if (spec.type === 'ImportSpecifier') {
114
578
  if (spec.importKind === 'type')
115
579
  continue
116
- if (spec.type === 'ImportSpecifier') {
117
- const imported = spec.imported.name as string
118
- const local = spec.local.name as string
119
- specifiers.push({ local, imported })
120
- if ((source === 'kay' || source === '@kayjs/kay') && REACTIVE_IMPORTS.has(imported))
121
- markInteractive(`imports ${imported} from '${source}'`)
122
- if ((source === 'kay' || source === '@kayjs/kay' || source === 'kay/ssr') && (imported === 'Head' || imported === 'Suspense'))
123
- usesRenderContext = true
124
- if ((source === 'kay/server' || source === '@kayjs/kay/server') && imported === 'action')
125
- actionLocalName = local
126
- }
127
- else if (spec.type === 'ImportDefaultSpecifier') {
128
- specifiers.push({ local: spec.local.name as string, imported: 'default' })
129
- }
130
- else if (spec.type === 'ImportNamespaceSpecifier') {
131
- specifiers.push({ local: spec.local.name as string, imported: '*' })
580
+ const imported = exportedName(spec.imported)
581
+ if (imported === undefined)
582
+ continue
583
+ const local = spec.local.name
584
+ specifiers.push({ local, imported })
585
+ if (KAY_SOURCES.has(source) && REACTIVE_IMPORTS.has(imported))
586
+ markInteractive(`imports ${imported} from '${source}'`, spec.start)
587
+ if (KAY_SOURCES.has(source) && imported === 'island')
588
+ islandLocalName = local
589
+ if (KAY_SOURCES.has(source) && STATE_PRIMITIVES.has(imported))
590
+ stateCallees.add(local)
591
+ if (KAY_SOURCES.has(source) && (imported === 'signal' || imported === 'computed'))
592
+ signalCallees.add(local)
593
+ if (KAY_SSR_SOURCES.has(source) && RENDER_CONTEXT_IMPORTS.has(imported))
594
+ usesRenderContext = true
595
+ if (KAY_SERVER_SOURCES.has(source) && imported === 'action')
596
+ actionLocalName = local
597
+ }
598
+ else if (spec.type === 'ImportDefaultSpecifier') {
599
+ specifiers.push({ local: spec.local.name, imported: 'default' })
600
+ }
601
+ else if (spec.type === 'ImportNamespaceSpecifier') {
602
+ specifiers.push({ local: spec.local.name, imported: '*' })
603
+ if (KAY_SOURCES.has(source))
604
+ kayNamespaces.add(spec.local.name)
605
+ if (KAY_SERVER_SOURCES.has(source))
606
+ serverNamespaces.add(spec.local.name)
607
+ }
608
+ }
609
+
610
+ imports.push({ source, specifiers, start: stmt.start, end: stmt.end })
611
+ }
612
+
613
+ const readIslandHydrate = (call: CallExpression): void => {
614
+ markInteractive('island() wrapper', call.start)
615
+ const opts = call.arguments[1]
616
+ if (opts !== undefined && opts.type === 'ObjectExpression') {
617
+ for (const prop of opts.properties) {
618
+ if (
619
+ prop.type === 'Property'
620
+ && !prop.computed
621
+ && prop.key.type === 'Identifier'
622
+ && prop.key.name === 'hydrate'
623
+ && prop.value.type === 'Literal'
624
+ && typeof prop.value.value === 'string'
625
+ ) {
626
+ checkHydrateMode(prop.value.value, `island() hydrate: "${prop.value.value}"`, filename)
627
+ defaultHydrate = prop.value.value
132
628
  }
133
629
  }
630
+ }
631
+ }
134
632
 
135
- if (stmt.importKind !== 'type')
136
- imports.push({ source, specifiers, start: stmt.start, end: stmt.end })
633
+ // Pass 2: collect top-level declarations, exports, re-exports, actions, and metadata.
634
+ for (const stmt of program.body) {
635
+ if (stmt.type === 'VariableDeclaration') {
636
+ collectInits(stmt)
637
+ }
638
+ else if (stmt.type === 'FunctionDeclaration') {
639
+ if (stmt.async === true && stmt.id !== null)
640
+ asyncLocals.add(stmt.id.name)
641
+ }
642
+ else if (stmt.type === 'ExportAllDeclaration') {
643
+ if (stmt.exportKind !== 'type')
644
+ reexports.push({ exported: '*', local: '*', source: stmt.source.value, start: stmt.start })
137
645
  }
138
646
  else if (stmt.type === 'ExportDefaultDeclaration') {
139
647
  exportedNames.push('default')
140
- const decl = stmt.declaration as AstNode
141
- if ((decl.type === 'FunctionDeclaration' || decl.type === 'FunctionExpression' || decl.type === 'ArrowFunctionExpression') && decl.async === true)
648
+ const decl = unwrapTsExpr(stmt.declaration)
649
+ if (isAsyncFunction(decl))
142
650
  hasAsyncDefault = true
651
+ else if (decl.type === 'Identifier')
652
+ defaultLocal = decl.name
653
+ else
654
+ localInits.set('default', decl)
143
655
 
144
- if (decl.type === 'CallExpression' && decl.callee?.name === 'island') {
145
- markInteractive('island() wrapper')
146
- const opts = decl.arguments?.[1]
147
- if (opts?.type === 'ObjectExpression') {
148
- for (const prop of opts.properties as AstNode[]) {
149
- if (prop.type === 'Property' && prop.key?.name === 'hydrate' && prop.value?.type === 'Literal' && typeof prop.value.value === 'string')
150
- defaultHydrate = prop.value.value
151
- }
152
- }
656
+ if (isIslandCall(decl, islandLocalName, kayNamespaces)) {
657
+ readIslandHydrate(decl)
658
+ const target = decl.arguments[0]
659
+ if (target !== undefined && isAsyncFunction(target))
660
+ hasAsyncDefault = true
153
661
  }
154
662
  }
155
663
  else if (stmt.type === 'ExportNamedDeclaration') {
156
- if (stmt.source?.value && stmt.exportKind !== 'type') {
157
- const src = stmt.source.value as string
158
- for (const spec of (stmt.specifiers ?? []) as AstNode[]) {
664
+ if (stmt.exportKind === 'type')
665
+ continue
666
+ if (stmt.source !== null) {
667
+ const src = stmt.source.value
668
+ for (const spec of stmt.specifiers) {
159
669
  if (spec.exportKind === 'type')
160
670
  continue
161
- const exported = (spec.exported?.name ?? spec.exported?.value) as string | undefined
162
- const local = (spec.local?.name ?? spec.local?.value) as string | undefined
163
- if (exported && local) {
671
+ const exported = exportedName(spec.exported)
672
+ const local = exportedName(spec.local)
673
+ if (exported !== undefined && local !== undefined) {
164
674
  exportedNames.push(exported)
165
- reexports.push({ exported, local, source: src })
675
+ reexports.push({ exported, local, source: src, start: stmt.start })
676
+ if (exported === 'load')
677
+ hasLoadExport = true
678
+ if (exported === 'paths')
679
+ hasPaths = true
166
680
  }
167
681
  }
168
682
  }
169
- const decl = stmt.declaration as AstNode | null
170
- if (decl?.type === 'FunctionDeclaration' && decl.id?.name) {
171
- const name = decl.id.name as string
683
+ else {
684
+ for (const spec of stmt.specifiers) {
685
+ if (spec.exportKind === 'type')
686
+ continue
687
+ const exported = exportedName(spec.exported)
688
+ const local = exportedName(spec.local)
689
+ if (exported !== undefined && local !== undefined) {
690
+ exportedNames.push(exported)
691
+ localExports.set(exported, local)
692
+ if (exported === 'default')
693
+ defaultLocal = local
694
+ if (exported === 'load')
695
+ hasLoadExport = true
696
+ if (exported === 'paths')
697
+ hasPaths = true
698
+ }
699
+ }
700
+ }
701
+ const decl = stmt.declaration
702
+ if (decl === null)
703
+ continue
704
+ if (decl.type === 'FunctionDeclaration' && decl.id !== null) {
705
+ if (decl.async === true)
706
+ asyncLocals.add(decl.id.name)
707
+ const name = decl.id.name
172
708
  exportedNames.push(name)
173
709
  if (name === 'load')
174
710
  hasLoadExport = true
175
711
  if (name === 'paths')
176
712
  hasPaths = true
177
713
  }
178
- else if (decl?.type === 'VariableDeclaration') {
179
- for (const d of decl.declarations as AstNode[]) {
180
- if (d.id?.type === 'Identifier') {
181
- const name = d.id.name as string
182
- exportedNames.push(name)
183
- if (name === 'load')
184
- hasLoadExport = true
185
- if (name === 'paths')
186
- hasPaths = true
187
- if (name === 'prerender' && d.init?.type === 'Literal' && d.init.value === true)
188
- hasPrerender = true
189
- if (name === 'hydrate' && d.init?.type === 'Literal' && typeof d.init.value === 'string')
190
- defaultHydrate = d.init.value
191
- if (d.init?.type === 'CallExpression' && d.init.callee?.type === 'Identifier' && d.init.callee.name === actionLocalName)
192
- exportedActions.push(name)
714
+ else if (decl.type === 'VariableDeclaration') {
715
+ collectInits(decl)
716
+ for (const d of decl.declarations) {
717
+ if (d.id.type !== 'Identifier')
718
+ continue
719
+ const name = d.id.name
720
+ exportedNames.push(name)
721
+ if (name === 'load')
722
+ hasLoadExport = true
723
+ if (name === 'paths')
724
+ hasPaths = true
725
+ if (name === 'prerender' && d.init?.type === 'Literal' && d.init.value === true)
726
+ hasPrerender = true
727
+ if (name === 'hydrate' && d.init?.type === 'Literal' && typeof d.init.value === 'string') {
728
+ checkHydrateMode(d.init.value, `hydrate = "${d.init.value}"`, filename)
729
+ defaultHydrate = d.init.value
730
+ }
731
+ if (d.init !== null && isIslandCall(d.init, islandLocalName, kayNamespaces) && d.init.arguments.length > 1)
732
+ throw mistake(`island() options on export ${name}`, filename, 'only the default export\'s island() options apply; export the island as default, or set $hydrate where it renders')
733
+ if (d.init !== null && isActionCall(d.init, actionLocalName, serverNamespaces)) {
734
+ exportedActions.push(name)
735
+ registeredActions.add(d.init)
193
736
  }
194
737
  }
195
738
  }
739
+ else if (decl.type === 'ClassDeclaration' && decl.id !== null) {
740
+ exportedNames.push(decl.id.name)
741
+ }
196
742
  }
197
743
  }
198
744
 
745
+ // Handle indirect `const C = island(Comp, { hydrate: 'visible' }); export default C`
746
+ if (defaultLocal !== undefined) {
747
+ const defInit = localInits.get(defaultLocal)
748
+ if (defInit !== undefined && isIslandCall(defInit, islandLocalName, kayNamespaces)) {
749
+ readIslandHydrate(defInit)
750
+ const target = defInit.arguments[0]
751
+ if (target !== undefined && isAsyncFunction(target))
752
+ hasAsyncDefault = true
753
+ }
754
+ }
755
+
756
+ // Pass 3: walk AST for JSX, mistakes, interactive handlers/refs, action() placement, namespace accesses.
199
757
  walk(program, (node) => {
200
- if (node.type === 'JSXElement' || node.type === 'JSXFragment')
758
+ if (isJsxNode(node))
201
759
  hasJsx = true
202
- if (node.type === 'JSXOpeningElement' && node.name?.type === 'JSXIdentifier') {
203
- const tag = node.name.name as string
204
- if (tag.charCodeAt(0) >= 65 && tag.charCodeAt(0) <= 90) {
205
- for (const attr of node.attributes as AstNode[]) {
206
- if (attr.type === 'JSXAttribute' && attr.name?.name === '$hydrate' && attr.value?.type === 'Literal' && typeof attr.value.value === 'string' && attr.value.value !== 'load')
760
+ if (node.type === 'JSXElement')
761
+ checkMistakes(node, filename, code, warnings)
762
+ if ((actionLocalName !== undefined || serverNamespaces.size > 0) && isActionCall(node, actionLocalName, serverNamespaces) && !registeredActions.has(node))
763
+ throw mistake('action() not declared as export const', filename, `write export const ${actionVariable(program, node) ?? 'name'} = ${actionLocalName ?? 'action'}(...) at the top level, only those get a URL`)
764
+ if (node.type === 'JSXOpeningElement') {
765
+ const tag = jsxTagName(node.name)
766
+ const isComponent = isComponentTag(tag)
767
+ if (isComponent) {
768
+ jsxTags.add(tag)
769
+ if (tag.includes('.')) {
770
+ const [ns, member] = tag.split('.')
771
+ if (ns !== undefined && kayNamespaces.has(ns) && member !== undefined && RENDER_CONTEXT_IMPORTS.has(member))
772
+ usesRenderContext = true
773
+ }
774
+ }
775
+ for (const attr of node.attributes) {
776
+ if (attr.type !== 'JSXAttribute' || attr.name.type !== 'JSXIdentifier')
777
+ continue
778
+ const attrName = attr.name.name
779
+ if (isComponent && attrName === '$hydrate') {
780
+ const mode = hydrateMode(attr.value)
781
+ checkHydrateMode(mode, `$hydrate="${mode}"`, filename)
782
+ hydrateModes.add(mode)
783
+ if (mode !== 'load')
207
784
  deferredIslandTags.add(tag)
208
785
  }
786
+ // A handler or ref on a component tag is a prop for that component; only a DOM element binds it in the browser.
787
+ if (!isComponent && tag !== '' && (EVENT_ATTR.test(attrName) || attrName === 'ref'))
788
+ markInteractive(`uses ${attrName}`, attr.start)
209
789
  }
210
790
  }
211
- if (node.type === 'JSXAttribute' && node.name?.type === 'JSXIdentifier') {
212
- const attrName = node.name.name as string
213
- if (EVENT_ATTR.test(attrName) || attrName === 'ref')
214
- markInteractive(`uses ${attrName}`)
791
+ if (node.type === 'MemberExpression' && !node.computed && node.object.type === 'Identifier' && kayNamespaces.has(node.object.name) && node.property.type === 'Identifier') {
792
+ const member = node.property.name
793
+ if (REACTIVE_IMPORTS.has(member))
794
+ markInteractive(`calls ${node.object.name}.${member}`, node.start)
795
+ if (STATE_PRIMITIVES.has(member))
796
+ stateCallees.add(`${node.object.name}.${member}`)
797
+ if (member === 'signal' || member === 'computed')
798
+ signalCallees.add(`${node.object.name}.${member}`)
799
+ if (RENDER_CONTEXT_IMPORTS.has(member))
800
+ usesRenderContext = true
215
801
  }
216
802
  })
217
803
 
218
- if (hasAsyncDefault && isInteractive) {
219
- throw new Error(
220
- `kay compiler: async route component in ${filename} cannot use browser interactivity (${interactiveReason}). Move interactive state/handlers into a non-async component and render it from the async page.`,
221
- )
804
+ checkBareSignals(program, signalCallees, filename)
805
+
806
+ for (const [name, init] of localInits) {
807
+ if (isAsyncFunction(init))
808
+ asyncLocals.add(name)
222
809
  }
810
+ if (defaultLocal !== undefined && asyncLocals.has(defaultLocal))
811
+ hasAsyncDefault = true
812
+
813
+ const isStateCall = (init: Node | undefined): boolean => {
814
+ if (init === undefined)
815
+ return false
816
+ const unwrapped = unwrapTsExpr(init)
817
+ if (unwrapped.type !== 'CallExpression')
818
+ return false
819
+ const callee = unwrapped.callee
820
+ const name = callee.type === 'Identifier'
821
+ ? callee.name
822
+ : callee.type === 'MemberExpression' && !callee.computed && callee.object.type === 'Identifier' && callee.property.type === 'Identifier'
823
+ ? `${callee.object.name}.${callee.property.name}`
824
+ : ''
825
+ return stateCallees.has(name)
826
+ }
827
+ const stateExportSet = new Set<string>()
828
+ for (const name of exportedNames) {
829
+ if (isStateCall(localInits.get(name)))
830
+ stateExportSet.add(name)
831
+ }
832
+ for (const [exported, local] of localExports) {
833
+ if (isStateCall(localInits.get(local)))
834
+ stateExportSet.add(exported)
835
+ }
836
+ const stateExports = [...stateExportSet]
837
+
838
+ if (hasAsyncDefault && isInteractive)
839
+ throw asyncInteractiveError(filename, interactiveReason)
840
+
841
+ const defaultDataKeys = isInteractive
842
+ ? analyzeDefaultDataKeys(program, defaultLocal, localInits, islandLocalName, kayNamespaces)
843
+ : undefined
223
844
 
224
845
  return {
225
846
  filename,
226
847
  program,
848
+ warnings,
227
849
  isInteractive,
228
850
  interactiveReason,
851
+ interactiveOffset,
229
852
  hasAsyncDefault,
230
- hasLoadExport,
853
+ hasLoadExport: hasLoadExport || loadDeclarations(program).length > 0,
231
854
  hasJsx,
855
+ jsxNodes: hasJsx ? computeJsxNodes(program) : new WeakSet<Node>(),
232
856
  hasPrerender,
233
857
  hasPaths,
234
858
  usesRenderContext,
235
859
  defaultHydrate,
236
860
  deferredIslandTags,
861
+ hydrateModes,
862
+ jsxTags,
863
+ stateExports,
864
+ defaultDataKeys,
237
865
  exportedActions,
238
866
  imports,
239
867
  reexports,
240
868
  exportedNames,
241
869
  }
242
870
  }
871
+
872
+ export type { OxcFunction }