@depup/react-native-worklets 0.11.3-depup.0 → 0.12.1-depup.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 (77) hide show
  1. package/Common/cpp/worklets/AnimationFrameQueue/AnimationFrameBatchinator.cpp +6 -3
  2. package/Common/cpp/worklets/Compat/StableApi.cpp +4 -0
  3. package/Common/cpp/worklets/Compat/StableApi.h +3 -1
  4. package/Common/cpp/worklets/NativeModules/JSIWorkletsModuleProxy.cpp +26 -43
  5. package/Common/cpp/worklets/RunLoop/AsyncQueueImpl.cpp +32 -0
  6. package/Common/cpp/worklets/RunLoop/EventLoop.cpp +16 -7
  7. package/Common/cpp/worklets/RunLoop/EventLoop.h +4 -2
  8. package/Common/cpp/worklets/SharedItems/MemoryManager.cpp +2 -2
  9. package/Common/cpp/worklets/SharedItems/Serializable.h +14 -16
  10. package/Common/cpp/worklets/Tools/UIScheduler.cpp +10 -0
  11. package/Common/cpp/worklets/Tools/UIScheduler.h +3 -0
  12. package/Common/cpp/worklets/Tools/WorkletsJSIUtils.h +23 -0
  13. package/Common/cpp/worklets/WorkletRuntime/RuntimeManager.cpp +7 -4
  14. package/Common/cpp/worklets/WorkletRuntime/RuntimeManager.h +2 -1
  15. package/Common/cpp/worklets/WorkletRuntime/WorkletRuntime.cpp +60 -88
  16. package/Common/cpp/worklets/WorkletRuntime/WorkletRuntime.h +335 -122
  17. package/README.md +2 -2
  18. package/android/build.gradle.kts +20 -6
  19. package/android/src/main/cpp/worklets/android/AndroidUIScheduler.cpp +10 -8
  20. package/android/src/main/cpp/worklets/android/JScriptBufferWrapper.cpp +2 -11
  21. package/android/src/main/cpp/worklets/android/JScriptBufferWrapper.h +1 -4
  22. package/android/src/main/java/com/swmansion/worklets/AndroidUIScheduler.kt +3 -0
  23. package/android/src/main/java/com/swmansion/worklets/ScriptBufferWrapper.kt +87 -43
  24. package/android/src/networking/com/swmansion/worklets/WorkletsModule.kt +25 -9
  25. package/android/src/no-networking/com/swmansion/worklets/WorkletsModule.kt +25 -9
  26. package/apple/worklets/apple/IOSUIScheduler.h +3 -0
  27. package/apple/worklets/apple/IOSUIScheduler.mm +6 -1
  28. package/apple/worklets/apple/ScriptLoader.h +11 -0
  29. package/apple/worklets/apple/ScriptLoader.mm +124 -0
  30. package/apple/worklets/apple/WorkletsModule.h +1 -16
  31. package/apple/worklets/apple/WorkletsModule.mm +4 -16
  32. package/changes.json +1 -1
  33. package/compatibility.json +4 -1
  34. package/lib/module/WorkletsModule/NativeWorklets.native.js +2 -2
  35. package/lib/module/WorkletsModule/NativeWorklets.native.js.map +1 -1
  36. package/lib/module/debug/jsVersion.js +1 -1
  37. package/lib/module/memory/serializable.native.js +59 -21
  38. package/lib/module/memory/serializable.native.js.map +1 -1
  39. package/lib/module/mock.js +58 -17
  40. package/lib/module/mock.js.map +1 -1
  41. package/lib/module/runLoop/uiRuntime/requestAnimationFrame.js +1 -2
  42. package/lib/module/runLoop/uiRuntime/requestAnimationFrame.js.map +1 -1
  43. package/lib/module/runLoop/workletRuntime/taskQueue.js +0 -1
  44. package/lib/module/runLoop/workletRuntime/taskQueue.js.map +1 -1
  45. package/lib/module/runtimes.native.js +7 -8
  46. package/lib/module/runtimes.native.js.map +1 -1
  47. package/lib/module/threads.js +35 -24
  48. package/lib/module/threads.js.map +1 -1
  49. package/lib/typescript/WorkletsModule/NativeWorklets.native.d.ts.map +1 -1
  50. package/lib/typescript/WorkletsModule/workletsModuleProxy.d.ts +1 -1
  51. package/lib/typescript/WorkletsModule/workletsModuleProxy.d.ts.map +1 -1
  52. package/lib/typescript/debug/jsVersion.d.ts +1 -1
  53. package/lib/typescript/memory/serializable.native.d.ts.map +1 -1
  54. package/lib/typescript/runLoop/uiRuntime/requestAnimationFrame.d.ts.map +1 -1
  55. package/lib/typescript/runLoop/workletRuntime/taskQueue.d.ts.map +1 -1
  56. package/lib/typescript/runtimes.native.d.ts.map +1 -1
  57. package/lib/typescript/specs/NativeWorkletsModule.d.ts +1 -1
  58. package/lib/typescript/threads.d.ts.map +1 -1
  59. package/lib/typescript/types.d.ts +38 -8
  60. package/lib/typescript/types.d.ts.map +1 -1
  61. package/package.json +14 -15
  62. package/plugin/index.js +1625 -1572
  63. package/src/WorkletsModule/NativeWorklets.native.ts +4 -2
  64. package/src/WorkletsModule/workletsModuleProxy.ts +2 -1
  65. package/src/debug/jsVersion.ts +1 -1
  66. package/src/memory/serializable.native.ts +103 -36
  67. package/src/mock.ts +85 -23
  68. package/src/runLoop/uiRuntime/requestAnimationFrame.ts +1 -2
  69. package/src/runLoop/workletRuntime/taskQueue.ts +0 -1
  70. package/src/runtimes.native.ts +12 -8
  71. package/src/threads.ts +38 -26
  72. package/src/types.ts +42 -8
  73. package/Common/cpp/worklets/Registries/EventHandlerRegistry.cpp +0 -95
  74. package/Common/cpp/worklets/Registries/EventHandlerRegistry.h +0 -44
  75. package/Common/cpp/worklets/Tools/WorkletEventHandler.cpp +0 -34
  76. package/Common/cpp/worklets/Tools/WorkletEventHandler.h +0 -44
  77. package/jest/pluginTestUtils.ts +0 -16
package/plugin/index.js CHANGED
@@ -25,6 +25,191 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
25
25
  mod
26
26
  ));
27
27
 
28
+ // lib/directives.js
29
+ var require_directives = __commonJS({
30
+ "lib/directives.js"(exports2) {
31
+ "use strict";
32
+ Object.defineProperty(exports2, "__esModule", { value: true });
33
+ exports2.handleWorkletDirective = handleWorkletDirective;
34
+ exports2.addWorkletDirectivesToPath = addWorkletDirectivesToPath;
35
+ exports2.addWorkletDirectivesToFunctionBody = addWorkletDirectivesToFunctionBody;
36
+ exports2.addDirective = addDirective;
37
+ var types_12 = require("@babel/types");
38
+ function handleWorkletDirective(path) {
39
+ if (path.node.value.value === "worklet" && path.parentPath.isBlockStatement()) {
40
+ addDirective(path.parentPath.node, "use no memo");
41
+ }
42
+ }
43
+ function addWorkletDirectivesToPath(path) {
44
+ if (path.isArrowFunctionExpression()) {
45
+ replaceImplicitReturnWithBlock(path.node);
46
+ }
47
+ addWorkletDirectivesToFunctionBody(path.node.body);
48
+ }
49
+ function addWorkletDirectivesToFunctionBody(node) {
50
+ addDirective(node, "worklet");
51
+ addDirective(node, "use no memo");
52
+ }
53
+ function addDirective(node, dir) {
54
+ if (!node.directives.some((functionDirective) => functionDirective.value.value === dir)) {
55
+ node.directives.push((0, types_12.directive)((0, types_12.directiveLiteral)(dir)));
56
+ }
57
+ }
58
+ function replaceImplicitReturnWithBlock(path) {
59
+ if (!(0, types_12.isBlockStatement)(path.body)) {
60
+ path.body = (0, types_12.blockStatement)([(0, types_12.returnStatement)(path.body)]);
61
+ }
62
+ }
63
+ }
64
+ });
65
+
66
+ // lib/types.js
67
+ var require_types = __commonJS({
68
+ "lib/types.js"(exports2) {
69
+ "use strict";
70
+ Object.defineProperty(exports2, "__esModule", { value: true });
71
+ exports2.generatedWorkletsDir = exports2.workletClassFactorySuffix = exports2.WorkletizableObject = exports2.WorkletizableFunction = void 0;
72
+ exports2.isWorkletizableFunctionPath = isWorkletizableFunctionPath;
73
+ exports2.isWorkletizableFunctionNode = isWorkletizableFunctionNode;
74
+ exports2.isWorkletizableObjectPath = isWorkletizableObjectPath;
75
+ exports2.isWorkletizableObjectNode = isWorkletizableObjectNode;
76
+ var types_12 = require("@babel/types");
77
+ exports2.WorkletizableFunction = "FunctionDeclaration|FunctionExpression|ArrowFunctionExpression|ObjectMethod";
78
+ exports2.WorkletizableObject = "ObjectExpression";
79
+ function isWorkletizableFunctionPath(path) {
80
+ return path.isFunctionDeclaration() || path.isFunctionExpression() || path.isArrowFunctionExpression() || path.isObjectMethod();
81
+ }
82
+ function isWorkletizableFunctionNode(node) {
83
+ return (0, types_12.isFunctionDeclaration)(node) || (0, types_12.isFunctionExpression)(node) || (0, types_12.isArrowFunctionExpression)(node) || (0, types_12.isObjectMethod)(node);
84
+ }
85
+ function isWorkletizableObjectPath(path) {
86
+ return path.isObjectExpression();
87
+ }
88
+ function isWorkletizableObjectNode(node) {
89
+ return (0, types_12.isObjectExpression)(node);
90
+ }
91
+ exports2.workletClassFactorySuffix = "__classFactory";
92
+ exports2.generatedWorkletsDir = ".worklets";
93
+ }
94
+ });
95
+
96
+ // lib/referencedWorklets.js
97
+ var require_referencedWorklets = __commonJS({
98
+ "lib/referencedWorklets.js"(exports2) {
99
+ "use strict";
100
+ Object.defineProperty(exports2, "__esModule", { value: true });
101
+ exports2.findReferencedWorklet = findReferencedWorklet;
102
+ var types_12 = require("@babel/types");
103
+ var types_2 = require_types();
104
+ function findReferencedWorklet(workletIdentifier, acceptWorkletizableFunction, acceptObject, state) {
105
+ const workletName = workletIdentifier.node.name;
106
+ const scope = workletIdentifier.scope;
107
+ const workletBinding = scope.getBinding(workletName);
108
+ if (!workletBinding) {
109
+ return void 0;
110
+ }
111
+ if (state.opts.bundleMode && bindingIsWorklet(workletBinding)) {
112
+ return void 0;
113
+ }
114
+ if (acceptWorkletizableFunction && workletBinding.path.isFunctionDeclaration()) {
115
+ return workletBinding.path;
116
+ }
117
+ const isConstant = workletBinding.constant;
118
+ if (isConstant) {
119
+ return findReferencedWorkletFromVariableDeclarator(workletBinding, acceptWorkletizableFunction, acceptObject, state);
120
+ }
121
+ return findReferencedWorkletFromAssignmentExpression(workletBinding, acceptWorkletizableFunction, acceptObject, state);
122
+ }
123
+ function findReferencedWorkletFromVariableDeclarator(workletBinding, acceptWorkletizableFunction, acceptObject, state) {
124
+ const workletDeclaration = workletBinding.path;
125
+ if (!workletDeclaration.isVariableDeclarator()) {
126
+ return void 0;
127
+ }
128
+ const worklet = workletDeclaration.get("init");
129
+ if (acceptWorkletizableFunction && (0, types_2.isWorkletizableFunctionPath)(worklet)) {
130
+ return worklet;
131
+ }
132
+ if (acceptObject && (0, types_2.isWorkletizableObjectPath)(worklet)) {
133
+ return worklet;
134
+ }
135
+ if (worklet.isIdentifier() && worklet.isReferencedIdentifier()) {
136
+ return findReferencedWorklet(worklet, acceptWorkletizableFunction, acceptObject, state);
137
+ }
138
+ return void 0;
139
+ }
140
+ function findReferencedWorkletFromAssignmentExpression(workletBinding, acceptWorkletizableFunction, acceptObject, state) {
141
+ const workletDeclaration = workletBinding.constantViolations.reverse().find((constantViolation) => constantViolation.isAssignmentExpression() && (acceptWorkletizableFunction && (0, types_2.isWorkletizableFunctionPath)(constantViolation.get("right")) || acceptObject && (0, types_2.isWorkletizableObjectPath)(constantViolation.get("right"))));
142
+ if (!workletDeclaration || !workletDeclaration.isAssignmentExpression()) {
143
+ return void 0;
144
+ }
145
+ const workletDefinition = workletDeclaration.get("right");
146
+ if (acceptWorkletizableFunction && (0, types_2.isWorkletizableFunctionPath)(workletDefinition)) {
147
+ return workletDefinition;
148
+ }
149
+ if (acceptObject && (0, types_2.isWorkletizableObjectPath)(workletDefinition)) {
150
+ return workletDefinition;
151
+ }
152
+ if (workletDefinition.isIdentifier() && workletDefinition.isReferencedIdentifier()) {
153
+ return findReferencedWorklet(workletDefinition, acceptWorkletizableFunction, acceptObject, state);
154
+ }
155
+ return void 0;
156
+ }
157
+ function bindingIsWorklet(binding) {
158
+ return binding.referencePaths.some((refPath) => !Array.isArray(refPath.container) && (0, types_12.isMemberExpression)(refPath.container) && refPath.container.object === refPath.node && (0, types_12.isIdentifier)(refPath.container.property) && refPath.container.property.name === "__workletHash");
159
+ }
160
+ }
161
+ });
162
+
163
+ // lib/findWorklet.js
164
+ var require_findWorklet = __commonJS({
165
+ "lib/findWorklet.js"(exports2) {
166
+ "use strict";
167
+ Object.defineProperty(exports2, "__esModule", { value: true });
168
+ exports2.findWorklet = findWorklet;
169
+ exports2.forEachWorkletizableFunction = forEachWorkletizableFunction;
170
+ exports2.forEachWorkletizableObjectProperty = forEachWorkletizableObjectProperty;
171
+ var referencedWorklets_1 = require_referencedWorklets();
172
+ var types_12 = require_types();
173
+ function findWorklet(nodePath, state, acceptWorkletizableFunction, acceptObject) {
174
+ if (acceptWorkletizableFunction && (0, types_12.isWorkletizableFunctionPath)(nodePath)) {
175
+ return nodePath;
176
+ }
177
+ if (acceptObject && (0, types_12.isWorkletizableObjectPath)(nodePath)) {
178
+ return nodePath;
179
+ }
180
+ if (nodePath.isIdentifier() && nodePath.isReferencedIdentifier()) {
181
+ const worklet = (0, referencedWorklets_1.findReferencedWorklet)(nodePath, acceptWorkletizableFunction, acceptObject, state);
182
+ return worklet;
183
+ }
184
+ return void 0;
185
+ }
186
+ function forEachWorkletizableFunction(arg, state, acceptWorkletizableFunction, acceptObject, callback) {
187
+ const maybeWorklet = findWorklet(arg, state, acceptWorkletizableFunction, acceptObject);
188
+ if (!maybeWorklet) {
189
+ return;
190
+ }
191
+ if ((0, types_12.isWorkletizableFunctionPath)(maybeWorklet)) {
192
+ callback(maybeWorklet);
193
+ } else if ((0, types_12.isWorkletizableObjectPath)(maybeWorklet)) {
194
+ forEachWorkletizableObjectProperty(maybeWorklet, state, callback);
195
+ }
196
+ }
197
+ function forEachWorkletizableObjectProperty(path, state, callback) {
198
+ const properties = path.get("properties");
199
+ for (const property of properties) {
200
+ if (property.isObjectMethod()) {
201
+ callback(property);
202
+ } else if (property.isObjectProperty()) {
203
+ const value = property.get("value");
204
+ forEachWorkletizableFunction(value, state, true, false, callback);
205
+ } else {
206
+ throw new Error(`'${property.type}' as to-be workletized argument is not supported for object hooks.`);
207
+ }
208
+ }
209
+ }
210
+ }
211
+ });
212
+
28
213
  // lib/gestureHandlerAutoworkletization.js
