@barefootjs/jsx 0.41.1 → 0.41.2

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 (96) hide show
  1. package/dist/adapters/attr-plan.d.ts +8 -0
  2. package/dist/adapters/attr-plan.d.ts.map +1 -1
  3. package/dist/adapters/component-props.d.ts.map +1 -1
  4. package/dist/adapters/computed-const.d.ts +19 -0
  5. package/dist/adapters/computed-const.d.ts.map +1 -1
  6. package/dist/adapters/dsl-template-adapter.d.ts +2 -1
  7. package/dist/adapters/dsl-template-adapter.d.ts.map +1 -1
  8. package/dist/adapters/inherited-const-server-read.d.ts +37 -0
  9. package/dist/adapters/inherited-const-server-read.d.ts.map +1 -0
  10. package/dist/adapters/loop-row-type.d.ts +18 -0
  11. package/dist/adapters/loop-row-type.d.ts.map +1 -1
  12. package/dist/adapters/non-primitive-equality.d.ts +8 -2
  13. package/dist/adapters/non-primitive-equality.d.ts.map +1 -1
  14. package/dist/adapters/unapplied-prop-default.d.ts +34 -0
  15. package/dist/adapters/unapplied-prop-default.d.ts.map +1 -0
  16. package/dist/adapters/uninlinable-seed-call.d.ts +29 -0
  17. package/dist/adapters/uninlinable-seed-call.d.ts.map +1 -0
  18. package/dist/analyzer.d.ts.map +1 -1
  19. package/dist/augment-inherited-props.d.ts +4 -22
  20. package/dist/augment-inherited-props.d.ts.map +1 -1
  21. package/dist/const-identity.d.ts +38 -0
  22. package/dist/const-identity.d.ts.map +1 -0
  23. package/dist/index.d.ts +9 -4
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +2328 -1340
  26. package/dist/ir-to-client-js/child-props-object.d.ts +39 -41
  27. package/dist/ir-to-client-js/child-props-object.d.ts.map +1 -1
  28. package/dist/ir-to-client-js/collect-elements.d.ts.map +1 -1
  29. package/dist/ir-to-client-js/component-scope.d.ts +13 -2
  30. package/dist/ir-to-client-js/component-scope.d.ts.map +1 -1
  31. package/dist/ir-to-client-js/control-flow/plan/build-inner-loop.d.ts.map +1 -1
  32. package/dist/ir-to-client-js/control-flow/plan/build-loop-child-arm.d.ts.map +1 -1
  33. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  34. package/dist/ir-to-client-js/prop-handling.d.ts.map +1 -1
  35. package/dist/jsx-to-ir.d.ts.map +1 -1
  36. package/dist/local-call-body.d.ts +112 -0
  37. package/dist/local-call-body.d.ts.map +1 -0
  38. package/dist/nullable-signal-attr.d.ts +10 -0
  39. package/dist/nullable-signal-attr.d.ts.map +1 -1
  40. package/dist/prop-default-resolution.d.ts +52 -0
  41. package/dist/prop-default-resolution.d.ts.map +1 -0
  42. package/dist/props-binding.d.ts +15 -0
  43. package/dist/props-binding.d.ts.map +1 -1
  44. package/dist/server-read-walk.d.ts +66 -0
  45. package/dist/server-read-walk.d.ts.map +1 -0
  46. package/dist/ssr-defaults.d.ts.map +1 -1
  47. package/dist/ssr-seed-plan.d.ts +24 -1
  48. package/dist/ssr-seed-plan.d.ts.map +1 -1
  49. package/dist/static-const-member.d.ts +92 -0
  50. package/dist/static-const-member.d.ts.map +1 -0
  51. package/dist/types.d.ts +45 -0
  52. package/dist/types.d.ts.map +1 -1
  53. package/package.json +2 -2
  54. package/src/__tests__/computed-const.test.ts +7 -1
  55. package/src/__tests__/const-identity-child-prop.test.ts +127 -0
  56. package/src/__tests__/inherited-const-server-read.test.ts +116 -0
  57. package/src/__tests__/issue-3688-props-spread-child-csr.test.ts +8 -3
  58. package/src/__tests__/issue-3714-open-rest-spread-child.test.ts +188 -0
  59. package/src/__tests__/local-call-body.test.ts +101 -0
  60. package/src/__tests__/prop-default-resolution.test.ts +185 -0
  61. package/src/__tests__/props-spread-shadowed.test.ts +113 -0
  62. package/src/__tests__/server-read-walk.test.ts +125 -0
  63. package/src/__tests__/ssr-defaults.test.ts +67 -7
  64. package/src/__tests__/static-record-literal-array.test.ts +82 -11
  65. package/src/adapters/attr-plan.ts +12 -1
  66. package/src/adapters/component-props.ts +2 -1
  67. package/src/adapters/computed-const.ts +108 -12
  68. package/src/adapters/dsl-template-adapter.ts +17 -4
  69. package/src/adapters/inherited-const-server-read.ts +174 -0
  70. package/src/adapters/loop-row-type.ts +69 -2
  71. package/src/adapters/non-primitive-equality.ts +17 -2
  72. package/src/adapters/unapplied-prop-default.ts +83 -0
  73. package/src/adapters/uninlinable-seed-call.ts +62 -0
  74. package/src/analyzer.ts +43 -3
  75. package/src/augment-inherited-props.ts +4 -49
  76. package/src/compiler.ts +4 -4
  77. package/src/const-identity.ts +189 -0
  78. package/src/index.ts +9 -4
  79. package/src/ir-to-client-js/child-props-object.ts +94 -62
  80. package/src/ir-to-client-js/collect-elements.ts +28 -22
  81. package/src/ir-to-client-js/component-scope.ts +16 -2
  82. package/src/ir-to-client-js/control-flow/plan/build-inner-loop.ts +1 -0
  83. package/src/ir-to-client-js/control-flow/plan/build-loop-child-arm.ts +1 -0
  84. package/src/ir-to-client-js/html-template.ts +24 -4
  85. package/src/ir-to-client-js/index.ts +2 -2
  86. package/src/ir-to-client-js/prop-handling.ts +4 -0
  87. package/src/jsx-to-ir.ts +23 -2
  88. package/src/local-call-body.ts +191 -0
  89. package/src/nullable-signal-attr.ts +39 -17
  90. package/src/prop-default-resolution.ts +195 -0
  91. package/src/props-binding.ts +16 -0
  92. package/src/server-read-walk.ts +174 -0
  93. package/src/ssr-defaults.ts +93 -10
  94. package/src/ssr-seed-plan.ts +104 -18
  95. package/src/static-const-member.ts +243 -0
  96. package/src/types.ts +45 -0
