@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
@@ -3,6 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
3
3
  import { ElementTemplateEnvManager } from '../test-utils/debug/envManager.js';
4
4
 
5
5
  const envManager = new ElementTemplateEnvManager();
6
+ const installElementTemplateRefInitValueListener = vi.fn();
6
7
 
7
8
  describe('element-template native index wiring', () => {
8
9
  const originalNodeEnv = process.env['NODE_ENV'];
@@ -10,6 +11,10 @@ describe('element-template native index wiring', () => {
10
11
  beforeEach(() => {
11
12
  vi.resetModules();
12
13
  vi.clearAllMocks();
14
+ vi.doMock('../../../src/element-template/main-thread-ref-init-value.js', async (importOriginal) => ({
15
+ ...await importOriginal<typeof import('../../../src/element-template/main-thread-ref-init-value.js')>(),
16
+ installElementTemplateRefInitValueListener,
17
+ }));
13
18
  globalThis.__ALOG_ELEMENT_API__ = undefined;
14
19
  });
15
20
 
@@ -17,6 +22,7 @@ describe('element-template native index wiring', () => {
17
22
  process.env['NODE_ENV'] = originalNodeEnv;
18
23
  globalThis.__ALOG_ELEMENT_API__ = undefined;
19
24
  vi.resetModules();
25
+ vi.doUnmock('../../../src/element-template/main-thread-ref-init-value.js');
20
26
  vi.doUnmock('../../../src/element-template/native/main-thread-api.js');
21
27
  vi.doUnmock('../../../src/element-template/native/patch-listener.js');
22
28
  vi.doUnmock('../../../src/element-template/native/mts-destroy.js');
@@ -98,6 +104,7 @@ describe('element-template native index wiring', () => {
98
104
 
99
105
  expect(initElementTemplatePAPICallAlog).toHaveBeenCalledTimes(1);
100
106
  expect(injectCalledByNative).toHaveBeenCalledTimes(1);
107
+ expect(installElementTemplateRefInitValueListener).toHaveBeenCalledTimes(1);
101
108
  expect(installElementTemplatePatchListener).toHaveBeenCalledTimes(1);
102
109
  expect(installOnMtsDestruction).toHaveBeenCalledTimes(1);
103
110
  expect(initProfileHook).toHaveBeenCalledTimes(1);
@@ -218,6 +225,7 @@ describe('element-template native index wiring', () => {
218
225
  );
219
226
 
220
227
  expect(injectCalledByNative).not.toHaveBeenCalled();
228
+ expect(installElementTemplateRefInitValueListener).not.toHaveBeenCalled();
221
229
  expect(installElementTemplatePatchListener).not.toHaveBeenCalled();
222
230
  expect(installOnMtsDestruction).not.toHaveBeenCalled();
223
231
  });
@@ -0,0 +1,100 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2
+
3
+ import { MainThreadRef, clearMainThreadRefLastIdForTesting } from '../../../src/core/main-thread-ref.js';
4
+ import { takeMainThreadRefInitValuePatch } from '../../../src/core/main-thread-ref-init-value.js';
5
+ import { clearMtsConfigCacheForTesting } from '../../../src/core/mts-capability.js';
6
+ import { increaseReloadVersion } from '../../../src/core/reload-version.js';
7
+ import {
8
+ installElementTemplateRefInitValueListener,
9
+ resetElementTemplateRefInitValueListener,
10
+ sendMTRefInitValueToMainThread,
11
+ } from '../../../src/element-template/main-thread-ref-init-value.js';
12
+ import {
13
+ installElementTemplatePatchListener,
14
+ resetElementTemplatePatchListener,
15
+ } from '../../../src/element-template/native/patch-listener.js';
16
+ import { destroyElementTemplateMainThreadRuntime } from '../../../src/element-template/native/mts-destroy.js';
17
+ import { ElementTemplateLifecycleConstant } from '../../../src/element-template/protocol/lifecycle-constant.js';
18
+ import { getFromWorkletRefMap, initWorkletRef } from '../../../src/worklet-runtime/workletRef.js';
19
+ import { ElementTemplateEnvManager } from '../test-utils/debug/envManager.js';
20
+
21
+ describe('ElementTemplate ref initialization event', () => {
22
+ const env = new ElementTemplateEnvManager();
23
+ let previousImpl: typeof globalThis.lynxWorkletImpl;
24
+ let previousSdkVersion: string;
25
+
26
+ beforeEach(() => {
27
+ env.resetEnv('background');
28
+ previousSdkVersion = SystemInfo.lynxSdkVersion;
29
+ SystemInfo.lynxSdkVersion = '4.0';
30
+ clearMtsConfigCacheForTesting();
31
+ clearMainThreadRefLastIdForTesting();
32
+ takeMainThreadRefInitValuePatch();
33
+ previousImpl = globalThis.lynxWorkletImpl;
34
+ globalThis.lynxWorkletImpl = { ...previousImpl, _refImpl: initWorkletRef() };
35
+ });
36
+
37
+ afterEach(() => {
38
+ env.switchToMainThread();
39
+ resetElementTemplateRefInitValueListener();
40
+ globalThis.lynxWorkletImpl = previousImpl;
41
+ SystemInfo.lynxSdkVersion = previousSdkVersion;
42
+ clearMtsConfigCacheForTesting();
43
+ takeMainThreadRefInitValuePatch();
44
+ vi.unstubAllGlobals();
45
+ });
46
+
47
+ it.each([true, false, undefined])('initializes a retained ref after reload (alog: %s)', (alog) => {
48
+ vi.stubGlobal('__ALOG__', alog);
49
+ const log = vi.spyOn(console, 'alog');
50
+ env.switchToMainThread();
51
+ installElementTemplateRefInitValueListener();
52
+ env.switchToBackground();
53
+ const ref = new MainThreadRef(233);
54
+ const handle = JSON.parse(JSON.stringify(ref));
55
+ sendMTRefInitValueToMainThread();
56
+ // Advance after BTS sent the event, before MTS receives it.
57
+ increaseReloadVersion();
58
+ env.switchToMainThread();
59
+ expect(getFromWorkletRefMap(handle)).toMatchObject({ current: 233 });
60
+ if (alog) {
61
+ expect(log).toHaveBeenCalledWith('[ReactLynxDebug] ElementTemplate BTS -> MTS sendMTRefInitValue:\n[[1,233]]');
62
+ expect(log).toHaveBeenCalledWith('[ReactLynxDebug] ElementTemplate MTS updateMTRefInitValue:\n[[1,233]]');
63
+ } else {
64
+ expect(log.mock.calls.some(([message]) => String(message).includes('MTRefInitValue'))).toBe(false);
65
+ }
66
+ });
67
+
68
+ it('does not send an empty queue or resend initialization', () => {
69
+ const dispatch = vi.spyOn(lynx.getCoreContext(), 'dispatchEvent');
70
+ sendMTRefInitValueToMainThread();
71
+ expect(dispatch).not.toHaveBeenCalled();
72
+ new MainThreadRef('once');
73
+ sendMTRefInitValueToMainThread();
74
+ sendMTRefInitValueToMainThread();
75
+ expect(dispatch).toHaveBeenCalledExactlyOnceWith({
76
+ type: ElementTemplateLifecycleConstant.updateMTRefInitValue,
77
+ data: JSON.stringify([[1, 'once']]),
78
+ });
79
+ });
80
+
81
+ it('keeps its receiver when the UI listener resets and removes it on destruction', () => {
82
+ env.switchToMainThread();
83
+ const apply = vi.spyOn(globalThis.lynxWorkletImpl._refImpl, 'updateWorkletRefInitValueChanges');
84
+ installElementTemplateRefInitValueListener();
85
+ installElementTemplateRefInitValueListener();
86
+ installElementTemplatePatchListener();
87
+ resetElementTemplatePatchListener();
88
+ env.switchToBackground();
89
+ new MainThreadRef('first');
90
+ sendMTRefInitValueToMainThread();
91
+ env.switchToMainThread();
92
+ expect(apply).toHaveBeenCalledOnce();
93
+ destroyElementTemplateMainThreadRuntime();
94
+ env.switchToBackground();
95
+ new MainThreadRef('after-destroy');
96
+ sendMTRefInitValueToMainThread();
97
+ env.switchToMainThread();
98
+ expect(apply).toHaveBeenCalledOnce();
99
+ });
100
+ });
@@ -0,0 +1,101 @@
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 { afterEach, describe, expect, it, vi } from 'vitest';
5
+
6
+ import {
7
+ registerBackgroundFunctionCtx,
8
+ runOnBackground,
9
+ } from '../../../src/core/background-function/run-on-background.js';
10
+ import { destroyElementTemplateBackgroundRuntime } from '../../../src/element-template/background/destroy.js';
11
+ import { getReloadVersion } from '../../../src/core/reload-version.js';
12
+ import { WorkletEvents } from '../../../src/worklet-runtime/bindings/events.js';
13
+ import { reloadMainThread } from '../../../src/element-template/native/reload-main-thread.js';
14
+ import { createElementTemplatePage, setupPage } from '../../../src/element-template/runtime/page/page.js';
15
+ import {
16
+ __etAttrPlanMap,
17
+ adaptMTRefAttrSlot,
18
+ clearEtAttrPlanMap,
19
+ } from '../../../src/element-template/runtime/template/attr-slot-plan.js';
20
+ import {
21
+ initializeMainThreadDynamicAttrSlots,
22
+ attachMainThreadDynamicAttrRefsForSubtree,
23
+ } from '../../../src/element-template/runtime/template/main-thread-dynamic-attr-state.js';
24
+ import { reloadBackground } from '../../../src/element-template/native/reload-background.js';
25
+ import { resetElementTemplateMainThreadBackgroundFunctionRuntime } from '../../../src/element-template/runtime/template/main-thread-background-function.js';
26
+ import { ElementTemplateEnvManager } from '../test-utils/debug/envManager.js';
27
+
28
+ // ET ordinary reload retains the entry, but clears its background function table.
29
+ // Queue a real MTS request, reload before BTS delivery, then deliver the request.
30
+ describe('ElementTemplate dual-thread communication delivery across ordinary reload', () => {
31
+ const env = new ElementTemplateEnvManager();
32
+ afterEach(() => {
33
+ env.switchToMainThread(() => resetElementTemplateMainThreadBackgroundFunctionRuntime());
34
+ env.switchToBackground(() => destroyElementTemplateBackgroundRuntime());
35
+ clearEtAttrPlanMap();
36
+ vi.unstubAllGlobals();
37
+ });
38
+ it('stamps calls from old main-thread ref cleanup with the old version', () => {
39
+ env.resetEnv('main');
40
+ SystemInfo.lynxSdkVersion = '4.0';
41
+ const page = createElementTemplatePage();
42
+ setupPage(page);
43
+ const oldVersion = getReloadVersion();
44
+ const dispatch = vi.spyOn(lynx.getJSContext(), 'dispatchEvent');
45
+ const cleanup = vi.fn(() => {
46
+ void runOnBackground(Object.assign(() => {}, { _execId: 2, _jsFnId: 1 }))();
47
+ });
48
+ vi.stubGlobal('runWorklet', vi.fn(() => cleanup));
49
+ __etAttrPlanMap._reload_dual_thread = [0, adaptMTRefAttrSlot];
50
+ initializeMainThreadDynamicAttrSlots(-1, '_reload_dual_thread', [
51
+ { type: 'main-thread-ref', value: { _wkltId: 'ref-cleanup' } },
52
+ ]);
53
+ attachMainThreadDynamicAttrRefsForSubtree([{ uid: -1, ref: page }]);
54
+
55
+ reloadMainThread({}, { reloadTemplate: true });
56
+
57
+ expect(cleanup).toHaveBeenCalledOnce();
58
+ const request = dispatch.mock.calls.find(([event]) => event.type === WorkletEvents.runOnBackground)![0];
59
+ expect(JSON.parse(request.data as string).reloadVersion).toBe(oldVersion);
60
+ expect(getReloadVersion()).toBe(oldVersion + 1);
61
+ });
62
+
63
+ it.each([1, 2])('drops a stale request from %i retired contexts before looking up a function', async (ctxCount) => {
64
+ env.resetEnv('background');
65
+ SystemInfo.lynxSdkVersion = '4.0';
66
+ const oldFn = vi.fn();
67
+ let oldCtx;
68
+ for (let i = 0; i < ctxCount; i++) {
69
+ oldCtx = { _wkltId: 'ctx', _c: { fn: { _jsFnId: 1, _fn: oldFn } }, _execId: 0 };
70
+ registerBackgroundFunctionCtx(oldCtx);
71
+ }
72
+ const oldId = oldCtx!._execId;
73
+ env.switchToMainThread();
74
+ void runOnBackground(Object.assign(() => {}, { _execId: oldId, _jsFnId: 1 }))();
75
+
76
+ // The harness shares core modules across threads. Retire MTS resolvers first,
77
+ // as its ordinary reload does, before exercising the real BTS reload below.
78
+ resetElementTemplateMainThreadBackgroundFunctionRuntime();
79
+
80
+ const freshFn = vi.fn(() => 'fresh');
81
+ const freshCtx = { _wkltId: 'ctx', _c: { fn: { _jsFnId: 1, _fn: freshFn } }, _execId: 0 };
82
+ expect(() =>
83
+ env.switchToBackground(() => {
84
+ reloadBackground({});
85
+ registerBackgroundFunctionCtx(freshCtx);
86
+ })
87
+ ).not.toThrow();
88
+ expect(freshCtx._execId).toBeGreaterThan(oldId);
89
+ // A stale request must be dropped before looking up its retired context.
90
+ expect(freshFn).not.toHaveBeenCalled();
91
+ expect(oldFn).not.toHaveBeenCalled();
92
+
93
+ env.switchToMainThread();
94
+ lynx.getJSContext().dispatchEvent({ type: WorkletEvents.releaseBackgroundWorkletCtx, data: [oldId] });
95
+ const result = runOnBackground(Object.assign(() => {}, { _execId: freshCtx._execId, _jsFnId: 1 }))();
96
+ env.switchToBackground();
97
+ env.switchToMainThread();
98
+ await expect(result).resolves.toBe('fresh');
99
+ expect(freshFn).toHaveBeenCalledOnce();
100
+ });
101
+ });
@@ -7,7 +7,8 @@ import { installElementTemplateHydrationListener } from '../../../src/element-te
7
7
  import { BackgroundPageRootInstance } from '../../../src/element-template/background/instance.js';
8
8
  import { profileEnd, profileStart } from '../../../src/element-template/debug/profile.js';
9
9
  import { reloadBackground } from '../../../src/element-template/native/reload-background.js';
10
- import { reloadMainThread } from '../../../src/element-template/native/reload-main-thread.js';
10
+ import { onMtsDestruction } from '../../../src/element-template/native/mts-destroy.js';
11
+ import { completeMainThreadReload, reloadMainThread } from '../../../src/element-template/native/reload-main-thread.js';
11
12
  import { resetEventStateForRuntime } from '../../../src/element-template/prop-adapters/event.js';
12
13
  import { destroyAllElementTemplateListStates } from '../../../src/element-template/runtime/list/list.js';
13
14
  import { setupPage } from '../../../src/element-template/runtime/page/page.js';
@@ -110,6 +111,10 @@ vi.mock('../../../src/element-template/background/instance.js', () => {
110
111
  };
111
112
  });
112
113
 
114
+ vi.mock('../../../src/element-template/native/mts-destroy.js', () => ({
115
+ onMtsDestruction: vi.fn(),
116
+ }));
117
+
113
118
  vi.mock('../../../src/element-template/debug/profile.js', () => ({
114
119
  profileEnd: vi.fn(),
115
120
  profileStart: vi.fn(),
@@ -295,6 +300,50 @@ describe('ElementTemplate reloadMainThread', () => {
295
300
  }
296
301
  });
297
302
 
303
+ it('evaluates the entry again and lets it render into the retained page', () => {
304
+ vi.mocked(mockRender).mockReturnValue({ pageAttributes: null, rootRefs: [], rootSubtreeHandles: [] });
305
+ const supportsReEvalKey = Symbol.for('__LYNX_ENTRY_SUPPORTS_RE_EVAL__');
306
+ const reloaderKey = Symbol.for('__LYNX_MAIN_THREAD_ENTRY_RELOADER__');
307
+ const completerKey = Symbol.for('__LYNX_MAIN_THREAD_RELOAD_COMPLETER__');
308
+ const host = lynx as unknown as Record<symbol, unknown>;
309
+ vi.stubGlobal('__EXPERIMENTAL_RE_EVAL_JS_ON_RELOAD__', true);
310
+ const page = mockedState.page;
311
+ const newJsx = { type: 'NewApp' };
312
+ const events: string[] = [];
313
+ lynx.__initData = { kept: 'yes', count: 1 };
314
+ vi.mocked(onMtsDestruction).mockImplementation(() => events.push('retire'));
315
+ vi.mocked(increaseReloadVersion).mockImplementationOnce(() => {
316
+ events.push('advance-version');
317
+ return 2;
318
+ });
319
+ host[supportsReEvalKey] = true;
320
+ host[reloaderKey] = () => {
321
+ events.push('evaluate');
322
+ // What evaluating the entry does: reset init data, install its completer, render into a fresh root.
323
+ lynx.__initData = {};
324
+ host[completerKey] = completeMainThreadReload;
325
+ setRoot({ __jsx: newJsx });
326
+ };
327
+ const options = { reloadTemplate: true };
328
+
329
+ try {
330
+ reloadMainThread({ count: 2 }, options);
331
+ } finally {
332
+ delete host[supportsReEvalKey];
333
+ delete host[reloaderKey];
334
+ delete host[completerKey];
335
+ }
336
+
337
+ expect(events).toEqual(['retire', 'advance-version', 'evaluate']);
338
+ expect(increaseReloadVersion).toHaveBeenCalledOnce();
339
+ expect(lynx.__initData).toEqual({ kept: 'yes', count: 2 });
340
+ expect(setupPage).toHaveBeenLastCalledWith(page);
341
+ expect(mockRender).toHaveBeenCalledWith(newJsx, undefined);
342
+ expect(__FlushElementTree).toHaveBeenLastCalledWith(undefined, options);
343
+ // The retained page is not rebuilt by the previous entry.
344
+ expect(elementTemplateRegistry.clear).not.toHaveBeenCalled();
345
+ });
346
+
298
347
  it('rebuilds when the physical page has no root slot', () => {
299
348
  mockedState.root = { __jsx: null };
300
349
  vi.mocked(mockRender).mockReturnValue({
@@ -222,64 +222,121 @@ describe('ElementTemplate commit hook', () => {
222
222
  expect(takeDelayedRunOnMainThreadData()).toEqual([]);
223
223
  });
224
224
 
225
- it('dispatches MainThreadRef init-value patch after commit when hydrated', () => {
226
- markElementTemplateHydrated();
225
+ it.each([false, true])('dispatches ref initialization separately (hydrated: %s)', (hydrated) => {
226
+ if (hydrated) markElementTemplateHydrated();
227
+ const dispatch = vi.spyOn(lynx.getCoreContext(), 'dispatchEvent');
227
228
  new MainThreadRef('commit-init');
228
229
 
229
230
  options.__c?.({} as unknown as object, []);
230
231
 
232
+ expect(dispatch).toHaveBeenCalledExactlyOnceWith({
233
+ type: ElementTemplateLifecycleConstant.updateMTRefInitValue,
234
+ data: JSON.stringify([[1, 'commit-init']]),
235
+ });
236
+ expect(takeMainThreadRefInitValuePatch()).toEqual([]);
231
237
  envManager.switchToMainThread();
232
- expect(updateEvents).toEqual([
233
- {
234
- ops: [],
235
- flushOptions: { emptyPatch: true },
236
- flowIds: undefined,
237
- reloadVersion: getReloadVersion(),
238
- mainThreadRefInitValuePatch: [[1, 'commit-init']],
239
- },
240
- ]);
238
+ expect(updateEvents).toEqual([]);
241
239
  envManager.switchToBackground();
242
- expect(takeMainThreadRefInitValuePatch()).toEqual([]);
243
240
  });
244
241
 
245
- it('cleans commit state when update serialization throws', () => {
246
- vi.useFakeTimers();
247
- globalThis.__ALOG__ = false;
248
- const serializeError = new Error('update serialization failed');
249
- const throwingValue = {
250
- toJSON() {
251
- throw serializeError;
252
- },
253
- } as unknown as string;
242
+ it.each(['update', 'ref', 'circular-ref', 'dispatch'])(
243
+ 'cleans commit state when %s fails and allows the next commit',
244
+ (failure) => {
245
+ vi.useFakeTimers();
246
+ globalThis.__ALOG__ = false;
247
+ const serializeError = new Error('update serialization failed');
248
+ const dispatch = vi.spyOn(lynx.getCoreContext(), 'dispatchEvent');
249
+ const throwingValue = {
250
+ toJSON() {
251
+ throw serializeError;
252
+ },
253
+ } as unknown as string;
254
+ const circularValue: { self?: unknown } = {};
255
+ circularValue.self = circularValue;
256
+ new MainThreadRef(
257
+ failure === 'ref' ? throwingValue : failure === 'circular-ref' ? circularValue : 'survives-ui-serialization',
258
+ );
259
+ if (failure === 'dispatch') {
260
+ dispatch.mockImplementationOnce(() => {
261
+ throw serializeError;
262
+ });
263
+ }
264
+ const ref = vi.fn();
265
+ const removedRoot = new BackgroundElementTemplateInstance('removed');
266
+ const removeEventListener = vi.spyOn(lynx.getCoreContext(), 'removeEventListener');
267
+
268
+ try {
269
+ markElementTemplateHydrated();
270
+ queueRefAttrUpdate(null, ref, { instanceId: -2 }, 0);
271
+ markRemovedSubtreeForPostDispatchTeardown(removedRoot);
272
+ globalCommitContext.ops = createRawTextOps(1, failure === 'update' ? throwingValue : 'failed');
273
+ enqueueDelayedRunOnMainThreadData({
274
+ worklet: { _wkltId: 'failed-serialize-main-thread-function' },
275
+ params: [],
276
+ resolveId: onFunctionCall(vi.fn()),
277
+ });
278
+
279
+ expect(() => options.__c?.({} as unknown as object, [])).toThrow(
280
+ failure === 'circular-ref' ? TypeError : serializeError,
281
+ );
282
+ if (failure === 'update' || failure === 'dispatch') {
283
+ expect(dispatch).toHaveBeenCalledExactlyOnceWith({
284
+ type: ElementTemplateLifecycleConstant.updateMTRefInitValue,
285
+ data: JSON.stringify([[1, 'survives-ui-serialization']]),
286
+ });
287
+ } else {
288
+ expect(dispatch).not.toHaveBeenCalled();
289
+ }
290
+ expect(takeMainThreadRefInitValuePatch()).toEqual([]);
291
+ expect(takeDelayedRunOnMainThreadData()).toEqual([]);
292
+ expect(removeEventListener).toHaveBeenCalledWith(WorkletEvents.FunctionCallRet, expect.any(Function));
293
+ expect(globalCommitContext.ops).toEqual([]);
294
+ expect([...globalCommitContext.nonPayload.removedSubtreesAwaitingTeardown]).toEqual([]);
295
+
296
+ dispatch.mockClear();
297
+ new MainThreadRef('next-ref');
298
+ globalCommitContext.ops = createRawTextOps(2, 'next-commit');
299
+ options.__c?.({} as unknown as object, []);
300
+ expect(ref).not.toHaveBeenCalled();
301
+ expect(dispatch.mock.calls.map(([event]) => event.type)).toEqual([
302
+ ElementTemplateLifecycleConstant.updateMTRefInitValue,
303
+ ElementTemplateLifecycleConstant.update,
304
+ ]);
305
+ expect(dispatch.mock.calls[0]![0].data).toBe(JSON.stringify([[2, 'next-ref']]));
306
+ expect(parseElementTemplateUpdateEventPayload(dispatch.mock.calls[1]![0].data)).toMatchObject({
307
+ ops: createRawTextOps(2, 'next-commit'),
308
+ });
309
+ expect(parseElementTemplateUpdateEventPayload(dispatch.mock.calls[1]![0].data).delayedRunOnMainThreadData)
310
+ .toBeUndefined();
311
+
312
+ vi.advanceTimersByTime(10000);
313
+ expect(backgroundElementTemplateInstanceManager.get(removedRoot.instanceId)).toBeUndefined();
314
+ } finally {
315
+ vi.useRealTimers();
316
+ }
317
+ },
318
+ );
319
+
320
+ it('cleans a failed ref initialization commit before hydration', () => {
321
+ const circularValue: { self?: unknown } = {};
322
+ circularValue.self = circularValue;
323
+ new MainThreadRef(circularValue);
254
324
  const ref = vi.fn();
255
- const removedRoot = new BackgroundElementTemplateInstance('removed');
325
+ queueRefAttrUpdate(null, ref, { instanceId: -2 }, 0);
326
+ globalCommitContext.ops = createRawTextOps(1, 'failed');
327
+ enqueueDelayedRunOnMainThreadData({
328
+ worklet: { _wkltId: 'failed-ref-init' },
329
+ params: [],
330
+ resolveId: onFunctionCall(vi.fn()),
331
+ });
256
332
  const removeEventListener = vi.spyOn(lynx.getCoreContext(), 'removeEventListener');
257
333
 
258
- try {
259
- markElementTemplateHydrated();
260
- queueRefAttrUpdate(null, ref, { instanceId: -2 }, 0);
261
- markRemovedSubtreeForPostDispatchTeardown(removedRoot);
262
- globalCommitContext.ops = createRawTextOps(1, throwingValue);
263
- enqueueDelayedRunOnMainThreadData({
264
- worklet: { _wkltId: 'failed-serialize-main-thread-function' },
265
- params: [],
266
- resolveId: onFunctionCall(vi.fn()),
267
- });
268
-
269
- expect(() => options.__c?.({} as unknown as object, [])).toThrow(serializeError);
270
- expect(takeDelayedRunOnMainThreadData()).toEqual([]);
271
- expect(removeEventListener).toHaveBeenCalledWith(WorkletEvents.FunctionCallRet, expect.any(Function));
272
- expect(globalCommitContext.ops).toEqual([]);
273
- expect([...globalCommitContext.nonPayload.removedSubtreesAwaitingTeardown]).toEqual([]);
274
-
275
- options.__c?.({} as unknown as object, []);
276
- expect(ref).not.toHaveBeenCalled();
277
-
278
- vi.advanceTimersByTime(10000);
279
- expect(backgroundElementTemplateInstanceManager.get(removedRoot.instanceId)).toBeUndefined();
280
- } finally {
281
- vi.useRealTimers();
282
- }
334
+ expect(() => options.__c?.({} as unknown as object, [])).toThrow(TypeError);
335
+ expect(globalCommitContext.ops).toEqual([]);
336
+ expect(takeDelayedRunOnMainThreadData()).toEqual([]);
337
+ expect(removeEventListener).toHaveBeenCalledWith(WorkletEvents.FunctionCallRet, expect.any(Function));
338
+ options.__c?.({} as unknown as object, []);
339
+ expect(ref).not.toHaveBeenCalled();
283
340
  });
284
341
 
285
342
  it('dispatches triggerDataUpdated when useInitData observes a data change', () => {
@@ -3,6 +3,10 @@
3
3
  // LICENSE file in the root directory of this source tree.
4
4
 
5
5
  import path from 'node:path';
6
+ import {
7
+ installElementTemplateRefInitValueListener,
8
+ resetElementTemplateRefInitValueListener,
9
+ } from '../../../../../src/element-template/main-thread-ref-init-value.js';
6
10
  import { fileURLToPath } from 'node:url';
7
11
 
8
12
  import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -104,6 +108,7 @@ describe('Compiled runOnMainThread background fixtures', () => {
104
108
  vi.stubGlobal('__LoadLepusChunk', vi.fn());
105
109
 
106
110
  envManager.switchToMainThread();
111
+ installElementTemplateRefInitValueListener();
107
112
  installElementTemplatePatchListener();
108
113
  lynx.getJSContext().addEventListener(ElementTemplateLifecycleConstant.update, onUpdate);
109
114
  envManager.switchToBackground();
@@ -113,6 +118,7 @@ describe('Compiled runOnMainThread background fixtures', () => {
113
118
  envManager.switchToMainThread();
114
119
  lynx.getJSContext().removeEventListener(ElementTemplateLifecycleConstant.update, onUpdate);
115
120
  resetElementTemplatePatchListener();
121
+ resetElementTemplateRefInitValueListener();
116
122
  envManager.switchToBackground();
117
123
  resetElementTemplateHydrationListener();
118
124
  resetElementTemplateCommitState();
@@ -137,7 +143,7 @@ describe('Compiled runOnMainThread background fixtures', () => {
137
143
  }> {
138
144
  return loadCompiledFixturePair<CompiledRunOnMainThreadModule>(
139
145
  FIXTURE,
140
- { enableWorkletTransform: true },
146
+ { enableWorkletTransform: true, envManager },
141
147
  );
142
148
  }
143
149
 
@@ -0,0 +1,69 @@
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 { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
5
+ import { createElement, render } from 'preact';
6
+ import { Component } from 'preact/compat';
7
+
8
+ import {
9
+ installElementTemplateCommitHook,
10
+ markElementTemplateHydrated,
11
+ uninstallElementTemplateCommitHookForTesting,
12
+ } from '../../../../src/element-template/background/commit-hook.js';
13
+ import { callDestroyLifetimeFun } from '../../../../src/element-template/native/callDestroyLifetimeFun.js';
14
+ import { reloadBackground } from '../../../../src/element-template/native/reload-background.js';
15
+ import { __root } from '../../../../src/element-template/runtime/page/root-instance.js';
16
+ import { ElementTemplateEnvManager } from '../../test-utils/debug/envManager.js';
17
+
18
+ describe('ElementTemplate entry reload', () => {
19
+ const env = new ElementTemplateEnvManager();
20
+
21
+ beforeEach(() => {
22
+ env.resetEnv('background');
23
+ vi.stubGlobal('__EXPERIMENTAL_RE_EVAL_JS_ON_RELOAD__', true);
24
+ lynx[Symbol.for('__LYNX_ENTRY_SUPPORTS_RE_EVAL__')] = true;
25
+ installElementTemplateCommitHook();
26
+ });
27
+
28
+ afterEach(() => {
29
+ uninstallElementTemplateCommitHookForTesting();
30
+ delete lynx[Symbol.for('__LYNX_ENTRY_SUPPORTS_RE_EVAL__')];
31
+ vi.restoreAllMocks();
32
+ vi.unstubAllGlobals();
33
+ });
34
+
35
+ it('runs old component cleanup without sending removals to the new native tree', () => {
36
+ const cleanup = vi.fn();
37
+ class Probe extends Component {
38
+ componentWillUnmount() {
39
+ cleanup();
40
+ }
41
+ render() {
42
+ return createElement('view', null, 'old page');
43
+ }
44
+ }
45
+ __root.__jsx = createElement(Probe);
46
+ render(__root.__jsx, __root as never);
47
+ markElementTemplateHydrated();
48
+ const dispatch = vi.spyOn(lynx.getCoreContext(), 'dispatchEvent');
49
+ dispatch.mockClear();
50
+ const oldRoot = __root;
51
+ lynx.__initData = { retained: 'initial', count: 1 };
52
+ const reloadCard = vi.fn(() => {
53
+ expect(cleanup).toHaveBeenCalledOnce();
54
+ expect(oldRoot.__jsx).toBeUndefined();
55
+ expect(dispatch).not.toHaveBeenCalled();
56
+ return true;
57
+ });
58
+ vi.spyOn(lynx, 'getApp').mockReturnValue({ callDestroyLifetimeFun, reloadCard } as never);
59
+ const options = { processorName: 'reload' };
60
+
61
+ reloadBackground({ count: 2 }, options);
62
+
63
+ expect(reloadCard).toHaveBeenCalledWith({ retained: 'initial', count: 2 }, options);
64
+ // An already queued old globalProps rerender cannot remount its page.
65
+ render(oldRoot.__jsx, oldRoot as never);
66
+ expect(dispatch).not.toHaveBeenCalled();
67
+ expect(cleanup).toHaveBeenCalledOnce();
68
+ });
69
+ });