@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
@@ -0,0 +1,63 @@
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, expect, it, vi } from 'vitest';
5
+
6
+ import { createElement } from '../../../lepus/index.js';
7
+ import { runOnBackground } from '../../../src/core/background-function/run-on-background.js';
8
+ import { getReloadVersion } from '../../../src/core/reload-version.js';
9
+ import { resetFunctionCallReturnListener } from '../../../src/core/thread-function-call/return-value.js';
10
+ import { __root } from '../../../src/root.js';
11
+ import { setupPage } from '../../../src/snapshot/index.js';
12
+ import { initRunOnBackgroundDelay } from '../../../src/worklet-runtime/delayRunOnBackground.js';
13
+ import { globalEnvManager } from '../utils/envManager.js';
14
+ import { elementTree } from '../utils/nativeMethod.js';
15
+
16
+ beforeEach(() => {
17
+ globalEnvManager.resetEnv();
18
+ setupPage(__CreatePage('0', 0));
19
+ });
20
+
21
+ afterEach(() => {
22
+ vi.restoreAllMocks();
23
+ globalEnvManager.resetEnv();
24
+ elementTree.clear();
25
+ });
26
+
27
+ it('clears old delayed background calls before rendering and preserves new calls', () => {
28
+ const previousImpl = globalThis.lynxWorkletImpl;
29
+ const previousSdkVersion = SystemInfo.lynxSdkVersion;
30
+ SystemInfo.lynxSdkVersion = '4.0';
31
+ const delay = initRunOnBackgroundDelay();
32
+ globalThis.lynxWorkletImpl = { ...previousImpl, _runOnBackgroundDelayImpl: delay };
33
+ const dispatch = vi.spyOn(lynx.getJSContext(), 'dispatchEvent').mockImplementation(() => {});
34
+ try {
35
+ __root.__jsx = createElement(() => {
36
+ void runOnBackground(Object.assign(() => {}, { _isFirstScreen: true }))();
37
+ return null;
38
+ });
39
+ renderPage({});
40
+ expect(delay.delayedBackgroundFunctionArray).toHaveLength(1);
41
+ const oldTask = delay.delayedBackgroundFunctionArray[0];
42
+ const oldCallback = vi.spyOn(oldTask, 'task');
43
+
44
+ updatePage({}, { reloadTemplate: true });
45
+
46
+ expect(delay.delayedBackgroundFunctionArray).toHaveLength(1);
47
+ expect(delay.delayedBackgroundFunctionArray[0]).not.toBe(oldTask);
48
+ delay.delayedBackgroundFunctionArray[0].jsFnHandle = { _jsFnId: 7, _execId: 9 };
49
+ delay.runDelayedBackgroundFunctions();
50
+ expect(oldCallback).not.toHaveBeenCalled();
51
+ expect(dispatch).toHaveBeenCalledOnce();
52
+ expect(JSON.parse(dispatch.mock.calls[0][0].data)).toMatchObject({
53
+ obj: { _jsFnId: 7, _execId: 9 },
54
+ reloadVersion: getReloadVersion(),
55
+ });
56
+ expect(delay.delayedBackgroundFunctionArray).toHaveLength(0);
57
+ } finally {
58
+ delay.clearDelayedBackgroundFunctions();
59
+ resetFunctionCallReturnListener();
60
+ globalThis.lynxWorkletImpl = previousImpl;
61
+ SystemInfo.lynxSdkVersion = previousSdkVersion;
62
+ }
63
+ });
@@ -0,0 +1,103 @@
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 { createElement } from 'preact';
5
+ import { useLayoutEffect } from 'preact/hooks';
6
+ import { expect, it, vi } from 'vitest';
7
+
8
+ import {
9
+ delayedRunOnMainThreadData,
10
+ takeDelayedRunOnMainThreadData,
11
+ } from '../../../src/core/thread-function-call/main-thread.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 { destroyBackground } from '../../../src/snapshot/lifecycle/destroy.js';
16
+ import { globalCommitTaskMap } from '../../../src/snapshot/lifecycle/patch/commit.js';
17
+ import { reloadBackground } from '../../../src/snapshot/lifecycle/reload.js';
18
+ import { setupPage } from '../../../src/snapshot/index.js';
19
+ import { runOnMainThread } from '../../../src/snapshot/worklet/call/runOnMainThread.js';
20
+ import { registerWorklet } from '../../../src/worklet-runtime/bindings/index.js';
21
+ import { initWorklet } from '../../../src/worklet-runtime/workletRuntime.js';
22
+ import { globalEnvManager } from '../utils/envManager.js';
23
+ import { elementTree } from '../utils/nativeMethod.js';
24
+
25
+ it('drops pre-hydration and unmount calls before a reload reuses their return IDs', async () => {
26
+ const oldResult = vi.fn();
27
+ const cleanupResult = vi.fn();
28
+ const cleanup = vi.fn(() => {
29
+ void runOnMainThread({ _wkltId: 'unmount-call' })().then(cleanupResult);
30
+ expect(delayedRunOnMainThreadData.map(data => data.resolveId)).toEqual([1, 2]);
31
+ });
32
+ function App() {
33
+ useLayoutEffect(() => cleanup, []);
34
+ return null;
35
+ }
36
+
37
+ const oldCall = vi.fn(() => 'old-page');
38
+ const unmountCall = vi.fn(() => 'old-page');
39
+ const newCall = vi.fn(() => 'new-page');
40
+ const workletGlobals = {
41
+ lynxWorkletImpl: globalThis.lynxWorkletImpl,
42
+ runWorklet: globalThis.runWorklet,
43
+ registerWorklet: globalThis.registerWorklet,
44
+ registerWorkletInternal: globalThis.registerWorkletInternal,
45
+ };
46
+ const sdkVersion = SystemInfo.lynxSdkVersion;
47
+ globalEnvManager.resetEnv();
48
+ SystemInfo.lynxSdkVersion = '4.0';
49
+ try {
50
+ initWorklet();
51
+ registerWorklet('main-thread', 'old-call', oldCall);
52
+ registerWorklet('main-thread', 'unmount-call', unmountCall);
53
+ registerWorklet('main-thread', 'new-call', newCall);
54
+ setupPage(__CreatePage('0', 0));
55
+ __root.__jsx = null;
56
+ renderPage({});
57
+ globalEnvManager.switchToBackground();
58
+ root.render(createElement(App));
59
+ void runOnMainThread({ _wkltId: 'old-call' })().then(oldResult);
60
+ expect(delayedRunOnMainThreadData[0]?.resolveId).toBe(1);
61
+
62
+ reloadBackground({});
63
+ expect(cleanup).toHaveBeenCalledOnce();
64
+ // Both threads share resolver state in this harness. Complete MTS reload
65
+ // before creating the replacement BTS call, then deliver its hydration.
66
+ globalEnvManager.switchToMainThread();
67
+ updatePage({}, { reloadTemplate: true });
68
+ globalEnvManager.switchToBackground();
69
+ const result = runOnMainThread({ _wkltId: 'new-call' })();
70
+ expect(delayedRunOnMainThreadData.at(-1)?.resolveId).toBe(1);
71
+
72
+ lynx.getNativeApp().callLepusMethod.mockClear();
73
+ lynx.getApp().OnLifecycleEvent(...__OnLifecycleEvent.mock.lastCall);
74
+ const [method, patch, complete] = lynx.getNativeApp().callLepusMethod.mock.lastCall;
75
+ expect(patch.patchOptions.isHydration).toBe(true);
76
+ expect(JSON.parse(patch.data).delayedRunOnMainThreadData).toEqual([
77
+ { worklet: expect.objectContaining({ _wkltId: 'new-call' }), params: [], resolveId: 1 },
78
+ ]);
79
+ globalEnvManager.switchToMainThread();
80
+ globalThis[method](patch);
81
+ globalEnvManager.switchToBackground();
82
+ complete();
83
+
84
+ await expect(result).resolves.toBe('new-page');
85
+ expect(newCall).toHaveBeenCalledExactlyOnceWith();
86
+ expect(oldCall).not.toHaveBeenCalled();
87
+ expect(unmountCall).not.toHaveBeenCalled();
88
+ expect(oldResult).not.toHaveBeenCalled();
89
+ expect(cleanupResult).not.toHaveBeenCalled();
90
+ } finally {
91
+ cleanup.mockImplementation(() => {});
92
+ globalEnvManager.switchToBackground();
93
+ destroyBackground();
94
+ takeDelayedRunOnMainThreadData();
95
+ resetFunctionCallReturnListener();
96
+ globalCommitTaskMap.clear();
97
+ globalEnvManager.resetEnv();
98
+ elementTree.clear();
99
+ Object.assign(globalThis, workletGlobals);
100
+ SystemInfo.lynxSdkVersion = sdkVersion;
101
+ vi.restoreAllMocks();
102
+ }
103
+ });
@@ -5,11 +5,19 @@ import { useEffect, useLayoutEffect, useState } from '../../src/index';
5
5
  import { globalEnvManager } from './utils/envManager';