@@ -0,0 +1,191 @@
1
+ /**
2
+ * Zero-argument calls a template resolves to what the called function
3
+ * returns (#3721).
4
+ *
5
+ * A template has no binding for a component's or module's functions: the
6
+ * backend receives the props, not the JS scope. Every template adapter reads
7
+ * a zero-argument identifier call as a signal or memo getter (`count()` →
8
+ * `count`), so a call to a function (`function value() { return 1 }` called
9
+ * as `value()`) read a template variable of the function's name — nothing,
10
+ * or a prop of the same name, which a `(props)`-arg component flattens into
11
+ * the same template namespace.
12
+ *
13
+ * This is the one decision of what such a call reads, made in two steps.
14
+ * First the declaration the name denotes where the call is written
15
+ * ({@link localBindings}): a component-scope declaration of a name hides
16
+ * the module one, whatever either is, and a function body's names resolve
17
+ * in the scope the function is declared in. A prop counts as a component
18
+ * binding only where its bare name is in scope (`templatePropReadParams`):
19
+ * a destructured parameter, or a body binding that holds the prop. A typed
20
+ * prop the body never binds does not hide a function of its name, as in JS.
21
+ * Then what a call of that declaration is ({@link localCall}): inlined, for
22
+ * a function taking no parameters whose body is a single `return <expr>` (a
23
+ * `function` declaration's `FunctionInfo.returnParsed`, or a zero-param
24
+ * arrow `const`); refused, for any other function; neither, for a binding
25
+ * that is not a function. The consumers resolve the call through this
26
+ * table: the SSR seed plan (signal seeds, memo bodies), the static SSR
27
+ * defaults, the template adapters' shared inlining of markup expressions
28
+ * (`inlineComputedConsts`), and the walk of what a server-rendered position
29
+ * reads (`walkServerReads`).
30
+ */
31
+
32
+ import { freeIdentifiers, mapParsedExpr, zeroArgCallBody, type ParsedExpr } from './expression-parser.ts'
33
+ import { templatePropReadParams, type TemplatePropReadBindings } from './props-binding.ts'
34
+ import type { ConstantInfo, FunctionInfo, MemoInfo, SignalInfo } from './types.ts'
35
+
36
+ /** A scope a name is declared in, and a function body's names are read in. */
37
+ export type LocalScope = 'component' | 'module'
38
+
39
+ /** What a zero-argument call of a function returns, and where its body's names resolve. */
40
+ export interface LocalCallBody {
41
+ /** The returned expression. */
42
+ body: ParsedExpr
43
+ /** The scope the function is declared in, which the body's free names are read in. */
44
+ scope: LocalScope
45
+ }
46
+
47
+ /** The component bindings {@link localBindings} reads. */
48
+ export interface LocalCallBindings extends TemplatePropReadBindings {
49
+ localFunctions: readonly FunctionInfo[]
50
+ restPropsName?: string | null
51
+ signals: readonly SignalInfo[]
52
+ memos: readonly MemoInfo[]
53
+ }
54
+
55
+ /**
56
+ * What a name denotes in the scope it is declared in. `opaque` is a binding
57
+ * with no declaration to read: a prop in scope by its bare name, the props
58
+ * object, the rest props, a signal setter.
59
+ */
60
+ export type LocalBinding =
61
+ | { kind: 'signal'; scope: LocalScope; info: SignalInfo }
62
+ | { kind: 'memo'; scope: LocalScope; info: MemoInfo }
63
+ | { kind: 'const'; scope: LocalScope; info: ConstantInfo }
64
+ | { kind: 'function'; scope: LocalScope; info: FunctionInfo }
65
+ | { kind: 'opaque'; scope: LocalScope }
66
+
67
+ /** The declaration `name` denotes, read from `from`: `null` for a name neither scope declares. */
68
+ export type LocalBindingResolver = (name: string, from: LocalScope) => LocalBinding | null
69
+
70
+ /**
71
+ * The lexical resolution of a component's and its module's names. Read from
72
+ * the component scope, a component declaration of the name is the binding,
73
+ * and only a name the component does not declare reaches the module's; read
74
+ * from the module scope (a module function's body), only the module's is.
75
+ */
76
+ export function localBindings(b: LocalCallBindings): LocalBindingResolver {
77
+ const scopes = { component: new Map<string, LocalBinding>(), module: new Map<string, LocalBinding>() }
78
+ const bind = (name: string, binding: LocalBinding): void => {
79
+ scopes[binding.scope].set(name, binding)
80
+ }
81
+ for (const info of b.localFunctions) {
82
+ bind(info.name, { kind: 'function', scope: info.inComponentBody ? 'component' : 'module', info })
83
+ }
84
+ for (const info of b.localConstants) bind(info.name, { kind: 'const', scope: info.isModule ? 'module' : 'component', info })
85
+ for (const info of b.memos) bind(info.name, { kind: 'memo', scope: info.isModule ? 'module' : 'component', info })
86
+ for (const info of b.signals) {
87
+ const scope = info.isModule ? 'module' : 'component'
88
+ bind(info.getter, { kind: 'signal', scope, info })
89
+ if (info.setter) bind(info.setter, { kind: 'opaque', scope })
90
+ }
91
+ const props = [b.propsObjectName, b.restPropsName, ...templatePropReadParams(b).map(p => p.name)]
92
+ for (const name of props) if (name) bind(name, { kind: 'opaque', scope: 'component' })
93
+ return (name, from) => (from === 'component' ? scopes.component.get(name) : undefined) ?? scopes.module.get(name) ?? null
94
+ }
95
+
96
+ /**
97
+ * What a zero-argument call of `binding` is to a template: `inline` with the
98
+ * expression the function returns, `refuse` for a function a template
99
+ * cannot inline (one with parameters, a body other than a single `return`,
100
+ * an `async` / generator one, a reassigned arrow `const`), or `null` for a
101
+ * binding that is not such a function. A function returning JSX is inlined
102
+ * into the markup before any template reads it, and is `null` too.
103
+ */
104
+ export function localCall(binding: LocalBinding | null): { kind: 'inline'; body: ParsedExpr } | { kind: 'refuse' } | null {
105
+ if (binding?.kind === 'function') {
106
+ const f = binding.info
107
+ if (f.isJsxFunction || f.containsJsx || f.isMultiReturnJsxHelper) return null
108
+ return f.returnParsed ? { kind: 'inline', body: f.returnParsed } : { kind: 'refuse' }
109
+ }
110
+ if (binding?.kind !== 'const') return null
111
+ const c = binding.info
112
+ const body = arrowConstBody(c)
113
+ if (body) return { kind: 'inline', body }
114
+ if (c.declarationKind !== 'const' || c.parsed?.kind !== 'arrow' || c.isJsxFunction || c.isJsx) return null
115
+ return { kind: 'refuse' }
116
+ }
117
+
118
+ /**
119
+ * Each function name a zero-argument call written in `from` reads as a
120
+ * function whose returned expression a template can inline, with that
121
+ * expression ({@link inlinedBody}).
122
+ */
123
+ export function localCallBodies(b: LocalCallBindings, from: LocalScope = 'component'): ReadonlyMap<string, LocalCallBody> {
124
+ const resolve = localBindings(b)
125
+ const out = new Map<string, LocalCallBody>()
126
+ for (const name of callableNames(b)) {
127
+ const binding = resolve(name, from)
128
+ const body = binding && inlinedBody(binding, resolve, new Set())
129
+ if (binding && body) out.set(name, { body, scope: binding.scope })
130
+ }
131
+ return out
132
+ }
133
+
134
+ /**
135
+ * Each function name a zero-argument call written in `from` reads as a
136
+ * function a template cannot inline: {@link localCall}'s `refuse`, or a
137
+ * module function whose returned expression calls one. Read as a getter,
138
+ * such a call would render an unbound name or a prop of that name, so a
139
+ * template refuses it.
140
+ */
141
+ export function uninlinableLocalCalls(b: LocalCallBindings, from: LocalScope = 'component'): ReadonlySet<string> {
142
+ const resolve = localBindings(b)
143
+ const out = new Set<string>()
144
+ for (const name of callableNames(b)) {
145
+ const binding = resolve(name, from)
146
+ if (binding && localCall(binding) && !inlinedBody(binding, resolve, new Set())) out.add(name)
147
+ }
148
+ return out
149
+ }
150
+
151
+ /**
152
+ * The expression a zero-argument call of `binding` is inlined as, or `null`
153
+ * when a template cannot inline it.
154
+ *
155
+ * A component function's returned expression is read where the call is
156
+ * written (these tables serve the component scope), so it stands as it is.
157
+ * A module function's is not: each local function it calls is the module's,
158
+ * which a component declaration of the same name would replace once the
159
+ * expression sits in the component scope. Those calls are inlined here, in
160
+ * module scope, and one a template cannot inline (or a function calling
161
+ * itself) makes the caller uninlinable too.
162
+ */
163
+ function inlinedBody(binding: LocalBinding, resolve: LocalBindingResolver, running: ReadonlySet<LocalBinding>): ParsedExpr | null {
164
+ const call = localCall(binding)
165
+ if (call?.kind !== 'inline' || running.has(binding)) return null
166
+ if (binding.scope === 'component') return call.body
167
+ const inner = new Set(running).add(binding)
168
+ let inlinable = true
169
+ const body = mapParsedExpr(call.body, (e, enclosing) => {
170
+ if (e.kind !== 'call' || e.args.length > 0 || e.callee.kind !== 'identifier' || enclosing.has(e.callee.name)) return null
171
+ const callee = resolve(e.callee.name, 'module')
172
+ if (!callee || !localCall(callee)) return null
173
+ const inlined = inlinedBody(callee, resolve, inner)
174
+ // Inlined under a callback param of one of its names, the expression would read the param.
175
+ const free = inlined && freeIdentifiers(inlined)
176
+ if (!inlined || !free || [...free].some(name => enclosing.has(name))) inlinable = false
177
+ return inlined
178
+ })
179
+ return inlinable ? body : null
180
+ }
181
+
182
+ /** Every name a function declaration or a const binds, in either scope. */
183
+ function callableNames(b: LocalCallBindings): Set<string> {
184
+ return new Set([...b.localFunctions.map(f => f.name), ...b.localConstants.map(c => c.name)])
185
+ }
186
+
187
+ /** The body of a zero-param arrow `const` that is never reassigned, or `null`. */
188
+ function arrowConstBody(c: ConstantInfo): ParsedExpr | null {
189
+ if (c.declarationKind !== 'const' || c.mutatedAfterDeclaration || !c.parsed) return null
190
+ return zeroArgCallBody(c.parsed)
191
+ }
@@ -242,6 +242,16 @@ export interface NullishAttrContext {
242
242
  * ToNumber unless both sides are strings, so its nil's reading decides the
243
243
  * comparison (`undefined < 1` is false, `null < 1` is true). */
244
244
  readonly nullableScalarProps?: ReadonlyMap<string, NullableScalarProp>
245
+ /**
246
+ * Whether the value a read names at the attribute site is declared to
247
+ * admit `undefined` / `null` (#3728): a loop row's optional member
248
+ * (`r.tone` where the element type has `tone?: string`, a destructured
249
+ * `tone`, `r.meta.tone`). The adapter answers it from the declared types
250
+ * through its live `BindingScope` (`declaredValueMayBeNil`). Consulted for
251
+ * the attribute's own reads only, never inside a memo body, whose names
252
+ * resolve where the memo is declared.
253
+ */
254
+ readonly declaredNil?: (expr: ParsedExpr) => boolean
245
255
  }
