@lynx-js/react 0.129.0 → 0.129.1

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 (206) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/components/tsconfig.tsbuildinfo +1 -1
  3. package/package.json +3 -4
  4. package/refresh/.turbo/turbo-build.log +1 -1
  5. package/runtime/__test__/core/hooks/useLynxGlobalEventListener.test.jsx +1 -1
  6. package/runtime/__test__/element-template/imports/no-legacy-imports.test.ts +7 -6
  7. package/runtime/__test__/element-template/internal/legacy-internal-guardrail.test.ts +1 -2
  8. package/runtime/__test__/element-template/native/main-thread-api.test.ts +5 -2
  9. package/runtime/__test__/element-template/native/mts-destroy.test.ts +83 -0
  10. package/runtime/__test__/element-template/native/reload-dual-thread-communication.test.ts +3 -0
  11. package/runtime/__test__/element-template/native/reload.test.ts +31 -2
  12. package/runtime/__test__/element-template/runtime/background/update-timing.test.ts +15 -0
  13. package/runtime/__test__/element-template/runtime/patch/element-template-patch.test.tsx +197 -7
  14. package/runtime/__test__/element-template/runtime/patch/update-timing.test.ts +4 -1
  15. package/runtime/__test__/element-template/runtime/render/render-direct-suspense.test.ts +4 -1
  16. package/runtime/__test__/element-template/runtime/render/render-direct.test.ts +4 -1
  17. package/runtime/__test__/element-template/runtime/render/render-main-thread.test.ts +101 -1
  18. package/runtime/__test__/element-template/runtime/template/element-template-handle.test.ts +32 -0
  19. package/runtime/__test__/element-template/runtime/template/main-thread-dynamic-attr-state.test.ts +121 -26
  20. package/runtime/__test__/element-template/test-utils/debug/envManager.ts +8 -5
  21. package/runtime/__test__/element-template/test-utils/mock/mockNativePapi.ts +35 -2
  22. package/runtime/__test__/guardrails/snapshot-containment.test.ts +45 -11
  23. package/runtime/__test__/shared/component-stack.test.ts +211 -0
  24. package/runtime/__test__/snapshot/debug/formatPatch.test.ts +0 -8
  25. package/runtime/__test__/snapshot/gesture/prepareGestureForCommit.test.js +1 -1
  26. package/runtime/__test__/snapshot/lynx/timing.test.jsx +3 -0
  27. package/runtime/__test__/snapshot/preact.test.jsx +0 -3
  28. package/runtime/__test__/snapshot/snapshotPatch.test.jsx +0 -33
  29. package/runtime/__test__/worklet-runtime/jsFunctionLifecycle.test.js +12 -0
  30. package/runtime/__test__/worklet-runtime/loadRuntime.test.js +68 -0
  31. package/runtime/__test__/worklet-runtime/workletRuntime.test.js +30 -0
  32. package/runtime/lazy/element-template-internal.js +0 -1
  33. package/runtime/lazy/internal.js +1 -1
  34. package/runtime/lazy/jsx-dev-runtime.js +1 -1
  35. package/runtime/lazy/jsx-runtime.js +1 -1
  36. package/runtime/lazy/legacy-react-runtime.js +1 -1
  37. package/runtime/lazy/react-lepus.js +1 -1
  38. package/runtime/lazy/react.js +1 -1
  39. package/runtime/lib/core/capture-main-thread-object.js +2 -1
  40. package/runtime/lib/core/capture-main-thread-object.js.map +1 -1
  41. package/runtime/lib/core/compat/legacy-react-runtime.js +1 -1
  42. package/runtime/lib/core/compat/legacy-react-runtime.js.map +1 -1
  43. package/runtime/lib/core/lynx/lazy-bundle.js +1 -1
  44. package/runtime/lib/core/lynx/lazy-bundle.js.map +1 -1
  45. package/runtime/lib/core/lynx-data-processors.d.ts +125 -1
  46. package/runtime/lib/core/lynx-data-processors.js +3 -0
  47. package/runtime/lib/core/lynx-data-processors.js.map +1 -1
  48. package/runtime/lib/core/runtime-destroy.js +1 -1
  49. package/runtime/lib/core/runtime-destroy.js.map +1 -1
  50. package/runtime/lib/document.js +0 -5
  51. package/runtime/lib/document.js.map +1 -1
  52. package/runtime/lib/element-template/background/commit-hook.js +11 -12
  53. package/runtime/lib/element-template/background/commit-hook.js.map +1 -1
  54. package/runtime/lib/element-template/client/root.d.ts +1 -1
  55. package/runtime/lib/element-template/client/root.js.map +1 -1
  56. package/runtime/lib/element-template/index.d.ts +2 -2
  57. package/runtime/lib/element-template/index.js.map +1 -1
  58. package/runtime/lib/element-template/internal.d.ts +1 -1
  59. package/runtime/lib/element-template/internal.js +0 -13
  60. package/runtime/lib/element-template/internal.js.map +1 -1
  61. package/runtime/lib/element-template/lynx/env.js.map +1 -1
  62. package/runtime/lib/element-template/native/flush.d.ts +1 -0
  63. package/runtime/lib/element-template/native/flush.js +9 -0
  64. package/runtime/lib/element-template/native/flush.js.map +1 -0
  65. package/runtime/lib/element-template/native/main-thread-api.js +3 -7
  66. package/runtime/lib/element-template/native/main-thread-api.js.map +1 -1
  67. package/runtime/lib/element-template/native/mts-destroy.js +8 -2
  68. package/runtime/lib/element-template/native/mts-destroy.js.map +1 -1
  69. package/runtime/lib/element-template/native/patch-listener.js +57 -50
  70. package/runtime/lib/element-template/native/patch-listener.js.map +1 -1
  71. package/runtime/lib/element-template/native/reload-main-thread.js +2 -1
  72. package/runtime/lib/element-template/native/reload-main-thread.js.map +1 -1
  73. package/runtime/lib/element-template/protocol/types.js.map +1 -1
  74. package/runtime/lib/element-template/runtime/page/root-instance.d.ts +0 -1
  75. package/runtime/lib/element-template/runtime/page/root-instance.js.map +1 -1
  76. package/runtime/lib/element-template/runtime/patch.js +4 -0
  77. package/runtime/lib/element-template/runtime/patch.js.map +1 -1
  78. package/runtime/lib/element-template/runtime/render/render-components.js +4 -4
  79. package/runtime/lib/element-template/runtime/render/render-components.js.map +1 -1
  80. package/runtime/lib/element-template/runtime/render/render-main-thread.js +2 -0
  81. package/runtime/lib/element-template/runtime/render/render-main-thread.js.map +1 -1
  82. package/runtime/lib/element-template/runtime/template/main-thread-background-function.js +8 -1
  83. package/runtime/lib/element-template/runtime/template/main-thread-background-function.js.map +1 -1
  84. package/runtime/lib/element-template/runtime/template/main-thread-dynamic-attr-state.d.ts +1 -0
  85. package/runtime/lib/element-template/runtime/template/main-thread-dynamic-attr-state.js +41 -21
  86. package/runtime/lib/element-template/runtime/template/main-thread-dynamic-attr-state.js.map +1 -1
  87. package/runtime/lib/element-template/runtime/template/main-thread-ref-ctx.d.ts +1 -1
  88. package/runtime/lib/element-template/runtime/template/main-thread-ref-ctx.js.map +1 -1
  89. package/runtime/lib/internal.d.ts +1 -1
  90. package/runtime/lib/internal.js +1 -1
  91. package/runtime/lib/internal.js.map +1 -1
  92. package/runtime/lib/lynx-api.d.ts +2 -125
  93. package/runtime/lib/lynx-api.js.map +1 -1
  94. package/runtime/lib/shared/component-stack.d.ts +0 -4
  95. package/runtime/lib/shared/component-stack.js +21 -5
  96. package/runtime/lib/shared/component-stack.js.map +1 -1
  97. package/runtime/lib/snapshot/gesture/{processGestureBagkround.js → processGestureBackground.js} +1 -1
  98. package/runtime/lib/snapshot/gesture/processGestureBackground.js.map +1 -0
  99. package/runtime/lib/snapshot/lifecycle/patch/snapshotPatch.d.ts +0 -1
  100. package/runtime/lib/snapshot/lifecycle/patch/snapshotPatch.js +0 -5
  101. package/runtime/lib/snapshot/lifecycle/patch/snapshotPatch.js.map +1 -1
  102. package/runtime/lib/snapshot/lifecycle/patch/snapshotPatchApply.js +0 -10
  103. package/runtime/lib/snapshot/lifecycle/patch/snapshotPatchApply.js.map +1 -1
  104. package/runtime/lib/snapshot/lifecycle/patch/updateMainThread.js +56 -51
  105. package/runtime/lib/snapshot/lifecycle/patch/updateMainThread.js.map +1 -1
  106. package/runtime/lib/snapshot/list/listUpdateInfo.js +0 -30
  107. package/runtime/lib/snapshot/list/listUpdateInfo.js.map +1 -1
  108. package/runtime/lib/snapshot/lynx/calledByNative.js +11 -8
  109. package/runtime/lib/snapshot/lynx/calledByNative.js.map +1 -1
  110. package/runtime/lib/snapshot/renderToOpcodes/hydrate.js +0 -52
  111. package/runtime/lib/snapshot/renderToOpcodes/hydrate.js.map +1 -1
  112. package/runtime/lib/snapshot/renderToOpcodes/index.js +10 -10
  113. package/runtime/lib/snapshot/renderToOpcodes/index.js.map +1 -1
  114. package/runtime/lib/snapshot/renderToOpcodes/opcodes.js +0 -51
  115. package/runtime/lib/snapshot/renderToOpcodes/opcodes.js.map +1 -1
  116. package/runtime/lib/snapshot/snapshot/backgroundSnapshot.js +1 -1
  117. package/runtime/lib/snapshot/snapshot/backgroundSnapshot.js.map +1 -1
  118. package/runtime/lib/tsconfig.tsbuildinfo +1 -1
  119. package/runtime/lib/worklet-runtime/bindings/index.d.ts +1 -0
  120. package/runtime/lib/worklet-runtime/bindings/index.js +1 -0
  121. package/runtime/lib/worklet-runtime/bindings/index.js.map +1 -1
  122. package/runtime/lib/worklet-runtime/bindings/loadRuntime.d.ts +8 -0
  123. package/runtime/lib/worklet-runtime/bindings/loadRuntime.js +23 -0
  124. package/runtime/lib/worklet-runtime/bindings/loadRuntime.js.map +1 -0
  125. package/runtime/lib/worklet-runtime/jsFunctionLifecycle.d.ts +2 -0
  126. package/runtime/lib/worklet-runtime/jsFunctionLifecycle.js +6 -0
  127. package/runtime/lib/worklet-runtime/jsFunctionLifecycle.js.map +1 -1
  128. package/runtime/lib/worklet-runtime/workletRuntime.js +2 -0
  129. package/runtime/lib/worklet-runtime/workletRuntime.js.map +1 -1
  130. package/runtime/package.json +2 -3
  131. package/runtime/src/core/capture-main-thread-object.ts +2 -1
  132. package/runtime/src/core/compat/legacy-react-runtime.ts +1 -1
  133. package/runtime/src/core/lynx/lazy-bundle.ts +1 -1
  134. package/runtime/src/core/lynx-data-processors.ts +124 -1
  135. package/runtime/src/core/runtime-destroy.ts +1 -1
  136. package/runtime/src/document.ts +0 -6
  137. package/runtime/src/element-template/background/commit-hook.ts +18 -12
  138. package/runtime/src/element-template/client/root.ts +1 -3
  139. package/runtime/src/element-template/index.ts +2 -2
  140. package/runtime/src/element-template/internal.ts +0 -20
  141. package/runtime/src/element-template/lynx/env.ts +1 -1
  142. package/runtime/src/element-template/native/flush.ts +10 -0
  143. package/runtime/src/element-template/native/main-thread-api.ts +3 -6
  144. package/runtime/src/element-template/native/mts-destroy.ts +7 -2
  145. package/runtime/src/element-template/native/patch-listener.ts +62 -57
  146. package/runtime/src/element-template/native/reload-main-thread.ts +2 -1
  147. package/runtime/src/element-template/protocol/types.ts +0 -13
  148. package/runtime/src/element-template/runtime/page/root-instance.ts +0 -1
  149. package/runtime/src/element-template/runtime/patch.ts +5 -0
  150. package/runtime/src/element-template/runtime/render/render-components.ts +3 -3
  151. package/runtime/src/element-template/runtime/render/render-main-thread.ts +2 -0
  152. package/runtime/src/element-template/runtime/template/main-thread-background-function.ts +8 -1
  153. package/runtime/src/element-template/runtime/template/main-thread-dynamic-attr-state.ts +51 -21
  154. package/runtime/src/element-template/runtime/template/main-thread-ref-ctx.ts +2 -2
  155. package/runtime/src/element-template/types.d.ts +6 -0
  156. package/runtime/src/internal.ts +1 -1
  157. package/runtime/src/lynx-api.ts +2 -124
  158. package/runtime/src/shared/component-stack.ts +22 -5
  159. package/runtime/src/snapshot/lifecycle/patch/snapshotPatch.ts +0 -5
  160. package/runtime/src/snapshot/lifecycle/patch/snapshotPatchApply.ts +0 -10
  161. package/runtime/src/snapshot/lifecycle/patch/updateMainThread.ts +62 -58
  162. package/runtime/src/snapshot/list/listUpdateInfo.ts +0 -52
  163. package/runtime/src/snapshot/lynx/calledByNative.ts +11 -9
  164. package/runtime/src/snapshot/renderToOpcodes/hydrate.ts +0 -58
  165. package/runtime/src/snapshot/renderToOpcodes/index.ts +8 -8
  166. package/runtime/src/snapshot/renderToOpcodes/opcodes.ts +0 -57
  167. package/runtime/src/snapshot/snapshot/backgroundSnapshot.ts +1 -1
  168. package/runtime/src/worklet-runtime/README.md +30 -10
  169. package/runtime/src/worklet-runtime/bindings/index.ts +2 -0
  170. package/runtime/src/worklet-runtime/bindings/loadRuntime.ts +25 -0
  171. package/runtime/src/worklet-runtime/jsFunctionLifecycle.ts +6 -0
  172. package/runtime/src/worklet-runtime/workletRuntime.ts +2 -0
  173. package/runtime/vitest.config.ts +0 -2
  174. package/testing-library/.turbo/turbo-build.log +6 -6
  175. package/testing-library/src/__tests__/act.test.jsx +0 -7
  176. package/testing-library/src/__tests__/alog.test.jsx +12 -54
  177. package/testing-library/src/__tests__/end-to-end.test.jsx +0 -7
  178. package/testing-library/src/__tests__/renderComponent.test.jsx +0 -14
  179. package/testing-library/src/__tests__/worklet.test.jsx +49 -0
  180. package/transform/.turbo/turbo-build$colon$wasm.log +98 -376
  181. package/transform/__test__/defines.spec.js +30 -0
  182. package/transform/__test__/object-methods.spec.js +79 -0
  183. package/transform/crates/swc_plugin_worklet/extract_ident.rs +99 -49
  184. package/transform/crates/swc_plugin_worklet/gen_stmt.rs +56 -48
  185. package/transform/crates/swc_plugin_worklet/lib.rs +393 -589
  186. package/transform/crates/swc_plugin_worklet/napi.rs +4 -6
  187. package/transform/crates/swc_plugin_worklet/tests/__swc_snapshots__/lib.rs/should_extract_member_expr_2_js.js +6 -1
  188. package/transform/crates/swc_plugin_worklet/tests/__swc_snapshots__/lib.rs/should_extract_member_expr_2_lepus.js +7 -1
  189. package/transform/crates/swc_plugin_worklet/tests/__swc_snapshots__/lib.rs/should_extract_member_expr_js.js +9 -0
  190. package/transform/crates/swc_plugin_worklet/tests/__swc_snapshots__/lib.rs/should_extract_member_expr_lepus.js +12 -1
  191. package/transform/crates/swc_plugin_worklet/tests/__swc_snapshots__/lib.rs/should_preserve_main_thread_objects_in_class_js.js +1 -1
  192. package/transform/crates/swc_plugin_worklet/tests/__swc_snapshots__/lib.rs/should_preserve_main_thread_objects_in_class_lepus.js +1 -1
  193. package/transform/dist/wasm.cjs +1 -1
  194. package/transform/package.json +0 -1
  195. package/transform/src/lib.rs +1 -1
  196. package/transform/swc-plugin-reactlynx/.turbo/turbo-build.log +113 -42
  197. package/transform/swc-plugin-reactlynx/src/lib.rs +1 -4
  198. package/transform/swc-plugin-reactlynx/swc_plugin_reactlynx.wasm +0 -0
  199. package/transform/swc-plugin-reactlynx-compat/.turbo/turbo-build.log +273 -66
  200. package/runtime/lib/snapshot/gesture/processGestureBagkround.js.map +0 -1
  201. package/runtime/lib/snapshot/worklet/hmr.d.ts +0 -1
  202. package/runtime/lib/snapshot/worklet/hmr.js +0 -28
  203. package/runtime/lib/snapshot/worklet/hmr.js.map +0 -1
  204. package/runtime/src/snapshot/worklet/hmr.ts +0 -34
  205. /package/runtime/lib/snapshot/gesture/{processGestureBagkround.d.ts → processGestureBackground.d.ts} +0 -0
  206. /package/runtime/src/snapshot/gesture/{processGestureBagkround.ts → processGestureBackground.ts} +0 -0
