@lynx-js/react 0.129.4 → 0.129.5

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 (147) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/components/tsconfig.tsbuildinfo +1 -1
  3. package/package.json +9 -1
  4. package/refresh/.turbo/turbo-build.log +1 -1
  5. package/runtime/__test__/core/lynx/env.test.ts +146 -0
  6. package/runtime/__test__/element-template/imports/suspense-lazy.test.ts +47 -4
  7. package/runtime/__test__/element-template/native/index.test.ts +9 -9
  8. package/runtime/__test__/element-template/native/mts-destroy.test.ts +55 -2
  9. package/runtime/__test__/element-template/native/reload.test.ts +15 -5
  10. package/runtime/__test__/element-template/runtime/background/main-thread-function/compiled-fixtures.test.tsx +1 -1
  11. package/runtime/__test__/element-template/runtime/hydration/hydration-listener.test.ts +1 -1
  12. package/runtime/__test__/element-template/runtime/render/render-transform.contract.test.ts +33 -0
  13. package/runtime/__test__/element-template/vitest.config.ts +1 -1
  14. package/runtime/__test__/snapshot/debug/profile.test.jsx +147 -26
  15. package/runtime/__test__/snapshot/lifecycle/reload-delayed-background.test.jsx +54 -0
  16. package/runtime/__test__/snapshot/lifecycle/transfer.mts.test.jsx +98 -6
  17. package/runtime/__test__/snapshot/lifecycle/transfer.test.jsx +214 -9
  18. package/runtime/__test__/snapshot/lynx/suspense.test.jsx +48 -0
  19. package/runtime/__test__/snapshot/utils/envManager.ts +2 -0
  20. package/runtime/__test__/worklet-runtime/delayWorkletEvent.test.js +21 -0
  21. package/runtime/__test__/worklet-runtime/lifecycle.test.js +297 -0
  22. package/runtime/__test__/worklet-runtime/profile.test.js +12 -6
  23. package/runtime/lazy/element-template-internal.js +1 -0
  24. package/runtime/lib/core/compat/componentIs.d.ts +1 -0
  25. package/runtime/lib/core/compat/componentIs.js +20 -0
  26. package/runtime/lib/core/compat/componentIs.js.map +1 -0
  27. package/runtime/lib/core/lynx/env.d.ts +1 -0
  28. package/runtime/lib/{element-template → core}/lynx/env.js +3 -2
  29. package/runtime/lib/core/lynx/env.js.map +1 -0
  30. package/runtime/lib/core/thread-function-call/main-thread.d.ts +1 -0
  31. package/runtime/lib/core/thread-function-call/main-thread.js +4 -1
  32. package/runtime/lib/core/thread-function-call/main-thread.js.map +1 -1
  33. package/runtime/lib/element-template/background/commit-event.d.ts +6 -0
  34. package/runtime/lib/element-template/background/commit-event.js +36 -0
  35. package/runtime/lib/element-template/background/commit-event.js.map +1 -0
  36. package/runtime/lib/element-template/background/commit-hook.js +3 -23
  37. package/runtime/lib/element-template/background/commit-hook.js.map +1 -1
  38. package/runtime/lib/element-template/background/destroy.js +1 -1
  39. package/runtime/lib/element-template/background/destroy.js.map +1 -1
  40. package/runtime/lib/element-template/background/hydrate.js +1 -2
  41. package/runtime/lib/element-template/background/hydrate.js.map +1 -1
  42. package/runtime/lib/element-template/background/hydration-listener.js +5 -25
  43. package/runtime/lib/element-template/background/hydration-listener.js.map +1 -1
  44. package/runtime/lib/element-template/{runtime/template → background}/main-thread-function.js +4 -4
  45. package/runtime/lib/element-template/background/main-thread-function.js.map +1 -0
  46. package/runtime/lib/element-template/index.d.ts +1 -1
  47. package/runtime/lib/element-template/index.js +1 -1
  48. package/runtime/lib/element-template/index.js.map +1 -1
  49. package/runtime/lib/element-template/internal.js +3 -0
  50. package/runtime/lib/element-template/internal.js.map +1 -1
  51. package/runtime/lib/element-template/native/index.js +2 -2
  52. package/runtime/lib/element-template/native/index.js.map +1 -1
  53. package/runtime/lib/element-template/native/mts-destroy.d.ts +2 -1
  54. package/runtime/lib/element-template/native/mts-destroy.js +15 -4
  55. package/runtime/lib/element-template/native/mts-destroy.js.map +1 -1
  56. package/runtime/lib/element-template/native/reload-main-thread.js +2 -2
  57. package/runtime/lib/element-template/native/reload-main-thread.js.map +1 -1
  58. package/runtime/lib/element-template/runtime/patch.js +4 -11
  59. package/runtime/lib/element-template/runtime/patch.js.map +1 -1
  60. package/runtime/lib/element-template/runtime/template/handle.d.ts +1 -1
  61. package/runtime/lib/element-template/runtime/template/handle.js +2 -2
  62. package/runtime/lib/element-template/runtime/template/handle.js.map +1 -1
  63. package/runtime/lib/element-template/runtime/template/main-thread-background-function.d.ts +1 -0
  64. package/runtime/lib/element-template/runtime/template/main-thread-background-function.js +7 -2
  65. package/runtime/lib/element-template/runtime/template/main-thread-background-function.js.map +1 -1
  66. package/runtime/lib/internal.js +4 -10
  67. package/runtime/lib/internal.js.map +1 -1
  68. package/runtime/lib/snapshot/debug/profileHooks.js +27 -62
  69. package/runtime/lib/snapshot/debug/profileHooks.js.map +1 -1
  70. package/runtime/lib/snapshot/lifecycle/reload.js +2 -2
  71. package/runtime/lib/snapshot/lifecycle/reload.js.map +1 -1
  72. package/runtime/lib/snapshot/lynx/env.js +2 -32
  73. package/runtime/lib/snapshot/lynx/env.js.map +1 -1
  74. package/runtime/lib/snapshot/transfer.d.ts +6 -0
  75. package/runtime/lib/snapshot/transfer.js +154 -11
  76. package/runtime/lib/snapshot/transfer.js.map +1 -1
  77. package/runtime/lib/tsconfig.tsbuildinfo +1 -1
  78. package/runtime/lib/worklet-runtime/bindings/lifecycle.d.ts +19 -0
  79. package/runtime/lib/worklet-runtime/bindings/lifecycle.js +49 -0
  80. package/runtime/lib/worklet-runtime/bindings/lifecycle.js.map +1 -0
  81. package/runtime/lib/worklet-runtime/delayWorkletEvent.d.ts +1 -1
  82. package/runtime/lib/worklet-runtime/delayWorkletEvent.js +9 -1
  83. package/runtime/lib/worklet-runtime/delayWorkletEvent.js.map +1 -1
  84. package/runtime/lib/worklet-runtime/utils/profile.js +1 -3
  85. package/runtime/lib/worklet-runtime/utils/profile.js.map +1 -1
  86. package/runtime/src/core/compat/componentIs.ts +32 -0
  87. package/runtime/src/{element-template → core}/lynx/env.ts +6 -4
  88. package/runtime/src/core/thread-function-call/main-thread.ts +5 -1
  89. package/runtime/src/element-template/background/commit-event.ts +52 -0
  90. package/runtime/src/element-template/background/commit-hook.ts +4 -31
  91. package/runtime/src/element-template/background/destroy.ts +1 -1
  92. package/runtime/src/element-template/background/hydrate.ts +5 -3
  93. package/runtime/src/element-template/background/hydration-listener.ts +7 -32
  94. package/runtime/src/element-template/{runtime/template → background}/main-thread-function.ts +4 -7
  95. package/runtime/src/element-template/index.ts +1 -1
  96. package/runtime/src/element-template/internal.ts +4 -0
  97. package/runtime/src/element-template/native/index.ts +2 -2
  98. package/runtime/src/element-template/native/mts-destroy.ts +21 -4
  99. package/runtime/src/element-template/native/reload-main-thread.ts +2 -2
  100. package/runtime/src/element-template/runtime/patch.ts +20 -35
  101. package/runtime/src/element-template/runtime/template/handle.ts +2 -0
  102. package/runtime/src/element-template/runtime/template/main-thread-background-function.ts +8 -2
  103. package/runtime/src/internal.ts +4 -13
  104. package/runtime/src/snapshot/debug/profileHooks.ts +30 -91
  105. package/runtime/src/snapshot/lifecycle/reload.ts +2 -3
  106. package/runtime/src/snapshot/lynx/env.ts +3 -43
  107. package/runtime/src/snapshot/transfer.ts +169 -13
  108. package/runtime/src/worklet-runtime/bindings/lifecycle.ts +51 -0
  109. package/runtime/src/worklet-runtime/delayWorkletEvent.ts +10 -2
  110. package/runtime/src/worklet-runtime/utils/profile.ts +1 -3
  111. package/runtime/types/internal-preact.d.ts +2 -0
  112. package/runtime/vitest.config.ts +0 -1
  113. package/testing-library/.turbo/turbo-build.log +7 -7
  114. package/testing-library/src/__tests__/events.test.jsx +1 -1
  115. package/testing-library/src/fire-event.ts +1 -1
  116. package/transform/.turbo/turbo-build$colon$wasm.log +67 -66
  117. package/transform/__test__/fixture.spec.js +1 -1
  118. package/transform/cjs/browser.cjs +11 -0
  119. package/transform/crates/swc_plugin_compat/lib.rs +20 -2
  120. package/transform/crates/swc_plugin_compat/napi.rs +7 -0
  121. package/transform/crates/swc_plugin_dynamic_import/lib.rs +15 -4
  122. package/transform/crates/swc_plugin_element_template/attr_name.rs +0 -3
  123. package/transform/crates/swc_plugin_element_template/extractor.rs +0 -8
  124. package/transform/crates/swc_plugin_element_template/lib.rs +12 -1
  125. package/transform/crates/swc_plugin_element_template/tests/element_template_contract.rs +35 -0
  126. package/transform/crates/swc_plugin_worklet/lib.rs +11 -7
  127. package/transform/dist/wasm.cjs +1 -1
  128. package/transform/rspack-napi/lib/index.js +1 -4
  129. package/transform/rspack-napi/lib/index.js.map +1 -1
  130. package/transform/rspack-napi/src/index.ts +1 -4
  131. package/transform/rspack-napi/tsconfig.tsbuildinfo +1 -1
  132. package/transform/src/lib.rs +394 -27
  133. package/transform/swc-plugin-reactlynx/.turbo/turbo-build.log +413 -105
  134. package/transform/swc-plugin-reactlynx/src/lib.rs +99 -22
  135. package/transform/swc-plugin-reactlynx/swc_plugin_reactlynx.wasm +0 -0
  136. package/transform/swc-plugin-reactlynx-compat/.turbo/turbo-build.log +28 -359
  137. package/transform/swc-plugin-reactlynx-compat/swc_plugin_reactlynx_compat.wasm +0 -0
  138. package/runtime/__test__/element-template/lynx/env.test.ts +0 -242
  139. package/runtime/lib/element-template/lynx/env.d.ts +0 -1
  140. package/runtime/lib/element-template/lynx/env.js.map +0 -1
  141. package/runtime/lib/element-template/runtime/template/main-thread-function.js.map +0 -1
  142. package/runtime/lib/snapshot/compat/componentIs.d.ts +0 -4
  143. package/runtime/lib/snapshot/compat/componentIs.js +0 -20
  144. package/runtime/lib/snapshot/compat/componentIs.js.map +0 -1
  145. package/runtime/src/snapshot/compat/componentIs.ts +0 -30
  146. /package/runtime/__test__/element-template/runtime/{template → background}/main-thread-function.test.ts +0 -0
  147. /package/runtime/lib/element-template/{runtime/template → background}/main-thread-function.d.ts +0 -0
