miaoda-expo-devkit 0.1.1-dev.development-build.7 → 0.1.1-dev.development-build.8

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.
package/README.md CHANGED
@@ -181,7 +181,10 @@ Bundle,避免使用失效的增量 revision。最终编译失败会返回 `422
181
181
 
182
182
  普通恢复执行 Fast Refresh;`/_hmr/reload` 执行完整 Bundle 重载,若当前暂停则延迟到
183
183
  恢复时执行。暂停期间 iOS/Android 客户端展示全屏「应用正在更新中」遮罩,阻断用户
184
- 对旧界面的交互,恢复后自动消失(Web 端不展示)。过渡期内旧路径
184
+ 对旧界面的交互,恢复后自动消失(Web 端不展示)。开发服务器停止时已加载的 JS 继续
185
+ 运行,`/_hmr/status` 轮询连续 3 个周期失败后 iOS/Android 客户端在顶部展示非阻断的
186
+ 「已断开开发服务器」横幅,轮询恢复或 WebSocket 重连后自动消失(Web 端不展示)。
187
+ 过渡期内旧路径
185
188
  `/innerapi/v1/sourcecode/__hmr_*` 作为别名同样可用,
186
189
  供平台网关 sourcecode 透传通道不改路由接入。协议、返回值、版本要求和加载边界见
187
190
  [Metro HMR 批量编辑控制](../../docs/metro-hmr-control.md)。
@@ -871,7 +874,7 @@ DevKit 当前管理以下补丁:
871
874
 
872
875
  - `@expo/cli@55.0.16-55.0.22`(Metro HMR 批量编辑控制的服务端,含 AI 错误采集;另按 55.0.16–55.0.22 每个小版本提供独立补丁文件)
873
876
  - `expo@55.0.6`(HMR 批量编辑控制的客户端;并固定 `expo-audio@55.0.6` 和 `expo-video@55.0.5` 的 Expo 兼容版本表)
874
- - `metro-runtime@0.83.3`(HMRClient 透传 `miaoda-hmr-control` 控制消息)
877
+ - `metro-runtime@0.83.3`(HMRClient 透传 `miaoda-hmr-control` 控制消息,并在执行增量前支持异步原生能力检查)
875
878
  - `metro-file-map@0.83.3`(`miaodaFlushChanges` 文件监听栅栏,保证恢复时 watcher 已看到全部写入)
876
879
  - `react-native@0.83.2`(LogBox 错误页增强:错误标题映射与一键复制)
877
880
  - `expo-modules-core@55.0.15`(Android CMake 打包 worklets 原生库)
@@ -879,6 +882,10 @@ DevKit 当前管理以下补丁:
879
882
  - `react-native-worklets@0.7.4`(Babel 插件规范化 TypeScript 函数类型)
880
883
 
881
884
  前四个补丁共同实现 [Metro HMR 批量编辑控制](../../docs/metro-hmr-control.md),须整体安装。
885
+ 定制 Development Build 的非空增量及 HMR 发起的完整重载会先检查原生能力,兼容时自动应用;
886
+ 不兼容或未知时弹框,用户保留旧应用后可通过底部横幅重试。需要 Launcher 0.1.17 起的
887
+ 只读检查接口,缺接口时提示升级;Web/Expo Go 保持原行为。原生开发菜单直接 reload
888
+ 不属于该 HMR 门控范围,能力结果也尚未与 Metro revision 原子绑定。
882
889
 
883
890
  `react-native-css-interop@0.2.7` 的 box-shadow fallthrough 已由上游修复,新模板不再需要 DevKit patch。
884
891
  为兼容升级 DevKit 的历史模板,DevKit 会在项目实际声明或 lockfile 中包含历史版本时注册已验证的 CSS interop(`0.2.6`)、Worklets(`0.7.2`)和 Skia(`@shopify/react-native-skia@2.4.18`,支持 `SKIA_DOWNLOAD_BASE_URL` 自定义二进制下载源)patch,由 pnpm 按实际安装版本匹配;新模板不会注册未使用的旧 patch。注册 patch 不会安装额外版本。历史项目升级后应重新生成并提交 lockfile。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "miaoda-expo-devkit",
3
- "version": "0.1.1-dev.development-build.7",
3
+ "version": "0.1.1-dev.development-build.8",
4
4
  "description": "Expo 应用开发工具集:Sentry DSN 替换 stub、错误/网络捕获、Metro 符号化",
5
5
  "license": "MIT",
6
6
  "main": "./dist/index.js",
@@ -21,10 +21,22 @@ index e2b8941..355deae 100644
21
21
  "jest-expo": "~55.0.9",
22
22
  "lottie-react-native": "~7.3.4",
23
23
  diff --git a/src/async-require/hmr.ts b/src/async-require/hmr.ts
24
- index c0ea71e..9250e76 100644
24
+ index c0ea71e..98fddec 100644
25
25
  --- a/src/async-require/hmr.ts
26
26
  +++ b/src/async-require/hmr.ts
27
- @@ -17,6 +17,7 @@ import {
27
+ @@ -11,12 +11,19 @@
28
+ import MetroHMRClient from '@expo/metro/metro-runtime/modules/HMRClient';
29
+ import prettyFormat, { plugins } from 'pretty-format';
30
+
31
+ +import {
32
+ + checkMiaodaHmrCompatibility,
33
+ + isMiaodaHmrCompatibilityEnabled,
34
+ + setMiaodaHmrCompatibilityRetry,
35
+ +} from './miaodaHmrCompatibilityCheck';
36
+ +
37
+ import {
38
+ getConnectionError,
39
+ getFullBundlerUrl,
28
40
  handleCompileError,
29
41
  hideLoading,
30
42
  resetErrorOverlay,
@@ -32,7 +44,7 @@ index c0ea71e..9250e76 100644
32
44
  showLoading,
33
45
  } from './hmrUtils';
34
46
 
35
- @@ -29,6 +30,66 @@ let hmrClient: MetroHMRClient | null = null;
47
+ @@ -29,8 +36,153 @@ let hmrClient: MetroHMRClient | null = null;
36
48
  let hmrUnavailableReason: string | null = null;
37
49
  const buildErrorQueue = new Set<unknown>();
38
50
  let didConnect: boolean = false;
@@ -68,6 +80,40 @@ index c0ea71e..9250e76 100644
68
80
  +export function isMiaodaPaused(): boolean {
69
81
  + return miaodaPaused;
70
82
  +}
83
+ +
84
+ +let miaodaServerDisconnected = false;
85
+ +// 开发服务器断线状态订阅者:launch/ 里的非阻断顶部横幅据此提示用户
86
+ +// Metro 已不可达。横幅挂在 dev 模式的根组件包装里,纯 JS 实现,
87
+ +// 不阻断交互(pointerEvents: 'none'),服务恢复后自动消失。
88
+ +const miaodaServerDisconnectedListeners = new Set<(disconnected: boolean) => void>();
89
+ +
90
+ +// miaodaServerDisconnected 的唯一写入入口:值真正变化时才广播,
91
+ +// 订阅者异常不能反过来打断 HMR 控制链路。
92
+ +function setMiaodaServerDisconnected(disconnected: boolean) {
93
+ + if (miaodaServerDisconnected === disconnected) return;
94
+ + miaodaServerDisconnected = disconnected;
95
+ + for (const listener of miaodaServerDisconnectedListeners) {
96
+ + try {
97
+ + listener(disconnected);
98
+ + } catch {}
99
+ + }
100
+ +}
101
+ +
102
+ +// 订阅断线状态变化,返回取消订阅函数(供 React useEffect 使用)。
103
+ +export function subscribeMiaodaServerDisconnected(
104
+ + listener: (disconnected: boolean) => void
105
+ +): () => void {
106
+ + miaodaServerDisconnectedListeners.add(listener);
107
+ + return () => {
108
+ + miaodaServerDisconnectedListeners.delete(listener);
109
+ + };
110
+ +}
111
+ +
112
+ +// 横幅挂载时读取当前值,避免错过订阅注册之前发生的断线。
113
+ +export function isMiaodaServerDisconnected(): boolean {
114
+ + return miaodaServerDisconnected;
115
+ +}
116
+ +
71
117
  +let fastRefreshRequested = false;
72
118
  +// 断线兜底轮询间隔。控制消息走 /hot WebSocket,轮询只用于 socket 断开期间的
73
119
  +// 状态同步,不需要很频繁。
@@ -96,10 +142,63 @@ index c0ea71e..9250e76 100644
96
142
  +// 也要按 reload 处理(暂停期间错过的批量编辑不能靠增量补齐)。
97
143
  +let miaodaObservedPaused = false;
98
144
  +let miaodaWebSocketDisconnected = false;
145
+ +// /_hmr/status 轮询的连续失败计数(按周期计:一个周期内协议重试仍算一次)。
146
+ +// 达到阈值才判定开发服务器断线并广播给顶部横幅。3 个周期(约 6 秒)
147
+ +// 跨过网关对 Metro 瞬时崩溃的一次自动恢复窗口(最长 5 秒 backoff),
148
+ +// 避免 Metro 快速重启时闪烁误报;WebSocket close 本身不触发横幅。
149
+ +let miaodaPollFailureCount = 0;
150
+ +const MIAODA_POLL_FAILURE_THRESHOLD = 3;
99
151
  const pendingLogs: [LogLevel, any[]][] = [];
100
152
 
153
+ +// 完整重载是独立于增量的待执行意图。轮询会反复返回同一个版本,用户暂缓后
154
+ +// 仍须记住它,同时禁止后续 resume 绕过检查直接应用增量。
155
+ +let miaodaReloadIntent: { key: string; attempted: boolean } | null = null;
156
+ +let miaodaReloadChecking = false;
157
+ +let miaodaReloadCommitted = false;
158
+ +let miaodaReloadEpoch = 0;
159
+ +
160
+ +function requestMiaodaReload(key: string) {
161
+ + if (miaodaReloadCommitted) return;
162
+ + if (!isMiaodaHmrCompatibilityEnabled()) {
163
+ + reload();
164
+ + return;
165
+ + }
166
+ + if (miaodaReloadIntent?.key !== key) {
167
+ + miaodaReloadIntent = { key, attempted: false };
168
+ + miaodaReloadEpoch += 1;
169
+ + hmrClient?.disable();
170
+ + }
171
+ + void attemptMiaodaReload();
172
+ +}
173
+ +
174
+ +async function attemptMiaodaReload() {
175
+ + const intent = miaodaReloadIntent;
176
+ + if (!intent || intent.attempted || miaodaReloadChecking || miaodaReloadCommitted || miaodaPaused) return;
177
+ + intent.attempted = true;
178
+ + miaodaReloadChecking = true;
179
+ + const epoch = miaodaReloadEpoch;
180
+ + const isCurrent = () => miaodaReloadIntent === intent && miaodaReloadEpoch === epoch && !miaodaPaused && !miaodaReloadCommitted;
181
+ + try {
182
+ + if (await checkMiaodaHmrCompatibility(isCurrent) && isCurrent()) {
183
+ + miaodaReloadCommitted = true;
184
+ + reload();
185
+ + }
186
+ + } catch {
187
+ + // 检查失败保留意图,用户可通过运行中的提示重试;不自动执行新 Bundle。
188
+ + } finally {
189
+ + miaodaReloadChecking = false;
190
+ + hideLoading();
191
+ + // 检查过程中收到更新的重载指令时,旧授权无效,新指令需要自己的检查。
192
+ + if (miaodaReloadIntent !== intent || miaodaReloadEpoch !== epoch) {
193
+ + void attemptMiaodaReload();
194
+ + }
195
+ + }
196
+ +}
197
+ +
101
198
  type LogLevel =
102
- @@ -42,6 +103,102 @@ type LogLevel =
199
+ | 'trace'
200
+ | 'info'
201
+ @@ -42,6 +194,127 @@ type LogLevel =
103
202
  | 'groupEnd'
104
203
  | 'debug';
105
204
 
@@ -148,10 +247,19 @@ index c0ea71e..9250e76 100644
148
247
  + clearTimeout(miaodaPollTimer);
149
248
  + miaodaPollTimer = null;
150
249
  + }
250
+ + // 404 仍是服务端给出的应答(进程活着,只是没挂控制路由),不算断线。
251
+ + miaodaPollFailureCount = 0;
252
+ + setMiaodaServerDisconnected(false);
151
253
  + return;
152
254
  + }
153
255
  + if (!response.ok) {
154
256
  + // 5xx 等暂时性 HTTP 失败不停止轮询,下一轮继续重试。
257
+ + // 网关在 Metro 进程退出后可能返回 5xx 而非拒绝连接,与网络
258
+ + // 错误一样计入连续失败,达到阈值同样判定为断线。
259
+ + miaodaPollFailureCount += 1;
260
+ + if (miaodaPollFailureCount >= MIAODA_POLL_FAILURE_THRESHOLD) {
261
+ + setMiaodaServerDisconnected(true);
262
+ + }
155
263
  + return;
156
264
  + }
157
265
  +
@@ -160,6 +268,9 @@ index c0ea71e..9250e76 100644
160
268
  + const state = (await response.json()) as {
161
269
  + paused?: boolean; reloadPending?: boolean; stateVersion?: number; lastMode?: string | null;
162
270
  + };
271
+ + // 拿到合法状态响应说明开发服务器存活:清零失败计数并撤下断线提示。
272
+ + miaodaPollFailureCount = 0;
273
+ + setMiaodaServerDisconnected(false);
163
274
  + // Number.isInteger 不是 TS 类型守卫,先收窄 number 再判整数,
164
275
  + // 使 version 的类型收敛为 number | null。
165
276
  + const version = typeof state.stateVersion === 'number' && Number.isInteger(state.stateVersion) ? state.stateVersion : null;
@@ -168,6 +279,10 @@ index c0ea71e..9250e76 100644
168
279
  + if (miaodaSessionBaseVersion === null && version !== null) miaodaSessionBaseVersion = version;
169
280
  + if (state.paused) {
170
281
  + miaodaObservedPaused = true;
282
+ + if (!miaodaPaused) {
283
+ + miaodaReloadEpoch += 1;
284
+ + if (miaodaReloadIntent) miaodaReloadIntent.attempted = false;
285
+ + }
171
286
  + setMiaodaPaused(true);
172
287
  + hmrClient?.disable();
173
288
  + // 把观察到的这次暂停作为本地基线版本。之后若出现没有对应 WebSocket
@@ -186,14 +301,23 @@ index c0ea71e..9250e76 100644
186
301
  + setMiaodaPaused(false);
187
302
  + miaodaLastControlVersion = version;
188
303
  + if (shouldReload) {
189
- + reload();
304
+ + requestMiaodaReload(`state:${version}`);
305
+ + return;
306
+ + }
307
+ + if (miaodaReloadIntent) {
308
+ + void attemptMiaodaReload();
190
309
  + return;
191
310
  + }
192
311
  + if (fastRefreshRequested) HMRClient.enable();
193
312
  + }
194
313
  + } catch {
195
314
  + // 网络错误、超时、响应解析失败都属于暂时故障:不解除编辑闸门,
196
- + // 也不停止轮询,下一轮继续。
315
+ + // 也不停止轮询,下一轮继续。同时计入断线判定:连续多个周期都
316
+ + // 无法获得可用响应,就广播给顶部横幅提示用户开发服务器不可达。
317
+ + miaodaPollFailureCount += 1;
318
+ + if (miaodaPollFailureCount >= MIAODA_POLL_FAILURE_THRESHOLD) {
319
+ + setMiaodaServerDisconnected(true);
320
+ + }
197
321
  + } finally {
198
322
  + scheduleMiaodaStatusPoll();
199
323
  + }
@@ -202,17 +326,17 @@ index c0ea71e..9250e76 100644
202
326
  function assert(foo: any, msg: string): asserts foo {
203
327
  if (!foo) throw new Error(msg);
204
328
  }
205
- @@ -52,6 +209,9 @@ function assert(foo: any, msg: string): asserts foo {
329
+ @@ -52,6 +325,9 @@ function assert(foo: any, msg: string): asserts foo {
206
330
  */
207
331
  const HMRClient = {
208
332
  enable() {
209
333
  + fastRefreshRequested = true;
210
334
  + // Agent 编辑闸门优先于用户操作:暂停期间只记录意图,等 resume 再恢复。
211
- + if (miaodaPaused) return;
335
+ + if (miaodaPaused || miaodaReloadIntent || miaodaReloadCommitted) return;
212
336
  if (hmrUnavailableReason !== null) {
213
337
  // If HMR became unavailable while you weren't using it,
214
338
  // explain why when you try to turn it on.
215
- @@ -87,6 +247,7 @@ const HMRClient = {
339
+ @@ -87,6 +363,7 @@ const HMRClient = {
216
340
  },
217
341
 
218
342
  disable() {
@@ -220,10 +344,39 @@ index c0ea71e..9250e76 100644
220
344
  assert(hmrClient, 'Expected HMRClient.setup() call at startup.');
221
345
  hmrClient.disable();
222
346
  },
223
- @@ -180,6 +341,13 @@ const HMRClient = {
347
+ @@ -180,6 +457,42 @@ const HMRClient = {
224
348
  const origin = `${serverScheme}://${serverHost}`;