6
6
  import { waitSchedule } from './utils/nativeMethod';
7
7
  import { globalCommitTaskMap, replaceCommitHook } from '../../src/snapshot/lifecycle/patch/commit';
8
- import { deinitGlobalSnapshotPatch, initGlobalSnapshotPatch } from '../../src/snapshot/lifecycle/patch/snapshotPatch';
8
+ import {
9
+ __globalSnapshotPatch,
10
+ deinitGlobalSnapshotPatch,
11
+ initGlobalSnapshotPatch,
12
+ } from '../../src/snapshot/lifecycle/patch/snapshotPatch';
9
13
  import { LifecycleConstant } from '../../src/snapshot/lifecycle/constant';
10
14
  import { CATCH_ERROR } from '../../src/shared/render-constants';
11
15
  import { __root } from '../../src/root';
12
16
  import { setupPage, backgroundSnapshotInstanceManager } from '../../src/snapshot';
17
+ import { onFunctionCall, resetFunctionCallReturnListener } from '../../src/core/thread-function-call/return-value.js';
18
+ import { getReloadVersion } from '../../src/core/reload-version.js';
19
+ import { reloadBackground } from '../../src/snapshot/lifecycle/reload.js';
20
+ import { WorkletEvents } from '../../src/worklet-runtime/bindings/events.js';
13
21
 
