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
@@ -13,163 +13,160 @@
13
13
  * See the License for the specific language governing permissions and
14
14
  * limitations under the License.
15
15
  */
16
-
17
16
  // package-transfer — sends a Flow B package to a board, as ERHR frames, one at a time.
18
17
  //
19
18
  // The device writes each chunk straight into its staging slot, and flash stalls the chip while it does. So this sends
20
19
  // one frame and waits for the reply, which keeps a UART with no flow control from losing bytes. The device's side is
21
20
  // runtime/erb_package_reload.c, whose header lists the replies.
22
-
23
- import {
24
- MSG_PACKAGE_BEGIN,
25
- MSG_PACKAGE_CHUNK,
26
- encodeFrame,
27
- } from './protocol.mjs';
28
-
21
+ import { MSG_PACKAGE_BEGIN, MSG_PACKAGE_CHUNK, encodeFrame, } from './protocol.mjs';
29
22
  const CHUNK_OFFSET_BYTES = 4;
30
23
  const BEGIN_RESEND_MS = 1000; // a board that is resetting, or holding a boot error on screen, misses a begin
31
24
  const BEGIN_TIMEOUT_MS = 15000;
32
25
  const CHUNK_TIMEOUT_MS = 2000;
33
26
  const CHUNK_RESENDS = 5;
34
27
  const LOAD_TIMEOUT_MS = 15000; // checking a large package from flash takes a slow board a few seconds
35
-
36
28
  const READY_LINE = /erb reload: ready (\d+)/;
37
29
  const GOT_LINE = /erb reload: got (\d+)/;
38
-
39
30
  /** What a line from the device says, or null when it is only a log. */
40
31
  export function parseReply(line) {
41
- const readyMatch = READY_LINE.exec(line);
42
- if (readyMatch) return {kind: 'ready', value: Number(readyMatch[1])};
43
- const gotMatch = GOT_LINE.exec(line);
44
- if (gotMatch) return {kind: 'got', value: Number(gotMatch[1])};
45
- if (/dropped frame/i.test(line)) return {kind: 'dropped'};
46
- if (/hot reload:\s*ok\b/i.test(line)) return {kind: 'ok'};
47
- if (/hot reload:/i.test(line)) return {kind: 'rejected'};
48
- return null;
32
+ const readyMatch = READY_LINE.exec(line);
33
+ if (readyMatch)
34
+ return { kind: 'ready', value: Number(readyMatch[1]) };
35
+ const gotMatch = GOT_LINE.exec(line);
36
+ if (gotMatch)
37
+ return { kind: 'got', value: Number(gotMatch[1]) };
38
+ if (/dropped frame/i.test(line))
39
+ return { kind: 'dropped' };
40
+ if (/hot reload:\s*ok\b/i.test(line))
41
+ return { kind: 'ok' };
42
+ if (/hot reload:/i.test(line))
43
+ return { kind: 'rejected' };
44
+ return null;
49
45
  }
50
-
51
46
  /** The frame that starts a package. */
52
47
  export function beginFrame(packageBytes) {
53
- const payload = Buffer.alloc(CHUNK_OFFSET_BYTES);
54
- payload.writeUInt32LE(packageBytes, 0);
55
- return encodeFrame(payload, {type: MSG_PACKAGE_BEGIN});
48
+ const payload = Buffer.alloc(CHUNK_OFFSET_BYTES);
49
+ payload.writeUInt32LE(packageBytes, 0);
50
+ return encodeFrame(payload, { type: MSG_PACKAGE_BEGIN });
56
51
  }
57
-
58
52
  /** The frame for the bytes of @p packageData at @p offset. */