225
349
  const client = new MetroHMRClient(`${origin}/hot`);
226
350
  hmrClient = client;
351
+ + if (isMiaodaHmrCompatibilityEnabled()) {
352
+ + // 必须在 enable 和 entrypoint 注册之前安装:初始追赶增量也可能包含新原生依赖。
353
+ + const gatedClient = client as MetroHMRClient & {
354
+ + setUpdateGate: (gate: (isCurrent: () => boolean) => Promise<boolean>) => void;
355
+ + retryPendingUpdate: () => void;
356
+ + };
357
+ + gatedClient.setUpdateGate((isCurrent) => checkMiaodaHmrCompatibility(
358
+ + () => isCurrent() && hmrClient === client && !miaodaPaused && !miaodaReloadIntent && !miaodaReloadCommitted
359
+ + ));
360
+ + setMiaodaHmrCompatibilityRetry(() => {
361
+ + if (miaodaPaused || miaodaReloadCommitted) return;
362
+ + if (miaodaReloadIntent) {
363
+ + miaodaReloadIntent.attempted = false;
364
+ + void attemptMiaodaReload();
365
+ + } else if (fastRefreshRequested) {
366
+ + gatedClient.retryPendingUpdate();
367
+ + }
368
+ + });
369
+ + client.on('update-applied', (update: { isInitialUpdate?: boolean }) => {
370
+ + if (!update.isInitialUpdate) resetErrorOverlay();
371
+ + hideLoading();
372
+ + });
373
+ + client.on('update-gate-error', () => hideLoading());
374
+ + client.on('update-apply-error', (error: Error) => {
375
+ + hideLoading();
376
+ + // 模块可能已经部分执行,不能自动重放同一增量;显示错误并保留完整重载入口。
377
+ + handleCompileError(error);
378
+ + });
379
+ + }
227
380
  + if (process.env.EXPO_OS !== 'web') {
228
381
  + // 仅 native 客户端启用状态轮询。初始协议跟随 bundle URL 的 scheme:
229
382
  + // 设备可能拿到证书无效的 HTTPS 开发地址,也有环境只暴露 HTTPS,
@@ -234,7 +387,7 @@ index c0ea71e..9250e76 100644
234
387
 
235
388
  pendingEntryPoints.push(
236
389
  // HMRServer understands regular bundle URLs, so prefer that in case
237
- @@ -193,6 +361,55 @@ const HMRClient = {
390
+ @@ -193,6 +506,61 @@ const HMRClient = {
238
391
  })
239
392
  );
240
393
 
@@ -243,6 +396,9 @@ index c0ea71e..9250e76 100644
243
396
  + // 重连对面的 Metro 可能是另一个进程(例如这次开启了 HMR 控制),
244
397
  + // 重置 404 停止标志,重新探测一次。
245
398
  + miaodaStatusPollingStopped = false;
399
+ + // WebSocket 重新连上说明服务已恢复:清零失败计数并撤下断线提示。
400
+ + miaodaPollFailureCount = 0;
401
+ + setMiaodaServerDisconnected(false);
246
402
  + scheduleMiaodaStatusPoll();
247
403
  + });
