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,199 +13,172 @@
13
13
  * See the License for the specific language governing permissions and
14
14
  * limitations under the License.
15
15
  */
16
-
17
- // uploader — writes ERHR-framed .erpkg containers to a device over a serial/USB port, and surfaces the
18
- // device's log output coming back the other way (CDC is full-duplex, so one port carries both).
19
- //
20
- // `serialport` is an optional, lazily-loaded dependency: it has a native binding, so we don't force it
21
- // on everyone who just wants the simulator or the AOT path. The first time you upload to a device, the
22
- // CLI asks you to `npm i serialport` if it isn't present.
23
-
24
- import {encodeFrame} from './protocol.mjs';
25
-
16
+ import { encodeFrame } from './protocol.mjs';
26
17
  const DEFAULT_BAUD = 460800;
27
18
  const PACED_CHUNK_BYTES = 16 * 1024;
28
-
29
19
  /** Loads the `serialport` package, with a friendly message if it isn't installed. */
30
20
  async function loadSerialPort() {
31
- try {
32
- return await import('serialport');
33
- } catch {
34
- throw new Error(
35
- "on-device upload needs the 'serialport' package.\n" +
36
- ' Install it in your project: npm i serialport\n' +
37
- ' (it has a native binding, so embedded-react keeps it optional.)',
38
- );
39
- }
21
+ try {
22
+ return await import('serialport');
23
+ }
24
+ catch {
25
+ throw new Error("on-device upload needs the 'serialport' package.\n" +
26
+ ' Install it in your project: npm i serialport\n' +
27
+ ' (it has a native binding, so embedded-react keeps it optional.)');
28
+ }
40
29
  }
41
-
42
30
  /**
43
31
  * Opens a serial port and streams hot-reload uploads to it.
44
32
  *
45
- * @param {object} options
46
- * @param {string} options.device Port path (e.g. /dev/tty.usbmodem1234 or COM5).
47
- * @param {number} [options.baud] Baud rate. Ignored by true USB-CDC links, required by UART bridges.
48
- * @param {(line: string) => void} [options.onLog] Called with each line the device prints back.
33
+ * @param options.device Port path (e.g. /dev/tty.usbmodem1234 or COM5).
34
+ * @param options.baud Baud rate. Ignored by true USB-CDC links, required by UART bridges.
35
+ * @param options.onLog Called with each line the device prints back.
49
36
  */