@@ -5,10 +5,14 @@
5
5
  // the thread, so the background side lives in `transfer.test.jsx`.
6
6
  import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
7
7
 
8
+ import { runOnBackground } from '../../../src/core/background-function/run-on-background';
9
+ import { resetFunctionCallReturnListener } from '../../../src/core/thread-function-call/return-value';
8
10
  import { root } from '../../../src/index';
9
11
  import { TransferRegistry } from '../../../src/internal';
10
12
  import { __root } from '../../../src/root';
11
13
  import { snapshotInstanceManager } from '../../../src/snapshot/snapshot/snapshotInstanceManager';
14
+ import { WorkletEvents } from '../../../src/worklet-runtime/bindings/events';
15
+ import { hydrateJsFnHandles, initRunOnBackgroundDelay } from '../../../src/worklet-runtime/run-on-background/index';
12
16
  import { globalEnvManager } from '../utils/envManager';
13
17
  import { elementTree } from '../utils/nativeMethod';
14
18
 
@@ -96,9 +100,11 @@ describe('transfer (main thread)', () => {
96
100
  create('1');
97
101
  native.fire('__CreateTransfer', { transferId: 'missing', componentName: 'Missing', initialProps: {} });
98
102
  // Props sent before the page renders replace the queued initial props.
99
- native.fire('__SetTransferProps', { transferId: '1', props: { text: 'queued' } });
103
+ native.fire('__UpdateTransfer', { transferId: '1', props: { text: 'early' } });
104
+ native.fire('__ReloadTransfer', { transferId: '1', props: { text: 'queued' } });
100
105
  expect(link.of('__TransferFirstFrame')).toHaveLength(0);
101
- expect(link.of('__SetTransferProps')).toHaveLength(0);
106
+ expect(link.of('__UpdateTransfer')).toHaveLength(0);
107
+ expect(link.of('__ReloadTransfer')).toHaveLength(0);
102
108
 
103
109
  engine.fire('__RenderPage', [{ text: 'init' }]);
104
110
  expect(lynx.__initData).toEqual({ text: 'init' });
@@ -125,11 +131,11 @@ describe('transfer (main thread)', () => {
125
131
  expect(commit('404', 1)).toEqual({ transferId: '404', version: 0, seq: 1, status: 'disposed' });
126
132
  });
127
133
 
128
- it('re-renders and re-syncs the first frame when props change', () => {
134
+ it('re-renders and re-syncs the first frame when props reload', () => {
129
135
  const view = elementTree.root.children[0].children[0];
130
136
  const size = snapshotInstanceManager.values.size;
131
- native.fire('__SetTransferProps', { transferId: '1', props: { text: 'x' } });
132
- expect(link.of('__SetTransferProps')).toEqual([{ transferId: '1', props: { text: 'x' } }]);
137
+ native.fire('__ReloadTransfer', { transferId: '1', props: { text: 'x' } });
138
+ expect(link.of('__ReloadTransfer')).toEqual([{ transferId: '1', props: { text: 'x' } }]);
133
139
 
134
140
  // Like a template reload, the new frame reuses the elements of the previous one.
135
141
  expect(elementTree.root.children[0].children[0]).toBe(view);
@@ -181,7 +187,7 @@ describe('transfer (main thread)', () => {
181
187
  });
182
188
  const size = snapshotInstanceManager.values.size;
183
189
  native.fire('__CreateTransfer', { transferId: '4', componentName: 'Flaky', initialProps: {} });
184
- native.fire('__SetTransferProps', { transferId: '4', props: { fail: true } });
190
+ native.fire('__ReloadTransfer', { transferId: '4', props: { fail: true } });
185
191
  expect(reportError).toHaveBeenCalledWith(new Error('flaky'));
186
192
  expect(elementTree.root.children).toHaveLength(0);
187
193
  expect(snapshotInstanceManager.values.size).toBe(size);
@@ -191,4 +197,90 @@ describe('transfer (main thread)', () => {
191
197
  engine.fire('__RenderPage', []);
192
198
  expect(lynx.__initData).toEqual({});
193
199
  });
200
+
201
+ it('runs first-screen runOnBackground calls after their own transfer hydrates', () => {
202
+ const previousImpl = globalThis.lynxWorkletImpl;
203
+ const previousSdkVersion = SystemInfo.lynxSdkVersion;
204
+ SystemInfo.lynxSdkVersion = '4.0';
205
+ // Only the parts of the worklet runtime that `onHydrationFinished` touches.
206
+ globalThis.lynxWorkletImpl = {
207
+ _runOnBackgroundDelayImpl: initRunOnBackgroundDelay(),
208
+ _refImpl: { clearFirstScreenWorkletRefMap() {} },
209
+ _eventDelayImpl: { clearDelayedWorklets() {} },
210
+ };
211
+ const firstScreenHandle = () => Object.assign(() => {}, { _isFirstScreen: true });
212
+ // What the hydrate patch of an instance binds onto its first-screen handles.
213
+ const bind = (handle, jsFnId, execId) =>
214
+ hydrateJsFnHandles({ _jsFn: { _jsFnId: jsFnId } }, { _jsFn: handle }, execId);
215
+ const sent = () => link.of(WorkletEvents.runOnBackground).map(({ obj }) => obj);
216
+ try {
217
+ create('rb-a');
218
+ create('rb-b');
219
+ const handleA = firstScreenHandle();
220
+ const handleB = firstScreenHandle();
221
+ const lateHandleB = firstScreenHandle();
222
+
223
+ // Both instances call from their first frames before any hydration.
224
+ void runOnBackground(handleA)();
225
+ void runOnBackground(handleB)();
226
+
227
+ // `rb-a` hydrates first.
228
+ bind(handleA, 1, 101);
229
+ expect(commit('rb-a', 1, true).status).toBe('applied');
230
+ expect(sent()).toEqual([{ _jsFnId: 1, _execId: 101 }]);
231
+
232
+ // `rb-b` is still waiting and calls again from its first frame.
233
+ void runOnBackground(lateHandleB)();
234
+
235
+ // `rb-b` hydrates: both of its calls should reach the background now.
236
+ bind(handleB, 2, 202);
237
+ bind(lateHandleB, 3, 202);
238
+ expect(commit('rb-b', 1, true).status).toBe('applied');
239
+ expect(sent()).toEqual([
240
+ { _jsFnId: 1, _execId: 101 },
241
+ { _jsFnId: 2, _execId: 202 },
242
+ { _jsFnId: 3, _execId: 202 },
243
+ ]);
244
+ } finally {
245
+ native.fire('__DestroyTransfer', { transferId: 'rb-a' });
246
+ native.fire('__DestroyTransfer', { transferId: 'rb-b' });
247
+ resetFunctionCallReturnListener();
248
+ globalThis.lynxWorkletImpl = previousImpl;
249
+ SystemInfo.lynxSdkVersion = previousSdkVersion;
250
+ }
251
+ });
252
+
253
+ it('keeps its elements on an update and re-renders them on a reload', () => {
254
+ const element = () => elementTree.root.children.find(child => child.props['transfer-id'] === 'u');
255
+ const text = () => element().children[0].children[0].children[0].props.text;
256
+ native.fire('__CreateTransfer', { transferId: 'u', componentName: 'Bubble', initialProps: { text: 'a' } });
257
+ const frames = link.of('__TransferFirstFrame').length;
258
+ const view = element().children[0];
259
+ expect(commit('u', 1, true).status).toBe('applied');
260
+
261
+ // The background renders updates; the main thread only forwards them.
262
+ native.fire('__UpdateTransfer', { transferId: 'u', props: { text: 'b' } });
263
+ expect(link.of('__UpdateTransfer')).toEqual([{ transferId: 'u', props: { text: 'b' } }]);
264
+ expect(link.of('__TransferFirstFrame')).toHaveLength(frames);
265
+ expect(text()).toBe('a');
266
+ expect(commit('u', 2)).toEqual({ transferId: 'u', version: 0, seq: 2, status: 'applied' });
267
+
268
+ // A reload renders the latest props into the same elements and re-syncs the first frame.
269
+ const reloads = link.of('__ReloadTransfer').length;
270
+ native.fire('__ReloadTransfer', { transferId: 'u', props: { text: 'c' } });
271
+ expect(link.of('__ReloadTransfer').at(-1)).toEqual({ transferId: 'u', props: { text: 'c' } });
272
+ expect(link.of('__TransferFirstFrame')).toHaveLength(frames + 1);
273
+ expect(element().children[0]).toBe(view);
274
+ expect(text()).toBe('c');
275
+ expect(commit('u', 1, true, 1).status).toBe('applied');
276
+ native.fire('__DestroyTransfer', { transferId: 'u' });
277
+
278
+ // Updates and reloads for unknown or destroyed instances are ignored.
279
+ native.fire('__UpdateTransfer', { transferId: 'u', props: { text: 'd' } });
280
+ native.fire('__UpdateTransfer', { transferId: 'missing', props: {} });
281
+ native.fire('__ReloadTransfer', { transferId: 'u', props: { text: 'e' } });
282
+ native.fire('__ReloadTransfer', { transferId: 'missing', props: {} });
283
+ expect(link.of('__UpdateTransfer')).toHaveLength(1);
284
+ expect(link.of('__ReloadTransfer')).toHaveLength(reloads + 1);
285
+ });
194
286
  });
@@ -3,16 +3,23 @@
3
3
  // LICENSE file in the root directory of this source tree.
4
4
  // Background side of the transfer protocol. The first `registerComponent` fixes
5
5
  // the thread, so the main thread side lives in `transfer.mts.test.jsx`.
6
- import { render } from 'preact';
6
+ import { options, render } from 'preact';
7
+ import { useEffect, useLayoutEffect } from 'preact/hooks';
7
8
  import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
8
9
 
9
- import { root, useState } from '../../../src/index';
10
+ import {
11
+ resetBackgroundFunctionRuntime,
12
+ runBackgroundFunction,
13
+ } from '../../../src/core/background-function/run-on-background';
14
+ import { runOnMainThread, root, useState } from '../../../src/index';
15
+ import { resetFunctionCallReturnListener } from '../../../src/core/thread-function-call/return-value';
10
16
  import { TransferRegistry } from '../../../src/internal';
11
17
  import { __root } from '../../../src/root';
12
18
  import {
13
19
  BackgroundSnapshotInstance,
14
20
  backgroundSnapshotInstanceManager,
15
21
  } from '../../../src/snapshot/snapshot/backgroundSnapshot';
22
+ import { WorkletEvents } from '../../../src/worklet-runtime/bindings/events';
16
23
  import { globalEnvManager } from '../utils/envManager';
17
24
  import { waitSchedule } from '../utils/nativeMethod';
18
25
 
@@ -58,7 +65,7 @@ function Page() {
58
65
  }
59
66
 
60
67
  /** Serializes the newest transfer root the way the main thread first frame would. */
61
- function firstFrame() {
68
+ function firstFrame(rootId) {
62
69
  const roots = [...backgroundSnapshotInstanceManager.values.values()].filter(si => si.type === 'root');
63
70
  const toJSON = si => ({
64
71
  id: si.__id,
@@ -66,7 +73,10 @@ function firstFrame() {
66
73
  values: si.__values,
67
74
  children: si.childNodes.length ? si.childNodes.map(toJSON) : undefined,
68
75
  });
69
- return JSON.stringify(toJSON(roots.reduce((a, b) => (a.__id > b.__id ? a : b))));
76
+ const transferRoot = rootId === undefined
77
+ ? roots.reduce((a, b) => (a.__id > b.__id ? a : b))
78
+ : roots.find(root => root.__id === rootId);
79
+ return JSON.stringify(toJSON(transferRoot));
70
80
  }
71
81
  function commits(transferId) {
72
82
  return link.of('__TransferCommit').filter(packet => packet.transferId === transferId);
@@ -126,8 +136,8 @@ describe('transfer (background thread)', () => {
126
136
  expect(commits('1')[1]).toMatchObject({ seq: 2, kind: 'update' });
127
137
  expect(JSON.stringify(commits('1')[1].patchList)).toContain('a:1');
128
138
 
129
- // Like a template reload, a props update remounts the component and waits for a new first frame.
130
- link.fire('__SetTransferProps', { transferId: '1', props: { text: 'b' } });
139
+ // Like a template reload, a reload remounts the component and waits for a new first frame.
140
+ link.fire('__ReloadTransfer', { transferId: '1', props: { text: 'b' } });
131
141
  ack('1', 2);
132
142
  expect(commits('1')).toHaveLength(2);
133
143
  const frame = firstFrame();
@@ -158,7 +168,7 @@ describe('transfer (background thread)', () => {
158
168
  // Disposed by the main thread: torn down without echoing back.
159
169
  link.fire('__DestroyTransfer', { transferId: '1' });
160
170
  expect(link.of('__TransferDisposed')).toHaveLength(1);
161
- link.fire('__SetTransferProps', { transferId: '1', props: { text: 'd' } });
171
+ link.fire('__ReloadTransfer', { transferId: '1', props: { text: 'd' } });
162
172
  expect(commits('1')).toHaveLength(3);
163
173
 
164
174
  link.fire('__CreateTransfer', { transferId: '3', componentName: 'Missing', initialProps: {} });
@@ -181,8 +191,8 @@ describe('transfer (background thread)', () => {
181
191
  await waitSchedule();
182
192
  expect(commits('4')).toHaveLength(1);
183
193
 
184
- // A props update releases the in-flight and queued commits; their results no longer match.
185
- link.fire('__SetTransferProps', { transferId: '4', props: { text: 'f' } });
194
+ // A reload releases the in-flight and queued commits; their results no longer match.
195
+ link.fire('__ReloadTransfer', { transferId: '4', props: { text: 'f' } });
186
196
  ack('4', 1);
187
197
  link.fire('__TransferFirstFrame', { transferId: '4', snapshot: emptyFrame(-102) });
188
198
  expect(commits('4')).toMatchObject([{ version: 0, seq: 1 }, { version: 1, seq: 1, kind: 'hydrate' }]);
@@ -202,6 +212,201 @@ describe('transfer (background thread)', () => {
202
212
  expect(reportError).toHaveBeenCalledWith(new Error('Commit rendered outside a transfer instance'));
203
213
  });
204
214
 
215
+ it('keeps pre-hydration render and effect worklets with their instance across reuse', async () => {
216
+ const sdkVersion = SystemInfo.lynxSdkVersion;
217
+ SystemInfo.lynxSdkVersion = '4.3';
218
+ const completed = [];
219
+ const callback = vi.fn();
220
+ const staleCleanup = vi.fn();
221
+ const initialize = { _wkltId: 'initialize', _jsFn: { callback: { _fn: callback, _jsFnId: 1 } } };
222
+ const call = (label) => void runOnMainThread(initialize)(label).then(() => completed.push(label));
223
+ const runCallback = execId =>
224
+ runBackgroundFunction({ obj: { _execId: execId, _jsFnId: 1 }, params: [], resolveId: 0 });
225
+ let updateA;
226
+ let updateB;
227
+ let flushEffects;
228
+ const requestAnimationFrame = options.requestAnimationFrame;
229
+ function Card({ name }) {
230
+ const [count, setCount] = useState(0);
231
+ if (name === 'a') updateA = setCount;
232
+ if (name === 'b') updateB = setCount;
233
+ call(`${name}:render:${count}`);
234
+ useEffect(() => {
235
+ if (name === 'a' && count === 1) {
236
+ call('a:effect');
237
+ return () => call('a:effect-cleanup');
238
+ }
239
+ if (name === 'a' && count === 2) {
240
+ return () => {
241
+ staleCleanup();
242
+ call('a:stale-effect-cleanup');
243
+ };
244
+ }
245
+ }, [count]);
246
+ useLayoutEffect(() => {
247
+ call(`${name}:layout`);
248
+ if (name !== 'a') return;
249
+ setCount(1);
250
+ return () => call('a:cleanup');
251
+ }, []);
252
+ return <text>{`${name}:${count}`}</text>;
253
+ }
254
+ const calls = (id, index) => commits(id)[index].patchList.delayedRunOnMainThreadData;
255
+ const worklets = (id, index) => calls(id, index).map(({ params }) => params[0]);
256
+ const returnFrom = (id, index) => {
257
+ for (const { resolveId } of calls(id, index)) {
258
+ link.fire(WorkletEvents.FunctionCallRet, { resolveId });
259
+ }
260
+ };
261
+ TransferRegistry.registerComponent('Worklets', () => Card);
262
+ try {
263
+ options.requestAnimationFrame = flush => {
264
+ flushEffects = flush;
265
+ };
266
+ const listenersBeforeFirstFrame = link.count();
267
+ link.fire('__CreateTransfer', { transferId: 'work-a', componentName: 'Worklets', initialProps: { name: 'a' } });
268
+ await waitSchedule();
269
+ const frameA = firstFrame();
270
+ link.fire('__CreateTransfer', { transferId: 'work-b', componentName: 'Worklets', initialProps: { name: 'b' } });
271
+ await waitSchedule();
272
+ expect(commits('work-a')).toHaveLength(0);
273
+ expect(commits('work-b')).toHaveLength(0);
274
+ expect(link.count()).toBe(listenersBeforeFirstFrame);
275
+ link.fire('__TransferFirstFrame', { transferId: 'work-b', snapshot: firstFrame() });
276
+ expect(worklets('work-b', 0)).toEqual(['b:render:0', 'b:layout']);
277
+ ack('work-b', 1);
278
+ updateB(1);
279
+ await waitSchedule();
280
+ expect(worklets('work-b', 1)).toEqual(['b:render:1']);
281
+ returnFrom('work-b', 1);
282
+ ack('work-b', 2);
283
+ flushEffects();
284
+ expect(link.of(WorkletEvents.runWorkletCtx)).not.toContainEqual(
285
+ expect.objectContaining({ params: ['a:effect'] }),
286
+ );
287
+ updateA(2);
288
+ await waitSchedule();
289
+ flushEffects();
290
+ expect(link.of(WorkletEvents.runWorkletCtx)).not.toContainEqual(
291
+ expect.objectContaining({ params: ['a:effect-cleanup'] }),
292
+ );
293
+ link.fire('__TransferFirstFrame', { transferId: 'work-a', snapshot: frameA });
294
+ expect(worklets('work-a', 0)).toEqual([
295
+ 'a:render:0',
296
+ 'a:layout',
297
+ 'a:render:1',
298
+ 'a:effect',
299
+ 'a:render:2',
300
+ 'a:effect-cleanup',
301
+ ]);
302
+ expect(new Set(calls('work-a', 0).map(({ worklet }) => worklet._execId)).size).toBe(6);
303
+ const lastExecId = calls('work-a', 0).at(-1).worklet._execId;
304
+ ack('work-a', 1);
305
+ link.fire('__ReloadTransfer', { transferId: 'work-a', props: { name: 'reused' } });
306
+ runCallback(calls('work-a', 0)[0].worklet._execId);
307
+ expect(callback).toHaveBeenCalledOnce();
308
+ await waitSchedule();
309
+ flushEffects();
310
+ expect(staleCleanup).toHaveBeenCalledOnce();
311
+ expect(link.of(WorkletEvents.runWorkletCtx)).not.toContainEqual(
312
+ expect.objectContaining({ params: ['a:stale-effect-cleanup'] }),
313
+ );
314
+ const replacementFrame = firstFrame(JSON.parse(frameA).id);
315
+ expect(replacementFrame).toContain('reused:0');
316
+ link.fire('__TransferFirstFrame', { transferId: 'work-a', snapshot: replacementFrame });
317
+ expect(commits('work-a')[1]).toMatchObject({ version: 1, seq: 1, kind: 'hydrate' });
318
+ expect(worklets('work-a', 1)).toEqual(['reused:render:0', 'reused:layout']);
319
+ expect(calls('work-a', 1)[0].worklet._execId).toBe(lastExecId + 1);
320
+ returnFrom('work-a', 0);
321
+ returnFrom('work-b', 0);
322
+ await waitSchedule();
323
+ expect(completed).toEqual(['b:render:1', 'b:render:0', 'b:layout']);
324
+ link.fire(WorkletEvents.FunctionCallRet, { resolveId: calls('work-a', 1)[0].resolveId });
325
+ ack('work-a', 1, 'failed', 1);
326
+ returnFrom('work-a', 1);
327
+ await waitSchedule();
328
+ expect(completed).toEqual(['b:render:1', 'b:render:0', 'b:layout', 'reused:render:0']);
329
+
330
+ const lastSentExecId = calls('work-a', 1).at(-1).worklet._execId;
331
+ link.fire('__CreateTransfer', { transferId: 'work-c', componentName: 'Worklets', initialProps: { name: 'c' } });
332
+ link.fire('__DestroyTransfer', { transferId: 'work-c' });
333
+ expect(commits('work-c')).toHaveLength(0);
334
+
335
+ call('outside-render');
336
+ expect(link.of(WorkletEvents.runWorkletCtx).at(-1)).toMatchObject({
337
+ params: ['outside-render'],
338
+ worklet: { _execId: lastSentExecId + 1 },
339
+ });
340
+ } finally {
341
+ link.fire('__DestroyTransfer', { transferId: 'work-a' });
342
+ link.fire('__DestroyTransfer', { transferId: 'work-b' });
343
+ flushEffects?.();
344
+ options.requestAnimationFrame = requestAnimationFrame;
345
+ resetFunctionCallReturnListener();
346
+ resetBackgroundFunctionRuntime();
347
+ SystemInfo.lynxSdkVersion = sdkVersion;
348
+ }
349
+ });
350
+
351
+ it('updates props in place and keeps state, while a reload resets it', async () => {
352
+ let mounts = 0;
353
+ let setN;
354
+ function Streamed(props) {
355
+ const [mounted, setMounted] = useState(false);
356
+ const [n, setNState] = useState(0);
357
+ setN = setNState;
358
+ useEffect(() => {
359
+ mounts++;
360
+ setMounted(true);
361
+ }, []);
362
+ return mounted ? <text>{`${props.text}:${n}`}</text> : null;
363
+ }
364
+ TransferRegistry.registerComponent('Streamed', () => Streamed);
365
+ link.fire('__CreateTransfer', { transferId: 's', componentName: 'Streamed', initialProps: { text: 'a' } });
366
+ link.fire('__TransferFirstFrame', { transferId: 's', snapshot: firstFrame() });
367
+ ack('s', 1);
368
+ await waitSchedule();
369
+ expect(mounts).toBe(1);
370
+ expect(JSON.stringify(commits('s')[1].patchList)).toContain('a:0');
371
+ ack('s', 2);
372
+
373
+ // An update re-renders the mounted component with new props and keeps its state.
374
+ link.fire('__UpdateTransfer', { transferId: 's', props: { text: 'b' } });
375
+ expect(commits('s')[2]).toMatchObject({ version: 0, seq: 3, kind: 'update' });
376
+ expect(JSON.stringify(commits('s')[2].patchList)).toContain('b:0');
377
+ ack('s', 3);
378
+ // Later commits still belong to the instance.
379
+ const errors = reportError.mock.calls.length;
380
+ setN(1);
381
+ await waitSchedule();
382
+ expect(reportError.mock.calls.length).toBe(errors);
383
+ expect(JSON.stringify(commits('s')[3].patchList)).toContain('b:1');
384
+ ack('s', 4);
385
+ expect(mounts).toBe(1);
386
+
387
+ // A reload remounts it and resets its state; updates before the new first frame are kept.
388
+ link.fire('__ReloadTransfer', { transferId: 's', props: { text: 'c' } });
389
+ link.fire('__UpdateTransfer', { transferId: 's', props: { text: 'd' } });
390
+ expect(commits('s')).toHaveLength(4);
391
+ link.fire('__TransferFirstFrame', { transferId: 's', snapshot: firstFrame() });
392
+ expect(commits('s')[4]).toMatchObject({ version: 1, seq: 1, kind: 'hydrate' });
393
+ ack('s', 1, 'applied', 1);
394
+ await waitSchedule();
395
+ expect(mounts).toBe(2);
396
+ setN(5);
397
+ await waitSchedule();
398
+ expect(JSON.stringify(commits('s').at(-1).patchList)).toContain('d:5');
399
+ link.fire('__DestroyTransfer', { transferId: 's' });
400
+
401
+ // Updates for destroyed or unknown instances render nothing.
402
+ const sent = commits('s').length;
403
+ link.fire('__UpdateTransfer', { transferId: 's', props: { text: 'e' } });
404
+ link.fire('__UpdateTransfer', { transferId: 'missing', props: {} });
405
+ await waitSchedule();
406
+ expect(commits('s')).toHaveLength(sent);
407
+ expect(mounts).toBe(2);
408
+ });
409
+
205
410
  it('removes its listeners when the lifetime is destroyed', () => {
206
411
  native.fire('__DestroyLifetime', {});
207
412
  expect(link.count()).toBe(0);
@@ -10,6 +10,7 @@ import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vite
10
10
  import { replaceCommitHook } from '../../../src/snapshot/lifecycle/patch/commit';
11
11
  import { injectUpdateMainThread } from '../../../src/snapshot/lifecycle/patch/updateMainThread';
12
12
  import { installComponentCompat } from '../../../src/core/component';
13
+ import { __ComponentIsPolyfill } from '../../../src/internal';
13
14
  import { __root } from '../../../src/root';
14
15
  import {
15
16
  setupPage,
@@ -39,10 +40,57 @@ afterEach(() => {
39
40
  vi.runAllTimers();
40
41
  vi.useRealTimers();
41
42
  vi.restoreAllMocks();
43
+ vi.unstubAllGlobals();
42
44
  elementTree.clear();
43
45
  });
44
46
 
45
47
  describe('suspense', () => {
48
+ it('renders an empty component and reports an invalid legacy component URL', () => {
49
+ const reportError = vi.spyOn(lynx, 'reportError').mockImplementation(() => {});
50
+ __root.__jsx = createElement(__ComponentIsPolyfill, { is: null });
51
+ renderPage();
52
+ expect(reportError).toHaveBeenCalledWith(expect.objectContaining({
53
+ message: expect.stringContaining('You must provide a string'),
54
+ }));
55
+ });
56
+
57
+ it('loads a legacy component asynchronously and remounts it when its URL changes', async () => {
58
+ globalEnvManager.switchToBackground();
59
+ const query = vi.fn();
60
+ const mount = vi.fn();
61
+ const renderChild = vi.fn();
62
+ function Child({ label }) {
63
+ useState(() => mount(label));
64
+ renderChild(label);
65
+ return null;
66
+ }
67
+ const app = lynx.getApp();
68
+ vi.stubGlobal('lynx', {
69
+ ...lynx,
70
+ QueryComponent: query,
71
+ getApp: () => ({ ...app, getDynamicComponentExports: () => ({ default: Child }) }),
72
+ });
73
+
74
+ render(createElement(__ComponentIsPolyfill, { is: 'one', label: 'first' }), __root);
75
+ expect(query).toHaveBeenCalledWith('one', expect.any(Function));
76
+ expect(renderChild).not.toHaveBeenCalled();
77
+ query.mock.calls[0][1]({ code: 0, detail: { schema: 'one' } });
78
+ await vi.runAllTimersAsync();
79
+ expect(renderChild).toHaveBeenLastCalledWith('first');
80
+
81
+ render(createElement(__ComponentIsPolyfill, { is: 'one', label: 'updated' }), __root);
82
+ expect(query).toHaveBeenCalledTimes(1);
83
+ expect(mount.mock.calls).toEqual([['first']]);
84
+ expect(renderChild).toHaveBeenLastCalledWith('updated');
85
+
86
+ render(createElement(__ComponentIsPolyfill, { is: 'two', label: 'second' }), __root);
87
+ expect(query).toHaveBeenLastCalledWith('two', expect.any(Function));
88
+ query.mock.calls[1][1]({ code: 0, detail: { schema: 'two' } });
89
+ await vi.runAllTimersAsync();
90
+ expect(mount.mock.calls).toEqual([['first'], ['second']]);
91
+ expect(renderChild).toHaveBeenLastCalledWith('second');
92
+ });
93
+
46
94
  /**
47
95
  * Tests the basic functionality of the `Suspense` component.
48
96
  *
@@ -105,6 +105,8 @@ export class EnvManager {
105
105
  workletImpl._jsFunctionLifecycleManager = workletImpl._jsFunctionLifecycleManager.recreate();
106
106
  }
107
107
  workletImpl?._runOnBackgroundDelayImpl?.clearDelayedBackgroundFunctions?.();
108
+ workletImpl?._refImpl?.clearFirstScreenWorkletRefMap?.();
109
+ workletImpl?._eventDelayImpl?.clearDelayedWorklets?.(true);
108
110
  getJSModule('GlobalEventEmitter')?.clear();
109
111
  this.switchToBackground();
110
112
  this.switchToMainThread();
@@ -97,4 +97,25 @@ describe('DelayWorkletEvent', () => {
97
97
  vi.runAllTimers();
98
98
  expect(fn).toHaveBeenCalledExactlyOnceWith(expect.anything(), 'first');
99
99
  });
100
+
101
+ it('replays scheduled events across normal hydration clear, but cancels them on reload/dispose clear', () => {
102
+ const fn = vi.fn();
103
+ globalThis.registerWorklet('main-thread', '1', fn);
104
+ const makeEvent = () => ({ currentTarget: { elementRefptr: 'element' } });
105
+
106
+ // Normal hydration finishes synchronously after scheduling replay: timer must still run.
107
+ globalThis.lynxWorkletImpl._eventDelayImpl.delayExecUntilJsReady('1', [makeEvent(), 'hydrated']);
108
+ globalThis.lynxWorkletImpl._eventDelayImpl.runDelayedWorklet({ _wkltId: '1' }, 'element');
109
+ globalThis.lynxWorkletImpl._eventDelayImpl.clearDelayedWorklets();
110
+ vi.runAllTimers();
111
+ expect(fn).toHaveBeenCalledExactlyOnceWith(expect.anything(), 'hydrated');
112
+
113
+ // Reload/dispose invalidates already-scheduled replays so old callbacks never run.
114
+ fn.mockClear();
115
+ globalThis.lynxWorkletImpl._eventDelayImpl.delayExecUntilJsReady('1', [makeEvent(), 'stale']);
116
+ globalThis.lynxWorkletImpl._eventDelayImpl.runDelayedWorklet({ _wkltId: '1' }, 'element');
117
+ globalThis.lynxWorkletImpl._eventDelayImpl.clearDelayedWorklets(true);
118
+ vi.runAllTimers();
119
+ expect(fn).not.toHaveBeenCalled();
120
+ });
100
121
  });