@amazon-devices/react-native-worklets 1.0.0 → 1.0.2

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 (110) hide show
  1. package/Common/cpp/worklets/Registries/EventHandlerRegistry.h +5 -3
  2. package/Common/cpp/worklets/RunLoop/AsyncQueueImpl.cpp +5 -6
  3. package/Common/cpp/worklets/RunLoop/EventLoop.cpp +6 -6
  4. package/Common/cpp/worklets/SharedItems/Serializable.h +9 -8
  5. package/Common/cpp/worklets/Tools/JSISerializer.h +4 -4
  6. package/Common/cpp/worklets/Tools/JSScheduler.h +5 -3
  7. package/Common/cpp/worklets/Tools/SingleInstanceChecker.h +3 -2
  8. package/Common/cpp/worklets/Tools/UIScheduler.h +4 -4
  9. package/Common/cpp/worklets/Tools/VersionUtils.h +1 -4
  10. package/Common/cpp/worklets/Tools/WorkletsSystraceSection.h +0 -25
  11. package/SystemModules/amzn__react-native-worklets-1.private.modules.txt +57 -33
  12. package/kepler-compatibility.json +3 -1
  13. package/lib/module/index.js +0 -25
  14. package/oss-attribution/attribution.txt +2262 -0
  15. package/oss-attribution/licenseInfos.json +585 -0
  16. package/package.json +1 -153
  17. package/src/index.ts +0 -52
  18. package/SystemBundles/cc12deac6e91c435b76698c8445aed85612f2f88e733218d14f88a35d06fb0f4.bundle +0 -10512
  19. package/SystemBundles/cc12deac6e91c435b76698c8445aed85612f2f88e733218d14f88a35d06fb0f4.map +0 -3771
  20. package/bundleMode/index.js +0 -59
  21. package/lib/module/PlatformChecker/PlatformChecker.js +0 -8
  22. package/lib/module/PlatformChecker/index.js +0 -18
  23. package/lib/module/WorkletsError.js +0 -29
  24. package/lib/module/WorkletsModule/JSWorklets.js +0 -111
  25. package/lib/module/WorkletsModule/NativeWorklets.js +0 -126
  26. package/lib/module/WorkletsModule/index.js +0 -4
  27. package/lib/module/WorkletsModule/workletsModuleInstance.js +0 -7
  28. package/lib/module/WorkletsModule/workletsModuleInstance.web.js +0 -5
  29. package/lib/module/WorkletsModule/workletsModuleProxy.js +0 -4
  30. package/lib/module/bundleUnpacker.js +0 -47
  31. package/lib/module/callGuard.js +0 -30
  32. package/lib/module/deprecated.js +0 -20
  33. package/lib/module/errors.js +0 -69
  34. package/lib/module/featureFlags/index.js +0 -48
  35. package/lib/module/initializers.js +0 -221
  36. package/lib/module/isSynchronizable.js +0 -6
  37. package/lib/module/logger.js +0 -15
  38. package/lib/module/privateGlobals.d.js +0 -7
  39. package/lib/module/publicGlobals.js +0 -6
  40. package/lib/module/runLoop/common/setImmediatePolyfill.js +0 -15
  41. package/lib/module/runLoop/common/setIntervalPolyfill.js +0 -26
  42. package/lib/module/runLoop/uiRuntime/mockedRequestAnimationFrame.js +0 -10
  43. package/lib/module/runLoop/uiRuntime/requestAnimationFrame.js +0 -52
  44. package/lib/module/runLoop/uiRuntime/setTimeoutPolyfill.js +0 -32
  45. package/lib/module/runLoop/workletRuntime/index.js +0 -19
  46. package/lib/module/runLoop/workletRuntime/queueMicrotask.js +0 -11
  47. package/lib/module/runLoop/workletRuntime/requestAnimationFramePolyfill.js +0 -48
  48. package/lib/module/runLoop/workletRuntime/setTimeout.js +0 -28
  49. package/lib/module/runLoop/workletRuntime/taskQueue.js +0 -37
  50. package/lib/module/runtimeKind.js +0 -39
  51. package/lib/module/runtimes.js +0 -100
  52. package/lib/module/serializable.js +0 -568
  53. package/lib/module/serializableMappingCache.js +0 -37
  54. package/lib/module/specs/NativeWorkletsModule.js +0 -5
  55. package/lib/module/specs/NativeWorkletsModule.kepler.js +0 -7
  56. package/lib/module/specs/index.js +0 -10
  57. package/lib/module/synchronizable.js +0 -9
  58. package/lib/module/synchronizableUnpacker.js +0 -42
  59. package/lib/module/threads.js +0 -347
  60. package/lib/module/utils/checkCppVersion.js +0 -30
  61. package/lib/module/utils/jsVersion.js +0 -9
  62. package/lib/module/valueUnpacker.js +0 -60
  63. package/lib/module/workletFunction.js +0 -37
  64. package/lib/module/workletRuntimeEntry.js +0 -32
  65. package/lib/module/workletTypes.js +0 -12
  66. package/scripts/validate-react-native-version.js +0 -43
  67. package/src/PlatformChecker/PlatformChecker.ts +0 -7
  68. package/src/PlatformChecker/index.ts +0 -30
  69. package/src/WorkletsError.ts +0 -36
  70. package/src/WorkletsModule/JSWorklets.ts +0 -200
  71. package/src/WorkletsModule/NativeWorklets.ts +0 -256
  72. package/src/WorkletsModule/index.ts +0 -7
  73. package/src/WorkletsModule/workletsModuleInstance.ts +0 -9
  74. package/src/WorkletsModule/workletsModuleInstance.web.ts +0 -5
  75. package/src/WorkletsModule/workletsModuleProxy.ts +0 -126
  76. package/src/bundleUnpacker.ts +0 -75
  77. package/src/callGuard.ts +0 -33
  78. package/src/deprecated.ts +0 -32
  79. package/src/errors.ts +0 -80
  80. package/src/featureFlags/index.ts +0 -72
  81. package/src/initializers.ts +0 -262
  82. package/src/isSynchronizable.ts +0 -13
  83. package/src/logger.ts +0 -16
  84. package/src/publicGlobals.ts +0 -39
  85. package/src/runLoop/common/setImmediatePolyfill.ts +0 -20
  86. package/src/runLoop/common/setIntervalPolyfill.ts +0 -38
  87. package/src/runLoop/uiRuntime/mockedRequestAnimationFrame.ts +0 -11
  88. package/src/runLoop/uiRuntime/requestAnimationFrame.ts +0 -66
  89. package/src/runLoop/uiRuntime/setTimeoutPolyfill.ts +0 -40
  90. package/src/runLoop/workletRuntime/index.ts +0 -18
  91. package/src/runLoop/workletRuntime/queueMicrotask.ts +0 -13
  92. package/src/runLoop/workletRuntime/requestAnimationFramePolyfill.ts +0 -61
  93. package/src/runLoop/workletRuntime/setTimeout.ts +0 -37
  94. package/src/runLoop/workletRuntime/taskQueue.ts +0 -44
  95. package/src/runtimeKind.ts +0 -37
  96. package/src/runtimes.ts +0 -193
  97. package/src/serializable.ts +0 -801
  98. package/src/serializableMappingCache.ts +0 -42
  99. package/src/specs/NativeWorkletsModule.kepler.ts +0 -11
  100. package/src/specs/NativeWorkletsModule.ts +0 -9
  101. package/src/specs/index.ts +0 -13
  102. package/src/synchronizable.ts +0 -32
  103. package/src/synchronizableUnpacker.ts +0 -67
  104. package/src/threads.ts +0 -452
  105. package/src/utils/checkCppVersion.ts +0 -34
  106. package/src/utils/jsVersion.ts +0 -7
  107. package/src/valueUnpacker.ts +0 -90
  108. package/src/workletFunction.ts +0 -42
  109. package/src/workletRuntimeEntry.ts +0 -35
  110. package/src/workletTypes.ts +0 -81
