@lynx-js/react 0.126.2 → 0.127.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 (190) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/components/tsconfig.tsbuildinfo +1 -1
  3. package/docs/directives.md +90 -0
  4. package/docs/global-events.md +50 -0
  5. package/docs/import-attributes.md +43 -0
  6. package/docs/macros.md +285 -0
  7. package/package.json +3 -2
  8. package/refresh/.turbo/turbo-build.log +1 -1
  9. package/refresh/dist/index.js +26 -6
  10. package/refresh/package.json +1 -1
  11. package/runtime/__test__/core/main-thread-object.test.js +149 -0
  12. package/runtime/__test__/element-template/fixtures/background/main-thread-function/run-on-main-thread/index.tsx +26 -3
  13. package/runtime/__test__/element-template/imports/main-thread-object-api.test.ts +10 -0
  14. package/runtime/__test__/element-template/internal/legacy-internal-guardrail.test.ts +3 -0
  15. package/runtime/__test__/element-template/runtime/background/main-thread-function/compiled-fixtures.test.tsx +4 -0
  16. package/runtime/__test__/snapshot/ctxNotFound.test.ts +271 -0
  17. package/runtime/__test__/snapshot/event.test.jsx +7 -7
  18. package/runtime/__test__/snapshot/lazy.test.js +73 -1
  19. package/runtime/__test__/snapshot/lynx/portals.test.jsx +75 -37
  20. package/runtime/__test__/snapshot/snapshotPatch.test.jsx +59 -47
  21. package/runtime/__test__/snapshot/spread.test.jsx +10 -10
  22. package/runtime/__test__/snapshot/worklet/main-thread-object.test.jsx +306 -0
  23. package/runtime/__test__/snapshot/worklet/workletRef.test.jsx +1 -0
  24. package/runtime/__test__/worklet-runtime/mainThreadObject.test.js +182 -0
  25. package/runtime/__test__/worklet-runtime/object-methods.test.js +60 -0
  26. package/runtime/__test__/worklet-runtime/workletRef.test.js +362 -2
  27. package/runtime/__test__/worklet-runtime/workletRuntime.test.js +246 -1
  28. package/runtime/lazy/compat.js +2 -0
  29. package/runtime/lazy/element-template-internal.js +1 -0
  30. package/runtime/lazy/element-template.js +2 -0
  31. package/runtime/lazy/internal.js +2 -0
  32. package/runtime/lazy/react.js +2 -0
  33. package/runtime/lib/core/background-function/run-on-background.d.ts +16 -0
  34. package/runtime/lib/core/background-function/run-on-background.js +16 -0
  35. package/runtime/lib/core/background-function/run-on-background.js.map +1 -1
  36. package/runtime/lib/core/capture-main-thread-object.d.ts +1 -0
  37. package/runtime/lib/core/capture-main-thread-object.js +16 -0
  38. package/runtime/lib/core/capture-main-thread-object.js.map +1 -0
  39. package/runtime/lib/core/globalProps.d.ts +2 -0
  40. package/runtime/lib/core/globalProps.js.map +1 -1
  41. package/runtime/lib/core/hooks/react.d.ts +4 -0
  42. package/runtime/lib/core/hooks/react.js +4 -0
  43. package/runtime/lib/core/hooks/react.js.map +1 -1
  44. package/runtime/lib/core/hooks/useLynxGlobalEventListener.d.ts +2 -0
  45. package/runtime/lib/core/hooks/useLynxGlobalEventListener.js +2 -0
  46. package/runtime/lib/core/hooks/useLynxGlobalEventListener.js.map +1 -1
  47. package/runtime/lib/core/initData.d.ts +2 -0
  48. package/runtime/lib/core/initData.js +2 -0
  49. package/runtime/lib/core/initData.js.map +1 -1
  50. package/runtime/lib/core/main-thread-object-handle-registry.d.ts +3 -0
  51. package/runtime/lib/core/main-thread-object-handle-registry.js +17 -0
  52. package/runtime/lib/core/main-thread-object-handle-registry.js.map +1 -0
  53. package/runtime/lib/core/main-thread-object.d.ts +77 -0
  54. package/runtime/lib/core/main-thread-object.js +261 -0
  55. package/runtime/lib/core/main-thread-object.js.map +1 -0
  56. package/runtime/lib/core/main-thread-ref-id.d.ts +1 -0
  57. package/runtime/lib/core/main-thread-ref-id.js +14 -0
  58. package/runtime/lib/core/main-thread-ref-id.js.map +1 -0
  59. package/runtime/lib/core/main-thread-ref-init-value.d.ts +1 -1
  60. package/runtime/lib/core/main-thread-ref-init-value.js +4 -2
  61. package/runtime/lib/core/main-thread-ref-init-value.js.map +1 -1
  62. package/runtime/lib/core/main-thread-ref.d.ts +4 -0
  63. package/runtime/lib/core/main-thread-ref.js +5 -8
  64. package/runtime/lib/core/main-thread-ref.js.map +1 -1
  65. package/runtime/lib/element-template/background/commit-hook.js.map +1 -1
  66. package/runtime/lib/element-template/index.d.ts +2 -0
  67. package/runtime/lib/element-template/index.js +1 -0
  68. package/runtime/lib/element-template/index.js.map +1 -1
  69. package/runtime/lib/element-template/internal.d.ts +1 -0
  70. package/runtime/lib/element-template/internal.js +1 -0
  71. package/runtime/lib/element-template/internal.js.map +1 -1
  72. package/runtime/lib/element-template/protocol/types.d.ts +1 -1
  73. package/runtime/lib/internal.d.ts +1 -0
  74. package/runtime/lib/internal.js +1 -0
  75. package/runtime/lib/internal.js.map +1 -1
  76. package/runtime/lib/lynx-api.d.ts +34 -0
  77. package/runtime/lib/lynx-api.js +21 -0
  78. package/runtime/lib/lynx-api.js.map +1 -1
  79. package/runtime/lib/lynx.js +4 -1
  80. package/runtime/lib/lynx.js.map +1 -1
  81. package/runtime/lib/snapshot/lifecycle/patch/error.d.ts +11 -1
  82. package/runtime/lib/snapshot/lifecycle/patch/error.js +24 -16
  83. package/runtime/lib/snapshot/lifecycle/patch/error.js.map +1 -1
  84. package/runtime/lib/snapshot/lifecycle/patch/snapshotPatchApply.d.ts +1 -1
  85. package/runtime/lib/snapshot/lifecycle/patch/snapshotPatchApply.js +29 -7
  86. package/runtime/lib/snapshot/lifecycle/patch/snapshotPatchApply.js.map +1 -1
  87. package/runtime/lib/snapshot/lifecycle/patch/updateMainThread.js +2 -2
  88. package/runtime/lib/snapshot/lifecycle/patch/updateMainThread.js.map +1 -1
  89. package/runtime/lib/snapshot/lynx/children.d.ts +2 -0
  90. package/runtime/lib/snapshot/lynx/children.js.map +1 -1
  91. package/runtime/lib/snapshot/lynx/element.d.ts +8 -0
  92. package/runtime/lib/snapshot/lynx/element.js +4 -0
  93. package/runtime/lib/snapshot/lynx/element.js.map +1 -1
  94. package/runtime/lib/snapshot/worklet/call/runOnMainThread.d.ts +2 -0
  95. package/runtime/lib/snapshot/worklet/call/runOnMainThread.js +2 -0
  96. package/runtime/lib/snapshot/worklet/call/runOnMainThread.js.map +1 -1
  97. package/runtime/lib/snapshot/worklet/ref/updateInitValue.js.map +1 -1
  98. package/runtime/lib/tsconfig.tsbuildinfo +1 -1
  99. package/runtime/lib/worklet-runtime/bindings/bindings.d.ts +3 -3
  100. package/runtime/lib/worklet-runtime/bindings/bindings.js +9 -1
  101. package/runtime/lib/worklet-runtime/bindings/bindings.js.map +1 -1
  102. package/runtime/lib/worklet-runtime/bindings/types.d.ts +3 -6
  103. package/runtime/lib/worklet-runtime/bindings/types.js.map +1 -1
  104. package/runtime/lib/worklet-runtime/hydrate.js +26 -7
  105. package/runtime/lib/worklet-runtime/hydrate.js.map +1 -1
  106. package/runtime/lib/worklet-runtime/mainThreadObject.d.ts +8 -0
  107. package/runtime/lib/worklet-runtime/mainThreadObject.js +67 -0
  108. package/runtime/lib/worklet-runtime/mainThreadObject.js.map +1 -0
  109. package/runtime/lib/worklet-runtime/workletRef.d.ts +11 -7
  110. package/runtime/lib/worklet-runtime/workletRef.js +72 -9
  111. package/runtime/lib/worklet-runtime/workletRef.js.map +1 -1
  112. package/runtime/lib/worklet-runtime/workletRuntime.js +68 -9
  113. package/runtime/lib/worklet-runtime/workletRuntime.js.map +1 -1
  114. package/runtime/package.json +2 -3
  115. package/runtime/src/core/background-function/run-on-background.ts +16 -0
  116. package/runtime/src/core/capture-main-thread-object.ts +17 -0
  117. package/runtime/src/core/globalProps.ts +2 -0
  118. package/runtime/src/core/hooks/react.ts +4 -0
  119. package/runtime/src/core/hooks/useLynxGlobalEventListener.ts +2 -0
  120. package/runtime/src/core/initData.ts +2 -0
  121. package/runtime/src/core/main-thread-object-handle-registry.ts +25 -0
  122. package/runtime/src/core/main-thread-object.ts +387 -0
  123. package/runtime/src/core/main-thread-ref-id.ts +16 -0
  124. package/runtime/src/core/main-thread-ref-init-value.ts +12 -4
  125. package/runtime/src/core/main-thread-ref.ts +7 -8
  126. package/runtime/src/element-template/background/commit-hook.ts +1 -1
  127. package/runtime/src/element-template/index.ts +6 -0
  128. package/runtime/src/element-template/internal.ts +2 -0
  129. package/runtime/src/element-template/protocol/types.ts +1 -1
  130. package/runtime/src/internal.ts +1 -0
  131. package/runtime/src/lynx-api.ts +38 -0
  132. package/runtime/src/lynx.ts +5 -1
  133. package/runtime/src/snapshot/lifecycle/patch/error.ts +36 -19
  134. package/runtime/src/snapshot/lifecycle/patch/snapshotPatchApply.ts +29 -7
  135. package/runtime/src/snapshot/lifecycle/patch/updateMainThread.ts +2 -2
  136. package/runtime/src/snapshot/lynx/children.ts +2 -0
  137. package/runtime/src/snapshot/lynx/element.ts +8 -0
  138. package/runtime/src/snapshot/worklet/call/runOnMainThread.ts +2 -0
  139. package/runtime/src/snapshot/worklet/ref/updateInitValue.ts +1 -1
  140. package/runtime/src/worklet-runtime/bindings/bindings.ts +17 -2
  141. package/runtime/src/worklet-runtime/bindings/types.ts +7 -11
  142. package/runtime/src/worklet-runtime/hydrate.ts +43 -10
  143. package/runtime/src/worklet-runtime/mainThreadObject.ts +117 -0
  144. package/runtime/src/worklet-runtime/workletRef.ts +120 -19
  145. package/runtime/src/worklet-runtime/workletRuntime.ts +83 -11
  146. package/runtime/worklet-runtime/dev.js +154 -17
  147. package/runtime/worklet-runtime/main.js +1 -1
  148. package/testing-library/.turbo/turbo-build.log +6 -6
  149. package/testing-library/dist/index.d.ts +165 -2
  150. package/testing-library/package.json +2 -1
  151. package/testing-library/src/__tests__/lynx.test.jsx +1 -1
  152. package/testing-library/src/__tests__/worklet.test.jsx +46 -1
  153. package/testing-library/tsconfig.docs.json +9 -0
  154. package/testing-library/typedoc.json +22 -0
  155. package/transform/.turbo/turbo-build$colon$wasm.log +150 -78
  156. package/transform/__test__/fixture.spec.js +72 -30
  157. package/transform/__test__/object-methods.spec.js +84 -0
  158. package/transform/crates/swc_plugin_worklet/decl_collect.rs +10 -0
  159. package/transform/crates/swc_plugin_worklet/extract_ident.rs +14 -0
  160. package/transform/crates/swc_plugin_worklet/gen_stmt.rs +202 -3
  161. package/transform/crates/swc_plugin_worklet/lib.rs +468 -3
  162. package/transform/crates/swc_plugin_worklet/tests/__swc_snapshots__/lib.rs/should_capture_env_js.js +8 -1
  163. package/transform/crates/swc_plugin_worklet/tests/__swc_snapshots__/lib.rs/should_capture_env_lepus.js +10 -5
  164. package/transform/crates/swc_plugin_worklet/tests/__swc_snapshots__/lib.rs/should_expose_object_method_capture_channels_js.js +27 -0
  165. package/transform/crates/swc_plugin_worklet/tests/__swc_snapshots__/lib.rs/should_expose_object_method_capture_channels_lepus.js +45 -0
  166. package/transform/crates/swc_plugin_worklet/tests/__swc_snapshots__/lib.rs/should_extract_member_expr_2_js.js +16 -14
  167. package/transform/crates/swc_plugin_worklet/tests/__swc_snapshots__/lib.rs/should_extract_member_expr_2_lepus.js +16 -16
  168. package/transform/crates/swc_plugin_worklet/tests/__swc_snapshots__/lib.rs/should_extract_member_expr_js.js +7 -5
  169. package/transform/crates/swc_plugin_worklet/tests/__swc_snapshots__/lib.rs/should_extract_member_expr_lepus.js +7 -7
  170. package/transform/crates/swc_plugin_worklet/tests/__swc_snapshots__/lib.rs/should_not_capture_computed_object_method_key_lepus.js +24 -0
  171. package/transform/crates/swc_plugin_worklet/tests/__swc_snapshots__/lib.rs/should_not_capture_object_method_local_decls_lepus.js +16 -0
  172. package/transform/crates/swc_plugin_worklet/tests/__swc_snapshots__/lib.rs/should_preserve_main_thread_objects_in_class_js.js +42 -0
  173. package/transform/crates/swc_plugin_worklet/tests/__swc_snapshots__/lib.rs/should_preserve_main_thread_objects_in_class_lepus.js +58 -0
  174. package/transform/crates/swc_plugin_worklet/tests/__swc_snapshots__/lib.rs/should_transform_js.js +3 -1
  175. package/transform/crates/swc_plugin_worklet/tests/__swc_snapshots__/lib.rs/should_transform_lepus.js +3 -3
  176. package/transform/crates/swc_plugin_worklet/tests/__swc_snapshots__/lib.rs/should_transform_object_methods_js.js +9 -0
  177. package/transform/crates/swc_plugin_worklet/tests/__swc_snapshots__/lib.rs/should_transform_object_methods_lepus.js +16 -0
  178. package/transform/dist/wasm.cjs +1 -1
  179. package/transform/rspack-napi/tsconfig.tsbuildinfo +1 -1
  180. package/transform/swc-plugin-reactlynx/.turbo/turbo-build.log +66 -469
  181. package/transform/swc-plugin-reactlynx/swc_plugin_reactlynx.wasm +0 -0
  182. package/transform/swc-plugin-reactlynx-compat/.turbo/turbo-build.log +364 -30
  183. package/transform/swc-plugin-reactlynx-compat/swc_plugin_reactlynx_compat.wasm +0 -0
  184. package/transform/vitest.config.ts +5 -1
  185. package/types/react.docs.d.ts +130 -11
  186. package/testing-library/node_modules/.bin/rsbuild +0 -68
  187. package/testing-library/node_modules/.bin/rspeedy +0 -68
  188. package/testing-library/node_modules/.bin/rstest +0 -68
  189. package/transform/node_modules/.bin/esbuild +0 -59
  190. package/transform/node_modules/.bin/napi +0 -68
