@lynx-js/react 0.128.0 → 0.129.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 (174) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/components/tsconfig.tsbuildinfo +1 -1
  3. package/package.json +1 -1
  4. package/refresh/.turbo/turbo-build.log +1 -1
  5. package/runtime/__test__/core/entry-re-eval.test.ts +161 -0
  6. package/runtime/__test__/core/reload-scoped-dual-thread-communication.test.ts +129 -0
  7. package/runtime/__test__/core/thread-function-call.test.ts +1 -0
  8. package/runtime/__test__/element-template/fixtures/background/render/_shared.tsx +2 -0
  9. package/runtime/__test__/element-template/native/index.test.ts +8 -0
  10. package/runtime/__test__/element-template/native/main-thread-ref-init-value.test.ts +100 -0
  11. package/runtime/__test__/element-template/native/reload-dual-thread-communication.test.ts +101 -0
  12. package/runtime/__test__/element-template/native/reload.test.ts +50 -1
  13. package/runtime/__test__/element-template/runtime/background/commit-hook.test.ts +104 -47
  14. package/runtime/__test__/element-template/runtime/background/main-thread-function/compiled-fixtures.test.tsx +7 -1
  15. package/runtime/__test__/element-template/runtime/background/re-eval-reload.test.ts +69 -0
  16. package/runtime/__test__/element-template/runtime/hydration/hydration-listener.test.ts +31 -5
  17. package/runtime/__test__/element-template/runtime/patch/element-template-patch.test.tsx +17 -3
  18. package/runtime/__test__/element-template/runtime/render/render-transform.contract.test.ts +2 -0
  19. package/runtime/__test__/element-template/runtime/template/main-thread-function.test.ts +89 -2
  20. package/runtime/__test__/element-template/test-utils/debug/compiledFixtureModule.ts +5 -0
  21. package/runtime/__test__/snapshot/lifecycle/re-eval-reload.test.jsx +114 -0
  22. package/runtime/__test__/snapshot/lifecycle/reload-background-function.test.jsx +169 -0
  23. package/runtime/__test__/snapshot/lifecycle/reload-delayed-background.test.jsx +63 -0
  24. package/runtime/__test__/snapshot/lifecycle/reload-delayed-main-thread.test.jsx +103 -0
  25. package/runtime/__test__/snapshot/lifecycle.test.jsx +61 -1
  26. package/runtime/__test__/snapshot/lynx/lazy-effect-scheduling.test.jsx +105 -0
  27. package/runtime/__test__/snapshot/ssr.test.jsx +2 -2
  28. package/runtime/__test__/snapshot/worklet/runOnBackground.test.js +6 -11
  29. package/runtime/__test__/snapshot/worklet/runOnMainThread.test.jsx +1 -1
  30. package/runtime/__test__/snapshot/worklet/workletRef.test.jsx +24 -1
  31. package/runtime/__test__/worklet-runtime/jsFunctionLifecycle.test.js +15 -1
  32. package/runtime/__test__/worklet-runtime/mainThreadObject.test.js +46 -0
  33. package/runtime/__test__/worklet-runtime/runOnMainThread.test.js +3 -3
  34. package/runtime/lib/core/background-function/exec-map.d.ts +2 -0
  35. package/runtime/lib/core/background-function/exec-map.js +7 -0
  36. package/runtime/lib/core/background-function/exec-map.js.map +1 -1
  37. package/runtime/lib/core/background-function/run-on-background.js +15 -16
  38. package/runtime/lib/core/background-function/run-on-background.js.map +1 -1
  39. package/runtime/lib/core/card-lifetime.d.ts +5 -0
  40. package/runtime/lib/core/card-lifetime.js +17 -0
  41. package/runtime/lib/core/card-lifetime.js.map +1 -0
  42. package/runtime/lib/core/entry-reload.d.ts +7 -0
  43. package/runtime/lib/core/entry-reload.js +49 -0
  44. package/runtime/lib/core/entry-reload.js.map +1 -0
  45. package/runtime/lib/core/lynx/lazy-bundle.js +4 -1
  46. package/runtime/lib/core/lynx/lazy-bundle.js.map +1 -1
  47. package/runtime/lib/core/main-thread-ref-id.js +4 -4
  48. package/runtime/lib/core/main-thread-ref-id.js.map +1 -1
  49. package/runtime/lib/core/reload-scoped-event.d.ts +5 -0
  50. package/runtime/lib/core/reload-scoped-event.js +26 -0
  51. package/runtime/lib/core/reload-scoped-event.js.map +1 -0
  52. package/runtime/lib/core/reload-version.js +4 -3
  53. package/runtime/lib/core/reload-version.js.map +1 -1
  54. package/runtime/lib/core/runtime-destroy.d.ts +2 -0
  55. package/runtime/lib/core/runtime-destroy.js +9 -0
  56. package/runtime/lib/core/runtime-destroy.js.map +1 -1
  57. package/runtime/lib/core/thread-function-call/main-thread.js +5 -4
  58. package/runtime/lib/core/thread-function-call/main-thread.js.map +1 -1
  59. package/runtime/lib/core/thread-function-call/return-value.js +6 -5
  60. package/runtime/lib/core/thread-function-call/return-value.js.map +1 -1
  61. package/runtime/lib/element-template/background/commit-hook.js +19 -16
  62. package/runtime/lib/element-template/background/commit-hook.js.map +1 -1
  63. package/runtime/lib/element-template/background/hydration-listener.js +2 -6
  64. package/runtime/lib/element-template/background/hydration-listener.js.map +1 -1
  65. package/runtime/lib/element-template/main-thread-ref-init-value.d.ts +3 -0
  66. package/runtime/lib/element-template/main-thread-ref-init-value.js +38 -0
  67. package/runtime/lib/element-template/main-thread-ref-init-value.js.map +1 -0
  68. package/runtime/lib/element-template/native/index.js +2 -0
  69. package/runtime/lib/element-template/native/index.js.map +1 -1
  70. package/runtime/lib/element-template/native/mts-destroy.js +2 -0
  71. package/runtime/lib/element-template/native/mts-destroy.js.map +1 -1
  72. package/runtime/lib/element-template/native/patch-listener.js +1 -4
  73. package/runtime/lib/element-template/native/patch-listener.js.map +1 -1
  74. package/runtime/lib/element-template/native/reload-background.d.ts +1 -1
  75. package/runtime/lib/element-template/native/reload-background.js +12 -1
  76. package/runtime/lib/element-template/native/reload-background.js.map +1 -1
  77. package/runtime/lib/element-template/native/reload-main-thread.d.ts +6 -0
  78. package/runtime/lib/element-template/native/reload-main-thread.js +18 -2
  79. package/runtime/lib/element-template/native/reload-main-thread.js.map +1 -1
  80. package/runtime/lib/element-template/protocol/lifecycle-constant.d.ts +2 -1
  81. package/runtime/lib/element-template/protocol/lifecycle-constant.js +1 -0
  82. package/runtime/lib/element-template/protocol/lifecycle-constant.js.map +1 -1
  83. package/runtime/lib/element-template/protocol/types.d.ts +0 -2
  84. package/runtime/lib/element-template/protocol/types.js.map +1 -1
  85. package/runtime/lib/shared/index-map.d.ts +4 -1
  86. package/runtime/lib/shared/index-map.js +5 -2
  87. package/runtime/lib/shared/index-map.js.map +1 -1
  88. package/runtime/lib/snapshot/lifecycle/destroy.js +6 -0
  89. package/runtime/lib/snapshot/lifecycle/destroy.js.map +1 -1
  90. package/runtime/lib/snapshot/lifecycle/event/firstScreenSync.d.ts +6 -2
  91. package/runtime/lib/snapshot/lifecycle/event/firstScreenSync.js +21 -18
  92. package/runtime/lib/snapshot/lifecycle/event/firstScreenSync.js.map +1 -1
  93. package/runtime/lib/snapshot/lifecycle/reload.d.ts +9 -2
  94. package/runtime/lib/snapshot/lifecycle/reload.js +29 -8
  95. package/runtime/lib/snapshot/lifecycle/reload.js.map +1 -1
  96. package/runtime/lib/snapshot/list/list.js +3 -2
  97. package/runtime/lib/snapshot/list/list.js.map +1 -1
  98. package/runtime/lib/snapshot/lynx/calledByNative.js +3 -3
  99. package/runtime/lib/snapshot/lynx/calledByNative.js.map +1 -1
  100. package/runtime/lib/snapshot/snapshot/list.js +2 -1
  101. package/runtime/lib/snapshot/snapshot/list.js.map +1 -1
  102. package/runtime/lib/snapshot/snapshot/snapshotInstanceManager.d.ts +4 -2
  103. package/runtime/lib/snapshot/snapshot/snapshotInstanceManager.js +11 -11
  104. package/runtime/lib/snapshot/snapshot/snapshotInstanceManager.js.map +1 -1
  105. package/runtime/lib/snapshot/worklet/call/runOnMainThread.d.ts +1 -0
  106. package/runtime/lib/snapshot/worklet/call/runOnMainThread.js +6 -1
  107. package/runtime/lib/snapshot/worklet/call/runOnMainThread.js.map +1 -1
  108. package/runtime/lib/snapshot/worklet/ctx.d.ts +1 -1
  109. package/runtime/lib/snapshot/worklet/ctx.js +6 -1
  110. package/runtime/lib/snapshot/worklet/ctx.js.map +1 -1
  111. package/runtime/lib/snapshot/worklet/ref/updateInitValue.js +6 -0
  112. package/runtime/lib/snapshot/worklet/ref/updateInitValue.js.map +1 -1
  113. package/runtime/lib/tsconfig.tsbuildinfo +1 -1
  114. package/runtime/lib/worklet-runtime/delayRunOnBackground.js +3 -1
  115. package/runtime/lib/worklet-runtime/delayRunOnBackground.js.map +1 -1
  116. package/runtime/lib/worklet-runtime/jsFunctionLifecycle.js +2 -1
  117. package/runtime/lib/worklet-runtime/jsFunctionLifecycle.js.map +1 -1
  118. package/runtime/lib/worklet-runtime/listeners.js +2 -2
  119. package/runtime/lib/worklet-runtime/listeners.js.map +1 -1
  120. package/runtime/lib/worklet-runtime/mainThreadObject.js +3 -1
  121. package/runtime/lib/worklet-runtime/mainThreadObject.js.map +1 -1
  122. package/runtime/lib/worklet-runtime/runOnMainThread.js +4 -3
  123. package/runtime/lib/worklet-runtime/runOnMainThread.js.map +1 -1
  124. package/runtime/src/core/background-function/exec-map.ts +9 -0
  125. package/runtime/src/core/background-function/run-on-background.ts +14 -16
  126. package/runtime/src/core/card-lifetime.ts +18 -0
  127. package/runtime/src/core/entry-reload.ts +63 -0
  128. package/runtime/src/core/lynx/lazy-bundle.ts +4 -1
  129. package/runtime/src/core/main-thread-ref-id.ts +5 -4
  130. package/runtime/src/core/reload-scoped-event.ts +35 -0
  131. package/runtime/src/core/reload-version.ts +5 -3
  132. package/runtime/src/core/runtime-destroy.ts +11 -0
  133. package/runtime/src/core/thread-function-call/main-thread.ts +4 -4
  134. package/runtime/src/core/thread-function-call/return-value.ts +6 -5
  135. package/runtime/src/element-template/background/commit-hook.ts +20 -17
  136. package/runtime/src/element-template/background/hydration-listener.ts +2 -6
  137. package/runtime/src/element-template/main-thread-ref-init-value.ts +44 -0
  138. package/runtime/src/element-template/native/index.ts +2 -0
  139. package/runtime/src/element-template/native/mts-destroy.ts +3 -0
  140. package/runtime/src/element-template/native/patch-listener.ts +0 -5
  141. package/runtime/src/element-template/native/reload-background.ts +13 -1
  142. package/runtime/src/element-template/native/reload-main-thread.ts +30 -2
  143. package/runtime/src/element-template/protocol/lifecycle-constant.ts +1 -0
  144. package/runtime/src/element-template/protocol/types.ts +0 -2
  145. package/runtime/src/shared/index-map.ts +3 -2
  146. package/runtime/src/snapshot/lifecycle/destroy.ts +7 -0
  147. package/runtime/src/snapshot/lifecycle/event/firstScreenSync.ts +26 -19
  148. package/runtime/src/snapshot/lifecycle/reload.ts +47 -11
  149. package/runtime/src/snapshot/list/list.ts +9 -2
  150. package/runtime/src/snapshot/lynx/calledByNative.ts +3 -4
  151. package/runtime/src/snapshot/snapshot/list.ts +5 -1
  152. package/runtime/src/snapshot/snapshot/snapshotInstanceManager.ts +19 -12
  153. package/runtime/src/snapshot/worklet/call/runOnMainThread.ts +10 -1
  154. package/runtime/src/snapshot/worklet/ctx.ts +10 -1
  155. package/runtime/src/snapshot/worklet/ref/updateInitValue.ts +6 -0
  156. package/runtime/src/worklet-runtime/README.md +13 -0
  157. package/runtime/src/worklet-runtime/delayRunOnBackground.ts +3 -1
  158. package/runtime/src/worklet-runtime/jsFunctionLifecycle.ts +2 -1
  159. package/runtime/src/worklet-runtime/listeners.ts +4 -7
  160. package/runtime/src/worklet-runtime/mainThreadObject.ts +2 -1
  161. package/runtime/src/worklet-runtime/runOnMainThread.ts +4 -3
  162. package/runtime/types/types.d.ts +3 -1
  163. package/testing-library/.turbo/turbo-build.log +7 -7
  164. package/testing-library/src/__tests__/worklet.test.jsx +10 -5
  165. package/transform/.turbo/turbo-build$colon$wasm.log +339 -134
  166. package/transform/__test__/defines.spec.js +107 -0
  167. package/transform/crates/swc_plugin_worklet/definition_imports.rs +97 -0
  168. package/transform/crates/swc_plugin_worklet/lib.rs +7 -6
  169. package/transform/dist/wasm.cjs +1 -1
  170. package/transform/index.d.ts +3 -1
  171. package/transform/src/lib.rs +172 -11
  172. package/transform/swc-plugin-reactlynx/.turbo/turbo-build.log +57 -55
  173. package/transform/swc-plugin-reactlynx/swc_plugin_reactlynx.wasm +0 -0
  174. package/transform/swc-plugin-reactlynx-compat/.turbo/turbo-build.log +66 -274
