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

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