14
22
  beforeAll(() => {
15
23
  setupPage(__CreatePage('0', 0));
@@ -673,3 +681,55 @@ describe('componentDidUpdate', () => {
673
681
  expect(callback).nthCalledWith(2, 2);
674
682
  });
675
683
  });
684
+
685
+ it.each(['page close', 'reload'])('cleans Snapshot patches and return listeners on %s', (boundary) => {
686
+ globalEnvManager.switchToBackground();
687
+ const context = lynx.getCoreContext();
688
+ const addListener = vi.spyOn(context, 'addEventListener').mockClear();
689
+ const removeListener = vi.spyOn(context, 'removeEventListener').mockClear();
690
+ const oldResolve = vi.fn();
691
+ let patchDuringUnmount = null;
692
+ const unmount = vi.fn(() => {
693
+ patchDuringUnmount = __globalSnapshotPatch;
694
+ // Cleanup can itself create a pending cross-thread call.
695
+ onFunctionCall(oldResolve);
696
+ });
697
+ class Comp extends Component {
698
+ componentWillUnmount() {
699
+ unmount();
700
+ }
701
+
702
+ render() {
703
+ return null;
704
+ }
705
+ }
706
+
707
+ try {
708
+ __root.__jsx = <Comp />;
709
+ render(__root.__jsx, __root);
710
+ initGlobalSnapshotPatch();
711
+ __globalSnapshotPatch.push('pending patch');
712
+ onFunctionCall(oldResolve);
713
+
714
+ if (boundary === 'page close') lynx.getApp().callDestroyLifetimeFun();
715
+ else reloadBackground({});
716
+
717
+ expect(unmount).toHaveBeenCalledOnce();
718
+ expect.soft(patchDuringUnmount).toBeUndefined();
719
+ expect.soft(__globalSnapshotPatch).toBeUndefined();
720
+ for (const [type, listener] of addListener.mock.calls) {
721
+ if (type === WorkletEvents.FunctionCallRet) {
722
+ expect.soft(removeListener).toHaveBeenCalledWith(type, listener);
723
+ }
724
+ }
725
+
726
+ const newResolve = vi.fn();
727
+ const resolveId = onFunctionCall(newResolve);
728
+ const listener = addListener.mock.lastCall[1];
729
+ listener({ data: JSON.stringify({ resolveId, returnValue: 'new result', reloadVersion: getReloadVersion() }) });
730
+ expect(newResolve).toHaveBeenCalledWith('new result');
731
+ expect(oldResolve).not.toHaveBeenCalled();
732
+ } finally {
733
+ resetFunctionCallReturnListener();
734
+ }
735
+ });
@@ -0,0 +1,105 @@
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
+
5
+ import { options, render } from 'preact';
6
+ import { createElement } from 'preact/compat';
7
+ import { afterEach, describe, expect, test, vi } from 'vitest';
8
+
9
+ import { lazy, useEffect, useRef, useState } from '../../../src/index.js';
10
+ import { makeSyncThen } from '../../../src/core/lynx/lazy-bundle.js';
11
+ import { __root } from '../../../src/root.js';
12
+ import { globalEnvManager } from '../utils/envManager.js';
13
+
14
+ afterEach(() => {
15
+ vi.restoreAllMocks();
16
+ });
17
+
18
+ describe('synchronous lazy imports with cached Promise.resolve results', () => {
19
+ test.each([undefined, null, true, false, 0, ''])(
20
+ 'keeps the shared promise for %j asynchronous',
21
+ async (value) => {
22
+ const resolve = Promise.resolve.bind(Promise);
23
+ const shared = resolve(value);
24
+ const originalThen = shared.then;
25
+ // The Lynx Promise polyfill reuses fulfilled promises for these values.
26
+ vi.spyOn(Promise, 'resolve').mockImplementation(result => result === value ? shared : resolve(result));
27
+
28
+ const promise = makeSyncThen('exports').call(resolve('exports'), () => value);
29
+ let lazyCallbackCalled = false;
30
+ promise.then(result => {
31
+ expect(result).toBe(value);
32
+ lazyCallbackCalled = true;
33
+ });
34
+ expect(lazyCallbackCalled).toBe(true);
35
+ expect(shared.then).toBe(originalThen);
36
+
37
+ let ordinaryCallbackCalled = false;
38
+ Promise.resolve(value).then(() => {
39
+ ordinaryCallbackCalled = true;
40
+ });
41
+ expect(ordinaryCallbackCalled).toBe(false);
42
+ await resolve();
43
+ expect(ordinaryCallbackCalled).toBe(true);
44
+ },
45
+ );
46
+
47
+ test('a cached lazy child mount effect can update its parent without re-entering', async () => {
48
+ globalEnvManager.resetEnv();
49
+ globalEnvManager.switchToBackground();
50
+ const previousDebounce = options.debounceRendering;
51
+ const previousRaf = options.requestAnimationFrame;
52
+ const resolve = Promise.resolve.bind(Promise);
53
+ const sharedUndefined = resolve();
54
+ vi.spyOn(Promise, 'resolve').mockImplementation(value => value === undefined ? sharedUndefined : resolve(value));
55
+
56
+ // This is Preact's fallback scheduler in Lynx runtimes without the global
57
+ // queueMicrotask API. Its Promise.resolve must remain asynchronous.
58
+ options.debounceRendering = callback => Promise.resolve().then(callback);
59
+ let flushEffects;
60
+ options.requestAnimationFrame = callback => {
61
+ flushEffects = callback;
62
+ };
63
+
64
+ const calls = [];
65
+ let parentValue;
66
+ function Leaf({ notify }) {
67
+ const count = useRef(0);
68
+ useEffect(() => {
69
+ count.current++;
70
+ calls.push(['effect', count.current]);
71
+ notify();
72
+ return () => calls.push(['cleanup', count.current]);
73
+ }, []);
74
+ return null;
75
+ }
76
+ const exports = { default: Leaf };
77
+ const cached = resolve(exports);
78
+ cached.then = makeSyncThen(exports);
79
+ const Remote = lazy(() => cached);
80
+ function App() {
81
+ const [value, setValue] = useState(0);
82
+ parentValue = value;
83
+ return createElement(Remote, { notify: () => setValue(v => v + 1) });
84
+ }
85
+
86
+ try {
87
+ render(createElement(App), __root);
88
+ flushEffects();
89
+ expect(calls).toEqual([['effect', 1]]);
90
+ expect(parentValue).toBe(0);
91
+ await resolve();
92
+ expect(parentValue).toBe(1);
93
+ expect(calls).toEqual([['effect', 1]]);
94
+
95
+ render(null, __root);
96
+ flushEffects();
97
+ expect(calls).toEqual([['effect', 1], ['cleanup', 1]]);
98
+ } finally {
99
+ render(null, __root);
100
+ flushEffects?.();
101
+ options.debounceRendering = previousDebounce;
102
+ options.requestAnimationFrame = previousRaf;
103
+ }
104
+ });
105
+ });
@@ -5,7 +5,7 @@ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi }
5
5
  import { globalEnvManager } from './utils/envManager';