50
37
  export class SerialUploader {
51
- constructor({device, baud = DEFAULT_BAUD, onLog, paced = true} = {}) {
52
- if (!device) throw new Error('SerialUploader: device path is required');
53
- this.device = device;
54
- this.baud = baud;
55
- this.onLog = onLog || (() => {});
56
- // paced=true (default): stream the frame in chunks, draining each, so the write is metered to roughly
57
- // the device's drain rate. Over USB this keeps the host from flooding the RX buffer while the running
58
- // app competes for the port; on a raw UART bridge (no flow control) it keeps the host under the line
59
- // rate so bytes aren't dropped. paced=false: stream the whole frame in one write, relying on the
60
- // link's own back-pressure — slightly less setup, but can stall mid-transfer when the device is busy.
61
- this.paced = paced;
62
- this._port = null;
63
- this._pendingLine = '';
64
- }
65
-
66
- /** Opens the port. Resolves once it is ready to accept writes. */
67
- async open() {
68
- const {SerialPort} = await loadSerialPort();
69
- await new Promise((resolve, reject) => {
70
- this._port = new SerialPort(
71
- {path: this.device, baudRate: this.baud},
72
- error => (error ? reject(error) : resolve()),
73
- );
74
- });
75
- // Surface device logs line-by-line (the data arriving between/around our uploads).
76
- this._port.on('data', chunk => this._onData(chunk));
77
- this._port.on('error', error =>
78
- this.onLog(`[serial error] ${error.message}`),
79
- );
80
- }
81
-
82
- _onData(chunk) {
83
- this._pendingLine += chunk.toString('utf8');
84
- let newline;
85
- while ((newline = this._pendingLine.indexOf('\n')) >= 0) {
86
- const line = this._pendingLine.slice(0, newline).replace(/\r$/, '');
87
- this._pendingLine = this._pendingLine.slice(newline + 1);
88
- if (line.length) this.onLog(line);
89
- }
90
- }
91
-
92
- _write(data) {
93
- return new Promise((resolve, reject) =>
94
- this._port.write(data, error => (error ? reject(error) : resolve())),
95
- );
96
- }
97
-
98
- _drain() {
99
- return new Promise((resolve, reject) =>
100
- this._port.drain(error => (error ? reject(error) : resolve())),
101
- );
102
- }
103
-
104
- /**
105
- * Frames an .erpkg and writes it to the device.
106
- *
107
- * Paced path (paced=true, the default): stream the frame in chunks, draining each, so the write is
108
- * metered to roughly the device's drain rate — over USB that keeps the host from flooding the RX buffer
109
- * while the running app competes for the port, and on a raw UART bridge (no flow control) it keeps the
110
- * host under the line rate so bytes aren't dropped.
111
- *
112
- * Fast path (paced=false): stream the whole frame in one write, relying on the link's own back-pressure.
113
- *
114
- * @param {Buffer|Uint8Array} erpkg Container bytes (from packAppContainer).
115
- * @returns {Promise<number>} The number of framed bytes written.
116
- */
117
- async send(erpkg) {
118
- if (!this._port) throw new Error('SerialUploader: call open() first');
119
- const frame = encodeFrame(erpkg);
120
-
121
- if (!this.paced) {
122
- await this._write(frame); // rely on the link's back-pressure (USB NAK) to throttle us
123
- await this._drain();
124
- return frame.length;
125
- }
126
-
127
- for (let offset = 0; offset < frame.length; offset += PACED_CHUNK_BYTES) {
128
- await this._write(frame.subarray(offset, offset + PACED_CHUNK_BYTES));
129
- await this._drain(); // meter to ~the device's drain rate so its RX buffer isn't overrun
130
- }
131
- return frame.length;
132
- }
133
-
134
- /** Writes a frame that is already encoded, for a transfer that waits for a reply to each. */
135
- async writeFrame(frame) {
136
- if (!this._port) throw new Error('SerialUploader: call open() first');
137
- await this._write(frame);
138
- await this._drain();
139
- }
140
-
141
- /** Closes the port. */
142
- async close() {
143
- if (!this._port) return;
144
- await new Promise(resolve => this._port.close(() => resolve()));
145
- this._port = null;
146
- }
38
+ device;
39
+ baud;
40
+ onLog;
41
+ paced;
42
+ _port;
43
+ _pendingLine;
44
+ constructor({ device, baud = DEFAULT_BAUD, onLog, paced = true, } = {}) {
45
+ if (!device)
46
+ throw new Error('SerialUploader: device path is required');
47
+ this.device = device;
48
+ this.baud = baud;
49
+ this.onLog = onLog || (() => { });
50
+ // paced=true (default): stream the frame in chunks, draining each, so the write is metered to roughly
51
+ // the device's drain rate. Over USB this keeps the host from flooding the RX buffer while the running
52
+ // app competes for the port; on a raw UART bridge (no flow control) it keeps the host under the line
53
+ // rate so bytes aren't dropped. paced=false: stream the whole frame in one write, relying on the
54
+ // link's own back-pressure — slightly less setup, but can stall mid-transfer when the device is busy.
55
+ this.paced = paced;
56
+ this._port = null;
57
+ this._pendingLine = '';
58
+ }
59
+ /** Opens the port. Resolves once it is ready to accept writes. */
60
+ async open() {
61
+ const { SerialPort } = await loadSerialPort();
62
+ await new Promise((resolve, reject) => {
63
+ this._port = new SerialPort({ path: this.device, baudRate: this.baud }, error => (error ? reject(error) : resolve()));
64
+ });
65
+ const port = this._port;
66
+ // Surface device logs line-by-line (the data arriving between/around our uploads).
67
+ port.on('data', (chunk) => this._onData(chunk));
68
+ port.on('error', (error) => this.onLog(`[serial error] ${error.message}`));
69
+ }
70
+ _onData(chunk) {
71
+ this._pendingLine += chunk.toString('utf8');
72
+ let newline;
73
+ while ((newline = this._pendingLine.indexOf('\n')) >= 0) {
74
+ const line = this._pendingLine.slice(0, newline).replace(/\r$/, '');
75
+ this._pendingLine = this._pendingLine.slice(newline + 1);
76
+ if (line.length)
77
+ this.onLog(line);
78
+ }
79
+ }
80
+ _write(data) {
81
+ return new Promise((resolve, reject) => this._port.write(data, error => (error ? reject(error) : resolve())));
82
+ }
83
+ _drain() {
84
+ return new Promise((resolve, reject) => this._port.drain(error => (error ? reject(error) : resolve())));
85
+ }
86
+ /**
87
+ * Frames an .erpkg and writes it to the device.
88
+ *
89
+ * Paced path (paced=true, the default): stream the frame in chunks, draining each, so the write is
90
+ * metered to roughly the device's drain rate — over USB that keeps the host from flooding the RX buffer
91
+ * while the running app competes for the port, and on a raw UART bridge (no flow control) it keeps the
92
+ * host under the line rate so bytes aren't dropped.
93
+ *
94
+ * Fast path (paced=false): stream the whole frame in one write, relying on the link's own back-pressure.
95
+ *
96
+ * @param erpkg Container bytes (from packAppContainer).
97
+ * @returns The number of framed bytes written.
98
+ */
99
+ async send(erpkg) {
100
+ if (!this._port)
101
+ throw new Error('SerialUploader: call open() first');
102
+ const frame = encodeFrame(erpkg);
103
+ if (!this.paced) {
104
+ await this._write(frame); // rely on the link's back-pressure (USB NAK) to throttle us
105
+ await this._drain();
106
+ return frame.length;
107
+ }
108
+ for (let offset = 0; offset < frame.length; offset += PACED_CHUNK_BYTES) {
109
+ await this._write(frame.subarray(offset, offset + PACED_CHUNK_BYTES));
110
+ await this._drain(); // meter to ~the device's drain rate so its RX buffer isn't overrun
111
+ }
112
+ return frame.length;
113
+ }
114
+ /** Writes a frame that is already encoded, for a transfer that waits for a reply to each. */
115
+ async writeFrame(frame) {
116
+ if (!this._port)
117
+ throw new Error('SerialUploader: call open() first');
118
+ await this._write(frame);
119
+ await this._drain();
120
+ }
121
+ /** Closes the port. */
122
+ async close() {
123
+ const port = this._port;
124
+ if (!port)
125
+ return;
126
+ await new Promise(resolve => port.close(() => resolve()));
127
+ this._port = null;
128
+ }
147
129
  }