@@ -8,6 +8,7 @@ import {
8
8
  } from '../../../../src/element-template/main-thread-ref-init-value.js';
9
9
  import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
10
10
 
11
+ import { JsFunctionLifecycleManager } from '../../../../src/worklet-runtime/jsFunctionLifecycle.js';
11
12
  import { getReloadVersion, increaseReloadVersion } from '../../../../src/core/reload-version.js';
12
13
  import type { BackgroundElementTemplateInstance } from '../../../../src/element-template/background/instance.js';
13
14
  import { root } from '../../../../src/element-template/index.js';
@@ -41,6 +42,7 @@ import {
41
42
  } from '../../../../src/element-template/runtime/list/list.js';
42
43
  import {
43
44
  attachMainThreadDynamicAttrRefsForSubtree,
45
+ applyPendingMainThreadRefAttachments,
44
46
  clearMainThreadDynamicAttrState,
45
47
  detachMainThreadDynamicAttrRefsForSubtree,
46
48
  getMainThreadDynamicAttrState,
@@ -113,6 +115,7 @@ function createMaterializedListForFrontendTest(nativeId: number): FiberElement {
113
115
 
114
116
  const MT_EVENT_TEMPLATE = '_et_mt_event';
115
117
  const MT_REF_TEMPLATE = '_et_mt_ref';
118
+ const REF_TARGET = { id: 'materialized-ref-node' } as unknown as ElementRef;
116
119
 
117
120
  function registerMTEventSlotsForTemplate(templateType: string, ...slotIndexes: number[]): void {
118
121
  __etAttrPlanMap[templateType] = slotIndexes.flatMap(slotIndex => [
@@ -158,6 +161,8 @@ function seedMTRefState(
158
161
  attributeSlots[attrSlotIndex] = { type: 'main-thread-ref', value };
159
162
  initializeMainThreadDynamicAttrSlots(handleId, MT_REF_TEMPLATE, attributeSlots);
160
163
  attachMainThreadDynamicAttrRefsForSubtree([{ uid: handleId, ref: nativeRef }]);
164
+ vi.mocked(__GetElementByAttrSlot).mockReturnValue(REF_TARGET);
165
+ applyPendingMainThreadRefAttachments();
161
166
  }
162
167
 
163
168
  function installWorkletRefRuntime(): {
@@ -339,6 +344,43 @@ describe('ElementTemplate patch stream (apply)', () => {
339
344
  expect(mockFlushElementTree.mock.calls.length).toBeGreaterThan(0);
340
345
  });
341
346
 
347
+ it.each([false, true])('tracks setter input before Native and commits only on success (throws=%s)', (throws) => {
348
+ const previous = globalThis.lynxWorkletImpl;
349
+ const manager = new JsFunctionLifecycleManager();
350
+ const hydrate = vi.fn();
351
+ globalThis.lynxWorkletImpl = { ...previous, _jsFunctionLifecycleManager: manager, _hydrateCtx: hydrate };
352
+ const oldCtx = { _wkltId: 'tap', _execId: 30 };
353
+ const nextCtx = { _wkltId: 'tap', _execId: 31 };
354
+ elementTemplateRegistry.set(101, {} as ElementTemplateHandle);
355
+ seedMTEventState(101, 0, oldCtx);
356
+ const retain = vi.spyOn(manager, 'addRef');
357
+ const error = new Error('setter failed');
358
+ mockSetElementTemplateAttributeSlot.mockImplementationOnce((_native, _slot, value) => {
359
+ expect(value.value).toBe(nextCtx);
360
+ expect(retain).toHaveBeenCalledExactlyOnceWith(31, nextCtx);
361
+ expect(getMainThreadDynamicAttrState(101, 0)?.nativeHeldValue).toBe(oldCtx);
362
+ if (throws) throw error;
363
+ });
364
+ try {
365
+ const apply = () =>
366
+ applyElementTemplateUpdateCommands([
367
+ ElementTemplateUpdateOps.setMainThreadEvent,
368
+ 101,
369
+ 0,
370
+ { type: 'worklet', value: nextCtx },
371
+ ], true);
372
+ if (throws) expect(apply).toThrow(error);
373
+ else apply();
374
+ expect(getMainThreadDynamicAttrState(101, 0)?.nativeHeldValue).toBe(throws ? oldCtx : nextCtx);
375
+ expect(retain).toHaveBeenCalledExactlyOnceWith(31, nextCtx);
376
+ if (throws) expect(hydrate).not.toHaveBeenCalled();
377
+ else expect(hydrate).toHaveBeenCalledExactlyOnceWith(nextCtx, oldCtx);
378
+ } finally {
379
+ manager.dispose();
380
+ globalThis.lynxWorkletImpl = previous;
381
+ }
382
+ });
383
+
342
384
  it('records MTEvent state after setMainThreadEvent PAPI succeeds', () => {
343
385
  const targetId = 101;
344
386
  const nativeRef = {};
@@ -606,7 +648,11 @@ describe('ElementTemplate patch stream (apply)', () => {
606
648
  ]);
607
649
 
608
650
  expect(mockInsertElementTemplateNodeIntoSlot).toHaveBeenCalledWith(parentRef, 0, nativeRef, null);
609
- expect(updateWorkletRef).toHaveBeenCalledWith(ref, nativeRef);
651
+ expect(updateWorkletRef).not.toHaveBeenCalled();
652
+ applyPendingMainThreadRefAttachments();
653
+ const target = vi.mocked(__GetElementByAttrSlot).mock.results.at(-1)!.value;
654
+ expect(target).not.toBe(nativeRef);
655
+ expect(updateWorkletRef).toHaveBeenCalledWith(ref, target);
610
656
  expect(getMainThreadDynamicAttrState(handleId, 0)).toEqual({
611
657
  kind: 'mt-ref',
612
658
  value: ref,
@@ -761,19 +807,19 @@ describe('ElementTemplate patch stream (apply)', () => {
761
807
 
762
808
  expect(mockSetElementTemplateAttributeSlot).not.toHaveBeenCalled();
763
809
  expect(oldCleanup).toHaveBeenCalledTimes(1);
764
- const mountedCallback = runWorklet.mock.calls[0]?.[0] as typeof nextCallback & {
765
- _unmount?: () => void;
766
- };
810
+ const mountedCallback = runWorklet.mock.calls[0]?.[0] as typeof nextCallback;
767
811
  expect(mountedCallback).toEqual(expect.objectContaining({
768
812
  _wkltId: 'next-ref-callback',
769
813
  }));
770
- expect(runWorklet.mock.calls[0]?.[1]).toEqual([{ elementRefptr: nativeRef }]);
771
- expect(mountedCallback._unmount).toBe(nextCleanup);
814
+ expect(runWorklet.mock.calls[0]?.[1]).toEqual([{ elementRefptr: REF_TARGET }]);
815
+ expect(mountedCallback).toHaveProperty('_unmount', nextCleanup);
772
816
  expect(nextCallback).not.toHaveProperty('_unmount');
773
817
  expect(getMainThreadDynamicAttrState(targetId, 0)).toEqual({
774
818
  kind: 'mt-ref',
775
819
  value: mountedCallback,
776
820
  });
821
+ applyElementTemplateUpdateCommands([ElementTemplateUpdateOps.setMainThreadRef, targetId, 0, null]);
822
+ expect(nextCleanup).toHaveBeenCalledOnce();
777
823
  } finally {
778
824
  globalThis.runWorklet = previousRunWorklet;
779
825
  }
@@ -808,10 +854,11 @@ describe('ElementTemplate patch stream (apply)', () => {
808
854
  { type: 'main-thread-ref', value: nextCallback },
809
855
  ], true);
810
856
 
857
+ applyPendingMainThreadRefAttachments();
811
858
  expect(hydrateCtx).toHaveBeenCalledWith(nextCallback, oldCallback);
812
859
  expect(runDelayedWorklet).not.toHaveBeenCalled();
813
860
  expect(oldCleanup).toHaveBeenCalledTimes(1);
814
- expect(globalThis.runWorklet).toHaveBeenCalledWith(nextCallback, [{ elementRefptr: nativeRef }]);
861
+ expect(globalThis.runWorklet).toHaveBeenCalledWith(nextCallback, [{ elementRefptr: REF_TARGET }]);
815
862
  } finally {
816
863
  globalThis.runWorklet = previousRunWorklet;
817
864
  globalThis.lynxWorkletImpl = previousWorkletImpl;
@@ -845,6 +892,7 @@ describe('ElementTemplate patch stream (apply)', () => {
845
892
  { type: 'main-thread-ref', value: nextCallback },
846
893
  ], true);
847
894
 
895
+ applyPendingMainThreadRefAttachments();
848
896
  expect(hydrateCtx).toHaveBeenCalledWith(nextCallback, oldCallback);
849
897
  expect(globalThis.runWorklet).not.toHaveBeenCalled();
850
898
  expect(getMainThreadDynamicAttrState(targetId, 0)).toEqual({
@@ -1392,6 +1440,55 @@ describe('ElementTemplate patch stream (apply)', () => {
1392
1440
  }
1393
1441
  });
1394
1442
 
1443
+ it('cleans hydration handoff and propagates a ref callback error without running later work', () => {
1444
+ const handle = { id: 'throwing-ref-template' } as unknown as ElementTemplateHandle;
1445
+ const target = { id: 'inner-node' } as unknown as ElementRef;
1446
+ const callback = { _wkltId: 'throwing-ref' };
1447
+ const callbackError = new Error('ref callback failed');
1448
+ const runDelayedBackgroundFunctions = vi.fn();
1449
+ const clearFirstScreenWorkletRefMap = vi.fn();
1450
+ const runRunOnMainThreadTask = vi.fn();
1451
+ const previousWorkletImpl = globalThis.lynxWorkletImpl;
1452
+ const previousRunWorklet = globalThis.runWorklet;
1453
+ globalThis.lynxWorkletImpl = {
1454
+ ...previousWorkletImpl,
1455
+ _refImpl: { ...createMainThreadRefImplMock(), clearFirstScreenWorkletRefMap },
1456
+ _runOnBackgroundDelayImpl: { runDelayedBackgroundFunctions },
1457
+ _runRunOnMainThreadTask: runRunOnMainThreadTask,
1458
+ };
1459
+ globalThis.runWorklet = vi.fn(() => {
1460
+ throw callbackError;
1461
+ });
1462
+ try {
1463
+ registerMTRefSlots(0);
1464
+ initializeMainThreadDynamicAttrSlots(193, MT_REF_TEMPLATE, [{ type: 'main-thread-ref', value: callback }]);
1465
+ attachMainThreadDynamicAttrRefsForSubtree([{ uid: 193, ref: handle }]);
1466
+ vi.mocked(__GetElementByAttrSlot).mockReturnValue(target);
1467
+ envManager.switchToMainThread();
1468
+ installElementTemplatePatchListener();
1469
+ mockFlushElementTree.mockClear();
1470
+ expect(() => {
1471
+ envManager.switchToBackground();
1472
+ dispatchElementTemplateUpdate({
1473
+ ops: [],
1474
+ isHydration: true,
1475
+ flushOptions: {},
1476
+ delayedRunOnMainThreadData: [{ worklet: { _wkltId: 'should-not-run' }, params: [], resolveId: 33 }],
1477
+ });
1478
+ envManager.switchToMainThread();
1479
+ }).toThrow(callbackError);
1480
+ expect(globalThis.runWorklet).toHaveBeenCalledWith(callback, [{ elementRefptr: target }]);
1481
+ expect(runDelayedBackgroundFunctions).toHaveBeenCalledTimes(1);
1482
+ expect(clearFirstScreenWorkletRefMap).toHaveBeenCalledTimes(1);
1483
+ expect(runRunOnMainThreadTask).not.toHaveBeenCalled();
1484
+ expect(mockFlushElementTree).not.toHaveBeenCalled();
1485
+ } finally {
1486
+ globalThis.runWorklet = previousRunWorklet;
1487
+ clearMainThreadDynamicAttrState();
1488
+ globalThis.lynxWorkletImpl = previousWorkletImpl;
1489
+ }
1490
+ });
1491
+
1395
1492
  it('continues delayed lifecycle when patch apply reports a missing target', () => {
1396
1493
  const runDelayedBackgroundFunctions = vi.fn();
1397
1494
  const runRunOnMainThreadTask = vi.fn();
@@ -1443,6 +1540,99 @@ describe('ElementTemplate patch stream (apply)', () => {
1443
1540
  }
1444
1541
  });
1445
1542
 
1543
+ it('delivers pending targets before hydration handoff and delayed tasks, then flushes their writes', () => {
1544
+ const callOrder: string[] = [];
1545
+ const handle = { id: 'pending-template' } as unknown as ElementTemplateHandle;
1546
+ const target = { id: 'inner-node' } as unknown as ElementRef;
1547
+ const ref = { _wvid: 91 };
1548
+ const worklet = { _wkltId: 'uses-hydrated-ref' };
1549
+ const updateWorkletRef = vi.fn(() => callOrder.push('attach'));
1550
+ const clearFirstScreenWorkletRefMap = vi.fn(() => callOrder.push('clear-first-screen'));
1551
+ const runDelayedBackgroundFunctions = vi.fn(() => callOrder.push('background-handoff'));
1552
+ const runRunOnMainThreadTask = vi.fn(() => {
1553
+ expect(updateWorkletRef).toHaveBeenCalledWith(ref, target);
1554
+ callOrder.push('task');
1555
+ });
1556
+ const previousWorkletImpl = globalThis.lynxWorkletImpl;
1557
+ globalThis.lynxWorkletImpl = {
1558
+ ...previousWorkletImpl,
1559
+ _refImpl: { updateWorkletRef, clearFirstScreenWorkletRefMap },
1560
+ _runOnBackgroundDelayImpl: { runDelayedBackgroundFunctions },
1561
+ _eomImpl: { setShouldFlush: vi.fn() },
1562
+ _runRunOnMainThreadTask: runRunOnMainThreadTask,
1563
+ };
1564
+ try {
1565
+ registerMTRefSlots(0);
1566
+ initializeMainThreadDynamicAttrSlots(191, MT_REF_TEMPLATE, [{ type: 'main-thread-ref', value: ref }]);
1567
+ attachMainThreadDynamicAttrRefsForSubtree([{ uid: 191, ref: handle }]);
1568
+ vi.mocked(__GetElementByAttrSlot).mockReturnValue(target);
1569
+ mockFlushElementTree.mockImplementationOnce(() => callOrder.push('initial-flush'));
1570
+ envManager.switchToMainThread();
1571
+ installElementTemplatePatchListener();
1572
+ envManager.switchToBackground();
1573
+ dispatchElementTemplateUpdate({
1574
+ ops: [],
1575
+ isHydration: true,
1576
+ flushOptions: { emptyPatch: true },
1577
+ delayedRunOnMainThreadData: [{ worklet, params: [], resolveId: 31 }],
1578
+ });
1579
+ envManager.switchToMainThread();
1580
+ expect(callOrder).toEqual(['attach', 'background-handoff', 'clear-first-screen', 'task', 'initial-flush']);
1581
+ expect(runRunOnMainThreadTask).toHaveBeenCalledWith(worklet, [], 31);
1582
+ expect(mockFlushElementTree).toHaveBeenCalledOnce();
1583
+ expect(mockFlushElementTree.mock.calls[0]![1]).toEqual({ emptyPatch: true });
1584
+ } finally {
1585
+ clearMainThreadDynamicAttrState();
1586
+ globalThis.lynxWorkletImpl = previousWorkletImpl;
1587
+ }
1588
+ });
1589
+
1590
+ it('delivers refs synchronously before a later delayed-task payload', () => {
1591
+ const handleId = 192;
1592
+ const handle = { id: 'pending-template' } as unknown as ElementTemplateHandle;
1593
+ const target = { id: 'inner-node' } as unknown as ElementRef;
1594
+ const ref = { _wvid: 92 };
1595
+ const worklet = { _wkltId: 'later-payload-uses-ref' };
1596
+ const updateWorkletRef = vi.fn();
1597
+ const runRunOnMainThreadTask = vi.fn(() => expect(updateWorkletRef).toHaveBeenCalledWith(ref, target));
1598
+ const previousWorkletImpl = globalThis.lynxWorkletImpl;
1599
+ globalThis.lynxWorkletImpl = {
1600
+ ...previousWorkletImpl,
1601
+ _refImpl: { updateWorkletRef },
1602
+ _eomImpl: { setShouldFlush: vi.fn() },
1603
+ _runRunOnMainThreadTask: runRunOnMainThreadTask,
1604
+ };
1605
+ try {
1606
+ elementTemplateRegistry.set(handleId, handle);
1607
+ registerMTRefSlots(0);
1608
+ attachMainThreadDynamicAttrRefsForSubtree([{ uid: handleId, ref: handle }]);
1609
+ vi.mocked(__GetElementByAttrSlot).mockReturnValue(target);
1610
+ envManager.switchToMainThread();
1611
+ installElementTemplatePatchListener();
1612
+ envManager.switchToBackground();
1613
+ dispatchElementTemplateUpdate({
1614
+ ops: [ElementTemplateUpdateOps.setMainThreadRef, handleId, 0, { type: 'main-thread-ref', value: ref }],
1615
+ flushOptions: {},
1616
+ });
1617
+ envManager.switchToMainThread();
1618
+ expect(updateWorkletRef).toHaveBeenCalledWith(ref, target);
1619
+ envManager.switchToBackground();
1620
+ dispatchElementTemplateUpdate({
1621
+ ops: [],
1622
+ flushOptions: { emptyPatch: true },
1623
+ delayedRunOnMainThreadData: [{ worklet, params: [], resolveId: 32 }],
1624
+ });
1625
+ envManager.switchToMainThread();
1626
+ expect(runRunOnMainThreadTask).toHaveBeenCalledWith(worklet, [], 32);
1627
+ expect(__GetElementByAttrSlot).toHaveBeenCalledOnce();
1628
+ expect(updateWorkletRef).toHaveBeenCalledOnce();
1629
+ expect(mockFlushElementTree.mock.calls).toEqual([[undefined, {}], [undefined, { emptyPatch: true }]]);
1630
+ } finally {
1631
+ clearMainThreadDynamicAttrState();
1632
+ globalThis.lynxWorkletImpl = previousWorkletImpl;
1633
+ }
1634
+ });
1635
+
1446
1636
  it('applies independent ref initialization before delayed main-thread tasks', () => {
1447
1637
  const callOrder: string[] = [];
1448
1638
  const updateWorkletRefInitValueChanges = vi.fn(() => {
@@ -4,7 +4,7 @@ import {
4
4
  installElementTemplatePatchListener,
5
5
  resetElementTemplatePatchListener,
6
6
  } from '../../../../src/element-template/native/patch-listener.js';
7
- import { setPipeline } from '../../../../src/core/performance.js';
7
+ import { globalPipelineOptions, setPipeline } from '../../../../src/core/performance.js';
8
8
  import { ElementTemplateUpdateOps } from '../../../../src/element-template/protocol/opcodes.js';
9
9
  import { ElementTemplateLifecycleConstant } from '../../../../src/element-template/protocol/lifecycle-constant.js';
10
10
  import {
@@ -105,6 +105,7 @@ describe('ElementTemplate update timing (main thread patch)', () => {
105
105
  ['pipelineID', 'patchChangesEnd'],
106
106
  ['pipelineID', 'mtsRenderEnd'],
107
107
  ]);
108
+ expect(globalPipelineOptions).toBeUndefined();
108
109
  });
109
110
 
110
111
  it('handles updates without pipeline options', () => {
@@ -154,6 +155,7 @@ describe('ElementTemplate update timing (main thread patch)', () => {
154
155
  ['pipelineID', 'parseChangesEnd'],
155
156
  ['pipelineID', 'mtsRenderEnd'],
156
157
  ]);
158
+ expect(globalPipelineOptions).toBeUndefined();
157
159
  });
158
160
 
159
161
  it('marks parse timing for empty update envelopes with pipeline options', () => {
@@ -179,6 +181,7 @@ describe('ElementTemplate update timing (main thread patch)', () => {
179
181
  ['pipelineID', 'parseChangesEnd'],
180
182
  ['pipelineID', 'mtsRenderEnd'],
181
183
  ]);
184
+ expect(globalPipelineOptions).toBeUndefined();
182
185
  });
183
186
 
184
187
  it('accepts update payloads from the current reload version', () => {
@@ -61,7 +61,10 @@ beforeEach(() => {
61
61
  compiledTemplate: {
62
62
  kind: 'element',
63
63
  type: 'view',
64
- attributesArray: [{ kind: 'slot', key: 'id', attrSlotIndex: 0 }],
64
+ attributesArray: [
65
+ { kind: 'slot', key: 'id', attrSlotIndex: 0 },
66
+ { kind: 'slot', key: 'main-thread:ref', attrSlotIndex: 1 },
67
+ ],
65
68
  },
66
69
  },
67
70
  ]);
@@ -46,7 +46,10 @@ beforeEach(() => {
46
46
  compiledTemplate: {
47
47
  kind: 'element',
48
48
  type: 'view',
49
- attributesArray: [{ kind: 'slot', key: 'id', attrSlotIndex: 0 }],
49
+ attributesArray: [
50
+ { kind: 'slot', key: 'id', attrSlotIndex: 0 },
51
+ { kind: 'slot', key: 'main-thread:ref', attrSlotIndex: 1 },
52
+ ],
50
53
  },
51
54
  },
52
55
  ]);
@@ -15,9 +15,11 @@ import {
15
15
  clearEtAttrPlanMap,
16
16
  } from '../../../../src/element-template/runtime/template/attr-slot-plan.js';
17
17
  import {
18
+ applyPendingMainThreadRefAttachments,
18
19
  clearMainThreadDynamicAttrState,
19
20
  getMainThreadDynamicAttrState,
20
21
  initializeMainThreadDynamicAttrSlots,
22
+ updateMainThreadRefAttrSlot,
21
23
  } from '../../../../src/element-template/runtime/template/main-thread-dynamic-attr-state.js';
22
24
  import { elementTemplateRegistry } from '../../../../src/element-template/runtime/template/registry.js';
23
25
 
@@ -50,6 +52,7 @@ describe('renderMainThread', () => {
50
52
  vi.stubGlobal('__InsertNodeToElementTemplate', vi.fn());
51
53
  vi.stubGlobal('__SetAttributeOfElementTemplate', vi.fn());
52
54
  vi.stubGlobal('__SerializeElementTemplate', vi.fn());
55
+ vi.stubGlobal('__FlushElementTree', vi.fn());
53
56
  elementTemplateRegistry.clear();
54
57
  destroyAllElementTemplateListStates();
55
58
  clearMainThreadDynamicAttrState();
@@ -281,6 +284,8 @@ describe('renderMainThread', () => {
281
284
 
282
285
  it('attaches root MTRef state only after page insertion succeeds', () => {
283
286
  const rootRef = { type: 'root-ref' } as unknown as ElementTemplateHandle;
287
+ const target = { type: 'actual-element' } as unknown as ElementRef;
288
+ vi.mocked(__GetElementByAttrSlot).mockReturnValue(target);
284
289
  const ref = { _wvid: 80 };
285
290
  const updateWorkletRef = vi.fn();
286
291
  const previousWorkletImpl = globalThis.lynxWorkletImpl;
@@ -312,7 +317,12 @@ describe('renderMainThread', () => {
312
317
  try {
313
318
  renderMainThread();
314
319
 
315
- expect(updateWorkletRef).toHaveBeenCalledWith(ref, rootRef);
320
+ expect(updateWorkletRef).toHaveBeenCalledWith(ref, target);
321
+ expect(__FlushElementTree).not.toHaveBeenCalled();
322
+ expect(updateWorkletRef.mock.invocationCallOrder[0]).toBeLessThan(
323
+ vi.mocked(__SerializeElementTemplate).mock.invocationCallOrder[0]!,
324
+ );
325
+ expect(updateWorkletRef.mock.invocationCallOrder[0]).toBeLessThan(dispatchEvent.mock.invocationCallOrder[0]!);
316
326
  expect(vi.mocked(__InsertNodeToElementTemplate).mock.invocationCallOrder[0]).toBeLessThan(
317
327
  updateWorkletRef.mock.invocationCallOrder[0]!,
318
328
  );
@@ -325,6 +335,96 @@ describe('renderMainThread', () => {
325
335
  }
326
336
  });
327
337
 
338
+ it('delivers first-screen callback effects before a synchronous hydrate roundtrip', () => {
339
+ const rootRef = {} as ElementTemplateHandle;
340
+ const target = {} as ElementRef;
341
+ const first = { _wkltId: 'ref-callback', initialized: false, delayIndices: [] as number[] };
342
+ const hydrated = { _wkltId: 'ref-callback' };
343
+ const events: string[] = [];
344
+ const previousRunWorklet = globalThis.runWorklet;
345
+ const previousWorkletImpl = globalThis.lynxWorkletImpl;
346
+ globalThis.runWorklet = vi.fn().mockImplementationOnce(() => {
347
+ events.push('first attach');
348
+ first.initialized = true;
349
+ first.delayIndices.push(0);
350
+ return () => events.push('first cleanup');
351
+ }).mockImplementation(() => {
352
+ events.push('hydrated attach');
353
+ });
354
+ globalThis.lynxWorkletImpl = {
355
+ ...previousWorkletImpl,
356
+ _hydrateCtx: vi.fn((_next, previous) => {
357
+ expect(previous).toBe(first);
358
+ expect(first.initialized).toBe(true);
359
+ expect(first.delayIndices).toEqual([0]);
360
+ events.push('hydrate context');
361
+ }),
362
+ } as typeof globalThis.lynxWorkletImpl;
363
+ __etAttrPlanMap._et_ref = [0, adaptMTRefAttrSlot];
364
+ initializeMainThreadDynamicAttrSlots(-1, '_et_ref', [{ type: 'main-thread-ref', value: first }]);
365
+ vi.mocked(mockRender).mockReturnValue({
366
+ pageAttributes: null,
367
+ rootRefs: [rootRef],
368
+ rootSubtreeHandles: [[{ uid: -1, ref: rootRef }]],
369
+ });
370
+ vi.mocked(__GetElementByAttrSlot).mockReturnValue(target);
371
+ vi.mocked(__SerializeElementTemplate).mockImplementation(() => {
372
+ events.push('serialize');
373
+ return {} as ReturnType<typeof __SerializeElementTemplate>;
374
+ });
375
+ dispatchEvent.mockImplementation(() => {
376
+ events.push('dispatch hydrate');
377
+ updateMainThreadRefAttrSlot(-1, 0, { type: 'main-thread-ref', value: hydrated }, rootRef, true);
378
+ applyPendingMainThreadRefAttachments();
379
+ });
380
+ try {
381
+ renderMainThread();
382
+ expect(events).toEqual([
383
+ 'first attach',
384
+ 'serialize',
385
+ 'dispatch hydrate',
386
+ 'first cleanup',
387
+ 'hydrate context',
388
+ 'hydrated attach',
389
+ ]);
390
+ clearMainThreadDynamicAttrState();
391
+ } finally {
392
+ globalThis.runWorklet = previousRunWorklet;
393
+ globalThis.lynxWorkletImpl = previousWorkletImpl;
394
+ }
395
+ });
396
+
397
+ it.each(['missing target', 'callback throws'])(
398
+ 'does not serialize or dispatch hydration when first-screen %s',
399
+ failure => {
400
+ const rootRef = {} as ElementTemplateHandle;
401
+ const previousRunWorklet = globalThis.runWorklet;
402
+ globalThis.runWorklet = vi.fn(() => {
403
+ throw new Error('ref callback failed');
404
+ });
405
+ __etAttrPlanMap._et_ref = [0, adaptMTRefAttrSlot];
406
+ initializeMainThreadDynamicAttrSlots(-1, '_et_ref', [{
407
+ type: 'main-thread-ref',
408
+ value: { _wkltId: 'failed-ref' },
409
+ }]);
410
+ vi.mocked(mockRender).mockReturnValue({
411
+ pageAttributes: null,
412
+ rootRefs: [rootRef],
413
+ rootSubtreeHandles: [[{ uid: -1, ref: rootRef }]],
414
+ });
415
+ vi.mocked(__GetElementByAttrSlot).mockReturnValue(failure === 'missing target' ? null : {} as ElementRef);
416
+ try {
417
+ expect(() => renderMainThread()).toThrow(
418
+ failure === 'missing target' ? 'could not be materialized' : 'ref callback failed',
419
+ );
420
+ expect(__SerializeElementTemplate).not.toHaveBeenCalled();
421
+ expect(dispatchEvent).not.toHaveBeenCalled();
422
+ } finally {
423
+ globalThis.runWorklet = previousRunWorklet;
424
+ }
425
+ },
426
+ );
427
+
328
428
  it('keeps root MTRef state blocked when page insertion throws', () => {
329
429
  const rootRef = { type: 'root-ref' } as unknown as ElementTemplateHandle;
330
430
  const ref = { _wvid: 81 };
@@ -23,6 +23,7 @@ import {
23
23
  clearMainThreadDynamicAttrState,
24
24
  getMainThreadDynamicAttrState,
25
25
  } from '../../../../src/element-template/runtime/template/main-thread-dynamic-attr-state.js';
26
+ import { JsFunctionLifecycleManager } from '../../../../src/worklet-runtime/jsFunctionLifecycle.js';
26
27
  import { resetTemplateId } from '../../../../src/element-template/runtime/template/handle.js';
27
28
 
28
29
  describe('ElementTemplateHandle', () => {
@@ -102,6 +103,37 @@ describe('ElementTemplateHandle', () => {
102
103
  });
103
104
  });
104
105
 
106
+ it.each(['success', 'null', 'throw'])(
107
+ 'prepares and tracks create input before Native %s without advancing failed state',
108
+ (outcome) => {
109
+ const previous = globalThis.lynxWorkletImpl;
110
+ const manager = new JsFunctionLifecycleManager();
111
+ globalThis.lynxWorkletImpl = { ...previous, _jsFunctionLifecycleManager: manager };
112
+ const ctx = { _wkltId: 'tap', _execId: 21 };
113
+ const retain = vi.spyOn(manager, 'addRef');
114
+ const error = new Error('create failed');
115
+ __etAttrPlanMap['__Card__:_et_test'] = [0, adaptMTEventAttrSlot];
116
+ mockCreateCompiledElementTemplate.mockImplementationOnce((_key, _url, slots) => {
117
+ expect(slots[0].value).toBe(ctx);
118
+ expect(retain).toHaveBeenCalledExactlyOnceWith(21, ctx);
119
+ expect(getMainThreadDynamicAttrState(-1, 0)).toBeUndefined();
120
+ if (outcome === 'throw') throw error;
121
+ return outcome === 'null' ? null : mockCreatedNativeRef;
122
+ });
123
+ try {
124
+ const create = () =>
125
+ createElementTemplateWithReservedHandle(-1, '_et_test', null, [{ type: 'worklet', value: ctx }], null);
126
+ if (outcome === 'throw') expect(create).toThrow(error);
127
+ else expect(create()).toBe(outcome === 'null' ? null : mockCreatedNativeRef);
128
+ expect(retain).toHaveBeenCalledExactlyOnceWith(21, ctx);
129
+ expect(getMainThreadDynamicAttrState(-1, 0)?.nativeHeldValue).toBe(outcome === 'success' ? ctx : undefined);
130
+ } finally {
131
+ manager.dispose();
132
+ globalThis.lynxWorkletImpl = previous;
133
+ }
134
+ },
135
+ );
136
+
105
137
  it('records dynamic-entry main-thread dynamic attr state with the full template identity', () => {
106
138
  const id = reserveElementTemplateId();
107
139
  const ctx = { _wkltId: 'tap' };