@@ -0,0 +1,306 @@
1
+ /*
2
+ // Copyright 2024 The Lynx Authors. All rights reserved.
3
+ // Licensed under the Apache License Version 2.0 that can be found in the
4
+ // LICENSE file in the root directory of this source tree.
5
+ */
6
+ import { render } from 'preact';
7
+ import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
8
+
9
+ import { replaceCommitHook } from '../../../src/snapshot/lifecycle/patch/commit';
10
+ import { injectUpdateMainThread } from '../../../src/snapshot/lifecycle/patch/updateMainThread';
11
+ import { __root } from '../../../src/root';
12
+ import { setupPage } from '../../../src/snapshot';
13
+ import { destroyWorklet } from '../../../src/snapshot/worklet/destroy';
14
+ import { clearConfigCacheForTesting } from '../../../src/snapshot/worklet/functionality';
15
+ import { captureMainThreadObject } from '../../../src/core/capture-main-thread-object';
16
+ import { defineMainThreadObjectType, useMainThreadObject } from '../../../src/core/main-thread-object';
17
+ import { globalEnvManager } from '../utils/envManager';
18
+ import { injectUpdateMTRefInitValue } from '../../../src/snapshot/worklet/ref/updateInitValue';
19
+
20
+ beforeAll(() => {
21
+ setupPage(__CreatePage('0', 0));
22
+ injectUpdateMainThread();
23
+ injectUpdateMTRefInitValue();
24
+ replaceCommitHook();
25
+ globalThis.lynxWorkletImpl = {
26
+ _refImpl: {
27
+ updateWorkletRef: vi.fn(),
28
+ updateWorkletRefInitValueChanges: vi.fn(),
29
+ registerMainThreadObjectType: vi.fn(),
30
+ clearFirstScreenWorkletRefMap: vi.fn(),
31
+ },
32
+ _runOnBackgroundDelayImpl: {
33
+ runDelayedBackgroundFunctions: vi.fn(),
34
+ },
35
+ _eventDelayImpl: {
36
+ clearDelayedWorklets: vi.fn(),
37
+ },
38
+ };
39
+ });
40
+
41
+ beforeEach(() => {
42
+ globalEnvManager.resetEnv();
43
+ SystemInfo.lynxSdkVersion = '999.999';
44
+ clearConfigCacheForTesting();
45
+ });
46
+
47
+ afterEach(() => {
48
+ destroyWorklet();
49
+ vi.clearAllMocks();
50
+ });
51
+
52
+ function renderTestMainThreadObject(initialValue) {
53
+ const type = defineMainThreadObjectType({
54
+ type: '@test/main-thread-object',
55
+ create: value => ({ value }),
56
+ });
57
+ let value;
58
+ const App = () => {
59
+ value = useMainThreadObject(type, initialValue);
60
+ return <view />;
61
+ };
62
+ render(<App />, __root);
63
+ return value;
64
+ }
65
+
66
+ describe('MainThreadObject', () => {
67
+ it('serializes an opaque typed handle and releases it with the shared id lifecycle', () => {
68
+ globalEnvManager.switchToBackground();
69
+ const dispatchEvent = vi.fn();
70
+ lynx.getCoreContext = () => ({ dispatchEvent });
71
+ const value = renderTestMainThreadObject(42);
72
+
73
+ expect(JSON.parse(JSON.stringify(value))).toEqual({
74
+ _wvid: 1,
75
+ _initValue: 42,
76
+ _type: '@test/main-thread-object',
77
+ });
78
+ expect(lynx.getNativeApp().callLepusMethod).toHaveBeenCalledWith(
79
+ 'rLynxChangeRefInitValue',
80
+ { data: JSON.stringify([[1, 42, '@test/main-thread-object']]) },
81
+ );
82
+
83
+ lynx.getNativeApp().createJSObjectDestructionObserver.mock.calls[0][0]();
84
+ expect(dispatchEvent).toHaveBeenCalledWith({
85
+ type: 'Lynx.Worklet.releaseWorkletRef',
86
+ data: { id: 1 },
87
+ });
88
+ });
89
+
90
+ it('preserves opaque handles without changing ordinary member captures', () => {
91
+ globalEnvManager.switchToBackground();
92
+ const value = renderTestMainThreadObject(42);
93
+
94
+ expect(captureMainThreadObject(value)).toBe(value);
95
+ expect(captureMainThreadObject({ value: 42 })).toBeUndefined();
96
+ });
97
+
98
+ it('creates a typed handle through the library-author hook', async () => {
99
+ const definition = {
100
+ type: '@test/counter',
101
+ create: value => ({ value }),
102
+ };
103
+ const type = defineMainThreadObjectType(definition);
104
+ let counter;
105
+ const App = () => {
106
+ counter = useMainThreadObject(type, 42);
107
+ return <view />;
108
+ };
109
+
110
+ globalThis.globDynamicComponentEntry = '__Card__';
111
+ globalEnvManager.switchToBackground();
112
+ render(<App />, __root);
113
+
114
+ expect(JSON.parse(JSON.stringify(counter))).toMatchObject({
115
+ _initValue: 42,
116
+ _type: '@test/counter',
117
+ });
118
+ definition.type = '@test/mutated-counter';
119
+ expect(type.type).toBe('@test/counter');
120
+ expect(type).not.toHaveProperty('create');
121
+ expect(type).not.toHaveProperty('dispose');
122
+ const counterHandle = type.downcast(counter);
123
+ expect(counterHandle).toBe(counter);
124
+ expect(counterHandle.creationPayload).toBe(42);
125
+
126
+ const otherType = defineMainThreadObjectType({
127
+ type: '@test/other-counter',
128
+ create: value => ({ value }),
129
+ });
130
+ expect(otherType.downcast(counter)).toBeUndefined();
131
+ expect(otherType.downcast(null)).toBeUndefined();
132
+ expect(otherType.downcast(42)).toBeUndefined();
133
+ expect(otherType.downcast({
134
+ _initValue: 42,
135
+ _type: '@test/other-counter',
136
+ })).toBeUndefined();
137
+ expect(() => counter.get()).toThrow(
138
+ 'MainThreadObject handle for "@test/counter" cannot access "get" in the background runtime. Use the object only inside a main-thread function.',
139
+ );
140
+ expect(counter.then).toBeUndefined();
141
+ expect(counter.$$typeof).toBeUndefined();
142
+ expect(counter[Symbol.toStringTag]).toBeUndefined();
143
+ await expect(Promise.resolve(counter)).resolves.toBe(counter);
144
+ expect(() => counter.value = 43).toThrow(
145
+ 'MainThreadObject handle for "@test/counter" cannot set "value" in the background runtime. Use the object only inside a main-thread function.',
146
+ );
147
+ expect(() => counter._type = '@test/counter').not.toThrow();
148
+ });
149
+
150
+ it('ensures registration on the first main-thread hook use', () => {
151
+ const create = value => ({ value });
152
+ const register = globalThis.lynxWorkletImpl._refImpl.registerMainThreadObjectType;
153
+
154
+ globalEnvManager.switchToBackground();
155
+ const definition = {
156
+ type: '@test/retained-module-value',
157
+ create,
158
+ };
159
+ const type = defineMainThreadObjectType(definition);
160
+ expect(register).not.toHaveBeenCalled();
161
+
162
+ // Registration is deferred in the background runtime. Mutating the
163
+ // caller-owned object before the first main-thread use must not change the
164
+ // validated definition retained by the type token.
165
+ definition.type = '@test/mutated-retained-module-value';
166
+ definition.create = value => ({ value: value + 1 });
167
+
168
+ globalEnvManager.switchToMainThread();
169
+ const App = () => {
170
+ useMainThreadObject(type, 42);
171
+ return <view />;
172
+ };
173
+ render(<App />, __root);
174
+
175
+ expect(register).toHaveBeenCalledWith(
176
+ '@test/retained-module-value',
177
+ create,
178
+ );
179
+ });
180
+
181
+ it('snapshots accessor-backed definition fields before validation', () => {
182
+ let typeReads = 0;
183
+ let createReads = 0;
184
+ const create = value => ({ value });
185
+ const definition = {
186
+ get type() {
187
+ typeReads += 1;
188
+ return typeReads === 1 ? '@test/accessor-definition' : '@test/mutated-definition';
189
+ },
190
+ get create() {
191
+ createReads += 1;
192
+ return createReads === 1 ? create : { _wkltId: 'invalid-create' };
193
+ },
194
+ };
195
+
196
+ globalEnvManager.switchToBackground();
197
+ const type = defineMainThreadObjectType(definition);
198
+ expect(type.type).toBe('@test/accessor-definition');
199
+ expect(typeReads).toBe(1);
200
+ expect(createReads).toBe(1);
201
+
202
+ globalEnvManager.switchToMainThread();
203
+ const App = () => {
204
+ useMainThreadObject(type, 42);
205
+ return <view />;
206
+ };
207
+ render(<App />, __root);
208
+
209
+ expect(globalThis.lynxWorkletImpl._refImpl.registerMainThreadObjectType)
210
+ .toHaveBeenCalledWith('@test/accessor-definition', create);
211
+ expect(typeReads).toBe(1);
212
+ expect(createReads).toBe(1);
213
+ });
214
+
215
+ it('rejects a forged main-thread object type token', () => {
216
+ globalEnvManager.switchToMainThread();
217
+ const App = () => {
218
+ useMainThreadObject({ type: '@test/forged' }, 42);
219
+ return <view />;
220
+ };
221
+
222
+ expect(() => render(<App />, __root)).toThrow(
223
+ 'Invalid MainThreadObject type token for "@test/forged". Create it with defineMainThreadObjectType().',
224
+ );
225
+ });
226
+
227
+ it('uses a plain serializable handle in the main-thread runtime', () => {
228
+ globalEnvManager.switchToMainThread();
229
+ const type = defineMainThreadObjectType({
230
+ type: '@test/main-thread-counter',
231
+ create: value => ({ value }),
232
+ });
233
+ let counter;
234
+ const App = () => {
235
+ counter = useMainThreadObject(type, 42);
236
+ return <view />;
237
+ };
238
+
239
+ globalThis.globDynamicComponentEntry = '__Card__';
240
+ render(<App />, __root);
241
+
242
+ expect(JSON.parse(JSON.stringify(counter))).toMatchObject({
243
+ _initValue: 42,
244
+ _type: '@test/main-thread-counter',
245
+ });
246
+ });
247
+
248
+ it('rejects non-serializable initialization payloads in development', () => {
249
+ globalEnvManager.switchToBackground();
250
+
251
+ expect(() => renderTestMainThreadObject({ nested: { callback() {} } }))
252
+ .toThrow(
253
+ 'MainThreadObject initial value for "@test/main-thread-object" must be JSON-serializable; invalid value at $.nested.callback.',
254
+ );
255
+
256
+ const cyclic = {};
257
+ cyclic.self = cyclic;
258
+ expect(() => renderTestMainThreadObject(cyclic)).toThrow(
259
+ 'MainThreadObject initial value for "@test/main-thread-object" must be JSON-serializable; invalid value at $.self.',
260
+ );
261
+ expect(() => renderTestMainThreadObject(new Date())).toThrow(
262
+ 'MainThreadObject initial value for "@test/main-thread-object" must be JSON-serializable; invalid value at $.',
263
+ );
264
+ expect(() => renderTestMainThreadObject([1, { value: 2 }])).not.toThrow();
265
+ const sparseArray = Array(2);
266
+ sparseArray[1] = 1;
267
+ expect(() => renderTestMainThreadObject(sparseArray)).not.toThrow();
268
+ expect(() => renderTestMainThreadObject([undefined, 1])).toThrow(
269
+ 'MainThreadObject initial value for "@test/main-thread-object" must be JSON-serializable; invalid value at $.0.',
270
+ );
271
+
272
+ const arrayWithCustomFlatMap = [undefined, 1];
273
+ arrayWithCustomFlatMap.flatMap = () => [];
274
+ expect(() => renderTestMainThreadObject(arrayWithCustomFlatMap)).toThrow(
275
+ 'MainThreadObject initial value for "@test/main-thread-object" must be JSON-serializable; invalid value at $.0.',
276
+ );
277
+ });
278
+
279
+ it('exposes the readonly-typed creation payload without a runtime copy', () => {
280
+ globalEnvManager.switchToBackground();
281
+ const initialValue = { nested: { value: 1 }, values: [2, 3] };
282
+ const value = renderTestMainThreadObject(initialValue);
283
+ const handle = captureMainThreadObject(value);
284
+
285
+ expect(handle).toBeDefined();
286
+
287
+ initialValue.nested.value = 4;
288
+ initialValue.values.push(5);
289
+
290
+ expect(handle.creationPayload).toBe(initialValue);
291
+ expect(Object.isFrozen(handle.creationPayload)).toBe(false);
292
+ expect(handle.creationPayload).toEqual({ nested: { value: 4 }, values: [2, 3, 5] });
293
+ expect(JSON.parse(JSON.stringify(value))._initValue).toEqual({
294
+ nested: { value: 4 },
295
+ values: [2, 3, 5],
296
+ });
297
+ });
298
+
299
+ it('identifies registered main-thread object handles', () => {
300
+ globalEnvManager.switchToBackground();
301
+ const value = renderTestMainThreadObject({ value: 1 });
302
+
303
+ expect(captureMainThreadObject(value)).toBe(value);
304
+ expect(captureMainThreadObject({ value: 1 })).toBeUndefined();
305
+ });
306
+ });
@@ -32,6 +32,7 @@ beforeAll(() => {
32
32
  _refImpl: {
33
33
  updateWorkletRef: vi.fn(),
34
34
  updateWorkletRefInitValueChanges: vi.fn(),
35
+ registerMainThreadObjectType: vi.fn(),
35
36
  clearFirstScreenWorkletRefMap: vi.fn(),
36
37
  },
37
38
  _runOnBackgroundDelayImpl: {
@@ -0,0 +1,182 @@
1
+ // Copyright 2024 The Lynx Authors. All rights reserved.
2
+ // Licensed under the Apache License Version 2.0 that can be found in the
3
+ // LICENSE file in the root directory of this source tree.
4
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
5
+
6
+ import {
7
+ getFromWorkletRefMap,
8
+ isHydratedWorkletValue,
9
+ removeValueFromWorkletRefMap,
10
+ updateWorkletRefInitValueChanges,
11
+ } from '../../src/worklet-runtime/workletRef';
12
+ import { initWorklet } from '../../src/worklet-runtime/workletRuntime';
13
+
14
+ const originalDev = globalThis.__DEV__;
15
+
16
+ beforeEach(() => {
17
+ globalThis.__DEV__ = false;
18
+ globalThis.SystemInfo = {
19
+ lynxSdkVersion: '2.16',
20
+ };
21
+ initWorklet();
22
+ });
23
+
24
+ afterEach(() => {
25
+ globalThis.__DEV__ = originalDev;
26
+ delete globalThis.lynxWorkletImpl;
27
+ });
28
+
29
+ describe('MainThreadObject registry and realization', () => {
30
+ it('creates registered main-thread objects from typed patches', () => {
31
+ const value = { get: () => 42 };
32
+ globalThis.lynxWorkletImpl._refImpl.registerMainThreadObjectType(
33
+ '@test/value',
34
+ () => value,
35
+ );
36
+
37
+ updateWorkletRefInitValueChanges([[7, 42, '@test/value']]);
38
+
39
+ expect(getFromWorkletRefMap({ _wvid: 7 })).toBe(value);
40
+ removeValueFromWorkletRefMap(7);
41
+ });
42
+
43
+ it('lazily resolves and caches Main Thread Function factory descriptors', () => {
44
+ const create = vi.fn(value => ({ value }));
45
+ const createDescriptor = { _wkltId: 'create-test-value' };
46
+ const bindFactory = vi.spyOn(create, 'bind');
47
+
48
+ globalThis.lynxWorkletImpl._refImpl.registerMainThreadObjectType(
49
+ '@test/lazy-factory',
50
+ createDescriptor,
51
+ );
52
+
53
+ // Type definition evaluation happens before the compiler-appended
54
+ // registerWorklet calls at the end of the MTS module.
55
+ globalThis.registerWorklet('main-thread', 'create-test-value', create);
56
+ const lookupFactory = vi.fn(() => create);
57
+ Object.defineProperty(lynxWorkletImpl._workletMap, 'create-test-value', { get: lookupFactory });
58
+
59
+ updateWorkletRefInitValueChanges([
60
+ [71, 'first', '@test/lazy-factory'],
61
+ [72, 'second', '@test/lazy-factory'],
62
+ ]);
63
+ expect(getFromWorkletRefMap({ _wvid: 71 })).toMatchObject({ value: 'first' });
64
+ expect(getFromWorkletRefMap({ _wvid: 72 })).toMatchObject({ value: 'second' });
65
+ expect(create).toHaveBeenCalledTimes(2);
66
+ expect(lookupFactory).toHaveBeenCalledOnce();
67
+ expect(bindFactory).not.toHaveBeenCalled();
68
+
69
+ removeValueFromWorkletRefMap(71);
70
+ removeValueFromWorkletRefMap(72);
71
+ expect(lookupFactory).toHaveBeenCalledOnce();
72
+ });
73
+
74
+ it('rejects an unregistered main-thread object type', () => {
75
+ expect(() => {
76
+ updateWorkletRefInitValueChanges([[8, 42, '@test/missing']]);
77
+ }).toThrow('MainThreadObject type is not registered: "@test/missing"');
78
+ });
79
+
80
+ it.each([{}, { _lepusWorkletHash: 'legacy' }, { _wkltId: 'legacy', _lepusWorkletHash: 'legacy' }])(
81
+ 'rejects invalid factory descriptors %j',
82
+ (descriptor) => {
83
+ lynxWorkletImpl._refImpl.registerMainThreadObjectType('@test/invalid-factory', descriptor);
84
+ expect(() => updateWorkletRefInitValueChanges([[1, null, '@test/invalid-factory']]))
85
+ .toThrow('Cannot resolve an invalid Main Thread Function.');
86
+ },
87
+ );
88
+
89
+ it('rejects conflicting registrations for the same type key', () => {
90
+ const create = value => ({ value });
91
+ globalThis.lynxWorkletImpl._refImpl.registerMainThreadObjectType(
92
+ '@test/value',
93
+ create,
94
+ );
95
+ expect(() => {
96
+ globalThis.lynxWorkletImpl._refImpl.registerMainThreadObjectType(
97
+ '@test/value',
98
+ value => ({ conflictingValue: value }),
99
+ );
100
+ }).toThrow('Conflicting MainThreadObject registration for type "@test/value"');
101
+ expect(() => {
102
+ globalThis.lynxWorkletImpl._refImpl.registerMainThreadObjectType(
103
+ '@test/value',
104
+ create,
105
+ );
106
+ }).not.toThrow();
107
+
108
+ globalThis.lynxWorkletImpl._refImpl.registerMainThreadObjectType(
109
+ '@test/worklet-value',
110
+ { _wkltId: 'stable-create' },
111
+ );
112
+ expect(() => {
113
+ globalThis.lynxWorkletImpl._refImpl.registerMainThreadObjectType(
114
+ '@test/worklet-value',
115
+ { _wkltId: 'stable-create' },
116
+ );
117
+ }).not.toThrow();
118
+ expect(() => {
119
+ globalThis.lynxWorkletImpl._refImpl.registerMainThreadObjectType(
120
+ '@test/worklet-value',
121
+ { _wkltId: 'different-create' },
122
+ );
123
+ }).toThrow('Conflicting MainThreadObject registration for type "@test/worklet-value"');
124
+ });
125
+
126
+ it('reserves the legacy MainThreadRef type key for typed registrations', () => {
127
+ expect(() => {
128
+ globalThis.lynxWorkletImpl._refImpl.registerMainThreadObjectType(
129
+ 'main-thread',
130
+ value => ({ value }),
131
+ );
132
+ }).toThrow(
133
+ 'MainThreadObject type "main-thread" is reserved for MainThreadRef.',
134
+ );
135
+ });
136
+
137
+ it('allows equivalent registrations from separately evaluated modules', () => {
138
+ const createDefinition = () => value => ({ value });
139
+ const createA = createDefinition();
140
+ const createB = createDefinition();
141
+
142
+ expect(createA).not.toBe(createB);
143
+ globalThis.lynxWorkletImpl._refImpl.registerMainThreadObjectType(
144
+ '@test/lazy-duplicate',
145
+ createA,
146
+ );
147
+ expect(() => {
148
+ globalThis.lynxWorkletImpl._refImpl.registerMainThreadObjectType(
149
+ '@test/lazy-duplicate',
150
+ createB,
151
+ );
152
+ }).not.toThrow();
153
+ });
154
+
155
+ it('rejects factories that do not create objects', () => {
156
+ globalThis.lynxWorkletImpl._refImpl.registerMainThreadObjectType(
157
+ '@test/invalid',
158
+ () => 42,
159
+ );
160
+
161
+ expect(() => {
162
+ updateWorkletRefInitValueChanges([[10, 42, '@test/invalid']]);
163
+ }).toThrow('MainThreadObject type "@test/invalid" created a non-object value.');
164
+ });
165
+
166
+ it('recognizes realized objects before inspecting their properties', () => {
167
+ const value = new Proxy({ value: 42 }, {
168
+ get() {
169
+ throw new Error('unexpected property access');
170
+ },
171
+ });
172
+ globalThis.lynxWorkletImpl._refImpl.registerMainThreadObjectType(
173
+ '@test/proxy-value',
174
+ () => value,
175
+ );
176
+
177
+ updateWorkletRefInitValueChanges([[93, null, '@test/proxy-value']]);
178
+
179
+ expect(isHydratedWorkletValue(getFromWorkletRefMap({ _wvid: 93 }))).toBe(true);
180
+ removeValueFromWorkletRefMap(93);
181
+ });
182
+ });
@@ -0,0 +1,60 @@
1
+ // Copyright 2026 The Lynx Authors. All rights reserved.
2
+ // Licensed under the Apache License, Version 2.0 that can be found in the LICENSE file in the root directory.
3
+ import { afterEach, expect, it } from 'vitest';
4
+ import { transformReactLynxSync } from '@lynx-js/react-transform';
5
+
6
+ import { initApiEnv } from '../../src/worklet-runtime/api/lynxApi';
7
+ import { initWorklet } from '../../src/worklet-runtime/workletRuntime';
8
+
9
+ afterEach(() => {
10
+ delete globalThis.lynxWorkletImpl;
11
+ });
12
+
13
+ it('resolves a compiler-generated object method through whole-object captures', () => {
14
+ globalThis.SystemInfo = { lynxSdkVersion: '2.16' };
15
+ initApiEnv();
16
+ initWorklet();
17
+ const result = transformReactLynxSync(
18
+ `
19
+ export const source = {
20
+ value: 1,
21
+ method() { 'main thread'; return this.value; },
22
+ };
23
+ `,
24
+ {
25
+ mode: 'test',
26
+ pluginName: '',
27
+ filename: 'method.js',
28
+ sourcemap: false,
29
+ cssScope: false,
30
+ shake: false,
31
+ compat: false,
32
+ refresh: false,
33
+ defineDCE: { define: {} },
34
+ directiveDCE: { target: 'LEPUS' },
35
+ snapshot: {
36
+ preserveJsx: false,
37
+ runtimePkg: '@lynx-js/react/internal',
38
+ jsxImportSource: '@lynx-js/react/lepus',
39
+ target: 'LEPUS',
40
+ filename: 'method',
41
+ },
42
+ worklet: { target: 'LEPUS', filename: 'method.js', runtimePkg: '@lynx-js/react/internal' },
43
+ },
44
+ );
45
+ const source = new Function(
46
+ '__loadWorkletRuntime',
47
+ 'registerWorkletInternal',
48
+ `${result.code.replace(/^import .*;$/gm, '').replace('export const source', 'const source')}\nreturn source;`,
49
+ )(() => true, registerWorklet);
50
+ registerWorklet('main-thread', 'parent', function() {
51
+ return this._c.source.method;
52
+ });
53
+ const first = runWorklet({ _wkltId: 'parent', _c: { source } }, []);
54
+ expect(first()).toBe(1);
55
+ source.value = 2;
56
+ const second = runWorklet({ _wkltId: 'parent', _c: { source } }, []);
57
+ expect(second()).toBe(2);
58
+ expect(first()).toBe(1);
59
+ expect(Object.getOwnPropertyDescriptor(source, 'method').get).toBeTypeOf('function');
60
+ });