embedded-react 0.19.0 → 0.21.0

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 (148) hide show
  1. package/NOTICE +5 -0
  2. package/README.md +8 -3
  3. package/aot/app-file-loader.mjs +116 -0
  4. package/aot/compile.mjs +180 -90
  5. package/aot/compiler/animations.mjs +568 -317
  6. package/aot/compiler/boot.mjs +97 -35
  7. package/aot/compiler/branch-merge.mjs +4 -3
  8. package/aot/compiler/check.mjs +70 -18
  9. package/aot/compiler/collect.mjs +787 -288
  10. package/aot/compiler/contexts.mjs +391 -0
  11. package/aot/compiler/control-flow.mjs +439 -268
  12. package/aot/compiler/custom-hooks.mjs +686 -0
  13. package/aot/compiler/diagnostics.mjs +22 -25
  14. package/aot/compiler/elements/activity-indicator.mjs +25 -24
  15. package/aot/compiler/elements/button.mjs +182 -0
  16. package/aot/compiler/elements/dial.mjs +91 -77
  17. package/aot/compiler/elements/flat-list.mjs +24 -22
  18. package/aot/compiler/elements/image-background.mjs +76 -0
  19. package/aot/compiler/elements/image.mjs +52 -50
  20. package/aot/compiler/elements/modal.mjs +31 -30
  21. package/aot/compiler/elements/props.mjs +61 -26
  22. package/aot/compiler/elements/rewrite.mjs +118 -0
  23. package/aot/compiler/elements/section-list.mjs +370 -0
  24. package/aot/compiler/elements/switch.mjs +42 -34
  25. package/aot/compiler/elements/text-input.mjs +34 -32
  26. package/aot/compiler/expressions.mjs +1685 -392
  27. package/aot/compiler/handlers.mjs +2029 -547
  28. package/aot/compiler/helper-values.mjs +312 -0
  29. package/aot/compiler/ir/functions.mjs +11 -1
  30. package/aot/compiler/ir/nodes.mjs +43 -4
  31. package/aot/compiler/ir/reads.mjs +223 -22
  32. package/aot/compiler/ir/text.mjs +5 -1
  33. package/aot/compiler/ir/types.mjs +26 -14
  34. package/aot/compiler/ir/vectors.mjs +5 -1
  35. package/aot/compiler/kept-states.mjs +177 -0
  36. package/aot/compiler/keyboard.mjs +17 -7
  37. package/aot/compiler/list-items.mjs +226 -0
  38. package/aot/compiler/list-order.mjs +586 -0
  39. package/aot/compiler/list-split.mjs +259 -0
  40. package/aot/compiler/loops.mjs +582 -0
  41. package/aot/compiler/lower.mjs +246 -111
  42. package/aot/compiler/native-files.mjs +439 -0
  43. package/aot/compiler/native-header.mjs +335 -0
  44. package/aot/compiler/native-modules.mjs +1173 -0
  45. package/aot/compiler/nodes.mjs +195 -172
  46. package/aot/compiler/options.mjs +37 -31
  47. package/aot/compiler/out.mjs +32 -23
  48. package/aot/compiler/package/animations.mjs +779 -0
  49. package/aot/compiler/package/arena.mjs +252 -0
  50. package/aot/compiler/package/assemble.mjs +175 -0
  51. package/aot/compiler/package/bytecode.mjs +315 -0
  52. package/aot/compiler/package/checks.mjs +1026 -0
  53. package/aot/compiler/package/codegen.mjs +2168 -0
  54. package/aot/compiler/package/enums.mjs +148 -0
  55. package/aot/compiler/package/format.mjs +771 -0
  56. package/aot/compiler/package/layouts.mjs +136 -0
  57. package/aot/compiler/package/lower.mjs +2103 -0
  58. package/aot/compiler/package/props.mjs +118 -0
  59. package/aot/compiler/package/string-caps.mjs +515 -0
  60. package/aot/compiler/package/tables.mjs +127 -0
  61. package/aot/compiler/package/vectors.mjs +502 -0
  62. package/aot/compiler/package/writer.mjs +686 -0
  63. package/aot/compiler/pan-responder.mjs +69 -61
  64. package/aot/compiler/parse.mjs +23 -21
  65. package/aot/compiler/record-shapes.mjs +246 -0
  66. package/aot/compiler/records.mjs +654 -0
  67. package/aot/compiler/reducers.mjs +272 -0
  68. package/aot/compiler/static-eval.mjs +340 -30
  69. package/aot/compiler/style-text.mjs +178 -174
  70. package/aot/compiler/svg.mjs +480 -251
  71. package/aot/compiler/switch-cases.mjs +198 -0
  72. package/aot/compiler/tagged-records.mjs +450 -0
  73. package/aot/compiler/typing.mjs +307 -0
  74. package/aot/compiler/updaters.mjs +320 -0
  75. package/aot/compiler/window-dimensions.mjs +94 -0
  76. package/aot/compiler/worked-values.mjs +319 -0
  77. package/aot/demo-file.mjs +30 -0
  78. package/aot/screenshot-smoke.mjs +54 -40
  79. package/aot/style-map.mjs +152 -92
  80. package/assets/bake-font.mjs +123 -77
  81. package/assets/bake-image.mjs +39 -22
  82. package/assets/bake-svg.mjs +361 -262
  83. package/assets/build-builtin-font.mjs +11 -7
  84. package/assets/emit-c.mjs +77 -58
  85. package/assets/emit-container.mjs +123 -37
  86. package/assets/emit-pack.mjs +77 -67
  87. package/assets/font-config.mjs +9 -6
  88. package/assets/font-sizes.mjs +163 -123
  89. package/assets/glyph-coverage.mjs +74 -54
  90. package/assets/index.mjs +31 -9
  91. package/assets/rasterize.mjs +126 -99
  92. package/assets/svg-loader.mjs +8 -8
  93. package/build.mjs +23 -13
  94. package/cli.mjs +402 -172
  95. package/compile-bin.mjs +3 -3
  96. package/flash.mjs +537 -0
  97. package/hotreload/dev-device.mjs +90 -33
  98. package/hotreload/pack-app.mjs +55 -43
  99. package/hotreload/pack-split.mjs +62 -64
  100. package/hotreload/package-transfer.mjs +175 -0
  101. package/hotreload/protocol.mjs +50 -37
  102. package/hotreload/uploader.mjs +38 -27
  103. package/hotreload/watch-tree.mjs +19 -19
  104. package/pack-container.mjs +37 -21
  105. package/package.json +7 -8
  106. package/persist-transform.mjs +34 -28
  107. package/qjsc-wasm.mjs +25 -14
  108. package/sim/embedded-react.cjs +1 -1
  109. package/sim/embedded-react.js +1 -1
  110. package/sim/embedded-react.wasm +0 -0
  111. package/sim/index.html +94 -85
  112. package/sim-server.mjs +113 -94
  113. package/src/embedded-react/Animated.js +24 -24
  114. package/src/embedded-react/Dimensions.js +37 -0
  115. package/src/embedded-react/Easing.js +1 -1
  116. package/src/embedded-react/FlatList.js +3 -3
  117. package/src/embedded-react/LayoutAnimation.js +8 -5
  118. package/src/embedded-react/PanResponder.js +75 -71
  119. package/src/embedded-react/Pressable.js +2 -8
  120. package/src/embedded-react/SectionList.js +7 -9
  121. package/src/embedded-react/StyleSheet.js +4 -3
  122. package/src/embedded-react/TouchableOpacity.js +13 -8
  123. package/src/embedded-react/index.d.ts +88 -8
  124. package/src/embedded-react/index.js +2 -0
  125. package/src/embedded-react/layout-anim-config.js +10 -4
  126. package/src/embedded-react/list-child.js +5 -5
  127. package/src/embedded-react/named-colors.js +1 -1
  128. package/src/embedded-react/nativeModule.js +462 -0
  129. package/src/embedded-react/split-style.js +11 -11
  130. package/src/embedded-react/svg-ops.js +760 -593
  131. package/src/embedded-react/useHostValue.js +3 -3
  132. package/src/embedded-react/usePersistentState.js +6 -6
  133. package/src/embedded-react/warn-props.js +1 -1
  134. package/src/host-config.js +60 -53
  135. package/src/props.js +49 -41
  136. package/src/renderer.js +7 -4
  137. package/aot/compiler/assemble.mjs +0 -944
  138. package/aot/compiler/c/animations.mjs +0 -436
  139. package/aot/compiler/c/boot.mjs +0 -127
  140. package/aot/compiler/c/expressions.mjs +0 -270
  141. package/aot/compiler/c/functions.mjs +0 -268
  142. package/aot/compiler/c/keyboard.mjs +0 -96
  143. package/aot/compiler/c/nodes.mjs +0 -303
  144. package/aot/compiler/c/pan-responder.mjs +0 -136
  145. package/aot/compiler/c/statements.mjs +0 -319
  146. package/aot/compiler/c/text.mjs +0 -83
  147. package/aot/compiler/c/vectors.mjs +0 -381
  148. package/aot/compiler/c-syntax.mjs +0 -127