148
-
149
130
  /**
150
131
  * Lists serial ports, best-effort, to help the user pick a --device. Returns [] if serialport is absent.
151
- *
152
- * @returns {Promise<Array<{path: string, manufacturer?: string}>>}
153
132
  */
154
133
  export async function listSerialPorts() {
155
- try {
156
- const {SerialPort} = await loadSerialPort();
157
- return await SerialPort.list();
158
- } catch {
159
- return [];
160
- }
134
+ try {
135
+ const { SerialPort } = await loadSerialPort();
136
+ return await SerialPort.list();
137
+ }
138
+ catch {
139
+ return [];
140
+ }
161
141
  }
162
-
163
142
  // The ESP32-S3/C3 built-in USB-Serial-JTAG enumerates with this fixed USB VID:PID, baked into the chip's
164
143
  // ROM independently of the board vendor — so it's a stable signal for auto-detecting the hot-reload port.
165
144
  // (The CH34x/CP210x/FTDI UART bridge used for *flashing* has a different id, e.g. 1a86:xxxx for WCH.)
166
145
  export const ESP_USB_JTAG_VID = '303a';
167
146
  export const ESP_USB_JTAG_PID = '1001';
168
-
169
- const hex = value => (value == null ? '' : String(value).toLowerCase());
170
-
147
+ const hex = (value) => value == null ? '' : String(value).toLowerCase();
171
148
  /** True if a `SerialPort.list()` entry is an ESP32-S3/C3 native USB-Serial-JTAG port. */
172
149
  export function isEspJtagPort(port) {
173
- return (
174
- hex(port?.vendorId) === ESP_USB_JTAG_VID &&
175
- hex(port?.productId) === ESP_USB_JTAG_PID
176
- );
150
+ return (hex(port?.vendorId) === ESP_USB_JTAG_VID &&
151
+ hex(port?.productId) === ESP_USB_JTAG_PID);
177
152
  }