246
256
 
247
257
  /** A string or boolean prop's nil reading ({@link NullishAttrContext.nullableScalarProps}). */
@@ -360,44 +370,56 @@ export function attrValueMayBeNullish(
360
370
  // `shadowed` is the scope the expression is read in: the attribute site's
361
371
  // loop bindings at the top level, none inside a memo body — its getters
362
372
  // resolve where the memo is declared, not where it is read.
363
- const walk = (expr: ParsedExpr, shadowed: (name: string) => boolean): boolean => {
373
+ // `atSite`: the expression is the attribute's own, read in the attribute
374
+ // site's scope, where the declared-type answer (`declaredNil`) applies.
375
+ const walk = (expr: ParsedExpr, shadowed: (name: string) => boolean, atSite = true): boolean => {
364
376
  if (readsUndefinedLeaf(expr, ctx, shadowed)) return true
377
+ if (atSite && ctx.declaredNil !== undefined && isPlainRead(expr) && ctx.declaredNil(expr)) return true
365
378
  switch (expr.kind) {
366
379
  case 'identifier':
367
380
  return expr.name === 'undefined'
368
381
  case 'literal':
369
382
  return expr.literalType === 'null'
370
- case 'call': {
371
- const getter = bareGetterCallName(expr)
372
- if (getter === null || shadowed(getter)) return false
373
- if (ctx.nullableSignals.has(getter)) return true
374
- const memo = ctx.memos.get(getter)
375
- if (!memo || visiting.has(getter)) return false
376
- if (admitsNullish(memo.type)) return true
377
- visiting.add(getter)
378
- const result = memo.parsed !== undefined && walk(memo.parsed, () => false)
379
- visiting.delete(getter)
380
- return result
381
- }
383
+ case 'call':
384
+ return getterMayBeNullish(expr, shadowed)
382
385
  // A computed key or an index (`pair[1]`, `row[key]`) reads `undefined`
383
386
  // when it is out of range or absent (#3497).
384
387
  case 'member':
385
- return expr.optional || expr.computed || walk(expr.object, shadowed)
388
+ return expr.optional || expr.computed || walk(expr.object, shadowed, atSite)
386
389
  case 'index-access':
387
390
  return true
388
391
  case 'conditional':
389
- return walk(expr.consequent, shadowed) || walk(expr.alternate, shadowed)
392
+ return walk(expr.consequent, shadowed, atSite) || walk(expr.alternate, shadowed, atSite)
390
393
  case 'logical':
391
394
  return expr.op === '&&'
392
- ? walk(expr.left, shadowed) || walk(expr.right, shadowed)
393
- : walk(expr.right, shadowed)
395
+ ? walk(expr.left, shadowed, atSite) || walk(expr.right, shadowed, atSite)
396
+ : walk(expr.right, shadowed, atSite)
394
397
  default:
395
398
  return false
396
399
  }
397
400
  }
401
+ // A nullable signal's getter, or a memo whose type or body can be nullish.
402
+ const getterMayBeNullish = (expr: ParsedExpr, shadowed: (name: string) => boolean): boolean => {
403
+ const getter = bareGetterCallName(expr)
404
+ if (getter === null || shadowed(getter)) return false
405
+ if (ctx.nullableSignals.has(getter)) return true
406
+ const memo = ctx.memos.get(getter)
407
+ if (!memo || visiting.has(getter)) return false
408
+ if (admitsNullish(memo.type)) return true
409
+ visiting.add(getter)
410
+ const result = memo.parsed !== undefined && walk(memo.parsed, () => false, false)
411
+ visiting.delete(getter)
412
+ return result
413
+ }
398
414
  return parsed !== undefined && walk(parsed, isShadowed)
399
415
  }
400
416
 
417
+ /** A bare name or a non-computed member path over one (`tone`, `r.tone`, `r.meta.tone`). */
418
+ function isPlainRead(expr: ParsedExpr): boolean {
419
+ if (expr.kind === 'identifier') return true
420
+ return expr.kind === 'member' && !expr.computed && isPlainRead(expr.object)
421
+ }
422
+
401
423
  /** A method call that can miss (`methodMayReturnUndefined`), or a read of a prop that can be absent. */
402
424
  function readsUndefinedLeaf(expr: ParsedExpr, ctx: NullishAttrContext, shadowed: (name: string) => boolean): boolean {
403
425
  return methodMayReturnUndefined(expr) || readsNullableProp(expr, ctx, shadowed)
@@ -0,0 +1,195 @@
1
+ /**
2
+ * What a computed destructure default evaluates, once the declarations it
3
+ * reads are resolved (#3725, #3791).
4
+ *
5
+ * A backend applies a computed default when it renders (the SSR seed plan's
6
+ * prop steps, Go's props constructor), and it receives the props, not the JS
7
+ * scope: a default naming a const (`const DEF = 'z'`, `{ b =
8
+ * DEF.toUpperCase() }`) or calling a function has nothing to read there.
9
+ * This is the one resolution of those names into the expression the default
10
+ * stands for, each name read lexically (`localBindings`):
11
+ *
12
+ * - A body destructure (`const { b = DEF } = props`) reads the component
13
+ * scope, where a component const hides a module const of its name.
14
+ * - A parameter destructure (`function C({ b = DEF })`) reads the module
15
+ * scope: a parameter default cannot see the body's declarations.
16
+ *
17
+ * A `const` is replaced by its own value resolved in the scope it is
18
+ * declared in, and a zero-argument call of a function a template inlines
19
+ * (`localCall`) by the expression it returns. A module value is taken only
20
+ * when nothing is left to read in it, so no name it reads can meet a
21
+ * component binding where it lands. What stays free is a prop, the props
22
+ * object, a global, or a module name no backend computes.
23
+ *
24
+ * A component-scope declaration that has no such value (a signal, a memo, a
25
+ * `let`, a mutated const, a function with parameters or statements, a const
26
+ * declared after the destructure, which JS has not initialized when the
27
+ * default runs) leaves the default with nothing a template can compute: it
28
+ * is `blocked`, and the adapters refuse it where the server render reads the
29
+ * prop (`refuseUnappliedPropDefaults`).
30
+ */
31
+
32
+ import { freeIdentifiers, mapParsedExpr, type ParsedExpr } from './expression-parser.ts'
33
+ import { localBindings, localCall, type LocalBinding, type LocalBindingResolver, type LocalScope } from './local-call-body.ts'
34
+ import { templatePropReadParams } from './props-binding.ts'
35
+ import type { IRMetadata, ParamInfo, Position, SourceLocation } from './types.ts'
36
+
37
+ /** A computed destructure default with the declarations it reads resolved. */
38
+ export interface ResolvedPropDefault {
39
+ /** The default as the expression it stands for. */
40
+ expr: ParsedExpr
41
+ /** Whether a declaration the default reads was resolved into `expr`. */
42
+ readsDeclaration: boolean
43
+ /** Where a body destructure binds the prop; unset for a parameter default. */
44
+ loc: SourceLocation | undefined
45
+ /** The component declarations it reads that have no value a template can compute. */
46
+ blocked: readonly string[]
47
+ }
48
+
49
+ /** The metadata {@link propDefaultResolver} reads. */
50
+ export type PropDefaultBindings = Pick<
51
+ IRMetadata,
52
+ 'propsParams' | 'propsObjectName' | 'restPropsName' | 'signals' | 'memos' | 'localFunctions' | 'localConstants'
53
+ >
54
+
55
+ /** One expression resolved in one scope. */
56
+ interface Resolution {
57
+ expr: ParsedExpr
58
+ blocked: Set<string>
59
+ /** Whether a declaration was resolved into `expr`. */
60
+ replaced: boolean
61
+ }
62
+
63
+ /** What a free name of an expression is replaced by. */
64
+ type Replacement =
65
+ | { kind: 'keep' }
66
+ | { kind: 'blocked' }
67
+ /** Every free read of the name. */
68
+ | { kind: 'value'; value: Resolution }
69
+ /** Only a call of the name with no arguments; any other read of it is `otherwise`. */
70
+ | { kind: 'call'; value: Resolution; otherwise: 'keep' | 'blocked' }
71
+
72
+ /**
73
+ * The resolver of a component's destructure defaults: `p`'s default as the
74
+ * expression it stands for ({@link ResolvedPropDefault}), or `null` for a
75
+ * prop with no parsed default.
76
+ */
77
+ export function propDefaultResolver(metadata: PropDefaultBindings): (p: ParamInfo) => ResolvedPropDefault | null {
78
+ const bindings = { ...metadata, localConstants: metadata.localConstants ?? [] }
79
+ const resolve = localBindings(bindings)
80
+ const props = new Set<string>(templatePropReadParams(bindings).map(p => p.name))
81
+ if (metadata.propsObjectName) props.add(metadata.propsObjectName)
82
+ if (metadata.restPropsName) props.add(metadata.restPropsName)
83
+ const bodyBound = new Map<string, SourceLocation>()
84
+ for (const c of bindings.localConstants) if (!c.isModule && c.propsDestructure) bodyBound.set(c.name, c.loc)
85
+ return (p) => {
86
+ if (p.isRest || !p.parsed) return null
87
+ const loc = bodyBound.get(p.name)
88
+ const resolver = new DeclarationResolver(resolve, props, loc?.start)
89
+ const { expr, blocked, replaced } = resolver.resolveExpr(p.parsed, loc ? 'component' : 'module', true)
90
+ return { expr, blocked: [...blocked], readsDeclaration: replaced, loc }
91
+ }
92
+ }
93
+
94
+ /** Resolves one default through the declarations it reads, each declaration once. */
95
+ class DeclarationResolver {
96
+ private readonly values = new Map<LocalBinding['scope'], Map<string, Resolution | null>>([
97
+ ['component', new Map()],
98
+ ['module', new Map()],
99
+ ])
100
+
101
+ constructor(
102
+ private readonly resolve: LocalBindingResolver,
103
+ /** The names a template reads as props, which hide a module declaration of the name. */
104
+ private readonly props: ReadonlySet<string>,
105
+ /** Where the body destructure holding the default starts: a component const declared from there on is not initialized yet. */
106
+ private readonly runsAt: Position | undefined,
107
+ ) {}
108
+
109
+ /**
110
+ * `expr` with each free name read from `scope` replaced by what it
111
+ * denotes. `propsInScope` is whether the expression sits where the props
112
+ * are bound (a default, a component declaration), not in a module one.
113
+ */
114
+ resolveExpr(expr: ParsedExpr, scope: LocalScope, propsInScope: boolean): Resolution {
115
+ const blocked = new Set<string>()
116
+ const free = freeIdentifiers(expr)
117
+ if (!free) return { expr, blocked, replaced: false }
118
+ const replacements = new Map<string, Replacement>()
119
+ for (const name of free) {
120
+ const replacement = propsInScope && this.props.has(name) ? KEEP : this.replacementOf(name, scope)
121
+ if (replacement.kind !== 'keep') replacements.set(name, replacement)
122
+ }
123
+ if (replacements.size === 0) return { expr, blocked, replaced: false }
124
+ let replaced = false
125
+ // A value landing under a callback param of one of its own names would read the param.
126
+ const take = (name: string, value: Resolution, enclosing: ReadonlySet<string>): ParsedExpr | null => {
127
+ const reads = freeIdentifiers(value.expr)
128
+ if (!reads || [...reads].some(read => enclosing.has(read))) {
129
+ blocked.add(name)
130
+ return null
131
+ }
132
+ for (const b of value.blocked) blocked.add(b)
133
+ replaced = true
134
+ return value.expr
135
+ }
136
+ const resolved = mapParsedExpr(expr, (e, enclosing) => {
137
+ if (e.kind === 'call' && e.args.length === 0 && e.callee.kind === 'identifier' && !enclosing.has(e.callee.name)) {
138
+ const r = replacements.get(e.callee.name)
139
+ if (r?.kind === 'call') return take(e.callee.name, r.value, enclosing)
140
+ }
141
+ if (e.kind !== 'identifier' || enclosing.has(e.name)) return null
142
+ const r = replacements.get(e.name)
143
+ if (r?.kind === 'value') return take(e.name, r.value, enclosing)
144
+ if (r?.kind === 'blocked' || (r?.kind === 'call' && r.otherwise === 'blocked')) blocked.add(e.name)
145
+ return null
146
+ })
147
+ return { expr: replaced ? resolved : expr, blocked, replaced }
148
+ }
149
+
150
+ /** What a free read of `name` from `scope` is replaced by. */
151
+ private replacementOf(name: string, scope: LocalScope): Replacement {
152
+ const binding = this.resolve(name, scope)
153
+ if (!binding || binding.kind === 'opaque') return KEEP
154
+ // A module declaration no backend computes stays a name, as before.
155
+ const otherwise = binding.scope === 'component' ? 'blocked' : 'keep'
156
+ if (binding.kind === 'const' && binding.scope === 'component' && !this.isInitialized(binding.info.loc?.start)) return { kind: 'blocked' }
157
+ const call = localCall(binding)
158
+ if (call) {
159
+ const value = call.kind === 'inline' ? this.valueOf(name, binding, call.body) : null
160
+ return value ? { kind: 'call', value, otherwise } : { kind: otherwise }
161
+ }
162
+ const value = binding.kind === 'const' && isStableConst(binding) ? this.valueOf(name, binding, binding.info.parsed!) : null
163
+ return value ? { kind: 'value', value } : { kind: otherwise }
164
+ }
165
+
166
+ /** Whether a component const declared at `declared` holds its value when the default runs. */
167
+ private isInitialized(declared: Position | undefined): boolean {
168
+ const at = this.runsAt
169
+ return !at || !declared || declared.line < at.line || (declared.line === at.line && declared.column < at.column)
170
+ }
171
+
172
+ /**
173
+ * The value `binding` (declared as `name`) holds, resolved in its own
174
+ * scope: `null` for a module value that still reads something, or one
175
+ * that reads itself.
176
+ */
177
+ private valueOf(name: string, binding: LocalBinding, expr: ParsedExpr): Resolution | null {
178
+ const known = this.values.get(binding.scope)!
179
+ if (known.has(name)) return known.get(name) ?? null
180
+ known.set(name, null)
181
+ const value = this.resolveExpr(expr, binding.scope, binding.scope === 'component')
182
+ const closed = binding.scope === 'component' || freeIdentifiers(value.expr)?.size === 0
183
+ const result = closed ? value : null
184
+ known.set(name, result)
185
+ return result
186
+ }
187
+ }
188
+
189
+ const KEEP: Replacement = { kind: 'keep' }
190
+
191
+ /** A `const` holding the one value its initializer gives it, which a template can read in its place. */
192
+ function isStableConst(binding: Extract<LocalBinding, { kind: 'const' }>): boolean {
193
+ const c = binding.info
194
+ return c.declarationKind === 'const' && !c.mutatedAfterDeclaration && c.parsed !== undefined && !c.isJsx && !c.isJsxFunction
195
+ }
@@ -619,6 +619,22 @@ export interface RestSpreadBindings {
619
619
  propsObjectName: string | null
620
620
  }
621
621
 
622
+ /**
623
+ * The caller keys the component's rest bag (`...rest`) leaves out: the keys
624
+ * its destructure takes before the rest element, spelled as the caller
625
+ * passes them. A body destructure of the props object (`const { a, ...rest }
626
+ * = props`) records them itself (`restPropsOmittedKeys`); a signature rest
627
+ * takes every destructured param, by its source key (`{ value: v }` takes
628
+ * `value`). The one definition `SpreadAttr.restOmittedKeys` is built from.
629
+ */
630
+ export function restBagOmittedKeys(bindings: {
631
+ propsParams: ReadonlyArray<{ name: string; sourceName?: string }>
632
+ restPropsOmittedKeys?: readonly string[] | null
633
+ }): string[] {
634
+ if (bindings.restPropsOmittedKeys) return [...bindings.restPropsOmittedKeys]
635
+ return bindings.propsParams.map(p => p.sourceName ?? p.name)
636
+ }
637
+
622
638
  /**
623
639
  * Walks a bare `const x__alias = <name>` hop chain recorded in
624
640
  * `constantValues` (name → initializer text) until `terminal` recognizes
@@ -0,0 +1,174 @@
1
+ /**
2
+ * The declarations a component's server render reads (#3721).
3
+ *
4
+ * A template renders a position from the values it reads there, and each of
5
+ * those from the values its own expression reads: a signal's seed, a memo's
6
+ * body, a const's initializer, the expression a called function returns.
7
+ * This is the one walk of that relation. It starts at every template
8
+ * position (`walkTemplatePositions`, which skips `/* @client *\/` reads) and
9
+ * follows the names each expression reads free, each resolved lexically
10
+ * (`localBindings`): a position's names in the scope it is read in, so a
11
+ * loop row, a callback param or a preamble local of a name is not the
12
+ * component's declaration of it (`BindingScope`); a declaration's names in
13
+ * the scope it is declared in, so a module function's body never reads a
14
+ * component binding.
15
+ *
16
+ * A function is read only where it is called with no arguments and a
17
+ * template inlines the call (`localCall`): its returned expression is then
18
+ * followed like any other. A call a template cannot inline ends the walk
19
+ * there and is reported on the declaration that makes it
20
+ * (`ServerRead.refusedCalls`). A function passed on uncalled, an event
21
+ * handler prop and a module-scope signal or memo (which never renders on the
22
+ * server) read nothing here.
23
+ */
24
+
25
+ import { freeIdentifiers, mapParsedExpr, type ParsedExpr, type ParsedStatement } from './expression-parser.ts'
26
+ import { isEventHandlerName } from './event-handler-name.ts'
27
+ import { localBindings, localCall, type LocalBinding, type LocalBindingResolver, type LocalScope } from './local-call-body.ts'
28
+ import { BindingScope } from './scope/binding-scope.ts'
29
+ import { walkTemplatePositions, type TemplatePosition } from './template-position-walk.ts'
30
+ import type { ComponentIR, SourceLocation } from './types.ts'
31
+
32
+ /** A declaration the server render reads. */
33
+ export interface ServerRead {
34
+ name: string
35
+ kind: 'signal' | 'memo' | 'const' | 'function'
36
+ /** The scope the declaration sits in. */
37
+ scope: LocalScope
38
+ loc: SourceLocation
39
+ /**
40
+ * The expression its value comes from (a called function's returned
41
+ * expression), read in `scope`. Unset for a declaration with no
42
+ * expression tree (a block-bodied memo no single expression stands for).
43
+ */
44
+ expr: ParsedExpr | undefined
45
+ /**
46
+ * The statements of a block-bodied memo with no `expr`, as far as its
47
+ * parse represents them. No server value is computed from them, but they
48
+ * are what the browser evaluates for the same slot.
49
+ */
50
+ block: readonly ParsedStatement[] | undefined
51
+ /**
52
+ * The functions its expression calls with no arguments that a template
53
+ * cannot inline, by the name they are called under. Empty for a
54
+ * declaration with no expression tree (a block-bodied memo).
55
+ */
56
+ refusedCalls: readonly string[]
57
+ }
58
+
59
+ /** What one expression reads: its free names, and those it calls with no arguments. */
60
+ interface Reads {
61
+ names: Iterable<string>
62
+ called: ReadonlySet<string>
63
+ }
64
+
65
+ /** A declaration the walk follows, with the expression its value comes from. */
66
+ interface Followed {
67
+ kind: ServerRead['kind']
68
+ loc: SourceLocation
69
+ expr: ParsedExpr | undefined
70
+ block?: readonly ParsedStatement[]
71
+ /** The names the declaration reads when its expression has no tree. */
72
+ fallback: ReadonlySet<string> | undefined
73
+ }
74
+
75
+ /** What {@link walkServerReads} reports besides the declarations, and where it starts. */
76
+ export interface ServerReadWalkOptions {
77
+ /**
78
+ * Sees each name read that has no declaration to follow: a prop in scope
79
+ * by its bare name, the props object, the rest props.
80
+ */
81
+ visitProp?: (name: string) => void
82
+ /** The positions the walk starts from; every position when unset. */
83
+ startsAt?: (position: TemplatePosition) => boolean
84
+ }
85
+
86
+ /** Visit each declaration the server render of `ir` reads, once. */
87
+ export function walkServerReads(ir: ComponentIR, visit: (read: ServerRead) => void, options: ServerReadWalkOptions = {}): void {
88
+ const { visitProp, startsAt } = options
89
+ const resolve = localBindings({ ...ir.metadata, localConstants: ir.metadata.localConstants ?? [] })
90
+ const seen = new Set<LocalBinding>()
91
+ const pending: Array<{ reads: Reads; from: LocalScope }> = []
92
+
93
+ const follow = (name: string, binding: LocalBinding): void => {
94
+ const followed = followedDeclaration(binding)
95
+ if (!followed || seen.has(binding)) return
96
+ seen.add(binding)
97
+ const reads = readsOf(followed.expr, followed.fallback)
98
+ const refusedCalls = [...reads.called].filter(fn => localCall(resolve(fn, binding.scope))?.kind === 'refuse')
99
+ visit({ name, kind: followed.kind, scope: binding.scope, loc: followed.loc, expr: followed.expr, block: followed.block, refusedCalls })
100
+ pending.push({ reads, from: binding.scope })
101
+ }
102
+ const followReads = (reads: Reads, from: LocalScope, isBound: (name: string) => boolean): void => {
103
+ for (const name of reads.names) {
104
+ if (isBound(name)) continue
105
+ const binding = resolve(name, from)
106
+ if (binding?.kind === 'opaque') visitProp?.(name)
107
+ else if (binding && isRead(binding, reads.called.has(name))) follow(name, binding)
108
+ }
109
+ }
110
+
111
+ const component = BindingScope.forComponent(ir.metadata.propsObjectName ?? null)
112
+ walkTemplatePositions(ir.root, (position) => {
113
+ const { expr, scope, attrName } = position
114
+ if (attrName !== undefined && isEventHandlerName(attrName)) return
115
+ if (startsAt && !startsAt(position)) return
116
+ followReads(readsOf(expr, undefined), 'component', name => (scope ?? component).isBound(name))
117
+ }, component)
118
+ for (let next = pending.pop(); next; next = pending.pop()) followReads(next.reads, next.from, () => false)
119
+ }
120
+
121
+ /** Whether reading `binding` reads its declaration: a function only where it is called. */
122
+ function isRead(binding: LocalBinding, called: boolean): boolean {
123
+ if (binding.kind === 'function' || (binding.kind === 'const' && binding.info.parsed?.kind === 'arrow')) {
124
+ return called && localCall(binding)?.kind === 'inline'
125
+ }
126
+ return true
127
+ }
128
+
129
+ /** {@link Followed} for `binding`, or `null` for one with nothing the server render computes. */
130
+ function followedDeclaration(binding: LocalBinding): Followed | null {
131
+ switch (binding.kind) {
132
+ case 'opaque':
133
+ return null
134
+ case 'signal': {
135
+ const s = binding.info
136
+ if (s.isModule || s.envReader) return null
137
+ return { kind: 'signal', loc: s.loc, expr: s.parsed, fallback: s.initialFreeIdentifiers }
138
+ }
139
+ case 'memo': {
140
+ const m = binding.info
141
+ if (m.isModule) return null
142
+ const block = m.parsed ? undefined : m.parsedBlock
143
+ return { kind: 'memo', loc: m.loc, expr: m.parsed, block, fallback: m.computationFreeIdentifiers }
144
+ }
145
+ case 'const': {
146
+ const c = binding.info
147
+ // JSX is inlined into the markup, where the positions already read it.
148
+ if (c.isJsx || c.isJsxFunction) return null
149
+ const call = localCall(binding)
150
+ const expr = call?.kind === 'inline' ? call.body : c.parsed
151
+ return { kind: call ? 'function' : 'const', loc: c.loc, expr, fallback: c.freeIdentifiers }
152
+ }
153
+ case 'function': {
154
+ const call = localCall(binding)
155
+ if (call?.kind !== 'inline') return null
156
+ return { kind: 'function', loc: binding.info.loc, expr: call.body, fallback: undefined }
157
+ }
158
+ }
159
+ }
160
+
161
+ /** {@link Reads} of `expr`, or of `fallback` (calling nothing) when it has no analyzable tree. */
162
+ function readsOf(expr: ParsedExpr | undefined, fallback: ReadonlySet<string> | undefined): Reads {
163
+ const names = expr && freeIdentifiers(expr)
164
+ // An IR that went through JSON holds no `Set`: such a declaration reads nothing here.
165
+ if (!expr || !names) return { names: fallback instanceof Set ? fallback : [], called: new Set() }
166
+ const called = new Set<string>()
167
+ mapParsedExpr(expr, (e, enclosing) => {
168
+ if (e.kind === 'call' && e.args.length === 0 && e.callee.kind === 'identifier' && !enclosing.has(e.callee.name)) {
169
+ called.add(e.callee.name)
170
+ }
171
+ return null
172
+ })
173
+ return { names, called }
174
+ }