@@ -1,3 +1,7 @@
1
+ import {
2
+ installElementTemplateRefInitValueListener,
3
+ resetElementTemplateRefInitValueListener,
4
+ } from '../../../../src/element-template/main-thread-ref-init-value.js';
1
5
  import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2
6
 
3
7
  import { WorkletEvents } from '@lynx-js/react/worklet-runtime/bindings';
@@ -262,8 +266,12 @@ describe('ElementTemplate hydration listener', () => {
262
266
  isHydration: true,
263
267
  reloadVersion: getReloadVersion(),
264
268
  delayedRunOnMainThreadData: undefined,
265
- mainThreadRefInitValuePatch: [[1, 'hydrate-init']],
266
269
  });
270
+ expect(dispatchSpy.mock.calls.map(([event]) => event.type)).toEqual([
271
+ ElementTemplateLifecycleConstant.updateMTRefInitValue,
272
+ ElementTemplateLifecycleConstant.update,
273
+ ]);
274
+ expect(dispatchSpy.mock.calls[0]![0].data).toBe(JSON.stringify([[1, 'hydrate-init']]));
267
275
  expect(takeMainThreadRefInitValuePatch()).toEqual([]);
268
276
  });
269
277
 
@@ -287,6 +295,7 @@ describe('ElementTemplate hydration listener', () => {
287
295
  new MainThreadRef('reload-init');
288
296
 
289
297
  envManager.switchToMainThread();
298
+ installElementTemplateRefInitValueListener();
290
299
  installElementTemplatePatchListener();
291
300
  dispatchHydrate([createSerializedTemplate(after.instanceId, '_et_test')]);
292
301
 
@@ -302,6 +311,7 @@ describe('ElementTemplate hydration listener', () => {
302
311
  } finally {
303
312
  envManager.switchToMainThread();
304
313
  resetElementTemplatePatchListener();
314
+ resetElementTemplateRefInitValueListener();
305
315
  globalThis.lynxWorkletImpl = previousWorkletImpl;
306
316
  envManager.switchToBackground();
307
317
  }
@@ -603,7 +613,7 @@ describe('ElementTemplate hydration listener', () => {
603
613
  }
604
614
  });
605
615
 
606
- it('resets commit state when hydrate update serialization throws', () => {
616
+ it.each(['update', 'ref', 'circular-ref', 'dispatch'])('resets hydrate commit state when %s fails', (failure) => {
607
617
  SystemInfo.lynxSdkVersion = '4.0';
608
618
  const serializeError = new Error('hydrate update serialization failed');
609
619
  const oldReportError = lynx.reportError;
@@ -623,6 +633,12 @@ describe('ElementTemplate hydration listener', () => {
623
633
  envManager.switchToBackground();
624
634
  installElementTemplateHydrationListener();
625
635
  const removeEventListener = vi.spyOn(lynx.getCoreContext(), 'removeEventListener');
636
+ const dispatch = vi.spyOn(lynx.getCoreContext(), 'dispatchEvent');
637
+ if (failure === 'dispatch') {
638
+ dispatch.mockImplementationOnce(() => {
639
+ throw serializeError;
640
+ });
641
+ }
626
642
 
627
643
  const backgroundRoot = __root as BackgroundElementTemplateInstance;
628
644
  const throwingValue = {
@@ -630,11 +646,19 @@ describe('ElementTemplate hydration listener', () => {
630
646
  throw serializeError;
631
647
  },
632
648
  } as unknown as SerializableValue;
633
- const after = new BackgroundElementTemplateInstance('_et_serialize_failure', [throwingValue, eventHandler, ref]);
649
+ const after = new BackgroundElementTemplateInstance('_et_serialize_failure', [
650
+ failure === 'update' ? throwingValue : 'after',
651
+ eventHandler,
652
+ ref,
653
+ ]);
634
654
  backgroundRoot.appendChild(after);
635
655
  publishEvent('-1:1:', { type: 'tap' });
636
656
  new ElementTemplateRefProxy(after.instanceId, 2).setNativeProps({ opacity: 1 }).exec();
637
- new MainThreadRef('failed-serialize-init');
657
+ const circularValue: { self?: unknown } = {};
658
+ circularValue.self = circularValue;
659
+ new MainThreadRef(
660
+ failure === 'ref' ? throwingValue : failure === 'circular-ref' ? circularValue : 'failed-serialize-init',
661
+ );
638
662
  void runOnMainThread({ _wkltId: 'failed-serialize-main-thread-function' } as unknown as () => void)();
639
663
 
640
664
  envManager.switchToMainThread();
@@ -646,7 +670,9 @@ describe('ElementTemplate hydration listener', () => {
646
670
  ]);
647
671
 
648
672
  expect(() => envManager.switchToBackground()).not.toThrow();
649
- expect(reportError).toHaveBeenCalledWith(serializeError);
673
+ expect(reportError).toHaveBeenCalledExactlyOnceWith(
674
+ failure === 'circular-ref' ? expect.any(TypeError) : serializeError,
675
+ );
650
676
  expect(globalCommitContext.ops).toEqual([]);
651
677
  expect([...globalCommitContext.nonPayload.removedSubtreesAwaitingTeardown]).toEqual([]);
652
678
  expect(takeMainThreadRefInitValuePatch()).toEqual([]);
@@ -2,6 +2,10 @@
2
2
  // Licensed under the Apache License Version 2.0 that can be found in the
3
3
  // LICENSE file in the root directory of this source tree.
4
4
 
5
+ import {
6
+ installElementTemplateRefInitValueListener,
7
+ resetElementTemplateRefInitValueListener,
8
+ } from '../../../../src/element-template/main-thread-ref-init-value.js';
5
9
  import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
6
10
 
7
11
  import { getReloadVersion, increaseReloadVersion } from '../../../../src/core/reload-version.js';
@@ -1439,7 +1443,7 @@ describe('ElementTemplate patch stream (apply)', () => {
1439
1443
  }
1440
1444
  });
1441
1445
 
1442
- it('applies MainThreadRef init patches before same-payload delayed main-thread tasks', () => {
1446
+ it('applies independent ref initialization before delayed main-thread tasks', () => {
1443
1447
  const callOrder: string[] = [];
1444
1448
  const updateWorkletRefInitValueChanges = vi.fn(() => {
1445
1449
  callOrder.push('init-patch');
@@ -1461,12 +1465,17 @@ describe('ElementTemplate patch stream (apply)', () => {
1461
1465
 
1462
1466
  try {
1463
1467
  envManager.switchToMainThread();
1468
+ installElementTemplateRefInitValueListener();
1464
1469
  installElementTemplatePatchListener();
1465
1470
  mockFlushElementTree.mockImplementationOnce(() => {
1466
1471
  callOrder.push('flushElementTree');
1467
1472
  });
1468
1473
 
1469
1474
  envManager.switchToBackground();
1475
+ lynx.getCoreContext().dispatchEvent({
1476
+ type: ElementTemplateLifecycleConstant.updateMTRefInitValue,
1477
+ data: JSON.stringify([[1, 'same-payload-init']]),
1478
+ });
1470
1479
  dispatchElementTemplateUpdate({
1471
1480
  ops: [],
1472
1481
  flushOptions: {},
@@ -1477,7 +1486,6 @@ describe('ElementTemplate patch stream (apply)', () => {
1477
1486
  resolveId: 10,
1478
1487
  },
1479
1488
  ],
1480
- mainThreadRefInitValuePatch: [[1, 'same-payload-init']],
1481
1489
  });
1482
1490
  envManager.switchToMainThread();
1483
1491
 
@@ -1489,6 +1497,7 @@ describe('ElementTemplate patch stream (apply)', () => {
1489
1497
  'flushElementTree',
1490
1498
  ]);
1491
1499
  } finally {
1500
+ resetElementTemplateRefInitValueListener();
1492
1501
  globalThis.lynxWorkletImpl = previousWorkletImpl;
1493
1502
  }
1494
1503
  });
@@ -1512,10 +1521,15 @@ describe('ElementTemplate patch stream (apply)', () => {
1512
1521
  try {
1513
1522
  increaseReloadVersion();
1514
1523
  envManager.switchToMainThread();
1524
+ installElementTemplateRefInitValueListener();
1515
1525
  installElementTemplatePatchListener();
1516
1526
  mockFlushElementTree.mockClear();
1517
1527
 
1518
1528
  envManager.switchToBackground();
1529
+ lynx.getCoreContext().dispatchEvent({
1530
+ type: ElementTemplateLifecycleConstant.updateMTRefInitValue,
1531
+ data: JSON.stringify([[1, 'stale-init']]),
1532
+ });
1519
1533
  dispatchElementTemplateUpdate({
1520
1534
  ops: [],
1521
1535
  flushOptions: {},
@@ -1527,7 +1541,6 @@ describe('ElementTemplate patch stream (apply)', () => {
1527
1541
  resolveId: 10,
1528
1542
  },
1529
1543
  ],
1530
- mainThreadRefInitValuePatch: [[1, 'stale-init']],
1531
1544
  });
1532
1545
  envManager.switchToMainThread();
1533
1546
 
@@ -1535,6 +1548,7 @@ describe('ElementTemplate patch stream (apply)', () => {
1535
1548
  expect(runRunOnMainThreadTask).not.toHaveBeenCalled();
1536
1549
  expect(mockFlushElementTree).not.toHaveBeenCalled();
1537
1550
  } finally {
1551
+ resetElementTemplateRefInitValueListener();
1538
1552
  globalThis.lynxWorkletImpl = previousWorkletImpl;
1539
1553
  }
1540
1554
  });
@@ -22,6 +22,7 @@ import { applyElementTemplateUpdateCommands } from '../../../../src/element-temp
22
22
  import { ElementTemplateUpdateOps } from '../../../../src/element-template/protocol/opcodes.js';
23
23
  import { renderToElementTemplate } from '../../../../src/element-template/runtime/render/render-direct.js';
24
24
  import { resetElementTemplatePatchListener } from '../../../../src/element-template/native/patch-listener.js';
25
+ import { resetElementTemplateRefInitValueListener } from '../../../../src/element-template/main-thread-ref-init-value.js';
25
26
  import { resetTemplateId } from '../../../../src/element-template/runtime/template/handle.js';
26
27
  import { elementTemplateRegistry } from '../../../../src/element-template/runtime/template/registry.js';
27
28
  import type {
@@ -181,6 +182,7 @@ async function compileAndRender(
181
182
  };
182
183
  } finally {
183
184
  resetElementTemplatePatchListener();
185
+ resetElementTemplateRefInitValueListener();
184
186
  fs.rmSync(tempDir, { recursive: true, force: true });
185
187
  }
186
188
  }
@@ -4,7 +4,7 @@
4
4
 
5
5
  import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
6
6
 
7
- import { WorkletEvents } from '@lynx-js/react/worklet-runtime/bindings';
7
+ import { WorkletEvents, registerWorklet } from '@lynx-js/react/worklet-runtime/bindings';
8
8
  import { options } from 'preact';
9
9
  import { createElement } from 'preact/compat';
10
10
  import { useLayoutEffect, useState } from 'preact/hooks';
@@ -16,11 +16,22 @@ import {
16
16
  } from '../../../../src/element-template/background/commit-hook.js';
17
17
  import { destroyElementTemplateBackgroundRuntime } from '../../../../src/element-template/background/destroy.js';
18
18
  import { clearMtsConfigCacheForTesting } from '../../../../src/core/mts-capability.js';
19
- import { takeDelayedRunOnMainThreadData } from '../../../../src/core/thread-function-call/main-thread.js';
19
+ import {
20
+ delayedRunOnMainThreadData,
21
+ takeDelayedRunOnMainThreadData,
22
+ } from '../../../../src/core/thread-function-call/main-thread.js';
20
23
  import { resetFunctionCallReturnListener } from '../../../../src/core/thread-function-call/return-value.js';
24
+ import {
25
+ installElementTemplatePatchListener,
26
+ resetElementTemplatePatchListener,
27
+ } from '../../../../src/element-template/native/patch-listener.js';
28
+ import { reloadBackground } from '../../../../src/element-template/native/reload-background.js';
29
+ import { reloadMainThread } from '../../../../src/element-template/native/reload-main-thread.js';
21
30
  import { resetElementTemplateBackgroundFunctionRuntime } from '../../../../src/element-template/runtime/template/main-thread-background-function.js';
22
31
  import { ElementTemplateLifecycleConstant } from '../../../../src/element-template/protocol/lifecycle-constant.js';
23
32
  import { parseElementTemplateUpdateEventPayload } from '../../../../src/element-template/protocol/update-event.js';
33
+ import { createElementTemplatePage, setupPage } from '../../../../src/element-template/runtime/page/page.js';
34
+ import { initWorklet } from '../../../../src/worklet-runtime/workletRuntime.js';
24
35
  import { ElementTemplateEnvManager } from '../../test-utils/debug/envManager.js';
25
36
 
26
37
  describe('ElementTemplate runOnMainThread', () => {
@@ -60,6 +71,7 @@ describe('ElementTemplate runOnMainThread', () => {
60
71
  worklet,
61
72
  params: ['hello'],
62
73
  resolveId: 1,
74
+ reloadVersion: 0,
63
75
  }),
64
76
  });
65
77
 
@@ -208,6 +220,7 @@ describe('ElementTemplate runOnMainThread', () => {
208
220
  worklet,
209
221
  params: ['from-layout-effect'],
210
222
  resolveId: 1,
223
+ reloadVersion: 0,
211
224
  }),
212
225
  });
213
226
  expect(takeDelayedRunOnMainThreadData()).toEqual([]);
@@ -262,6 +275,80 @@ describe('ElementTemplate runOnMainThread', () => {
262
275
  expect(removeEventListener).toHaveBeenCalledWith(WorkletEvents.FunctionCallRet, expect.any(Function));
263
276
  });
264
277
 
278
+ it('drops pre-hydration and unmount calls before a reload reuses their return IDs', async () => {
279
+ const oldResult = vi.fn();
280
+ const cleanupResult = vi.fn();
281
+ const cleanup = vi.fn(() => {
282
+ void runOnMainThread({ _wkltId: 'unmount-call' } as unknown as () => string)().then(cleanupResult);
283
+ expect(delayedRunOnMainThreadData.map(data => data.resolveId)).toEqual([1, 2]);
284
+ });
285
+ function App() {
286
+ useLayoutEffect(() => cleanup, []);
287
+ return null;
288
+ }
289
+
290
+ const oldCall = vi.fn(() => 'old-page');
291
+ const unmountCall = vi.fn(() => 'old-page');
292
+ const newCall = vi.fn(() => 'new-page');
293
+ const workletGlobals = {
294
+ lynxWorkletImpl: globalThis.lynxWorkletImpl as unknown,
295
+ runWorklet: globalThis.runWorklet as unknown,
296
+ registerWorklet: globalThis.registerWorklet as unknown,
297
+ registerWorkletInternal: globalThis.registerWorkletInternal as unknown,
298
+ };
299
+ const dispatch = vi.spyOn(lynx.getCoreContext(), 'dispatchEvent');
300
+ try {
301
+ envManager.switchToMainThread();
302
+ initWorklet();
303
+ registerWorklet('main-thread', 'old-call', oldCall);
304
+ registerWorklet('main-thread', 'unmount-call', unmountCall);
305
+ registerWorklet('main-thread', 'new-call', newCall);
306
+ setupPage(createElementTemplatePage());
307
+ root.render(null);
308
+ installElementTemplatePatchListener();
309
+ envManager.switchToBackground();
310
+ root.render(createElement(App));
311
+ void runOnMainThread({ _wkltId: 'old-call' } as unknown as () => string)().then(oldResult);
312
+ expect(delayedRunOnMainThreadData[0]?.resolveId).toBe(1);
313
+
314
+ reloadBackground({});
315
+ expect(cleanup).toHaveBeenCalledOnce();
316
+ expect(delayedRunOnMainThreadData).toEqual([]);
317
+ // The harness shares resolver state between threads. Finish MTS reload
318
+ // before registering the new BTS call, then deliver the real hydration.
319
+ envManager.switchToMainThread(() => reloadMainThread({}, { reloadTemplate: true }));
320
+ let result!: Promise<string>;
321
+ envManager.switchToBackground(() => {
322
+ result = runOnMainThread({ _wkltId: 'new-call' } as unknown as () => string)();
323
+ expect(delayedRunOnMainThreadData[0]?.resolveId).toBe(1);
324
+ });
325
+
326
+ const update = dispatch.mock.calls.find(([event]) =>
327
+ String(event.type) === ElementTemplateLifecycleConstant.update
328
+ )?.[0];
329
+ expect(parseElementTemplateUpdateEventPayload(update?.data)).toMatchObject({
330
+ isHydration: true,
331
+ delayedRunOnMainThreadData: [{ worklet: { _wkltId: 'new-call' }, params: [], resolveId: 1 }],
332
+ });
333
+ envManager.switchToMainThread();
334
+ envManager.switchToBackground();
335
+
336
+ expect(newCall).toHaveBeenCalledExactlyOnceWith();
337
+ expect(oldCall).not.toHaveBeenCalled();
338
+ expect(unmountCall).not.toHaveBeenCalled();
339
+ await expect(result).resolves.toBe('new-page');
340
+ expect(oldResult).not.toHaveBeenCalled();
341
+ expect(cleanupResult).not.toHaveBeenCalled();
342
+ } finally {
343
+ // Do not enqueue another cleanup call while disposing the replacement tree.
344
+ cleanup.mockImplementation(() => {});
345
+ envManager.switchToBackground(() => destroyElementTemplateBackgroundRuntime());
346
+ envManager.switchToMainThread(() => resetElementTemplatePatchListener());
347
+ envManager.switchToBackground();
348
+ Object.assign(globalThis, workletGlobals);
349
+ }
350
+ });
351
+
265
352
  it('throws on the main thread', () => {
266
353
  envManager.switchToMainThread();
267
354
 
@@ -9,6 +9,7 @@ import {
9
9
  type CompiledFixtureTarget,
10
10
  } from './compiledFixtureCompiler.js';
11
11
  import { primeCompiledFixtureTemplates } from './compiledFixtureRegistry.js';
12
+ import type { ElementTemplateEnvManager } from './envManager.js';
12
13
 
13
14
  export interface CompiledFixtureModuleExports {
14
15
  App: (props?: Record<string, unknown>) => JSX.Element;
@@ -33,6 +34,7 @@ export async function loadCompiledFixtureModule<T extends object = CompiledFixtu
33
34
  interface LoadCompiledFixturePairOptions {
34
35
  backgroundTarget?: CompiledFixtureTarget;
35
36
  enableWorkletTransform?: boolean;
37
+ envManager?: ElementTemplateEnvManager;
36
38
  isDynamicComponent?: boolean;
37
39
  mainTarget?: CompiledFixtureTarget;
38
40
  registerMainTemplates?: boolean;
@@ -48,6 +50,7 @@ export async function loadCompiledFixturePair<T extends object = CompiledFixture
48
50
  const {
49
51
  backgroundTarget = 'JS',
50
52
  enableWorkletTransform = false,
53
+ envManager,
51
54
  isDynamicComponent = false,
52
55
  mainTarget = 'LEPUS',
53
56
  registerMainTemplates = true,
@@ -61,6 +64,7 @@ export async function loadCompiledFixturePair<T extends object = CompiledFixture
61
64
  if (registerMainTemplates) {
62
65
  primeCompiledFixtureTemplates(mainArtifact);
63
66
  }
67
+ envManager?.switchToMainThread();
64
68
  const mainModule = await loadCompiledFixtureModule<T>(mainArtifact);
65
69
 
66
70
  const backgroundArtifact = await compileFixtureSource(sourcePath, {
@@ -68,6 +72,7 @@ export async function loadCompiledFixturePair<T extends object = CompiledFixture
68
72
  isDynamicComponent,
69
73
  target: backgroundTarget,
70
74
  });
75
+ envManager?.switchToBackground();
71
76
  const backgroundModule = await loadCompiledFixtureModule<T>(backgroundArtifact);
72
77
 
73
78
  return { backgroundModule, mainModule };
@@ -0,0 +1,114 @@
1
+ /*
2
+ // Copyright 2026 The Lynx Authors. All rights reserved.
3
+ // Licensed under the Apache License Version 2.0 that can be found in the
4
+ // LICENSE file in the root directory of this source tree.
5
+ */
6
+ import { render } from 'preact';
7
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
8
+
9
+ import { registerDestroyTask } from '../../../src/core/runtime-destroy';
10
+ import { __root, setRoot } from '../../../src/root';
11
+ import { completeMainThreadReload } from '../../../src/snapshot/lifecycle/reload';
12
+ import { SnapshotInstance } from '../../../src/snapshot/snapshot/snapshot';
13
+ import { globalEnvManager } from '../utils/envManager';
14
+ import { elementTree } from '../utils/nativeMethod';
15
+
16
+ const supportsReEvalKey = Symbol.for('__LYNX_ENTRY_SUPPORTS_RE_EVAL__');
17
+ const reloaderKey = Symbol.for('__LYNX_MAIN_THREAD_ENTRY_RELOADER__');
18
+ const completerKey = Symbol.for('__LYNX_MAIN_THREAD_RELOAD_COMPLETER__');
19
+
20
+ function App({ label = 'app' }) {
21
+ return (
22
+ <view>
23
+ <text>{label}</text>
24
+ </view>
25
+ );
26
+ }
27
+
28
+ describe('re-evaluating the main-thread entry on reload', () => {
29
+ beforeEach(() => {
30
+ globalEnvManager.resetEnv();
31
+ vi.stubGlobal('__EXPERIMENTAL_RE_EVAL_JS_ON_RELOAD__', true);
32
+ globalEnvManager.switchToMainThread();
33
+ lynx[supportsReEvalKey] = true;
34
+ });
35
+
36
+ afterEach(() => {
37
+ delete lynx[supportsReEvalKey];
38
+ delete lynx[reloaderKey];
39
+ delete lynx[completerKey];
40
+ vi.restoreAllMocks();
41
+ vi.unstubAllGlobals();
42
+ globalEnvManager.resetEnv();
43
+ elementTree.clear();
44
+ });
45
+
46
+ it('retires the entry, evaluates it again and lets it hydrate the existing tree', () => {
47
+ __root.__jsx = <App label='old' />;
48
+ renderPage({ kept: 'yes', count: 1 });
49
+ const page = __root.__element_root;
50
+ const events = [];
51
+ registerDestroyTask(() => events.push('retire'));
52
+ lynx[reloaderKey] = () => {
53
+ events.push('evaluate');
54
+ // What evaluating the entry does: reset init data, install its completer, render into a fresh root.
55
+ lynx.__initData = {};
56
+ lynx[completerKey] = completeMainThreadReload;
57
+ setRoot(new SnapshotInstance('root'));
58
+ __root.__jsx = <App label='new' />;
59
+ };
60
+ const createText = vi.spyOn(globalThis, '__CreateText');
61
+
62
+ updatePage({ count: 2 }, { reloadTemplate: true });
63
+
64
+ expect(events).toEqual(['retire', 'evaluate']);
65
+ expect(lynx.__initData).toEqual({ kept: 'yes', count: 2 });
66
+ expect(__root.__element_root).toBe(page);
67
+ expect(createText).not.toHaveBeenCalled();
68
+ expect(JSON.stringify(page)).toContain('new');
69
+ expect(JSON.stringify(page)).not.toContain('old');
70
+ });
71
+ });
72
+
73
+ describe('re-evaluating the background entry on reload', () => {
74
+ let reloadCard;
75
+
76
+ beforeEach(() => {
77
+ globalEnvManager.resetEnv();
78
+ vi.stubGlobal('__EXPERIMENTAL_RE_EVAL_JS_ON_RELOAD__', true);
79
+ globalEnvManager.switchToBackground();
80
+ lynx[supportsReEvalKey] = true;
81
+ reloadCard = vi.fn();
82
+ lynx.getApp().reloadCard = reloadCard;
83
+ lynx.__globalProps = {};
84
+ __root.__jsx = <App />;
85
+ render(<App />, __root);
86
+ });
87
+
88
+ afterEach(() => {
89
+ delete lynx[supportsReEvalKey];
90
+ delete lynx.getApp().reloadCard;
91
+ vi.unstubAllGlobals();
92
+ globalEnvManager.resetEnv();
93
+ elementTree.clear();
94
+ });
95
+
96
+ it('retires the entry, then asks the client to evaluate it with the merged data', () => {
97
+ lynx.__initData = { kept: 'yes', count: 1 };
98
+ const destroy = vi.spyOn(lynx.getApp(), 'callDestroyLifetimeFun');
99
+
100
+ lynx.getApp().onAppReload({ count: 2 }, { source: 'test' });
101
+
102
+ expect(reloadCard).toHaveBeenCalledWith({ kept: 'yes', count: 2 }, { source: 'test' });
103
+ expect(destroy.mock.invocationCallOrder[0]).toBeLessThan(reloadCard.mock.invocationCallOrder[0]);
104
+ expect(__root.childNodes).toEqual([]);
105
+ });
106
+
107
+ it('does not render the old tree again from a globalProps update queued before the reload', async () => {
108
+ lynx.getApp().updateGlobalProps({ theme: 'dark' });
109
+ lynx.getApp().onAppReload({});
110
+ await Promise.resolve();
111
+
112
+ expect(__root.childNodes).toEqual([]);
113
+ });
114
+ });
@@ -0,0 +1,169 @@
1
+ // Copyright 2026 The Lynx Authors. All rights reserved.
2
+ // Licensed under the Apache License Version 2.0 that can be found in the
3
+ // LICENSE file in the root directory of this source tree.
4
+ import { useLayoutEffect } from 'preact/hooks';
5
+ import { expect, it, vi } from 'vitest';
6
+
7
+ import { createBackgroundFunctionHandle } from '../../../src/core/background-function/handle.js';
8
+ import {
9
+ resetBackgroundFunctionRuntime,
10
+ runOnBackground,
11
+ } from '../../../src/core/background-function/run-on-background.js';
12
+ import { resetFunctionCallReturnListener } from '../../../src/core/thread-function-call/return-value.js';
13
+ import { root } from '../../../src/lynx-api.js';
14
+ import { __root } from '../../../src/root.js';
15
+ import { setupPage } from '../../../src/snapshot/index.js';
16
+ import { destroyBackground } from '../../../src/snapshot/lifecycle/destroy.js';
17
+ import { globalCommitTaskMap } from '../../../src/snapshot/lifecycle/patch/commit.js';
18
+ import { onPostWorkletCtx } from '../../../src/snapshot/worklet/ctx.js';
19
+ import { clearConfigCacheForTesting } from '../../../src/snapshot/worklet/functionality.js';
20
+ import { registerWorklet } from '../../../src/worklet-runtime/bindings/index.js';
21
+ import { WorkletEvents } from '../../../src/worklet-runtime/bindings/events.js';
22
+ import { initWorklet } from '../../../src/worklet-runtime/workletRuntime.js';
23
+ import { globalEnvManager } from '../utils/envManager.js';
24
+ import { elementTree } from '../utils/nativeMethod.js';
25
+
26
+ it('retires old and unmount background functions across ordinary reload and hydrates working replacements', async () => {
27
+ const oldCall = vi.fn(() => 'old-page');
28
+ const cleanupCall = vi.fn(() => 'unmounted-page');
29
+ const newCall = vi.fn(() => 'new-page');
30
+ const oldResult = vi.fn();
31
+ const oldRequestResult = vi.fn();
32
+ const newResult = vi.fn(value => value);
33
+ let generation = 0;
34
+ let cleanupCtx;
35
+ const cleanup = vi.fn(() => {
36
+ cleanupCtx = onPostWorkletCtx({
37
+ _wkltId: 'cleanup',
38
+ _jsFn: { callback: createBackgroundFunctionHandle(cleanupCall) },
39
+ });
40
+ });
41
+ function App() {
42
+ useLayoutEffect(() => cleanup, []);
43
+ const ctx = {
44
+ _wkltId: 'call-background',
45
+ _jsFn: {
46
+ callback: __MAIN_THREAD__
47
+ ? { _isFirstScreen: true }
48
+ : createBackgroundFunctionHandle(generation === 0 ? oldCall : newCall),
49
+ },
50
+ };
51
+ return <view main-thread:bindtap={ctx} />;
52
+ }
53
+
54
+ function hydratePage() {
55
+ globalEnvManager.switchToBackground();
56
+ lynx.getNativeApp().callLepusMethod.mockClear();
57
+ lynx.getApp().OnLifecycleEvent(...__OnLifecycleEvent.mock.lastCall);
58
+ const [method, patch, complete] = lynx.getNativeApp().callLepusMethod.mock.lastCall;
59
+ expect(patch.patchOptions.isHydration).toBe(true);
60
+ globalEnvManager.switchToMainThread();
61
+ globalThis[method](patch);
62
+ globalEnvManager.switchToBackground();
63
+ complete();
64
+ globalEnvManager.switchToMainThread();
65
+ return __root.__element_root.children[0].props.event['bindEvent:tap'].value;
66
+ }
67
+
68
+ const workletGlobals = {
69
+ lynxWorkletImpl: globalThis.lynxWorkletImpl,
70
+ runWorklet: globalThis.runWorklet,
71
+ registerWorklet: globalThis.registerWorklet,
72
+ registerWorkletInternal: globalThis.registerWorkletInternal,
73
+ };
74
+ const sdkVersion = SystemInfo.lynxSdkVersion;
75
+ globalEnvManager.resetEnv();
76
+ SystemInfo.lynxSdkVersion = '4.0';
77
+ clearConfigCacheForTesting();
78
+ try {
79
+ initWorklet();
80
+ registerWorklet('main-thread', 'call-background', function(value) {
81
+ return runOnBackground(this._jsFn.callback)(value);
82
+ });
83
+ setupPage(__CreatePage('0', 0));
84
+ __root.__jsx = <App />;
85
+ renderPage({});
86
+ globalEnvManager.switchToBackground();
87
+ root.render(<App />);
88
+ const oldCtx = hydratePage();
89
+ const context = lynx.getCoreContext();
90
+ const jsContext = lynx.getJSContext();
91
+ // Hold a real old return and request at the transport boundary. Replay the
92
+ // original envelopes after reload; do not manufacture their version/IDs.
93
+ context.dispatchEvent.mockImplementationOnce(() => {});
94
+ void runWorklet(oldCtx, ['before']).then(oldResult);
95
+ const oldReturn = context.dispatchEvent.mock.lastCall[0];
96
+ expect(oldReturn.type).toBe(WorkletEvents.FunctionCallRet);
97
+ expect(oldCall).toHaveBeenCalledExactlyOnceWith('before');
98
+ jsContext.dispatchEvent.mockImplementationOnce(() => {});
99
+ void runWorklet(oldCtx, ['delayed-request']).then(oldRequestResult);
100
+ const oldRequest = jsContext.dispatchEvent.mock.lastCall[0];
101
+ expect(oldRequest.type).toBe(WorkletEvents.runOnBackground);
102
+
103
+ globalEnvManager.switchToBackground();
104
+ const oldListeners = context.addEventListener.mock.calls.filter(([type]) =>
105
+ type === WorkletEvents.runOnBackground || type === WorkletEvents.releaseBackgroundWorkletCtx
106
+ );
107
+ expect(oldListeners).toHaveLength(2);
108
+ context.removeEventListener.mockClear();
109
+ generation = 1;
110
+ lynx.getApp().onAppReload({});
111
+ expect(cleanup).toHaveBeenCalledOnce();
112
+ // The test harness shares resolver state across threads: finish MTS reload
113
+ // before dispatching new calls, then apply the actual hydration patch.
114
+ globalEnvManager.switchToMainThread();
115
+ updatePage({}, { reloadTemplate: true });
116
+ const newCtx = hydratePage();
117
+ context.dispatchEvent.mockImplementationOnce(() => {});
118
+ const result = runWorklet(newCtx, ['after']).then(newResult);
119
+ const newReturn = context.dispatchEvent.mock.lastCall[0];
120
+ expect(JSON.parse(newReturn.data).resolveId).toBe(JSON.parse(oldReturn.data).resolveId);
121
+ expect(newCall).toHaveBeenCalledExactlyOnceWith('after');
122
+ jsContext.dispatchEvent(oldRequest);
123
+ globalEnvManager.switchToBackground();
124
+ context.dispatchEvent(oldReturn);
125
+ await Promise.resolve();
126
+ expect(newResult).not.toHaveBeenCalled();
127
+ expect(oldResult).not.toHaveBeenCalled();
128
+ expect(oldRequestResult).not.toHaveBeenCalled();
129
+ context.dispatchEvent(newReturn);
130
+ await expect(result).resolves.toBe('new-page');
131
+
132
+ globalEnvManager.switchToMainThread();
133
+ await expect(runWorklet(oldCtx, ['retired'])).rejects.toThrow('runOnBackground: JS function not found');
134
+ // A thrown native listener leaves this harness on the receiving thread.
135
+ globalEnvManager.switchToMainThread();
136
+ await expect(
137
+ runOnBackground({
138
+ _jsFnId: cleanupCtx._jsFn.callback._jsFnId,
139
+ _execId: cleanupCtx._execId,
140
+ })(),
141
+ ).rejects.toThrow('runOnBackground: JS function not found');
142
+ expect.soft(oldCall).toHaveBeenCalledOnce();
143
+ expect.soft(cleanupCall).not.toHaveBeenCalled();
144
+ for (const [type, listener] of oldListeners) {
145
+ expect.soft(context.removeEventListener).toHaveBeenCalledWith(type, listener);
146
+ }
147
+ globalEnvManager.switchToMainThread();
148
+ // Releasing retired contexts must not remove a replacement page's context.
149
+ lynx.getJSContext().dispatchEvent({
150
+ type: WorkletEvents.releaseBackgroundWorkletCtx,
151
+ data: [oldCtx._execId, cleanupCtx._execId],
152
+ });
153
+ await expect(runWorklet(newCtx, ['after-release'])).resolves.toBe('new-page');
154
+ expect(newCall).toHaveBeenCalledTimes(2);
155
+ } finally {
156
+ cleanup.mockImplementation(() => {});
157
+ globalEnvManager.switchToBackground();
158
+ destroyBackground();
159
+ resetBackgroundFunctionRuntime();
160
+ resetFunctionCallReturnListener();
161
+ globalCommitTaskMap.clear();
162
+ globalEnvManager.resetEnv();
163
+ elementTree.clear();
164
+ Object.assign(globalThis, workletGlobals);
165
+ SystemInfo.lynxSdkVersion = sdkVersion;
166
+ clearConfigCacheForTesting();
167
+ vi.restoreAllMocks();
168
+ }
169
+ });