178
-
179
153
  /**
180
154
  * On macOS a USB serial device appears as both `/dev/tty.*` (dial-in, blocks until carrier-detect) and
181
155
  * `/dev/cu.*` (call-out, the one to use for an outgoing link). `SerialPort.list()` reports the tty.* side;
182
156
  * map it to cu.* on darwin so an auto-detected port opens without hanging. No-op elsewhere.
183
157
  */
184
158
  export function preferCalloutPath(path) {
185
- if (process.platform === 'darwin' && path && path.startsWith('/dev/tty.')) {
186
- return `/dev/cu.${path.slice('/dev/tty.'.length)}`;
187
- }
188
- return path;
159
+ if (process.platform === 'darwin' && path && path.startsWith('/dev/tty.')) {
160
+ return `/dev/cu.${path.slice('/dev/tty.'.length)}`;
161
+ }
162
+ return path;
189
163
  }
190
-
191
164
  /**
192
165
  * Enumerate serial ports and pick out the ESP32 USB-Serial-JTAG candidates for auto-detecting `--device`.
193
166
  * Distinguishes "serialport not installed" from "installed but nothing matched" so the CLI can advise.
194
- *
195
- * @returns {Promise<{matches: object[], all: object[], serialportMissing: boolean}>}
196
167
  */
197
168
  export async function detectDevicePorts() {
198
- let SerialPort;
199
- try {
200
- ({SerialPort} = await import('serialport'));
201
- } catch {
202
- return {matches: [], all: [], serialportMissing: true};
203
- }
204
- let all = [];
205
- try {
206
- all = await SerialPort.list();
207
- } catch {
208
- all = [];
209
- }
210
- return {matches: all.filter(isEspJtagPort), all, serialportMissing: false};
169
+ let SerialPortClass;
170
+ try {
171
+ ({ SerialPort: SerialPortClass } = await import('serialport'));
172
+ }
173
+ catch {
174
+ return { matches: [], all: [], serialportMissing: true };
175
+ }
176
+ let all = [];
177
+ try {
178
+ all = await SerialPortClass.list();
179
+ }
180
+ catch {
181
+ all = [];
182
+ }
183
+ return { matches: all.filter(isEspJtagPort), all, serialportMissing: false };
211
184
  }
@@ -13,91 +13,82 @@
13
13
  * See the License for the specific language governing permissions and
14
14
  * limitations under the License.
15
15
  */
16
-
17
16
  // watchTree — recursively watch a directory across platforms.
18
17
  //
19
18
  // fs.watch's `{recursive: true}` is only supported on macOS, Windows, and Node >=20 on Linux; on older
20
19
  // Linux/Node it throws. A naive fallback that watches just the root misses edits under src/** — which makes
21
20
  // the dev loop look broken. So where native recursive watching isn't available we fall back to a
22
21
  // per-directory watcher that also picks up directories created after startup.
23
-
24
- import {watch, readdirSync, statSync} from 'node:fs';
25
- import {join} from 'node:path';
26
-
22
+ import { watch, readdirSync, statSync } from 'node:fs';
23
+ import { join } from 'node:path';
27
24
  // Directories never worth watching (build output, deps, VCS/tool caches). Skipping them keeps the watcher
28
25
  // count low on the per-directory fallback and avoids rebuild storms from generated files.
29
- const IGNORED_DIRECTORY =
30
- /^(node_modules|dist|build|out|coverage|\.git|\.hg|\.svn|\.next|\.cache)$/;
31
-
26
+ const IGNORED_DIRECTORY = /^(node_modules|dist|build|out|coverage|\.git|\.hg|\.svn|\.next|\.cache)$/;
32
27
  /**
33
28
  * Recursively watch `root`, calling `onEvent(eventType, filename)` on any change beneath it. Uses the
34
29
  * native recursive watcher where the platform supports it, else a per-directory fallback.
35
- *
36
- * @param {string} root
37
- * @param {(eventType: string, filename: string|null) => void} onEvent
38
- * @returns {{close: () => void}}
39
30
  */
