@barefootjs/jsx 0.41.1 → 0.41.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 (105) 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/caller-value-reach.d.ts +57 -0
  22. package/dist/caller-value-reach.d.ts.map +1 -0
  23. package/dist/const-identity.d.ts +38 -0
  24. package/dist/const-identity.d.ts.map +1 -0
  25. package/dist/index.d.ts +10 -5
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +2685 -1381
  28. package/dist/ir-to-client-js/child-props-object.d.ts +39 -41
  29. package/dist/ir-to-client-js/child-props-object.d.ts.map +1 -1
  30. package/dist/ir-to-client-js/collect-elements.d.ts.map +1 -1
  31. package/dist/ir-to-client-js/component-scope.d.ts +13 -2
  32. package/dist/ir-to-client-js/component-scope.d.ts.map +1 -1
  33. package/dist/ir-to-client-js/control-flow/plan/build-inner-loop.d.ts.map +1 -1
  34. package/dist/ir-to-client-js/control-flow/plan/build-loop-child-arm.d.ts.map +1 -1
  35. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  36. package/dist/ir-to-client-js/prop-handling.d.ts.map +1 -1
  37. package/dist/jsx-to-ir.d.ts.map +1 -1
  38. package/dist/local-call-body.d.ts +112 -0
  39. package/dist/local-call-body.d.ts.map +1 -0
  40. package/dist/nullable-signal-attr.d.ts +10 -0
  41. package/dist/nullable-signal-attr.d.ts.map +1 -1
  42. package/dist/prop-default-resolution.d.ts +52 -0
  43. package/dist/prop-default-resolution.d.ts.map +1 -0
  44. package/dist/props-binding.d.ts +15 -0
  45. package/dist/props-binding.d.ts.map +1 -1
  46. package/dist/server-read-walk.d.ts +66 -0
  47. package/dist/server-read-walk.d.ts.map +1 -0
  48. package/dist/ssr-defaults.d.ts.map +1 -1
  49. package/dist/ssr-seed-plan.d.ts +24 -1
  50. package/dist/ssr-seed-plan.d.ts.map +1 -1
  51. package/dist/static-const-member.d.ts +92 -0
  52. package/dist/static-const-member.d.ts.map +1 -0
  53. package/dist/static-literal.d.ts +21 -1
  54. package/dist/static-literal.d.ts.map +1 -1
  55. package/dist/types.d.ts +63 -0
  56. package/dist/types.d.ts.map +1 -1
  57. package/package.json +2 -2
  58. package/src/__tests__/computed-const.test.ts +7 -1
  59. package/src/__tests__/const-identity-child-prop.test.ts +127 -0
  60. package/src/__tests__/inherited-const-server-read.test.ts +116 -0
  61. package/src/__tests__/issue-3688-props-spread-child-csr.test.ts +8 -3
  62. package/src/__tests__/issue-3714-open-rest-spread-child.test.ts +188 -0
  63. package/src/__tests__/local-call-body.test.ts +101 -0
  64. package/src/__tests__/loop-branch-bare-expression-reactive-text.test.ts +212 -56
  65. package/src/__tests__/nested-loop-conditional.test.ts +16 -16
  66. package/src/__tests__/prop-default-resolution.test.ts +185 -0
  67. package/src/__tests__/props-spread-shadowed.test.ts +113 -0
  68. package/src/__tests__/server-read-walk.test.ts +125 -0
  69. package/src/__tests__/ssr-defaults.test.ts +67 -7
  70. package/src/__tests__/static-literal.test.ts +47 -2
  71. package/src/__tests__/static-record-literal-array.test.ts +82 -11
  72. package/src/adapters/attr-plan.ts +12 -1
  73. package/src/adapters/component-props.ts +2 -1
  74. package/src/adapters/computed-const.ts +108 -12
  75. package/src/adapters/dsl-template-adapter.ts +17 -4
  76. package/src/adapters/inherited-const-server-read.ts +174 -0
  77. package/src/adapters/loop-row-type.ts +69 -2
  78. package/src/adapters/non-primitive-equality.ts +17 -2
  79. package/src/adapters/unapplied-prop-default.ts +83 -0
  80. package/src/adapters/uninlinable-seed-call.ts +62 -0
  81. package/src/analyzer.ts +43 -3
  82. package/src/augment-inherited-props.ts +4 -49
  83. package/src/caller-value-reach.ts +436 -0
  84. package/src/compiler.ts +4 -4
  85. package/src/const-identity.ts +189 -0
  86. package/src/index.ts +10 -5
  87. package/src/ir-to-client-js/child-props-object.ts +94 -62
  88. package/src/ir-to-client-js/collect-elements.ts +53 -68
  89. package/src/ir-to-client-js/component-scope.ts +16 -2
  90. package/src/ir-to-client-js/control-flow/plan/build-inner-loop.ts +1 -0
  91. package/src/ir-to-client-js/control-flow/plan/build-loop-child-arm.ts +1 -0
  92. package/src/ir-to-client-js/html-template.ts +24 -4
  93. package/src/ir-to-client-js/index.ts +2 -2
  94. package/src/ir-to-client-js/prop-handling.ts +4 -0
  95. package/src/jsx-to-ir.ts +40 -2
  96. package/src/local-call-body.ts +191 -0
  97. package/src/nullable-signal-attr.ts +39 -17
  98. package/src/prop-default-resolution.ts +195 -0
  99. package/src/props-binding.ts +16 -0
  100. package/src/server-read-walk.ts +174 -0
  101. package/src/ssr-defaults.ts +93 -10
  102. package/src/ssr-seed-plan.ts +104 -18
  103. package/src/static-const-member.ts +243 -0
  104. package/src/static-literal.ts +55 -1
  105. package/src/types.ts +63 -1