29
214
  var require_gestureHandlerAutoworkletization = __commonJS({
30
215
  "lib/gestureHandlerAutoworkletization.js"(exports2) {
@@ -251,124 +436,173 @@ var require_layoutAnimationAutoworkletization = __commonJS({
251
436
  }
252
437
  });
253
438
 
254
- // lib/types.js
255
- var require_types = __commonJS({
256
- "lib/types.js"(exports2) {
439
+ // lib/autoworkletization.js
440
+ var require_autoworkletization = __commonJS({
441
+ "lib/autoworkletization.js"(exports2) {
257
442
  "use strict";
258
443
  Object.defineProperty(exports2, "__esModule", { value: true });
259
- exports2.generatedWorkletsDir = exports2.workletClassFactorySuffix = exports2.WorkletizableObject = exports2.WorkletizableFunction = void 0;
260
- exports2.isWorkletizableFunctionPath = isWorkletizableFunctionPath;
261
- exports2.isWorkletizableFunctionNode = isWorkletizableFunctionNode;
262
- exports2.isWorkletizableObjectPath = isWorkletizableObjectPath;
263
- exports2.isWorkletizableObjectNode = isWorkletizableObjectNode;
444
+ exports2.addDirectivesToKnownCallback = addDirectivesToKnownCallback;
445
+ exports2.handleWorkletizableCallback = handleWorkletizableCallback;
264
446
  var types_12 = require("@babel/types");
265
- exports2.WorkletizableFunction = "FunctionDeclaration|FunctionExpression|ArrowFunctionExpression|ObjectMethod";
266
- exports2.WorkletizableObject = "ObjectExpression";
267
- function isWorkletizableFunctionPath(path) {
268
- return path.isFunctionDeclaration() || path.isFunctionExpression() || path.isArrowFunctionExpression() || path.isObjectMethod();
269
- }
270
- function isWorkletizableFunctionNode(node) {
271
- return (0, types_12.isFunctionDeclaration)(node) || (0, types_12.isFunctionExpression)(node) || (0, types_12.isArrowFunctionExpression)(node) || (0, types_12.isObjectMethod)(node);
447
+ var directives_12 = require_directives();
448
+ var findWorklet_1 = require_findWorklet();
449
+ var gestureHandlerAutoworkletization_1 = require_gestureHandlerAutoworkletization();
450
+ var layoutAnimationAutoworkletization_1 = require_layoutAnimationAutoworkletization();
451
+ var reanimatedObjectHooks = /* @__PURE__ */ new Set([
452
+ "useAnimatedScrollHandler",
453
+ ...Array.from(gestureHandlerAutoworkletization_1.gestureHandlerObjectHooks)
454
+ ]);
455
+ var reanimatedFunctionHooks = /* @__PURE__ */ new Set([
456
+ "useFrameCallback",
457
+ "useAnimatedStyle",
458
+ "useAnimatedProps",
459
+ "createAnimatedPropAdapter",
460
+ "useDerivedValue",
461
+ "useAnimatedScrollHandler",
462
+ "useAnimatedReaction",
463
+ // animations' callbacks
464
+ "withTiming",
465
+ "withSpring",
466
+ "withDecay",
467
+ "withRepeat",
468
+ // scheduling functions
469
+ "runOnUI",
470
+ "executeOnUIRuntimeSync",
471
+ "scheduleOnUI",
472
+ "runOnUISync",
473
+ "runOnUIAsync",
474
+ "runOnRuntime",
475
+ "runOnRuntimeSync",
476
+ "runOnRuntimeAsync",
477
+ "scheduleOnRuntime",
478
+ "runOnRuntimeSyncWithId",
479
+ "scheduleOnRuntimeWithId"
480
+ ]);
481
+ var reanimatedFunctionArgsToWorkletize = new Map([
482
+ ["useFrameCallback", [0]],
483
+ ["useAnimatedStyle", [0]],
484
+ ["useAnimatedProps", [0]],
485
+ ["createAnimatedPropAdapter", [0]],
486
+ ["useDerivedValue", [0]],
487
+ ["useAnimatedScrollHandler", [0]],
488
+ ["useAnimatedReaction", [0, 1]],
489
+ ["withTiming", [2]],
490
+ ["withSpring", [2]],
491
+ ["withDecay", [1]],
492
+ ["withRepeat", [3]],
493
+ ["runOnUI", [0]],
494
+ ["executeOnUIRuntimeSync", [0]],
495
+ ["scheduleOnUI", [0]],
496
+ ["runOnUISync", [0]],
497
+ ["runOnUIAsync", [0]],
498
+ ["runOnRuntime", [1]],
499
+ ["runOnRuntimeSync", [1]],
500
+ ["runOnRuntimeAsync", [1]],
501
+ ["scheduleOnRuntime", [1]],
502
+ ["runOnRuntimeSyncWithId", [1]],
503
+ ["scheduleOnRuntimeWithId", [1]],
504
+ ...Array.from(gestureHandlerAutoworkletization_1.gestureHandlerObjectHooks).map((name) => [name, [0]]),
505
+ ...Array.from(gestureHandlerAutoworkletization_1.gestureHandlerBuilderMethods).map((name) => [name, [0]])
506
+ ]);
507
+ function addDirectivesToKnownCallback(path) {
508
+ if ((0, gestureHandlerAutoworkletization_1.isGestureHandlerEventCallback)(path) || (0, layoutAnimationAutoworkletization_1.isLayoutAnimationCallback)(path)) {
509
+ (0, directives_12.addWorkletDirectivesToPath)(path);
510
+ }
272
511
  }
273
- function isWorkletizableObjectPath(path) {
274
- return path.isObjectExpression();
512
+ function handleWorkletizableCallback(path, state) {
513
+ const callee = (0, types_12.isSequenceExpression)(path.node.callee) ? path.node.callee.expressions[path.node.callee.expressions.length - 1] : path.node.callee;
514
+ const name = "name" in callee ? callee.name : "property" in callee && "name" in callee.property ? callee.property.name : void 0;
515
+ if (name === void 0) {
516
+ return;
517
+ }
518
+ if (reanimatedFunctionHooks.has(name) || reanimatedObjectHooks.has(name)) {
519
+ const acceptWorkletizableFunction = reanimatedFunctionHooks.has(name);
520
+ const acceptObject = reanimatedObjectHooks.has(name);
521
+ const argIndices = reanimatedFunctionArgsToWorkletize.get(name);
522
+ const args = path.get("arguments").filter((_, index) => argIndices.includes(index));
523
+ addDirectivesToArgs(args, state, acceptWorkletizableFunction, acceptObject);
524
+ } else if (!(0, types_12.isV8IntrinsicIdentifier)(callee) && (0, gestureHandlerAutoworkletization_1.isGestureObjectEventCallbackMethod)(callee)) {
525
+ const args = path.get("arguments");
526
+ addDirectivesToArgs(args, state, true, true);
527
+ }
275
528
  }
276
- function isWorkletizableObjectNode(node) {
277
- return (0, types_12.isObjectExpression)(node);
529
+ function addDirectivesToArgs(args, state, acceptWorkletizableFunction, acceptObject) {
530
+ args.forEach((arg) => {
531
+ (0, findWorklet_1.forEachWorkletizableFunction)(arg, state, acceptWorkletizableFunction, acceptObject, directives_12.addWorkletDirectivesToPath);
532
+ });
278
533
  }
279
- exports2.workletClassFactorySuffix = "__classFactory";
280
- exports2.generatedWorkletsDir = ".worklets";
281
534
  }
282
535
  });
283
536
 
284
- // lib/referencedWorklets.js
285
- var require_referencedWorklets = __commonJS({
286
- "lib/referencedWorklets.js"(exports2) {
537
+ // lib/bundleMode.js
538
+ var require_bundleMode = __commonJS({
539
+ "lib/bundleMode.js"(exports2) {
287
540
  "use strict";
288
541
  Object.defineProperty(exports2, "__esModule", { value: true });
289
- exports2.findReferencedWorklet = findReferencedWorklet;
542
+ exports2.toggleBundleMode = toggleBundleMode;
290
543
  var types_12 = require("@babel/types");
291
- var types_2 = require_types();
292
- function findReferencedWorklet(workletIdentifier, acceptWorkletizableFunction, acceptObject, state) {
293
- const workletName = workletIdentifier.node.name;
294
- const scope = workletIdentifier.scope;
295
- const workletBinding = scope.getBinding(workletName);
296
- if (!workletBinding) {
297
- return void 0;
298
- }
299
- if (state.opts.bundleMode && bindingIsWorklet(workletBinding)) {
300
- return void 0;
301
- }
302
- if (acceptWorkletizableFunction && workletBinding.path.isFunctionDeclaration()) {
303
- return workletBinding.path;
304
- }
305
- const isConstant = workletBinding.constant;
306
- if (isConstant) {
307
- return findReferencedWorkletFromVariableDeclarator(workletBinding, acceptWorkletizableFunction, acceptObject, state);
308
- }
309
- return findReferencedWorkletFromAssignmentExpression(workletBinding, acceptWorkletizableFunction, acceptObject, state);
310
- }
311
- function findReferencedWorkletFromVariableDeclarator(workletBinding, acceptWorkletizableFunction, acceptObject, state) {
312
- const workletDeclaration = workletBinding.path;
313
- if (!workletDeclaration.isVariableDeclarator()) {
314
- return void 0;
315
- }
316
- const worklet = workletDeclaration.get("init");
317
- if (acceptWorkletizableFunction && (0, types_2.isWorkletizableFunctionPath)(worklet)) {
318
- return worklet;
319
- }
320
- if (acceptObject && (0, types_2.isWorkletizableObjectPath)(worklet)) {
321
- return worklet;
322
- }
323
- if (worklet.isIdentifier() && worklet.isReferencedIdentifier()) {
324
- return findReferencedWorklet(worklet, acceptWorkletizableFunction, acceptObject, state);
325
- }
326
- return void 0;
327
- }
328
- function findReferencedWorkletFromAssignmentExpression(workletBinding, acceptWorkletizableFunction, acceptObject, state) {
329
- const workletDeclaration = workletBinding.constantViolations.reverse().find((constantViolation) => constantViolation.isAssignmentExpression() && (acceptWorkletizableFunction && (0, types_2.isWorkletizableFunctionPath)(constantViolation.get("right")) || acceptObject && (0, types_2.isWorkletizableObjectPath)(constantViolation.get("right"))));
330
- if (!workletDeclaration || !workletDeclaration.isAssignmentExpression()) {
331
- return void 0;
544
+ var path_1 = require("path");
545
+ var WORKLETS_PACKAGE = "react-native-worklets";
546
+ var WORKLETS_SRC_DIR = (0, path_1.join)(WORKLETS_PACKAGE, "src");
547
+ var WORKLETS_LIB_DIR = (0, path_1.join)(WORKLETS_PACKAGE, "lib", "module");
548
+ var togglePaths = [
549
+ (0, path_1.join)(WORKLETS_SRC_DIR, "index.ts"),
550
+ (0, path_1.join)(WORKLETS_SRC_DIR, "debug", "bundleMode.native.ts"),
551
+ (0, path_1.join)(WORKLETS_LIB_DIR, "index.js"),
552
+ (0, path_1.join)(WORKLETS_LIB_DIR, "debug", "bundleMode.native.js")
553
+ ];
554
+ function toggleBundleMode(path, state) {
555
+ if (!state.opts.bundleMode || !togglePaths.some((togglePath) => {
556
+ var _a;
557
+ return (_a = state.filename) === null || _a === void 0 ? void 0 : _a.endsWith(togglePath);
558
+ })) {
559
+ return;
332
560
  }
333
- const workletDefinition = workletDeclaration.get("right");
334
- if (acceptWorkletizableFunction && (0, types_2.isWorkletizableFunctionPath)(workletDefinition)) {
335
- return workletDefinition;
561
+ const expressionPath = path.get("expression");
562
+ if (!expressionPath.isAssignmentExpression()) {
563
+ return;
336
564
  }
337
- if (acceptObject && (0, types_2.isWorkletizableObjectPath)(workletDefinition)) {
338
- return workletDefinition;
565
+ const left = expressionPath.get("left");
566
+ if (!left.isMemberExpression()) {
567
+ return;
339
568
  }
340
- if (workletDefinition.isIdentifier() && workletDefinition.isReferencedIdentifier()) {
341
- return findReferencedWorklet(workletDefinition, acceptWorkletizableFunction, acceptObject, state);
569
+ const object = left.get("object");
570
+ const property = left.get("property");
571
+ if (!object.isIdentifier() || object.node.name !== "globalThis" || !property.isIdentifier() || property.node.name !== "_WORKLETS_BUNDLE_MODE_ENABLED") {
572
+ return;
342
573
  }
343
- return void 0;
344
- }
345
- function bindingIsWorklet(binding) {
346
- return binding.referencePaths.some((refPath) => !Array.isArray(refPath.container) && (0, types_12.isMemberExpression)(refPath.container) && refPath.container.object === refPath.node && (0, types_12.isIdentifier)(refPath.container.property) && refPath.container.property.name === "__workletHash");
574
+ const right = expressionPath.get("right");
575
+ right.replaceWith((0, types_12.booleanLiteral)(true));
347
576
  }
348
577
  }
349
578
  });
350
579
 
351
- // lib/findWorklet.js
352
- var require_findWorklet = __commonJS({
353
- "lib/findWorklet.js"(exports2) {
580
+ // lib/transform.js
581
+ var require_transform = __commonJS({
582
+ "lib/transform.js"(exports2) {
354
583
  "use strict";
584
+ var __rest = exports2 && exports2.__rest || function(s, e) {
585
+ var t = {};
586
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
587
+ t[p] = s[p];
588
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
589
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
590
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
591
+ t[p[i]] = s[p[i]];
592
+ }
593
+ return t;
594
+ };
355
595
  Object.defineProperty(exports2, "__esModule", { value: true });
356
- exports2.findWorklet = findWorklet;
357
- var referencedWorklets_1 = require_referencedWorklets();
358
- var types_12 = require_types();
359
- function findWorklet(nodePath, state, acceptWorkletizableFunction, acceptObject) {
360
- if (acceptWorkletizableFunction && (0, types_12.isWorkletizableFunctionPath)(nodePath)) {
361
- return nodePath;
362
- }
363
- if (acceptObject && (0, types_12.isWorkletizableObjectPath)(nodePath)) {
364
- return nodePath;
365
- }
366
- if (nodePath.isIdentifier() && nodePath.isReferencedIdentifier()) {
367
- const worklet = (0, referencedWorklets_1.findReferencedWorklet)(nodePath, acceptWorkletizableFunction, acceptObject, state);
368
- return worklet;
369
- }
370
- return void 0;
596
+ exports2.workletTransformSync = workletTransformSync;
597
+ var core_1 = require("@babel/core");
598
+ function workletTransformSync(code, opts) {
599
+ const { extraPlugins = [], extraPresets = [] } = opts, rest = __rest(opts, ["extraPlugins", "extraPresets"]);
600
+ return (0, core_1.transformSync)(code, Object.assign(Object.assign({}, rest), { plugins: [...defaultPlugins, ...extraPlugins], presets: [...defaultPresets, ...extraPresets] }));
371
601
  }
602
+ var defaultPresets = [
603
+ require.resolve("@babel/preset-typescript")
604
+ ];
605
+ var defaultPlugins = [];
372
606
  }
373
607
  });
374
608
 
@@ -411,1698 +645,1489 @@ var require_utils = __commonJS({
411
645
  }
412
646
  });
413
647
 
414
- // lib/globals.js
415
- var require_globals = __commonJS({
416
- "lib/globals.js"(exports2) {
648
+ // lib/class.js
649
+ var require_class = __commonJS({
650
+ "lib/class.js"(exports2) {
417
651
  "use strict";
418
652
  var __importDefault = exports2 && exports2.__importDefault || function(mod) {
419
653
  return mod && mod.__esModule ? mod : { "default": mod };
420
654
  };
421
655
  Object.defineProperty(exports2, "__esModule", { value: true });
422
- exports2.globals = exports2.defaultGlobals = void 0;
423
- exports2.initializeState = initializeState;
424
- exports2.isGeneratedWorkletFile = isGeneratedWorkletFile;
425
- exports2.initializeGlobals = initializeGlobals;
426
- exports2.addCustomGlobals = addCustomGlobals;
656
+ exports2.processIfWorkletClass = processIfWorkletClass;
657
+ var generator_1 = __importDefault(require("@babel/generator"));
658
+ var traverse_1 = __importDefault(require("@babel/traverse"));
659
+ var types_12 = require("@babel/types");
427
660
  var assert_1 = require("assert");
428
- var path_1 = __importDefault(require("path"));
429
- var autoworkletization_12 = require_autoworkletization();
430
- var types_12 = require_types();
431
- var notCapturedIdentifiers = [
432
- // Based on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects
433
- // Note that objects' properties don't need to be listed since we always only capture the whole object,
434
- // e.g. `global.__ErrorUtils` or `Intl.DateTimeFormat`.
435
- // Value properties
436
- "globalThis",
437
- "Infinity",
438
- "NaN",
439
- "undefined",
440
- // Function properties
441
- "eval",
442
- "isFinite",
443
- "isNaN",
444
- "parseFloat",
445
- "parseInt",
446
- "decodeURI",
447
- "decodeURIComponent",
448
- "encodeURI",
449
- "encodeURIComponent",
450
- "escape",
451
- "unescape",
452
- // Fundamental objects
453
- "Object",
454
- "Function",
455
- "Boolean",
456
- "Symbol",
457
- // Error objects
458
- "Error",
459
- "AggregateError",
460
- "EvalError",
461
- "RangeError",
462
- "ReferenceError",
463
- "SyntaxError",
464
- "TypeError",
465
- "URIError",
466
- "InternalError",
467
- // Numbers and dates
468
- "Number",
469
- "BigInt",
470
- "Math",
471
- "Date",
472
- // Text processing
473
- "String",
474
- "RegExp",
475
- // Indexed collections
476
- "Array",
477
- "Int8Array",
478
- "Uint8Array",
479
- "Uint8ClampedArray",
480
- "Int16Array",
481
- "Uint16Array",
482
- "Int32Array",
483
- "Uint32Array",
484
- "BigInt64Array",
485
- "BigUint64Array",
486
- "Float32Array",
487
- "Float64Array",
488
- // Keyed collections
489
- "Map",
490
- "Set",
491
- "WeakMap",
492
- "WeakSet",
493
- // Structured data
494
- "ArrayBuffer",
495
- "SharedArrayBuffer",
496
- "DataView",
497
- "Atomics",
498
- "JSON",
499
- // Managing memory
500
- "WeakRef",
501
- "FinalizationRegistry",
502
- // Control abstraction objects
503
- "Iterator",
504
- "AsyncIterator",
505
- "Promise",
506
- "GeneratorFunction",
507
- "AsyncGeneratorFunction",
508
- "Generator",
509
- "AsyncGenerator",
510
- "AsyncFunction",
511
- // Reflection
512
- "Reflect",
513
- "Proxy",
514
- // Internationalization
515
- "Intl",
516
- // Other stuff
517
- "null",
518
- "this",
519
- "global",
520
- "window",
521
- "globalThis",
522
- "self",
523
- "console",
524
- "performance",
525
- "arguments",
526
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments
527
- "require",
528
- "fetch",
529
- "XMLHttpRequest",
530
- "WebSocket",
531
- // Run loop
532
- "queueMicrotask",
533
- "requestAnimationFrame",
534
- "cancelAnimationFrame",
535
- "setTimeout",
536
- "clearTimeout",
537
- "setImmediate",
538
- "clearImmediate",
539
- "setInterval",
540
- "clearInterval",
541
- // Hermes
542
- "HermesInternal",
543
- // Worklets
544
- "_WORKLET"
545
- ];
546
- function initializeState(state) {
547
- var _a, _b;
548
- state.skipFile = isGeneratedWorkletFile(state.file.opts.filename);
549
- if (state.skipFile) {
550
- return;
551
- }
552
- state.workletNumber = 1;
553
- state.classesToWorkletize = [];
554
- state.autoworkletizationPlugin = {
555
- name: "worklets-autoworkletization",
556
- visitor: {
557
- CallExpression: {
558
- enter(nodePath) {
559
- (0, autoworkletization_12.processCalleesAutoworkletizableCallbacks)(nodePath, state);
560
- }
561
- }
562
- }
563
- };
564
- if (!state.opts.strictGlobal) {
565
- initializeGlobals();
566
- addCustomGlobals(state);
567
- }
568
- const userImportForwarding = state.opts.importForwarding;
569
- (0, assert_1.strict)(state.importForwarding === void 0, "state.importForwarding should be undefined at this point");
570
- state.importForwarding = {
571
- relativePaths: [
572
- ...defaultAllowedPaths,
573
- ...(_a = userImportForwarding === null || userImportForwarding === void 0 ? void 0 : userImportForwarding.relativePaths) !== null && _a !== void 0 ? _a : []
574
- ],
575
- moduleNames: [
576
- ...defaultAllowedModules,
577
- ...(_b = userImportForwarding === null || userImportForwarding === void 0 ? void 0 : userImportForwarding.moduleNames) !== null && _b !== void 0 ? _b : []
578
- ]
579
- };
580
- }
581
- function isGeneratedWorkletFile(filename) {
582
- if (!filename) {
661
+ var directives_12 = require_directives();
662
+ var transform_1 = require_transform();
663
+ var types_2 = require_types();
664
+ var utils_1 = require_utils();
665
+ var classWorkletMarker = "__workletClass";
666
+ function processIfWorkletClass(classPath, state) {
667
+ if (!isWorkletizableClass(classPath, state) || state.opts.bundleMode) {
583
668
  return false;
584
669
  }
585
- const generatedWorkletsDirPath = path_1.default.join("react-native-worklets", types_12.generatedWorkletsDir);
586
- return filename.includes(generatedWorkletsDirPath);
670
+ removeWorkletClassMarker(classPath.node.body);
671
+ processClass(classPath, state);
672
+ return true;
587
673
  }
588
- exports2.defaultGlobals = new Set(notCapturedIdentifiers);
589
- function initializeGlobals() {
590
- exports2.globals = new Set(exports2.defaultGlobals);
674
+ function processClass(classPath, state) {
675
+ (0, assert_1.strict)(classPath.node.id);
676
+ const className = classPath.node.id.name;
677
+ const polyfilledClassAst = getPolyfilledAst(classPath.node, state);
678
+ sortPolyfills(polyfilledClassAst);
679
+ appendWorkletDirectiveToPolyfills(polyfilledClassAst.program.body);
680
+ replaceClassDeclarationWithFactoryAndCall(polyfilledClassAst.program.body, className);
681
+ polyfilledClassAst.program.body.push((0, types_12.returnStatement)((0, types_12.identifier)(className)));
682
+ const factoryFactory = (0, types_12.functionExpression)(null, [], (0, types_12.blockStatement)([...polyfilledClassAst.program.body]));
683
+ const factoryCall = (0, types_12.callExpression)(factoryFactory, []);
684
+ (0, utils_1.replaceWithFactoryCall)(classPath, className, factoryCall);
591
685
  }
592
- var defaultAllowedPaths = ["react-native-worklets"];
593
- var defaultAllowedModules = [
594
- "react-native-worklets",
595
- "react-native/Libraries/Core/setUpXHR"
596
- ];
597
- function addCustomGlobals(state) {
598
- if (state.opts && Array.isArray(state.opts.globals)) {
599
- state.opts.globals.forEach((name) => {
600
- exports2.globals.add(name);
601
- });
602
- }
686
+ function getPolyfilledAst(classNode, state) {
687
+ var _a;
688
+ const classCode = (0, generator_1.default)(classNode).code;
689
+ const classWithPolyfills = (0, transform_1.workletTransformSync)(classCode, {
690
+ extraPlugins: [
691
+ "@babel/plugin-transform-class-properties",
692
+ "@babel/plugin-transform-classes",
693
+ "@babel/plugin-transform-unicode-regex",
694
+ ...(_a = state.opts.extraPlugins) !== null && _a !== void 0 ? _a : []
695
+ ],
696
+ extraPresets: state.opts.extraPresets,
697
+ filename: state.file.opts.filename,
698
+ ast: true,
699
+ babelrc: false,
700
+ configFile: false
701
+ });
702
+ (0, assert_1.strict)(classWithPolyfills && classWithPolyfills.ast);
703
+ return classWithPolyfills.ast;
603
704
  }
604
- }
605
- });
606
-
607
- // lib/imports.js
608
- var require_imports = __commonJS({
609
- "lib/imports.js"(exports2) {
610
- "use strict";
611
- Object.defineProperty(exports2, "__esModule", { value: true });
612
- exports2.updateRelativeRequires = updateRelativeRequires;
613
- exports2.isImport = isImport;
614
- exports2.isImportRelative = isImportRelative;
615
- exports2.canForwardModuleImport = canForwardModuleImport;
616
- exports2.canForwardRelativeImport = canForwardRelativeImport;
617
- exports2.createImportPathLiteral = createImportPathLiteral;
618
- var core_1 = require("@babel/core");
619
- var types_12 = require("@babel/types");
620
- var path_1 = require("path");
621
- var types_2 = require_types();
622
- function updateRelativeRequires(node, state) {
623
- (0, core_1.traverse)(node, {
624
- noScope: true,
625
- CallExpression(nodePath) {
626
- var _a;
627
- if (nodePath.get("callee").isIdentifier({ name: "require" }) && ((_a = nodePath.get("arguments")[0]) === null || _a === void 0 ? void 0 : _a.isStringLiteral())) {
628
- const requiredModule = nodePath.get("arguments")[0];
629
- if (requiredModule.node.value.startsWith(".") && canForwardRelativeImport(state.file.opts.filename || "", state.importForwarding.relativePaths)) {
630
- requiredModule.replaceWith(createImportPathLiteral(requiredModule.node.value, state));
631
- }
632
- }
705
+ function appendWorkletDirectiveToPolyfills(statements) {
706
+ statements.forEach((statement) => {
707
+ if ((0, types_12.isFunctionDeclaration)(statement)) {
708
+ (0, directives_12.addWorkletDirectivesToFunctionBody)(statement.body);
633
709
  }
634
710
  });
635
711
  }
636
- function isImport(binding) {
637
- return binding.kind === "module" && binding.constant && (binding.path.isImportSpecifier() || binding.path.isImportDefaultSpecifier()) && binding.path.parentPath.isImportDeclaration();
712
+ function replaceClassDeclarationWithFactoryAndCall(statements, className) {
713
+ const classFactoryName = className + types_2.workletClassFactorySuffix;
714
+ const classDeclarationIndex = getPolyfilledClassDeclarationIndex(statements, className);
715
+ const classDeclarationToReplace = statements[classDeclarationIndex];
716
+ const classDeclarationInit = classDeclarationToReplace.declarations[0].init;
717
+ const classFactoryDeclaration = (0, types_12.functionDeclaration)((0, types_12.identifier)(classFactoryName), [], (0, types_12.blockStatement)([
718
+ (0, types_12.variableDeclaration)("const", [
719
+ (0, types_12.variableDeclarator)((0, types_12.identifier)(className), classDeclarationInit)
720
+ ]),
721
+ (0, types_12.expressionStatement)((0, types_12.assignmentExpression)("=", (0, types_12.memberExpression)((0, types_12.identifier)(className), (0, types_12.identifier)(classFactoryName)), (0, types_12.identifier)(classFactoryName))),
722
+ (0, types_12.returnStatement)((0, types_12.identifier)(className))
723
+ ]));
724
+ (0, directives_12.addWorkletDirectivesToFunctionBody)(classFactoryDeclaration.body);
725
+ const newClassDeclaration = (0, types_12.variableDeclaration)("const", [
726
+ (0, types_12.variableDeclarator)((0, types_12.identifier)(className), (0, types_12.callExpression)((0, types_12.identifier)(classFactoryName), []))
727
+ ]);
728
+ statements.splice(classDeclarationIndex, 1, classFactoryDeclaration, newClassDeclaration);
638
729
  }
639
- function isImportRelative(imported) {
640
- return imported.path.parentPath.node.source.value.startsWith(".");
730
+ function getPolyfilledClassDeclarationIndex(statements, className) {
731
+ const index = statements.findIndex((statement) => (0, types_12.isVariableDeclaration)(statement) && statement.declarations.some((declaration) => (0, types_12.isIdentifier)(declaration.id) && declaration.id.name === className));
732
+ (0, assert_1.strict)(index >= 0);
733
+ return index;
641
734
  }
642
- function canForwardModuleImport(moduleName, forwardableModuleNames) {
643
- return forwardableModuleNames.some((forwardableModuleName) => moduleName === forwardableModuleName || moduleName.startsWith(forwardableModuleName + "/"));
735
+ function hasWorkletClassMarker(classBody) {
736
+ return classBody.body.some((statement) => (0, types_12.isClassProperty)(statement) && (0, types_12.isIdentifier)(statement.key) && statement.key.name === classWorkletMarker);
644
737
  }
645
- function canForwardRelativeImport(modulePath, relativePaths) {
646
- return !!modulePath && relativePaths.some((relativePath) => matchesFilenameSegment(modulePath, relativePath));
738
+ function removeWorkletClassMarker(classBody) {
739
+ classBody.body = classBody.body.filter((statement) => !(0, types_12.isClassProperty)(statement) || !(0, types_12.isIdentifier)(statement.key) || statement.key.name !== classWorkletMarker);
647
740
  }
648
- function matchesFilenameSegment(filename, allowedPath) {
649
- const pkgSegments = allowedPath.split(path_1.posix.sep);
650
- let fileSegments = filename.split(path_1.sep);
651
- const lastNodeModules = fileSegments.lastIndexOf("node_modules");
652
- if (lastNodeModules !== -1) {
653
- fileSegments = fileSegments.slice(lastNodeModules + 1);
741
+ function sortPolyfills(ast) {
742
+ const toSort = getPolyfillsToSort(ast);
743
+ const sorted = topoSort(toSort);
744
+ const toSortIndices = toSort.map((element) => element.index);
745
+ const sortedIndices = sorted.map((element) => element.index);
746
+ const statements = ast.program.body;
747
+ const oldStatements = [...statements];
748
+ for (let i = 0; i < toSort.length; i++) {
749
+ const sourceIndex = sortedIndices[i];
750
+ const targetIndex = toSortIndices[i];
751
+ const source = oldStatements[sourceIndex];
752
+ statements[targetIndex] = source;
654
753
  }
655
- for (let i = 0; i <= fileSegments.length - pkgSegments.length; i++) {
656
- if (pkgSegments.every((segment, segmentIndex) => fileSegments[i + segmentIndex] === segment)) {
657
- return true;
754
+ }
755
+ function getPolyfillsToSort(ast) {
756
+ const polyfills = [];
757
+ (0, traverse_1.default)(ast, {
758
+ Program: {
759
+ enter: (functionPath) => {
760
+ const statements = functionPath.get("body");
761
+ statements.forEach((statement, index) => {
762
+ var _a;
763
+ const bindingIdentifiers = statement.getBindingIdentifiers();
764
+ if (!statement.isFunctionDeclaration() || !((_a = statement.node.id) === null || _a === void 0 ? void 0 : _a.name)) {
765
+ return;
766
+ }
767
+ const element = {
768
+ name: statement.node.id.name,
769
+ index,
770
+ dependencies: /* @__PURE__ */ new Set()
771
+ };
772
+ polyfills.push(element);
773
+ statement.traverse({
774
+ Identifier(path) {
775
+ if (isOutsideDependency(path, bindingIdentifiers, statement)) {
776
+ element.dependencies.add(path.node.name);
777
+ }
778
+ }
779
+ });
780
+ });
781
+ }
658
782
  }
783
+ });
784
+ return polyfills;
785
+ }
786
+ function topoSort(toSort) {
787
+ const sorted = [];
788
+ const stack = /* @__PURE__ */ new Set();
789
+ for (const element of toSort) {
790
+ recursiveTopoSort(element, toSort, sorted, stack);
659
791
  }
660
- return false;
792
+ return sorted;
661
793
  }
662
- function createImportPathLiteral(originalPath, state) {
663
- const generatedWorkletsDirPath = (0, path_1.resolve)((0, path_1.dirname)(require.resolve("react-native-worklets/package.json")), types_2.generatedWorkletsDir);
664
- const resolved = (0, path_1.resolve)((0, path_1.dirname)(state.file.opts.filename), originalPath);
665
- const relativePath = (0, path_1.relative)(generatedWorkletsDirPath, resolved);
666
- return (0, types_12.stringLiteral)(path_1.sep === "/" ? relativePath : relativePath.split(path_1.sep).join("/"));
794
+ function recursiveTopoSort(current, toSort, sorted, stack) {
795
+ if (stack.has(current.name)) {
796
+ throw new Error("Cycle detected. This should never happen.");
797
+ }
798
+ if (sorted.find((element) => element.name === current.name)) {
799
+ return;
800
+ }
801
+ stack.add(current.name);
802
+ for (const dependency of current.dependencies) {
803
+ if (!sorted.find((element) => element.name === dependency)) {
804
+ const next = toSort.find((element) => element.name === dependency);
805
+ (0, assert_1.strict)(next);
806
+ recursiveTopoSort(next, toSort, sorted, stack);
807
+ }
808
+ }
809
+ sorted.push(current);
810
+ stack.delete(current.name);
667
811
  }
668
- }
669
- });
670
-
671
- // lib/closure.js
672
- var require_closure = __commonJS({
673
- "lib/closure.js"(exports2) {
674
- "use strict";
675
- Object.defineProperty(exports2, "__esModule", { value: true });
676
- exports2.getClosure = getClosure;
677
- var types_12 = require("@babel/types");
678
- var globals_12 = require_globals();
679
- var imports_1 = require_imports();
680
- function getClosure(funPath, state) {
681
- const capturedNames = /* @__PURE__ */ new Set();
682
- const closureVariables = new Array();
683
- const moduleBindingsToImport = /* @__PURE__ */ new Set();
684
- const relativeBindingsToImport = /* @__PURE__ */ new Set();
685
- let recrawled = false;
686
- funPath.traverse({
687
- "TSType|TSTypeAliasDeclaration|TSInterfaceDeclaration"(typePath) {
688
- typePath.skip();
689
- },
690
- ReferencedIdentifier(idPath) {
691
- if (idPath.isJSXIdentifier() && !state.opts.bundleMode) {
692
- return;
693
- }
694
- const name = idPath.node.name;
695
- if (capturedNames.has(name)) {
696
- return;
697
- }
698
- let binding = idPath.scope.getBinding(name);
699
- if (!binding && !recrawled) {
700
- recrawled = true;
701
- idPath.scope.crawl();
702
- binding = idPath.scope.getBinding(name);
703
- }
704
- if (!binding) {
705
- if (state.opts.strictGlobal || globals_12.globals.has(name)) {
706
- return;
707
- }
708
- capturedNames.add(name);
709
- closureVariables.push((0, types_12.cloneNode)(idPath.node, true));
710
- return;
711
- }
712
- if ("id" in funPath.node) {
713
- const id = idPath.scope.getBindingIdentifier(name);
714
- if (id && id === funPath.node.id) {
715
- return;
716
- }
717
- }
718
- let scope = idPath.scope;
719
- while (scope !== funPath.scope.parent) {
720
- if (scope.hasOwnBinding(name)) {
721
- return;
722
- }
723
- scope = scope.parent;
724
- }
725
- if (state.opts.bundleMode && (0, imports_1.isImport)(binding)) {
726
- if ((0, imports_1.isImportRelative)(binding) && (0, imports_1.canForwardRelativeImport)(state.filename, state.importForwarding.relativePaths)) {
727
- capturedNames.add(name);
728
- relativeBindingsToImport.add(binding);
729
- return;
730
- }
731
- const source = binding.path.parentPath.node.source.value;
732
- if ((0, imports_1.canForwardModuleImport)(source, state.importForwarding.moduleNames)) {
733
- capturedNames.add(name);
734
- moduleBindingsToImport.add(binding);
735
- return;
736
- }
737
- }
738
- capturedNames.add(name);
739
- closureVariables.push((0, types_12.cloneNode)(idPath.node, true));
740
- }
741
- }, state);
742
- return {
743
- closureVariables,
744
- moduleBindingsToImport,
745
- relativeBindingsToImport
746
- };
812
+ function isOutsideDependency(identifierPath, bindingIdentifiers, functionPath) {
813
+ return (
814
+ // We don't care about identifiers that were just declared.
815
+ identifierPath.isReferencedIdentifier() && // We don't care about identifiers that are bound in the scope.
816
+ !(identifierPath.node.name in bindingIdentifiers) && // This I don't exactly understand, but the function identifier itself isn't in `bindingIdentifiers`,
817
+ // but it return true on `hasOwnBinding`.
818
+ !functionPath.scope.hasOwnBinding(identifierPath.node.name) && // `hasReference` returns true for global identifiers, like `Object`,
819
+ // we don't want to include those.
820
+ functionPath.scope.hasReference(identifierPath.node.name)
821
+ );
822
+ }
823
+ function isWorkletizableClass(classPath, state) {
824
+ var _a;
825
+ const className = (_a = classPath.node.id) === null || _a === void 0 ? void 0 : _a.name;
826
+ const classNode = classPath.node;
827
+ if (!className) {
828
+ return false;
829
+ }
830
+ const isMarked = hasWorkletClassMarker(classNode.body);
831
+ const isMemoizedNode = state.classesToWorkletize.some((record) => record.node === classNode);
832
+ const isTopLevelMemoizedName = classPath.parentPath.isProgram() && state.classesToWorkletize.some((record) => record.name === className);
833
+ state.classesToWorkletize = state.classesToWorkletize.filter((record) => record.node !== classNode && record.name !== className);
834
+ const result = isMarked || isMemoizedNode || isTopLevelMemoizedName;
835
+ return result;
747
836
  }
748
837
  }
749
838
  });
750
839
 
751
- // lib/generate.js
752
- var require_generate = __commonJS({
753
- "lib/generate.js"(exports2) {
840
+ // lib/classMethod.js
841
+ var require_classMethod = __commonJS({
842
+ "lib/classMethod.js"(exports2) {
754
843
  "use strict";
755
- var __importDefault = exports2 && exports2.__importDefault || function(mod) {
756
- return mod && mod.__esModule ? mod : { "default": mod };
757
- };
758
844
  Object.defineProperty(exports2, "__esModule", { value: true });
759
- exports2.generateWorkletFile = generateWorkletFile;
760
- var core_1 = require("@babel/core");
845
+ exports2.processIfWorkletMethod = processIfWorkletMethod;
761
846
  var types_12 = require("@babel/types");
762
- var assert_1 = __importDefault(require("assert"));
763
- var fs_1 = require("fs");
764
- var path_1 = require("path");
765
- var imports_1 = require_imports();
766
- var types_2 = require_types();
767
- function generateWorkletFile(moduleBindingsToImport, relativeBindingsToImport, factory, workletHash, state) {
768
- var _a;
769
- const libraryImports = Array.from(moduleBindingsToImport).filter((binding) => (binding.path.isImportSpecifier() || binding.path.isImportDefaultSpecifier()) && binding.path.parentPath.isImportDeclaration()).map((binding) => (0, types_12.importDeclaration)([(0, types_12.cloneNode)(binding.path.node, true)], (0, types_12.stringLiteral)(binding.path.parentPath.node.source.value)));
770
- const filesDirPath = (0, path_1.resolve)((0, path_1.dirname)(require.resolve("react-native-worklets/package.json")), types_2.generatedWorkletsDir);
771
- const relativeImports = Array.from(relativeBindingsToImport).filter((binding) => binding.path.isImportSpecifier() && binding.path.parentPath.isImportDeclaration()).map((binding) => (0, types_12.importDeclaration)([(0, types_12.cloneNode)(binding.path.node, true)], (0, imports_1.createImportPathLiteral)(binding.path.parentPath.node.source.value, state)));
772
- const imports = [...libraryImports, ...relativeImports];
773
- const newProg = (0, types_12.program)([...imports, (0, types_12.exportDefaultDeclaration)(factory)]);
774
- const transformedProg = (_a = (0, core_1.transformFromAstSync)(newProg, void 0, {
775
- filename: state.file.opts.filename,
776
- presets: [resolvePresetTypescript()],
777
- plugins: [state.autoworkletizationPlugin, stripJsxDevAttributesPlugin],
778
- ast: false,
779
- babelrc: false,
780
- configFile: false,
781
- comments: false
782
- })) === null || _a === void 0 ? void 0 : _a.code;
783
- (0, assert_1.default)(transformedProg, "[Worklets] `transformedProg` is undefined.");
784
- const dedicatedFilePath = (0, path_1.resolve)(filesDirPath, `${workletHash}.js`);
785
- (0, fs_1.writeFileSync)(dedicatedFilePath, transformedProg);
786
- }
787
- function resolvePresetTypescript() {
788
- try {
789
- return require.resolve("@babel/preset-typescript");
790
- } catch (_a) {
791
- return require.resolve("@babel/preset-typescript", {
792
- paths: [(0, path_1.dirname)(require.resolve("react-native-worklets/package.json"))]
793
- });
847
+ var assert_1 = require("assert");
848
+ function processIfWorkletMethod(path) {
849
+ if (path.node.body.directives.some((d) => d.value.value === "worklet")) {
850
+ (0, assert_1.strict)((0, types_12.isIdentifier)(path.node.key), "ClassMethod key must be an Identifier");
851
+ const methodIdentifier = path.node.key;
852
+ path.replaceWith((0, types_12.classProperty)((0, types_12.cloneNode)(methodIdentifier, true), (0, types_12.functionExpression)((0, types_12.cloneNode)(methodIdentifier, true), path.node.params.filter((p) => (0, types_12.isFunctionParameter)(p)).map((p) => (0, types_12.cloneNode)(p, true)), (0, types_12.cloneNode)(path.node.body, true), path.node.generator, path.node.async)));
794
853
  }
795
854
  }
796
- var stripJsxDevAttributesPlugin = {
797
- name: "worklets-strip-jsx-dev-attributes",
798
- visitor: {
799
- JSXAttribute(path) {
800
- const name = path.node.name;
801
- if (name.type !== "JSXIdentifier") {
802
- return;
803
- }
804
- if (name.name !== "__self" && name.name !== "__source") {
805
- return;
806
- }
807
- path.remove();
808
- }
809
- }
810
- };
811
855
  }
812
856
  });
813
857
 
814
- // lib/hermesBytecode.js
815
- var require_hermesBytecode = __commonJS({
816
- "lib/hermesBytecode.js"(exports2) {
858
+ // lib/contextObject.js
859
+ var require_contextObject = __commonJS({
860
+ "lib/contextObject.js"(exports2) {
817
861
  "use strict";
818
862
  Object.defineProperty(exports2, "__esModule", { value: true });
819
- exports2.compileWorkletToHbc = compileWorkletToHbc;
820
- var core_1 = require("@babel/core");
821
- var child_process_1 = require("child_process");
822
- function compileWorkletToHbc(funString, workletHash, state) {
823
- if (compilationCache.has(workletHash)) {
824
- return compilationCache.get(workletHash);
863
+ exports2.contextObjectMarker = void 0;
864
+ exports2.processIfWorkletContextObject = processIfWorkletContextObject;
865
+ exports2.isContextObject = isContextObject;
866
+ var types_12 = require("@babel/types");
867
+ var directives_12 = require_directives();
868
+ exports2.contextObjectMarker = "__workletContextObject";
869
+ function processIfWorkletContextObject(path, _state) {
870
+ if (!isContextObject(path.node)) {
871
+ return false;
825
872
  }
826
- const result = compile(funString, state);
827
- compilationCache.set(workletHash, result);
828
- return result;
873
+ removeContextObjectMarker(path.node);
874
+ processWorkletContextObject(path.node);
875
+ return true;
829
876
  }
830
- function compile(funString, state) {
831
- const hermesc = resolveHbcBinary(state);
832
- if (!hermesc) {
833
- return null;
834
- }
835
- try {
836
- return runHermesc(hermesc, funString);
837
- } catch (error) {
838
- if (getErrorOutput(error).includes("JSX")) {
839
- const transformed = transformJsx(funString);
840
- if (transformed !== null) {
841
- try {
842
- return runHermesc(hermesc, transformed);
843
- } catch (retryError) {
844
- return warnFallback(retryError);
845
- }
846
- }
847
- }
848
- return warnFallback(error);
849
- }
877
+ function isContextObject(objectExpression) {
878
+ return objectExpression.properties.some((property) => (0, types_12.isObjectProperty)(property) && (0, types_12.isIdentifier)(property.key) && property.key.name === exports2.contextObjectMarker);
850
879
  }
851
- var MAX_BYTECODE_BYTES = 256 * 1024 * 1024;
852
- var compilationCache = /* @__PURE__ */ new Map();
853
- var warnedMessages = /* @__PURE__ */ new Set();
854
- function warnOnce(message) {
855
- if (warnedMessages.has(message)) {
856
- return;
857
- }
858
- warnedMessages.add(message);
859
- console.warn(`[Worklets] ${message}`);
880
+ function processWorkletContextObject(objectExpression) {
881
+ const workletObjectFactory = (0, types_12.functionExpression)(null, [], (0, types_12.blockStatement)([(0, types_12.returnStatement)((0, types_12.cloneNode)(objectExpression))]));
882
+ (0, directives_12.addWorkletDirectivesToFunctionBody)(workletObjectFactory.body);
883
+ objectExpression.properties.push((0, types_12.objectProperty)((0, types_12.identifier)(`${exports2.contextObjectMarker}Factory`), workletObjectFactory));
860
884
  }
861
- function resolveHbcBinary(state) {
862
- const { getHBCBinary } = state.opts;
863
- if (!getHBCBinary) {
864
- warnOnce("The `getHBCBinary` plugin option is required to compile worklets to Hermes bytecode. Falling back to shipping worklets as source strings.");
865
- return null;
866
- }
867
- try {
868
- const binary = getHBCBinary();
869
- if (!binary) {
870
- throw new Error("`getHBCBinary` returned an empty path.");
871
- }
872
- return binary;
873
- } catch (error) {
874
- warnOnce(`Calling \`getHBCBinary\` failed, falling back to a source string. ${error instanceof Error ? error.message : String(error)}`);
875
- return null;
885
+ function removeContextObjectMarker(objectExpression) {
886
+ objectExpression.properties = objectExpression.properties.filter((property) => !((0, types_12.isObjectProperty)(property) && (0, types_12.isIdentifier)(property.key) && property.key.name === exports2.contextObjectMarker));
887
+ }
888
+ }
889
+ });
890
+
891
+ // lib/file.js
892
+ var require_file = __commonJS({
893
+ "lib/file.js"(exports2) {
894
+ "use strict";
895
+ Object.defineProperty(exports2, "__esModule", { value: true });
896
+ exports2.processIfWorkletFile = processIfWorkletFile;
897
+ exports2.isImplicitContextObject = isImplicitContextObject;
898
+ var types_12 = require("@babel/types");
899
+ var contextObject_12 = require_contextObject();
900
+ var directives_12 = require_directives();
901
+ var types_2 = require_types();
902
+ function processIfWorkletFile(path, state) {
903
+ if (!path.node.directives.some((functionDirective) => functionDirective.value.value === "worklet")) {
904
+ return false;
876
905
  }
906
+ path.node.directives = path.node.directives.filter((functionDirective) => functionDirective.value.value !== "worklet");
907
+ processWorkletFile(path, state);
908
+ return true;
877
909
  }
878
- function runHermesc(hermesc, source) {
879
- return (0, child_process_1.execFileSync)(hermesc, ["-g0", "-emit-binary", "-O", "-w", "-"], {
880
- input: source,
881
- maxBuffer: MAX_BYTECODE_BYTES,
882
- stdio: ["pipe", "pipe", "pipe"]
910
+ function processWorkletFile(programPath, state) {
911
+ const statements = programPath.get("body");
912
+ dehoistCommonJSExports(programPath.node);
913
+ statements.forEach((statement) => {
914
+ const candidatePath = getCandidate(statement);
915
+ processWorkletizableEntity(candidatePath, state);
883
916
  });
884
917
  }
885
- function getErrorOutput(error) {
886
- const stderr = error === null || error === void 0 ? void 0 : error.stderr;
887
- if (stderr) {
888
- return stderr.toString();
918
+ function getCandidate(statementPath) {
919
+ if (statementPath.isExportNamedDeclaration() || statementPath.isExportDefaultDeclaration()) {
920
+ return statementPath.get("declaration");
921
+ } else {
922
+ return statementPath;
889
923
  }
890
- return error instanceof Error ? error.message : String(error);
891
924
  }
892
- function warnFallback(error) {
893
- const reason = getErrorOutput(error).trim().split("\n")[0];
894
- warnOnce(`Could not compile a worklet to Hermes bytecode, falling back to a source string. ${reason}`);
895
- return null;
896
- }
897
- var jsxPluginPath;
898
- function resolveJsxPlugin() {
899
- if (jsxPluginPath === void 0) {
900
- try {
901
- jsxPluginPath = require.resolve("@babel/plugin-transform-react-jsx");
902
- } catch (_a) {
903
- jsxPluginPath = null;
904
- }
905
- }
906
- return jsxPluginPath;
907
- }
908
- function transformJsx(source) {
925
+ function processWorkletizableEntity(nodePath, state) {
909
926
  var _a;
910
- const plugin = resolveJsxPlugin();
911
- if (!plugin) {
912
- return null;
913
- }
914
- try {
915
- const result = (0, core_1.transformSync)(source, {
916
- babelrc: false,
917
- configFile: false,
918
- compact: true,
919
- plugins: [plugin]
920
- });
921
- return (_a = result === null || result === void 0 ? void 0 : result.code) !== null && _a !== void 0 ? _a : null;
922
- } catch (_b) {
923
- return null;
924
- }
925
- }
926
- }
927
- });
928
-
929
- // lib/transform.js
930
- var require_transform = __commonJS({
931
- "lib/transform.js"(exports2) {
932
- "use strict";
933
- var __rest = exports2 && exports2.__rest || function(s, e) {
934
- var t = {};
935
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
936
- t[p] = s[p];
937
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
938
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
939
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
940
- t[p[i]] = s[p[i]];
927
+ if ((0, types_2.isWorkletizableFunctionPath)(nodePath)) {
928
+ (0, directives_12.addWorkletDirectivesToPath)(nodePath);
929
+ } else if ((0, types_2.isWorkletizableObjectPath)(nodePath)) {
930
+ if (isImplicitContextObject(nodePath)) {
931
+ appendWorkletContextObjectMarker(nodePath.node);
932
+ } else {
933
+ processWorkletAggregator(nodePath, state);
941
934
  }
942
- return t;
943
- };
944
- Object.defineProperty(exports2, "__esModule", { value: true });
945
- exports2.workletTransformSync = workletTransformSync;
946
- var core_1 = require("@babel/core");
947
- function workletTransformSync(code, opts) {
948
- const { extraPlugins = [], extraPresets = [] } = opts, rest = __rest(opts, ["extraPlugins", "extraPresets"]);
949
- return (0, core_1.transformSync)(code, Object.assign(Object.assign({}, rest), { plugins: [...defaultPlugins, ...extraPlugins], presets: [...defaultPresets, ...extraPresets] }));
950
- }
951
- var defaultPresets = [
952
- require.resolve("@babel/preset-typescript")
953
- ];
954
- var defaultPlugins = [];
955
- }
956
- });
957
-
958
- // lib/workletStringCode.js
959
- var require_workletStringCode = __commonJS({
960
- "lib/workletStringCode.js"(exports2) {
961
- "use strict";
962
- var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
963
- if (k2 === void 0) k2 = k;
964
- var desc = Object.getOwnPropertyDescriptor(m, k);
965
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
966
- desc = { enumerable: true, get: function() {
967
- return m[k];
968
- } };
969
- }
970
- Object.defineProperty(o, k2, desc);
971
- }) : (function(o, m, k, k2) {
972
- if (k2 === void 0) k2 = k;
973
- o[k2] = m[k];
974
- }));
975
- var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
976
- Object.defineProperty(o, "default", { enumerable: true, value: v });
977
- }) : function(o, v) {
978
- o["default"] = v;
979
- });
980
- var __importStar = exports2 && exports2.__importStar || /* @__PURE__ */ (function() {
981
- var ownKeys = function(o) {
982
- ownKeys = Object.getOwnPropertyNames || function(o2) {
983
- var ar = [];
984
- for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
985
- return ar;
986
- };
987
- return ownKeys(o);
988
- };
989
- return function(mod) {
990
- if (mod && mod.__esModule) return mod;
991
- var result = {};
992
- if (mod != null) {
993
- for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
935
+ } else if (nodePath.isVariableDeclaration()) {
936
+ processVariableDeclaration(nodePath, state);
937
+ } else if (nodePath.isClassDeclaration()) {
938
+ appendWorkletClassMarker(nodePath.node.body);
939
+ if ((_a = nodePath.node.id) === null || _a === void 0 ? void 0 : _a.name) {
940
+ state.classesToWorkletize.push({
941
+ node: nodePath.node,
942
+ name: nodePath.node.id.name
943
+ });
994
944
  }
995
- __setModuleDefault(result, mod);
996
- return result;
997
- };
998
- })();
999
- var __importDefault = exports2 && exports2.__importDefault || function(mod) {
1000
- return mod && mod.__esModule ? mod : { "default": mod };
1001
- };
1002
- Object.defineProperty(exports2, "__esModule", { value: true });
1003
- exports2.buildWorkletString = buildWorkletString;
1004
- var core_1 = require("@babel/core");
1005
- var generator_1 = __importDefault(require("@babel/generator"));
1006
- var types_12 = require("@babel/types");
1007
- var assert_1 = require("assert");
1008
- var convertSourceMap = __importStar(require("convert-source-map"));
1009
- var fs = __importStar(require("fs"));
1010
- var transform_1 = require_transform();
1011
- var types_2 = require_types();
1012
- var utils_1 = require_utils();
1013
- var MOCK_SOURCE_MAP = "mock source map";
1014
- var querySuffixRE = /[?#].*$/;
1015
- function buildWorkletString(fun, state, closureVariables, workletName, inputMap) {
1016
- var _a;
1017
- restoreRecursiveCalls(fun, workletName);
1018
- const draftExpression = fun.program.body.find((obj) => (0, types_12.isFunctionDeclaration)(obj)) || fun.program.body.find((obj) => (0, types_12.isExpressionStatement)(obj));
1019
- (0, assert_1.strict)(draftExpression, "`draftExpression` is undefined.");
1020
- const expression = (0, types_12.isFunctionDeclaration)(draftExpression) ? draftExpression : draftExpression.expression;
1021
- (0, assert_1.strict)("params" in expression, "'params' property is undefined in 'expression'");
1022
- (0, assert_1.strict)((0, types_12.isBlockStatement)(expression.body), "`expression.body` is not a `BlockStatement`");
1023
- const parsedClasses = /* @__PURE__ */ new Set();
1024
- if (!state.opts.disableWorkletClasses) {
1025
- (0, core_1.traverse)(fun, {
1026
- NewExpression(path) {
1027
- if (!(0, types_12.isIdentifier)(path.node.callee)) {
1028
- return;
1029
- }
1030
- const constructorName = path.node.callee.name;
1031
- if (!closureVariables.some((variable) => variable.name === constructorName) || parsedClasses.has(constructorName)) {
1032
- return;
1033
- }
1034
- const index = closureVariables.findIndex((variable) => variable.name === constructorName);
1035
- closureVariables.splice(index, 1);
1036
- const workletClassFactoryName = constructorName + types_2.workletClassFactorySuffix;
1037
- closureVariables.push((0, types_12.identifier)(workletClassFactoryName));
1038
- (0, types_12.assertBlockStatement)(expression.body);
1039
- expression.body.body.unshift((0, types_12.variableDeclaration)("const", [
1040
- (0, types_12.variableDeclarator)((0, types_12.identifier)(constructorName), (0, types_12.callExpression)((0, types_12.identifier)(workletClassFactoryName), []))
1041
- ]));
1042
- parsedClasses.add(constructorName);
1043
- }
1044
- });
1045
945
  }
1046
- const workletFunction = (0, types_12.functionExpression)((0, types_12.identifier)(workletName), expression.params, expression.body, expression.generator, expression.async);
1047
- const code = (0, generator_1.default)(workletFunction).code;
1048
- (0, assert_1.strict)(inputMap, "`inputMap` is undefined.");
1049
- const includeSourceMap = !((0, utils_1.isRelease)(state) || state.opts.disableSourceMaps);
1050
- if (includeSourceMap) {
1051
- inputMap.sourcesContent = [];
1052
- for (const sourceFile of inputMap.sources) {
1053
- inputMap.sourcesContent.push(fs.readFileSync(sourceFile.replace(querySuffixRE, "")).toString("utf-8"));
946
+ }
947
+ function processVariableDeclaration(variableDeclarationPath, state) {
948
+ const declarations = variableDeclarationPath.get("declarations");
949
+ declarations.forEach((declaration) => {
950
+ const initPath = declaration.get("init");
951
+ if (initPath.isExpression()) {
952
+ processWorkletizableEntity(initPath, state);
1054
953
  }
1055
- }
1056
- const transformed = (0, transform_1.workletTransformSync)(code, {
1057
- filename: state.file.opts.filename,
1058
- extraPlugins: [
1059
- getClosurePlugin(closureVariables),
1060
- ...(_a = state.opts.extraPlugins) !== null && _a !== void 0 ? _a : []
1061
- ],
1062
- extraPresets: state.opts.extraPresets,
1063
- compact: true,
1064
- sourceMaps: includeSourceMap,
1065
- inputSourceMap: inputMap,
1066
- ast: false,
1067
- babelrc: false,
1068
- configFile: false,
1069
- comments: false
1070
954
  });
1071
- (0, assert_1.strict)(transformed, "`transformed` is null.");
1072
- let sourceMap;
1073
- if (includeSourceMap) {
1074
- if (shouldMockSourceMap()) {
1075
- sourceMap = MOCK_SOURCE_MAP;
1076
- } else {
1077
- sourceMap = convertSourceMap.fromObject(transformed.map).toObject();
1078
- delete sourceMap.sourcesContent;
955
+ }
956
+ function processWorkletAggregator(objectPath, state) {
957
+ const properties = objectPath.get("properties");
958
+ properties.forEach((property) => {
959
+ if (property.isObjectMethod()) {
960
+ (0, directives_12.addWorkletDirectivesToPath)(property);
961
+ } else if (property.isObjectProperty()) {
962
+ const valuePath = property.get("value");
963
+ processWorkletizableEntity(valuePath, state);
1079
964
  }
965
+ });
966
+ }
967
+ function appendWorkletContextObjectMarker(objectExpression) {
968
+ if (objectExpression.properties.some((value) => (0, types_12.isObjectProperty)(value) && (0, types_12.isIdentifier)(value.key) && value.key.name === contextObject_12.contextObjectMarker)) {
969
+ return;
1080
970
  }
1081
- const wrappedCode = `(${transformed.code})`;
1082
- return [wrappedCode, JSON.stringify(sourceMap)];
971
+ objectExpression.properties.push((0, types_12.objectProperty)((0, types_12.identifier)(`${contextObject_12.contextObjectMarker}`), (0, types_12.booleanLiteral)(true)));
1083
972
  }
1084
- function restoreRecursiveCalls(file, newName) {
1085
- (0, core_1.traverse)(file, {
1086
- FunctionExpression(path) {
1087
- if (!path.node.id) {
1088
- path.stop();
1089
- return;
1090
- }
1091
- const oldName = path.node.id.name;
1092
- const scope = path.scope;
1093
- scope.rename(oldName, newName);
973
+ function isImplicitContextObject(path) {
974
+ const propertyPaths = path.get("properties");
975
+ return propertyPaths.some((propertyPath) => {
976
+ if (!propertyPath.isObjectMethod()) {
977
+ return false;
1094
978
  }
979
+ return hasThisExpression(propertyPath);
1095
980
  });
1096
981
  }
1097
- function shouldMockSourceMap() {
1098
- return process.env.WORKLETS_JEST_SHOULD_MOCK_SOURCE_MAP === "1";
982
+ function hasThisExpression(path) {
983
+ let result = false;
984
+ path.traverse({
985
+ ThisExpression(thisPath) {
986
+ result = true;
987
+ thisPath.stop();
988
+ }
989
+ });
990
+ return result;
1099
991
  }
1100
- function prependClosure(path, closureVariables, closureDeclaration) {
1101
- if (closureVariables.length === 0 || !(0, types_12.isProgram)(path.parent)) {
1102
- return;
1103
- }
1104
- if (!(0, types_12.isExpression)(path.node.body)) {
1105
- path.node.body.body.unshift(closureDeclaration);
1106
- }
992
+ function appendWorkletClassMarker(classBody) {
993
+ classBody.body.push((0, types_12.classProperty)((0, types_12.identifier)("__workletClass"), (0, types_12.booleanLiteral)(true)));
1107
994
  }
1108
- function prependRecursiveDeclaration(path) {
1109
- var _a;
1110
- if ((0, types_12.isProgram)(path.parent) && !(0, types_12.isArrowFunctionExpression)(path.node) && !(0, types_12.isObjectMethod)(path.node) && path.node.id && path.scope.parent) {
1111
- const hasRecursiveCalls = ((_a = path.scope.parent.bindings[path.node.id.name]) === null || _a === void 0 ? void 0 : _a.references) > 0;
1112
- if (hasRecursiveCalls) {
1113
- path.node.body.body.unshift((0, types_12.variableDeclaration)("const", [
1114
- (0, types_12.variableDeclarator)((0, types_12.identifier)(path.node.id.name), (0, types_12.memberExpression)((0, types_12.thisExpression)(), (0, types_12.identifier)("_recur")))
1115
- ]));
995
+ function dehoistCommonJSExports(program) {
996
+ const statements = program.body;
997
+ let end = statements.length;
998
+ let current = 0;
999
+ while (current < end) {
1000
+ const statement = statements[current];
1001
+ if (!isCommonJSExport(statement)) {
1002
+ current++;
1003
+ continue;
1116
1004
  }
1005
+ const exportStatement = statements.splice(current, 1);
1006
+ statements.push(...exportStatement);
1007
+ end--;
1117
1008
  }
1118
1009
  }
1119
- function getClosurePlugin(closureVariables) {
1120
- const closureDeclaration = (0, types_12.variableDeclaration)("const", [
1121
- (0, types_12.variableDeclarator)((0, types_12.objectPattern)(closureVariables.map((variable) => (0, types_12.objectProperty)((0, types_12.identifier)(variable.name), (0, types_12.identifier)(variable.name), false, true))), (0, types_12.memberExpression)((0, types_12.thisExpression)(), (0, types_12.identifier)("__closure")))
1122
- ]);
1123
- return {
1124
- visitor: {
1125
- "FunctionDeclaration|FunctionExpression|ArrowFunctionExpression|ObjectMethod": (path) => {
1126
- prependClosure(path, closureVariables, closureDeclaration);
1127
- prependRecursiveDeclaration(path);
1128
- }
1129
- }
1130
- };
1010
+ function isCommonJSExport(statement) {
1011
+ return (0, types_12.isExpressionStatement)(statement) && (0, types_12.isAssignmentExpression)(statement.expression) && (0, types_12.isMemberExpression)(statement.expression.left) && (0, types_12.isIdentifier)(statement.expression.left.object) && statement.expression.left.object.name === "exports";
1131
1012
  }
1132
1013
  }
1133
1014
  });
1134
1015
 
1135
- // lib/workletFactory.js
1136
- var require_workletFactory = __commonJS({
1137
- "lib/workletFactory.js"(exports2) {
1016
+ // lib/globals.js
1017
+ var require_globals = __commonJS({
1018
+ "lib/globals.js"(exports2) {
1138
1019
  "use strict";
1139
1020
  var __importDefault = exports2 && exports2.__importDefault || function(mod) {
1140
1021
  return mod && mod.__esModule ? mod : { "default": mod };
1141
1022
  };
1142
1023
  Object.defineProperty(exports2, "__esModule", { value: true });
1143
- exports2.makeWorkletFactory = makeWorkletFactory;
1144
- var generator_1 = __importDefault(require("@babel/generator"));
1145
- var types_12 = require("@babel/types");
1024
+ exports2.globals = exports2.defaultGlobals = void 0;
1025
+ exports2.initializeState = initializeState;
1026
+ exports2.isGeneratedWorkletFile = isGeneratedWorkletFile;
1027
+ exports2.initializeGlobals = initializeGlobals;
1028
+ exports2.addCustomGlobals = addCustomGlobals;
1146
1029
  var assert_1 = require("assert");
1147
- var path_1 = require("path");
1148
- var closure_1 = require_closure();
1149
- var generate_1 = require_generate();
1150
- var hermesBytecode_1 = require_hermesBytecode();
1151
- var imports_1 = require_imports();
1152
- var transform_1 = require_transform();
1153
- var types_2 = require_types();
1154
- var utils_1 = require_utils();
1155
- var workletStringCode_1 = require_workletStringCode();
1156
- var REAL_VERSION = require("../package.json").version;
1157
- var MOCK_VERSION = "x.y.z";
1158
- function makeWorkletFactory(fun, state) {
1159
- var _a;
1160
- const includeClosure = state.opts.bundleMode || !hasDirective(fun, "no-worklet-closure");
1161
- const limitInitDataHoisting = hasDirective(fun, "limit-init-data-hoisting");
1162
- stripWorkletDirectives(fun);
1163
- (0, assert_1.strict)(state.file.opts.filename, "`state.file.opts.filename` is undefined.");
1164
- const codeObject = (0, generator_1.default)(fun.node, {
1165
- sourceMaps: true,
1166
- sourceFileName: state.file.opts.filename
1167
- });
1168
- codeObject.code = "(" + (fun.isObjectMethod() ? "function " : "") + codeObject.code + "\n)";
1169
- const transformed = (0, transform_1.workletTransformSync)(codeObject.code, {
1170
- extraPlugins: [...extraPlugins, ...(_a = state.opts.extraPlugins) !== null && _a !== void 0 ? _a : []],
1171
- extraPresets: state.opts.extraPresets,
1172
- filename: state.file.opts.filename,
1173
- ast: true,
1174
- babelrc: false,
1175
- configFile: false,
1176
- inputSourceMap: codeObject.map
1177
- });
1178
- (0, assert_1.strict)(transformed, "`transformed` is undefined.");
1179
- (0, assert_1.strict)(transformed.ast, "`transformed.ast` is undefined.");
1180
- const { closureVariables, moduleBindingsToImport, relativeBindingsToImport } = includeClosure ? (0, closure_1.getClosure)(fun, state) : {
1181
- closureVariables: [],
1182
- moduleBindingsToImport: /* @__PURE__ */ new Set(),
1183
- relativeBindingsToImport: /* @__PURE__ */ new Set()
1184
- };
1185
- const clone = (0, types_12.cloneNode)(fun.node);
1186
- const funExpression = (0, types_12.isBlockStatement)(clone.body) ? (0, types_12.functionExpression)(null, clone.params, clone.body, clone.generator, clone.async) : clone;
1187
- const { workletName, reactName } = makeWorkletName(fun, state);
1188
- let mutatedClosureVariables;
1189
- if (state.opts.bundleMode) {
1190
- mutatedClosureVariables = closureVariables.map((variable) => (0, types_12.cloneNode)(variable, true));
1191
- } else {
1192
- mutatedClosureVariables = closureVariables;
1193
- }
1194
- let [funString, sourceMapString] = (0, workletStringCode_1.buildWorkletString)(transformed.ast, state, mutatedClosureVariables, workletName, transformed.map);
1195
- (0, assert_1.strict)(funString, "`funString` is undefined.");
1196
- const workletHash = hash(funString);
1197
- let lineOffset = 1;
1198
- if (closureVariables.length > 0) {
1199
- lineOffset -= closureVariables.length + 2;
1200
- }
1201
- const pathForStringDefinitions = fun.parentPath.isProgram() ? fun : fun.findParent((path) => {
1202
- var _a2, _b;
1203
- return (_b = (_a2 = path.parentPath) === null || _a2 === void 0 ? void 0 : _a2.isProgram()) !== null && _b !== void 0 ? _b : false;
1204
- });
1205
- (0, assert_1.strict)(pathForStringDefinitions, "`pathForStringDefinitions` is null.");
1206
- (0, assert_1.strict)(pathForStringDefinitions.parentPath, "`pathForStringDefinitions.parentPath` is null.");
1207
- const initDataId = pathForStringDefinitions.parentPath.scope.generateUidIdentifier(`worklet_${workletHash}_init_data`);
1208
- const shouldIncludeInitData = !state.opts.omitNativeOnlyData && !state.opts.bundleMode;
1209
- const shouldEmitBytecode = !!state.opts.hermesBytecode && (0, utils_1.isRelease)(state) && shouldIncludeInitData;
1210
- const bytecode = shouldEmitBytecode ? (0, hermesBytecode_1.compileWorkletToHbc)(funString, workletHash, state) : null;
1211
- const initDataObjectExpression = (0, types_12.objectExpression)(bytecode ? [
1212
- (0, types_12.objectProperty)((0, types_12.identifier)("bytecode"), (0, types_12.memberExpression)((0, types_12.newExpression)((0, types_12.identifier)("Uint8Array"), [
1213
- (0, types_12.arrayExpression)(Array.from(bytecode, (byte) => (0, types_12.numericLiteral)(byte)))
1214
- ]), (0, types_12.identifier)("buffer")))
1215
- ] : [(0, types_12.objectProperty)((0, types_12.identifier)("code"), (0, types_12.stringLiteral)(funString))]);
1216
- const shouldInjectLocation = !(0, utils_1.isRelease)(state);
1217
- if (shouldInjectLocation) {
1218
- let location = state.file.opts.filename;
1219
- if (state.opts.relativeSourceLocation) {
1220
- location = (0, path_1.relative)(state.cwd, location);
1221
- sourceMapString = sourceMapString === null || sourceMapString === void 0 ? void 0 : sourceMapString.replace(toPosix(state.file.opts.filename), toPosix(location));
1222
- }
1223
- location = toPosix(location);
1224
- initDataObjectExpression.properties.push((0, types_12.objectProperty)((0, types_12.identifier)("location"), (0, types_12.stringLiteral)(location)));
1225
- }
1226
- if (!bytecode && sourceMapString) {
1227
- initDataObjectExpression.properties.push((0, types_12.objectProperty)((0, types_12.identifier)("sourceMap"), (0, types_12.stringLiteral)(sourceMapString)));
1228
- }
1229
- if (shouldIncludeInitData) {
1230
- const initDataDeclaration = (0, types_12.variableDeclaration)("const", [
1231
- (0, types_12.variableDeclarator)(initDataId, initDataObjectExpression)
1232
- ]);
1233
- if (limitInitDataHoisting) {
1234
- fun.getFunctionParent().node.body.body.unshift(initDataDeclaration);
1235
- } else {
1236
- pathForStringDefinitions.insertBefore(initDataDeclaration);
1237
- }
1238
- }
1239
- (0, assert_1.strict)(!(0, types_12.isFunctionDeclaration)(funExpression), "`funExpression` is a `FunctionDeclaration`.");
1240
- (0, assert_1.strict)(!(0, types_12.isObjectMethod)(funExpression), "`funExpression` is an `ObjectMethod`.");
1241
- const statements = [
1242
- (0, types_12.variableDeclaration)("const", [
1243
- (0, types_12.variableDeclarator)((0, types_12.identifier)(reactName), funExpression)
1244
- ]),
1245
- (0, types_12.expressionStatement)((0, types_12.assignmentExpression)("=", (0, types_12.memberExpression)((0, types_12.identifier)(reactName), (0, types_12.identifier)("__closure"), false), (0, types_12.objectExpression)(closureVariables.map((variable) => !state.opts.bundleMode && variable.name.endsWith(types_2.workletClassFactorySuffix) ? (0, types_12.objectProperty)((0, types_12.identifier)(variable.name), (0, types_12.memberExpression)((0, types_12.identifier)(variable.name.slice(0, variable.name.length - types_2.workletClassFactorySuffix.length)), (0, types_12.identifier)(variable.name))) : (0, types_12.objectProperty)((0, types_12.cloneNode)(variable, true), (0, types_12.cloneNode)(variable, true), false, true))))),
1246
- (0, types_12.expressionStatement)((0, types_12.assignmentExpression)("=", (0, types_12.memberExpression)((0, types_12.identifier)(reactName), (0, types_12.identifier)("__workletHash"), false), (0, types_12.numericLiteral)(workletHash)))
1247
- ];
1248
- const shouldInjectVersion = !(0, utils_1.isRelease)(state);
1249
- if (shouldInjectVersion) {
1250
- statements.push((0, types_12.expressionStatement)((0, types_12.assignmentExpression)("=", (0, types_12.memberExpression)((0, types_12.identifier)(reactName), (0, types_12.identifier)("__pluginVersion")), (0, types_12.stringLiteral)(shouldMockVersion() ? MOCK_VERSION : REAL_VERSION))));
1251
- }
1252
- if (shouldIncludeInitData) {
1253
- statements.push((0, types_12.expressionStatement)((0, types_12.assignmentExpression)("=", (0, types_12.memberExpression)((0, types_12.identifier)(reactName), (0, types_12.identifier)("__initData"), false), (0, types_12.cloneNode)(initDataId, true))));
1254
- }
1255
- if (!(0, utils_1.isRelease)(state) && !state.opts.bundleMode) {
1256
- statements.unshift((0, types_12.variableDeclaration)("const", [
1257
- (0, types_12.variableDeclarator)((0, types_12.identifier)("_e"), (0, types_12.arrayExpression)([
1258
- (0, types_12.newExpression)((0, types_12.memberExpression)((0, types_12.identifier)("global"), (0, types_12.identifier)("Error")), []),
1259
- (0, types_12.numericLiteral)(lineOffset),
1260
- (0, types_12.numericLiteral)(-27)
1261
- // the placement of opening bracket after Exception in line that defined '_e' variable
1262
- ]))
1263
- ]));
1264
- statements.push((0, types_12.expressionStatement)((0, types_12.assignmentExpression)("=", (0, types_12.memberExpression)((0, types_12.identifier)(reactName), (0, types_12.identifier)("__stackDetails"), false), (0, types_12.identifier)("_e"))));
1265
- }
1266
- statements.push((0, types_12.returnStatement)((0, types_12.identifier)(reactName)));
1267
- const factoryParams = closureVariables.map((variableId) => {
1268
- const clonedId = (0, types_12.cloneNode)(variableId, true);
1269
- if (!state.opts.bundleMode && clonedId.name.endsWith(types_2.workletClassFactorySuffix)) {
1270
- clonedId.name = clonedId.name.slice(0, clonedId.name.length - types_2.workletClassFactorySuffix.length);
1271
- }
1272
- return clonedId;
1273
- });
1274
- if (shouldIncludeInitData) {
1275
- factoryParams.unshift((0, types_12.cloneNode)(initDataId, true));
1030
+ var path_1 = __importDefault(require("path"));
1031
+ var types_12 = require_types();
1032
+ var notCapturedIdentifiers = [
1033
+ // Based on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects
1034
+ // Note that objects' properties don't need to be listed since we always only capture the whole object,
1035
+ // e.g. `global.__ErrorUtils` or `Intl.DateTimeFormat`.
1036
+ // Value properties
1037
+ "globalThis",
1038
+ "Infinity",
1039
+ "NaN",
1040
+ "undefined",
1041
+ // Function properties
1042
+ "eval",
1043
+ "isFinite",
1044
+ "isNaN",
1045
+ "parseFloat",
1046
+ "parseInt",
1047
+ "decodeURI",
1048
+ "decodeURIComponent",
1049
+ "encodeURI",
1050
+ "encodeURIComponent",
1051
+ "escape",
1052
+ "unescape",
1053
+ // Fundamental objects
1054
+ "Object",
1055
+ "Function",
1056
+ "Boolean",
1057
+ "Symbol",
1058
+ // Error objects
1059
+ "Error",
1060
+ "AggregateError",
1061
+ "EvalError",
1062
+ "RangeError",
1063
+ "ReferenceError",
1064
+ "SyntaxError",
1065
+ "TypeError",
1066
+ "URIError",
1067
+ "InternalError",
1068
+ // Numbers and dates
1069
+ "Number",
1070
+ "BigInt",
1071
+ "Math",
1072
+ "Date",
1073
+ // Text processing
1074
+ "String",
1075
+ "RegExp",
1076
+ // Indexed collections
1077
+ "Array",
1078
+ "Int8Array",
1079
+ "Uint8Array",
1080
+ "Uint8ClampedArray",
1081
+ "Int16Array",
1082
+ "Uint16Array",
1083
+ "Int32Array",
1084
+ "Uint32Array",
1085
+ "BigInt64Array",
1086
+ "BigUint64Array",
1087
+ "Float32Array",
1088
+ "Float64Array",
1089
+ // Keyed collections
1090
+ "Map",
1091
+ "Set",
1092
+ "WeakMap",
1093
+ "WeakSet",
1094
+ // Structured data
1095
+ "ArrayBuffer",
1096
+ "SharedArrayBuffer",
1097
+ "DataView",
1098
+ "Atomics",
1099
+ "JSON",
1100
+ // Managing memory
1101
+ "WeakRef",
1102
+ "FinalizationRegistry",
1103
+ // Control abstraction objects
1104
+ "Iterator",
1105
+ "AsyncIterator",
1106
+ "Promise",
1107
+ "GeneratorFunction",
1108
+ "AsyncGeneratorFunction",
1109
+ "Generator",
1110
+ "AsyncGenerator",
1111
+ "AsyncFunction",
1112
+ // Reflection
1113
+ "Reflect",
1114
+ "Proxy",
1115
+ // Internationalization
1116
+ "Intl",
1117
+ // Other stuff
1118
+ "null",
1119
+ "this",
1120
+ "global",
1121
+ "window",
1122
+ "globalThis",
1123
+ "self",
1124
+ "console",
1125
+ "performance",
1126
+ "arguments",
1127
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments
1128
+ "require",
1129
+ "fetch",
1130
+ "XMLHttpRequest",
1131
+ "WebSocket",
1132
+ // Run loop
1133
+ "queueMicrotask",
1134
+ "requestAnimationFrame",
1135
+ "cancelAnimationFrame",
1136
+ "setTimeout",
1137
+ "clearTimeout",
1138
+ "setImmediate",
1139
+ "clearImmediate",
1140
+ "setInterval",
1141
+ "clearInterval",
1142
+ // Hermes
1143
+ "HermesInternal",
1144
+ // Worklets
1145
+ "_WORKLET"
1146
+ ];
1147
+ function initializeState(state) {
1148
+ var _a, _b;
1149
+ state.skipFile = isGeneratedWorkletFile(state.file.opts.filename);
1150
+ if (state.skipFile) {
1151
+ return;
1276
1152
  }
1277
- const factoryParamObjectPattern = (0, types_12.objectPattern)(factoryParams.map((param) => (0, types_12.objectProperty)((0, types_12.cloneNode)(param, true), (0, types_12.cloneNode)(param, true), false, true)));
1278
- const factory = (0, types_12.functionExpression)((0, types_12.identifier)(workletName + "Factory"), [factoryParamObjectPattern], (0, types_12.blockStatement)(statements));
1279
- const factoryCallArgs = factoryParams.map((param) => (0, types_12.cloneNode)(param, true));
1280
- const factoryCallParamPack = (0, types_12.objectExpression)(factoryCallArgs.map((param) => (0, types_12.objectProperty)((0, types_12.cloneNode)(param, true), (0, types_12.cloneNode)(param, true), false, true)));
1281
- if (state.opts.bundleMode) {
1282
- (0, imports_1.updateRelativeRequires)(factory, state);
1283
- (0, generate_1.generateWorkletFile)(moduleBindingsToImport, relativeBindingsToImport, factory, workletHash, state);
1153
+ state.workletNumber = 1;
1154
+ state.classesToWorkletize = [];
1155
+ if (!state.opts.strictGlobal) {
1156
+ initializeGlobals();
1157
+ addCustomGlobals(state);
1284
1158
  }
1285
- factory.workletized = true;
1286
- return { factory, factoryCallParamPack, workletHash };
1159
+ const userImportForwarding = state.opts.importForwarding;
1160
+ (0, assert_1.strict)(state.importForwarding === void 0, "state.importForwarding should be undefined at this point");
1161
+ state.importForwarding = {
1162
+ relativePaths: [
1163
+ ...defaultAllowedPaths,
1164
+ ...(_a = userImportForwarding === null || userImportForwarding === void 0 ? void 0 : userImportForwarding.relativePaths) !== null && _a !== void 0 ? _a : []
1165
+ ],
1166
+ moduleNames: [
1167
+ ...defaultAllowedModules,
1168
+ ...(_b = userImportForwarding === null || userImportForwarding === void 0 ? void 0 : userImportForwarding.moduleNames) !== null && _b !== void 0 ? _b : []
1169
+ ]
1170
+ };
1287
1171
  }
1288
- function hasDirective(path, directiveText) {
1289
- if (!path.node.body) {
1172
+ function isGeneratedWorkletFile(filename) {
1173
+ if (!filename) {
1290
1174
  return false;
1291
1175
  }
1292
- const bodyPath = path.get("body");
1293
- let has = false;
1294
- if (bodyPath.isBlockStatement()) {
1295
- has = bodyPath.get("directives").some((directivePath) => {
1296
- if (directivePath.isDirective() && directivePath.node.value.value === directiveText) {
1297
- return true;
1298
- }
1299
- });
1300
- }
1301
- return has;
1302
- }
1303
- function stripWorkletDirectives(fun) {
1304
- fun.traverse({
1305
- DirectiveLiteral(nodePath) {
1306
- if ((nodePath.node.value === "worklet" || nodePath.node.value === "no-worklet-closure" || nodePath.node.value === "limit-init-data-hoisting") && nodePath.getFunctionParent() === fun) {
1307
- nodePath.parentPath.remove();
1308
- }
1309
- }
1310
- });
1311
- }
1312
- function shouldMockVersion() {
1313
- return process.env.WORKLETS_JEST_SHOULD_MOCK_VERSION === "1";
1176
+ const generatedWorkletsDirPath = path_1.default.join("react-native-worklets", types_12.generatedWorkletsDir);
1177
+ return filename.includes(generatedWorkletsDirPath);
1314
1178
  }
1315
- function hash(str) {
1316
- let i = str.length;
1317
- let hash1 = 5381;
1318
- let hash2 = 52711;
1319
- while (i--) {
1320
- const char = str.charCodeAt(i);
1321
- hash1 = hash1 * 33 ^ char;
1322
- hash2 = hash2 * 33 ^ char;
1323
- }
1324
- return (hash1 >>> 0) * 4096 + (hash2 >>> 0);
1179
+ exports2.defaultGlobals = new Set(notCapturedIdentifiers);
1180
+ function initializeGlobals() {
1181
+ exports2.globals = new Set(exports2.defaultGlobals);
1325
1182
  }
1326
- function makeWorkletName(fun, state) {
1327
- let source = "unknownFile";
1328
- if (state.file.opts.filename) {
1329
- const filepath = state.file.opts.filename;
1330
- source = (0, path_1.basename)(filepath);
1331
- const splitFilepath = filepath.split(/[\\/]/);
1332
- const nodeModulesIndex = splitFilepath.indexOf("node_modules");
1333
- if (nodeModulesIndex !== -1) {
1334
- const libraryName = splitFilepath[nodeModulesIndex + 1];
1335
- source = `${libraryName}_${source}`;
1336
- }
1337
- }
1338
- const suffix = `${source}${state.workletNumber++}`;
1339
- let reactName = "";
1340
- if ((0, types_12.isObjectMethod)(fun.node) && (0, types_12.isIdentifier)(fun.node.key)) {
1341
- reactName = fun.node.key.name;
1342
- } else if (((0, types_12.isFunctionDeclaration)(fun.node) || (0, types_12.isFunctionExpression)(fun.node)) && (0, types_12.isIdentifier)(fun.node.id)) {
1343
- reactName = fun.node.id.name;
1183
+ var defaultAllowedPaths = ["react-native-worklets"];
1184
+ var defaultAllowedModules = [
1185
+ "react-native-worklets",
1186
+ "react-native/Libraries/Core/setUpXHR"
1187
+ ];
1188
+ function addCustomGlobals(state) {
1189
+ if (state.opts && Array.isArray(state.opts.globals)) {
1190
+ state.opts.globals.forEach((name) => {
1191
+ exports2.globals.add(name);
1192
+ });
1344
1193
  }
1345
- const workletName = reactName ? (0, types_12.toIdentifier)(`${reactName}_${suffix}`) : (0, types_12.toIdentifier)(suffix);
1346
- reactName = reactName || (0, types_12.toIdentifier)(suffix);
1347
- return { workletName, reactName };
1348
1194
  }
1349
- function toPosix(p) {
1350
- return path_1.sep === "/" ? p : p.split(path_1.sep).join("/");
1351
- }
1352
- var extraPlugins = [
1353
- require.resolve("@babel/plugin-transform-shorthand-properties"),
1354
- require.resolve("@babel/plugin-transform-arrow-functions"),
1355
- require.resolve("@babel/plugin-transform-optional-chaining"),
1356
- require.resolve("@babel/plugin-transform-nullish-coalescing-operator"),
1357
- [
1358
- require.resolve("@babel/plugin-transform-template-literals"),
1359
- { loose: true }
1360
- ]
1361
- ];
1362
1195
  }
1363
1196
  });
1364
1197
 
1365
- // lib/workletFactoryCall.js
1366
- var require_workletFactoryCall = __commonJS({
1367
- "lib/workletFactoryCall.js"(exports2) {
1198
+ // lib/inlineStylesWarning.js
1199
+ var require_inlineStylesWarning = __commonJS({
1200
+ "lib/inlineStylesWarning.js"(exports2) {
1368
1201
  "use strict";
1369
1202
  Object.defineProperty(exports2, "__esModule", { value: true });
1370
- exports2.makeWorkletFactoryCall = makeWorkletFactoryCall;
1203
+ exports2.processInlineStylesWarning = processInlineStylesWarning;
1371
1204
  var types_12 = require("@babel/types");
1372
- var types_2 = require_types();
1373
- var workletFactory_1 = require_workletFactory();
1374
- function makeWorkletFactoryCall(path, state) {
1375
- const { factory, factoryCallParamPack, workletHash } = (0, workletFactory_1.makeWorkletFactory)(path, state);
1376
- let factoryCall;
1377
- if (state.opts.bundleMode) {
1378
- factoryCall = (0, types_12.callExpression)((0, types_12.memberExpression)((0, types_12.callExpression)((0, types_12.identifier)("require"), [
1379
- (0, types_12.stringLiteral)(`react-native-worklets/${types_2.generatedWorkletsDir}/${workletHash}.js`)
1380
- ]), (0, types_12.identifier)("default")), [factoryCallParamPack]);
1381
- } else {
1382
- factoryCall = (0, types_12.callExpression)(factory, [factoryCallParamPack]);
1205
+ var assert_1 = require("assert");
1206
+ var utils_1 = require_utils();
1207
+ function generateInlineStylesWarning(path) {
1208
+ return (0, types_12.callExpression)((0, types_12.arrowFunctionExpression)([], (0, types_12.blockStatement)([
1209
+ (0, types_12.expressionStatement)((0, types_12.callExpression)((0, types_12.memberExpression)((0, types_12.identifier)("console"), (0, types_12.identifier)("warn")), [
1210
+ (0, types_12.callExpression)((0, types_12.memberExpression)((0, types_12.callExpression)((0, types_12.identifier)("require"), [
1211
+ (0, types_12.stringLiteral)("react-native-reanimated")
1212
+ ]), (0, types_12.identifier)("getUseOfValueInStyleWarning")), [])
1213
+ ])),
1214
+ (0, types_12.returnStatement)(path.node)
1215
+ ])), []);
1216
+ }
1217
+ function processPropertyValueForInlineStylesWarning(path) {
1218
+ if (path.isMemberExpression() && (0, types_12.isIdentifier)(path.node.property)) {
1219
+ if (!path.node.computed && path.node.property.name === "value") {
1220
+ path.replaceWith(generateInlineStylesWarning(path));
1221
+ }
1383
1222
  }
1384
- addStackTraceDataToWorkletFactory(path, factoryCall);
1385
- const replacement = factoryCall;
1386
- return replacement;
1387
1223
  }
1388
- function addStackTraceDataToWorkletFactory(path, workletFactoryCall) {
1389
- const originalWorkletLocation = path.node.loc;
1390
- if (originalWorkletLocation) {
1391
- workletFactoryCall.callee.loc = {
1392
- filename: originalWorkletLocation.filename,
1393
- identifierName: originalWorkletLocation.identifierName,
1394
- start: originalWorkletLocation.start,
1395
- end: originalWorkletLocation.start
1396
- };
1224
+ function processTransformPropertyForInlineStylesWarning(path) {
1225
+ if ((0, types_12.isArrayExpression)(path.node)) {
1226
+ const elements = path.get("elements");
1227
+ (0, assert_1.strict)(Array.isArray(elements), "`elements` should be an array.");
1228
+ for (const element of elements) {
1229
+ if (element.isObjectExpression()) {
1230
+ processStyleObjectForInlineStylesWarning(element);
1231
+ }
1232
+ }
1233
+ }
1234
+ }
1235
+ function processStyleObjectForInlineStylesWarning(path) {
1236
+ const properties = path.get("properties");
1237
+ for (const property of properties) {
1238
+ if (property.isObjectProperty()) {
1239
+ const value = property.get("value");
1240
+ if ((0, types_12.isIdentifier)(property.node.key) && property.node.key.name === "transform") {
1241
+ processTransformPropertyForInlineStylesWarning(value);
1242
+ } else {
1243
+ processPropertyValueForInlineStylesWarning(value);
1244
+ }
1245
+ }
1246
+ }
1247
+ }
1248
+ function processInlineStylesWarning(path, state) {
1249
+ if ((0, utils_1.isRelease)(state)) {
1250
+ return;
1251
+ }
1252
+ if (state.opts.disableInlineStylesWarning) {
1253
+ return;
1254
+ }
1255
+ if (path.node.name.name !== "style") {
1256
+ return;
1257
+ }
1258
+ if (!(0, types_12.isJSXExpressionContainer)(path.node.value)) {
1259
+ return;
1260
+ }
1261
+ const expression = path.get("value").get("expression");
1262
+ (0, assert_1.strict)(!Array.isArray(expression), "`expression` should not be an array.");
1263
+ if (expression.isArrayExpression()) {
1264
+ const elements = expression.get("elements");
1265
+ (0, assert_1.strict)(Array.isArray(elements), "`elements` should be an array.");
1266
+ for (const element of elements) {
1267
+ if (element.isObjectExpression()) {
1268
+ processStyleObjectForInlineStylesWarning(element);
1269
+ }
1270
+ }
1271
+ } else if (expression.isObjectExpression()) {
1272
+ processStyleObjectForInlineStylesWarning(expression);
1397
1273
  }
1398
1274
  }
1399
1275
  }
1400
1276
  });
1401
1277
 
1402
- // lib/workletSubstitution.js
1403
- var require_workletSubstitution = __commonJS({
1404
- "lib/workletSubstitution.js"(exports2) {
1278
+ // lib/webOptimization.js
1279
+ var require_webOptimization = __commonJS({
1280
+ "lib/webOptimization.js"(exports2) {
1405
1281
  "use strict";
1406
1282
  Object.defineProperty(exports2, "__esModule", { value: true });
1407
- exports2.processIfWithWorkletDirective = processIfWithWorkletDirective;
1408
- exports2.processWorklet = processWorklet;
1409
- exports2.substituteObjectMethodWithObjectProperty = substituteObjectMethodWithObjectProperty;
1283
+ exports2.substituteWebCallExpression = substituteWebCallExpression;
1410
1284
  var types_12 = require("@babel/types");
1411
- var types_2 = require_types();
1412
- var utils_1 = require_utils();
1413
- var workletFactoryCall_1 = require_workletFactoryCall();
1414
- function processIfWithWorkletDirective(path, state) {
1415
- if (!(0, types_12.isBlockStatement)(path.node.body)) {
1416
- return false;
1417
- }
1418
- if (!hasWorkletDirective(path.node.body.directives)) {
1419
- return false;
1420
- }
1421
- processWorklet(path, state);
1422
- return true;
1423
- }
1424
- function processWorklet(path, state) {
1425
- path.traverse({
1426
- // @ts-expect-error TypeScript doesn't like this syntax here.
1427
- [types_2.WorkletizableFunction](subPath, passedState) {
1428
- processIfWithWorkletDirective(subPath, passedState);
1285
+ function substituteWebCallExpression(path) {
1286
+ const callee = path.node.callee;
1287
+ if ((0, types_12.isIdentifier)(callee)) {
1288
+ const name = callee.name;
1289
+ if (name === "isWeb" || name === "shouldBeUseWeb") {
1290
+ path.replaceWith((0, types_12.booleanLiteral)(true));
1429
1291
  }
1430
- }, state);
1431
- const workletFactoryCall = (0, workletFactoryCall_1.makeWorkletFactoryCall)(path, state);
1432
- substituteWorkletWithWorkletFactoryCall(path, workletFactoryCall);
1433
- path.scope.getProgramParent().crawl();
1434
- }
1435
- function hasWorkletDirective(directives) {
1436
- return directives.some((directive) => (0, types_12.isDirectiveLiteral)(directive.value) && directive.value.value === "worklet");
1437
- }
1438
- function substituteWorkletWithWorkletFactoryCall(path, workletFactoryCall) {
1439
- var _a;
1440
- if (path.isObjectMethod()) {
1441
- substituteObjectMethodWithObjectProperty(path, workletFactoryCall);
1442
- } else {
1443
- const name = "id" in path.node ? (_a = path.node.id) === null || _a === void 0 ? void 0 : _a.name : void 0;
1444
- (0, utils_1.replaceWithFactoryCall)(path, name, workletFactoryCall);
1445
1292
  }
1446
1293
  }
1447
- function substituteObjectMethodWithObjectProperty(path, workletFactoryCall) {
1448
- const replacement = (0, types_12.objectProperty)(path.node.key, workletFactoryCall);
1449
- path.replaceWith(replacement);
1450
- }
1451
1294
  }
1452
1295
  });
1453
1296
 
1454
- // lib/objectWorklets.js
1455
- var require_objectWorklets = __commonJS({
1456
- "lib/objectWorklets.js"(exports2) {
1297
+ // lib/imports.js
1298
+ var require_imports = __commonJS({
1299
+ "lib/imports.js"(exports2) {
1457
1300
  "use strict";
1458
1301
  Object.defineProperty(exports2, "__esModule", { value: true });
1459
- exports2.tryProcessingNode = tryProcessingNode;
1460
- exports2.processWorkletizableObject = processWorkletizableObject;
1461
- var findWorklet_1 = require_findWorklet();
1462
- var types_12 = require_types();
1463
- var workletSubstitution_12 = require_workletSubstitution();
1464
- function tryProcessingNode(arg, state, acceptWorkletizableFunction, acceptObject) {
1465
- var _a;
1466
- const maybeWorklet = (0, findWorklet_1.findWorklet)(arg, state, acceptWorkletizableFunction, acceptObject);
1467
- if (!maybeWorklet || ((_a = maybeWorklet.getFunctionParent()) === null || _a === void 0 ? void 0 : _a.node.workletized)) {
1468
- return;
1469
- }
1470
- if ((0, types_12.isWorkletizableFunctionPath)(maybeWorklet)) {
1471
- (0, workletSubstitution_12.processWorklet)(maybeWorklet, state);
1472
- } else if ((0, types_12.isWorkletizableObjectPath)(maybeWorklet)) {
1473
- processWorkletizableObject(maybeWorklet, state);
1474
- }
1302
+ exports2.updateRelativeRequires = updateRelativeRequires;
1303
+ exports2.isImport = isImport;
1304
+ exports2.isImportRelative = isImportRelative;
1305
+ exports2.canForwardModuleImport = canForwardModuleImport;
1306
+ exports2.canForwardRelativeImport = canForwardRelativeImport;
1307
+ exports2.createImportPathLiteral = createImportPathLiteral;
1308
+ var core_1 = require("@babel/core");
1309
+ var types_12 = require("@babel/types");
1310
+ var path_1 = require("path");
1311
+ var types_2 = require_types();
1312
+ function updateRelativeRequires(node, state) {
1313
+ (0, core_1.traverse)(node, {
1314
+ noScope: true,
1315
+ CallExpression(nodePath) {
1316
+ var _a;
1317
+ if (nodePath.get("callee").isIdentifier({ name: "require" }) && ((_a = nodePath.get("arguments")[0]) === null || _a === void 0 ? void 0 : _a.isStringLiteral())) {
1318
+ const requiredModule = nodePath.get("arguments")[0];
1319
+ if (requiredModule.node.value.startsWith(".") && canForwardRelativeImport(state.file.opts.filename || "", state.importForwarding.relativePaths)) {
1320
+ requiredModule.replaceWith(createImportPathLiteral(requiredModule.node.value, state));
1321
+ }
1322
+ }
1323
+ }
1324
+ });
1475
1325
  }
1476
- function processWorkletizableObject(path, state) {
1477
- const properties = path.get("properties");
1478
- for (const property of properties) {
1479
- if (property.isObjectMethod()) {
1480
- (0, workletSubstitution_12.processWorklet)(property, state);
1481
- } else if (property.isObjectProperty()) {
1482
- const value = property.get("value");
1483
- tryProcessingNode(
1484
- value,
1485
- state,
1486
- true,
1487
- // acceptWorkletizableFunction
1488
- false
1489
- // acceptObject
1490
- );
1491
- } else {
1492
- throw new Error(`'${property.type}' as to-be workletized argument is not supported for object hooks.`);
1326
+ function isImport(binding) {
1327
+ return binding.kind === "module" && binding.constant && (binding.path.isImportSpecifier() || binding.path.isImportDefaultSpecifier()) && binding.path.parentPath.isImportDeclaration();
1328
+ }
1329
+ function isImportRelative(imported) {
1330
+ return imported.path.parentPath.node.source.value.startsWith(".");
1331
+ }
1332
+ function canForwardModuleImport(moduleName, forwardableModuleNames) {
1333
+ return forwardableModuleNames.some((forwardableModuleName) => moduleName === forwardableModuleName || moduleName.startsWith(forwardableModuleName + "/"));
1334
+ }
1335
+ function canForwardRelativeImport(modulePath, relativePaths) {
1336
+ return !!modulePath && relativePaths.some((relativePath) => matchesFilenameSegment(modulePath, relativePath));
1337
+ }
1338
+ function matchesFilenameSegment(filename, allowedPath) {
1339
+ const pkgSegments = allowedPath.split(path_1.posix.sep);
1340
+ let fileSegments = filename.split(path_1.sep);
1341
+ const lastNodeModules = fileSegments.lastIndexOf("node_modules");
1342
+ if (lastNodeModules !== -1) {
1343
+ fileSegments = fileSegments.slice(lastNodeModules + 1);
1344
+ }
1345
+ for (let i = 0; i <= fileSegments.length - pkgSegments.length; i++) {
1346
+ if (pkgSegments.every((segment, segmentIndex) => fileSegments[i + segmentIndex] === segment)) {
1347
+ return true;
1493
1348
  }
1494
1349
  }
1350
+ return false;
1351
+ }
1352
+ function createImportPathLiteral(originalPath, state) {
1353
+ const generatedWorkletsDirPath = (0, path_1.resolve)((0, path_1.dirname)(require.resolve("react-native-worklets/package.json")), types_2.generatedWorkletsDir);
1354
+ const resolved = (0, path_1.resolve)((0, path_1.dirname)(state.file.opts.filename), originalPath);
1355
+ const relativePath = (0, path_1.relative)(generatedWorkletsDirPath, resolved);
1356
+ return (0, types_12.stringLiteral)(path_1.sep === "/" ? relativePath : relativePath.split(path_1.sep).join("/"));
1495
1357
  }
1496
1358
  }
1497
1359
  });
1498
1360
 
1499
- // lib/autoworkletization.js
1500
- var require_autoworkletization = __commonJS({
1501
- "lib/autoworkletization.js"(exports2) {
1361
+ // lib/closure.js
1362
+ var require_closure = __commonJS({
1363
+ "lib/closure.js"(exports2) {
1502
1364
  "use strict";
1503
1365
  Object.defineProperty(exports2, "__esModule", { value: true });
1504
- exports2.processIfAutoworkletizableCallback = processIfAutoworkletizableCallback;
1505
- exports2.processCalleesAutoworkletizableCallbacks = processCalleesAutoworkletizableCallbacks;
1366
+ exports2.getClosure = getClosure;
1506
1367
  var types_12 = require("@babel/types");
1507
- var gestureHandlerAutoworkletization_1 = require_gestureHandlerAutoworkletization();
1508
- var layoutAnimationAutoworkletization_1 = require_layoutAnimationAutoworkletization();
1509
- var objectWorklets_1 = require_objectWorklets();
1510
- var workletSubstitution_12 = require_workletSubstitution();
1511
- var reanimatedObjectHooks = /* @__PURE__ */ new Set([
1512
- "useAnimatedScrollHandler",
1513
- ...Array.from(gestureHandlerAutoworkletization_1.gestureHandlerObjectHooks)
1514
- ]);
1515
- var reanimatedFunctionHooks = /* @__PURE__ */ new Set([
1516
- "useFrameCallback",
1517
- "useAnimatedStyle",
1518
- "useAnimatedProps",
1519
- "createAnimatedPropAdapter",
1520
- "useDerivedValue",
1521
- "useAnimatedScrollHandler",
1522
- "useAnimatedReaction",
1523
- // animations' callbacks
1524
- "withTiming",
1525
- "withSpring",
1526
- "withDecay",
1527
- "withRepeat",
1528
- // scheduling functions
1529
- "runOnUI",
1530
- "executeOnUIRuntimeSync",
1531
- "scheduleOnUI",
1532
- "runOnUISync",
1533
- "runOnUIAsync",
1534
- "runOnRuntime",
1535
- "runOnRuntimeSync",
1536
- "runOnRuntimeAsync",
1537
- "scheduleOnRuntime",
1538
- "runOnRuntimeSyncWithId",
1539
- "scheduleOnRuntimeWithId"
1540
- ]);
1541
- var reanimatedFunctionArgsToWorkletize = new Map([
1542
- ["useFrameCallback", [0]],
1543
- ["useAnimatedStyle", [0]],
1544
- ["useAnimatedProps", [0]],
1545
- ["createAnimatedPropAdapter", [0]],
1546
- ["useDerivedValue", [0]],
1547
- ["useAnimatedScrollHandler", [0]],
1548
- ["useAnimatedReaction", [0, 1]],
1549
- ["withTiming", [2]],
1550
- ["withSpring", [2]],
1551
- ["withDecay", [1]],
1552
- ["withRepeat", [3]],
1553
- ["runOnUI", [0]],
1554
- ["executeOnUIRuntimeSync", [0]],
1555
- ["scheduleOnUI", [0]],
1556
- ["runOnUISync", [0]],
1557
- ["runOnUIAsync", [0]],
1558
- ["runOnRuntime", [1]],
1559
- ["runOnRuntimeSync", [1]],
1560
- ["runOnRuntimeAsync", [1]],
1561
- ["scheduleOnRuntime", [1]],
1562
- ["runOnRuntimeSyncWithId", [1]],
1563
- ["scheduleOnRuntimeWithId", [1]],
1564
- ...Array.from(gestureHandlerAutoworkletization_1.gestureHandlerObjectHooks).map((name) => [name, [0]]),
1565
- ...Array.from(gestureHandlerAutoworkletization_1.gestureHandlerBuilderMethods).map((name) => [name, [0]])
1566
- ]);
1567
- function processIfAutoworkletizableCallback(path, state) {
1568
- if ((0, gestureHandlerAutoworkletization_1.isGestureHandlerEventCallback)(path) || (0, layoutAnimationAutoworkletization_1.isLayoutAnimationCallback)(path)) {
1569
- (0, workletSubstitution_12.processWorklet)(path, state);
1570
- return true;
1571
- }
1572
- return false;
1573
- }
1574
- function processCalleesAutoworkletizableCallbacks(path, state) {
1575
- const callee = (0, types_12.isSequenceExpression)(path.node.callee) ? path.node.callee.expressions[path.node.callee.expressions.length - 1] : path.node.callee;
1576
- const name = "name" in callee ? callee.name : "property" in callee && "name" in callee.property ? callee.property.name : void 0;
1577
- if (name === void 0) {
1578
- return;
1579
- }
1580
- if (reanimatedFunctionHooks.has(name) || reanimatedObjectHooks.has(name)) {
1581
- const acceptWorkletizableFunction = reanimatedFunctionHooks.has(name);
1582
- const acceptObject = reanimatedObjectHooks.has(name);
1583
- const argIndices = reanimatedFunctionArgsToWorkletize.get(name);
1584
- const args = path.get("arguments").filter((_, index) => argIndices.includes(index));
1585
- processArgs(args, state, acceptWorkletizableFunction, acceptObject);
1586
- } else if (!(0, types_12.isV8IntrinsicIdentifier)(callee) && (0, gestureHandlerAutoworkletization_1.isGestureObjectEventCallbackMethod)(callee)) {
1587
- const args = path.get("arguments");
1588
- processArgs(args, state, true, true);
1589
- }
1590
- }
1591
- function processArgs(args, state, acceptWorkletizableFunction, acceptObject) {
1592
- args.forEach((arg) => {
1593
- (0, objectWorklets_1.tryProcessingNode)(arg, state, acceptWorkletizableFunction, acceptObject);
1594
- });
1368
+ var globals_12 = require_globals();
1369
+ var imports_1 = require_imports();
1370
+ function getClosure(funPath, state) {
1371
+ const capturedNames = /* @__PURE__ */ new Set();
1372
+ const closureVariables = new Array();
1373
+ const moduleBindingsToImport = /* @__PURE__ */ new Set();
1374
+ const relativeBindingsToImport = /* @__PURE__ */ new Set();
1375
+ let recrawled = false;
1376
+ funPath.traverse({
1377
+ "TSType|TSTypeAliasDeclaration|TSInterfaceDeclaration"(typePath) {
1378
+ typePath.skip();
1379
+ },
1380
+ ReferencedIdentifier(idPath) {
1381
+ if (idPath.isJSXIdentifier() && !state.opts.bundleMode) {
1382
+ return;
1383
+ }
1384
+ const name = idPath.node.name;
1385
+ if (capturedNames.has(name)) {
1386
+ return;
1387
+ }
1388
+ let binding = idPath.scope.getBinding(name);
1389
+ if (!binding && !recrawled) {
1390
+ recrawled = true;
1391
+ idPath.scope.crawl();
1392
+ binding = idPath.scope.getBinding(name);
1393
+ }
1394
+ if (!binding) {
1395
+ if (state.opts.strictGlobal || globals_12.globals.has(name)) {
1396
+ return;
1397
+ }
1398
+ capturedNames.add(name);
1399
+ closureVariables.push((0, types_12.cloneNode)(idPath.node, true));
1400
+ return;
1401
+ }
1402
+ if ("id" in funPath.node) {
1403
+ const id = idPath.scope.getBindingIdentifier(name);
1404
+ if (id && id === funPath.node.id) {
1405
+ return;
1406
+ }
1407
+ }
1408
+ let scope = idPath.scope;
1409
+ while (scope !== funPath.scope.parent) {
1410
+ if (scope.hasOwnBinding(name)) {
1411
+ return;
1412
+ }
1413
+ scope = scope.parent;
1414
+ }
1415
+ if (state.opts.bundleMode && (0, imports_1.isImport)(binding)) {
1416
+ if ((0, imports_1.isImportRelative)(binding) && (0, imports_1.canForwardRelativeImport)(state.filename, state.importForwarding.relativePaths)) {
1417
+ capturedNames.add(name);
1418
+ relativeBindingsToImport.add(binding);
1419
+ return;
1420
+ }
1421
+ const source = binding.path.parentPath.node.source.value;
1422
+ if ((0, imports_1.canForwardModuleImport)(source, state.importForwarding.moduleNames)) {
1423
+ capturedNames.add(name);
1424
+ moduleBindingsToImport.add(binding);
1425
+ return;
1426
+ }
1427
+ }
1428
+ capturedNames.add(name);
1429
+ closureVariables.push((0, types_12.cloneNode)(idPath.node, true));
1430
+ }
1431
+ }, state);
1432
+ return {
1433
+ closureVariables,
1434
+ moduleBindingsToImport,
1435
+ relativeBindingsToImport
1436
+ };
1595
1437
  }
1596
1438
  }
1597
1439
  });
1598
1440
 
1599
- // lib/bundleMode.js
1600
- var require_bundleMode = __commonJS({
1601
- "lib/bundleMode.js"(exports2) {
1441
+ // lib/generate.js
1442
+ var require_generate = __commonJS({
1443
+ "lib/generate.js"(exports2) {
1602
1444
  "use strict";
1445
+ var __importDefault = exports2 && exports2.__importDefault || function(mod) {
1446
+ return mod && mod.__esModule ? mod : { "default": mod };
1447
+ };
1603
1448
  Object.defineProperty(exports2, "__esModule", { value: true });
1604
- exports2.toggleBundleMode = toggleBundleMode;
1449
+ exports2.generateWorkletFile = generateWorkletFile;
1450
+ var core_1 = require("@babel/core");
1605
1451
  var types_12 = require("@babel/types");
1452
+ var assert_1 = __importDefault(require("assert"));
1453
+ var fs_1 = require("fs");
1606
1454
  var path_1 = require("path");
1607
- var WORKLETS_PACKAGE = "react-native-worklets";
1608
- var WORKLETS_SRC_DIR = (0, path_1.join)(WORKLETS_PACKAGE, "src");
1609
- var WORKLETS_LIB_DIR = (0, path_1.join)(WORKLETS_PACKAGE, "lib", "module");
1610
- var togglePaths = [
1611
- (0, path_1.join)(WORKLETS_SRC_DIR, "index.ts"),
1612
- (0, path_1.join)(WORKLETS_SRC_DIR, "debug", "bundleMode.native.ts"),
1613
- (0, path_1.join)(WORKLETS_LIB_DIR, "index.js"),
1614
- (0, path_1.join)(WORKLETS_LIB_DIR, "debug", "bundleMode.native.js")
1615
- ];
1616
- function toggleBundleMode(path, state) {
1617
- if (!state.opts.bundleMode || !togglePaths.some((togglePath) => {
1618
- var _a;
1619
- return (_a = state.filename) === null || _a === void 0 ? void 0 : _a.endsWith(togglePath);
1620
- })) {
1621
- return;
1622
- }
1623
- const expressionPath = path.get("expression");
1624
- if (!expressionPath.isAssignmentExpression()) {
1625
- return;
1626
- }
1627
- const left = expressionPath.get("left");
1628
- if (!left.isMemberExpression()) {
1629
- return;
1630
- }
1631
- const object = left.get("object");
1632
- const property = left.get("property");
1633
- if (!object.isIdentifier() || object.node.name !== "globalThis" || !property.isIdentifier() || property.node.name !== "_WORKLETS_BUNDLE_MODE_ENABLED") {
1634
- return;
1455
+ var imports_1 = require_imports();
1456
+ var types_2 = require_types();
1457
+ function generateWorkletFile(moduleBindingsToImport, relativeBindingsToImport, factory, workletHash, state) {
1458
+ var _a, _b;
1459
+ const libraryImports = Array.from(moduleBindingsToImport).filter((binding) => (binding.path.isImportSpecifier() || binding.path.isImportDefaultSpecifier()) && binding.path.parentPath.isImportDeclaration()).map((binding) => (0, types_12.importDeclaration)([(0, types_12.cloneNode)(binding.path.node, true)], (0, types_12.stringLiteral)(binding.path.parentPath.node.source.value)));
1460
+ const filesDirPath = (0, path_1.resolve)((0, path_1.dirname)(require.resolve("react-native-worklets/package.json")), types_2.generatedWorkletsDir);
1461
+ const relativeImports = Array.from(relativeBindingsToImport).filter((binding) => binding.path.isImportSpecifier() && binding.path.parentPath.isImportDeclaration()).map((binding) => (0, types_12.importDeclaration)([(0, types_12.cloneNode)(binding.path.node, true)], (0, imports_1.createImportPathLiteral)(binding.path.parentPath.node.source.value, state)));
1462
+ const imports = [...libraryImports, ...relativeImports];
1463
+ const newProg = (0, types_12.program)([...imports, (0, types_12.exportDefaultDeclaration)(factory)]);
1464
+ const transformedProg = (_a = (0, core_1.transformFromAstSync)(newProg, void 0, {
1465
+ filename: state.file.opts.filename,
1466
+ presets: [resolvePresetTypescript()],
1467
+ plugins: [stripJsxDevAttributesPlugin],
1468
+ ast: false,
1469
+ babelrc: false,
1470
+ configFile: false,
1471
+ comments: false
1472
+ })) === null || _a === void 0 ? void 0 : _a.code;
1473
+ (0, assert_1.default)(transformedProg, "[Worklets] `transformedProg` is undefined.");
1474
+ const dedicatedFilePath = (0, path_1.resolve)(filesDirPath, `${workletHash}.js`);
1475
+ const output = process.env.WORKLETS_WRITE_ORIGIN ? `// __workletOrigin: ${(_b = state.file.opts.filename) !== null && _b !== void 0 ? _b : "unknown"}
1476
+ ${transformedProg}` : transformedProg;
1477
+ (0, fs_1.writeFileSync)(dedicatedFilePath, output);
1478
+ }
1479
+ function resolvePresetTypescript() {
1480
+ try {
1481
+ return require.resolve("@babel/preset-typescript");
1482
+ } catch (_a) {
1483
+ return require.resolve("@babel/preset-typescript", {
1484
+ paths: [(0, path_1.dirname)(require.resolve("react-native-worklets/package.json"))]
1485
+ });
1635
1486
  }
1636
- const right = expressionPath.get("right");
1637
- right.replaceWith((0, types_12.booleanLiteral)(true));
1638
1487
  }
1488
+ var stripJsxDevAttributesPlugin = {
1489
+ name: "worklets-strip-jsx-dev-attributes",
1490
+ visitor: {
1491
+ JSXAttribute(path) {
1492
+ const name = path.node.name;
1493
+ if (name.type !== "JSXIdentifier") {
1494
+ return;
1495
+ }
1496
+ if (name.name !== "__self" && name.name !== "__source") {
1497
+ return;
1498
+ }
1499
+ path.remove();
1500
+ }
1501
+ }
1502
+ };
1639
1503
  }
1640
1504
  });
1641
1505
 
1642
- // lib/class.js
1643
- var require_class = __commonJS({
1644
- "lib/class.js"(exports2) {
1506
+ // lib/hermesBytecode.js
1507
+ var require_hermesBytecode = __commonJS({
1508
+ "lib/hermesBytecode.js"(exports2) {
1645
1509
  "use strict";
1646
- var __importDefault = exports2 && exports2.__importDefault || function(mod) {
1647
- return mod && mod.__esModule ? mod : { "default": mod };
1648
- };
1649
1510
  Object.defineProperty(exports2, "__esModule", { value: true });
1650
- exports2.processIfWorkletClass = processIfWorkletClass;
1651
- var generator_1 = __importDefault(require("@babel/generator"));
1652
- var traverse_1 = __importDefault(require("@babel/traverse"));
1653
- var types_12 = require("@babel/types");
1654
- var assert_1 = require("assert");
1655
- var transform_1 = require_transform();
1656
- var types_2 = require_types();
1657
- var utils_1 = require_utils();
1658
- var classWorkletMarker = "__workletClass";
1659
- function processIfWorkletClass(classPath, state) {
1660
- if (!isWorkletizableClass(classPath, state) || state.opts.bundleMode) {
1661
- return false;
1511
+ exports2.compileWorkletToHbc = compileWorkletToHbc;
1512
+ var core_1 = require("@babel/core");
1513
+ var child_process_1 = require("child_process");
1514
+ function compileWorkletToHbc(funString, workletHash, state) {
1515
+ if (compilationCache.has(workletHash)) {
1516
+ return compilationCache.get(workletHash);
1662
1517
  }
1663
- removeWorkletClassMarker(classPath.node.body);
1664
- processClass(classPath, state);
1665
- return true;
1666
- }
1667
- function processClass(classPath, state) {
1668
- (0, assert_1.strict)(classPath.node.id);
1669
- const className = classPath.node.id.name;
1670
- const polyfilledClassAst = getPolyfilledAst(classPath.node, state);
1671
- sortPolyfills(polyfilledClassAst);
1672
- appendWorkletDirectiveToPolyfills(polyfilledClassAst.program.body);
1673
- replaceClassDeclarationWithFactoryAndCall(polyfilledClassAst.program.body, className);
1674
- polyfilledClassAst.program.body.push((0, types_12.returnStatement)((0, types_12.identifier)(className)));
1675
- const factoryFactory = (0, types_12.functionExpression)(null, [], (0, types_12.blockStatement)([...polyfilledClassAst.program.body]));
1676
- const factoryCall = (0, types_12.callExpression)(factoryFactory, []);
1677
- (0, utils_1.replaceWithFactoryCall)(classPath, className, factoryCall);
1678
- }
1679
- function getPolyfilledAst(classNode, state) {
1680
- var _a;
1681
- const classCode = (0, generator_1.default)(classNode).code;
1682
- const classWithPolyfills = (0, transform_1.workletTransformSync)(classCode, {
1683
- extraPlugins: [
1684
- "@babel/plugin-transform-class-properties",
1685
- "@babel/plugin-transform-classes",
1686
- "@babel/plugin-transform-unicode-regex",
1687
- ...(_a = state.opts.extraPlugins) !== null && _a !== void 0 ? _a : []
1688
- ],
1689
- extraPresets: state.opts.extraPresets,
1690
- filename: state.file.opts.filename,
1691
- ast: true,
1692
- babelrc: false,
1693
- configFile: false
1694
- });
1695
- (0, assert_1.strict)(classWithPolyfills && classWithPolyfills.ast);
1696
- return classWithPolyfills.ast;
1697
- }
1698
- function appendWorkletDirectiveToPolyfills(statements) {
1699
- statements.forEach((statement) => {
1700
- if ((0, types_12.isFunctionDeclaration)(statement)) {
1701
- const workletDirective = (0, types_12.directive)((0, types_12.directiveLiteral)("worklet"));
1702
- statement.body.directives.push(workletDirective);
1703
- }
1704
- });
1705
- }
1706
- function replaceClassDeclarationWithFactoryAndCall(statements, className) {
1707
- const classFactoryName = className + types_2.workletClassFactorySuffix;
1708
- const classDeclarationIndex = getPolyfilledClassDeclarationIndex(statements, className);
1709
- const classDeclarationToReplace = statements[classDeclarationIndex];
1710
- const classDeclarationInit = classDeclarationToReplace.declarations[0].init;
1711
- const classFactoryDeclaration = (0, types_12.functionDeclaration)((0, types_12.identifier)(classFactoryName), [], (0, types_12.blockStatement)([
1712
- (0, types_12.variableDeclaration)("const", [
1713
- (0, types_12.variableDeclarator)((0, types_12.identifier)(className), classDeclarationInit)
1714
- ]),
1715
- (0, types_12.expressionStatement)((0, types_12.assignmentExpression)("=", (0, types_12.memberExpression)((0, types_12.identifier)(className), (0, types_12.identifier)(classFactoryName)), (0, types_12.identifier)(classFactoryName))),
1716
- (0, types_12.returnStatement)((0, types_12.identifier)(className))
1717
- ], [(0, types_12.directive)((0, types_12.directiveLiteral)("worklet"))]));
1718
- const newClassDeclaration = (0, types_12.variableDeclaration)("const", [
1719
- (0, types_12.variableDeclarator)((0, types_12.identifier)(className), (0, types_12.callExpression)((0, types_12.identifier)(classFactoryName), []))
1720
- ]);
1721
- statements.splice(classDeclarationIndex, 1, classFactoryDeclaration, newClassDeclaration);
1722
- }
1723
- function getPolyfilledClassDeclarationIndex(statements, className) {
1724
- const index = statements.findIndex((statement) => (0, types_12.isVariableDeclaration)(statement) && statement.declarations.some((declaration) => (0, types_12.isIdentifier)(declaration.id) && declaration.id.name === className));
1725
- (0, assert_1.strict)(index >= 0);
1726
- return index;
1727
- }
1728
- function hasWorkletClassMarker(classBody) {
1729
- return classBody.body.some((statement) => (0, types_12.isClassProperty)(statement) && (0, types_12.isIdentifier)(statement.key) && statement.key.name === classWorkletMarker);
1730
- }
1731
- function removeWorkletClassMarker(classBody) {
1732
- classBody.body = classBody.body.filter((statement) => !(0, types_12.isClassProperty)(statement) || !(0, types_12.isIdentifier)(statement.key) || statement.key.name !== classWorkletMarker);
1518
+ const result = compile(funString, state);
1519
+ compilationCache.set(workletHash, result);
1520
+ return result;
1733
1521
  }
1734
- function sortPolyfills(ast) {
1735
- const toSort = getPolyfillsToSort(ast);
1736
- const sorted = topoSort(toSort);
1737
- const toSortIndices = toSort.map((element) => element.index);
1738
- const sortedIndices = sorted.map((element) => element.index);
1739
- const statements = ast.program.body;
1740
- const oldStatements = [...statements];
1741
- for (let i = 0; i < toSort.length; i++) {
1742
- const sourceIndex = sortedIndices[i];
1743
- const targetIndex = toSortIndices[i];
1744
- const source = oldStatements[sourceIndex];
1745
- statements[targetIndex] = source;
1522
+ function compile(funString, state) {
1523
+ const hermesc = resolveHbcBinary(state);
1524
+ if (!hermesc) {
1525
+ return null;
1746
1526
  }
1747
- }
1748
- function getPolyfillsToSort(ast) {
1749
- const polyfills = [];
1750
- (0, traverse_1.default)(ast, {
1751
- Program: {
1752
- enter: (functionPath) => {
1753
- const statements = functionPath.get("body");
1754
- statements.forEach((statement, index) => {
1755
- var _a;
1756
- const bindingIdentifiers = statement.getBindingIdentifiers();
1757
- if (!statement.isFunctionDeclaration() || !((_a = statement.node.id) === null || _a === void 0 ? void 0 : _a.name)) {
1758
- return;
1759
- }
1760
- const element = {
1761
- name: statement.node.id.name,
1762
- index,
1763
- dependencies: /* @__PURE__ */ new Set()
1764
- };
1765
- polyfills.push(element);
1766
- statement.traverse({
1767
- Identifier(path) {
1768
- if (isOutsideDependency(path, bindingIdentifiers, statement)) {
1769
- element.dependencies.add(path.node.name);
1770
- }
1771
- }
1772
- });
1773
- });
1527
+ try {
1528
+ return runHermesc(hermesc, funString);
1529
+ } catch (error) {
1530
+ if (getErrorOutput(error).includes("JSX")) {
1531
+ const transformed = transformJsx(funString);
1532
+ if (transformed !== null) {
1533
+ try {
1534
+ return runHermesc(hermesc, transformed);
1535
+ } catch (retryError) {
1536
+ return warnFallback(retryError);
1537
+ }
1774
1538
  }
1775
1539
  }
1776
- });
1777
- return polyfills;
1778
- }
1779
- function topoSort(toSort) {
1780
- const sorted = [];
1781
- const stack = /* @__PURE__ */ new Set();
1782
- for (const element of toSort) {
1783
- recursiveTopoSort(element, toSort, sorted, stack);
1540
+ return warnFallback(error);
1784
1541
  }
1785
- return sorted;
1786
1542
  }
1787
- function recursiveTopoSort(current, toSort, sorted, stack) {
1788
- if (stack.has(current.name)) {
1789
- throw new Error("Cycle detected. This should never happen.");
1790
- }
1791
- if (sorted.find((element) => element.name === current.name)) {
1543
+ var MAX_BYTECODE_BYTES = 256 * 1024 * 1024;
1544
+ var compilationCache = /* @__PURE__ */ new Map();
1545
+ var warnedMessages = /* @__PURE__ */ new Set();
1546
+ function warnOnce(message) {
1547
+ if (warnedMessages.has(message)) {
1792
1548
  return;
1793
1549
  }
1794
- stack.add(current.name);
1795
- for (const dependency of current.dependencies) {
1796
- if (!sorted.find((element) => element.name === dependency)) {
1797
- const next = toSort.find((element) => element.name === dependency);
1798
- (0, assert_1.strict)(next);
1799
- recursiveTopoSort(next, toSort, sorted, stack);
1550
+ warnedMessages.add(message);
1551
+ console.warn(`[Worklets] ${message}`);
1552
+ }
1553
+ function resolveHbcBinary(state) {
1554
+ const { getHBCBinary } = state.opts;
1555
+ if (!getHBCBinary) {
1556
+ warnOnce("The `getHBCBinary` plugin option is required to compile worklets to Hermes bytecode. Falling back to shipping worklets as source strings.");
1557
+ return null;
1558
+ }
1559
+ try {
1560
+ const binary = getHBCBinary();
1561
+ if (!binary) {
1562
+ throw new Error("`getHBCBinary` returned an empty path.");
1800
1563
  }
1564
+ return binary;
1565
+ } catch (error) {
1566
+ warnOnce(`Calling \`getHBCBinary\` failed, falling back to a source string. ${error instanceof Error ? error.message : String(error)}`);
1567
+ return null;
1801
1568
  }
1802
- sorted.push(current);
1803
- stack.delete(current.name);
1804
1569
  }
1805
- function isOutsideDependency(identifierPath, bindingIdentifiers, functionPath) {
1806
- return (
1807
- // We don't care about identifiers that were just declared.
1808
- identifierPath.isReferencedIdentifier() && // We don't care about identifiers that are bound in the scope.
1809
- !(identifierPath.node.name in bindingIdentifiers) && // This I don't exactly understand, but the function identifier itself isn't in `bindingIdentifiers`,
1810
- // but it return true on `hasOwnBinding`.
1811
- !functionPath.scope.hasOwnBinding(identifierPath.node.name) && // `hasReference` returns true for global identifiers, like `Object`,
1812
- // we don't want to include those.
1813
- functionPath.scope.hasReference(identifierPath.node.name)
1814
- );
1570
+ function runHermesc(hermesc, source) {
1571
+ return (0, child_process_1.execFileSync)(hermesc, ["-g0", "-emit-binary", "-O", "-w", "-"], {
1572
+ input: source,
1573
+ maxBuffer: MAX_BYTECODE_BYTES,
1574
+ stdio: ["pipe", "pipe", "pipe"]
1575
+ });
1815
1576
  }
1816
- function isWorkletizableClass(classPath, state) {
1577
+ function getErrorOutput(error) {
1578
+ const stderr = error === null || error === void 0 ? void 0 : error.stderr;
1579
+ if (stderr) {
1580
+ return stderr.toString();
1581
+ }
1582
+ return error instanceof Error ? error.message : String(error);
1583
+ }
1584
+ function warnFallback(error) {
1585
+ const reason = getErrorOutput(error).trim().split("\n")[0];
1586
+ warnOnce(`Could not compile a worklet to Hermes bytecode, falling back to a source string. ${reason}`);
1587
+ return null;
1588
+ }
1589
+ var jsxPluginPath;
1590
+ function resolveJsxPlugin() {
1591
+ if (jsxPluginPath === void 0) {
1592
+ try {
1593
+ jsxPluginPath = require.resolve("@babel/plugin-transform-react-jsx");
1594
+ } catch (_a) {
1595
+ jsxPluginPath = null;
1596
+ }
1597
+ }
1598
+ return jsxPluginPath;
1599
+ }
1600
+ function transformJsx(source) {
1817
1601
  var _a;
1818
- const className = (_a = classPath.node.id) === null || _a === void 0 ? void 0 : _a.name;
1819
- const classNode = classPath.node;
1820
- if (!className) {
1821
- return false;
1602
+ const plugin = resolveJsxPlugin();
1603
+ if (!plugin) {
1604
+ return null;
1605
+ }
1606
+ try {
1607
+ const result = (0, core_1.transformSync)(source, {
1608
+ babelrc: false,
1609
+ configFile: false,
1610
+ compact: true,
1611
+ plugins: [plugin]
1612
+ });
1613
+ return (_a = result === null || result === void 0 ? void 0 : result.code) !== null && _a !== void 0 ? _a : null;
1614
+ } catch (_b) {
1615
+ return null;
1822
1616
  }
1823
- const isMarked = hasWorkletClassMarker(classNode.body);
1824
- const isMemoizedNode = state.classesToWorkletize.some((record) => record.node === classNode);
1825
- const isTopLevelMemoizedName = classPath.parentPath.isProgram() && state.classesToWorkletize.some((record) => record.name === className);
1826
- state.classesToWorkletize = state.classesToWorkletize.filter((record) => record.node !== classNode && record.name !== className);
1827
- const result = isMarked || isMemoizedNode || isTopLevelMemoizedName;
1828
- return result;
1829
1617
  }
1830
1618
  }
1831
1619
  });
1832
1620
 
1833
- // lib/contextObject.js
1834
- var require_contextObject = __commonJS({
1835
- "lib/contextObject.js"(exports2) {
1621
+ // lib/workletStringCode.js
1622
+ var require_workletStringCode = __commonJS({
1623
+ "lib/workletStringCode.js"(exports2) {
1836
1624
  "use strict";
1625
+ var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
1626
+ if (k2 === void 0) k2 = k;
1627
+ var desc = Object.getOwnPropertyDescriptor(m, k);
1628
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
1629
+ desc = { enumerable: true, get: function() {
1630
+ return m[k];
1631
+ } };
1632
+ }
1633
+ Object.defineProperty(o, k2, desc);
1634
+ }) : (function(o, m, k, k2) {
1635
+ if (k2 === void 0) k2 = k;
1636
+ o[k2] = m[k];
1637
+ }));
1638
+ var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
1639
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
1640
+ }) : function(o, v) {
1641
+ o["default"] = v;
1642
+ });
1643
+ var __importStar = exports2 && exports2.__importStar || /* @__PURE__ */ (function() {
1644
+ var ownKeys = function(o) {
1645
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
1646
+ var ar = [];
1647
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
1648
+ return ar;
1649
+ };
1650
+ return ownKeys(o);
1651
+ };
1652
+ return function(mod) {
1653
+ if (mod && mod.__esModule) return mod;
1654
+ var result = {};
1655
+ if (mod != null) {
1656
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
1657
+ }
1658
+ __setModuleDefault(result, mod);
1659
+ return result;
1660
+ };
1661
+ })();
1662
+ var __importDefault = exports2 && exports2.__importDefault || function(mod) {
1663
+ return mod && mod.__esModule ? mod : { "default": mod };
1664
+ };
1837
1665
  Object.defineProperty(exports2, "__esModule", { value: true });
1838
- exports2.contextObjectMarker = void 0;
1839
- exports2.processIfWorkletContextObject = processIfWorkletContextObject;
1840
- exports2.isContextObject = isContextObject;
1666
+ exports2.buildWorkletString = buildWorkletString;
1667
+ var core_1 = require("@babel/core");
1668
+ var generator_1 = __importDefault(require("@babel/generator"));
1841
1669
  var types_12 = require("@babel/types");
1842
- exports2.contextObjectMarker = "__workletContextObject";
1843
- function processIfWorkletContextObject(path, _state) {
1844
- if (!isContextObject(path.node)) {
1845
- return false;
1670
+ var assert_1 = require("assert");
1671
+ var convertSourceMap = __importStar(require("convert-source-map"));
1672
+ var fs = __importStar(require("fs"));
1673
+ var transform_1 = require_transform();
1674
+ var types_2 = require_types();
1675
+ var utils_1 = require_utils();
1676
+ var MOCK_SOURCE_MAP = "mock source map";
1677
+ var querySuffixRE = /[?#].*$/;
1678
+ function buildWorkletString(fun, state, closureVariables, workletName, inputMap) {
1679
+ var _a;
1680
+ restoreRecursiveCalls(fun, workletName);
1681
+ const draftExpression = fun.program.body.find((obj) => (0, types_12.isFunctionDeclaration)(obj)) || fun.program.body.find((obj) => (0, types_12.isExpressionStatement)(obj));
1682
+ (0, assert_1.strict)(draftExpression, "`draftExpression` is undefined.");
1683
+ const expression = (0, types_12.isFunctionDeclaration)(draftExpression) ? draftExpression : draftExpression.expression;
1684
+ (0, assert_1.strict)("params" in expression, "'params' property is undefined in 'expression'");
1685
+ (0, assert_1.strict)((0, types_12.isBlockStatement)(expression.body), "`expression.body` is not a `BlockStatement`");
1686
+ const parsedClasses = /* @__PURE__ */ new Set();
1687
+ if (!state.opts.disableWorkletClasses) {
1688
+ (0, core_1.traverse)(fun, {
1689
+ NewExpression(path) {
1690
+ if (!(0, types_12.isIdentifier)(path.node.callee)) {
1691
+ return;
1692
+ }
1693
+ const constructorName = path.node.callee.name;
1694
+ if (!closureVariables.some((variable) => variable.name === constructorName) || parsedClasses.has(constructorName)) {
1695
+ return;
1696
+ }
1697
+ const index = closureVariables.findIndex((variable) => variable.name === constructorName);
1698
+ closureVariables.splice(index, 1);
1699
+ const workletClassFactoryName = constructorName + types_2.workletClassFactorySuffix;
1700
+ closureVariables.push((0, types_12.identifier)(workletClassFactoryName));
1701
+ (0, types_12.assertBlockStatement)(expression.body);
1702
+ expression.body.body.unshift((0, types_12.variableDeclaration)("const", [
1703
+ (0, types_12.variableDeclarator)((0, types_12.identifier)(constructorName), (0, types_12.callExpression)((0, types_12.identifier)(workletClassFactoryName), []))
1704
+ ]));
1705
+ parsedClasses.add(constructorName);
1706
+ }
1707
+ });
1846
1708
  }
1847
- removeContextObjectMarker(path.node);
1848
- processWorkletContextObject(path.node);
1849
- return true;
1709
+ const workletFunction = (0, types_12.functionExpression)((0, types_12.identifier)(workletName), expression.params, expression.body, expression.generator, expression.async);
1710
+ (0, core_1.traverse)(fun, {
1711
+ Directive(path) {
1712
+ path.remove();
1713
+ }
1714
+ });
1715
+ const code = (0, generator_1.default)(workletFunction).code;
1716
+ (0, assert_1.strict)(inputMap, "`inputMap` is undefined.");
1717
+ const includeSourceMap = !((0, utils_1.isRelease)(state) || state.opts.disableSourceMaps);
1718
+ if (includeSourceMap) {
1719
+ inputMap.sourcesContent = [];
1720
+ for (const sourceFile of inputMap.sources) {
1721
+ inputMap.sourcesContent.push(fs.readFileSync(sourceFile.replace(querySuffixRE, "")).toString("utf-8"));
1722
+ }
1723
+ }
1724
+ const transformed = (0, transform_1.workletTransformSync)(code, {
1725
+ filename: state.file.opts.filename,
1726
+ extraPlugins: [
1727
+ getClosurePlugin(closureVariables),
1728
+ ...(_a = state.opts.extraPlugins) !== null && _a !== void 0 ? _a : []
1729
+ ],
1730
+ extraPresets: state.opts.extraPresets,
1731
+ compact: true,
1732
+ sourceMaps: includeSourceMap,
1733
+ inputSourceMap: inputMap,
1734
+ ast: false,
1735
+ babelrc: false,
1736
+ configFile: false,
1737
+ comments: false
1738
+ });
1739
+ (0, assert_1.strict)(transformed, "`transformed` is null.");
1740
+ let sourceMap;
1741
+ if (includeSourceMap) {
1742
+ if (shouldMockSourceMap()) {
1743
+ sourceMap = MOCK_SOURCE_MAP;
1744
+ } else {
1745
+ sourceMap = convertSourceMap.fromObject(transformed.map).toObject();
1746
+ delete sourceMap.sourcesContent;
1747
+ }
1748
+ }
1749
+ const wrappedCode = `(${transformed.code})`;
1750
+ return [wrappedCode, JSON.stringify(sourceMap)];
1751
+ }
1752
+ function restoreRecursiveCalls(file, newName) {
1753
+ (0, core_1.traverse)(file, {
1754
+ FunctionExpression(path) {
1755
+ if (!path.node.id) {
1756
+ path.stop();
1757
+ return;
1758
+ }
1759
+ const oldName = path.node.id.name;
1760
+ const scope = path.scope;
1761
+ scope.rename(oldName, newName);
1762
+ }
1763
+ });
1850
1764
  }
1851
- function isContextObject(objectExpression) {
1852
- return objectExpression.properties.some((property) => (0, types_12.isObjectProperty)(property) && (0, types_12.isIdentifier)(property.key) && property.key.name === exports2.contextObjectMarker);
1765
+ function shouldMockSourceMap() {
1766
+ return process.env.WORKLETS_JEST_SHOULD_MOCK_SOURCE_MAP === "1";
1853
1767
  }
1854
- function processWorkletContextObject(objectExpression) {
1855
- const workletObjectFactory = (0, types_12.functionExpression)(null, [], (0, types_12.blockStatement)([(0, types_12.returnStatement)((0, types_12.cloneNode)(objectExpression))], [(0, types_12.directive)((0, types_12.directiveLiteral)("worklet"))]));
1856
- objectExpression.properties.push((0, types_12.objectProperty)((0, types_12.identifier)(`${exports2.contextObjectMarker}Factory`), workletObjectFactory));
1768
+ function prependClosure(path, closureVariables, closureDeclaration) {
1769
+ if (closureVariables.length === 0 || !(0, types_12.isProgram)(path.parent)) {
1770
+ return;
1771
+ }
1772
+ if (!(0, types_12.isExpression)(path.node.body)) {
1773
+ path.node.body.body.unshift(closureDeclaration);
1774
+ }
1857
1775
  }
1858
- function removeContextObjectMarker(objectExpression) {
1859
- objectExpression.properties = objectExpression.properties.filter((property) => !((0, types_12.isObjectProperty)(property) && (0, types_12.isIdentifier)(property.key) && property.key.name === exports2.contextObjectMarker));
1776
+ function prependRecursiveDeclaration(path) {
1777
+ var _a;
1778
+ if ((0, types_12.isProgram)(path.parent) && !(0, types_12.isArrowFunctionExpression)(path.node) && !(0, types_12.isObjectMethod)(path.node) && path.node.id && path.scope.parent) {
1779
+ const hasRecursiveCalls = ((_a = path.scope.parent.bindings[path.node.id.name]) === null || _a === void 0 ? void 0 : _a.references) > 0;
1780
+ if (hasRecursiveCalls) {
1781
+ path.node.body.body.unshift((0, types_12.variableDeclaration)("const", [
1782
+ (0, types_12.variableDeclarator)((0, types_12.identifier)(path.node.id.name), (0, types_12.memberExpression)((0, types_12.thisExpression)(), (0, types_12.identifier)("_recur")))
1783
+ ]));
1784
+ }
1785
+ }
1786
+ }
1787
+ function getClosurePlugin(closureVariables) {
1788
+ const closureDeclaration = (0, types_12.variableDeclaration)("const", [
1789
+ (0, types_12.variableDeclarator)((0, types_12.objectPattern)(closureVariables.map((variable) => (0, types_12.objectProperty)((0, types_12.identifier)(variable.name), (0, types_12.identifier)(variable.name), false, true))), (0, types_12.memberExpression)((0, types_12.thisExpression)(), (0, types_12.identifier)("__closure")))
1790
+ ]);
1791
+ return {
1792
+ visitor: {
1793
+ "FunctionDeclaration|FunctionExpression|ArrowFunctionExpression|ObjectMethod": (path) => {
1794
+ prependClosure(path, closureVariables, closureDeclaration);
1795
+ prependRecursiveDeclaration(path);
1796
+ }
1797
+ }
1798
+ };
1860
1799
  }
1861
1800
  }
1862
1801
  });
1863
1802
 
1864
- // lib/file.js
1865
- var require_file = __commonJS({
1866
- "lib/file.js"(exports2) {
1803
+ // lib/workletFactory.js
1804
+ var require_workletFactory = __commonJS({
1805
+ "lib/workletFactory.js"(exports2) {
1867
1806
  "use strict";
1807
+ var __importDefault = exports2 && exports2.__importDefault || function(mod) {
1808
+ return mod && mod.__esModule ? mod : { "default": mod };
1809
+ };
1868
1810
  Object.defineProperty(exports2, "__esModule", { value: true });
1869
- exports2.processIfWorkletFile = processIfWorkletFile;
1870
- exports2.isImplicitContextObject = isImplicitContextObject;
1811
+ exports2.makeWorkletFactory = makeWorkletFactory;
1812
+ var generator_1 = __importDefault(require("@babel/generator"));
1871
1813
  var types_12 = require("@babel/types");
1872
- var contextObject_12 = require_contextObject();
1814
+ var assert_1 = require("assert");
1815
+ var path_1 = require("path");
1816
+ var closure_1 = require_closure();
1817
+ var generate_1 = require_generate();
1818
+ var hermesBytecode_1 = require_hermesBytecode();
1819
+ var imports_1 = require_imports();
1820
+ var transform_1 = require_transform();
1873
1821
  var types_2 = require_types();
1874
- function processIfWorkletFile(path, state) {
1875
- if (!path.node.directives.some((functionDirective) => functionDirective.value.value === "worklet")) {
1876
- return false;
1877
- }
1878
- path.node.directives = path.node.directives.filter((functionDirective) => functionDirective.value.value !== "worklet");
1879
- processWorkletFile(path, state);
1880
- return true;
1881
- }
1882
- function processWorkletFile(programPath, state) {
1883
- const statements = programPath.get("body");
1884
- dehoistCommonJSExports(programPath.node);
1885
- statements.forEach((statement) => {
1886
- const candidatePath = getCandidate(statement);
1887
- processWorkletizableEntity(candidatePath, state);
1822
+ var utils_1 = require_utils();
1823
+ var workletStringCode_1 = require_workletStringCode();
1824
+ var REAL_VERSION = require("../package.json").version;
1825
+ var MOCK_VERSION = "x.y.z";
1826
+ function makeWorkletFactory(fun, state) {
1827
+ var _a;
1828
+ const includeClosure = state.opts.bundleMode || !hasDirective(fun, "no-worklet-closure");
1829
+ const limitInitDataHoisting = hasDirective(fun, "limit-init-data-hoisting");
1830
+ stripWorkletDirectives(fun);
1831
+ (0, assert_1.strict)(state.file.opts.filename, "`state.file.opts.filename` is undefined.");
1832
+ const codeObject = (0, generator_1.default)(fun.node, {
1833
+ sourceMaps: true,
1834
+ sourceFileName: state.file.opts.filename
1888
1835
  });
1889
- }
1890
- function getCandidate(statementPath) {
1891
- if (statementPath.isExportNamedDeclaration() || statementPath.isExportDefaultDeclaration()) {
1892
- return statementPath.get("declaration");
1836
+ codeObject.code = "(" + (fun.isObjectMethod() ? "function " : "") + codeObject.code + "\n)";
1837
+ const transformed = (0, transform_1.workletTransformSync)(codeObject.code, {
1838
+ extraPlugins: [...extraPlugins, ...(_a = state.opts.extraPlugins) !== null && _a !== void 0 ? _a : []],
1839
+ extraPresets: state.opts.extraPresets,
1840
+ filename: state.file.opts.filename,
1841
+ ast: true,
1842
+ babelrc: false,
1843
+ configFile: false,
1844
+ inputSourceMap: codeObject.map
1845
+ });
1846
+ (0, assert_1.strict)(transformed, "`transformed` is undefined.");
1847
+ (0, assert_1.strict)(transformed.ast, "`transformed.ast` is undefined.");
1848
+ const { closureVariables, moduleBindingsToImport, relativeBindingsToImport } = includeClosure ? (0, closure_1.getClosure)(fun, state) : {
1849
+ closureVariables: [],
1850
+ moduleBindingsToImport: /* @__PURE__ */ new Set(),
1851
+ relativeBindingsToImport: /* @__PURE__ */ new Set()
1852
+ };
1853
+ const clone = (0, types_12.cloneNode)(fun.node);
1854
+ const funExpression = (0, types_12.isBlockStatement)(clone.body) ? (0, types_12.functionExpression)(null, clone.params, clone.body, clone.generator, clone.async) : clone;
1855
+ const { workletName, reactName } = makeWorkletName(fun, state);
1856
+ let mutatedClosureVariables;
1857
+ if (state.opts.bundleMode) {
1858
+ mutatedClosureVariables = closureVariables.map((variable) => (0, types_12.cloneNode)(variable, true));
1893
1859
  } else {
1894
- return statementPath;
1860
+ mutatedClosureVariables = closureVariables;
1895
1861
  }
1896
- }
1897
- function processWorkletizableEntity(nodePath, state) {
1898
- var _a;
1899
- if ((0, types_2.isWorkletizableFunctionPath)(nodePath)) {
1900
- if (nodePath.isArrowFunctionExpression()) {
1901
- replaceImplicitReturnWithBlock(nodePath.node);
1862
+ let [funString, sourceMapString] = (0, workletStringCode_1.buildWorkletString)(transformed.ast, state, mutatedClosureVariables, workletName, transformed.map);
1863
+ (0, assert_1.strict)(funString, "`funString` is undefined.");
1864
+ const workletHash = hash(funString);
1865
+ let lineOffset = 1;
1866
+ if (closureVariables.length > 0) {
1867
+ lineOffset -= closureVariables.length + 2;
1868
+ }
1869
+ const pathForStringDefinitions = fun.parentPath.isProgram() ? fun : fun.findParent((path) => {
1870
+ var _a2, _b;
1871
+ return (_b = (_a2 = path.parentPath) === null || _a2 === void 0 ? void 0 : _a2.isProgram()) !== null && _b !== void 0 ? _b : false;
1872
+ });
1873
+ (0, assert_1.strict)(pathForStringDefinitions, "`pathForStringDefinitions` is null.");
1874
+ (0, assert_1.strict)(pathForStringDefinitions.parentPath, "`pathForStringDefinitions.parentPath` is null.");
1875
+ const initDataId = pathForStringDefinitions.parentPath.scope.generateUidIdentifier(`worklet_${workletHash}_init_data`);
1876
+ const shouldIncludeInitData = !state.opts.omitNativeOnlyData && !state.opts.bundleMode;
1877
+ const shouldEmitBytecode = !!state.opts.hermesBytecode && (0, utils_1.isRelease)(state) && shouldIncludeInitData;
1878
+ const bytecode = shouldEmitBytecode ? (0, hermesBytecode_1.compileWorkletToHbc)(funString, workletHash, state) : null;
1879
+ const initDataObjectExpression = (0, types_12.objectExpression)(bytecode ? [
1880
+ (0, types_12.objectProperty)((0, types_12.identifier)("bytecode"), (0, types_12.memberExpression)((0, types_12.newExpression)((0, types_12.identifier)("Uint8Array"), [
1881
+ (0, types_12.arrayExpression)(Array.from(bytecode, (byte) => (0, types_12.numericLiteral)(byte)))
1882
+ ]), (0, types_12.identifier)("buffer")))
1883
+ ] : [(0, types_12.objectProperty)((0, types_12.identifier)("code"), (0, types_12.stringLiteral)(funString))]);
1884
+ const shouldInjectLocation = !(0, utils_1.isRelease)(state);
1885
+ if (shouldInjectLocation) {
1886
+ let location = state.file.opts.filename;
1887
+ if (state.opts.relativeSourceLocation) {
1888
+ location = (0, path_1.relative)(state.cwd, location);
1889
+ sourceMapString = sourceMapString === null || sourceMapString === void 0 ? void 0 : sourceMapString.replace(toPosix(state.file.opts.filename), toPosix(location));
1902
1890
  }
1903
- appendWorkletDirective(nodePath.node.body);
1904
- } else if ((0, types_2.isWorkletizableObjectPath)(nodePath)) {
1905
- if (isImplicitContextObject(nodePath)) {
1906
- appendWorkletContextObjectMarker(nodePath.node);
1891
+ location = toPosix(location);
1892
+ initDataObjectExpression.properties.push((0, types_12.objectProperty)((0, types_12.identifier)("location"), (0, types_12.stringLiteral)(location)));
1893
+ }
1894
+ if (!bytecode && sourceMapString) {
1895
+ initDataObjectExpression.properties.push((0, types_12.objectProperty)((0, types_12.identifier)("sourceMap"), (0, types_12.stringLiteral)(sourceMapString)));
1896
+ }
1897
+ if (shouldIncludeInitData) {
1898
+ const initDataDeclaration = (0, types_12.variableDeclaration)("const", [
1899
+ (0, types_12.variableDeclarator)(initDataId, initDataObjectExpression)
1900
+ ]);
1901
+ if (limitInitDataHoisting) {
1902
+ fun.getFunctionParent().node.body.body.unshift(initDataDeclaration);
1907
1903
  } else {
1908
- processWorkletAggregator(nodePath, state);
1909
- }
1910
- } else if (nodePath.isVariableDeclaration()) {
1911
- processVariableDeclaration(nodePath, state);
1912
- } else if (nodePath.isClassDeclaration()) {
1913
- appendWorkletClassMarker(nodePath.node.body);
1914
- if ((_a = nodePath.node.id) === null || _a === void 0 ? void 0 : _a.name) {
1915
- state.classesToWorkletize.push({
1916
- node: nodePath.node,
1917
- name: nodePath.node.id.name
1918
- });
1904
+ pathForStringDefinitions.insertBefore(initDataDeclaration);
1919
1905
  }
1920
1906
  }
1921
- }
1922
- function processVariableDeclaration(variableDeclarationPath, state) {
1923
- const declarations = variableDeclarationPath.get("declarations");
1924
- declarations.forEach((declaration) => {
1925
- const initPath = declaration.get("init");
1926
- if (initPath.isExpression()) {
1927
- processWorkletizableEntity(initPath, state);
1928
- }
1929
- });
1930
- }
1931
- function processWorkletAggregator(objectPath, state) {
1932
- const properties = objectPath.get("properties");
1933
- properties.forEach((property) => {
1934
- if (property.isObjectMethod()) {
1935
- appendWorkletDirective(property.node.body);
1936
- } else if (property.isObjectProperty()) {
1937
- const valuePath = property.get("value");
1938
- processWorkletizableEntity(valuePath, state);
1907
+ (0, assert_1.strict)(!(0, types_12.isFunctionDeclaration)(funExpression), "`funExpression` is a `FunctionDeclaration`.");
1908
+ (0, assert_1.strict)(!(0, types_12.isObjectMethod)(funExpression), "`funExpression` is an `ObjectMethod`.");
1909
+ const statements = [
1910
+ (0, types_12.variableDeclaration)("const", [
1911
+ (0, types_12.variableDeclarator)((0, types_12.identifier)(reactName), funExpression)
1912
+ ]),
1913
+ (0, types_12.expressionStatement)((0, types_12.assignmentExpression)("=", (0, types_12.memberExpression)((0, types_12.identifier)(reactName), (0, types_12.identifier)("__closure"), false), (0, types_12.objectExpression)(closureVariables.map((variable) => !state.opts.bundleMode && variable.name.endsWith(types_2.workletClassFactorySuffix) ? (0, types_12.objectProperty)((0, types_12.identifier)(variable.name), (0, types_12.memberExpression)((0, types_12.identifier)(variable.name.slice(0, variable.name.length - types_2.workletClassFactorySuffix.length)), (0, types_12.identifier)(variable.name))) : (0, types_12.objectProperty)((0, types_12.cloneNode)(variable, true), (0, types_12.cloneNode)(variable, true), false, true))))),
1914
+ (0, types_12.expressionStatement)((0, types_12.assignmentExpression)("=", (0, types_12.memberExpression)((0, types_12.identifier)(reactName), (0, types_12.identifier)("__workletHash"), false), (0, types_12.numericLiteral)(workletHash)))
1915
+ ];
1916
+ const shouldInjectVersion = !(0, utils_1.isRelease)(state);
1917
+ if (shouldInjectVersion) {
1918
+ statements.push((0, types_12.expressionStatement)((0, types_12.assignmentExpression)("=", (0, types_12.memberExpression)((0, types_12.identifier)(reactName), (0, types_12.identifier)("__pluginVersion")), (0, types_12.stringLiteral)(shouldMockVersion() ? MOCK_VERSION : REAL_VERSION))));
1919
+ }
1920
+ if (shouldIncludeInitData) {
1921
+ statements.push((0, types_12.expressionStatement)((0, types_12.assignmentExpression)("=", (0, types_12.memberExpression)((0, types_12.identifier)(reactName), (0, types_12.identifier)("__initData"), false), (0, types_12.cloneNode)(initDataId, true))));
1922
+ }
1923
+ if (!(0, utils_1.isRelease)(state) && !state.opts.bundleMode) {
1924
+ statements.unshift((0, types_12.variableDeclaration)("const", [
1925
+ (0, types_12.variableDeclarator)((0, types_12.identifier)("_e"), (0, types_12.arrayExpression)([
1926
+ (0, types_12.newExpression)((0, types_12.memberExpression)((0, types_12.identifier)("global"), (0, types_12.identifier)("Error")), []),
1927
+ (0, types_12.numericLiteral)(lineOffset),
1928
+ (0, types_12.numericLiteral)(-27)
1929
+ // the placement of opening bracket after Exception in line that defined '_e' variable
1930
+ ]))
1931
+ ]));
1932
+ statements.push((0, types_12.expressionStatement)((0, types_12.assignmentExpression)("=", (0, types_12.memberExpression)((0, types_12.identifier)(reactName), (0, types_12.identifier)("__stackDetails"), false), (0, types_12.identifier)("_e"))));
1933
+ }
1934
+ statements.push((0, types_12.returnStatement)((0, types_12.identifier)(reactName)));
1935
+ const factoryParams = closureVariables.map((variableId) => {
1936
+ const clonedId = (0, types_12.cloneNode)(variableId, true);
1937
+ if (!state.opts.bundleMode && clonedId.name.endsWith(types_2.workletClassFactorySuffix)) {
1938
+ clonedId.name = clonedId.name.slice(0, clonedId.name.length - types_2.workletClassFactorySuffix.length);
1939
1939
  }
1940
+ return clonedId;
1940
1941
  });
1941
- }
1942
- function replaceImplicitReturnWithBlock(path) {
1943
- if (!(0, types_12.isBlockStatement)(path.body)) {
1944
- path.body = (0, types_12.blockStatement)([(0, types_12.returnStatement)(path.body)]);
1942
+ if (shouldIncludeInitData) {
1943
+ factoryParams.unshift((0, types_12.cloneNode)(initDataId, true));
1945
1944
  }
1946
- }
1947
- function appendWorkletDirective(node) {
1948
- if (!node.directives.some((functionDirective) => functionDirective.value.value === "worklet")) {
1949
- node.directives.push((0, types_12.directive)((0, types_12.directiveLiteral)("worklet")));
1945
+ const factoryParamObjectPattern = (0, types_12.objectPattern)(factoryParams.map((param) => (0, types_12.objectProperty)((0, types_12.cloneNode)(param, true), (0, types_12.cloneNode)(param, true), false, true)));
1946
+ const factory = (0, types_12.functionExpression)((0, types_12.identifier)(workletName + "Factory"), [factoryParamObjectPattern], (0, types_12.blockStatement)(statements));
1947
+ const factoryCallArgs = factoryParams.map((param) => (0, types_12.cloneNode)(param, true));
1948
+ const factoryCallParamPack = (0, types_12.objectExpression)(factoryCallArgs.map((param) => (0, types_12.objectProperty)((0, types_12.cloneNode)(param, true), (0, types_12.cloneNode)(param, true), false, true)));
1949
+ if (state.opts.bundleMode) {
1950
+ (0, imports_1.updateRelativeRequires)(factory, state);
1951
+ (0, generate_1.generateWorkletFile)(moduleBindingsToImport, relativeBindingsToImport, factory, workletHash, state);
1950
1952
  }
1953
+ factory.workletized = true;
1954
+ return { factory, factoryCallParamPack, workletHash };
1951
1955
  }
1952
- function appendWorkletContextObjectMarker(objectExpression) {
1953
- if (objectExpression.properties.some((value) => (0, types_12.isObjectProperty)(value) && (0, types_12.isIdentifier)(value.key) && value.key.name === contextObject_12.contextObjectMarker)) {
1954
- return;
1956
+ function hasDirective(path, directiveText) {
1957
+ if (!path.node.body) {
1958
+ return false;
1959
+ }
1960
+ const bodyPath = path.get("body");
1961
+ let has = false;
1962
+ if (bodyPath.isBlockStatement()) {
1963
+ has = bodyPath.get("directives").some((directivePath) => {
1964
+ if (directivePath.isDirective() && directivePath.node.value.value === directiveText) {
1965
+ return true;
1966
+ }
1967
+ });
1955
1968
  }
1956
- objectExpression.properties.push((0, types_12.objectProperty)((0, types_12.identifier)(`${contextObject_12.contextObjectMarker}`), (0, types_12.booleanLiteral)(true)));
1969
+ return has;
1957
1970
  }
1958
- function isImplicitContextObject(path) {
1959
- const propertyPaths = path.get("properties");
1960
- return propertyPaths.some((propertyPath) => {
1961
- if (!propertyPath.isObjectMethod()) {
1962
- return false;
1971
+ function stripWorkletDirectives(fun) {
1972
+ fun.traverse({
1973
+ DirectiveLiteral(nodePath) {
1974
+ if ((nodePath.node.value === "worklet" || nodePath.node.value === "no-worklet-closure" || nodePath.node.value === "limit-init-data-hoisting") && nodePath.getFunctionParent() === fun) {
1975
+ nodePath.parentPath.remove();
1976
+ }
1963
1977
  }
1964
- return hasThisExpression(propertyPath);
1965
1978
  });
1966
1979
  }
1967
- function hasThisExpression(path) {
1968
- let result = false;
1969
- path.traverse({
1970
- ThisExpression(thisPath) {
1971
- result = true;
1972
- thisPath.stop();
1973
- }
1974
- });
1975
- return result;
1980
+ function shouldMockVersion() {
1981
+ return process.env.WORKLETS_JEST_SHOULD_MOCK_VERSION === "1";
1976
1982
  }
1977
- function appendWorkletClassMarker(classBody) {
1978
- classBody.body.push((0, types_12.classProperty)((0, types_12.identifier)("__workletClass"), (0, types_12.booleanLiteral)(true)));
1983
+ function hash(str) {
1984
+ let i = str.length;
1985
+ let hash1 = 5381;
1986
+ let hash2 = 52711;
1987
+ while (i--) {
1988
+ const char = str.charCodeAt(i);
1989
+ hash1 = hash1 * 33 ^ char;
1990
+ hash2 = hash2 * 33 ^ char;
1991
+ }
1992
+ return (hash1 >>> 0) * 4096 + (hash2 >>> 0);
1979
1993
  }
1980
- function dehoistCommonJSExports(program) {
1981
- const statements = program.body;
1982
- let end = statements.length;
1983
- let current = 0;
1984
- while (current < end) {
1985
- const statement = statements[current];
1986
- if (!isCommonJSExport(statement)) {
1987
- current++;
1988
- continue;
1994
+ function makeWorkletName(fun, state) {
1995
+ let source = "unknownFile";
1996
+ if (state.file.opts.filename) {
1997
+ const filepath = state.file.opts.filename;
1998
+ source = (0, path_1.basename)(filepath);
1999
+ const splitFilepath = filepath.split(/[\\/]/);
2000
+ const nodeModulesIndex = splitFilepath.indexOf("node_modules");
2001
+ if (nodeModulesIndex !== -1) {
2002
+ const libraryName = splitFilepath[nodeModulesIndex + 1];
2003
+ source = `${libraryName}_${source}`;
1989
2004
  }
1990
- const exportStatement = statements.splice(current, 1);
1991
- statements.push(...exportStatement);
1992
- end--;
1993
2005
  }
2006
+ const suffix = `${source}${state.workletNumber++}`;
2007
+ let reactName = "";
2008
+ if ((0, types_12.isObjectMethod)(fun.node) && (0, types_12.isIdentifier)(fun.node.key)) {
2009
+ reactName = fun.node.key.name;
2010
+ } else if (((0, types_12.isFunctionDeclaration)(fun.node) || (0, types_12.isFunctionExpression)(fun.node)) && (0, types_12.isIdentifier)(fun.node.id)) {
2011
+ reactName = fun.node.id.name;
2012
+ }
2013
+ const workletName = reactName ? (0, types_12.toIdentifier)(`${reactName}_${suffix}`) : (0, types_12.toIdentifier)(suffix);
2014
+ reactName = reactName || (0, types_12.toIdentifier)(suffix);
2015
+ return { workletName, reactName };
1994
2016
  }
1995
- function isCommonJSExport(statement) {
1996
- return (0, types_12.isExpressionStatement)(statement) && (0, types_12.isAssignmentExpression)(statement.expression) && (0, types_12.isMemberExpression)(statement.expression.left) && (0, types_12.isIdentifier)(statement.expression.left.object) && statement.expression.left.object.name === "exports";
2017
+ function toPosix(p) {
2018
+ return path_1.sep === "/" ? p : p.split(path_1.sep).join("/");
1997
2019
  }
2020
+ var extraPlugins = [
2021
+ require.resolve("@babel/plugin-transform-shorthand-properties"),
2022
+ require.resolve("@babel/plugin-transform-arrow-functions"),
2023
+ require.resolve("@babel/plugin-transform-optional-chaining"),
2024
+ require.resolve("@babel/plugin-transform-nullish-coalescing-operator"),
2025
+ [
2026
+ require.resolve("@babel/plugin-transform-template-literals"),
2027
+ { loose: true }
2028
+ ]
2029
+ ];
1998
2030
  }
1999
2031
  });
2000
2032
 
2001
- // lib/inlineStylesWarning.js
2002
- var require_inlineStylesWarning = __commonJS({
2003
- "lib/inlineStylesWarning.js"(exports2) {
2033
+ // lib/workletFactoryCall.js
2034
+ var require_workletFactoryCall = __commonJS({
2035
+ "lib/workletFactoryCall.js"(exports2) {
2004
2036
  "use strict";
2005
2037
  Object.defineProperty(exports2, "__esModule", { value: true });
2006
- exports2.processInlineStylesWarning = processInlineStylesWarning;
2038
+ exports2.makeWorkletFactoryCall = makeWorkletFactoryCall;
2007
2039
  var types_12 = require("@babel/types");
2008
- var assert_1 = require("assert");
2009
- var utils_1 = require_utils();
2010
- function generateInlineStylesWarning(path) {
2011
- return (0, types_12.callExpression)((0, types_12.arrowFunctionExpression)([], (0, types_12.blockStatement)([
2012
- (0, types_12.expressionStatement)((0, types_12.callExpression)((0, types_12.memberExpression)((0, types_12.identifier)("console"), (0, types_12.identifier)("warn")), [
2013
- (0, types_12.callExpression)((0, types_12.memberExpression)((0, types_12.callExpression)((0, types_12.identifier)("require"), [
2014
- (0, types_12.stringLiteral)("react-native-reanimated")
2015
- ]), (0, types_12.identifier)("getUseOfValueInStyleWarning")), [])
2016
- ])),
2017
- (0, types_12.returnStatement)(path.node)
2018
- ])), []);
2019
- }
2020
- function processPropertyValueForInlineStylesWarning(path) {
2021
- if (path.isMemberExpression() && (0, types_12.isIdentifier)(path.node.property)) {
2022
- if (!path.node.computed && path.node.property.name === "value") {
2023
- path.replaceWith(generateInlineStylesWarning(path));
2024
- }
2025
- }
2026
- }
2027
- function processTransformPropertyForInlineStylesWarning(path) {
2028
- if ((0, types_12.isArrayExpression)(path.node)) {
2029
- const elements = path.get("elements");
2030
- (0, assert_1.strict)(Array.isArray(elements), "`elements` should be an array.");
2031
- for (const element of elements) {
2032
- if (element.isObjectExpression()) {
2033
- processStyleObjectForInlineStylesWarning(element);
2034
- }
2035
- }
2036
- }
2037
- }
2038
- function processStyleObjectForInlineStylesWarning(path) {
2039
- const properties = path.get("properties");
2040
- for (const property of properties) {
2041
- if (property.isObjectProperty()) {
2042
- const value = property.get("value");
2043
- if ((0, types_12.isIdentifier)(property.node.key) && property.node.key.name === "transform") {
2044
- processTransformPropertyForInlineStylesWarning(value);
2045
- } else {
2046
- processPropertyValueForInlineStylesWarning(value);
2047
- }
2048
- }
2040
+ var types_2 = require_types();
2041
+ var workletFactory_1 = require_workletFactory();
2042
+ function makeWorkletFactoryCall(path, state) {
2043
+ const { factory, factoryCallParamPack, workletHash } = (0, workletFactory_1.makeWorkletFactory)(path, state);
2044
+ let factoryCall;
2045
+ if (state.opts.bundleMode) {
2046
+ factoryCall = (0, types_12.callExpression)((0, types_12.memberExpression)((0, types_12.callExpression)((0, types_12.identifier)("require"), [
2047
+ (0, types_12.stringLiteral)(`react-native-worklets/${types_2.generatedWorkletsDir}/${workletHash}.js`)
2048
+ ]), (0, types_12.identifier)("default")), [factoryCallParamPack]);
2049
+ } else {
2050
+ factoryCall = (0, types_12.callExpression)(factory, [factoryCallParamPack]);
2049
2051
  }
2052
+ addStackTraceDataToWorkletFactory(path, factoryCall);
2053
+ const replacement = factoryCall;
2054
+ return replacement;
2050
2055
  }
2051
- function processInlineStylesWarning(path, state) {
2052
- if ((0, utils_1.isRelease)(state)) {
2053
- return;
2054
- }
2055
- if (state.opts.disableInlineStylesWarning) {
2056
- return;
2057
- }
2058
- if (path.node.name.name !== "style") {
2059
- return;
2060
- }
2061
- if (!(0, types_12.isJSXExpressionContainer)(path.node.value)) {
2062
- return;
2063
- }
2064
- const expression = path.get("value").get("expression");
2065
- (0, assert_1.strict)(!Array.isArray(expression), "`expression` should not be an array.");
2066
- if (expression.isArrayExpression()) {
2067
- const elements = expression.get("elements");
2068
- (0, assert_1.strict)(Array.isArray(elements), "`elements` should be an array.");
2069
- for (const element of elements) {
2070
- if (element.isObjectExpression()) {
2071
- processStyleObjectForInlineStylesWarning(element);
2072
- }
2073
- }
2074
- } else if (expression.isObjectExpression()) {
2075
- processStyleObjectForInlineStylesWarning(expression);
2056
+ function addStackTraceDataToWorkletFactory(path, workletFactoryCall) {
2057
+ const originalWorkletLocation = path.node.loc;
2058
+ if (originalWorkletLocation) {
2059
+ workletFactoryCall.callee.loc = {
2060
+ filename: originalWorkletLocation.filename,
2061
+ identifierName: originalWorkletLocation.identifierName,
2062
+ start: originalWorkletLocation.start,
2063
+ end: originalWorkletLocation.start
2064
+ };
2076
2065
  }
2077
2066
  }
2078
2067
  }
2079
2068
  });
2080
2069
 
2081
- // lib/webOptimization.js
2082
- var require_webOptimization = __commonJS({
2083
- "lib/webOptimization.js"(exports2) {
2070
+ // lib/workletSubstitution.js
2071
+ var require_workletSubstitution = __commonJS({
2072
+ "lib/workletSubstitution.js"(exports2) {
2084
2073
  "use strict";
2085
2074
  Object.defineProperty(exports2, "__esModule", { value: true });
2086
- exports2.substituteWebCallExpression = substituteWebCallExpression;
2075
+ exports2.processIfWithWorkletDirective = processIfWithWorkletDirective;
2076
+ exports2.processWorklet = processWorklet;
2077
+ exports2.substituteObjectMethodWithObjectProperty = substituteObjectMethodWithObjectProperty;
2087
2078
  var types_12 = require("@babel/types");
2088
- function substituteWebCallExpression(path) {
2089
- const callee = path.node.callee;
2090
- if ((0, types_12.isIdentifier)(callee)) {
2091
- const name = callee.name;
2092
- if (name === "isWeb" || name === "shouldBeUseWeb") {
2093
- path.replaceWith((0, types_12.booleanLiteral)(true));
2079
+ var types_2 = require_types();
2080
+ var utils_1 = require_utils();
2081
+ var workletFactoryCall_1 = require_workletFactoryCall();
2082
+ function processIfWithWorkletDirective(path, state) {
2083
+ if (!(0, types_12.isBlockStatement)(path.node.body)) {
2084
+ return false;
2085
+ }
2086
+ if (!hasWorkletDirective(path.node.body.directives)) {
2087
+ return false;
2088
+ }
2089
+ processWorklet(path, state);
2090
+ return true;
2091
+ }
2092
+ function processWorklet(path, state) {
2093
+ path.traverse({
2094
+ // @ts-expect-error TypeScript doesn't like this syntax here.
2095
+ [types_2.WorkletizableFunction](subPath, passedState) {
2096
+ processIfWithWorkletDirective(subPath, passedState);
2094
2097
  }
2098
+ }, state);
2099
+ const workletFactoryCall = (0, workletFactoryCall_1.makeWorkletFactoryCall)(path, state);
2100
+ substituteWorkletWithWorkletFactoryCall(path, workletFactoryCall);
2101
+ path.scope.getProgramParent().crawl();
2102
+ }
2103
+ function hasWorkletDirective(directives) {
2104
+ return directives.some((directive) => (0, types_12.isDirectiveLiteral)(directive.value) && directive.value.value === "worklet");
2105
+ }
2106
+ function substituteWorkletWithWorkletFactoryCall(path, workletFactoryCall) {
2107
+ var _a;
2108
+ if (path.isObjectMethod()) {
2109
+ substituteObjectMethodWithObjectProperty(path, workletFactoryCall);
2110
+ } else {
2111
+ const name = "id" in path.node ? (_a = path.node.id) === null || _a === void 0 ? void 0 : _a.name : void 0;
2112
+ (0, utils_1.replaceWithFactoryCall)(path, name, workletFactoryCall);
2095
2113
  }
2096
2114
  }
2115
+ function substituteObjectMethodWithObjectProperty(path, workletFactoryCall) {
2116
+ const replacement = (0, types_12.objectProperty)(path.node.key, workletFactoryCall);
2117
+ path.replaceWith(replacement);
2118
+ }
2097
2119
  }
2098
2120
  });
2099
2121
 
2100
2122
  // lib/plugin.js
2101
2123
  Object.defineProperty(exports, "__esModule", { value: true });
2124
+ exports.getAutoworkletizationMicroPlugin = getAutoworkletizationMicroPlugin;
2102
2125
  var autoworkletization_1 = require_autoworkletization();
2103
2126
  var bundleMode_1 = require_bundleMode();
2104
2127
  var class_1 = require_class();
2128
+ var classMethod_1 = require_classMethod();
2105
2129
  var contextObject_1 = require_contextObject();
2130
+ var directives_1 = require_directives();
2106
2131
  var file_1 = require_file();
2107
2132
  var globals_1 = require_globals();
2108
2133
  var inlineStylesWarning_1 = require_inlineStylesWarning();
@@ -2128,13 +2153,13 @@ module.exports = function WorkletsBabelPlugin() {
2128
2153
  pre() {
2129
2154
  runWithTaggedExceptions(this, () => {
2130
2155
  (0, globals_1.initializeState)(this);
2156
+ this.file.path.traverse(getAutoworkletizationMicroPlugin(), this);
2131
2157
  });
2132
2158
  },
2133
2159
  visitor: {
2134
2160
  CallExpression: {
2135
2161
  enter(path, state) {
2136
2162
  runWithTaggedExceptions(state, () => {
2137
- (0, autoworkletization_1.processCalleesAutoworkletizableCallbacks)(path, state);
2138
2163
  if (state.opts.substituteWebPlatformChecks) {
2139
2164
  (0, webOptimization_1.substituteWebCallExpression)(path);
2140
2165
  }
@@ -2143,7 +2168,9 @@ module.exports = function WorkletsBabelPlugin() {
2143
2168
  },
2144
2169
  [types_1.WorkletizableFunction]: {
2145
2170
  enter(path, state) {
2146
- runWithTaggedExceptions(state, () => (0, workletSubstitution_1.processIfWithWorkletDirective)(path, state) || (0, autoworkletization_1.processIfAutoworkletizableCallback)(path, state));
2171
+ runWithTaggedExceptions(state, () => {
2172
+ (0, workletSubstitution_1.processIfWithWorkletDirective)(path, state);
2173
+ });
2147
2174
  }
2148
2175
  },
2149
2176
  ObjectExpression: {
@@ -2163,6 +2190,13 @@ module.exports = function WorkletsBabelPlugin() {
2163
2190
  });
2164
2191
  }
2165
2192
  },
2193
+ ClassMethod: {
2194
+ enter(path, state) {
2195
+ runWithTaggedExceptions(state, () => {
2196
+ (0, classMethod_1.processIfWorkletMethod)(path);
2197
+ });
2198
+ }
2199
+ },
2166
2200
  Program: {
2167
2201
  enter(path, state) {
2168
2202
  runWithTaggedExceptions(state, () => {
@@ -2185,4 +2219,23 @@ module.exports = function WorkletsBabelPlugin() {
2185
2219
  }
2186
2220
  };
2187
2221
  };
2222
+ function getAutoworkletizationMicroPlugin() {
2223
+ return {
2224
+ CallExpression: {
2225
+ enter(path, state) {
2226
+ (0, autoworkletization_1.handleWorkletizableCallback)(path, state);
2227
+ }
2228
+ },
2229
+ [types_1.WorkletizableFunction]: {
2230
+ enter(path) {
2231
+ (0, autoworkletization_1.addDirectivesToKnownCallback)(path);
2232
+ }
2233
+ },
2234
+ Directive: {
2235
+ enter(path) {
2236
+ (0, directives_1.handleWorkletDirective)(path);
2237
+ }
2238
+ }
2239
+ };
2240
+ }
2188
2241
  //# sourceMappingURL=index.js.map