40
31
  export function watchTree(root, onEvent) {
41
- try {
42
- const watcher = watch(root, {recursive: true}, onEvent);
43
- return {close: () => watcher.close()};
44
- } catch {
45
- // Native recursive watching unavailable (older Linux/Node, or an unsupported FS) — use the fallback.
46
- return watchTreePolyfill(root, onEvent);
47
- }
32
+ try {
33
+ const watcher = watch(root, { recursive: true }, onEvent);
34
+ return { close: () => watcher.close() };
35
+ }
36
+ catch {
37
+ // Native recursive watching unavailable (older Linux/Node, or an unsupported FS) — use the fallback.
38
+ return watchTreePolyfill(root, onEvent);
39
+ }
48
40
  }
49
-
50
41
  /**
51
42
  * Per-directory recursive watcher: one non-recursive `fs.watch` per directory under `root`, plus hooks for
52
43
  * directories created later. This is what makes `src/**` edits fire on platforms without native recursion.
53
44
  * Exported for direct testing (so the fallback can be exercised even where native recursion works).
54
- *
55
- * @param {string} root
56
- * @param {(eventType: string, filename: string|null) => void} onEvent
57
- * @returns {{close: () => void}}
58
45
  */
59
46
  export function watchTreePolyfill(root, onEvent) {
60
- const watchers = new Map(); // absolute directory path -> FSWatcher
61
-
62
- const watchDirectory = directory => {
63
- if (watchers.has(directory)) return;
64
- let watcher;
65
- try {
66
- watcher = watch(directory, {}, (event, name) => {
67
- onEvent(event, name);
68
- // `mkdir src/components` needs its own watcher — hook any freshly-created subdirectory.
69
- if (!name || IGNORED_DIRECTORY.test(name)) return;
70
- const child = join(directory, name);
47
+ const watchers = new Map(); // absolute directory path -> FSWatcher
48
+ const watchDirectory = (directory) => {
49
+ if (watchers.has(directory))
50
+ return;
51
+ let watcher;
71
52
  try {
72
- if (statSync(child).isDirectory()) scan(child);
73
- } catch {
74
- /* a file (not a dir), or created-then-removed — ignore */
53
+ watcher = watch(directory, {}, (event, name) => {
54
+ onEvent(event, name);
55
+ // `mkdir src/components` needs its own watcher — hook any freshly-created subdirectory.
56
+ if (!name || IGNORED_DIRECTORY.test(name))
57
+ return;
58
+ const child = join(directory, name);
59
+ try {
60
+ if (statSync(child).isDirectory())
61
+ scan(child);
62
+ }
63
+ catch {
64
+ /* a file (not a dir), or created-then-removed — ignore */
65
+ }
66
+ });
75
67
  }
76
- });
77
- } catch {
78
- return; // directory vanished between scan and watch
79
- }
80
- watchers.set(directory, watcher);
81
- };
82
-
83
- const scan = directory => {
84
- watchDirectory(directory);
85
- let entries;
86
- try {
87
- entries = readdirSync(directory, {withFileTypes: true});
88
- } catch {
89
- return;
90
- }
91
- for (const entry of entries)
92
- if (entry.isDirectory() && !IGNORED_DIRECTORY.test(entry.name))
93
- scan(join(directory, entry.name));
94
- };
95
-
96
- scan(root);
97
- return {
98
- close() {
99
- for (const watcher of watchers.values()) watcher.close();
100
- watchers.clear();
101
- },
102
- };
68
+ catch {
69
+ return; // directory vanished between scan and watch
70
+ }
71
+ watchers.set(directory, watcher);
72
+ };
73
+ const scan = (directory) => {
74
+ watchDirectory(directory);
75
+ let entries;
76
+ try {
77
+ entries = readdirSync(directory, { withFileTypes: true });
78
+ }
79
+ catch {
80
+ return;
81
+ }
82
+ for (const entry of entries)
83
+ if (entry.isDirectory() && !IGNORED_DIRECTORY.test(entry.name))
84
+ scan(join(directory, entry.name));
85
+ };
86
+ scan(root);
87
+ return {
88
+ close() {
89
+ for (const watcher of watchers.values())
90
+ watcher.close();
91
+ watchers.clear();
92
+ },
93
+ };
103
94
  }