embedded-react 0.20.0 → 0.22.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 (140) hide show
  1. package/NOTICE +5 -0
  2. package/README.md +3 -2
  3. package/aot/app-file-loader.mjs +116 -0
  4. package/aot/compile.mjs +17 -47
  5. package/aot/compiler/alerts.mjs +604 -0
  6. package/aot/compiler/animations.mjs +299 -57
  7. package/aot/compiler/boot.mjs +27 -2
  8. package/aot/compiler/check.mjs +62 -10
  9. package/aot/compiler/collect.mjs +517 -137
  10. package/aot/compiler/contexts.mjs +391 -0
  11. package/aot/compiler/control-flow.mjs +276 -117
  12. package/aot/compiler/custom-hooks.mjs +686 -0
  13. package/aot/compiler/elements/button.mjs +182 -0
  14. package/aot/compiler/elements/image-background.mjs +76 -0
  15. package/aot/compiler/elements/image.mjs +2 -1
  16. package/aot/compiler/elements/props.mjs +47 -8
  17. package/aot/compiler/elements/rewrite.mjs +118 -0
  18. package/aot/compiler/elements/section-list.mjs +370 -0
  19. package/aot/compiler/expressions.mjs +1378 -97
  20. package/aot/compiler/handlers.mjs +1807 -354
  21. package/aot/compiler/helper-values.mjs +312 -0
  22. package/aot/compiler/ir/nodes.mjs +40 -1
  23. package/aot/compiler/ir/reads.mjs +206 -5
  24. package/aot/compiler/ir/text.mjs +5 -1
  25. package/aot/compiler/ir/types.mjs +12 -0
  26. package/aot/compiler/kept-states.mjs +177 -0
  27. package/aot/compiler/keyboard-dismiss.mjs +99 -0
  28. package/aot/compiler/keyboard.mjs +1 -1
  29. package/aot/compiler/list-items.mjs +226 -0
  30. package/aot/compiler/list-order.mjs +586 -0
  31. package/aot/compiler/list-split.mjs +259 -0
  32. package/aot/compiler/loops.mjs +582 -0
  33. package/aot/compiler/lower.mjs +203 -53
  34. package/aot/compiler/native-files.mjs +439 -0
  35. package/aot/compiler/native-header.mjs +335 -0
  36. package/aot/compiler/native-modules.mjs +1173 -0
  37. package/aot/compiler/nodes.mjs +45 -31
  38. package/aot/compiler/options.mjs +3 -2
  39. package/aot/compiler/out.mjs +18 -1
  40. package/aot/compiler/package/animations.mjs +133 -23
  41. package/aot/compiler/package/assemble.mjs +2 -4
  42. package/aot/compiler/package/bytecode.mjs +37 -8
  43. package/aot/compiler/package/checks.mjs +4 -0
  44. package/aot/compiler/package/codegen.mjs +906 -33
  45. package/aot/compiler/package/enums.mjs +10 -0
  46. package/aot/compiler/package/format.mjs +16 -3
  47. package/aot/compiler/package/lower.mjs +707 -176
  48. package/aot/compiler/package/string-caps.mjs +515 -0
  49. package/aot/compiler/package/tables.mjs +24 -0
  50. package/aot/compiler/package/writer.mjs +22 -0
  51. package/aot/compiler/parse.mjs +3 -1
  52. package/aot/compiler/record-shapes.mjs +246 -0
  53. package/aot/compiler/records.mjs +654 -0
  54. package/aot/compiler/reducers.mjs +272 -0
  55. package/aot/compiler/scroll-to.mjs +112 -0
  56. package/aot/compiler/static-eval.mjs +315 -7
  57. package/aot/compiler/style-text.mjs +20 -5
  58. package/aot/compiler/svg.mjs +13 -7
  59. package/aot/compiler/switch-cases.mjs +198 -0
  60. package/aot/compiler/tagged-records.mjs +450 -0
  61. package/aot/compiler/typing.mjs +307 -0
  62. package/aot/compiler/updaters.mjs +321 -0
  63. package/aot/compiler/window-dimensions.mjs +94 -0
  64. package/aot/compiler/worked-values.mjs +319 -0
  65. package/aot/demo-file.mjs +30 -0
  66. package/aot/style-map.mjs +94 -3
  67. package/assets/bake-font.mjs +187 -244
  68. package/assets/bake-image.mjs +47 -71
  69. package/assets/bake-svg.mjs +465 -533
  70. package/assets/build-builtin-font.mjs +14 -27
  71. package/assets/emit-c.mjs +124 -204
  72. package/assets/emit-container.mjs +129 -197
  73. package/assets/emit-pack.mjs +92 -136
  74. package/assets/font-config.mjs +19 -27
  75. package/assets/font-sizes.mjs +432 -507
  76. package/assets/glyph-coverage.mjs +170 -214
  77. package/assets/index.mjs +52 -97
  78. package/assets/rasterize.mjs +173 -194
  79. package/assets/svg-loader.mjs +42 -48
  80. package/build.mjs +85 -94
  81. package/cli.mjs +490 -586
  82. package/compile-bin.mjs +24 -36
  83. package/flash.mjs +297 -401
  84. package/hotreload/dev-device.mjs +229 -270
  85. package/hotreload/pack-app.mjs +118 -159
  86. package/hotreload/pack-split.mjs +146 -213
  87. package/hotreload/package-transfer.mjs +128 -131
  88. package/hotreload/protocol.mjs +118 -118
  89. package/hotreload/uploader.mjs +132 -159
  90. package/hotreload/watch-tree.mjs +56 -65
  91. package/pack-container.mjs +94 -116
  92. package/package.json +19 -16
  93. package/persist-transform.mjs +89 -105
  94. package/qjsc-wasm.mjs +47 -72
  95. package/sim/embedded-react.wasm +0 -0
  96. package/sim/index.html +1 -1
  97. package/sim-server.mjs +260 -354
  98. package/src/embedded-react/Alert.mjs +112 -0
  99. package/src/embedded-react/Animated.mjs +412 -0
  100. package/src/embedded-react/{AppRegistry.js → AppRegistry.mjs} +26 -25
  101. package/src/embedded-react/{Button.js → Button.mjs} +29 -53
  102. package/src/embedded-react/Dimensions.mjs +32 -0
  103. package/src/embedded-react/Easing.mjs +34 -0
  104. package/src/embedded-react/{FlatList.js → FlatList.mjs} +25 -42
  105. package/src/embedded-react/{ImageBackground.js → ImageBackground.mjs} +11 -22
  106. package/src/embedded-react/Keyboard.mjs +82 -0
  107. package/src/embedded-react/{LayoutAnimation.js → LayoutAnimation.mjs} +17 -28
  108. package/src/embedded-react/PanResponder.mjs +256 -0
  109. package/src/embedded-react/{Platform.js → Platform.mjs} +8 -9
  110. package/src/embedded-react/{Pressable.js → Pressable.mjs} +12 -25
  111. package/src/embedded-react/SectionList.mjs +103 -0
  112. package/src/embedded-react/{StyleSheet.js → StyleSheet.mjs} +16 -20
  113. package/src/embedded-react/{TouchableOpacity.js → TouchableOpacity.mjs} +47 -83
  114. package/src/embedded-react/background-image.mjs +321 -0
  115. package/src/embedded-react/{components.js → components.mjs} +1 -3
  116. package/src/embedded-react/{imperative.js → imperative.mjs} +27 -38
  117. package/src/embedded-react/index.d.ts +238 -5
  118. package/src/embedded-react/index.js +26 -17
  119. package/src/embedded-react/layout-anim-config.mjs +85 -0
  120. package/src/embedded-react/{list-child.js → list-child.mjs} +11 -20
  121. package/src/embedded-react/{named-colors.js → named-colors.mjs} +2 -6
  122. package/src/embedded-react/nativeModule.mjs +371 -0
  123. package/src/embedded-react/split-style.mjs +57 -0
  124. package/src/embedded-react/svg-ops.mjs +1075 -0
  125. package/src/embedded-react/{useHostValue.js → useHostValue.mjs} +2 -4
  126. package/src/embedded-react/{usePersistentState.js → usePersistentState.mjs} +34 -38
  127. package/src/embedded-react/{warn-props.js → warn-props.mjs} +32 -39
  128. package/src/host-config.mjs +512 -0
  129. package/src/{native-ui.js → native-ui.mjs} +1 -8
  130. package/src/props.mjs +341 -0
  131. package/src/{renderer.js → renderer.mjs} +30 -44
  132. package/src/embedded-react/Animated.js +0 -440
  133. package/src/embedded-react/Easing.js +0 -39
  134. package/src/embedded-react/PanResponder.js +0 -330
  135. package/src/embedded-react/SectionList.js +0 -148
  136. package/src/embedded-react/layout-anim-config.js +0 -101
  137. package/src/embedded-react/split-style.js +0 -58
  138. package/src/embedded-react/svg-ops.js +0 -1295
  139. package/src/host-config.js +0 -548
  140. package/src/props.js +0 -306