6
6
  import { elementTree, options } from './utils/nativeMethod';
7
7
  import { __page as __internalPage } from '../../src/internal';
8
- import { firstScreenEventIdSwap } from '../../src/snapshot/lifecycle/event/firstScreenSync';
8
+ import { firstScreenSync } from '../../src/snapshot/lifecycle/event/firstScreenSync';
9
9
  import { __root } from '../../src/root';
10
10
  import { clearPage } from '../../src/snapshot';
11
11
 
@@ -467,7 +467,7 @@ describe('ssr', () => {
467
467
 
468
468
  ssrHydrate(info);
469
469
  expect(__internalPage).toBe(__page);
470
- expect(firstScreenEventIdSwap).toEqual({});
470
+ expect(firstScreenSync.eventIdSwap).toEqual({});
471
471
  {
472
472
  const listRef = elementTree.getElementById('ssr-list');
473
473
  expect(elementTree.triggerComponentAtIndex(listRef, 0)).toEqual(uiSign1);
@@ -40,7 +40,7 @@ describe('runOnBackground', () => {
40
40
  [
41
41
  [
42
42
  {
43
- "data": "{"obj":{"_jsFnId":233,"_execId":244},"params":[1,["args"]],"resolveId":1}",
43
+ "data": "{"obj":{"_jsFnId":233,"_execId":244},"params":[1,["args"]],"resolveId":1,"reloadVersion":0}",
44
44
  "type": "Lynx.Worklet.runOnBackground",
45
45
  },
46
46
  ],
@@ -69,7 +69,7 @@ describe('runOnBackground', () => {
69
69
  [
70
70
  [
71
71
  {
72
- "data": "{"obj":{"_jsFnId":7,"_execId":8},"params":[1,["args"]],"resolveId":1}",
72
+ "data": "{"obj":{"_jsFnId":7,"_execId":8},"params":[1,["args"]],"resolveId":1,"reloadVersion":0}",
73
73
  "type": "Lynx.Worklet.runOnBackground",
74
74
  },
75
75
  ],
@@ -111,14 +111,9 @@ describe('runOnBackground', () => {
111
111
 
112
112
  expect(() => {
113
113
  runJSFunction({
114
- data: JSON.stringify({
115
- obj: {
116
- _jsFnId: 234,
117
- _execId: id,
118
- },
119
- params: [],
120
- resolveId: 1,
121
- }),
114
+ obj: { _jsFnId: 234, _execId: id },
115
+ params: [],
116
+ resolveId: 1,
122
117
  });
123
118
  }).toThrowError('runOnBackground: JS function not found');
124
119
  });
@@ -229,6 +224,6 @@ describe('runJSFunction', () => {
229
224
  data: [id],
230
225
  });
231
226
 
232
- expect(trigger).toThrow('runOnBackground: JS function not found: {"_jsFnId":233,"_execId":1}');
227
+ expect(trigger).toThrow(`runOnBackground: JS function not found: {"_jsFnId":233,"_execId":${id}}`);
233
228
  });
234
229
  });
@@ -90,7 +90,7 @@ describe('runOnMainThread', () => {
90
90
  [
91
91
  [
92
92
  {
93
- "data": "{"worklet":{"_wkltId":"835d:450ef:2"},"params":[1,["args"]],"resolveId":1}",
93
+ "data": "{"worklet":{"_wkltId":"835d:450ef:2"},"params":[1,["args"]],"resolveId":1,"reloadVersion":0}",
94
94
  "type": "Lynx.Worklet.runWorkletCtx",
95
95
  },
96
96
  ],
@@ -16,7 +16,10 @@ import { MainThreadRef, isMainThreadRef, useMainThreadRef } from '../../../src/c
16
16
  import { isMainThreadFunction } from '../../../src/core/main-thread-function';
17
17
  import { takeMainThreadRefInitValuePatch } from '../../../src/core/main-thread-ref-init-value';
18
18
  import { globalEnvManager } from '../utils/envManager';
19
- import { injectUpdateMTRefInitValue } from '../../../src/snapshot/worklet/ref/updateInitValue';
19
+ import {
20
+ injectUpdateMTRefInitValue,
21
+ sendMTRefInitValueToMainThread,
22
+ } from '../../../src/snapshot/worklet/ref/updateInitValue';
20
23
 
21
24
  const Comp = () => {
22
25
  const ref = useMainThreadRef(233);
@@ -51,6 +54,7 @@ beforeEach(() => {
51
54
  });
52
55
 
53
56
  afterEach(() => {
57
+ globalThis.__ALOG__ = true;
54
58
  destroyWorklet();
55
59
  vi.clearAllMocks();
56
60
  });
@@ -151,6 +155,13 @@ describe('WorkletRef in js', () => {
151
155
  expect(globalThis.lynxWorkletImpl._refImpl.updateWorkletRefInitValueChanges).toBeCalledTimes(1);
152
156
  globalThis[rLynxChange[1][0]](rLynxChange[1][1]);
153
157
  expect(globalThis.lynxWorkletImpl._refImpl.updateWorkletRefInitValueChanges).toBeCalledTimes(1);
158
+ const logs = console.alog.mock.calls.map(([message]) => message).filter(message =>
159
+ message.includes('MTRefInitValue')
160
+ );
161
+ expect(logs).toEqual([
162
+ '[ReactLynxDebug] Snapshot BTS -> MTS sendMTRefInitValue:\n[[1,233]]',
163
+ '[ReactLynxDebug] Snapshot MTS updateMTRefInitValue:\n[[1,233]]',
164
+ ]);
154
165
  }
155
166
  });
156
167
 
@@ -176,6 +187,18 @@ describe('WorkletRef in js', () => {
176
187
  );
177
188
  });
178
189
 
190
+ it.each([false, undefined])('should initialize refs without alog when the flag is %s', (alog) => {
191
+ globalThis.__ALOG__ = alog;
192
+ globalEnvManager.switchToBackground();
193
+ new MainThreadRef(233);
194
+ sendMTRefInitValueToMainThread();
195
+ const [name, data] = lynx.getNativeApp().callLepusMethod.mock.calls.at(-1);
196
+ globalEnvManager.switchToMainThread();
197
+ globalThis[name](data);
198
+ expect(globalThis.lynxWorkletImpl._refImpl.updateWorkletRefInitValueChanges).toHaveBeenCalledWith([[1, 233]]);
199
+ expect(console.alog.mock.calls.some(([message]) => message.includes('MTRefInitValue'))).toBe(false);
200
+ });
201
+
179
202
  it('should not send init value to the main thread when native capabilities not fulfilled', () => {
180
203
  SystemInfo.lynxSdkVersion = '2.13';
181
204
  const Comp = () => {
@@ -1,7 +1,7 @@
1
1
  // Copyright 2024 The Lynx Authors. All rights reserved.
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
- import { beforeEach, describe, expect, it } from 'vitest';
4
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
5
5
 
6
6
  import { JsFunctionLifecycleManager } from '../../src/worklet-runtime/jsFunctionLifecycle';
7
7
 
@@ -86,4 +86,18 @@ describe('jsFunctionLifecycle', () => {
86
86
  }
87
87
  `);
88
88
  });
89
+ it('leaves failed registrations retryable', () => {
90
+ const manager = new JsFunctionLifecycleManager();
91
+ const target = {};
92
+ const error = new TypeError('target must be an object');
93
+ const register = vi.spyOn(manager.registry, 'register').mockImplementationOnce(() => {
94
+ throw error;
95
+ });
96
+ expect(() => manager.addRef(3, target)).toThrow(error);
97
+ expect(manager.execIdRefCount.size).toBe(0);
98
+ expect(manager.retainedObjects.has(target)).toBe(false);
99
+ manager.addRef(3, target);
100
+ expect(register).toHaveBeenCalledTimes(2);
101
+ expect(manager.execIdRefCount.get(3)).toBe(1);
102
+ });
89
103
  });
@@ -152,6 +152,52 @@ describe('MainThreadObject registry and realization', () => {
152
152
  }).not.toThrow();
153
153
  });
154
154
 
155
+ it('keeps the resolved factory when the same create is registered again', () => {
156
+ const create = vi.fn(value => ({ value }));
157
+ const createDescriptor = { _wkltId: 'create-repeat' };
158
+ globalThis.registerWorklet('main-thread', 'create-repeat', create);
159
+ const lookupFactory = vi.fn(() => create);
160
+ Object.defineProperty(lynxWorkletImpl._workletMap, 'create-repeat', { get: lookupFactory });
161
+
162
+ const register = () =>
163
+ globalThis.lynxWorkletImpl._refImpl.registerMainThreadObjectType('@test/repeat', createDescriptor);
164
+ register();
165
+ updateWorkletRefInitValueChanges([[81, 'first', '@test/repeat']]);
166
+ // `useMainThreadObject` registers the type again on its first use.
167
+ register();
168
+ updateWorkletRefInitValueChanges([[82, 'second', '@test/repeat']]);
169
+
170
+ expect(lookupFactory).toHaveBeenCalledOnce();
171
+ removeValueFromWorkletRefMap(81);
172
+ removeValueFromWorkletRefMap(82);
173
+ });
174
+
175
+ it('uses the factory of the latest evaluation of the defining module', () => {
176
+ // Each evaluation of the module creates its own descriptor and its own
177
+ // module state; the worklet ID and source stay the same.
178
+ const evaluateModule = (generation) => {
179
+ globalThis.registerWorklet('main-thread', 'create-generation', value => ({ value, generation }));
180
+ globalThis.lynxWorkletImpl._refImpl.registerMainThreadObjectType(
181
+ '@test/generation',
182
+ { _wkltId: 'create-generation' },
183
+ );
184
+ };
185
+
186
+ evaluateModule('old');
187
+ updateWorkletRefInitValueChanges([[91, 'a', '@test/generation']]);
188
+ const oldObject = getFromWorkletRefMap({ _wvid: 91 });
189
+ expect(oldObject).toMatchObject({ generation: 'old' });
190
+
191
+ evaluateModule('new');
192
+ updateWorkletRefInitValueChanges([[92, 'b', '@test/generation']]);
193
+ expect(getFromWorkletRefMap({ _wvid: 92 })).toMatchObject({ generation: 'new' });
194
+ // Objects that already exist keep their identity.
195
+ expect(getFromWorkletRefMap({ _wvid: 91 })).toBe(oldObject);
196
+
197
+ removeValueFromWorkletRefMap(91);
198
+ removeValueFromWorkletRefMap(92);
199
+ });
200
+
155
201
  it('rejects factories that do not create objects', () => {
156
202
  globalThis.lynxWorkletImpl._refImpl.registerMainThreadObjectType(
157
203
  '@test/invalid',
@@ -37,7 +37,7 @@ describe('runOnMainThread', () => {
37
37
  [
38
38
  [
39
39
  {
40
- "data": "{"resolveId":10,"returnValue":"ret"}",
40
+ "data": "{"resolveId":10,"returnValue":"ret","reloadVersion":0}",
41
41
  "type": "Lynx.Worklet.FunctionCallRet",
42
42
  },
43
43
  ],
@@ -45,7 +45,7 @@ describe('runOnMainThread', () => {
45
45
  `);
46
46
  });
47
47
 
48
- it('dispatches the legacy return event when the worklet throws', () => {
48
+ it('sends a scoped return event when the worklet throws', () => {
49
49
  const error = new Error('main-thread worklet failed');
50
50
  globalThis.registerWorklet('main-thread', '1', () => {
51
51
  throw error;
@@ -56,7 +56,7 @@ describe('runOnMainThread', () => {
56
56
  [
57
57
  [
58
58
  {
59
- "data": "{"resolveId":10}",
59
+ "data": "{"resolveId":10,"reloadVersion":0}",
60
60
  "type": "Lynx.Worklet.FunctionCallRet",
61
61
  },
62
62
  ],
@@ -5,6 +5,8 @@ import type { JsFnHandle, Worklet } from '../../worklet-runtime/bindings/types.j
5
5
  * a handle to one of its background functions.
6
6
  */
7
7
  export declare class BackgroundFunctionExecMap extends IndexMap<Worklet> {
8
+ constructor();
9
+ clear(): void;
8
10
  add(worklet: Worklet): number;
9
11
  findJsFnHandle(execId: number, fnId: number): JsFnHandle | undefined;
10
12
  private findJsFnHandleInValue;
@@ -2,11 +2,18 @@
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
  import { IndexMap } from '../../shared/index-map.js';
5
+ import { cardLifetime } from '../card-lifetime.js';
5
6
  /**
6
7
  * Keeps the background-thread worklet ctx alive while main thread still holds
7
8
  * a handle to one of its background functions.
8
9
  */
9
10
  export class BackgroundFunctionExecMap extends IndexMap {
11
+ constructor() {
12
+ super(cardLifetime('backgroundFunctionCtxId', () => ({ lastIndex: 0 })));
13
+ }
14
+ clear() {
15
+ this.indexMap.clear();
16
+ }
10
17
  add(worklet) {
11
18
  const execId = super.add(worklet);
12
19
  worklet._execId = execId;
@@ -1 +1 @@
1
- {"version":3,"file":"exec-map.js","sourceRoot":"","sources":["../../../src/core/background-function/exec-map.ts"],"names":[],"mappings":"AAAA,wDAAwD;AACxD,yEAAyE;AACzE,0DAA0D;AAE1D,OAAO,EAAE,QAAQ,EAAE,MAAM,2BAA2B,CAAC;AAGrD;;;GAGG;AACH,MAAM,OAAO,yBAA0B,SAAQ,QAAiB;IAC9C,GAAG,CAAC,OAAgB;QAClC,MAAM,MAAM,GAAG,KAAK,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;QAClC,OAAO,CAAC,OAAO,GAAG,MAAM,CAAC;QACzB,OAAO,MAAM,CAAC;IAChB,CAAC;IAEM,cAAc,CAAC,MAAc,EAAE,IAAY;QAChD,MAAM,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QACjC,IAAI,CAAC,OAAO,EAAE,CAAC;YACb,OAAO,SAAS,CAAC;QACnB,CAAC;QAED,OAAO,IAAI,CAAC,qBAAqB,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;IACnD,CAAC;IAEO,qBAAqB,CAAC,KAAc,EAAE,IAAY;QACxD,IAAI,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;YAChD,OAAO,SAAS,CAAC;QACnB,CAAC;QACD,MAAM,GAAG,GAAG,KAAgC,CAAC;QAC7C,IAAI,SAAS,IAAI,GAAG,IAAI,GAAG,CAAC,SAAS,CAAC,KAAK,IAAI,EAAE,CAAC;YAChD,OAAO,GAAiB,CAAC;QAC3B,CAAC;QACD,KAAK,MAAM,CAAC,IAAI,GAAG,EAAE,CAAC;YACpB,MAAM,MAAM,GAAG,IAAI,CAAC,qBAAqB,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;YACxD,IAAI,MAAM,EAAE,CAAC;gBACX,OAAO,MAAM,CAAC;YAChB,CAAC;QACH,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;CACF","sourcesContent":["// Copyright 2024 The Lynx Authors. All rights reserved.\n// Licensed under the Apache License Version 2.0 that can be found in the\n// LICENSE file in the root directory of this source tree.\n\nimport { IndexMap } from '../../shared/index-map.js';\nimport type { JsFnHandle, Worklet } from '../../worklet-runtime/bindings/types.js';\n\n/**\n * Keeps the background-thread worklet ctx alive while main thread still holds\n * a handle to one of its background functions.\n */\nexport class BackgroundFunctionExecMap extends IndexMap<Worklet> {\n public override add(worklet: Worklet): number {\n const execId = super.add(worklet);\n worklet._execId = execId;\n return execId;\n }\n\n public findJsFnHandle(execId: number, fnId: number): JsFnHandle | undefined {\n const worklet = this.get(execId);\n if (!worklet) {\n return undefined;\n }\n\n return this.findJsFnHandleInValue(worklet, fnId);\n }\n\n private findJsFnHandleInValue(value: unknown, fnId: number): JsFnHandle | undefined {\n if (value === null || typeof value !== 'object') {\n return undefined;\n }\n const obj = value as Record<string, unknown>;\n if ('_jsFnId' in obj && obj['_jsFnId'] === fnId) {\n return obj as JsFnHandle;\n }\n for (const i in obj) {\n const result = this.findJsFnHandleInValue(obj[i], fnId);\n if (result) {\n return result;\n }\n }\n return undefined;\n }\n}\n"]}
1
+ {"version":3,"file":"exec-map.js","sourceRoot":"","sources":["../../../src/core/background-function/exec-map.ts"],"names":[],"mappings":"AAAA,wDAAwD;AACxD,yEAAyE;AACzE,0DAA0D;AAE1D,OAAO,EAAE,QAAQ,EAAE,MAAM,2BAA2B,CAAC;AAErD,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAEnD;;;GAGG;AACH,MAAM,OAAO,yBAA0B,SAAQ,QAAiB;IAC9D;QACE,KAAK,CAAC,YAAY,CAAC,yBAAyB,EAAE,GAAG,EAAE,CAAC,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;IAC3E,CAAC;IAEM,KAAK;QACV,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC;IACxB,CAAC;IAEe,GAAG,CAAC,OAAgB;QAClC,MAAM,MAAM,GAAG,KAAK,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;QAClC,OAAO,CAAC,OAAO,GAAG,MAAM,CAAC;QACzB,OAAO,MAAM,CAAC;IAChB,CAAC;IAEM,cAAc,CAAC,MAAc,EAAE,IAAY;QAChD,MAAM,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QACjC,IAAI,CAAC,OAAO,EAAE,CAAC;YACb,OAAO,SAAS,CAAC;QACnB,CAAC;QAED,OAAO,IAAI,CAAC,qBAAqB,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;IACnD,CAAC;IAEO,qBAAqB,CAAC,KAAc,EAAE,IAAY;QACxD,IAAI,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;YAChD,OAAO,SAAS,CAAC;QACnB,CAAC;QACD,MAAM,GAAG,GAAG,KAAgC,CAAC;QAC7C,IAAI,SAAS,IAAI,GAAG,IAAI,GAAG,CAAC,SAAS,CAAC,KAAK,IAAI,EAAE,CAAC;YAChD,OAAO,GAAiB,CAAC;QAC3B,CAAC;QACD,KAAK,MAAM,CAAC,IAAI,GAAG,EAAE,CAAC;YACpB,MAAM,MAAM,GAAG,IAAI,CAAC,qBAAqB,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;YACxD,IAAI,MAAM,EAAE,CAAC;gBACX,OAAO,MAAM,CAAC;YAChB,CAAC;QACH,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;CACF","sourcesContent":["// Copyright 2024 The Lynx Authors. All rights reserved.\n// Licensed under the Apache License Version 2.0 that can be found in the\n// LICENSE file in the root directory of this source tree.\n\nimport { IndexMap } from '../../shared/index-map.js';\nimport type { JsFnHandle, Worklet } from '../../worklet-runtime/bindings/types.js';\nimport { cardLifetime } from '../card-lifetime.js';\n\n/**\n * Keeps the background-thread worklet ctx alive while main thread still holds\n * a handle to one of its background functions.\n */\nexport class BackgroundFunctionExecMap extends IndexMap<Worklet> {\n constructor() {\n super(cardLifetime('backgroundFunctionCtxId', () => ({ lastIndex: 0 })));\n }\n\n public clear(): void {\n this.indexMap.clear();\n }\n\n public override add(worklet: Worklet): number {\n const execId = super.add(worklet);\n worklet._execId = execId;\n return execId;\n }\n\n public findJsFnHandle(execId: number, fnId: number): JsFnHandle | undefined {\n const worklet = this.get(execId);\n if (!worklet) {\n return undefined;\n }\n\n return this.findJsFnHandleInValue(worklet, fnId);\n }\n\n private findJsFnHandleInValue(value: unknown, fnId: number): JsFnHandle | undefined {\n if (value === null || typeof value !== 'object') {\n return undefined;\n }\n const obj = value as Record<string, unknown>;\n if ('_jsFnId' in obj && obj['_jsFnId'] === fnId) {\n return obj as JsFnHandle;\n }\n for (const i in obj) {\n const result = this.findJsFnHandleInValue(obj[i], fnId);\n if (result) {\n return result;\n }\n }\n return undefined;\n }\n}\n"]}