248
404
  +
@@ -261,6 +417,8 @@ index c0ea71e..9250e76 100644
261
417
  + case 'pause':
262
418
  + // 立即闸住 HMR 并隐藏刷新提示,然后回 ack——服务端要等所有客户端
263
419
  + // ack 后才认为暂停完成,ack 之前 Agent 不会开始写文件。
420
+ + miaodaReloadEpoch += 1;
421
+ + if (miaodaReloadIntent) miaodaReloadIntent.attempted = false;
264
422
  + setMiaodaPaused(true);
265
423
  + client.disable();
266
424
  + hideLoading();
@@ -270,13 +428,14 @@ index c0ea71e..9250e76 100644
270
428
  + // 解除 Agent 闸门;用户自己的 Fast Refresh 开关保持独立,
271
429
  + // 只有它开着才真正恢复更新。
272
430
  + setMiaodaPaused(false);
273
- + if (fastRefreshRequested) HMRClient.enable();
431
+ + if (miaodaReloadIntent) void attemptMiaodaReload();
432
+ + else if (fastRefreshRequested) HMRClient.enable();
274
433
  + break;
275
434
  + case 'reload':
276
- + // 完整加载前也保持闸门,避免 reload 完成前又有增量进来。
277
- + setMiaodaPaused(true);
435
+ + // 完整重载意图保持增量闸门,但不使用编辑遮罩困住选择保留旧应用的用户。
436
+ + setMiaodaPaused(false);
278
437
  + client.disable();
279
- + reload();
438
+ + requestMiaodaReload(`state:${message.stateVersion ?? 'socket'}`);
280
439
  + break;
281
440
  + case 'error':
282
441
  + // 批次最终编译失败:闸门仍然关着(服务端等 Agent 修好重试),
@@ -290,7 +449,22 @@ index c0ea71e..9250e76 100644
290
449
  client.on('connection-error', (e: Error) => {
291
450
  setHMRUnavailableReason(getConnectionError(serverHost, e));
292
451
  });