@@ -1,126 +0,0 @@
1
- 'use strict';
2
-
3
- import type { SynchronizableRef } from '../synchronizable';
4
- import type { SerializableRef, WorkletRuntime } from '../workletTypes';
5
-
6
- /** Type of `__workletsModuleProxy` injected with JSI. */
7
- export interface WorkletsModuleProxy {
8
- createSerializable<TValue>(
9
- value: TValue,
10
- shouldPersistRemote: boolean,
11
- nativeStateSource?: object
12
- ): SerializableRef<TValue>;
13
-
14
- createSerializableImport<TValue>(
15
- source: string,
16
- imported: string
17
- ): SerializableRef<TValue>;
18
-
19
- createSerializableString(str: string): SerializableRef<string>;
20
-
21
- createSerializableNumber(num: number): SerializableRef<number>;
22
-
23
- createSerializableBoolean(bool: boolean): SerializableRef<boolean>;
24
-
25
- createSerializableBigInt(bigInt: bigint): SerializableRef<bigint>;
26
-
27
- createSerializableUndefined(): SerializableRef<undefined>;
28
-
29
- createSerializableNull(): SerializableRef<null>;
30
-
31
- createSerializableTurboModuleLike<
32
- TProps extends object,
33
- TProto extends object,
34
- >(
35
- props: TProps,
36
- proto: TProto
37
- ): SerializableRef<TProps>;
38
-
39
- createSerializableObject<T extends object>(
40
- obj: T,
41
- shouldRetainRemote: boolean,
42
- nativeStateSource?: object
43
- ): SerializableRef<T>;
44
-
45
- createSerializableHostObject<T extends object>(obj: T): SerializableRef<T>;
46
-
47
- createSerializableArray(
48
- array: unknown[],
49
- shouldRetainRemote: boolean
50
- ): SerializableRef<unknown[]>;
51
-
52
- createSerializableMap<TKey, TValue>(
53
- keys: TKey[],
54
- values: TValue[]
55
- ): SerializableRef<Map<TKey, TValue>>;
56
-
57
- createSerializableSet<TValues>(
58
- values: TValues[]
59
- ): SerializableRef<Set<TValues>>;
60
-
61
- createSerializableInitializer(obj: object): SerializableRef<object>;
62
-
63
- createSerializableFunction<TArgs extends unknown[], TReturn>(
64
- func: (...args: TArgs) => TReturn
65
- ): SerializableRef<TReturn>;
66
-
67
- createSerializableWorklet(
68
- worklet: object,
69
- shouldPersistRemote: boolean
70
- ): SerializableRef<object>;
71
-
72
- scheduleOnUI<TValue>(serializable: SerializableRef<TValue>): void;
73
-
74
- executeOnUIRuntimeSync<TValue, TReturn>(
75
- serializable: SerializableRef<TValue>
76
- ): TReturn;
77
-
78
- createWorkletRuntime(
79
- name: string,
80
- initializer: SerializableRef<() => void>,
81
- useDefaultQueue: boolean,
82
- customQueue: object | undefined,
83
- enableEventLoop: boolean
84
- ): WorkletRuntime;
85
-
86
- scheduleOnRuntime<TValue>(
87
- workletRuntime: WorkletRuntime,
88
- worklet: SerializableRef<TValue>
89
- ): void;
90
-
91
- reportFatalErrorOnJS(
92
- message: string,
93
- stack: string,
94
- name: string,
95
- jsEngine: string
96
- ): void;
97
-
98
- createSynchronizable<TValue>(value: TValue): SynchronizableRef<TValue>;
99
-
100
- synchronizableGetDirty<TValue>(
101
- synchronizableRef: SynchronizableRef<TValue>
102
- ): TValue;
103
-
104
- synchronizableGetBlocking<TValue>(
105
- synchronizableRef: SynchronizableRef<TValue>
106
- ): TValue;
107
-
108
- synchronizableSetBlocking<TValue>(
109
- synchronizableRef: SynchronizableRef<TValue>,
110
- value: SerializableRef<TValue>
111
- ): void;
112
-
113
- synchronizableLock<TValue>(
114
- synchronizableRef: SynchronizableRef<TValue>
115
- ): void;
116
-
117
- synchronizableUnlock<TValue>(
118
- synchronizableRef: SynchronizableRef<TValue>
119
- ): void;
120
-
121
- getStaticFeatureFlag(name: string): boolean;
122
-
123
- setDynamicFeatureFlag(name: string, value: boolean): void;
124
- }
125
-
126
- export type IWorkletsModule = WorkletsModuleProxy;
@@ -1,75 +0,0 @@
1
- 'use strict';
2
- import { logger } from './logger';
3
- import { WorkletsError } from './WorkletsError';
4
- import type { WorkletFactory, WorkletFunction } from './workletTypes';
5
-
6
- const handleCache = new WeakMap<WorkletFunction, unknown>();
7
-
8
- export function bundleValueUnpacker(
9
- objectToUnpack: ObjectToUnpack,
10
- category?: string,
11
- remoteFunctionName?: string
12
- ): unknown {
13
- const workletHash = objectToUnpack.__workletHash;
14
- if (workletHash !== undefined) {
15
- return getWorklet(workletHash, objectToUnpack.__closure);
16
- } else if (objectToUnpack.__init !== undefined) {
17
- let value = handleCache.get(objectToUnpack);
18
- if (value === undefined) {
19
- value = objectToUnpack.__init();
20
- handleCache.set(objectToUnpack, value);
21
- }
22
- return value;
23
- } else if (category === 'RemoteFunction') {
24
- const remoteFunctionHolder = () => {
25
- const label = remoteFunctionName
26
- ? `function \`${remoteFunctionName}\``
27
- : 'anonymous function';
28
- throw new WorkletsError(`Tried to synchronously call a non-worklet ${label} on the UI thread.
29
- See https://docs.swmansion.com/react-native-reanimated/docs/guides/troubleshooting#tried-to-synchronously-call-a-non-worklet-function-on-the-ui-thread for more details.`);
30
- };
31
- remoteFunctionHolder.__remoteFunction = objectToUnpack;
32
- return remoteFunctionHolder;
33
- } else {
34
- throw new WorkletsError(
35
- `Data type in category "${category}" not recognized by value unpacker: "${globalThis._toString(
36
- objectToUnpack
37
- )}".`
38
- );
39
- }
40
- }
41
-
42
- function getWorklet(
43
- workletHash: number,
44
- closureVariables: Record<string, unknown>
45
- ): WorkletFunction | undefined {
46
- let worklet;
47
- if (__DEV__) {
48
- try {
49
- worklet = getWorkletFromMetroRequire(workletHash, closureVariables);
50
- } catch (_e) {
51
- logger.error(
52
- 'Unable to resolve worklet with hash ' +
53
- workletHash +
54
- '. Try reloading the app.'
55
- );
56
- }
57
- } else {
58
- worklet = getWorkletFromMetroRequire(workletHash, closureVariables);
59
- }
60
- return worklet;
61
- }
62
-
63
- const metroRequire = globalThis.__r;
64
-
65
- function getWorkletFromMetroRequire(
66
- workletHash: number,
67
- closureVariables: Record<string, unknown>
68
- ): WorkletFunction {
69
- const factory = metroRequire(workletHash).default as WorkletFactory;
70
- return factory(closureVariables);
71
- }
72
-
73
- interface ObjectToUnpack extends WorkletFunction {
74
- _recur: unknown;
75
- }
package/src/callGuard.ts DELETED
@@ -1,33 +0,0 @@
1
- 'use strict';
2
-
3
- import type { RNError } from './errors';
4
-
5
- /** Used only with debug builds. */
6
- export function callGuardDEV<Args extends unknown[], ReturnValue>(
7
- fn: (...args: Args) => ReturnValue,
8
- ...args: Args
9
- ): ReturnValue | void {
10
- 'worklet';
11
- try {
12
- return fn(...args);
13
- } catch (error) {
14
- if (globalThis.__workletsModuleProxy) {
15
- const { message, stack, name, jsEngine } = error as RNError;
16
- globalThis.__workletsModuleProxy.reportFatalErrorOnJS(
17
- message,
18
- stack ?? '',
19
- name ?? 'WorkletsError',
20
- jsEngine ?? 'Worklets'
21
- );
22
- } else {
23
- throw error;
24
- }
25
- }
26
- }
27
-
28
- export function setupCallGuard() {
29
- 'worklet';
30
- if (!globalThis.__callGuardDEV) {
31
- globalThis.__callGuardDEV = callGuardDEV;
32
- }
33
- }
package/src/deprecated.ts DELETED
@@ -1,32 +0,0 @@
1
- 'use strict';
2
-
3
- import {
4
- createSerializable,
5
- isSerializableRef,
6
- makeShareable,
7
- makeShareableCloneOnUIRecursive,
8
- } from './serializable';
9
- import { serializableMappingCache } from './serializableMappingCache';
10
- import type { SerializableRef } from './workletTypes';
11
-
12
- /** @deprecated Use {@link SerializableRef} instead. */
13
- export type ShareableRef<T> = SerializableRef<T>;
14
-
15
- export { makeShareable, makeShareableCloneOnUIRecursive };
16
-
17
- /** @deprecated It will be removed in the next major version. */
18
- export type MakeShareableClone = <T>(
19
- value: T,
20
- shouldPersistRemote?: boolean,
21
- depth?: number
22
- ) => ShareableRef<T>;
23
-
24
- /** @deprecated Use {@link createSerializable} instead. */
25
- export const makeShareableCloneRecursive: MakeShareableClone =
26
- createSerializable;
27
-
28
- /** @deprecated Use {@link isSerializableRef} instead. */
29
- export const isShareableRef = isSerializableRef;
30
-
31
- /** @deprecated Use {@link serializableMappingCache} instead. */
32
- export const shareableMappingCache = serializableMappingCache;
package/src/errors.ts DELETED
@@ -1,80 +0,0 @@
1
- 'use strict';
2
-
3
- import { WorkletsError } from './WorkletsError';
4
- import type { WorkletStackDetails } from './workletTypes';
5
-
6
- const _workletStackDetails = new Map<number, WorkletStackDetails>();
7
-
8
- export function registerWorkletStackDetails(
9
- hash: number,
10
- stackDetails: WorkletStackDetails
11
- ) {
12
- _workletStackDetails.set(hash, stackDetails);
13
- }
14
-
15
- function getBundleOffset(error: Error): [string, number, number] {
16
- const frame = error.stack?.split('\n')?.[0];
17
- if (frame) {
18
- const parsedFrame = /@([^@]+):(\d+):(\d+)/.exec(frame);
19
- if (parsedFrame) {
20
- const [, file, line, col] = parsedFrame;
21
- return [file, Number(line), Number(col)];
22
- }
23
- }
24
- return ['unknown', 0, 0];
25
- }
26
-
27
- function processStack(stack?: string): string | undefined {
28
- if (stack === '' || stack === undefined) {
29
- return undefined;
30
- }
31
- const workletStackEntries = stack.match(/worklet_(\d+):(\d+):(\d+)/g);
32
- let result = stack;
33
- workletStackEntries?.forEach((match) => {
34
- const [, hash, origLine, origCol] = match.split(/:|_/).map(Number);
35
- const errorDetails = _workletStackDetails.get(hash);
36
- if (!errorDetails) {
37
- return;
38
- }
39
- const [error, lineOffset, colOffset] = errorDetails;
40
- const [bundleFile, bundleLine, bundleCol] = getBundleOffset(error);
41
- const line = origLine + bundleLine + lineOffset;
42
- const col = origCol + bundleCol + colOffset;
43
-
44
- result = result.replace(match, `${bundleFile}:${line}:${col}`);
45
- });
46
- return result;
47
- }
48
-
49
- export interface RNError extends Error {
50
- jsEngine: string;
51
- }
52
-
53
- /**
54
- * Remote error is an error coming from a Worklet Runtime that we bubble up to
55
- * the RN Runtime.
56
- */
57
- export function reportFatalRemoteError(
58
- { message, stack, name, jsEngine }: RNError,
59
- force: boolean
60
- ): void {
61
- const error = new WorkletsError() as RNError;
62
- error.message = message;
63
- error.stack = processStack(stack);
64
- error.name = name;
65
- error.jsEngine = jsEngine;
66
- if (force) {
67
- throw error;
68
- } else {
69
- // @ts-expect-error React Native's `ErrorUtils` are hidden from the global scope.
70
- globalThis.ErrorUtils.reportFatalError(error);
71
- }
72
- }
73
-
74
- /**
75
- * Registers `reportFatalRemoteError` function in global scope to allow to
76
- * invoke it from C++.
77
- */
78
- export function registerReportFatalRemoteError() {
79
- globalThis.__reportFatalRemoteError = reportFatalRemoteError;
80
- }
@@ -1,72 +0,0 @@
1
- 'use strict';
2
- import { logger } from '../logger';
3
- import { WorkletsModule } from '../WorkletsModule';
4
- import type StaticFeatureFlagsJSON from './staticFlags.json';
5
-
6
- type DynamicFlagsType = {
7
- EXAMPLE_DYNAMIC_FLAG: boolean;
8
- init(): void;
9
- setFlag(name: DynamicFlagName, value: boolean): void;
10
- };
11
- type DynamicFlagName = keyof Omit<Omit<DynamicFlagsType, 'setFlag'>, 'init'>;
12
-
13
- export const DynamicFlags: DynamicFlagsType = {
14
- EXAMPLE_DYNAMIC_FLAG: true,
15
-
16
- init() {
17
- Object.keys(DynamicFlags).forEach((key) => {
18
- if (key !== 'init' && key !== 'setFlag') {
19
- WorkletsModule.setDynamicFeatureFlag(
20
- key,
21
- DynamicFlags[key as DynamicFlagName]
22
- );
23
- }
24
- });
25
- },
26
- setFlag(name, value) {
27
- if (name in DynamicFlags) {
28
- DynamicFlags[name] = value;
29
- WorkletsModule.setDynamicFeatureFlag(name, value);
30
- } else {
31
- logger.warn(
32
- `The feature flag: '${name}' no longer exists, you can safely remove invocation of \`setDynamicFeatureFlag('${name}')\` from your code.`
33
- );
34
- }
35
- },
36
- };
37
- DynamicFlags.init();
38
- // Public API function to update a feature flag
39
- export function setDynamicFeatureFlag(
40
- name: DynamicFlagName,
41
- value: boolean
42
- ): void {
43
- DynamicFlags.setFlag(name, value);
44
- }
45
-
46
- /**
47
- * This constant is needed for typechecking and preserving static typechecks in
48
- * generated .d.ts files. Without it, the static flags resolve to an object
49
- * without specific keys.
50
- */
51
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
52
- const DefaultStaticFeatureFlags = {
53
- RUNTIME_TEST_FLAG: false,
54
- IOS_DYNAMIC_FRAMERATE_ENABLED: false,
55
- } as const satisfies typeof StaticFeatureFlagsJSON;
56
-
57
- type StaticFeatureFlagsSchema = {
58
- -readonly [K in keyof typeof DefaultStaticFeatureFlags]: boolean;
59
- };
60
-
61
- const staticFeatureFlags: Partial<StaticFeatureFlagsSchema> = {};
62
-
63
- export function getStaticFeatureFlag(
64
- name: keyof StaticFeatureFlagsSchema
65
- ): boolean {
66
- if (name in staticFeatureFlags) {
67
- return staticFeatureFlags[name]!;
68
- }
69
- const featureFlagValue = WorkletsModule.getStaticFeatureFlag(name);
70
- staticFeatureFlags[name] = featureFlagValue;
71
- return featureFlagValue;
72
- }
@@ -1,262 +0,0 @@
1
- 'use strict';
2
-
3
- import { bundleValueUnpacker } from './bundleUnpacker';
4
- import { setupCallGuard } from './callGuard';
5
- import { registerReportFatalRemoteError } from './errors';
6
- import { IS_JEST, SHOULD_BE_USE_WEB } from './PlatformChecker';
7
- import { setupSetImmediate } from './runLoop/common/setImmediatePolyfill';
8
- import { setupSetInterval } from './runLoop/common/setIntervalPolyfill';
9
- import { mockedRequestAnimationFrame } from './runLoop/uiRuntime/mockedRequestAnimationFrame';
10
- import { setupRequestAnimationFrame } from './runLoop/uiRuntime/requestAnimationFrame';
11
- import { setupSetTimeout } from './runLoop/uiRuntime/setTimeoutPolyfill';
12
- import { RuntimeKind } from './runtimeKind';
13
- import { __installUnpacker as installSynchronizableUnpacker } from './synchronizableUnpacker';
14
- import { executeOnUIRuntimeSync, runOnJS, setupMicrotasks } from './threads';
15
- import { isWorkletFunction } from './workletFunction';
16
- import { registerWorkletsError, WorkletsError } from './WorkletsError';
17
- import { WorkletsModule } from './WorkletsModule';
18
- import type { ValueUnpacker } from './workletTypes';
19
-
20
- let capturableConsole: typeof console;
21
-
22
- /**
23
- * Currently there seems to be a bug in the JSI layer which causes a crash when
24
- * we try to copy some of the console methods, i.e. `clear` or `dirxml`.
25
- *
26
- * The crash happens only in React Native 0.75. It's not reproducible in neither
27
- * 0.76 nor 0.74. It also happens only in the configuration of a debug app and
28
- * production bundle.
29
- *
30
- * I haven't yet discovered what exactly causes the crash. It's tied to the
31
- * console methods sometimes being `HostFunction`s. Therefore, as a workaround
32
- * we don't copy the methods as they are in the original console object, we copy
33
- * JavaScript wrappers instead.
34
- */
35
- export function getMemorySafeCapturableConsole(): typeof console {
36
- if (capturableConsole) {
37
- return capturableConsole;
38
- }
39
-
40
- const consoleCopy = Object.fromEntries(
41
- Object.entries(console).map(([methodName, method]) => {
42
- const methodWrapper = function methodWrapper(...args: unknown[]) {
43
- return method(...args);
44
- };
45
- if (method.name) {
46
- /**
47
- * Set the original method name as the wrapper name if available.
48
- *
49
- * It might be unnecessary but if we want to fully mimic the console
50
- * object we should take into the account the fact some code might rely
51
- * on the method name.
52
- */
53
- Object.defineProperty(methodWrapper, 'name', {
54
- value: method.name,
55
- writable: false,
56
- });
57
- }
58
- return [methodName, methodWrapper];
59
- })
60
- );
61
-
62
- capturableConsole = consoleCopy as unknown as typeof console;
63
-
64
- return consoleCopy as unknown as typeof console;
65
- }
66
-
67
- export function setupConsole(boundCapturableConsole: typeof console) {
68
- 'worklet';
69
- // @ts-ignore TypeScript doesn't like that there are missing methods in console object, but we don't provide all the methods for the UI runtime console version
70
- globalThis.console = {
71
- assert: runOnJS(boundCapturableConsole.assert),
72
- debug: runOnJS(boundCapturableConsole.debug),
73
- log: runOnJS(boundCapturableConsole.log),
74
- warn: runOnJS(boundCapturableConsole.warn),
75
- error: runOnJS(boundCapturableConsole.error),
76
- info: runOnJS(boundCapturableConsole.info),
77
- };
78
- }
79
-
80
- let initialized = false;
81
-
82
- export function init() {
83
- if (initialized) {
84
- return;
85
- }
86
- initialized = true;
87
-
88
- if (globalThis.__RUNTIME_KIND === undefined) {
89
- // The only runtime that doesn't have `__RUNTIME_KIND` preconfigured
90
- // is the RN Runtime. We must set it as soon as possible.
91
- globalThis.__RUNTIME_KIND = RuntimeKind.ReactNative;
92
- }
93
-
94
- initializeRuntime();
95
-
96
- if (SHOULD_BE_USE_WEB) {
97
- initializeRuntimeOnWeb();
98
- }
99
-
100
- if (globalThis.__RUNTIME_KIND !== RuntimeKind.ReactNative) {
101
- initializeWorkletRuntime();
102
- } else {
103
- initializeRNRuntime();
104
- if (!SHOULD_BE_USE_WEB) {
105
- installRNBindingsOnUIRuntime();
106
- }
107
- }
108
- }
109
-
110
- /** A function that should be run on any kind of runtime. */
111
- function initializeRuntime() {
112
- if (globalThis._WORKLETS_BUNDLE_MODE) {
113
- globalThis.__valueUnpacker = bundleValueUnpacker as ValueUnpacker;
114
- }
115
- installSynchronizableUnpacker();
116
- }
117
-
118
- /** A function that should be run only on React Native runtime. */
119
- function initializeRNRuntime() {
120
- if (__DEV__) {
121
- const testWorklet = () => {
122
- 'worklet';
123
- };
124
- if (!isWorkletFunction(testWorklet)) {
125
- throw new WorkletsError(
126
- `Failed to create a worklet. See https://docs.swmansion.com/react-native-reanimated/docs/guides/troubleshooting#failed-to-create-a-worklet for more details.`
127
- );
128
- }
129
- }
130
-
131
- registerReportFatalRemoteError();
132
- }
133
-
134
- /** A function that should be run only on Worklet runtimes. */
135
- function initializeWorkletRuntime() {
136
- if (globalThis._WORKLETS_BUNDLE_MODE) {
137
- setupCallGuard();
138
-
139
- if (__DEV__) {
140
- /*
141
- * Temporary workaround for Metro bundler. We must implement a dummy
142
- * Refresh module to prevent Metro from throwing irrelevant errors.
143
- */
144
- const Refresh = new Proxy(
145
- {},
146
- {
147
- get() {
148
- return () => {};
149
- },
150
- }
151
- );
152
-
153
- globalThis.__r.Refresh = Refresh;
154
-
155
- /* Gracefully handle unwanted imports from React Native. */
156
- // @ts-expect-error type not exposed by Metro
157
- const modules = require.getModules();
158
- // @ts-expect-error type not exposed by Metro
159
- const ReactNativeModuleId = require.resolveWeak('react-native');
160
-
161
- const factory = function (
162
- _global: unknown,
163
- _require: unknown,
164
- _importDefault: unknown,
165
- _importAll: unknown,
166
- module: Record<string, unknown>,
167
- _exports: unknown,
168
- _dependencyMap: unknown
169
- ) {
170
- module.exports = new Proxy(
171
- {},
172
- {
173
- get: function get(_target, prop) {
174
- globalThis.console.warn(
175
- `You tried to import '${String(prop)}' from 'react-native' module on a Worklet Runtime. Using 'react-native' module on a Worklet Runtime is not allowed.`
176
- );
177
- return {
178
- get() {
179
- return undefined;
180
- },
181
- };
182
- },
183
- }
184
- );
185
- };
186
-
187
- const mod = {
188
- dependencyMap: [],
189
- factory,
190
- hasError: false,
191
- importedAll: {},
192
- importedDefault: {},
193
- isInitialized: false,
194
- publicModule: {
195
- exports: {},
196
- },
197
- };
198
-
199
- modules.set(ReactNativeModuleId, mod);
200
- }
201
- }
202
- }
203
-
204
- /** A function that should be run only on RN Runtime in web implementation. */
205
- function initializeRuntimeOnWeb() {
206
- globalThis._WORKLET = false;
207
- globalThis._log = console.log;
208
- globalThis._getAnimationTimestamp = () => performance.now();
209
- if (IS_JEST) {
210
- // requestAnimationFrame react-native jest's setup is incorrect as it polyfills
211
- // the method directly using setTimeout, therefore the callback doesn't get the
212
- // expected timestamp as the only argument: https://github.com/facebook/react-native/blob/main/packages/react-native/jest/setup.js#L28
213
- // We override this setup here to make sure that callbacks get the proper timestamps
214
- // when executed. For non-jest environments we define requestAnimationFrame in setupRequestAnimationFrame
215
- // @ts-ignore TypeScript uses Node definition for rAF, setTimeout, etc which returns a Timeout object rather than a number
216
- globalThis.requestAnimationFrame = mockedRequestAnimationFrame;
217
- }
218
- }
219
-
220
- /**
221
- * A function that should be run on the RN Runtime to configure the UI Runtime
222
- * with callback bindings.
223
- */
224
- function installRNBindingsOnUIRuntime() {
225
- if (!WorkletsModule) {
226
- throw new WorkletsError(
227
- 'Worklets are trying to initialize the UI runtime without a valid WorkletsModule'
228
- );
229
- }
230
-
231
- const runtimeBoundCapturableConsole = getMemorySafeCapturableConsole();
232
-
233
- if (!globalThis._WORKLETS_BUNDLE_MODE) {
234
- /** In bundle mode Runtimes setup their callGuard themselves. */
235
- executeOnUIRuntimeSync(setupCallGuard)();
236
-
237
- /**
238
- * Register WorkletsError in the UI runtime global scope. (we are using
239
- * `executeOnUIRuntimeSync` here to make sure that the changes are applied
240
- * before any async operations are executed on the UI runtime).
241
- *
242
- * There's no need to register the error in bundle mode.
243
- */
244
- executeOnUIRuntimeSync(registerWorkletsError)();
245
- }
246
-
247
- executeOnUIRuntimeSync(() => {
248
- 'worklet';
249
-
250
- setupConsole(runtimeBoundCapturableConsole);
251
- /**
252
- * TODO: Move `setupMicrotasks` and `setupRequestAnimationFrame` to a
253
- * separate function once we have a better way to distinguish between
254
- * Worklet Runtimes.
255
- */
256
- setupMicrotasks();
257
- setupRequestAnimationFrame();
258
- setupSetTimeout();
259
- setupSetImmediate();
260
- setupSetInterval();
261
- })();
262
- }
@@ -1,13 +0,0 @@
1
- 'use strict';
2
- import type { Synchronizable } from './synchronizable';
3
-
4
- export function isSynchronizable<TValue>(
5
- value: unknown
6
- ): value is Synchronizable<TValue> {
7
- return (
8
- typeof value === 'object' &&
9
- value !== null &&
10
- '__synchronizableRef' in value &&
11
- value.__synchronizableRef === true
12
- );
13
- }