@@ -87,7 +87,7 @@ export function lowerGestureField(field, pan) {
87
87
  return {
88
88
  kind: 'gesture',
89
89
  field: field,
90
- statePrefix: pan.cPrefix,
90
+ statePrefix: pan.statePrefix,
91
91
  stateID: pan.stateID,
92
92
  type: field === 'vx' || field === 'vy' ? FLOAT : INT,
93
93
  };
@@ -99,7 +99,7 @@ export function lowerGestureField(field, pan) {
99
99
  *
100
100
  * @param name The JS name the responder is bound to.
101
101
  * @param createCall The `PanResponder.create(…)` call.
102
- * @param prefix The C name prefix: none for the App, `c<n>_` for an inlined instance.
102
+ * @param prefix The name prefix: none for the App, `c<n>_` for an inlined instance.
103
103
  *
104
104
  * @returns The responder.
105
105
  */
@@ -133,7 +133,7 @@ function buildPanDescriptor(name, createCall, prefix) {
133
133
  throw aotError(`AOT: unknown PanResponder config key "${key}"`, `supported: ${[...Object.keys(PAN_QUERIES), ...Object.keys(PAN_EVENTS)].join(', ')}.`);
134
134
  }
135
135
  if (prop.type !== 'ObjectMethod' && !isFn(callback)) {
136
- throw aotError(`AOT: PanResponder "${key}" must be a function`, 'pass an inline arrow — `(e, g) => …` — so it can be compiled into the generated C.');
136
+ throw aotError(`AOT: PanResponder "${key}" must be a function`, 'pass an inline arrow — `(e, g) => …` — so it can be compiled.');
137
137
  }
138
138
  if (query) {
139
139
  queries.set(query, callback);
@@ -144,8 +144,8 @@ function buildPanDescriptor(name, createCall, prefix) {
144
144
  }
145
145
  return {
146
146
  name,
147
- cPrefix: `s_pan_${prefix}${name}`,
148
- fnPrefix: `er_pan_${prefix}${name}`,
147
+ statePrefix: `pan_state_${prefix}${name}`,
148
+ functionPrefix: `pan_${prefix}${name}`,
149
149
  stateID: 0, // assigned when the responder is first wired to a node
150
150
  queries,
151
151
  events,
@@ -157,49 +157,49 @@ function buildPanDescriptor(name, createCall, prefix) {
157
157
  * `useRef(…)` form (read back as `pan.current.panHandlers`) is accepted too; a bare `create(…)` is not,
158
158
  * because it would re-create the recognizer every render in Flow A and the two flows must agree.
159
159
  *
160
- * @param fnBody The component's body.
161
- * @param prefix The C name prefix: none for the App, `c<n>_` for an inlined instance.
160
+ * @param functionBody The component's body.
161
+ * @param prefix The name prefix: none for the App, `c<n>_` for an inlined instance.
162
162
  *
163
163
  * @returns The responders, by name.
164
164
  */
165
- export function collectPanResponders(fnBody, prefix = '') {
165
+ export function collectPanResponders(functionBody, prefix = '') {
166
166
  // Only the component body's own top-level declarations can hold a responder.
167
167
  const pans = new Map();
168
- if (fnBody.type !== 'BlockStatement')
168
+ if (functionBody.type !== 'BlockStatement')
169
169
  return pans;
170
- for (const statement of fnBody.body) {
170
+ for (const statement of functionBody.body) {
171
171
  if (statement.type !== 'VariableDeclaration')
172
172
  continue;
173
- for (const decl of statement.declarations) {
174
- const init = decl.init;
175
- if (decl.id.type !== 'Identifier' || !init)
173
+ for (const declarator of statement.declarations) {
174
+ const initializer = declarator.init;
175
+ if (declarator.id.type !== 'Identifier' || !initializer)
176
176
  continue;
177
177
  // Find the useRef call in either `useRef(…).current` or a bare `useRef(…)`.
178
- const viaCurrent = init.type === 'MemberExpression' &&
179
- !init.computed &&
180
- init.property.name === 'current' &&
181
- init.object.type === 'CallExpression' &&
182
- init.object.callee.name === 'useRef'
183
- ? init.object
178
+ const viaCurrent = initializer.type === 'MemberExpression' &&
179
+ !initializer.computed &&
180
+ initializer.property.name === 'current' &&
181
+ initializer.object.type === 'CallExpression' &&
182
+ initializer.object.callee.name === 'useRef'
183
+ ? initializer.object
184
184
  : null;
185
- const viaRef = init.type === 'CallExpression' &&
186
- init.callee.name === 'useRef'
187
- ? init
185
+ const viaRef = initializer.type === 'CallExpression' &&
186
+ initializer.callee.name === 'useRef'
187
+ ? initializer
188
188
  : null;
189
189
  const useRefCall = viaCurrent || viaRef;
190
190
  // Skip anything that is not a useRef around PanResponder.create(…); an unwrapped create is an error.
191
191
  if (!useRefCall || !isPanCreate(useRefCall.arguments[0])) {
192
- if (isPanCreate(init)) {
193
- throw aotError('AOT: PanResponder.create(...) must be kept in a useRef', `write \`const ${decl.id.name} = useRef(PanResponder.create({…})).current;\` — the ` +
192
+ if (isPanCreate(initializer)) {
193
+ throw aotError('AOT: PanResponder.create(...) must be kept in a useRef', `write \`const ${declarator.id.name} = useRef(PanResponder.create({…})).current;\` — the ` +
194
194
  `recognizer owns the live gesture, so a fresh one per render would throw the drag ` +
195
195
  `away (the same rule Flow A enforces).`);
196
196
  }
197
197
  continue;
198
198
  }
199
199
  // Build the responder's descriptor and record which way the app must spell its spread.
200
- const pan = buildPanDescriptor(decl.id.name, useRefCall.arguments[0], prefix);
200
+ const pan = buildPanDescriptor(declarator.id.name, useRefCall.arguments[0], prefix);
201
201
  pan.viaRefCurrent = !viaCurrent; // how the app spells the spread: pan.current.panHandlers
202
- pans.set(decl.id.name, pan);
202
+ pans.set(declarator.id.name, pan);
203
203
  }
204
204
  }
205
205
  return pans;
@@ -208,64 +208,68 @@ export function collectPanResponders(fnBody, prefix = '') {
208
208
  * Lowers a should-set predicate to a single condition: the engine calls these synchronously inside
209
209
  * hit-testing, before anyone owns the gesture, so they may only READ.
210
210
  *
211
- * @param fnNode The predicate.
212
- * @param env The expression environment.
211
+ * @param functionNode The predicate.
212
+ * @param environment The expression environment.
213
213
  * @param pan The responder it belongs to.
214
214
  *
215
215
  * @returns The condition.
216
216
  */
217
- function lowerPanQuery(fnNode, env, pan) {
217
+ function lowerPanQuery(functionNode, environment, pan) {
218
218
  // The predicate reads the event and gestureState through its own parameter names.
219
- const eventParam = fnNode.params[0]?.type === 'Identifier' ? fnNode.params[0].name : null;
220
- const gestureParam = fnNode.params[1]?.type === 'Identifier' ? fnNode.params[1].name : null;
221
- const queryEnv = { ...env, pan };
222
- if (eventParam) {
223
- queryEnv.event = eventParam;
219
+ const eventParameter = functionNode.params[0]?.type === 'Identifier'
220
+ ? functionNode.params[0].name
221
+ : null;
222
+ const gestureParameter = functionNode.params[1]?.type === 'Identifier'
223
+ ? functionNode.params[1].name
224
+ : null;
225
+ const queryEnvironment = { ...environment, pan };
226
+ if (eventParameter) {
227
+ queryEnvironment.event = eventParameter;
224
228
  }
225
- if (gestureParam) {
226
- queryEnv.gesture = gestureParam;
229
+ if (gestureParameter) {
230
+ queryEnvironment.gesture = gestureParameter;
227
231
  }
228
232
  // Its body must be one expression: an expression body, or a block that only returns one.
229
- const body = fnNode.body;
230
- const expr = body.type === 'BlockStatement'
233
+ const body = functionNode.body;
234
+ const expression = body.type === 'BlockStatement'
231
235
  ? body.body.length === 1 && body.body[0].type === 'ReturnStatement'
232
236
  ? body.body[0].argument
233
237
  : null
234
238
  : body;
235
- if (!expr) {
239
+ if (!expression) {
236
240
  throw aotError('AOT: a PanResponder should-set predicate must be a single boolean expression', 'write it as `() => true` or `(e, g) => Math.abs(g.dx) > 8`. The engine asks these ' +
237
241
  'mid-hit-test, so they may only read (state, event/gesture fields, constants) — never ' +
238
242
  'set state.');
239
243
  }
240
- return lowerExpr(expr, queryEnv);
244
+ return lowerExpr(expression, queryEnvironment);
241
245
  }
242
246
  /**
243
247
  * Lowers a PanResponder onto the engine's responder system, not a transpiled copy of it: the engine already runs
244
- * RN's state machine in C. Capture/bubble negotiation (er_responder_query_set) picks an owner, then GRANT / MOVE /
248
+ * RN's state machine in the engine. Capture/bubble negotiation (er_responder_query_set) picks an owner, then GRANT / MOVE /
245
249
  * RELEASE / TERMINATE fire on the owner alone, carrying cumulative travel and velocity. So the should-set
246
250
  * predicates become QUERIES and the callbacks become responder EVENT handlers: no gesture math is duplicated into
247
- * the generated C, and a granted pan owns the gesture, so a ScrollView ancestor cannot auto-scroll out from under
251
+ * the package, and a granted pan owns the gesture, so a ScrollView ancestor cannot auto-scroll out from under
248
252
  * it.
249
253
  *
250
254
  * The one thing with no engine counterpart is RN's anchor: `g.dx` is measured from the grant, while the engine's
251
255
  * `data->dx` runs from touch-down, so a claim that needed 10 px of slop would otherwise open with a 10 px jump.
252
- * That anchor, plus `x0`/`y0`, is a handful of file-scope ints per responder, kept by the grant, release and
256
+ * That anchor, plus `x0`/`y0`, is a handful of ints per responder, kept by the grant, release and
253
257
  * terminate handlers. Those three are ALWAYS lowered, even with no app callback; move and reject only with one.
254
258
  *
255
259
  * @param pan The responder; its gesture id must be assigned.
256
- * @param env The expression environment.
260
+ * @param environment The expression environment.
257
261
  * @param state The component's state table.
258
- * @param out Everything emitted so far.
262
+ * @param output Everything emitted so far.
259
263
  *
260
264
  * @returns The responder.
261
265
  */
262
- export function lowerPanResponder(pan, env, state, out) {
263
- const panEnv = { ...env, pan };
266
+ export function lowerPanResponder(pan, environment, state, output) {
267
+ const panEnvironment = { ...environment, pan };
264
268
  const event = (name, role) => ({
265
269
  event: name,
266
270
  role,
267
271
  callback: pan.events.has(name)
268
- ? lowerHandler(pan.events.get(name), panEnv, state, out, pan)
272
+ ? lowerHandler(pan.events.get(name), panEnvironment, state, output, pan)
269
273
  : null,
270
274
  });
271
275
  const events = [
@@ -281,13 +285,13 @@ export function lowerPanResponder(pan, env, state, out) {
281
285
  }
282
286
  return {
283
287
  name: pan.name,
284
- statePrefix: pan.cPrefix,
285
- fnPrefix: pan.fnPrefix,
288
+ statePrefix: pan.statePrefix,
289
+ functionPrefix: pan.functionPrefix,
286
290
  stateID: pan.stateID,
287
291
  events,
288
292
  queries: [...pan.queries].map(([query, predicate]) => ({
289
293
  query,
290
- test: lowerPanQuery(predicate, panEnv, pan),
294
+ test: lowerPanQuery(predicate, panEnvironment, pan),
291
295
  })),
292
296
  };
293
297
  }
@@ -296,19 +300,23 @@ export function lowerPanResponder(pan, env, state, out) {
296
300
  * handlers to the output. Each node that spreads it wires them in its own build lines.
297
301
  *
298
302
  * @param pan The responder.
299
- * @param out Everything emitted so far.
300
- * @param env The expression environment.
303
+ * @param output Everything emitted so far.
304
+ * @param environment The expression environment.
301
305
  * @param state The component's state table.
302
306
  *
303
307
  * @returns The lowered responder.
304
308
  */
305
- export function emitPanResponder(pan, out, env, state) {
309
+ export function emitPanResponder(pan, output, environment, state) {
306
310
  if (!pan.lowered) {
307
- pan.stateID = ++out.panN;
308
- pan.lowered = lowerPanResponder(pan, env, state, out);
309
- out.panResponders.push(pan.lowered);
311
+ pan.stateID = ++output.panCount;
312
+ pan.lowered = lowerPanResponder(pan, environment, state, output);
313
+ output.panResponders.push(pan.lowered);
310
314
  for (const panEvent of pan.lowered.events) {
311
- out.handlers.push({ kind: 'panEvent', pan: pan.lowered, event: panEvent });
315
+ output.handlers.push({
316
+ kind: 'panEvent',
317
+ pan: pan.lowered,
318
+ event: panEvent,
319
+ });
312
320
  }
313
321
  }
314
322
  return pan.lowered;
@@ -319,11 +327,11 @@ export function emitPanResponder(pan, out, env, state) {
319
327
  * or vice versa) is an error rather than a silent miss — Flow A would throw at runtime on the same code.
320
328
  *
321
329
  * @param argument The spread's argument.
322
- * @param env The expression environment.
330
+ * @param environment The expression environment.
323
331
  *
324
332
  * @returns The responder, or null when the spread is not `<responder>.panHandlers`.
325
333
  */
326
- export function panSpreadTarget(argument, env) {
334
+ export function panSpreadTarget(argument, environment) {
327
335
  // Only `<name>.panHandlers` or `<name>.current.panHandlers` can spread a responder.
328
336
  if (argument?.type !== 'MemberExpression' ||
329
337
  argument.computed ||
@@ -339,7 +347,7 @@ export function panSpreadTarget(argument, env) {
339
347
  ? handlersOwner.object.name
340
348
  : handlersOwner.name;
341
349
  const pan = handlersOwner.type === 'Identifier' || usesCurrent
342
- ? env.pans?.get(rootName)
350
+ ? environment.pans?.get(rootName)
343
351
  : null;
344
352
  if (!pan)
345
353
  return null;
@@ -23,7 +23,7 @@ import { isUndeclaredAttribute } from './elements/props.mjs';
23
23
  - Constants
24
24
  ---------------------------------------------------------------------------------------------------------------------*/
25
25
  // Type-only expression wrappers: `x as T`, `x satisfies T`, `x!`, `<T>x`, `f<T>` — unwrap to the inner expr.
26
- const TS_EXPR_WRAPPERS = new Set([
26
+ const TS_EXPRESSION_WRAPPERS = new Set([
27
27
  'TSAsExpression',
28
28
  'TSSatisfiesExpression',
29
29
  'TSNonNullExpression',
@@ -31,7 +31,7 @@ const TS_EXPR_WRAPPERS = new Set([
31
31
  'TSInstantiationExpression',
32
32
  ]);
33
33
  // Type-only declarations (no runtime presence) — dropped from any statement/body list.
34
- const TS_TYPE_DECLS = new Set([
34
+ const TS_TYPE_DECLARATIONS = new Set([
35
35
  'TSInterfaceDeclaration',
36
36
  'TSTypeAliasDeclaration',
37
37
  'TSDeclareFunction',
@@ -66,13 +66,13 @@ const TS_SKIP_KEYS = new Set([
66
66
  - Implementation
67
67
  ---------------------------------------------------------------------------------------------------------------------*/
68
68
  /**
69
- * Is this app a TypeScript entry? Driven by the filename extension, or an explicit opts.ts (for tests).
69
+ * Is this app a TypeScript entry? Driven by the filename extension, or an explicit options.ts (for tests).
70
70
  *
71
- * @param opts compileSource's options.
71
+ * @param options compilePackage's options.
72
72
  *
73
73
  * @returns Whether to parse the source as TypeScript.
74
74
  */
75
- const isTsEntry = (opts) => opts.ts ?? /\.[cm]?tsx$/.test(opts.filename || '');
75
+ const isTsEntry = (options) => options.ts ?? /\.[cm]?tsx$/.test(options.filename || '');
76
76
  /**
77
77
  * The Babel parser plugins for an entry.
78
78
  *
@@ -89,7 +89,7 @@ const parserPlugins = (isTypeScript) => isTypeScript ? ['jsx', 'typescript'] : [
89
89
  * @returns Whether it is type-only.
90
90
  */
91
91
  const isTypeOnly = (node) => !!node &&
92
- (TS_TYPE_DECLS.has(node.type) ||
92
+ (TS_TYPE_DECLARATIONS.has(node.type) ||
93
93
  // `import type ... ` / `export type ...`, and per-specifier `import { type X }`.
94
94
  ((node.type === 'ImportDeclaration' || node.type === 'ImportSpecifier') &&
95
95
  node.importKind === 'type') ||
@@ -104,7 +104,7 @@ const isTypeOnly = (node) => !!node &&
104
104
  * @returns The expression under every wrapper.
105
105
  */
106
106
  const unwrapTs = (node) => {
107
- while (node && TS_EXPR_WRAPPERS.has(node.type)) {
107
+ while (node && TS_EXPRESSION_WRAPPERS.has(node.type)) {
108
108
  node = node.expression;
109
109
  }
110
110
  return node;
@@ -139,7 +139,7 @@ function stripTypeScript(root) {
139
139
  for (let item of value) {
140
140
  if (isTypeOnly(item))
141
141
  continue;
142
- if (item && TS_EXPR_WRAPPERS.has(item.type)) {
142
+ if (item && TS_EXPRESSION_WRAPPERS.has(item.type)) {
143
143
  item = unwrapTs(item);
144
144
  }
145
145
  kept.push(item);
@@ -149,7 +149,7 @@ function stripTypeScript(root) {
149
149
  }
150
150
  else if (value && typeof value.type === 'string') {
151
151
  // A single child node: replace a type-only wrapper with the expression under it.
152
- if (TS_EXPR_WRAPPERS.has(value.type)) {
152
+ if (TS_EXPRESSION_WRAPPERS.has(value.type)) {
153
153
  value = unwrapTs(value);
154
154
  node[key] = value;
155
155
  }
@@ -210,10 +210,10 @@ export function normalizeUndefined(ast) {
210
210
  }
211
211
  };
212
212
  // A JSX attribute written as exactly `name={undefined}`.
213
- const isUndefinedAttr = (attr) => attr.type === 'JSXAttribute' &&
214
- attr.value?.type === 'JSXExpressionContainer' &&
215
- attr.value.expression.type === 'Identifier' &&
216
- attr.value.expression.name === 'undefined';
213
+ const isUndefinedAttr = (attribute) => attribute.type === 'JSXAttribute' &&
214
+ attribute.value?.type === 'JSXExpressionContainer' &&
215
+ attribute.value.expression.type === 'Identifier' &&
216
+ attribute.value.expression.name === 'undefined';
217
217
  // Keys that never hold child nodes.
218
218
  const SKIP = new Set([
219
219
  'loc',
@@ -259,8 +259,8 @@ export function normalizeUndefined(ast) {
259
259
  break;
260
260
  case 'JSXOpeningElement':
261
261
  // An undeclared prop stays, so the element refuses it by name whatever its value.
262
- node.attributes = node.attributes.filter((attr) => !isUndefinedAttr(attr) ||
263
- isUndeclaredAttribute(node, attr));
262
+ node.attributes = node.attributes.filter((attribute) => !isUndefinedAttr(attribute) ||
263
+ isUndeclaredAttribute(node, attribute));
264
264
  break;
265
265
  }
266
266
  // Then walk every child node.
@@ -280,19 +280,21 @@ export function normalizeUndefined(ast) {
280
280
  }
281
281
  /**
282
282
  * Parses an app entry to a JS+JSX AST, transparently stripping TypeScript when the entry is .tsx (JSX is not
283
- * allowed in a .ts file). The strip is faithful: an App.tsx compiles to the same C as its untyped App.jsx twin.
283
+ * allowed in a .ts file). The strip is faithful: an App.tsx compiles to the same package as its untyped App.jsx twin.
284
284
  *
285
- * @param src The entry's source.
286
- * @param opts compileSource's options: its filename (or `ts`) decides whether it is TypeScript.
285
+ * @param source The entry's source.
286
+ * @param options compilePackage's options: its filename (or `ts`) decides whether it is TypeScript.
287
+ * @param readTypes Reads what the compile needs of the types, before they are stripped.
287
288
  *
288
289
  * @returns The parsed file.
289
290
  */
290
- export function parseApp(src, opts = {}) {
291
- const isTypeScript = isTsEntry(opts);
292
- const ast = parse(src, {
291
+ export function parseApp(source, options = {}, readTypes) {
292
+ const isTypeScript = isTsEntry(options);
293
+ const ast = parse(source, {
293
294
  sourceType: 'module',
294
295
  plugins: parserPlugins(isTypeScript),
295
296
  });
297
+ readTypes?.(ast);
296
298
  if (isTypeScript) {
297
299
  stripTypeScript(ast);
298
300
  }
@@ -0,0 +1,246 @@
1
+ /*
2
+ * Copyright 2026 Cory Lamming
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ // record-shapes.mts — the shapes an object state takes: its initial value, and the objects its setter is given.
17
+ /*----------------------------------------------------------------------------------------------------------------------
18
+ - Imports
19
+ ---------------------------------------------------------------------------------------------------------------------*/
20
+ import { aotError } from './diagnostics.mjs';
21
+ import { flattenTree, isObjectTree, propertyKey } from './records.mjs';
22
+ import { evalStatic, rethrowFoldLimit } from './static-eval.mjs';
23
+ import { returnedValues } from './updaters.mjs';
24
+ /*----------------------------------------------------------------------------------------------------------------------
25
+ - Constants
26
+ ---------------------------------------------------------------------------------------------------------------------*/
27
+ // Keys that never hold child AST nodes.
28
+ const SKIP_KEYS = new Set([
29
+ 'loc',
30
+ 'start',
31
+ 'end',
32
+ 'range',
33
+ 'extra',
34
+ 'leadingComments',
35
+ 'trailingComments',
36
+ 'innerComments',
37
+ ]);
38
+ /*----------------------------------------------------------------------------------------------------------------------
39
+ - Implementation
40
+ ---------------------------------------------------------------------------------------------------------------------*/
41
+ /**
42
+ * Whether a value can name a shape: a string, a finite number or a boolean.
43
+ *
44
+ * @param value The value.
45
+ *
46
+ * @returns Whether it can.
47
+ */
48
+ const isTagValue = (value) => typeof value === 'string' ||
49
+ typeof value === 'boolean' ||
50
+ (typeof value === 'number' && Number.isFinite(value));
51
+ /**
52
+ * The fields of an object literal, nested ones flattened; a field that folds holds its value.
53
+ *
54
+ * @param node The object.
55
+ * @param scope Compile-time constants in reach.
56
+ *
57
+ * @returns The object.
58
+ */
59
+ function writtenObjectOf(node, scope) {
60
+ const written = { fields: new Map(), spread: false, node };
61
+ const visit = (object, path) => {
62
+ for (const property of object.properties) {
63
+ if (property.type === 'SpreadElement') {
64
+ written.spread = true;
65
+ continue;
66
+ }
67
+ if (property.type !== 'ObjectProperty')
68
+ continue;
69
+ let key;
70
+ try {
71
+ key = propertyKey(property);
72
+ }
73
+ catch {
74
+ continue; // refused where the write is lowered
75
+ }
76
+ const fieldPath = [...path, key];
77
+ const { value: valueNode } = property;
78
+ if (valueNode.type === 'ObjectExpression') {
79
+ visit(valueNode, fieldPath);
80
+ continue;
81
+ }
82
+ let value;
83
+ let known = true;
84
+ try {
85
+ value = evalStatic(valueNode, scope);
86
+ }
87
+ catch (error) {
88
+ rethrowFoldLimit(error);
89
+ known = false;
90
+ }
91
+ if (known && isObjectTree(value)) {
92
+ for (const [nestedKey, nested] of flattenTree(value)) {
93
+ written.fields.set([...fieldPath, nestedKey].join('.'), {
94
+ known: true,
95
+ value: nested,
96
+ });
97
+ }
98
+ continue;
99
+ }
100
+ written.fields.set(fieldPath.join('.'), known ? { known, value, node: valueNode } : { known, node: valueNode });
101
+ }
102
+ };
103
+ visit(node, []);
104
+ return written;
105
+ }
106
+ /**
107
+ * The objects a value can be: itself, a side of a ternary, or what a function returns.
108
+ *
109
+ * @param node The value.
110
+ * @param scope Compile-time constants in reach.
111
+ * @param objects Takes the objects.
112
+ */
113
+ function collectObjects(node, scope, objects) {
114
+ if (node.type === 'ObjectExpression') {
115
+ objects.push(writtenObjectOf(node, scope));
116
+ }
117
+ else if (node.type === 'ConditionalExpression') {
118
+ collectObjects(node.consequent, scope, objects);
119
+ collectObjects(node.alternate, scope, objects);
120
+ }
121
+ else if (node.type === 'ArrowFunctionExpression' ||
122
+ node.type === 'FunctionExpression' ||
123
+ node.type === 'FunctionDeclaration') {
124
+ const values = node.body.type === 'BlockStatement'
125
+ ? returnedValues(node.body)
126
+ : [node.body];
127
+ values.forEach(value => collectObjects(value, scope, objects));
128
+ }
129
+ }
130
+ /**
131
+ * The objects a reducer returns.
132
+ *
133
+ * @param reducer The reducer.
134
+ * @param scope Compile-time constants in reach.
135
+ *
136
+ * @returns The objects.
137
+ */
138
+ export function returnedObjects(reducer, scope) {
139
+ const objects = [];
140
+ collectObjects(reducer, scope, objects);
141
+ return objects;
142
+ }
143
+ /**
144
+ * The objects a setter is called with anywhere in a component: given directly, as a side of a ternary, or by an
145
+ * updater.
146
+ *
147
+ * @param body The component's body.
148
+ * @param setter The setter's name.
149
+ * @param scope Compile-time constants in reach.
150
+ *
151
+ * @returns The objects.
152
+ */
153
+ export function writtenObjects(body, setter, scope) {
154
+ const objects = [];
155
+ const walk = (node) => {
156
+ if (Array.isArray(node)) {
157
+ node.forEach(walk);
158
+ return;
159
+ }
160
+ if (typeof node !== 'object' || node === null)
161
+ return;
162
+ const astNode = node;
163
+ if (astNode.type === 'CallExpression' &&
164
+ astNode.callee.type === 'Identifier' &&
165
+ astNode.callee.name === setter &&
166
+ astNode.arguments[0]) {
167
+ collectObjects(astNode.arguments[0], scope, objects);
168
+ }
169
+ for (const [key, child] of Object.entries(astNode)) {
170
+ if (!SKIP_KEYS.has(key))
171
+ walk(child);
172
+ }
173
+ };
174
+ walk(body);
175
+ return objects;
176
+ }
177
+ /**
178
+ * The shapes an object state takes, when it takes more than one: the initial value and each object written out in
179
+ * full, told apart by a field that holds a constant in each, the first such field of the initial value.
180
+ *
181
+ * @param name The state's name.
182
+ * @param setter The setter's name.
183
+ * @param initial The initial value's fields.
184
+ * @param written The objects the setter is given.
185
+ * @param write How a write of an object is written, for errors: by default a call to the setter.
186
+ *
187
+ * @returns The shapes, or null when the state has one shape.
188
+ */
189
+ export function recordShapesOf(name, setter, initial, written, write = object => `${setter}(${object})`) {
190
+ // A write that spreads the old value keeps its shape, so one that changes a constant of the initial value and adds
191
+ // a field no shape has is a new shape written as a spread.
192
+ const full = written.filter(object => !object.spread);
193
+ const known = new Set([
194
+ ...initial.keys(),
195
+ ...full.flatMap(object => [...object.fields.keys()]),
196
+ ]);
197
+ for (const object of written) {
198
+ if (!object.spread)
199
+ continue;
200
+ const added = [...object.fields.keys()].find(key => !known.has(key));
201
+ const retagged = [...object.fields].find(([key, field]) => field.known &&
202
+ isTagValue(initial.get(key)) &&
203
+ field.value !== initial.get(key));
204
+ if (!added || !retagged)
205
+ continue;
206
+ const [tagKey, { value }] = retagged;
207
+ const error = aotError(`AOT: a write that spreads "${name}" keeps its shape, so it can't add "${added}"`, `to give ${name} another shape, write the new shape out in full: ` +
208
+ `${write(`{${tagKey}: ${typeof value === 'string' ? `'${value}'` : String(value)}, ${added}: …}`)}.`);
209
+ if (object.node.loc)
210
+ error.aotLoc = object.node.loc.start;
211
+ throw error;
212
+ }
213
+ const keysDiffer = (object) => [...object.fields.keys()].some(key => !initial.has(key)) ||
214
+ (!object.spread && object.fields.size !== initial.size);
215
+ if (!full.length || !written.some(keysDiffer))
216
+ return null;
217
+ for (const [key, initialValue] of initial) {
218
+ if (key.includes('.') || !isTagValue(initialValue))
219
+ continue;
220
+ const values = [initialValue];
221
+ const shapes = [
222
+ new Set([...initial.keys()].filter(field => field !== key)),
223
+ ];
224
+ const agrees = full.every(object => {
225
+ const tag = object.fields.get(key);
226
+ if (!tag?.known || typeof tag.value !== typeof initialValue)
227
+ return false;
228
+ if (!isTagValue(tag.value))
229
+ return false;
230
+ const fields = new Set([...object.fields.keys()].filter(field => field !== key));
231
+ const shape = values.indexOf(tag.value);
232
+ if (shape < 0) {
233
+ values.push(tag.value);
234
+ shapes.push(fields);
235
+ return true;
236
+ }
237
+ return (shapes[shape].size === fields.size &&
238
+ [...fields].every(field => shapes[shape].has(field)));
239
+ });
240
+ if (agrees && values.length > 1)
241
+ return { key, values, shapes };
242
+ }
243
+ throw aotError(`AOT: state "${name}" is written with objects of different fields`, `an object of several shapes needs a field naming the shape, with a constant written in each: ` +
244
+ `${write("{kind: 'busy', pct: 0}")}. Write each new shape out in full; a write that keeps the shape ` +
245
+ `spreads the old value: ${write(`{...${name}, pct: 1}`)}.`);
246
+ }