@@ -20,6 +20,9 @@ import { freeIdentifiers, inlineBinding, mapParsedExpr, parseExpression, stringi
20
20
  import type { ConstantInfo, ExpressionAttr, IRMetadata, ParamInfo } from '../types.ts'
21
21
  import { componentBindings } from '../relocate.ts'
22
22
  import { PROPS_OBJECT_IDENTIFIER } from '../scope/binding-scope.ts'
23
+ import { readLiteralMember } from '../static-const-member.ts'
24
+ import { localCallBodies, uninlinableLocalCalls, type LocalCallBody } from '../local-call-body.ts'
25
+ import { templatePropReadParams } from '../props-binding.ts'
23
26
 
24
27
  export interface ComputedConstContext {
25
28
  constants: IRMetadata['localConstants'] | undefined
@@ -38,6 +41,24 @@ export interface ComputedConstContext {
38
41
  propReads: ReadonlyMap<string, string>
39
42
  /** Component-scope local functions, which shadow a module const of the same name. */
40
43
  localFunctions: ReadonlySet<string>
44
+ /**
45
+ * The functions whose zero-argument call a template reads as the
46
+ * expression they return (`localCallBodies`, #3721).
47
+ */
48
+ calls: ReadonlyMap<string, LocalCallBody>
49
+ /**
50
+ * Typed props a template holds under their name although no component
51
+ * binding of that name is the prop: a `(props)`-arg component's prop the
52
+ * body never binds (`templatePropReadParams`). A const of such a name,
53
+ * read by its name, would read the prop, so it is always inlined.
54
+ */
55
+ propNamed: ReadonlySet<string>
56
+ /**
57
+ * The functions whose zero-argument call a template cannot inline
58
+ * (`uninlinableLocalCalls`): read as a getter, the call would render an
59
+ * unbound name or a prop of that name, so it is refused.
60
+ */
61
+ uninlinableCalls: ReadonlySet<string>
41
62
  /**
42
63
  * Names the component scope lexically binds (the props object, destructured
43
64
  * and rest props, its consts, local functions, signals, memos), which
@@ -74,6 +95,9 @@ export function computedConstContext(
74
95
  propsBindings: propsBindingNames(metadata),
75
96
  propReads: propReadKeys(metadata, bindings),
76
97
  localFunctions: new Set(metadata.localFunctions.filter(f => !f.isModule).map(f => f.name)),
98
+ calls: localCallBodies(metadata),
99
+ propNamed: propNamedBindings(metadata),
100
+ uninlinableCalls: uninlinableLocalCalls(metadata),
77
101
  componentNames: componentScopeNames(metadata),
78
102
  props: { params: metadata.propsParams, objectName: metadata.propsObjectName },
79
103
  isShadowed,
@@ -82,6 +106,13 @@ export function computedConstContext(
82
106
  }
83
107
  }
84
108
 
109
+ /** {@link ComputedConstContext.propNamed}. */
110
+ function propNamedBindings(metadata: IRMetadata): Set<string> {
111
+ if (metadata.propsObjectName === null) return new Set()
112
+ const inScope = new Set(templatePropReadParams(metadata).map(p => p.name))
113
+ return new Set(metadata.propsParams.filter(p => !p.isRest && !inScope.has(p.name)).map(p => p.name))
114
+ }
115
+
85
116
  /**
86
117
  * Consts a props destructure binds (`const { label: text = 'none' } = props`).
87
118
  * The analyzer records each as a props param, renamed and defaulted, and the
@@ -165,7 +196,7 @@ const MAX_DEPTH = 16
165
196
  * repeated so a const read inside an initializer is replaced too.
166
197
  */
167
198
  export function inlineComputedConsts(expr: ParsedExpr, ctx: ComputedConstContext | null): ParsedExpr {
168
- if (!ctx?.constants?.length) return expr
199
+ if (!ctx || (!ctx.constants?.length && ctx.calls.size === 0 && ctx.uninlinableCalls.size === 0)) return expr
169
200
  let current = expr
170
201
  for (let depth = 0; depth < MAX_DEPTH; depth++) {
171
202
  const next = inlineOnce(current, ctx)
@@ -180,6 +211,15 @@ function inlineOnce(expr: ParsedExpr, ctx: ComputedConstContext): ParsedExpr {
180
211
  if (!free) return expr
181
212
  let result = expr
182
213
  for (const name of free) {
214
+ const call = callBody(name, ctx)
215
+ if (call) {
216
+ result = inlineZeroArgCalls(result, name, call)
217
+ continue
218
+ }
219
+ if (ctx.uninlinableCalls.has(name) && !ctx.isShadowed(name)) {
220
+ result = inlineZeroArgCalls(result, name, uninlinableCall(name))
221
+ continue
222
+ }
183
223
  const object = objectConstInitializer(name, ctx)
184
224
  if (object) {
185
225
  result = projectObjectReads(result, name, object, ctx) ?? result
@@ -192,6 +232,43 @@ function inlineOnce(expr: ParsedExpr, ctx: ComputedConstContext): ParsedExpr {
192
232
  return result
193
233
  }
194
234
 
235
+ /**
236
+ * What a zero-argument call of `name` returns, resolved in the scope the
237
+ * function is declared in, or `null` when a call of it stays as written: a
238
+ * loop row or callback binds the name where the expression is read, or the
239
+ * adapter binds it itself.
240
+ */
241
+ function callBody(name: string, ctx: ComputedConstContext): ParsedExpr | null {
242
+ const call = ctx.calls.get(name)
243
+ if (!call || ctx.isShadowed(name) || (ctx.isAdapterBound(name) && !ctx.propNamed.has(name))) return null
244
+ return resolveInitializer(call.body, ctx, n => ctx.isShadowed(n), call.scope)
245
+ }
246
+
247
+ /** The refusal a zero-argument call of the function `name` reads as ({@link ComputedConstContext.uninlinableCalls}). */
248
+ function uninlinableCall(name: string): ParsedExpr {
249
+ return {
250
+ kind: 'unsupported',
251
+ raw: `${name}()`,
252
+ reason: `'${name}' is a function a template cannot call: only one that takes no parameters and whose body is a single 'return <expr>' is read in a template, as the expression it returns`,
253
+ }
254
+ }
255
+
256
+ /**
257
+ * `expr` with each zero-argument call of `name` replaced by `body`, except
258
+ * where an enclosing callback binds `name` (the call is the param's) or one
259
+ * of `body`'s free names (the substitution would read the param).
260
+ */
261
+ function inlineZeroArgCalls(expr: ParsedExpr, name: string, body: ParsedExpr): ParsedExpr {
262
+ // A refusal reads nothing; any other body whose names are unknown stays out.
263
+ const bodyFree = body.kind === 'unsupported' ? new Set<string>() : freeIdentifiers(body)
264
+ if (!bodyFree) return expr
265
+ return mapParsedExpr(expr, (e, enclosing) => {
266
+ if (e.kind !== 'call' || e.args.length > 0 || e.callee.kind !== 'identifier' || e.callee.name !== name) return null
267
+ if (enclosing.has(name) || [...bodyFree].some(n => enclosing.has(n))) return null
268
+ return body
269
+ })
270
+ }
271
+
195
272
  /**
196
273
  * {@link inlineBinding} for an initializer a callback param inside `expr`
197
274
  * would capture (`rows.filter(a => a !== b)` with `const b = a`): the
@@ -307,7 +384,7 @@ function constValue(
307
384
  // A props destructure const is the component's; a module const of that name is not one.
308
385
  if (!constant || !init || (!constant.isModule && ctx.propsBindings.has(constant.name))) return null
309
386
  const literal = lookupLiteralConst(constant.name, [constant], () => false) !== null
310
- if (!literal && !(isPlainComputedConst(constant, init) && callsOnlyGetters(init, constant.isModule ? new Set() : ctx.getters))) return null
387
+ if (!literal && !(isPlainComputedConst(constant, init) && callsOnlyReadable(init, constant, constant.isModule ? new Set() : ctx.getters, ctx))) return null
311
388
  return resolveInitializer(init, ctx, captured, constant.isModule ? 'module' : 'component', depth + 1)
312
389
  }
313
390
 
@@ -344,10 +421,13 @@ function inlinableInitializer(name: string, ctx: ComputedConstContext): ParsedEx
344
421
  const init = constant?.parsed
345
422
  if (!constant || !init || !isPlainComputedConst(constant, init)) return null
346
423
  if (ctx.isShadowed(name) || ctx.getters.has(name) || ctx.contextConsumers.has(name) || ctx.propsBindings.has(name)) return null
347
- if (ctx.isAdapterBound(name)) return null
424
+ // Spelled by its name, a const named like a prop the template holds under
425
+ // that name would read the prop (#3721).
426
+ const readsAsProp = ctx.propNamed.has(name)
427
+ if (!readsAsProp && ctx.isAdapterBound(name)) return null
348
428
  // An adapter already inlines a literal const in its own syntax.
349
- if (lookupLiteralConst(name, [constant], ctx.isShadowed) !== null) return null
350
- if (!callsOnlyGetters(init, ctx.getters)) return null
429
+ if (!readsAsProp && lookupLiteralConst(name, [constant], ctx.isShadowed) !== null) return null
430
+ if (!callsOnlyReadable(init, constant, ctx.getters, ctx)) return null
351
431
  // A free name the read site rebinds would be captured by the substitution:
352
432
  // it is read as what it holds where the const is declared instead.
353
433
  return resolveInitializer(init, ctx, n => ctx.isShadowed(n), constant.isModule ? 'module' : 'component')
@@ -393,6 +473,22 @@ function callsOnlyGetters(init: ParsedExpr, getters: ReadonlySet<string>): boole
393
473
  return ok
394
474
  }
395
475
 
476
+ /**
477
+ * {@link callsOnlyGetters} for the initializer of `constant`, also admitting
478
+ * a call of a local function a template inlines (`const initial = value()`,
479
+ * #3721): inlined with the initializer, the call is replaced by what the
480
+ * function returns. Only a name denoting the same function where the const
481
+ * is declared as in the component scope the markup reads it from: any
482
+ * inlinable function for a component const, a module one for a module const.
483
+ */
484
+ function callsOnlyReadable(init: ParsedExpr, constant: ConstantInfo, getters: ReadonlySet<string>, ctx: ComputedConstContext): boolean {
485
+ const readable = new Set(getters)
486
+ for (const [name, call] of ctx.calls) {
487
+ if (!constant.isModule || call.scope === 'module') readable.add(name)
488
+ }
489
+ return callsOnlyGetters(init, readable)
490
+ }
491
+
396
492
  /**
397
493
  * The initializer of a `const` holding an object literal (`const flags = { a:
398
494
  * n > 1, label: 'L' + n }`, `const labels = { ok: 'Fine', err: 'Broken' }`)
@@ -447,7 +543,7 @@ function projectObjectReads(
447
543
  // left to the walk, which projects the inner read.
448
544
  if (base.kind !== 'object-literal') return null
449
545
  const values = literalValues(base)
450
- const value = values === null ? undefined : e.kind === 'member' ? memberValue(values, e.property) : keyedValue(values, e.index, enclosing, ctx)
546
+ const value = values === null ? undefined : e.kind === 'member' ? memberValue(base, e.property) : keyedValue(values, e.index, enclosing, ctx)
451
547
  if (value === undefined) ok = false
452
548
  // An index whose keys are not known reads the literal itself, which no
453
549
  // template lowers: the adapter refuses it (BF101) instead of reading an
@@ -505,13 +601,13 @@ function literalValues(object: ObjectLiteral): Map<string, ParsedExpr> | null {
505
601
 
506
602
  /**
507
603
  * What `object.<key>` reads: the value the literal gives `key`, and
508
- * `undefined` for a key it does not list. `undefined` (no projection) for a
509
- * key `Object.prototype` holds, which JS reads from there.
604
+ * `undefined` for a key it does not list (`readLiteralMember`, the one
605
+ * decision every literal const member read takes). `undefined` (no
606
+ * projection) for a key `Object.prototype` holds, which JS reads from there.
510
607
  */
511
- function memberValue(values: ReadonlyMap<string, ParsedExpr>, key: string): ParsedExpr | undefined {
512
- const value = values.get(key)
513
- if (value) return value
514
- return key in Object.prototype ? undefined : { kind: 'identifier', name: 'undefined' }
608
+ function memberValue(object: ObjectLiteral, key: string): ParsedExpr | undefined {
609
+ const read = readLiteralMember(object, key)
610
+ return read?.kind === 'value' ? read.expr : undefined
515
611
  }
516
612
 
517
613
  /** {@link keyedValue}'s answer for an index whose keys are not all known. */
@@ -17,7 +17,7 @@ import {
17
17
  type NullishAttrContext,
18
18
  } from '../nullable-signal-attr.ts'
19
19
  import { BindingScope } from '../scope/binding-scope.ts'
20
- import { declaredValueType, declaredValueTypes, loopRowType, type DeclaredValueTypes } from './loop-row-type.ts'
20
+ import { declaredValueMayBeNil, declaredValueType, declaredValueTypes, loopRowType, type DeclaredValueTypes } from './loop-row-type.ts'
21
21
  import { collectOperandTyping, EMPTY_OPERAND_TYPING, factsOfType, type OperandTyping, type ScopedOperandTyping } from './operand-typing.ts'
22
22
  import { rootPropAliasesForLoop, rootPropAliasNames } from '../scope/root-prop-alias.ts'
23
23
  import type {
@@ -30,6 +30,9 @@ import type {
30
30
  PreambleValueDeclaration,
31
31
  } from '../types.ts'
32
32
  import { refuseNonPrimitiveStrictEquality, type NonPrimitiveEqualitySink } from './non-primitive-equality.ts'
33
+ import { refuseInheritedConstServerReads } from './inherited-const-server-read.ts'
34
+ import { refuseUninlinableSeedCalls } from './uninlinable-seed-call.ts'
35
+ import { refuseUnappliedPropDefaults } from './unapplied-prop-default.ts'
33
36
  import { collectImportedLoopChildComponentErrors } from './component-tree.ts'
34
37
  import { computedConstContext, type ComputedConstContext } from './computed-const.ts'
35
38
  import { searchParamsLocalNames } from './env-signal.ts'
@@ -274,7 +277,7 @@ export abstract class DslTemplateAdapter extends BaseAdapter {
274
277
  return arithmeticOperandCoercion(op, operand, other, this.nullishAttrCtx, isShadowed)
275
278
  }
276
279
 
277
- private errorSink(): NonPrimitiveEqualitySink {
280
+ protected errorSink(): NonPrimitiveEqualitySink {
278
281
  return { errors: this.errors, componentName: this.componentName }
279
282
  }
280
283
 
@@ -423,9 +426,13 @@ export abstract class DslTemplateAdapter extends BaseAdapter {
423
426
  this.rootPropAliases = rootPropAliasNames(ir, this.propsParams.map(p => p.name))
424
427
  this.scope = BindingScope.forComponent(this.propsObjectName)
425
428
  this.nullableOptionalProps = collectNullableOptionalProps(ir)
426
- this.nullishAttrCtx = collectNullishAttrContext(ir)
427
429
  this.stringValueNames = this.stringValueNamesFor(ir)
428
- this.declaredTypes = declaredValueTypes(ir)
430
+ const declaredTypes = declaredValueTypes(ir)
431
+ this.declaredTypes = declaredTypes
432
+ this.nullishAttrCtx = {
433
+ ...collectNullishAttrContext(ir),
434
+ declaredNil: expr => declaredValueMayBeNil(declaredTypes, expr, this.scope),
435
+ }
429
436
  this.nullableSignalGetters = new Set([
430
437
  ...collectNullableSignalGetters(ir),
431
438
  ...memberSeededNilSignals(ir, this.declaredTypes, this.scope),
@@ -459,6 +466,12 @@ export abstract class DslTemplateAdapter extends BaseAdapter {
459
466
  }
460
467
  // `===` / `!==` over an object or array (#3774, #3824 step 8).
461
468
  refuseNonPrimitiveStrictEquality(ir, this.operandTyping, this.errorSink())
469
+ // An inherited literal-const read in a value the server render computes off the emitter (#3813).
470
+ refuseInheritedConstServerReads(ir, this.errorSink())
471
+ // A server-read signal seed or memo body calling a function no template can inline (#3721).
472
+ refuseUninlinableSeedCalls(ir, this.errorSink())
473
+ // A server-read prop whose computed destructure default no template can apply (#3725).
474
+ refuseUnappliedPropDefaults(ir, this.errorSink())
462
475
  }
463
476
  }
464
477
 
@@ -0,0 +1,174 @@
1
+ /**
2
+ * BF101 for an inherited literal-const read (`R.toString`, see
3
+ * `spellStaticConstMember`) in a value the server render computes (#3813).
4
+ *
5
+ * An emitter refuses the read where it spells it, but not every read the
6
+ * server render performs is spelled by an emitter whose refusal survives. A
7
+ * signal's seed, a memo's body, a const's initializer and the expression a
8
+ * called function returns are computed apart from the position that reads
9
+ * them: by the SSR seed plan (whose lowering failures fall back silently, on
10
+ * purpose, to the static SSR defaults), by the static evaluator, or on the
11
+ * backend. A position's own value can be dropped the same way (a child prop
12
+ * the Go constructor cannot compute is left out). The value then renders as
13
+ * if the key were missing.
14
+ *
15
+ * This pass refuses the read in each server-rendered position
16
+ * (`walkTemplatePositions`, read in the position's own scope) and in each
17
+ * declaration the server render reads (`walkServerReads`, the one walk of
18
+ * that relation). Both skip `/* @client *\/` positions and resolve each name
19
+ * lexically, so a loop row or a callback param named like a declaration is
20
+ * not that declaration. Within an expression only the reads its evaluation
21
+ * performs are refused: a function is entered where it is called or handed
22
+ * to a call (a callback, an IIFE, a local function or a method of a literal
23
+ * const called by name), not where it is stored
24
+ * (`{ get: () => R.toString }` read for another key, an event handler). A
25
+ * const that only names another (`const A = R`) is read as that one.
26
+ *
27
+ * A block-bodied memo no single expression stands for has no server value
28
+ * computed from its statements: it renders its static default. The browser
29
+ * still evaluates them for the same slot, so an inherited read in one of
30
+ * them (as far as the parse represents the block) is refused all the same;
31
+ * the block's own `const` / `let` names shadow the component's there.
32
+ */
33
+
34
+ import { parsedExprChildren } from '../action-accessor.ts'
35
+ import { resolveStaticConstBinding } from '../augment-inherited-props.ts'
36
+ import { isEventHandlerName } from '../event-handler-name.ts'
37
+ import type { ParsedExpr, ParsedStatement } from '../expression-parser.ts'
38
+ import { localBindings, localCall, type LocalBindingResolver, type LocalScope } from '../local-call-body.ts'
39
+ import { BindingScope } from '../scope/binding-scope.ts'
40
+ import { walkServerReads } from '../server-read-walk.ts'
41
+ import { spellStaticConstMember, staticConstValue, staticIndexKey, type InheritedReadPlace, type StaticConstMemberSink } from '../static-const-member.ts'
42
+ import { walkTemplatePositions } from '../template-position-walk.ts'
43
+ import type { ComponentIR } from '../types.ts'
44
+
45
+ type Constants = ComponentIR['metadata']['localConstants']
46
+
47
+ /** Record BF101 for each inherited literal-const read the server render of `ir` performs. */
48
+ export function refuseInheritedConstServerReads(ir: ComponentIR, sink: StaticConstMemberSink): void {
49
+ const constants = ir.metadata.localConstants ?? []
50
+ if (constants.length === 0) return
51
+ const component = BindingScope.forComponent(ir.metadata.propsObjectName ?? null)
52
+ const shared: Omit<Check, 'place'> = {
53
+ // A module declaration's names are the module's: a component binding of a name does not hide them there.
54
+ constants: { component: constants, module: constants.filter(c => c.isModule).map(c => ({ ...c, shadowedInComponent: false })) },
55
+ scopes: { component, module: BindingScope.EMPTY },
56
+ resolve: localBindings({ ...ir.metadata, localConstants: constants }),
57
+ sink,
58
+ entered: new Set(),
59
+ }
60
+ // This pass runs before any emitter, so its record of a read is the one that stands.
61
+ walkTemplatePositions(ir.root, ({ expr, scope, attrName, loc, role }) => {
62
+ if (attrName !== undefined && isEventHandlerName(attrName)) return
63
+ // A component renders on the server whatever directive its prop carries.
64
+ const place = { loc, deferrable: role !== 'prop' }
65
+ refuseReads(expr, { scope: scope ?? component, from: 'component' }, { ...shared, place }, 'value')
66
+ }, component)
67
+ walkServerReads(ir, (read) => {
68
+ const check = { ...shared, place: { loc: read.loc } }
69
+ const outer = shared.scopes[read.scope]
70
+ if (read.expr) refuseReads(read.expr, { scope: outer, from: read.scope }, check, 'value')
71
+ else if (read.block) {
72
+ const parts = blockParts(read.block)
73
+ const at = { scope: outer.enterCallback(parts.locals), from: read.scope }
74
+ for (const expr of parts.exprs) refuseReads(expr, at, check, 'value')
75
+ }
76
+ })
77
+ }
78
+
79
+ /** The expressions parsed statements evaluate and the names they declare, nested `if` blocks included. */
80
+ function blockParts(statements: readonly ParsedStatement[], into: { exprs: ParsedExpr[]; locals: string[] } = { exprs: [], locals: [] }) {
81
+ for (const s of statements) {
82
+ if (s.kind === 'var-decl') {
83
+ into.locals.push(s.name)
84
+ into.exprs.push(s.init)
85
+ } else if (s.kind === 'return') into.exprs.push(s.value)
86
+ else {
87
+ into.exprs.push(s.condition)
88
+ blockParts(s.consequent, into)
89
+ if (s.alternate) blockParts(s.alternate, into)
90
+ }
91
+ }
92
+ return into
93
+ }
94
+
95
+ interface Check {
96
+ constants: Record<LocalScope, Constants>
97
+ /** The scope a declaration of each `LocalScope` is read in. */
98
+ scopes: Record<LocalScope, BindingScope>
99
+ resolve: LocalBindingResolver
100
+ sink: StaticConstMemberSink
101
+ place: InheritedReadPlace
102
+ /** The function bodies already entered, so one that calls itself ends. */
103
+ entered: Set<ParsedExpr>
104
+ }
105
+
106
+ /** Where an expression is read: the bindings around it, and the scope its free names are declared in. */
107
+ interface At {
108
+ scope: BindingScope
109
+ from: LocalScope
110
+ }
111
+
112
+ /** How the expression being visited is used: its value, the function a call calls, or an argument handed to a call. */
113
+ type Use = 'value' | 'callee' | 'argument'
114
+
115
+ function refuseReads(expr: ParsedExpr, at: At, check: Check, use: Use): void {
116
+ if (expr.kind === 'arrow') {
117
+ // A stored function evaluates nothing until it is called.
118
+ if (use !== 'value') refuseReads(expr.body, { ...at, scope: at.scope.enterCallback(expr.params) }, check, 'value')
119
+ return
120
+ }
121
+ if (use === 'callee') enterCalledFunction(expr, at, check)
122
+ else if (expr.kind === 'member' || expr.kind === 'index-access') {
123
+ const key = expr.kind === 'member' ? expr.property : staticIndexKey(expr.index)
124
+ const isShadowed = (name: string): boolean => at.scope.isBound(name)
125
+ const object = throughAliases(expr.object, check.constants[at.from], isShadowed)
126
+ if (key !== null) spellStaticConstMember(object, key, check.constants[at.from], isShadowed, check.sink, check.place)
127
+ }
128
+ for (const child of parsedExprChildren(expr)) refuseReads(child.expr, at, check, childUse(expr, child.expr))
129
+ }
130
+
131
+ function childUse(parent: ParsedExpr, child: ParsedExpr): Use {
132
+ if (parent.kind === 'call') return child === parent.callee ? 'callee' : 'argument'
133
+ if (parent.kind === 'array-method') return child === parent.object ? 'value' : 'argument'
134
+ return 'value'
135
+ }
136
+
137
+ /**
138
+ * A call by name evaluates the called function's body, in the scope the
139
+ * function is declared in: an arrow `const` (`f('a')`), a function
140
+ * declaration a template inlines (`localCall`), or a literal const's own
141
+ * method (`H.get()`).
142
+ */
143
+ function enterCalledFunction(callee: ParsedExpr, at: At, check: Check): void {
144
+ const isShadowed = (name: string): boolean => at.scope.isBound(name)
145
+ if (callee.kind !== 'identifier') {
146
+ const method = staticConstValue(throughAliases(callee, check.constants[at.from], isShadowed), check.constants[at.from], isShadowed)
147
+ if (method?.kind === 'arrow') enterBody(method.body, method.params, at.from, check)
148
+ return
149
+ }
150
+ const binding = isShadowed(callee.name) ? null : check.resolve(callee.name, at.from)
151
+ if (binding?.kind === 'const' && binding.info.declarationKind === 'const' && binding.info.parsed?.kind === 'arrow') {
152
+ enterBody(binding.info.parsed.body, binding.info.parsed.params, binding.scope, check)
153
+ } else if (binding?.kind === 'function') {
154
+ const call = localCall(binding)
155
+ if (call?.kind === 'inline') enterBody(call.body, [], binding.scope, check)
156
+ }
157
+ }
158
+
159
+ function enterBody(body: ParsedExpr, params: readonly string[], from: LocalScope, check: Check): void {
160
+ if (check.entered.has(body)) return
161
+ check.entered.add(body)
162
+ refuseReads(body, { scope: check.scopes[from].enterCallback(params), from }, check, 'value')
163
+ }
164
+
165
+ /** `expr` with a root const that only names another const (`const A = R`) replaced by that one. */
166
+ function throughAliases(expr: ParsedExpr, constants: Constants, isShadowed: (name: string) => boolean, hops = 0): ParsedExpr {
167
+ if (expr.kind === 'member' || expr.kind === 'index-access') {
168
+ return { ...expr, object: throughAliases(expr.object, constants, isShadowed, hops) }
169
+ }
170
+ if (expr.kind !== 'identifier' || hops > constants.length) return expr
171
+ const named = resolveStaticConstBinding(expr.name, constants, isShadowed)?.parsed
172
+ // The aliased name is read where the alias is declared, outside any callback around the read.
173
+ return named?.kind === 'identifier' ? throughAliases(named, constants, () => false, hops + 1) : expr
174
+ }
@@ -11,6 +11,7 @@
11
11
 
12
12
  import type { ParsedExpr } from '../expression-parser.ts'
13
13
  import type { ComponentIR, TypeInfo } from '../types.ts'
14
+ import { factsOfType } from './operand-typing.ts'
14
15
  import {
15
16
  arrayElementType,
16
17
  loopValueTypeAt,
@@ -38,6 +39,12 @@ export interface DeclaredValueTypes {
38
39
  }[]
39
40
  readonly signals: readonly { readonly getter: string; readonly type: TypeInfo }[]
40
41
  readonly memos: readonly { readonly name: string; readonly type: TypeInfo }[]
42
+ /**
43
+ * The component's module- and function-scope consts with their declared
44
+ * types (`const ROWS: Row[] = […]`), read when no prop or loop binding
45
+ * holds the name (#3728). Optional: a view without them types no const.
46
+ */
47
+ readonly constants?: readonly { readonly name: string; readonly type: TypeInfo | null; readonly parsed?: ParsedExpr }[]
41
48
  /** The identifier the component reads its props object as (`props`); null for a destructured signature. */
42
49
  readonly propsObjectName: string | null
43
50
  readonly namedFields: NamedTypeFields
@@ -45,11 +52,12 @@ export interface DeclaredValueTypes {
45
52
 
46
53
  /** {@link DeclaredValueTypes} of a component. */
47
54
  export function declaredValueTypes(ir: ComponentIR): DeclaredValueTypes {
48
- const { propsParams, signals, memos, typeDefinitions, propsObjectName } = ir.metadata
55
+ const { propsParams, signals, memos, typeDefinitions, propsObjectName, localConstants } = ir.metadata
49
56
  return {
50
57
  propsParams,
51
58
  signals,
52
59
  memos,
60
+ constants: localConstants,
53
61
  propsObjectName: propsObjectName ?? null,
54
62
  namedFields: name => typeDefinitions.find(td => td.name === name)?.properties,
55
63
  }
@@ -77,11 +85,22 @@ export function declaredValueType(types: DeclaredValueTypes, expr: ParsedExpr, s
77
85
  return valueType(types, expr, scope)
78
86
  }
79
87
 
88
+ /**
89
+ * Whether the value `expr` reads in `scope` is declared to admit `undefined`
90
+ * or `null` (#3728): a loop row's optional field (`r.tone` with
91
+ * `tone?: string`), a destructured one, or a nullable union. The one answer
92
+ * every template adapter's nullish-attribute guard reads
93
+ * (`NullishAttrContext.declaredNil`). An undeclared value answers false.
94
+ */
95
+ export function declaredValueMayBeNil(types: DeclaredValueTypes, expr: ParsedExpr, scope: BindingScope): boolean {
96
+ return factsOfType(valueType(types, expr, scope)).types.has('nil')
97
+ }
98
+
80
99
  function valueType(types: DeclaredValueTypes, expr: ParsedExpr, scope: BindingScope): LoopValueType | null {
81
100
  switch (expr.kind) {
82
101
  case 'identifier': {
83
102
  const hit = scope.lookup(expr.name)
84
- if (!hit) return propType(types, expr.name)
103
+ if (!hit) return propType(types, expr.name) ?? constType(types, expr.name)
85
104
  const row = hit.binding.row
86
105
  return row ? loopValueTypeAt(row.itemType, row.segments, types.namedFields) : null
87
106
  }
@@ -142,6 +161,54 @@ function callType(types: DeclaredValueTypes, expr: Extract<ParsedExpr, { kind: '
142
161
  return SAME_ELEMENT_METHODS.has(callee.property) ? valueType(types, callee.object, scope) : null
143
162
  }
144
163
 
164
+ /**
165
+ * A const's type: its declared one (`const ROWS: Row[] = […]`), or, for an
166
+ * untyped array of object literals (`unknown[]` carries no field types), the
167
+ * row shape the literal spells (`literalRowsType`).
168
+ */
169
+ function constType(types: DeclaredValueTypes, name: string): LoopValueType | null {
170
+ const constant = types.constants?.find(c => c.name === name)
171
+ if (!constant) return null
172
+ const type = constant.type
173
+ if (type && type.kind !== 'unknown' && !(type.kind === 'array' && !type.elementType)) return type
174
+ return constant.parsed ? literalRowsType(constant.parsed) : null
175
+ }
176
+
177
+ /**
178
+ * The array type an array literal of plain object literals spells
179
+ * (`[{ id: 1, tone: 'k' }, { id: 2 }]`): one object row whose fields are
180
+ * every key a row has, typed by the literal values the rows hold, and
181
+ * optional when some row omits the key, as TypeScript infers it (#3728).
182
+ * A value that is not a scalar literal types its field `unknown`. Null for
183
+ * any other shape (a spread, a non-object element, an empty array).
184
+ */
185
+ function literalRowsType(parsed: ParsedExpr): LoopValueType | null {
186
+ if (parsed.kind !== 'array-literal' || parsed.elements.length === 0) return null
187
+ const rows: Map<string, LoopValueType>[] = []
188
+ for (const element of parsed.elements) {
189
+ if (element.kind !== 'object-literal') return null
190
+ const row = new Map<string, LoopValueType>()
191
+ for (const p of element.properties) {
192
+ if (p.kind !== 'prop') return null
193
+ row.set(p.key, literalValueType(p.value))
194
+ }
195
+ rows.push(row)
196
+ }
197
+ const keys = [...new Set(rows.flatMap(row => [...row.keys()]))]
198
+ const properties = keys.map(key => {
199
+ const present = rows.flatMap(row => (row.has(key) ? [row.get(key)!] : []))
200
+ return { name: key, type: unionOfLoopValueTypes(present), optional: present.length < rows.length }
201
+ })
202
+ return { kind: 'array', elementType: { kind: 'object', properties } }
203
+ }
204
+
205
+ /** The type of a scalar literal (`'k'`, `1`, `true`, `null`, `undefined`); `unknown` otherwise. */
206
+ function literalValueType(value: ParsedExpr): LoopValueType {
207
+ if (value.kind === 'literal') return { kind: 'primitive', primitive: value.literalType, raw: value.literalType }
208
+ if (value.kind === 'identifier' && value.name === 'undefined') return { kind: 'primitive', primitive: 'undefined', raw: 'undefined' }
209
+ return { kind: 'unknown' }
210
+ }
211
+
145
212
  function propType(types: DeclaredValueTypes, name: string): LoopValueType | null {
146
213
  const param = types.propsParams.find(p => !p.isRest && p.name === name)
147
214
  if (!param) return null
@@ -15,15 +15,22 @@
15
15
  * The primitive plan names the refusal per node (`mode: 'refuse'`), and
16
16
  * every emitter spells the runtime's `strict_eq` for it; the error itself
17
17
  * is recorded here, once per component, over every template position, each
18
- * read in its own scope, and over the memo bodies the adapters seed at SSR.
18
+ * read in its own scope, over the memo bodies the adapters seed at SSR, and
19
+ * over the computed destructure defaults a backend applies
20
+ * (`appliedPropDefaults`) for a prop the server render reads. A default is
21
+ * checked as the expression it stands
22
+ * for: a const it reads twice (`DEF === DEF`) is spelled there as two
23
+ * separate literals, which no runtime compares as one reference.
19
24
  */
20
25
 
21
26
  import { exprToString, type ParsedExpr } from '../expression-parser.ts'
22
27
  import { parsedExprChildren } from '../action-accessor.ts'
23
28
  import { BindingScope } from '../scope/binding-scope.ts'
29
+ import { appliedPropDefaults } from '../ssr-seed-plan.ts'
24
30
  import { walkTemplatePositions } from '../template-position-walk.ts'
25
31
  import type { ComponentIR, CompilerError, SourceLocation } from '../types.ts'
26
32
  import type { OperandTyping, ScopedOperandTyping } from './operand-typing.ts'
33
+ import { propsReadFrom } from './unapplied-prop-default.ts'
27
34
  import { isNullishTest, mayHoldObject } from './primitive-plan.ts'
28
35
 
29
36
  /** Where a template adapter records the refusal. */
@@ -52,7 +59,8 @@ function refusedComparisons(expr: ParsedExpr, typing: ScopedOperandTyping, isObj
52
59
 
53
60
  /**
54
61
  * Record BF101 for every `===` / `!==` over an operand that may be an
55
- * object in `ir`'s template positions and memo bodies. One error per
62
+ * object in `ir`'s template positions, memo bodies and applied prop
63
+ * defaults. One error per
56
64
  * comparison text per compile.
57
65
  */
58
66
  export function refuseNonPrimitiveStrictEquality(ir: ComponentIR, typing: OperandTyping, sink: NonPrimitiveEqualitySink): void {
@@ -70,6 +78,13 @@ export function refuseNonPrimitiveStrictEquality(ir: ComponentIR, typing: Operan
70
78
  for (const memo of ir.metadata.memos ?? []) {
71
79
  if (memo.parsed) check(memo.parsed, component, ir.root.loc)
72
80
  }
81
+ // Only a default the server render reads: one whose prop every read
82
+ // defers with `/* @client */` is computed in the browser.
83
+ const { defaults } = appliedPropDefaults(ir.metadata)
84
+ const serverRead = defaults.size > 0 ? propsReadFrom(ir, defaults) : new Set<string>()
85
+ for (const [name, resolved] of defaults) {
86
+ if (serverRead.has(name) && resolved.blocked.length === 0) check(resolved.expr, component, resolved.loc ?? ir.root.loc)
87
+ }
73
88
  }
74
89
 
75
90
  function record(comparison: string, loc: SourceLocation, sink: NonPrimitiveEqualitySink): void {