293
- @@ -234,6 +451,10 @@ const HMRClient = {
452
+ @@ -221,7 +589,13 @@ const HMRClient = {
453
+ }) => {
454
+ // NOTE(@krystofwoldrich): I don't know why sometimes empty updates are sent. But they should not reset the overlay.
455
+ const isEmpty = added.length === 0 && modified.length === 0 && deleted.length === 0;
456
+ - if (client.isEnabled() && !isInitialUpdate && !isEmpty) {
457
+ + if (!isEmpty && miaodaReloadIntent && !miaodaReloadCommitted) {
458
+ + // 重载检查期间项目又有变化,旧检查及弹框授权不能放行新的完整 Bundle。
459
+ + miaodaReloadEpoch += 1;
460
+ + miaodaReloadIntent.attempted = false;
461
+ + void attemptMiaodaReload();
462
+ + }
463
+ + if (!isMiaodaHmrCompatibilityEnabled() && client.isEnabled() && !isInitialUpdate && !isEmpty) {
464
+ resetErrorOverlay();
465
+ }
466
+ }
467
+ @@ -234,6 +608,10 @@ const HMRClient = {
294
468
  client.on('error', (data) => this._onMetroError(data));
295
469
 
296
470
  client.on('close', (closeEvent?: { code: number; reason: string }) => {
@@ -301,7 +475,17 @@ index c0ea71e..9250e76 100644
301
475
  hideLoading();
302
476
  const reason = closeEvent?.reason;
303
477
  const code = closeEvent?.code || 1000;
304
- @@ -326,6 +547,9 @@ function registerBundleEntryPoints(client: MetroHMRClient | null) {
478
+ @@ -318,7 +696,8 @@ function setHMRUnavailableReason(reason: string) {
479
+ function registerBundleEntryPoints(client: MetroHMRClient | null) {
480
+ if (hmrUnavailableReason != null) {
481
+ // "Bundle Splitting – Metro disconnected"
482
+ - window.location.reload();
483
+ + if (process.env.EXPO_OS === 'web') window.location.reload();
484
+ + else requestMiaodaReload('entrypoint-unavailable');
485
+ return;
486
+ }
487
+
488
+ @@ -326,6 +705,9 @@ function registerBundleEntryPoints(client: MetroHMRClient | null) {
305
489
  client?.send(
306
490
  JSON.stringify({
307
491
  type: 'register-entrypoints',
@@ -311,6 +495,336 @@ index c0ea71e..9250e76 100644
311
495
  entryPoints: pendingEntryPoints,
312
496
  })
313
497
  );
498
+ diff --git a/src/async-require/miaodaHmrCompatibility.ts b/src/async-require/miaodaHmrCompatibility.ts
499
+ new file mode 100644
500
+ index 0000000..2201769
501
+ --- /dev/null
502
+ +++ b/src/async-require/miaodaHmrCompatibility.ts
503
+ @@ -0,0 +1,125 @@
504
+ +export type HmrCompatibilityState = {
505
+ + status: 'idle' | 'checking' | 'blocked';
506
+ + reason?: string;
507
+ +};
508
+ +
509
+ +export type HmrCompatibilityDecision = 'hold' | 'retry' | 'update';
510
+ +
511
+ +type Dependencies = {
512
+ + isEnabled: () => boolean;
513
+ + check: () => Promise<unknown>;
514
+ + confirm: (status: 'incompatible' | 'unknown', reason: string) => Promise<HmrCompatibilityDecision>;
515
+ + timeoutMs?: number;
516
+ +};
517
+ +
518
+ +const idle: HmrCompatibilityState = { status: 'idle' };
519
+ +
520
+ +// 纯协调器不依赖 RN,检查和弹框共用队列,旧弹框必须由用户关闭后才释放队列。
521
+ +export function createHmrCompatibilityController(deps: Dependencies) {
522
+ + let state = idle;
523
+ + let queue: Promise<unknown> = Promise.resolve();
524
+ + let retry: (() => void) | undefined;
525
+ + const listeners = new Set<(state: HmrCompatibilityState) => void>();
526
+ +
527
+ + function publish(next: HmrCompatibilityState) {
528
+ + state = next;
529
+ + for (const listener of listeners) {
530
+ + try {
531
+ + listener(state);
532
+ + } catch {
533
+ + // 横幅订阅异常不能中断校验,也不能阻止其他订阅者接收状态。
534
+ + }
535
+ + }
536
+ + }
537
+ +
538
+ + async function inspect(): Promise<{ status: 'compatible' | 'incompatible' | 'unknown'; reason: string }> {
539
+ + let timer: ReturnType<typeof setTimeout> | undefined;
540
+ + try {
541
+ + const result = await Promise.race([
542
+ + Promise.resolve().then(deps.check),
543
+ + new Promise<never>((_, reject) => {
544
+ + timer = setTimeout(
545
+ + () => reject(new Error('兼容性检查超过 8 秒,请检查网络后重试。')),
546
+ + deps.timeoutMs ?? 8000
547
+ + );
548
+ + }),
549
+ + ]);
550
+ + const value = result as { status?: unknown; reason?: unknown } | null;
551
+ + const reason = typeof value?.reason === 'string' ? value.reason.trim() : '';
552
+ + if (value?.status === 'compatible') {
553
+ + return { status: 'compatible', reason };
554
+ + }
555
+ + if (value?.status === 'incompatible') {
556
+ + return { status: 'incompatible', reason: reason || '当前开发构建缺少项目所需的原生能力。' };
557
+ + }
558
+ + return { status: 'unknown', reason: reason || '兼容性检查未返回明确结果,请更新开发客户端后重试。' };
559
+ + } catch (error) {
560
+ + return {
561
+ + status: 'unknown',
562
+ + reason: error instanceof Error ? error.message : '兼容性检查失败,请检查网络后重试。',
563
+ + };
564
+ + } finally {
565
+ + clearTimeout(timer);
566
+ + }
567
+ + }
568
+ +
569
+ + async function run(isCurrent: () => boolean): Promise<boolean> {
570
+ + if (!isCurrent()) {
571
+ + return false;
572
+ + }
573
+ + if (!deps.isEnabled()) {
574
+ + return true;
575
+ + }
576
+ + while (isCurrent()) {
577
+ + publish({ status: 'checking' });
578
+ + const result = await inspect();
579
+ + if (!isCurrent()) {
580
+ + return false;
581
+ + }
582
+ + if (result.status === 'compatible') {
583
+ + publish(idle);
584
+ + return true;
585
+ + }
586
+ + publish({ status: 'blocked', reason: result.reason });
587
+ + let decision: HmrCompatibilityDecision;
588
+ + try {
589
+ + decision = await deps.confirm(result.status, result.reason);
590
+ + } catch {
591
+ + // 弹框异常也保留暂停状态,横幅仍可触发重试。
592
+ + return false;
593
+ + }
594
+ + if (!isCurrent()) {
595
+ + return false;
596
+ + }
597
+ + if (decision === 'update') {
598
+ + publish(idle);
599
+ + return true;
600
+ + }
601
+ + if (decision !== 'retry') {
602
+ + return false;
603
+ + }
604
+ + }
605
+ + return false;
606
+ + }
607
+ +
608
+ + return {
609
+ + checkMiaodaHmrCompatibility(isCurrent: () => boolean): Promise<boolean> {
610
+ + const task = queue.then(() => run(isCurrent));
611
+ + // 检查异常不能阻塞后续目标的校验。
612
+ + queue = task.catch(() => {});
613
+ + return task;
614
+ + },
615
+ + isMiaodaHmrCompatibilityEnabled: deps.isEnabled,
616
+ + getMiaodaHmrCompatibilityState: () => state,
617
+ + subscribeMiaodaHmrCompatibility(listener: (state: HmrCompatibilityState) => void) {
618
+ + listeners.add(listener);
619
+ + return () => { listeners.delete(listener); };
620
+ + },
621
+ + setMiaodaHmrCompatibilityRetry(callback: () => void) {
622
+ + retry = callback;
623
+ + },
624
+ + retryMiaodaHmrCompatibility() {
625
+ + retry?.();
626
+ + },
627
+ + };
628
+ +}
629
+ diff --git a/src/async-require/miaodaHmrCompatibilityCheck.native.ts b/src/async-require/miaodaHmrCompatibilityCheck.native.ts
630
+ new file mode 100644
631
+ index 0000000..721fd81
632
+ --- /dev/null
633
+ +++ b/src/async-require/miaodaHmrCompatibilityCheck.native.ts
634
+ @@ -0,0 +1,47 @@
635
+ +import { Alert } from 'react-native';
636
+ +
637
+ +import { createHmrCompatibilityController } from './miaodaHmrCompatibility';
638
+ +import { isRunningInExpoGo } from '../environment/ExpoGo';
639
+ +
640
+ +export type { HmrCompatibilityState } from './miaodaHmrCompatibility';
641
+ +
642
+ +const controller = createHmrCompatibilityController({
643
+ + isEnabled: () => !isRunningInExpoGo(),
644
+ + check: async () => {
645
+ + // 按 LogBox 的延迟注册方式取模块,兼容桥接模块尚未安装的初始化阶段。
646
+ + const runtime = globalThis as typeof globalThis & {
647
+ + expo?: { modules?: { ExpoDevLauncher?: { checkCopyCompatibility?: () => Promise<unknown> } } };
648
+ + };
649
+ + if (runtime.expo == null) {
650
+ + const registry = require('react-native/Libraries/TurboModule/TurboModuleRegistry');
651
+ + registry.get('ExpoModulesCore')?.installModules?.();
652
+ + }
653
+ + const module = runtime.expo?.modules?.ExpoDevLauncher;
654
+ + if (typeof module?.checkCopyCompatibility !== 'function') {
655
+ + throw new Error('当前开发客户端不支持兼容性检查,请升级开发客户端并重新构建应用。');
656
+ + }
657
+ + // 只读取兼容性结果,不触发任何剪贴板写入。
658
+ + return module.checkCopyCompatibility();
659
+ + },
660
+ + confirm: (status, reason) => new Promise((resolve) => {
661
+ + Alert.alert(
662
+ + status === 'incompatible' ? '当前开发构建能力不完整' : '无法确认当前开发构建是否适用',
663
+ + `${reason}\n\n更新已暂停,当前应用仍可继续使用。建议根据项目最新原生依赖重新构建并安装开发客户端后再更新。仍要更新可能导致应用无法运行。`,
664
+ + [
665
+ + { text: '保留当前应用', style: 'cancel', onPress: () => resolve('hold') },
666
+ + { text: '重新检查', onPress: () => resolve('retry') },
667
+ + { text: '仍要更新', style: 'destructive', onPress: () => resolve('update') },
668
+ + ],
669
+ + { cancelable: false }
670
+ + );
671
+ + }),
672
+ +});
673
+ +
674
+ +export const {
675
+ + checkMiaodaHmrCompatibility,
676
+ + isMiaodaHmrCompatibilityEnabled,
677
+ + subscribeMiaodaHmrCompatibility,
678
+ + getMiaodaHmrCompatibilityState,
679
+ + setMiaodaHmrCompatibilityRetry,
680
+ + retryMiaodaHmrCompatibility,
681
+ +} = controller;
682
+ diff --git a/src/async-require/miaodaHmrCompatibilityCheck.ts b/src/async-require/miaodaHmrCompatibilityCheck.ts
683
+ new file mode 100644
684
+ index 0000000..1487079
685
+ --- /dev/null
686
+ +++ b/src/async-require/miaodaHmrCompatibilityCheck.ts
687
+ @@ -0,0 +1,18 @@
688
+ +import { createHmrCompatibilityController } from './miaodaHmrCompatibility';
689
+ +
690
+ +export type { HmrCompatibilityState } from './miaodaHmrCompatibility';
691
+ +
692
+ +const controller = createHmrCompatibilityController({
693
+ + isEnabled: () => false,
694
+ + check: async () => ({ status: 'compatible' }),
695
+ + confirm: async () => 'hold',
696
+ +});
697
+ +
698
+ +export const {
699
+ + checkMiaodaHmrCompatibility,
700
+ + isMiaodaHmrCompatibilityEnabled,
701
+ + subscribeMiaodaHmrCompatibility,
702
+ + getMiaodaHmrCompatibilityState,
703
+ + setMiaodaHmrCompatibilityRetry,
704
+ + retryMiaodaHmrCompatibility,
705
+ +} = controller;
706
+ diff --git a/src/launch/MiaodaDevServerBanner.tsx b/src/launch/MiaodaDevServerBanner.tsx
707
+ new file mode 100644
708
+ index 0000000..6313570
709
+ --- /dev/null
710
+ +++ b/src/launch/MiaodaDevServerBanner.tsx
711
+ @@ -0,0 +1,47 @@
712
+ +import * as React from 'react';
713
+ +import { StyleSheet, Text, View } from 'react-native';
714
+ +
715
+ +import { isMiaodaServerDisconnected, subscribeMiaodaServerDisconnected } from '../async-require/hmr';
716
+ +import { getInitialSafeArea } from '../environment/getInitialSafeArea';
717
+ +
718
+ +// 开发服务器断线提示横幅:/_hmr/status 轮询连续失败达到阈值后显示,
719
+ +// 服务恢复或 WebSocket 重连后自动消失。非阻断(pointerEvents: 'none'),
720
+ +// 不影响应用交互;已加载的 JS 继续运行,只有代码更新会中断。
721
+ +export default function MiaodaDevServerBanner(): React.ReactElement | null {
722
+ + const [disconnected, setDisconnected] = React.useState(isMiaodaServerDisconnected);
723
+ + React.useEffect(() => subscribeMiaodaServerDisconnected(setDisconnected), []);
724
+ + if (!disconnected) return null;
725
+ + return (
726
+ + <View style={styles.container}>
727
+ + <Text style={styles.title}>已断开开发服务器</Text>
728
+ + <Text style={styles.subtitle}>应用仍可继续使用,服务恢复后将自动重连</Text>
729
+ + </View>
730
+ + );
731
+ +}
732
+ +
733
+ +const styles = StyleSheet.create({
734
+ + container: {
735
+ + position: 'absolute',
736
+ + top: 0,
737
+ + left: 0,
738
+ + right: 0,
739
+ + alignItems: 'center',
740
+ + paddingTop: 12 + getInitialSafeArea().top,
741
+ + paddingBottom: 12,
742
+ + backgroundColor: 'rgba(0,0,0,0.75)',
743
+ + // 与 Expo 自带的 Fast Refresh 横幅同层,盖在应用内容之上。
744
+ + zIndex: 42,
745
+ + // 非阻断:整条横幅不接收任何触摸事件,应用照常可交互。
746
+ + pointerEvents: 'none',
747
+ + },
748
+ + title: {
749
+ + color: '#ffffff',
750
+ + fontSize: 15,
751
+ + fontWeight: '600',
752
+ + },
753
+ + subtitle: {
754
+ + color: 'rgba(255,255,255,0.8)',
755
+ + fontSize: 13,
756
+ + marginTop: 4,
757
+ + },
758
+ +});
759
+ diff --git a/src/launch/MiaodaHmrCompatibilityBanner.tsx b/src/launch/MiaodaHmrCompatibilityBanner.tsx
760
+ new file mode 100644
761
+ index 0000000..4d17e1c
762
+ --- /dev/null
763
+ +++ b/src/launch/MiaodaHmrCompatibilityBanner.tsx
764
+ @@ -0,0 +1,63 @@
765
+ +import * as React from 'react';
766
+ +import { Pressable, StyleSheet, Text, View } from 'react-native';
767
+ +
768
+ +import {
769
+ + getMiaodaHmrCompatibilityState,
770
+ + isMiaodaHmrCompatibilityEnabled,
771
+ + retryMiaodaHmrCompatibility,
772
+ + subscribeMiaodaHmrCompatibility,
773
+ +} from '../async-require/miaodaHmrCompatibilityCheck';
774
+ +import { getInitialSafeArea } from '../environment/getInitialSafeArea';
775
+ +
776
+ +export default function MiaodaHmrCompatibilityBanner(): React.ReactElement | null {
777
+ + const [state, setState] = React.useState(getMiaodaHmrCompatibilityState);
778
+ + React.useEffect(() => {
779
+ + const unsubscribe = subscribeMiaodaHmrCompatibility(setState);
780
+ + setState(getMiaodaHmrCompatibilityState());
781
+ + return unsubscribe;
782
+ + }, []);
783
+ + if (!isMiaodaHmrCompatibilityEnabled() || state.status !== 'blocked') {
784
+ + return null;
785
+ + }
786
+ + return (
787
+ + <View pointerEvents="box-none" style={styles.container}>
788
+ + <View style={styles.banner}>
789
+ + <Text style={styles.title}>更新已暂停</Text>
790
+ + <Text style={styles.subtitle}>当前应用仍可使用,请重建开发客户端以补全原生能力</Text>
791
+ + <Pressable
792
+ + accessibilityRole="button"
793
+ + accessibilityLabel="重试检查开发构建兼容性"
794
+ + onPress={retryMiaodaHmrCompatibility}
795
+ + style={styles.retry}>
796
+ + <Text style={styles.retryText}>重试检查</Text>
797
+ + </Pressable>
798
+ + </View>
799
+ + </View>
800
+ + );
801
+ +}
802
+ +
803
+ +const styles = StyleSheet.create({
804
+ + container: {
805
+ + position: 'absolute',
806
+ + left: 0,
807
+ + right: 0,
808
+ + bottom: 12 + getInitialSafeArea().bottom,
809
+ + alignItems: 'center',
810
+ + // 底部悬浮避免遮住顶部断线横幅,容器外的应用内容仍可交互。
811
+ + zIndex: 42,
812
+ + },
813
+ + banner: {
814
+ + alignItems: 'center',
815
+ + maxWidth: 420,
816
+ + marginHorizontal: 12,
817
+ + paddingHorizontal: 16,
818
+ + paddingTop: 12,
819
+ + paddingBottom: 8,
820
+ + borderRadius: 12,
821
+ + backgroundColor: 'rgba(0,0,0,0.8)',
822
+ + },
823
+ + title: { color: '#ffffff', fontSize: 15, fontWeight: '600' },
824
+ + subtitle: { color: 'rgba(255,255,255,0.8)', fontSize: 13, marginTop: 4, textAlign: 'center' },
825
+ + retry: { paddingHorizontal: 16, paddingVertical: 10, marginTop: 2 },
826
+ + retryText: { color: '#ffffff', fontSize: 14, fontWeight: '600' },
827
+ +});
314
828
  diff --git a/src/launch/MiaodaHmrOverlay.tsx b/src/launch/MiaodaHmrOverlay.tsx
315
829
  new file mode 100644
316
830
  index 0000000..2db61b9
@@ -376,23 +890,27 @@ index 0000000..2db61b9
376
890
  + },
377
891
  +});
378
892
  diff --git a/src/launch/withDevTools.ios.tsx b/src/launch/withDevTools.ios.tsx
379
- index f1f686c..0029bfa 100644
893
+ index f1f686c..c64b1ca 100644
380
894
  --- a/src/launch/withDevTools.ios.tsx
381
895
  +++ b/src/launch/withDevTools.ios.tsx
382
- @@ -3,6 +3,8 @@ import * as React from 'react';
896
+ @@ -3,6 +3,10 @@ import * as React from 'react';
383
897
  import DevLoadingView from '../environment/DevLoadingView';
384
898
  import { isRunningInExpoGo } from '../environment/ExpoGo';
385
899
 
900
+ +import MiaodaDevServerBanner from './MiaodaDevServerBanner';
386
901
  +import MiaodaHmrOverlay from './MiaodaHmrOverlay';
902
+ +import MiaodaHmrCompatibilityBanner from './MiaodaHmrCompatibilityBanner';
387
903
  +
388
904
  /**
389
905
  * Append the Expo Fast Refresh view and optionally
390
906
  * keep the screen awake if `expo-keep-awake` is installed.
391
- @@ -31,11 +33,17 @@ export function withDevTools<TComponent extends React.ComponentType<any>>(
907
+ @@ -31,11 +35,21 @@ export function withDevTools<TComponent extends React.ComponentType<any>>(
392
908
  <>
393
909
  <AppRootComponent {...props} />
394
910
  <DevLoadingView />
395
911
  + <MiaodaHmrOverlay />
912
+ + <MiaodaDevServerBanner />
913
+ + <MiaodaHmrCompatibilityBanner />
396
914
  </>
397
915
  );
398
916
  }
@@ -402,24 +920,28 @@ index f1f686c..0029bfa 100644
402
920
  + <>
403
921
  + <AppRootComponent {...props} />
404
922
  + <MiaodaHmrOverlay />
923
+ + <MiaodaDevServerBanner />
924
+ + <MiaodaHmrCompatibilityBanner />
405
925
  + </>
406
926
  + );
407
927
  }
408
928
 
409
929
  if (process.env.NODE_ENV !== 'production') {
410
930
  diff --git a/src/launch/withDevTools.tsx b/src/launch/withDevTools.tsx
411
- index 5a98062..6a6c3b7 100644
931
+ index 5a98062..c97b70d 100644
412
932
  --- a/src/launch/withDevTools.tsx
413
933
  +++ b/src/launch/withDevTools.tsx
414
- @@ -1,5 +1,7 @@
934
+ @@ -1,5 +1,9 @@
415
935
  import * as React from 'react';
416
936
 
937
+ +import MiaodaDevServerBanner from './MiaodaDevServerBanner';
417
938
  +import MiaodaHmrOverlay from './MiaodaHmrOverlay';
939
+ +import MiaodaHmrCompatibilityBanner from './MiaodaHmrCompatibilityBanner';
418
940
  +
419
941
  // Keep the screen awake on Android, we don't use the Fast Refresh overlay here.
420
942
  // The default behavior here is to skip the custom Fast Refresh indicator.
421
943
  export function withDevTools<TComponent extends React.ComponentType<any>>(
422
- @@ -18,7 +20,12 @@ export function withDevTools<TComponent extends React.ComponentType<any>>(
944
+ @@ -18,7 +22,14 @@ export function withDevTools<TComponent extends React.ComponentType<any>>(
423
945
 
424
946
  function WithDevTools(props: React.ComponentProps<TComponent>) {
425
947
  useOptionalKeepAwake();
@@ -428,6 +950,8 @@ index 5a98062..6a6c3b7 100644
428
950
  + <>
429
951
  + <AppRootComponent {...props} />
430
952
  + <MiaodaHmrOverlay />
953
+ + <MiaodaDevServerBanner />
954
+ + <MiaodaHmrCompatibilityBanner />
431
955
  + </>
432
956
  + );
433
957
  }
@@ -1,8 +1,37 @@
1
1
  diff --git a/src/modules/HMRClient.js b/src/modules/HMRClient.js
2
- index 3e2652d..8225714 100644
2
+ index 3e2652d..111bf20 100644
3
3
  --- a/src/modules/HMRClient.js
4
4
  +++ b/src/modules/HMRClient.js
5
- @@ -35,6 +35,12 @@ class HMRClient extends EventEmitter {
5
+ @@ -15,12 +15,21 @@ const injectUpdate = (update) => {
6
+ class HMRClient extends EventEmitter {
7
+ _isEnabled = false;
8
+ _pendingUpdate = null;
9
+ + _updateGate = null;
10
+ + _updateGeneration = 0;
11
+ + _gateEpoch = 0;
12
+ + _gateRunning = false;
13
+ + _gateRequested = false;
14
+ + _isInvalid = false;
15
+ _queue = [];
16
+ _state = "opening";
17
+ constructor(url) {
18
+ super();
19
+ this._ws = new global.WebSocket(url);
20
+ this._ws.onopen = () => {
21
+ + if (this._isInvalid) {
22
+ + return;
23
+ + }
24
+ this._state = "open";
25
+ this.emit("open");
26
+ this._flushQueue();
27
+ @@ -29,12 +38,20 @@ class HMRClient extends EventEmitter {
28
+ this.emit("connection-error", error);
29
+ };
30
+ this._ws.onclose = (closeEvent) => {
31
+ - this._state = "closed";
32
+ + this._invalidate();
33
+ this.emit("close", closeEvent);
34
+ };
6
35
  this._ws.onmessage = (message) => {
7
36
  const data = JSON.parse(String(message.data));
8
37
  switch (data.type) {
@@ -10,8 +39,327 @@ index 3e2652d..8225714 100644
10
39
  + // 控制消息。HMRClient 只做透传转发,具体处理在 expo 包的
11
40
  + // async-require/hmr.ts(该补丁同时加了版本协商,version !== 1 直接忽略)。
12
41
  + case "miaoda-hmr-control":
13
- + if (data.version === 1) this.emit("miaoda-hmr-control", data);
42
+ + if (data.version === 1) {
43
+ + this.emit("miaoda-hmr-control", data);
44
+ + }
14
45
  + break;
15
46
  case "bundle-registered":
16
47
  this.emit("bundle-registered");
17
48
  break;
49
+ @@ -58,16 +75,18 @@ class HMRClient extends EventEmitter {
50
+ }
51
+ };
52
+ this.on("update", (update) => {
53
+ - if (this._isEnabled) {
54
+ - injectUpdate(update);
55
+ - } else if (this._pendingUpdate == null) {
56
+ - this._pendingUpdate = update;
57
+ - } else {
58
+ - this._pendingUpdate = mergeUpdates(this._pendingUpdate, update);
59
+ + if (this._isInvalid) {
60
+ + return;
61
+ }
62
+ + this._updateGeneration++;
63
+ + this._pendingUpdate = this._pendingUpdate == null
64
+ + ? update
65
+ + : mergeUpdates(this._pendingUpdate, update);
66
+ + this._requestPendingUpdate();
67
+ });
68
+ }
69
+ close() {
70
+ + this._invalidate();
71
+ this._ws.close();
72
+ }
73
+ send(message) {
74
+ @@ -89,15 +108,98 @@ class HMRClient extends EventEmitter {
75
+ this._queue.length = 0;
76
+ }
77
+ enable() {
78
+ + if (this._isInvalid || this._isEnabled) {
79
+ + return;
80
+ + }
81
+ this._isEnabled = true;
82
+ + this._requestPendingUpdate();
83
+ + }
84
+ + disable() {
85
+ + this._isEnabled = false;
86
+ + this._gateEpoch++;
87
+ + }
88
+ + setUpdateGate(gate) {
89
+ + if (this._updateGate === gate) {
90
+ + return;
91
+ + }
92
+ + this._updateGate = gate;
93
+ + this._gateEpoch++;
94
+ + this._requestPendingUpdate();
95
+ + }
96
+ + retryPendingUpdate() {
97
+ + this._gateEpoch++;
98
+ + this._requestPendingUpdate();
99
+ + }
100
+ + _invalidate() {
101
+ + this._isInvalid = true;
102
+ + this._isEnabled = false;
103
+ + this._state = "closed";
104
+ + this._gateEpoch++;
105
+ + }
106
+ + _requestPendingUpdate() {
107
+ + this._gateRequested = true;
108
+ + this._flushPendingUpdate();
109
+ + }
110
+ + _flushPendingUpdate() {
111
+ + if (this._isInvalid || !this._isEnabled || this._gateRunning || !this._gateRequested) {
112
+ + return;
113
+ + }
114
+ + this._gateRequested = false;
115
+ const update = this._pendingUpdate;
116
+ + if (update == null) {
117
+ + return;
118
+ + }
119
+ + const gate = this._updateGate;
120
+ + if (gate == null || (update.added.length === 0 && update.modified.length === 0 && update.deleted.length === 0)) {
121
+ + this._applyPendingUpdate(update);
122
+ + return;
123
+ + }
124
+ + this._gateRunning = true;
125
+ + this._runUpdateGate(update, this._updateGeneration, this._gateEpoch, gate).catch(error => {
126
+ + // 异步路径不能把监听器或收尾异常变成未处理的 Promise 拒绝。
127
+ + this._emitSafely("update-gate-error", error);
128
+ + });
129
+ + }
130
+ + async _runUpdateGate(update, generation, epoch, gate) {
131
+ + const isCurrent = () => !this._isInvalid && this._isEnabled &&
132
+ + this._pendingUpdate === update && this._updateGeneration === generation && this._gateEpoch === epoch;
133
+ + try {
134
+ + let allowed;
135
+ + try {
136
+ + allowed = await gate(isCurrent);
137
+ + } catch (error) {
138
+ + this._emitSafely("update-gate-error", error);
139
+ + return;
140
+ + }
141
+ + if (allowed && isCurrent()) {
142
+ + this._applyPendingUpdate(update, true);
143
+ + }
144
+ + } finally {
145
+ + // 旧检查完成后才处理新请求,避免同时出现多个兼容性弹窗。
146
+ + this._gateRunning = false;
147
+ + this._flushPendingUpdate();
148
+ + }
149
+ + }
150
+ + _emitSafely(event, value) {
151
+ + try {
152
+ + this.emit(event, value);
153
+ + } catch (error) {
154
+ + // 事件监听器属于宿主代码,不能破坏 gate 的异步收尾。
155
+ + }
156
+ + }
157
+ + _applyPendingUpdate(update, handleErrors = false) {
158
+ + // 注入必须同步完成;提前移除整批,避免部分注入失败后被重放。
159
+ this._pendingUpdate = null;
160
+ - if (update != null) {
161
+ + try {
162
+ injectUpdate(update);
163
+ + } catch (error) {
164
+ + if (!handleErrors) {
165
+ + throw error;
166
+ + }
167
+ + this._emitSafely("update-apply-error", error);
168
+ + return;
169
+ }
170
+ - }
171
+ - disable() {
172
+ - this._isEnabled = false;
173
+ + this._emitSafely("update-applied", update);
174
+ }
175
+ isEnabled() {
176
+ return this._isEnabled;
177
+ diff --git a/src/modules/HMRClient.js.flow b/src/modules/HMRClient.js.flow
178
+ index 18040c4..62b7b20 100644
179
+ --- a/src/modules/HMRClient.js.flow
180
+ +++ b/src/modules/HMRClient.js.flow
181
+ @@ -15,6 +15,8 @@ import type {HmrMessage, HmrUpdate} from './types';
182
+
183
+ const EventEmitter = require('./vendor/eventemitter3');
184
+
185
+ +type UpdateGate = (isCurrent: () => boolean) => Promise<boolean>;
186
+ +
187
+ type SocketState = 'opening' | 'open' | 'closed';
188
+
189
+ const inject = ({module: [id, code], sourceURL}: HmrModule) => {
190
+ @@ -36,6 +38,12 @@ const injectUpdate = (update: HmrUpdate) => {
191
+ class HMRClient extends EventEmitter {
192
+ _isEnabled: boolean = false;
193
+ _pendingUpdate: HmrUpdate | null = null;
194
+ + _updateGate: UpdateGate | null = null;
195
+ + _updateGeneration: number = 0;
196
+ + _gateEpoch: number = 0;
197
+ + _gateRunning: boolean = false;
198
+ + _gateRequested: boolean = false;
199
+ + _isInvalid: boolean = false;
200
+ _queue: Array<string> = [];
201
+ _state: SocketState = 'opening';
202
+ _ws: WebSocket;
203
+ @@ -47,6 +55,9 @@ class HMRClient extends EventEmitter {
204
+ // since some polyfills do the initialization lazily.
205
+ this._ws = new global.WebSocket(url);
206
+ this._ws.onopen = () => {
207
+ + if (this._isInvalid) {
208
+ + return;
209
+ + }
210
+ this._state = 'open';
211
+ this.emit('open');
212
+ this._flushQueue();
213
+ @@ -55,13 +66,20 @@ class HMRClient extends EventEmitter {
214
+ this.emit('connection-error', error);
215
+ };
216
+ this._ws.onclose = closeEvent => {
217
+ - this._state = 'closed';
218
+ + this._invalidate();
219
+ this.emit('close', closeEvent);
220
+ };
221
+ this._ws.onmessage = message => {
222
+ - const data: HmrMessage = JSON.parse(String(message.data));
223
+ + const data: HmrMessage | {type: 'miaoda-hmr-control', version: number, [string]: mixed} = JSON.parse(String(message.data));
224
+
225
+ switch (data.type) {
226
+ + // 与运行代码对齐,只透传当前版本的批量编辑控制帧。
227
+ + case 'miaoda-hmr-control':
228
+ + if (data.version === 1) {
229
+ + this.emit('miaoda-hmr-control', data);
230
+ + }
231
+ + break;
232
+ +
233
+ case 'bundle-registered':
234
+ this.emit('bundle-registered');
235
+ break;
236
+ @@ -88,17 +106,19 @@ class HMRClient extends EventEmitter {
237
+ };
238
+
239
+ this.on('update', (update: HmrUpdate) => {
240
+ - if (this._isEnabled) {
241
+ - injectUpdate(update);
242
+ - } else if (this._pendingUpdate == null) {
243
+ - this._pendingUpdate = update;
244
+ - } else {
245
+ - this._pendingUpdate = mergeUpdates(this._pendingUpdate, update);
246
+ + if (this._isInvalid) {
247
+ + return;
248
+ }
249
+ + this._updateGeneration++;
250
+ + this._pendingUpdate = this._pendingUpdate == null
251
+ + ? update
252
+ + : mergeUpdates(this._pendingUpdate, update);
253
+ + this._requestPendingUpdate();
254
+ });
255
+ }
256
+
257
+ close(): void {
258
+ + this._invalidate();
259
+ this._ws.close();
260
+ }
261
+
262
+ @@ -124,16 +144,98 @@ class HMRClient extends EventEmitter {
263
+ }
264
+
265
+ enable() {
266
+ + if (this._isInvalid || this._isEnabled) {
267
+ + return;
268
+ + }
269
+ this._isEnabled = true;
270
+ + this._requestPendingUpdate();
271
+ + }
272
+ + disable() {
273
+ + this._isEnabled = false;
274
+ + this._gateEpoch++;
275
+ + }
276
+ + setUpdateGate(gate: UpdateGate | null) {
277
+ + if (this._updateGate === gate) {
278
+ + return;
279
+ + }
280
+ + this._updateGate = gate;
281
+ + this._gateEpoch++;
282
+ + this._requestPendingUpdate();
283
+ + }
284
+ + retryPendingUpdate() {
285
+ + this._gateEpoch++;
286
+ + this._requestPendingUpdate();
287
+ + }
288
+ + _invalidate() {
289
+ + this._isInvalid = true;
290
+ + this._isEnabled = false;
291
+ + this._state = 'closed';
292
+ + this._gateEpoch++;
293
+ + }
294
+ + _requestPendingUpdate() {
295
+ + this._gateRequested = true;
296
+ + this._flushPendingUpdate();
297
+ + }
298
+ + _flushPendingUpdate() {
299
+ + if (this._isInvalid || !this._isEnabled || this._gateRunning || !this._gateRequested) {
300
+ + return;
301
+ + }
302
+ + this._gateRequested = false;
303
+ const update = this._pendingUpdate;
304
+ + if (update == null) {
305
+ + return;
306
+ + }
307
+ + const gate = this._updateGate;
308
+ + if (gate == null || (update.added.length === 0 && update.modified.length === 0 && update.deleted.length === 0)) {
309
+ + this._applyPendingUpdate(update);
310
+ + return;
311
+ + }
312
+ + this._gateRunning = true;
313
+ + this._runUpdateGate(update, this._updateGeneration, this._gateEpoch, gate).catch(error => {
314
+ + // 异步路径不能把监听器或收尾异常变成未处理的 Promise 拒绝。
315
+ + this._emitSafely('update-gate-error', error);
316
+ + });
317
+ + }
318
+ + async _runUpdateGate(update: HmrUpdate, generation: number, epoch: number, gate: UpdateGate): Promise<void> {
319
+ + const isCurrent = () => !this._isInvalid && this._isEnabled &&
320
+ + this._pendingUpdate === update && this._updateGeneration === generation && this._gateEpoch === epoch;
321
+ + try {
322
+ + let allowed;
323
+ + try {
324
+ + allowed = await gate(isCurrent);
325
+ + } catch (error) {
326
+ + this._emitSafely('update-gate-error', error);
327
+ + return;
328
+ + }
329
+ + if (allowed && isCurrent()) {
330
+ + this._applyPendingUpdate(update, true);
331
+ + }
332
+ + } finally {
333
+ + // 旧检查完成后才处理新请求,避免同时出现多个兼容性弹窗。
334
+ + this._gateRunning = false;
335
+ + this._flushPendingUpdate();
336
+ + }
337
+ + }
338
+ + _emitSafely(event: string, value: mixed): void {
339
+ + try {
340
+ + this.emit(event, value);
341
+ + } catch (error) {
342
+ + // 事件监听器属于宿主代码,不能破坏 gate 的异步收尾。
343
+ + }
344
+ + }
345
+ + _applyPendingUpdate(update: HmrUpdate, handleErrors: boolean = false) {
346
+ + // 注入必须同步完成;提前移除整批,避免部分注入失败后被重放。
347
+ this._pendingUpdate = null;
348
+ - if (update != null) {
349
+ + try {
350
+ injectUpdate(update);
351
+ + } catch (error) {
352
+ + if (!handleErrors) {
353
+ + throw error;
354
+ + }
355
+ + this._emitSafely('update-apply-error', error);
356
+ + return;
357
+ }
358
+ - }
359
+ -
360
+ - disable() {
361
+ - this._isEnabled = false;
362
+ + this._emitSafely('update-applied', update);
363
+ }
364
+
365
+ isEnabled(): boolean {
package/pnpmfile.cjs CHANGED
@@ -27,6 +27,7 @@ const managedPatches = {
27
27
  'metro-runtime@0.83.3': {
28
28
  filename: 'metro-runtime@0.83.3.patch',
29
29
  legacyHashes: new Set([
30
+ '76aa02561be5343f25d60309a5a6fef13bd1d32f72203ac2e81352cef24e361f',
30
31
  'bd14ae6037bcf49028607c01caf67d4bd03e543460609a62e72647664c27b242',
31
32
  ]),
32
33
  },
@@ -51,6 +52,10 @@ const managedPatches = {
51
52
  'expo@55.0.6': {
52
53
  filename: 'expo@55.0.6.patch',
53
54
  legacyHashes: new Set([
55
+ '4a8905eb936e57ba88f0492c12def4e6e402526cb93069cba54d2f1afe820f96',
56
+ 'fd87f54739c416500b09153e6733f49f2ee64e31622a007ec868dbd7e308a558',
57
+ '7a7e7180540cbffd985d0e8cfa57ad6b87e0ae425c2a25b231e4b15463357992',
58
+ '912a9598dcce4a4803ad9f96079bd0f0dc71d3d0adea2c2e2f9784161faef381',
54
59
  '3eca6fa71eb9640bccf2075dc37c5c8ed2fa060db77b36bb2c67fba902a9a9c5',
55
60
  '1df9b522728e93daf64f9e2298ab835ce52d55b4aa2de92a68b947e7ed08f40a',
56
61
  '8ac63998a9852ddafda7af96deb4d7ac4c3a5da5e65e865af32be9d4fd966e02',