59
53
  export function chunkFrame(packageData, offset, chunkBytes) {
60
- const chunk = packageData.subarray(offset, offset + chunkBytes);
61
- const payload = Buffer.alloc(CHUNK_OFFSET_BYTES + chunk.length);
62
- payload.writeUInt32LE(offset, 0);
63
- chunk.copy(payload, CHUNK_OFFSET_BYTES);
64
- return encodeFrame(payload, {type: MSG_PACKAGE_CHUNK});
54
+ const chunk = packageData.subarray(offset, offset + chunkBytes);
55
+ const payload = Buffer.alloc(CHUNK_OFFSET_BYTES + chunk.length);
56
+ payload.writeUInt32LE(offset, 0);
57
+ chunk.copy(payload, CHUNK_OFFSET_BYTES);
58
+ return encodeFrame(payload, { type: MSG_PACKAGE_CHUNK });
65
59
  }
66
-
67
60
  export class PackageTransfer {
68
- /**
69
- * @param {object} options
70
- * @param {(frame: Buffer) => Promise<unknown>} options.write Writes a frame to the device.
71
- */
72
- constructor({
73
- write,
74
- beginResendMs = BEGIN_RESEND_MS,
75
- chunkTimeoutMs = CHUNK_TIMEOUT_MS,
76
- chunkResends = CHUNK_RESENDS,
77
- loadTimeoutMs = LOAD_TIMEOUT_MS,
78
- }) {
79
- this.write = write;
80
- this.beginResendMs = beginResendMs;
81
- this.chunkTimeoutMs = chunkTimeoutMs;
82
- this.chunkResends = chunkResends;
83
- this.loadTimeoutMs = loadTimeoutMs;
84
- this._replies = [];
85
- this._wake = null;
86
- }
87
-
88
- /** Takes a line from the device. Returns true when it is part of the transfer and not worth showing. */
89
- onLine(line) {
90
- const reply = parseReply(line);
91
- if (!reply) return false;
92
- this._replies.push(reply);
93
- if (this._wake) this._wake();
94
- return reply.kind === 'ready' || reply.kind === 'got';
95
- }
96
-
97
- /** The next reply, or null after @p timeoutMs. */
98
- async _nextReply(timeoutMs) {
99
- if (!this._replies.length) {
100
- await new Promise(resolve => {
101
- const timer = setTimeout(resolve, timeoutMs);
102
- this._wake = () => {
103
- clearTimeout(timer);
104
- resolve();
105
- };
106
- });
107
- this._wake = null;
61
+ write;
62
+ beginResendMs;
63
+ chunkTimeoutMs;
64
+ chunkResends;
65
+ loadTimeoutMs;
66
+ _replies;
67
+ _wake;
68
+ /**
69
+ * @param options.write Writes a frame to the device.
70
+ */
71
+ constructor({ write, beginResendMs = BEGIN_RESEND_MS, chunkTimeoutMs = CHUNK_TIMEOUT_MS, chunkResends = CHUNK_RESENDS, loadTimeoutMs = LOAD_TIMEOUT_MS, }) {
72
+ this.write = write;
73
+ this.beginResendMs = beginResendMs;
74
+ this.chunkTimeoutMs = chunkTimeoutMs;
75
+ this.chunkResends = chunkResends;
76
+ this.loadTimeoutMs = loadTimeoutMs;
77
+ this._replies = [];
78
+ this._wake = null;
108
79
  }
109
- return this._replies.shift() ?? null;
110
- }
111
-
112
- /** Starts the package on the device. Returns its chunk size, or the outcome when it never got that far. */
113
- async _begin(packageData, timeoutMs) {
114
- const deadline = Date.now() + timeoutMs;
115
- const frame = beginFrame(packageData.length);
116
- while (Date.now() < deadline) {
117
- await this.write(frame);
118
- const waitUntil = Math.min(Date.now() + this.beginResendMs, deadline);
119
- for (;;) {
120
- const reply = await this._nextReply(waitUntil - Date.now());
121
- if (!reply || reply.kind === 'dropped') break; // send it again
122
- if (reply.kind === 'ready') return {chunkBytes: reply.value};
123
- if (reply.kind === 'rejected') return {outcome: 'rejected'};
124
- }
80
+ /** Takes a line from the device. Returns true when it is part of the transfer and not worth showing. */
81
+ onLine(line) {
82
+ const reply = parseReply(line);
83
+ if (!reply)
84
+ return false;
85
+ this._replies.push(reply);
86
+ if (this._wake)
87
+ this._wake();
88
+ return reply.kind === 'ready' || reply.kind === 'got';
125
89
  }
126
- return {outcome: 'timeout'};
127
- }
128
-
129
- /**
130
- * Sends one package and waits for the device to load it.
131
- *
132
- * @param {Buffer} packageData
133
- * @param {object} [options]
134
- * @param {number} [options.beginTimeoutMs] How long a device may take to answer at all.
135
- * @returns {Promise<'ok'|'rejected'|'dropped'|'timeout'>}
136
- */
137
- async send(packageData, {beginTimeoutMs = BEGIN_TIMEOUT_MS} = {}) {
138
- this._replies = [];
139
- const begun = await this._begin(packageData, beginTimeoutMs);
140
- if (begun.outcome) return begun.outcome;
141
- const {chunkBytes} = begun;
142
-
143
- let offset = 0;
144
- let resends = 0;
145
- while (offset < packageData.length) {
146
- await this.write(chunkFrame(packageData, offset, chunkBytes));
147
- const reply = await this._awaitChunkReply();
148
- if (reply === 'ok' || reply === 'rejected') return reply;
149
- if (reply === null || reply === 'dropped') {
150
- if (++resends > this.chunkResends) return reply ?? 'timeout';
151
- continue;
152
- }
153
- // Where the device says it has got to, even if that is behind: a repeated begin starts it over.
154
- if (reply > offset) resends = 0;
155
- offset = reply;
90
+ /** The next reply, or null after @p timeoutMs. */
91
+ async _nextReply(timeoutMs) {
92
+ if (!this._replies.length) {
93
+ await new Promise(resolve => {
94
+ const timer = setTimeout(resolve, timeoutMs);
95
+ this._wake = () => {
96
+ clearTimeout(timer);
97
+ resolve();
98
+ };
99
+ });
100
+ this._wake = null;
101
+ }
102
+ return this._replies.shift() ?? null;
156
103
  }
157
-
158
- for (;;) {
159
- const reply = await this._nextReply(this.loadTimeoutMs);
160
- if (!reply) return 'timeout';
161
- if (reply.kind === 'ok' || reply.kind === 'rejected') return reply.kind;
104
+ /** Starts the package on the device. Returns its chunk size, or the outcome when it never got that far. */
105
+ async _begin(packageData, timeoutMs) {
106
+ const deadline = Date.now() + timeoutMs;
107
+ const frame = beginFrame(packageData.length);
108
+ while (Date.now() < deadline) {
109
+ await this.write(frame);
110
+ const waitUntil = Math.min(Date.now() + this.beginResendMs, deadline);
111
+ for (;;) {
112
+ const reply = await this._nextReply(waitUntil - Date.now());
113
+ if (!reply || reply.kind === 'dropped')
114
+ break; // send it again
115
+ if (reply.kind === 'ready')
116
+ return { chunkBytes: reply.value };
117
+ if (reply.kind === 'rejected')
118
+ return { outcome: 'rejected' };
119
+ }
120
+ }
121
+ return { outcome: 'timeout' };
162
122
  }
163
- }
164
-
165
- /** What the device said about a chunk: its offset, 'ok', 'rejected', 'dropped', or null for nothing. */
166
- async _awaitChunkReply() {
167
- const waitUntil = Date.now() + this.chunkTimeoutMs;
168
- for (;;) {
169
- const reply = await this._nextReply(waitUntil - Date.now());
170
- if (!reply) return null;
171
- if (reply.kind === 'got') return reply.value;
172
- if (reply.kind !== 'ready') return reply.kind;
123
+ /**
124
+ * Sends one package and waits for the device to load it.
125
+ *
126
+ * @param options.beginTimeoutMs How long a device may take to answer at all.
127
+ */
128
+ async send(packageData, { beginTimeoutMs = BEGIN_TIMEOUT_MS } = {}) {
129
+ this._replies = [];
130
+ const begun = await this._begin(packageData, beginTimeoutMs);
131
+ if ('outcome' in begun)
132
+ return begun.outcome;
133
+ const { chunkBytes } = begun;
134
+ let offset = 0;
135
+ let resends = 0;
136
+ while (offset < packageData.length) {
137
+ await this.write(chunkFrame(packageData, offset, chunkBytes));
138
+ const reply = await this._awaitChunkReply();
139
+ if (reply === 'ok' || reply === 'rejected')
140
+ return reply;
141
+ if (reply === null || reply === 'dropped') {
142
+ if (++resends > this.chunkResends)
143
+ return reply ?? 'timeout';
144
+ continue;
145
+ }
146
+ // Where the device says it has got to, even if that is behind: a repeated begin starts it over.
147
+ if (reply > offset)
148
+ resends = 0;
149
+ offset = reply;
150
+ }
151
+ for (;;) {
152
+ const reply = await this._nextReply(this.loadTimeoutMs);
153
+ if (!reply)
154
+ return 'timeout';
155
+ if (reply.kind === 'ok' || reply.kind === 'rejected')
156
+ return reply.kind;
157
+ }
158
+ }
159
+ /** What the device said about a chunk: its offset, 'ok', 'rejected', 'dropped', or null for nothing. */
160
+ async _awaitChunkReply() {
161
+ const waitUntil = Date.now() + this.chunkTimeoutMs;
162
+ for (;;) {
163
+ const reply = await this._nextReply(waitUntil - Date.now());
164
+ if (!reply)
165
+ return null;
166
+ if (reply.kind === 'got')
167
+ return reply.value;
168
+ if (reply.kind !== 'ready')
169
+ return reply.kind;
170
+ }
173
171
  }
174
- }
175
172
  }
@@ -13,7 +13,6 @@
13
13
  * See the License for the specific language governing permissions and
14
14
  * limitations under the License.
15
15
  */
16
-
17
16
  // ERHR — the embedded-react hot-reload transport frame.
18
17
  //
19
18
  // One self-describing frame that carries an .erpkg (ERCF container) over a byte stream — USB-CDC, a
@@ -35,14 +34,11 @@
35
34
  // payload bytes[payload_len] — the .erpkg (ERCF container)
36
35
  //
37
36
  // The mirror of this lives in the firmware parser (runtime/er_hotreload.c); the two MUST stay
38
- // byte-compatible. crc32 is shared with emit-container.mjs so all three CRCs are the one algorithm.
39
-
40
- import {crc32} from '../assets/emit-container.mjs';
41
-
37
+ // byte-compatible. crc32 is shared with emit-container.mts so all three CRCs are the one algorithm.
38
+ import { crc32 } from '../assets/emit-container.mjs';
42
39
  export const ERHR_MAGIC = 'ERHR';
43
40
  export const ERHR_PROTO_VERSION = 1;
44
41
  export const ERHR_HEADER_SIZE = 16;
45
-
46
42
  const MAGIC_BYTES = 4;
47
43
  const VERSION_OFFSET = 4;
48
44
  const TYPE_OFFSET = 5;
@@ -50,34 +46,30 @@ const FLAGS_OFFSET = 6;
50
46
  const PAYLOAD_LENGTH_OFFSET = 8;
51
47
  const PAYLOAD_CRC_OFFSET = 12;
52
48
  const DEFAULT_MAX_PAYLOAD_BYTES = 32 * 1024 * 1024;
53
-
54
49
  /** Frame message types (room to grow: ping/ack/reset later without a version bump). */
55
50
  export const MSG_LOAD_CONTAINER = 1;
56
- export const MSG_PACKAGE_BEGIN = 2; // Flow B: see package-transfer.mjs
51
+ export const MSG_PACKAGE_BEGIN = 2; // Flow B: see package-transfer.mts
57
52
  export const MSG_PACKAGE_CHUNK = 3;
58
-
59
53
  /**
60
54
  * Encodes an .erpkg into an ERHR transport frame ready to write to the device's byte stream.
61
55
  *
62
- * @param {Buffer|Uint8Array} erpkg The ERCF container bytes (from emitContainer).
63
- * @param {object} [opts]
64
- * @param {number} [opts.type] Message type (default MSG_LOAD_CONTAINER).
65
- * @returns {Buffer} The framed bytes (16-byte header + payload).
56
+ * @param erpkg The ERCF container bytes (from emitContainer).
57
+ * @param options.type Message type (default MSG_LOAD_CONTAINER).
58
+ * @returns The framed bytes (16-byte header + payload).
66
59
  */
67
- export function encodeFrame(erpkg, {type = MSG_LOAD_CONTAINER} = {}) {
68
- if (!erpkg || !erpkg.length)
69
- throw new Error('encodeFrame: payload (.erpkg) is required');
70
- const payload = Buffer.from(erpkg);
71
- const header = Buffer.alloc(ERHR_HEADER_SIZE);
72
- header.write(ERHR_MAGIC, 0, 'ascii');
73
- header.writeUInt8(ERHR_PROTO_VERSION, VERSION_OFFSET);
74
- header.writeUInt8(type & 0xff, TYPE_OFFSET);
75
- header.writeUInt16LE(0, FLAGS_OFFSET); // reserved
76
- header.writeUInt32LE(payload.length >>> 0, PAYLOAD_LENGTH_OFFSET);
77
- header.writeUInt32LE(crc32(payload), PAYLOAD_CRC_OFFSET);
78
- return Buffer.concat([header, payload]);
60
+ export function encodeFrame(erpkg, { type = MSG_LOAD_CONTAINER } = {}) {
61
+ if (!erpkg || !erpkg.length)
62
+ throw new Error('encodeFrame: payload (.erpkg) is required');
63
+ const payload = Buffer.from(erpkg);
64
+ const header = Buffer.alloc(ERHR_HEADER_SIZE);
65
+ header.write(ERHR_MAGIC, 0, 'ascii');
66
+ header.writeUInt8(ERHR_PROTO_VERSION, VERSION_OFFSET);
67
+ header.writeUInt8(type & 0xff, TYPE_OFFSET);
68
+ header.writeUInt16LE(0, FLAGS_OFFSET); // reserved
69
+ header.writeUInt32LE(payload.length >>> 0, PAYLOAD_LENGTH_OFFSET);
70
+ header.writeUInt32LE(crc32(payload), PAYLOAD_CRC_OFFSET);
71
+ return Buffer.concat([header, payload]);
79
72
  }
80
-
81
73
  /**
82
74
  * A streaming decoder mirroring the firmware parser: feed it arbitrary chunks of a byte stream and it
83
75
  * scans for the ERHR magic, parses the header, collects the payload, and verifies the CRC. Used by the
@@ -86,100 +78,108 @@ export function encodeFrame(erpkg, {type = MSG_LOAD_CONTAINER} = {}) {
86
78
  * Emits via the callbacks passed to the constructor; tolerant of leading/interleaved non-frame bytes.
87
79
  */
88
80
  export class FrameDecoder {
89
- /**
90
- * @param {object} handlers
91
- * @param {(payload: Buffer, meta: {type: number}) => void} [handlers.onFrame] A complete, CRC-valid frame.
92
- * @param {(reason: string) => void} [handlers.onError] A framed payload failed validation.
93
- */
94
- constructor({onFrame, onError, maxPayload = DEFAULT_MAX_PAYLOAD_BYTES} = {}) {
95
- this.onFrame = onFrame || (() => {});
96
- this.onError = onError || (() => {});
97
- this.maxPayload = maxPayload; // guard against a coincidental "ERHR" in noise claiming a huge length
98
- this._reset();
99
- }
100
-
101
- _reset() {
102
- this._state = 'scan'; // scan magic → header → payload
103
- this._window = Buffer.alloc(MAGIC_BYTES); // rolling 4-byte window for magic resync
104
- this._windowLength = 0;
105
- this._header = Buffer.alloc(ERHR_HEADER_SIZE);
106
- this._headerReceived = MAGIC_BYTES; // magic already in _header once matched
107
- this._payloadLength = 0;
108
- this._payloadCrc = 0;
109
- this._type = 0;
110
- this._payload = null;
111
- this._payloadReceived = 0;
112
- }
113
-
114
- /** Feed a chunk of received bytes. May complete zero, one, or several frames. */
115
- push(chunk) {
116
- const data = Buffer.from(chunk);
117
- for (let index = 0; index < data.length; index++) this._byte(data[index]);
118
- }
119
-
120
- _byte(byte) {
121
- if (this._state === 'scan') {
122
- // Slide the byte into a 4-byte window; a full match transitions to header collection. This
123
- // naturally handles partial matches and overlaps without backtracking.
124
- if (this._windowLength < MAGIC_BYTES) {
125
- this._window[this._windowLength++] = byte;
126
- } else {
127
- this._window.copyWithin(0, 1);
128
- this._window[MAGIC_BYTES - 1] = byte;
129
- }
130
- if (
131
- this._windowLength === MAGIC_BYTES &&
132
- this._window.toString('ascii') === ERHR_MAGIC
133
- ) {
134
- this._window.copy(this._header, 0, 0, MAGIC_BYTES);
135
- this._headerReceived = MAGIC_BYTES;
81
+ onFrame;
82
+ onError;
83
+ maxPayload;
84
+ _state = 'scan';
85
+ _window = Buffer.alloc(MAGIC_BYTES);
86
+ _windowLength = 0;
87
+ _header = Buffer.alloc(ERHR_HEADER_SIZE);
88
+ _headerReceived = MAGIC_BYTES;
89
+ _payloadLength = 0;
90
+ _payloadCrc = 0;
91
+ _type = 0;
92
+ _payload = null;
93
+ _payloadReceived = 0;
94
+ /**
95
+ * @param handlers.onFrame A complete, CRC-valid frame.
96
+ * @param handlers.onError A framed payload failed validation.
97
+ */
98
+ constructor({ onFrame, onError, maxPayload = DEFAULT_MAX_PAYLOAD_BYTES, } = {}) {
99
+ this.onFrame = onFrame || (() => { });
100
+ this.onError = onError || (() => { });
101
+ this.maxPayload = maxPayload; // guard against a coincidental "ERHR" in noise claiming a huge length
102
+ this._reset();
103
+ }
104
+ _reset() {
105
+ this._state = 'scan'; // scan magic → header → payload
106
+ this._window = Buffer.alloc(MAGIC_BYTES); // rolling 4-byte window for magic resync
136
107
  this._windowLength = 0;
137
- this._state = 'header';
138
- }
139
- return;
108
+ this._header = Buffer.alloc(ERHR_HEADER_SIZE);
109
+ this._headerReceived = MAGIC_BYTES; // magic already in _header once matched
110
+ this._payloadLength = 0;
111
+ this._payloadCrc = 0;
112
+ this._type = 0;
113
+ this._payload = null;
114
+ this._payloadReceived = 0;
140
115
  }
141
- if (this._state === 'header') {
142
- this._header[this._headerReceived++] = byte;
143
- if (this._headerReceived < ERHR_HEADER_SIZE) return;
144
- const version = this._header.readUInt8(VERSION_OFFSET);
145
- this._type = this._header.readUInt8(TYPE_OFFSET);
146
- this._payloadLength = this._header.readUInt32LE(PAYLOAD_LENGTH_OFFSET);
147
- this._payloadCrc = this._header.readUInt32LE(PAYLOAD_CRC_OFFSET);
148
- if (version !== ERHR_PROTO_VERSION) {
149
- this.onError(`unsupported protocol version ${version}`);
150
- this._reset();
151
- return;
152
- }
153
- if (this._payloadLength === 0) {
154
- this.onError('empty payload');
155
- this._reset();
156
- return;
157
- }
158
- if (this._payloadLength > this.maxPayload) {
159
- // Almost certainly a false magic in noise — drop it and keep scanning, don't allocate.
160
- this.onError(`payload too large (${this._payloadLength} bytes)`);
161
- this._reset();
162
- return;
163
- }
164
- this._payload = Buffer.alloc(this._payloadLength);
165
- this._payloadReceived = 0;
166
- this._state = 'payload';
167
- return;
116
+ /** Feed a chunk of received bytes. May complete zero, one, or several frames. */
117
+ push(chunk) {
118
+ const data = Buffer.from(chunk);
119
+ for (let index = 0; index < data.length; index++)
120
+ this._byte(data[index]);
168
121
  }
169
- // payload
170
- this._payload[this._payloadReceived++] = byte;
171
- if (this._payloadReceived < this._payloadLength) return;
172
- const actualCrc = crc32(this._payload);
173
- if (actualCrc !== this._payloadCrc) {
174
- this.onError(
175
- `payload CRC mismatch (got ${actualCrc.toString(16)}, want ${this._payloadCrc.toString(16)})`,
176
- );
177
- this._reset();
178
- return;
122
+ _byte(byte) {
123
+ if (this._state === 'scan') {
124
+ // Slide the byte into a 4-byte window; a full match transitions to header collection. This
125
+ // naturally handles partial matches and overlaps without backtracking.
126
+ if (this._windowLength < MAGIC_BYTES) {
127
+ this._window[this._windowLength++] = byte;
128
+ }
129
+ else {
130
+ this._window.copyWithin(0, 1);
131
+ this._window[MAGIC_BYTES - 1] = byte;
132
+ }
133
+ if (this._windowLength === MAGIC_BYTES &&
134
+ this._window.toString('ascii') === ERHR_MAGIC) {
135
+ this._window.copy(this._header, 0, 0, MAGIC_BYTES);
136
+ this._headerReceived = MAGIC_BYTES;
137
+ this._windowLength = 0;
138
+ this._state = 'header';
139
+ }
140
+ return;
141
+ }
142
+ if (this._state === 'header') {
143
+ this._header[this._headerReceived++] = byte;
144
+ if (this._headerReceived < ERHR_HEADER_SIZE)
145
+ return;
146
+ const version = this._header.readUInt8(VERSION_OFFSET);
147
+ this._type = this._header.readUInt8(TYPE_OFFSET);
148
+ this._payloadLength = this._header.readUInt32LE(PAYLOAD_LENGTH_OFFSET);
149
+ this._payloadCrc = this._header.readUInt32LE(PAYLOAD_CRC_OFFSET);
150
+ if (version !== ERHR_PROTO_VERSION) {
151
+ this.onError(`unsupported protocol version ${version}`);
152
+ this._reset();
153
+ return;
154
+ }
155
+ if (this._payloadLength === 0) {
156
+ this.onError('empty payload');
157
+ this._reset();
158
+ return;
159
+ }
160
+ if (this._payloadLength > this.maxPayload) {
161
+ // Almost certainly a false magic in noise — drop it and keep scanning, don't allocate.
162
+ this.onError(`payload too large (${this._payloadLength} bytes)`);
163
+ this._reset();
164
+ return;
165
+ }
166
+ this._payload = Buffer.alloc(this._payloadLength);
167
+ this._payloadReceived = 0;
168
+ this._state = 'payload';
169
+ return;
170
+ }
171
+ const payload = this._payload;
172
+ payload[this._payloadReceived++] = byte;
173
+ if (this._payloadReceived < this._payloadLength)
174
+ return;
175
+ const actualCrc = crc32(payload);
176
+ if (actualCrc !== this._payloadCrc) {
177
+ this.onError(`payload CRC mismatch (got ${actualCrc.toString(16)}, want ${this._payloadCrc.toString(16)})`);
178
+ this._reset();
179
+ return;
180
+ }
181
+ const type = this._type;
182
+ this._reset();
183
+ this.onFrame(payload, { type });
179
184
  }
180
- const payload = this._payload;
181
- const type = this._type;
182
- this._reset();
183
- this.onFrame(payload, {type});
184
- }
185
185
  }