@@ -0,0 +1,177 @@
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
+ /*
17
+ * A handler, effect or timer reads the state its render had: `setCount(count + 1)` leaves `count` as it was for the
18
+ * rest of the body. A setter writes its slot at once, so a body that sets a state and then reads it starts by
19
+ * keeping a copy, which its reads use. An updater's parameter and a reducer's state still read the slot.
20
+ */
21
+ /*----------------------------------------------------------------------------------------------------------------------
22
+ - Imports
23
+ ---------------------------------------------------------------------------------------------------------------------*/
24
+ import { defersTyping, whenTyped } from './check.mjs';
25
+ /*----------------------------------------------------------------------------------------------------------------------
26
+ - Constants
27
+ ---------------------------------------------------------------------------------------------------------------------*/
28
+ /** What a walk doesn't follow: an expression before typing repeats its reads, and the rest hold none. */
29
+ const SKIPPED_KEYS = new Set(['source', 'location', 'readsLatest']);
30
+ /*----------------------------------------------------------------------------------------------------------------------
31
+ - Implementation
32
+ ---------------------------------------------------------------------------------------------------------------------*/
33
+ /**
34
+ * Marks the statements an object state's updater or reducer lowered to, so their reads of its fields give what they
35
+ * hold now.
36
+ *
37
+ * @param statements The statements.
38
+ * @param states The slots of the state set.
39
+ *
40
+ * @returns The statements, marked, and those inside them.
41
+ */
42
+ export function readingLatest(statements, states) {
43
+ if (!states.size)
44
+ return statements;
45
+ // Each is marked in place: the typing pass has yet to fill some in, which a copy would miss.
46
+ return statements.map(statement => {
47
+ const marked = Object.assign(statement, { readsLatest: states });
48
+ switch (marked.kind) {
49
+ case 'if':
50
+ marked.consequent = readingLatest(marked.consequent, states);
51
+ marked.alternate =
52
+ marked.alternate && readingLatest(marked.alternate, states);
53
+ break;
54
+ case 'block':
55
+ case 'updateItems':
56
+ marked.body = readingLatest(marked.body, states);
57
+ break;
58
+ case 'loop':
59
+ marked.body = readingLatest(marked.body, states);
60
+ marked.step = readingLatest(marked.step, states);
61
+ break;
62
+ }
63
+ return marked;
64
+ });
65
+ }
66
+ /**
67
+ * The states a body reads after setting them.
68
+ *
69
+ * @param body The body's statements.
70
+ *
71
+ * @returns The states, in the order they are first read so.
72
+ */
73
+ function statesReadAfterSet(body) {
74
+ let written = new Set();
75
+ const found = new Set();
76
+ const path = new Set();
77
+ /** Every state the statements under a value set. */
78
+ const sets = (value, into) => {
79
+ if (!value || typeof value !== 'object' || path.has(value))
80
+ return;
81
+ if (Array.isArray(value)) {
82
+ value.forEach(element => sets(element, into));
83
+ return;
84
+ }
85
+ const node = value;
86
+ if ('slotName' in node)
87
+ return;
88
+ if (node.kind === 'setState' || node.kind === 'setStateText') {
89
+ into.add(node.state);
90
+ }
91
+ path.add(node);
92
+ for (const [key, child] of Object.entries(node)) {
93
+ if (!SKIPPED_KEYS.has(key))
94
+ sets(child, into);
95
+ }
96
+ path.delete(node);
97
+ };
98
+ const walk = (value, latest) => {
99
+ if (!value || typeof value !== 'object' || path.has(value))
100
+ return;
101
+ if (Array.isArray(value)) {
102
+ value.forEach(element => walk(element, latest));
103
+ return;
104
+ }
105
+ const node = value;
106
+ // A state or a list itself, which a statement names.
107
+ if ('slotName' in node)
108
+ return;
109
+ if (node.kind === 'state' && 'type' in node) {
110
+ const state = node.state;
111
+ if (written.has(state) && !node.latest && !latest?.has(state)) {
112
+ found.add(state);
113
+ }
114
+ return;
115
+ }
116
+ // A field given back as it was reads it, where the body set it before.
117
+ if (node.kind === 'keepField') {
118
+ const state = node.state;
119
+ const live = node.readsLatest ?? latest;
120
+ if (written.has(state) && !live?.has(state))
121
+ found.add(state);
122
+ return;
123
+ }
124
+ const reads = node.readsLatest ?? latest;
125
+ // Only one branch runs, so neither reads what the other set.
126
+ if (node.kind === 'if') {
127
+ walk(node.test, reads);
128
+ // A branch that returns sets nothing for what comes after.
129
+ const returns = (branch) => Array.isArray(branch) && branch.at(-1)?.kind === 'return';
130
+ const before = new Set(written);
131
+ walk(node.consequent, reads);
132
+ const consequent = returns(node.consequent) ? before : written;
133
+ written = new Set(before);
134
+ walk(node.alternate, reads);
135
+ if (returns(node.alternate))
136
+ written = new Set(before);
137
+ consequent.forEach(state => written.add(state));
138
+ return;
139
+ }
140
+ // A loop's later visits read what its earlier ones set.
141
+ if (node.kind === 'loop')
142
+ sets(node, written);
143
+ path.add(node);
144
+ for (const [key, child] of Object.entries(node)) {
145
+ if (!SKIPPED_KEYS.has(key))
146
+ walk(child, reads);
147
+ }
148
+ path.delete(node);
149
+ // A setter's own value reads the state before it is set.
150
+ if (node.kind === 'setState' || node.kind === 'setStateText') {
151
+ written.add(node.state);
152
+ }
153
+ };
154
+ walk(body, undefined);
155
+ return [...found];
156
+ }
157
+ /**
158
+ * Starts a body by keeping a copy of each state it sets and then reads, for those reads.
159
+ *
160
+ * @param body The body's statements.
161
+ * @param output Everything emitted so far; the states kept are added to it.
162
+ *
163
+ * @returns The body, after the copies when it needs any.
164
+ */
165
+ export function keepingStates(body, output) {
166
+ // What the body reads is known once it is typed, so the copies are found then: none leaves nothing to keep.
167
+ const states = [];
168
+ const kept = [{ kind: 'keepStates', states }, ...body];
169
+ whenTyped(() => {
170
+ states.push(...statesReadAfterSet(body));
171
+ states.forEach(state => output.keptStates.add(state));
172
+ if (!states.length && kept[0]?.kind === 'keepStates') {
173
+ kept.shift();
174
+ }
175
+ });
176
+ return defersTyping() || states.length ? kept : body;
177
+ }
@@ -0,0 +1,99 @@
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
+ /**
17
+ * @file compiler/keyboard-dismiss.mts
18
+ * @brief Finds each `Keyboard.dismiss()`, by the package's own export, and refuses any other use of Keyboard.
19
+ */
20
+ import { traverse } from '@babel/core';
21
+ import { aotError } from './diagnostics.mjs';
22
+ /*----------------------------------------------------------------------------------------------------------------------
23
+ - Constants
24
+ ---------------------------------------------------------------------------------------------------------------------*/
25
+ /** The package Keyboard is imported from. */
26
+ const PACKAGE = 'embedded-react';
27
+ /** What a `Keyboard.dismiss()` is rewritten to call. Not a name JS allows, so no binding of the app's is one. */
28
+ export const KEYBOARD_DISMISS_CALL = '#Keyboard.dismiss';
29
+ const HINT = 'Keyboard.dismiss() is the one Keyboard call a package has; to follow the keyboard, set state in the ' +
30
+ "<TextInput>'s onFocus and onBlur.";
31
+ /*----------------------------------------------------------------------------------------------------------------------
32
+ - Implementation
33
+ ---------------------------------------------------------------------------------------------------------------------*/
34
+ /**
35
+ * Whether a name stands for the package's Keyboard where it is read. A local, a prop or a state of that name hides
36
+ * the import.
37
+ *
38
+ * @param path Where the name is read.
39
+ *
40
+ * @returns Whether it does.
41
+ */
42
+ function isKeyboard(path) {
43
+ const binding = path.scope.getBinding(path.node.name);
44
+ const specifier = binding?.path.node;
45
+ const declaration = binding?.path.parent;
46
+ if (specifier?.type !== 'ImportSpecifier' ||
47
+ declaration?.type !== 'ImportDeclaration' ||
48
+ declaration.source.value !== PACKAGE) {
49
+ return false;
50
+ }
51
+ const { imported } = specifier;
52
+ return ((imported.type === 'Identifier' ? imported.name : imported.value) ===
53
+ 'Keyboard');
54
+ }
55
+ /**
56
+ * Rewrites every `Keyboard.dismiss()` to a call of KEYBOARD_DISMISS_CALL, by whatever name Keyboard is imported.
57
+ *
58
+ * @param ast The parsed file, rewritten in place.
59
+ *
60
+ * @throws An AotError for any other use of Keyboard.
61
+ */
62
+ export function rewriteKeyboardDismiss(ast) {
63
+ traverse.cache.clear();
64
+ traverse(ast, {
65
+ Identifier(path) {
66
+ if (!path.isReferencedIdentifier() || !isKeyboard(path))
67
+ return;
68
+ const member = path.parent;
69
+ const call = path.parentPath?.parent;
70
+ const method = member.type === 'MemberExpression' &&
71
+ member.object === path.node &&
72
+ !member.computed &&
73
+ member.property.type === 'Identifier' &&
74
+ call?.type === 'CallExpression' &&
75
+ call.callee === member
76
+ ? member.property.name
77
+ : null;
78
+ if (method === 'dismiss' &&
79
+ call.arguments.length === 0) {
80
+ call.callee = {
81
+ type: 'Identifier',
82
+ name: KEYBOARD_DISMISS_CALL,
83
+ loc: member.loc,
84
+ };
85
+ path.skip();
86
+ return;
87
+ }
88
+ const error = aotError(method === 'dismiss'
89
+ ? 'AOT: Keyboard.dismiss() takes no arguments'
90
+ : method
91
+ ? `AOT: Keyboard.${method}() is not in the subset`
92
+ : 'AOT: Keyboard has only Keyboard.dismiss()', HINT);
93
+ if (path.node.loc)
94
+ error.aotLoc = path.node.loc.start;
95
+ throw error;
96
+ },
97
+ });
98
+ traverse.cache.clear();
99
+ }
@@ -16,7 +16,7 @@
16
16
  /*----------------------------------------------------------------------------------------------------------------------
17
17
  - Imports
18
18
  ---------------------------------------------------------------------------------------------------------------------*/
19
- import { parseColor } from '../../src/embedded-react/svg-ops.js';
19
+ import { parseColor } from '../../src/embedded-react/svg-ops.mjs';
20
20
  import { aotError, withLoc } from './diagnostics.mjs';
21
21
  import { evalStatic } from './static-eval.mjs';
22
22
  /*----------------------------------------------------------------------------------------------------------------------
@@ -0,0 +1,226 @@
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
+ // list-items.mts — the fields of a list's items: worked out from its initial items, and laid out in a row.
17
+ /*----------------------------------------------------------------------------------------------------------------------
18
+ - Imports
19
+ ---------------------------------------------------------------------------------------------------------------------*/
20
+ import { readLocalOf, settledOf } from './typing.mjs';
21
+ import { aotError } from './diagnostics.mjs';
22
+ /*----------------------------------------------------------------------------------------------------------------------
23
+ - Implementation
24
+ ---------------------------------------------------------------------------------------------------------------------*/
25
+ /**
26
+ * Whether a value is a plain object, as an item or a nested field is.
27
+ *
28
+ * @param value The value.
29
+ *
30
+ * @returns Whether it is one.
31
+ */
32
+ export const isPlainObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
33
+ /**
34
+ * The kind of field a value is stored in, or null when it is none.
35
+ *
36
+ * @param value The value.
37
+ *
38
+ * @returns The kind.
39
+ */
40
+ function kindOf(value) {
41
+ if (typeof value === 'string')
42
+ return 'string';
43
+ if (typeof value === 'boolean')
44
+ return 'bool';
45
+ if (typeof value === 'number') {
46
+ return Number.isInteger(value) ? 'int' : 'float';
47
+ }
48
+ return null;
49
+ }
50
+ /**
51
+ * Whether two kinds can share a field: a whole number and a fraction can, as a fraction.
52
+ *
53
+ * @param first The kind the field has.
54
+ * @param other Another item's kind.
55
+ *
56
+ * @returns Whether they agree.
57
+ */
58
+ const kindsAgree = (first, other) => first === other ||
59
+ ((first === 'int' || first === 'float') &&
60
+ (other === 'int' || other === 'float'));
61
+ /**
62
+ * Works out the fields of a list's items from its initial items. Objects take the union of their fields, nested
63
+ * objects flattened into dotted paths; a field some item leaves out, or sets to null, is optional. Plain values
64
+ * (numbers, strings or booleans) are one field. A number field is a fraction when any item's value is one.
65
+ *
66
+ * @param items The initial items.
67
+ * @param what The list, for errors: `list state "items"`.
68
+ *
69
+ * @returns The struct.
70
+ */
71
+ export function inferItemStruct(items, what) {
72
+ const shapeHint = 'a list holds objects with string, number or boolean fields (nested objects too), or plain numbers, strings ' +
73
+ 'or booleans, e.g. useState([{title: "A", n: 1}, {title: "B", n: 2}]).';
74
+ if (!Array.isArray(items) || !items.length) {
75
+ throw aotError(`AOT: ${what} needs ≥1 initial element to infer its item shape`, shapeHint);
76
+ }
77
+ // Plain values: one field, of the values' kind.
78
+ if (!items.some(isPlainObject)) {
79
+ const kind = kindOf(items[0]);
80
+ if (!kind ||
81
+ items.some(item => !kindOf(item) || !kindsAgree(kind, kindOf(item)))) {
82
+ throw aotError(`AOT: ${what} must hold objects, or values of one kind (numbers, strings or booleans)`, shapeHint);
83
+ }
84
+ const widened = items.some(item => kindOf(item) === 'float')
85
+ ? 'float'
86
+ : kind;
87
+ return { fields: [{ key: '', path: [], kind: widened }], plain: true };
88
+ }
89
+ if (!items.every(isPlainObject)) {
90
+ throw aotError(`AOT: ${what} elements must all be objects`, shapeHint);
91
+ }
92
+ // Each field in the order it first appears, typed by the items' values.
93
+ const fields = new Map();
94
+ const objects = new Set();
95
+ const nulls = new Set();
96
+ const visit = (object, path) => {
97
+ const keys = Object.keys(object);
98
+ if (path.length && !keys.length) {
99
+ throw aotError(`AOT: field "${path.join('.')}" of ${what} is an empty object`, 'give it a field, or leave it out.');
100
+ }
101
+ for (const key of keys) {
102
+ const fieldPath = [...path, key];
103
+ const name = fieldPath.join('.');
104
+ if (key.includes('.') || key === '') {
105
+ throw aotError(`AOT: ${what} has a field named "${key}"`, 'name each field with letters, digits or `_`.');
106
+ }
107
+ const value = object[key];
108
+ if (isPlainObject(value)) {
109
+ if (fields.has(name)) {
110
+ throw aotError(`AOT: field "${name}" of ${what} is a value in one item and an object in another`, shapeHint);
111
+ }
112
+ objects.add(name);
113
+ visit(value, fieldPath);
114
+ continue;
115
+ }
116
+ if (value == null) {
117
+ nulls.add(name);
118
+ continue;
119
+ }
120
+ const kind = kindOf(value);
121
+ if (!kind || objects.has(name)) {
122
+ throw aotError(`AOT: field "${name}" of ${what} must be a string, a number, a boolean or an object of those`, shapeHint);
123
+ }
124
+ const field = fields.get(name);
125
+ if (!field) {
126
+ fields.set(name, { key: name, path: fieldPath, kind });
127
+ }
128
+ else if (!kindsAgree(field.kind, kind)) {
129
+ throw aotError(`AOT: field "${name}" of ${what} is a ${field.kind === 'bool' ? 'boolean' : field.kind === 'string' ? 'string' : 'number'} in one item and not in another`, shapeHint);
130
+ }
131
+ else if (kind === 'float') {
132
+ field.kind = 'float';
133
+ }
134
+ }
135
+ };
136
+ items.forEach(item => visit(item, []));
137
+ // A field that is null in every item has no kind.
138
+ for (const name of nulls) {
139
+ if (!fields.has(name) && !objects.has(name)) {
140
+ throw aotError(`AOT: field "${name}" of ${what} is null in every item`, 'give one item a value for it, so the field has a kind.');
141
+ }
142
+ }
143
+ const struct = { fields: [...fields.values()] };
144
+ for (const field of struct.fields) {
145
+ if (items.some(item => !itemValueAt(item, field).present)) {
146
+ field.optional = true;
147
+ }
148
+ }
149
+ return struct;
150
+ }
151
+ /**
152
+ * A field's value in an item: missing when the item, or an object on the way, leaves it out or holds null.
153
+ *
154
+ * @param item The item.
155
+ * @param field The field.
156
+ *
157
+ * @returns The value, and whether it is there.
158
+ */
159
+ export function itemValueAt(item, field) {
160
+ let value = item;
161
+ for (const key of field.path) {
162
+ if (!isPlainObject(value) || !Object.hasOwn(value, key)) {
163
+ return { present: false, value: undefined };
164
+ }
165
+ value = value[key];
166
+ }
167
+ return value == null
168
+ ? { present: false, value: undefined }
169
+ : { present: true, value };
170
+ }
171
+ /**
172
+ * The fields of a row in order: every value, then a flag for each optional one.
173
+ *
174
+ * @param struct The items' fields.
175
+ *
176
+ * @returns The row's fields.
177
+ */
178
+ export const rowEntries = (struct) => [
179
+ ...struct.fields.map(field => ({ field, presence: false })),
180
+ ...struct.fields
181
+ .filter(field => field.optional)
182
+ .map(field => ({ field, presence: true })),
183
+ ];
184
+ /**
185
+ * Where a field, or its flag, is in a row.
186
+ *
187
+ * @param struct The items' fields.
188
+ * @param field The field.
189
+ * @param presence The flag rather than the value.
190
+ *
191
+ * @returns Its index.
192
+ */
193
+ export function rowIndexOf(struct, field, presence = false) {
194
+ const index = rowEntries(struct).findIndex(entry => entry.field === field && entry.presence === presence);
195
+ if (index < 0) {
196
+ throw new Error(`AOT internal: no row field for "${field.key}"`);
197
+ }
198
+ return index;
199
+ }
200
+ /**
201
+ * The fields at or under a path: the field itself, or every field of the object there.
202
+ *
203
+ * @param struct The items' fields.
204
+ * @param path The path.
205
+ *
206
+ * @returns The fields, none when nothing is there.
207
+ */
208
+ export function fieldsUnder(struct, path) {
209
+ return struct.fields.filter(field => field.path.length >= path.length &&
210
+ path.every((key, index) => field.path[index] === key));
211
+ }
212
+ /**
213
+ * The list item field an expression reads, directly or through a local that stands for it (a prop given one).
214
+ *
215
+ * @param expression The expression.
216
+ *
217
+ * @returns The read, or null.
218
+ */
219
+ export function itemReadOf(expression) {
220
+ const settled = settledOf(expression);
221
+ if (settled?.kind === 'itemField') {
222
+ return settled;
223
+ }
224
+ const local = readLocalOf(expression);
225
+ return local?.expression ? itemReadOf(local.expression) : null;
226
+ }