@vxrn/compiler 2.13.3 → 2.13.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"scope.js","names":[],"sources":["esm/worklets/scope.js"],"sourcesContent":["function getClosureVariables(fnNode, globals) {\n const rootScope = {\n parent: null,\n isFunction: true,\n bindings: /* @__PURE__ */ new Set(),\n varBindings: /* @__PURE__ */ new Set()\n };\n let currentScope = rootScope;\n const freeVariables = /* @__PURE__ */ new Set();\n if (fnNode.id && fnNode.id.name) {\n rootScope.bindings.add(fnNode.id.name);\n }\n function pushScope(isFunction) {\n const newScope = {\n parent: currentScope,\n isFunction,\n bindings: /* @__PURE__ */ new Set(),\n varBindings: isFunction ? /* @__PURE__ */ new Set() : currentScope.varBindings\n };\n currentScope = newScope;\n return newScope;\n }\n function popScope() {\n if (currentScope.parent) {\n currentScope = currentScope.parent;\n }\n }\n function addBindings(pattern, targetSet) {\n if (!pattern) return;\n switch (pattern.type) {\n case \"Identifier\":\n targetSet.add(pattern.name);\n break;\n case \"AssignmentPattern\":\n addBindings(pattern.left, targetSet);\n walk(pattern.right);\n break;\n case \"RestElement\":\n addBindings(pattern.argument, targetSet);\n break;\n case \"ArrayPattern\":\n for (const el of pattern.elements) {\n if (el) addBindings(el, targetSet);\n }\n break;\n case \"ObjectPattern\":\n for (const prop of pattern.properties) {\n if (prop.type === \"Property\") {\n if (prop.computed) walk(prop.key);\n addBindings(prop.value, targetSet);\n } else if (prop.type === \"RestElement\") {\n addBindings(prop.argument, targetSet);\n }\n }\n break;\n }\n }\n function addBindingsOnly(pattern, targetSet) {\n if (!pattern) return;\n switch (pattern.type) {\n case \"Identifier\":\n targetSet.add(pattern.name);\n break;\n case \"AssignmentPattern\":\n addBindingsOnly(pattern.left, targetSet);\n break;\n case \"RestElement\":\n addBindingsOnly(pattern.argument, targetSet);\n break;\n case \"ArrayPattern\":\n for (const el of pattern.elements) {\n if (el) addBindingsOnly(el, targetSet);\n }\n break;\n case \"ObjectPattern\":\n for (const prop of pattern.properties) {\n if (prop.type === \"Property\") {\n addBindingsOnly(prop.value, targetSet);\n } else if (prop.type === \"RestElement\") {\n addBindingsOnly(prop.argument, targetSet);\n }\n }\n break;\n }\n }\n function hoistDeclarations(node, direct) {\n if (!node || typeof node !== \"object\" || typeof node.type !== \"string\") return;\n switch (node.type) {\n case \"FunctionDeclaration\":\n if (node.id?.name) {\n currentScope.bindings.add(node.id.name);\n currentScope.varBindings.add(node.id.name);\n }\n return;\n case \"FunctionExpression\":\n case \"ArrowFunctionExpression\":\n return;\n case \"ClassDeclaration\":\n if (direct && node.id?.name) currentScope.bindings.add(node.id.name);\n return;\n case \"VariableDeclaration\":\n if (node.kind === \"var\") {\n for (const d of node.declarations)\n addBindingsOnly(d.id, currentScope.varBindings);\n } else if (direct) {\n for (const d of node.declarations) addBindingsOnly(d.id, currentScope.bindings);\n }\n return;\n case \"ExportNamedDeclaration\":\n case \"ExportDefaultDeclaration\":\n hoistDeclarations(node.declaration, direct);\n return;\n }\n for (const key of Object.keys(node)) {\n if (key === \"start\" || key === \"end\" || key === \"loc\" || key === \"range\") continue;\n const child = node[key];\n if (Array.isArray(child)) {\n for (const item of child) hoistDeclarations(item, false);\n } else if (child && typeof child === \"object\") {\n hoistDeclarations(child, false);\n }\n }\n }\n if (fnNode.params) {\n for (const param of fnNode.params) {\n addBindings(param, rootScope.bindings);\n }\n }\n function isDeclaredInScopes(name, fromScope) {\n let s = fromScope;\n while (s) {\n if (s.bindings.has(name) || s.varBindings.has(name)) {\n return true;\n }\n s = s.parent;\n }\n return false;\n }\n function resolveIdentifier(name) {\n if (!isDeclaredInScopes(name, currentScope) && !globals.has(name)) {\n freeVariables.add(name);\n }\n }\n function walk(node) {\n if (!node || typeof node !== \"object\") return;\n if (node.type === \"TSTypeAnnotation\" || node.type === \"TSTypeReference\" || node.type === \"TSTypeAliasDeclaration\" || node.type === \"TSInterfaceDeclaration\" || node.type === \"TSTypeParameterDeclaration\" || node.type === \"TSTypeParameterInstantiation\" || node.type === \"TSTypeQuery\" || node.type === \"TSQualifiedName\") {\n return;\n }\n if (node.type === \"TSAsExpression\" || node.type === \"TSSatisfiesExpression\" || node.type === \"TSTypeAssertion\" || node.type === \"TSNonNullExpression\" || node.type === \"TSInstantiationExpression\") {\n walk(node.expression);\n return;\n }\n switch (node.type) {\n case \"BlockStatement\": {\n const isRootBody = node === fnNode.body;\n if (!isRootBody) {\n pushScope(false);\n }\n for (const stmt of node.body) {\n hoistDeclarations(stmt, true);\n }\n for (const stmt of node.body) {\n walk(stmt);\n }\n if (!isRootBody) {\n popScope();\n }\n return;\n }\n case \"VariableDeclaration\": {\n const isVar = node.kind === \"var\";\n const targetSet = isVar ? currentScope.varBindings : currentScope.bindings;\n for (const decl of node.declarations) {\n addBindings(decl.id, targetSet);\n if (decl.init) walk(decl.init);\n }\n return;\n }\n case \"FunctionDeclaration\":\n case \"FunctionExpression\": {\n if (node.id && node.id.name) {\n currentScope.bindings.add(node.id.name);\n }\n pushScope(true);\n if (node.params) {\n for (const param of node.params) {\n addBindings(param, currentScope.bindings);\n }\n }\n walk(node.body);\n popScope();\n return;\n }\n case \"ArrowFunctionExpression\": {\n pushScope(true);\n if (node.params) {\n for (const param of node.params) {\n addBindings(param, currentScope.bindings);\n }\n }\n walk(node.body);\n popScope();\n return;\n }\n case \"CatchClause\": {\n pushScope(false);\n if (node.param) {\n addBindings(node.param, currentScope.bindings);\n }\n walk(node.body);\n popScope();\n return;\n }\n case \"ForStatement\": {\n pushScope(false);\n if (node.init) walk(node.init);\n if (node.test) walk(node.test);\n if (node.update) walk(node.update);\n walk(node.body);\n popScope();\n return;\n }\n case \"ForInStatement\":\n case \"ForOfStatement\": {\n pushScope(false);\n walk(node.left);\n walk(node.right);\n walk(node.body);\n popScope();\n return;\n }\n case \"ClassDeclaration\":\n case \"ClassExpression\": {\n if (node.id && node.id.name) {\n currentScope.bindings.add(node.id.name);\n }\n if (node.superClass) walk(node.superClass);\n pushScope(false);\n walk(node.body);\n popScope();\n return;\n }\n case \"MemberExpression\": {\n walk(node.object);\n if (node.computed) {\n walk(node.property);\n }\n return;\n }\n case \"Property\": {\n if (node.computed) {\n walk(node.key);\n }\n walk(node.value);\n return;\n }\n case \"MethodDefinition\": {\n if (node.computed) {\n walk(node.key);\n }\n walk(node.value);\n return;\n }\n case \"Identifier\": {\n resolveIdentifier(node.name);\n return;\n }\n case \"JSXElement\": {\n if (node.openingElement) {\n const nameNode = node.openingElement.name;\n if (nameNode.type === \"JSXIdentifier\") {\n if (/^[A-Z]/.test(nameNode.name)) {\n resolveIdentifier(nameNode.name);\n }\n } else if (nameNode.type === \"JSXMemberExpression\") {\n let root = nameNode.object;\n while (root.type === \"JSXMemberExpression\") {\n root = root.object;\n }\n if (root.type === \"JSXIdentifier\") {\n resolveIdentifier(root.name);\n }\n }\n if (node.openingElement.attributes) {\n for (const attr of node.openingElement.attributes) {\n walk(attr);\n }\n }\n }\n if (node.children) {\n for (const child of node.children) {\n walk(child);\n }\n }\n return;\n }\n case \"JSXAttribute\": {\n if (node.value) {\n walk(node.value);\n }\n return;\n }\n case \"JSXExpressionContainer\": {\n walk(node.expression);\n return;\n }\n case \"BreakStatement\":\n case \"ContinueStatement\":\n case \"LabeledStatement\": {\n if (node.body) walk(node.body);\n return;\n }\n }\n for (const key of Object.keys(node)) {\n if (key === \"start\" || key === \"end\" || key === \"loc\" || key === \"range\") continue;\n const child = node[key];\n if (Array.isArray(child)) {\n for (const item of child) {\n walk(item);\n }\n } else if (child && typeof child === \"object\") {\n walk(child);\n }\n }\n }\n walk(fnNode.body);\n return Array.from(freeVariables).sort();\n}\nexport {\n getClosureVariables\n};\n//# sourceMappingURL=scope.js.map\n"],"mappings":";AAAA,SAAS,oBAAoB,QAAQ,SAAS;CAC5C,MAAM,YAAY;EAChB,QAAQ;EACR,YAAY;EACZ,0BAA0B,IAAI,IAAI;EAClC,6BAA6B,IAAI,IAAI;CACvC;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KAAK,IAAI;IAC7B;GACF;EACF;EACA,KAAK,MAAM,OAAO,OAAO,KAAK,IAAI,GAAG;GACnC,IAAI,QAAQ,WAAW,QAAQ,SAAS,QAAQ,SAAS,QAAQ,SAAS;GAC1E,MAAM,QAAQ,KAAK;GACnB,IAAI,MAAM,QAAQ,KAAK,GAAG;IACxB,KAAK,MAAM,QAAQ,OAAO;KACxB,KAAK,IAAI;IACX;GACF,OAAO,IAAI,SAAS,OAAO,UAAU,UAAU;IAC7C,KAAK,KAAK;GACZ;EACF;CACF;CACA,KAAK,OAAO,IAAI;CAChB,OAAO,MAAM,KAAK,aAAa,CAAC,CAAC,KAAK;AACxC"}
1
+ {"version":3,"file":"scope.js","names":[],"sources":["esm/worklets/scope.js"],"sourcesContent":["function getClosureVariables(fnNode, globals) {\n const rootScope = {\n parent: null,\n isFunction: true,\n bindings: /* @__PURE__ */ new Set(),\n varBindings: /* @__PURE__ */ new Set()\n };\n let currentScope = rootScope;\n const freeVariables = /* @__PURE__ */ new Set();\n if (fnNode.id && fnNode.id.name) {\n rootScope.bindings.add(fnNode.id.name);\n }\n function pushScope(isFunction) {\n const newScope = {\n parent: currentScope,\n isFunction,\n bindings: /* @__PURE__ */ new Set(),\n varBindings: isFunction ? /* @__PURE__ */ new Set() : currentScope.varBindings\n };\n currentScope = newScope;\n return newScope;\n }\n function popScope() {\n if (currentScope.parent) {\n currentScope = currentScope.parent;\n }\n }\n function addBindings(pattern, targetSet) {\n if (!pattern) return;\n switch (pattern.type) {\n case \"Identifier\":\n targetSet.add(pattern.name);\n break;\n case \"AssignmentPattern\":\n addBindings(pattern.left, targetSet);\n walk(pattern.right);\n break;\n case \"RestElement\":\n addBindings(pattern.argument, targetSet);\n break;\n case \"ArrayPattern\":\n for (const el of pattern.elements) {\n if (el) addBindings(el, targetSet);\n }\n break;\n case \"ObjectPattern\":\n for (const prop of pattern.properties) {\n if (prop.type === \"Property\") {\n if (prop.computed) walk(prop.key);\n addBindings(prop.value, targetSet);\n } else if (prop.type === \"RestElement\") {\n addBindings(prop.argument, targetSet);\n }\n }\n break;\n }\n }\n function addBindingsOnly(pattern, targetSet) {\n if (!pattern) return;\n switch (pattern.type) {\n case \"Identifier\":\n targetSet.add(pattern.name);\n break;\n case \"AssignmentPattern\":\n addBindingsOnly(pattern.left, targetSet);\n break;\n case \"RestElement\":\n addBindingsOnly(pattern.argument, targetSet);\n break;\n case \"ArrayPattern\":\n for (const el of pattern.elements) {\n if (el) addBindingsOnly(el, targetSet);\n }\n break;\n case \"ObjectPattern\":\n for (const prop of pattern.properties) {\n if (prop.type === \"Property\") {\n addBindingsOnly(prop.value, targetSet);\n } else if (prop.type === \"RestElement\") {\n addBindingsOnly(prop.argument, targetSet);\n }\n }\n break;\n }\n }\n function hoistDeclarations(node, direct) {\n if (!node || typeof node !== \"object\" || typeof node.type !== \"string\") return;\n switch (node.type) {\n case \"FunctionDeclaration\":\n if (node.id?.name) {\n currentScope.bindings.add(node.id.name);\n currentScope.varBindings.add(node.id.name);\n }\n return;\n case \"FunctionExpression\":\n case \"ArrowFunctionExpression\":\n return;\n case \"ClassDeclaration\":\n if (direct && node.id?.name) currentScope.bindings.add(node.id.name);\n return;\n case \"VariableDeclaration\":\n if (node.kind === \"var\") {\n for (const d of node.declarations)\n addBindingsOnly(d.id, currentScope.varBindings);\n } else if (direct) {\n for (const d of node.declarations) addBindingsOnly(d.id, currentScope.bindings);\n }\n return;\n case \"ExportNamedDeclaration\":\n case \"ExportDefaultDeclaration\":\n hoistDeclarations(node.declaration, direct);\n return;\n }\n for (const key of Object.keys(node)) {\n if (key === \"start\" || key === \"end\" || key === \"loc\" || key === \"range\") continue;\n const child = node[key];\n if (Array.isArray(child)) {\n for (const item of child) hoistDeclarations(item, false);\n } else if (child && typeof child === \"object\") {\n hoistDeclarations(child, false);\n }\n }\n }\n if (fnNode.params) {\n for (const param of fnNode.params) {\n addBindings(param, rootScope.bindings);\n }\n }\n function isDeclaredInScopes(name, fromScope) {\n let s = fromScope;\n while (s) {\n if (s.bindings.has(name) || s.varBindings.has(name)) {\n return true;\n }\n s = s.parent;\n }\n return false;\n }\n function resolveIdentifier(name) {\n if (!isDeclaredInScopes(name, currentScope) && !globals.has(name)) {\n freeVariables.add(name);\n }\n }\n function walk(node) {\n if (!node || typeof node !== \"object\") return;\n if (node.type === \"TSTypeAnnotation\" || node.type === \"TSTypeReference\" || node.type === \"TSTypeAliasDeclaration\" || node.type === \"TSInterfaceDeclaration\" || node.type === \"TSTypeParameterDeclaration\" || node.type === \"TSTypeParameterInstantiation\" || node.type === \"TSTypeQuery\" || node.type === \"TSQualifiedName\") {\n return;\n }\n if (node.type === \"TSAsExpression\" || node.type === \"TSSatisfiesExpression\" || node.type === \"TSTypeAssertion\" || node.type === \"TSNonNullExpression\" || node.type === \"TSInstantiationExpression\") {\n walk(node.expression);\n return;\n }\n switch (node.type) {\n case \"BlockStatement\": {\n const isRootBody = node === fnNode.body;\n if (!isRootBody) {\n pushScope(false);\n }\n for (const stmt of node.body) {\n hoistDeclarations(stmt, true);\n }\n for (const stmt of node.body) {\n walk(stmt);\n }\n if (!isRootBody) {\n popScope();\n }\n return;\n }\n case \"VariableDeclaration\": {\n const isVar = node.kind === \"var\";\n const targetSet = isVar ? currentScope.varBindings : currentScope.bindings;\n for (const decl of node.declarations) {\n addBindings(decl.id, targetSet);\n if (decl.init) walk(decl.init);\n }\n return;\n }\n case \"FunctionDeclaration\":\n case \"FunctionExpression\": {\n if (node.id && node.id.name) {\n currentScope.bindings.add(node.id.name);\n }\n pushScope(true);\n if (node.params) {\n for (const param of node.params) {\n addBindings(param, currentScope.bindings);\n }\n }\n walk(node.body);\n popScope();\n return;\n }\n case \"ArrowFunctionExpression\": {\n pushScope(true);\n if (node.params) {\n for (const param of node.params) {\n addBindings(param, currentScope.bindings);\n }\n }\n walk(node.body);\n popScope();\n return;\n }\n case \"CatchClause\": {\n pushScope(false);\n if (node.param) {\n addBindings(node.param, currentScope.bindings);\n }\n walk(node.body);\n popScope();\n return;\n }\n case \"ForStatement\": {\n pushScope(false);\n if (node.init) walk(node.init);\n if (node.test) walk(node.test);\n if (node.update) walk(node.update);\n walk(node.body);\n popScope();\n return;\n }\n case \"ForInStatement\":\n case \"ForOfStatement\": {\n pushScope(false);\n walk(node.left);\n walk(node.right);\n walk(node.body);\n popScope();\n return;\n }\n case \"ClassDeclaration\":\n case \"ClassExpression\": {\n if (node.id && node.id.name) {\n currentScope.bindings.add(node.id.name);\n }\n if (node.decorators) {\n for (const decorator of node.decorators) walk(decorator);\n }\n if (node.superClass) walk(node.superClass);\n pushScope(false);\n walk(node.body);\n popScope();\n return;\n }\n case \"MemberExpression\": {\n walk(node.object);\n if (node.computed) {\n walk(node.property);\n }\n return;\n }\n case \"Property\": {\n if (node.computed) {\n walk(node.key);\n }\n walk(node.value);\n return;\n }\n case \"MethodDefinition\":\n case \"TSAbstractMethodDefinition\": {\n if (node.computed) {\n walk(node.key);\n }\n if (node.decorators) {\n for (const decorator of node.decorators) walk(decorator);\n }\n walk(node.value);\n return;\n }\n case \"PropertyDefinition\":\n case \"AccessorProperty\":\n case \"TSAbstractPropertyDefinition\": {\n if (node.computed) {\n walk(node.key);\n }\n if (node.decorators) {\n for (const decorator of node.decorators) walk(decorator);\n }\n if (node.value) walk(node.value);\n return;\n }\n case \"TSIndexSignature\": {\n return;\n }\n case \"Identifier\": {\n resolveIdentifier(node.name);\n return;\n }\n case \"JSXElement\": {\n if (node.openingElement) {\n const nameNode = node.openingElement.name;\n if (nameNode.type === \"JSXIdentifier\") {\n if (/^[A-Z]/.test(nameNode.name)) {\n resolveIdentifier(nameNode.name);\n }\n } else if (nameNode.type === \"JSXMemberExpression\") {\n let root = nameNode.object;\n while (root.type === \"JSXMemberExpression\") {\n root = root.object;\n }\n if (root.type === \"JSXIdentifier\") {\n resolveIdentifier(root.name);\n }\n }\n if (node.openingElement.attributes) {\n for (const attr of node.openingElement.attributes) {\n walk(attr);\n }\n }\n }\n if (node.children) {\n for (const child of node.children) {\n walk(child);\n }\n }\n return;\n }\n case \"JSXAttribute\": {\n if (node.value) {\n walk(node.value);\n }\n return;\n }\n case \"JSXExpressionContainer\": {\n walk(node.expression);\n return;\n }\n case \"BreakStatement\":\n case \"ContinueStatement\":\n case \"LabeledStatement\": {\n if (node.body) walk(node.body);\n return;\n }\n }\n for (const key of Object.keys(node)) {\n if (key === \"start\" || key === \"end\" || key === \"loc\" || key === \"range\") continue;\n const child = node[key];\n if (Array.isArray(child)) {\n for (const item of child) {\n walk(item);\n }\n } else if (child && typeof child === \"object\") {\n walk(child);\n }\n }\n }\n walk(fnNode.body);\n return Array.from(freeVariables).sort();\n}\nexport {\n getClosureVariables\n};\n//# sourceMappingURL=scope.js.map\n"],"mappings":";AAAA,SAAS,oBAAoB,QAAQ,SAAS;CAC5C,MAAM,YAAY;EAChB,QAAQ;EACR,YAAY;EACZ,0BAA0B,IAAI,IAAI;EAClC,6BAA6B,IAAI,IAAI;CACvC;CACA,IAAI,eAAe;CACnB,MAAM,gCAAgC,IAAI,IAAI;CAC9C,IAAI,OAAO,MAAM,OAAO,GAAG,MAAM;EAC/B,UAAU,SAAS,IAAI,OAAO,GAAG,IAAI;CACvC;CACA,SAAS,UAAU,YAAY;EAC7B,MAAM,WAAW;GACf,QAAQ;GACR;GACA,0BAA0B,IAAI,IAAI;GAClC,aAAa,6BAA6B,IAAI,IAAI,IAAI,aAAa;EACrE;EACA,eAAe;EACf,OAAO;CACT;CACA,SAAS,WAAW;EAClB,IAAI,aAAa,QAAQ;GACvB,eAAe,aAAa;EAC9B;CACF;CACA,SAAS,YAAY,SAAS,WAAW;EACvC,IAAI,CAAC,SAAS;EACd,QAAQ,QAAQ,MAAhB;GACE,KAAK;IACH,UAAU,IAAI,QAAQ,IAAI;IAC1B;GACF,KAAK;IACH,YAAY,QAAQ,MAAM,SAAS;IACnC,KAAK,QAAQ,KAAK;IAClB;GACF,KAAK;IACH,YAAY,QAAQ,UAAU,SAAS;IACvC;GACF,KAAK;IACH,KAAK,MAA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,OAAO;KACxB,KAAK,IAAI;IACX;GACF,OAAO,IAAI,SAAS,OAAO,UAAU,UAAU;IAC7C,KAAK,KAAK;GACZ;EACF;CACF;CACA,KAAK,OAAO,IAAI;CAChB,OAAO,MAAM,KAAK,aAAa,CAAC,CAAC,KAAK;AACxC"}
@@ -10,7 +10,7 @@ function assertTransformed(transformed, name, what) {
10
10
  throw new Error(`[worklets] built empty ${what} code for ${name || "anonymous worklet"}`);
11
11
  }
12
12
  }
13
- function serializeWorkletForUI(fnNode, code, name, closureVars) {
13
+ function serializeWorkletForUI(fnNode, code, name, closureVars, reconstructions = []) {
14
14
  let rawParams = "";
15
15
  if (fnNode.params && fnNode.params.length > 0) {
16
16
  const pStart = fnNode.params[0].start;
@@ -27,11 +27,13 @@ function serializeWorkletForUI(fnNode, code, name, closureVars) {
27
27
  }
28
28
  const unpacker = closureVars.length > 0 ? `const [${closureVars.join(", ")}] = this.__closure;
29
29
  ` : "";
30
+ const rebuilt = reconstructions.length > 0 ? reconstructions.map(({ name: name2, factory }) => `const ${name2} = ${factory}();
31
+ `).join("") : "";
30
32
  const asyncPrefix = fnNode.async ? "async " : "";
31
33
  const genPrefix = fnNode.generator ? "*" : "";
32
34
  const fnName = name || "_worklet";
33
35
  const fullFn = `${asyncPrefix}function${genPrefix} ${fnName}(${rawParams}) {
34
- ${unpacker}${rawBody}
36
+ ${unpacker}${rebuilt}${rawBody}
35
37
  }`;
36
38
  const transformed = transformSync("worklet.ts", fullFn);
37
39
  assertTransformed(transformed, name, "serialized");
@@ -1 +1 @@
1
- {"version":3,"file":"serialize.js","names":[],"sources":["esm/worklets/serialize.js"],"sourcesContent":["import { transformSync } from \"oxc-transform\";\nimport { bodyStartAfterDirectives } from \"./autoworklet\";\nfunction assertTransformed(transformed, name, what) {\n const error = transformed.errors?.[0];\n if (error) {\n throw new Error(\n `[worklets] failed to build ${what} code for ${name || \"anonymous worklet\"}: ${error.message || error}`\n );\n }\n if (!transformed.code.trim()) {\n throw new Error(\n `[worklets] built empty ${what} code for ${name || \"anonymous worklet\"}`\n );\n }\n}\nfunction serializeWorkletForUI(fnNode, code, name, closureVars) {\n let rawParams = \"\";\n if (fnNode.params && fnNode.params.length > 0) {\n const pStart = fnNode.params[0].start;\n const pEnd = fnNode.params[fnNode.params.length - 1].end;\n rawParams = code.slice(pStart, pEnd);\n }\n let rawBody = \"\";\n if (fnNode.body.type === \"BlockStatement\") {\n const bodyStart = bodyStartAfterDirectives(fnNode, code);\n const bodyEnd = fnNode.body.end - 1;\n rawBody = code.slice(bodyStart, bodyEnd);\n } else {\n rawBody = `return ${code.slice(fnNode.body.start, fnNode.body.end)};`;\n }\n const unpacker = closureVars.length > 0 ? `const [${closureVars.join(\", \")}] = this.__closure;\n` : \"\";\n const asyncPrefix = fnNode.async ? \"async \" : \"\";\n const genPrefix = fnNode.generator ? \"*\" : \"\";\n const fnName = name || \"_worklet\";\n const fullFn = `${asyncPrefix}function${genPrefix} ${fnName}(${rawParams}) {\n${unpacker}${rawBody}\n}`;\n const transformed = transformSync(\"worklet.ts\", fullFn);\n assertTransformed(transformed, name, \"serialized\");\n return `(${transformed.code.trim().replace(/;$/, \"\")})`;\n}\nfunction buildLocalFunction(fnNode, code, name) {\n let rawParams = \"\";\n if (fnNode.params && fnNode.params.length > 0) {\n const pStart = fnNode.params[0].start;\n const pEnd = fnNode.params[fnNode.params.length - 1].end;\n rawParams = code.slice(pStart, pEnd);\n }\n let rawBody = \"\";\n if (fnNode.body.type === \"BlockStatement\") {\n const bodyStart = bodyStartAfterDirectives(fnNode, code);\n const bodyEnd = fnNode.body.end - 1;\n rawBody = code.slice(bodyStart, bodyEnd);\n } else {\n rawBody = code.slice(fnNode.body.start, fnNode.body.end);\n }\n let rawFn = \"\";\n const asyncPrefix = fnNode.async ? \"async \" : \"\";\n const genPrefix = fnNode.generator ? \"*\" : \"\";\n if (fnNode.type === \"ArrowFunctionExpression\") {\n if (fnNode.body.type === \"BlockStatement\") {\n rawFn = `${asyncPrefix}(${rawParams}) => {\n${rawBody}\n}`;\n } else {\n rawFn = `${asyncPrefix}(${rawParams}) => (${rawBody})`;\n }\n } else {\n rawFn = `${asyncPrefix}function${genPrefix} ${name || \"_worklet\"}(${rawParams}) {\n${rawBody}\n}`;\n }\n const transformed = transformSync(\"local.ts\", rawFn);\n assertTransformed(transformed, name, \"local\");\n return transformed.code.trim().replace(/;$/, \"\");\n}\nexport {\n buildLocalFunction,\n serializeWorkletForUI\n};\n//# sourceMappingURL=serialize.js.map\n"],"mappings":";;;;AAEA,SAAS,kBAAkB,aAAa,MAAM,MAAM;CAClD,MAAM,QAAQ,YAAY,SAAS;CACnC,IAAI,OAAO;EACT,MAAM,IAAI,MACR,8BAA8B,KAAK,YAAY,QAAQ,oBAAoB,IAAI,MAAM,WAAW,OAClG;CACF;CACA,IAAI,CAAC,YAAY,KAAK,KAAK,GAAG;EAC5B,MAAM,IAAI,MACR,0BAA0B,KAAK,YAAY,QAAQ,qBACrD;CACF;AACF;AACA,SAAS,sBAAsB,QAAQ,MAAM,MAAM,aAAa;CAC9D,IAAI,YAAY;CAChB,IAAI,OAAO,UAAU,OAAO,OAAO,SAAS,GAAG;EAC7C,MAAM,SAAS,OAAO,OAAO,EAAE,CAAC;EAChC,MAAM,OAAO,OAAO,OAAO,OAAO,OAAO,SAAS,EAAE,CAAC;EACrD,YAAY,KAAK,MAAM,QAAQ,IAAI;CACrC;CACA,IAAI,UAAU;CACd,IAAI,OAAO,KAAK,SAAS,kBAAkB;EACzC,MAAM,YAAY,yBAAyB,QAAQ,IAAI;EACvD,MAAM,UAAU,OAAO,KAAK,MAAM;EAClC,UAAU,KAAK,MAAM,WAAW,OAAO;CACzC,OAAO;EACL,UAAU,UAAU,KAAK,MAAM,OAAO,KAAK,OAAO,OAAO,KAAK,GAAG,EAAE;CACrE;CACA,MAAM,WAAW,YAAY,SAAS,IAAI,UAAU,YAAY,KAAK,IAAI,EAAE;IACzE;CACF,MAAM,cAAc,OAAO,QAAQ,WAAW;CAC9C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M,OAAO;CAC5C,OAAO,YAAY,KAAK,KAAK,CAAC,CAAC,QAAQ,MAAM,EAAE;AACjD"}
1
+ {"version":3,"file":"serialize.js","names":[],"sources":["esm/worklets/serialize.js"],"sourcesContent":["import { transformSync } from \"oxc-transform\";\nimport { bodyStartAfterDirectives } from \"./autoworklet\";\nfunction assertTransformed(transformed, name, what) {\n const error = transformed.errors?.[0];\n if (error) {\n throw new Error(\n `[worklets] failed to build ${what} code for ${name || \"anonymous worklet\"}: ${error.message || error}`\n );\n }\n if (!transformed.code.trim()) {\n throw new Error(\n `[worklets] built empty ${what} code for ${name || \"anonymous worklet\"}`\n );\n }\n}\nfunction serializeWorkletForUI(fnNode, code, name, closureVars, reconstructions = []) {\n let rawParams = \"\";\n if (fnNode.params && fnNode.params.length > 0) {\n const pStart = fnNode.params[0].start;\n const pEnd = fnNode.params[fnNode.params.length - 1].end;\n rawParams = code.slice(pStart, pEnd);\n }\n let rawBody = \"\";\n if (fnNode.body.type === \"BlockStatement\") {\n const bodyStart = bodyStartAfterDirectives(fnNode, code);\n const bodyEnd = fnNode.body.end - 1;\n rawBody = code.slice(bodyStart, bodyEnd);\n } else {\n rawBody = `return ${code.slice(fnNode.body.start, fnNode.body.end)};`;\n }\n const unpacker = closureVars.length > 0 ? `const [${closureVars.join(\", \")}] = this.__closure;\n` : \"\";\n const rebuilt = reconstructions.length > 0 ? reconstructions.map(({ name: name2, factory }) => `const ${name2} = ${factory}();\n`).join(\"\") : \"\";\n const asyncPrefix = fnNode.async ? \"async \" : \"\";\n const genPrefix = fnNode.generator ? \"*\" : \"\";\n const fnName = name || \"_worklet\";\n const fullFn = `${asyncPrefix}function${genPrefix} ${fnName}(${rawParams}) {\n${unpacker}${rebuilt}${rawBody}\n}`;\n const transformed = transformSync(\"worklet.ts\", fullFn);\n assertTransformed(transformed, name, \"serialized\");\n return `(${transformed.code.trim().replace(/;$/, \"\")})`;\n}\nfunction buildLocalFunction(fnNode, code, name) {\n let rawParams = \"\";\n if (fnNode.params && fnNode.params.length > 0) {\n const pStart = fnNode.params[0].start;\n const pEnd = fnNode.params[fnNode.params.length - 1].end;\n rawParams = code.slice(pStart, pEnd);\n }\n let rawBody = \"\";\n if (fnNode.body.type === \"BlockStatement\") {\n const bodyStart = bodyStartAfterDirectives(fnNode, code);\n const bodyEnd = fnNode.body.end - 1;\n rawBody = code.slice(bodyStart, bodyEnd);\n } else {\n rawBody = code.slice(fnNode.body.start, fnNode.body.end);\n }\n let rawFn = \"\";\n const asyncPrefix = fnNode.async ? \"async \" : \"\";\n const genPrefix = fnNode.generator ? \"*\" : \"\";\n if (fnNode.type === \"ArrowFunctionExpression\") {\n if (fnNode.body.type === \"BlockStatement\") {\n rawFn = `${asyncPrefix}(${rawParams}) => {\n${rawBody}\n}`;\n } else {\n rawFn = `${asyncPrefix}(${rawParams}) => (${rawBody})`;\n }\n } else {\n rawFn = `${asyncPrefix}function${genPrefix} ${name || \"_worklet\"}(${rawParams}) {\n${rawBody}\n}`;\n }\n const transformed = transformSync(\"local.ts\", rawFn);\n assertTransformed(transformed, name, \"local\");\n return transformed.code.trim().replace(/;$/, \"\");\n}\nexport {\n buildLocalFunction,\n serializeWorkletForUI\n};\n//# sourceMappingURL=serialize.js.map\n"],"mappings":";;;;AAEA,SAAS,kBAAkB,aAAa,MAAM,MAAM;CAClD,MAAM,QAAQ,YAAY,SAAS;CACnC,IAAI,OAAO;EACT,MAAM,IAAI,MACR,8BAA8B,KAAK,YAAY,QAAQ,oBAAoB,IAAI,MAAM,WAAW,OAClG;CACF;CACA,IAAI,CAAC,YAAY,KAAK,KAAK,GAAG;EAC5B,MAAM,IAAI,MACR,0BAA0B,KAAK,YAAY,QAAQ,qBACrD;CACF;AACF;AACA,SAAS,sBAAsB,QAAQ,MAAM,MAAM,aAAa,kBAAkB,CAAC,GAAG;CACpF,IAAI,YAAY;CAChB,IAAI,OAAO,UAAU,OAAO,OAAO,SAAS,GAAG;EAC7C,MAAM,SAAS,OAAO,OAAO,EAAE,C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M,YAAY,yBAAyB,QAAQ,IAAI;EACvD,MAAM,UAAU,OAAO,KAAK,MAAM;EAClC,UAAU,KAAK,MAAM,WAAW,OAAO;CACzC,OAAO;EACL,UAAU,KAAK,MAAM,OAAO,KAAK,OAAO,OAAO,KAAK,GAAG;CACzD;CACA,IAAI,QAAQ;CACZ,MAAM,cAAc,OAAO,QAAQ,WAAW;CAC9C,MAAM,YAAY,OAAO,YAAY,MAAM;CAC3C,IAAI,OAAO,SAAS,2BAA2B;EAC7C,IAAI,OAAO,KAAK,SAAS,kBAAkB;GACzC,QAAQ,GAAG,YAAY,GAAG,UAAU;EACxC,QAAQ;;EAEN,OAAO;GACL,QAAQ,GAAG,YAAY,GAAG,UAAU,QAAQ,QAAQ;EACtD;CACF,OAAO;EACL,QAAQ,GAAG,YAAY,UAAU,UAAU,GAAG,QAAQ,WAAW,GAAG,UAAU;EAChF,QAAQ;;CAER;CACA,MAAM,cAAc,cAAc,YAAY,KAAK;CACnD,kBAAkB,aAAa,MAAM,OAAO;CAC5C,OAAO,YAAY,KAAK,KAAK,CAAC,CAAC,QAAQ,MAAM,EAAE;AACjD"}
@@ -3,6 +3,7 @@ import MagicString from "magic-string";
3
3
  import remapping from "@jridgewell/remapping";
4
4
  import { parseSync } from "oxc-parser";
5
5
  import { bodyStartAfterDirectives, findWorkletCandidates, hasDirective } from "./autoworklet.mjs";
6
+ import { buildClassFactoryDeclaration, classFactoryName, findConstructedNames, findUnambiguousClassNames, findWorkletClasses } from "./classes.mjs";
6
7
  import { createGlobalsSet } from "./globals.mjs";
7
8
  import { calculateWorkletHash } from "./hash.mjs";
8
9
  import { getClosureVariables } from "./scope.mjs";
@@ -77,7 +78,10 @@ function executeWorkletTransform(id, code, sourceMaps = false, options, resolveV
77
78
  throw new Error(err.codeframe || err.message || "Syntax Error while parsing worklet");
78
79
  }
79
80
  const initialCandidates = findWorkletCandidates(initialParse.program);
80
- if (initialCandidates.length === 0) {
81
+ const workletClassesEnabled = !options?.disableWorkletClasses && !options?.bundleMode;
82
+ const initialClasses = workletClassesEnabled ? findWorkletClasses(initialParse.program) : [];
83
+ const resolvableClassNames = initialClasses.length > 0 ? findUnambiguousClassNames(initialParse.program, initialClasses) : /* @__PURE__ */ new Set();
84
+ if (initialCandidates.length === 0 && initialClasses.length === 0) {
81
85
  let map2 = void 0;
82
86
  if (sourceMaps) {
83
87
  const ms = new MagicString(code);
@@ -102,6 +106,33 @@ function executeWorkletTransform(id, code, sourceMaps = false, options, resolveV
102
106
  let currentCode = code;
103
107
  const initDataDefs = /* @__PURE__ */ new Map();
104
108
  const passMaps = [];
109
+ if (initialClasses.length > 0) {
110
+ const ms = new MagicString(currentCode);
111
+ for (const candidate of initialClasses) {
112
+ const factoryDecl = buildClassFactoryDeclaration(candidate, currentCode);
113
+ const rebound = `const ${candidate.name} = ${classFactoryName(candidate.name)}();`;
114
+ if (candidate.parent?.type === "ExportNamedDeclaration") {
115
+ ms.overwrite(candidate.parent.start, candidate.parent.end, `${factoryDecl}
116
+ export ${rebound}`);
117
+ } else if (candidate.parent?.type === "ExportDefaultDeclaration") {
118
+ ms.overwrite(candidate.parent.start, candidate.parent.end, `${factoryDecl}
119
+ ${rebound}
120
+ export default ${candidate.name};`);
121
+ } else {
122
+ ms.overwrite(candidate.node.start, candidate.node.end, `${factoryDecl}
123
+ ${rebound}`);
124
+ }
125
+ }
126
+ if (sourceMaps) {
127
+ passMaps.push(ms.generateMap({
128
+ source: cleanId,
129
+ file: cleanId,
130
+ hires: true,
131
+ includeContent: true
132
+ }));
133
+ }
134
+ currentCode = ms.toString();
135
+ }
105
136
  let remainingPassBudget = 100;
106
137
  while (remainingPassBudget-- > 0) {
107
138
  const parseResult = parseSync(cleanId, currentCode, {
@@ -125,9 +156,31 @@ function executeWorkletTransform(id, code, sourceMaps = false, options, resolveV
125
156
  const ms = new MagicString(currentCode);
126
157
  const inlinedInitData = /* @__PURE__ */ new Map();
127
158
  for (const candidate of innermostCandidates) {
128
- const closureVars = hasDirective(candidate.fnNode, "no-worklet-closure") ? [] : getClosureVariables(candidate.fnNode, globals);
159
+ let closureVars = hasDirective(candidate.fnNode, "no-worklet-closure") ? [] : getClosureVariables(candidate.fnNode, globals);
160
+ const reconstructions = [];
161
+ if (workletClassesEnabled && closureVars.length > 0) {
162
+ const captured = new Set(closureVars);
163
+ const rewriteToFactory = (name) => {
164
+ if (!captured.has(name)) return;
165
+ const factory = classFactoryName(name);
166
+ captured.delete(name);
167
+ captured.add(factory);
168
+ if (!reconstructions.some((r) => r.factory === factory)) {
169
+ reconstructions.push({
170
+ name,
171
+ factory
172
+ });
173
+ }
174
+ };
175
+ const knownCaptures = [...captured].filter((name) => resolvableClassNames.has(name));
176
+ for (const name of knownCaptures) rewriteToFactory(name);
177
+ for (const constructed of findConstructedNames(candidate.fnNode)) {
178
+ rewriteToFactory(constructed);
179
+ }
180
+ closureVars = [...captured].sort();
181
+ }
129
182
  const fnName = candidate.name;
130
- const serializedCode = serializeWorkletForUI(candidate.fnNode, currentCode, fnName, closureVars);
183
+ const serializedCode = serializeWorkletForUI(candidate.fnNode, currentCode, fnName, closureVars, reconstructions);
131
184
  const workletHash = calculateWorkletHash(serializedCode);
132
185
  const initDataVar = `_worklet_${workletHash}_init_data`;
133
186
  const initDataDecl = `var ${initDataVar} = {
@@ -153,7 +206,8 @@ ${initDataDecl}
153
206
  }
154
207
  const localFnCode = buildLocalFunction(candidate.fnNode, currentCode, fnName);
155
208
  const localName = fnName || "_worklet";
156
- const closureValues = closureVars.join(", ");
209
+ const factoryOwners = new Map(reconstructions.map((r) => [r.factory, r.name]));
210
+ const closureValues = closureVars.map((v) => factoryOwners.has(v) ? `${factoryOwners.get(v)}.${v}` : v).join(", ");
157
211
  const iife = `(function () {
158
212
  var _e = [new (typeof global !== 'undefined' ? global : globalThis).Error(), 1, -27];
159
213
  var ${localName} = ${localFnCode};
@@ -1 +1 @@
1
- {"version":3,"file":"transform.js","names":[],"sources":["esm/worklets/transform.js"],"sourcesContent":["import path from \"node:path\";\nimport MagicString from \"magic-string\";\nimport remapping from \"@jridgewell/remapping\";\nimport { parseSync } from \"oxc-parser\";\nimport {\n bodyStartAfterDirectives,\n findWorkletCandidates,\n hasDirective\n} from \"./autoworklet\";\nimport { createGlobalsSet } from \"./globals\";\nimport { calculateWorkletHash } from \"./hash\";\nimport { getClosureVariables } from \"./scope\";\nimport { buildLocalFunction, serializeWorkletForUI } from \"./serialize\";\nconst FUNCTION_TYPES = /* @__PURE__ */ new Set([\n \"FunctionDeclaration\",\n \"FunctionExpression\",\n \"ArrowFunctionExpression\"\n]);\nfunction prepareWorkletsForReactCompiler(id, code, sourceMaps = false) {\n const cleanId = id.split(\"?\")[0];\n const parsed = parseSync(cleanId, code, {\n sourceType: \"module\",\n lang: /\\.[cm]?ts$/.test(cleanId) ? \"ts\" : cleanId.endsWith(\".tsx\") ? \"tsx\" : \"jsx\"\n });\n if (parsed.errors.length) {\n const error = parsed.errors[0];\n throw new Error(\n error.codeframe || error.message || \"Syntax Error while parsing worklet\"\n );\n }\n const candidates = findWorkletCandidates(parsed.program).filter(\n (candidate) => candidate.isAutoWorklet && !hasDirective(candidate.fnNode, \"worklet\")\n );\n if (!candidates.length) return null;\n const output = new MagicString(code);\n for (const { fnNode } of candidates) {\n const body = fnNode.body;\n if (body.type === \"BlockStatement\") {\n output.appendLeft(body.start + 1, \"'worklet';\");\n } else {\n output.appendLeft(body.start, \"{ 'worklet'; return (\");\n output.appendLeft(body.end, \"); }\");\n }\n }\n return {\n code: output.toString(),\n map: sourceMaps ? output.generateMap({ source: cleanId, hires: true, includeContent: true }) : void 0\n };\n}\nfunction findEnclosingFunction(program, node) {\n let best = void 0;\n const walk = (n) => {\n if (!n || typeof n !== \"object\") return;\n if (Array.isArray(n)) {\n for (const c of n) walk(c);\n return;\n }\n if (typeof n.type !== \"string\") return;\n if (typeof n.start === \"number\" && (n.start > node.start || n.end < node.end)) return;\n if (FUNCTION_TYPES.has(n.type) && n !== node && n.body?.type === \"BlockStatement\" && n.body.start < node.start && n.body.end > node.end && (!best || n.body.start > best.body.start)) {\n best = n;\n }\n for (const key in n) {\n if (key === \"parent\") continue;\n walk(n[key]);\n }\n };\n walk(program);\n return best;\n}\nfunction executeWorkletTransform(id, code, sourceMaps = false, options, resolveVersionFn) {\n const cleanId = id.split(\"?\")[0];\n const lang = /\\.[cm]?ts$/.test(cleanId) ? \"ts\" : cleanId.endsWith(\".tsx\") ? \"tsx\" : \"jsx\";\n const initialParse = parseSync(cleanId, code, {\n sourceType: \"module\",\n lang\n });\n if (initialParse.errors && initialParse.errors.length > 0) {\n const err = initialParse.errors[0];\n throw new Error(err.codeframe || err.message || \"Syntax Error while parsing worklet\");\n }\n const initialCandidates = findWorkletCandidates(initialParse.program);\n if (initialCandidates.length === 0) {\n let map2 = void 0;\n if (sourceMaps) {\n const ms = new MagicString(code);\n map2 = ms.generateMap({\n source: cleanId,\n file: cleanId,\n hires: true,\n includeContent: true\n });\n }\n return { code, map: map2 };\n }\n const pluginVersion = options?.pluginVersion || (resolveVersionFn ? resolveVersionFn(options?.projectRoot, cleanId) : \"0.0.0\");\n const globals = createGlobalsSet(options?.globals, options?.strictGlobal);\n let location = cleanId;\n if (options?.relativeSourceLocation && options?.projectRoot) {\n location = path.relative(options.projectRoot, cleanId).replace(/\\\\/g, \"/\");\n }\n let currentCode = code;\n const initDataDefs = /* @__PURE__ */ new Map();\n const passMaps = [];\n let remainingPassBudget = 100;\n while (remainingPassBudget-- > 0) {\n const parseResult = parseSync(cleanId, currentCode, {\n sourceType: \"module\",\n lang\n });\n if (parseResult.errors && parseResult.errors.length > 0) {\n const err = parseResult.errors[0];\n throw new Error(\n err.codeframe || err.message || \"Syntax Error while parsing worklet\"\n );\n }\n const candidates = findWorkletCandidates(parseResult.program);\n if (candidates.length === 0) {\n break;\n }\n const innermostCandidates = candidates.filter((c) => {\n return !candidates.some(\n (other) => other !== c && other.fnNode.start >= c.fnNode.start && other.fnNode.end <= c.fnNode.end\n );\n });\n if (innermostCandidates.length === 0) {\n throw new Error(\n `[worklets] Cyclic or unresolvable worklet nesting detected in ${cleanId}`\n );\n }\n const ms = new MagicString(currentCode);\n const inlinedInitData = /* @__PURE__ */ new Map();\n for (const candidate of innermostCandidates) {\n const closureVars = hasDirective(candidate.fnNode, \"no-worklet-closure\") ? [] : getClosureVariables(candidate.fnNode, globals);\n const fnName = candidate.name;\n const serializedCode = serializeWorkletForUI(\n candidate.fnNode,\n currentCode,\n fnName,\n closureVars\n );\n const workletHash = calculateWorkletHash(serializedCode);\n const initDataVar = `_worklet_${workletHash}_init_data`;\n const initDataDecl = `var ${initDataVar} = {\n code: ${JSON.stringify(serializedCode)},\n location: ${JSON.stringify(location)}\n};`;\n const enclosingFn = hasDirective(candidate.fnNode, \"limit-init-data-hoisting\") ? findEnclosingFunction(parseResult.program, candidate.fnNode) : void 0;\n if (enclosingFn) {\n const insertAt = bodyStartAfterDirectives(enclosingFn, currentCode);\n let declared = inlinedInitData.get(insertAt);\n if (!declared) {\n declared = /* @__PURE__ */ new Set();\n inlinedInitData.set(insertAt, declared);\n }\n if (!declared.has(initDataVar)) {\n declared.add(initDataVar);\n ms.appendLeft(insertAt, `\n${initDataDecl}\n`);\n }\n } else if (!initDataDefs.has(initDataVar)) {\n initDataDefs.set(initDataVar, initDataDecl);\n }\n const localFnCode = buildLocalFunction(candidate.fnNode, currentCode, fnName);\n const localName = fnName || \"_worklet\";\n const closureValues = closureVars.join(\", \");\n const iife = `(function () {\n var _e = [new (typeof global !== 'undefined' ? global : globalThis).Error(), 1, -27];\n var ${localName} = ${localFnCode};\n ${localName}.__closure = [${closureValues}];\n ${localName}.__workletHash = ${workletHash};\n ${localName}.__pluginVersion = ${JSON.stringify(pluginVersion)};\n ${localName}.__initData = ${initDataVar};\n ${localName}.__stackDetails = _e;\n return ${localName};\n})()`;\n if (candidate.kind === \"function_declaration\") {\n if (candidate.parent?.type === \"ExportNamedDeclaration\") {\n ms.overwrite(\n candidate.parent.start,\n candidate.parent.end,\n `export var ${candidate.name} = ${iife};`\n );\n } else if (candidate.parent?.type === \"ExportDefaultDeclaration\") {\n ms.overwrite(\n candidate.parent.start,\n candidate.parent.end,\n `var ${candidate.name || \"_defaultWorklet\"} = ${iife};\nexport default ${candidate.name || \"_defaultWorklet\"};`\n );\n } else {\n ms.overwrite(\n candidate.node.start,\n candidate.node.end,\n `var ${candidate.name} = ${iife};`\n );\n }\n } else if (candidate.kind === \"object_method\") {\n ms.overwrite(\n candidate.node.start,\n candidate.node.end,\n `${candidate.name}: ${iife}`\n );\n } else {\n ms.overwrite(candidate.node.start, candidate.node.end, iife);\n }\n }\n if (sourceMaps) {\n passMaps.push(\n ms.generateMap({\n source: cleanId,\n file: cleanId,\n hires: true,\n includeContent: true\n })\n );\n }\n currentCode = ms.toString();\n }\n const finalCheck = parseSync(cleanId, currentCode, { sourceType: \"module\", lang });\n const remaining = findWorkletCandidates(finalCheck.program);\n if (remaining.length > 0) {\n throw new Error(\n `[worklets] Exceeded maximum pass budget while transforming worklets in ${cleanId}. ${remaining.length} worklet(s) remained untransformed.`\n );\n }\n if (initDataDefs.size > 0) {\n const initDataCode = Array.from(initDataDefs.values()).join(\"\\n\") + \"\\n\";\n const msPrepend = new MagicString(currentCode);\n msPrepend.prepend(initDataCode);\n if (sourceMaps) {\n passMaps.push(\n msPrepend.generateMap({\n source: cleanId,\n file: cleanId,\n hires: true,\n includeContent: true\n })\n );\n }\n currentCode = msPrepend.toString();\n }\n let map = void 0;\n if (sourceMaps && passMaps.length > 0) {\n if (passMaps.length === 1) {\n map = passMaps[0];\n } else {\n map = remapping(passMaps.slice().reverse(), () => null);\n }\n if (map) {\n map.sources = [cleanId];\n map.file = cleanId;\n }\n }\n return {\n code: currentCode,\n map\n };\n}\nexport {\n executeWorkletTransform,\n prepareWorkletsForReactCompiler\n};\n//# sourceMappingURL=transform.js.map\n"],"mappings":";;;;;;;;;;;AAaA,MAAM,iCAAiC,IAAI,IAAI;CAC7C;CACA;CACA;AACF,CAAC;AACD,SAAS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;GACF,OAAO;IACL,GAAG,UAAU,UAAU,KAAK,OAAO,UAAU,KAAK,KAAK,IAAI;GAC7D;EACF;EACA,IAAI,YAAY;GACd,SAAS,KACP,GAAG,YAAY;IACb,QAAQ;IACR,MAAM;IACN,OAAO;IACP,gBAAgB;GAClB,CAAC,CACH;EACF;EACA,cAAc,GAAG,SAAS;CAC5B;CACA,MAAM,aAAa,UAAU,SAAS,aAAa;EAAE,YAAY;EAAU;CAAK,CAAC;CACjF,MAAM,YAAY,sBAAsB,WAAW,OAAO;CAC1D,IAAI,UAAU,SAAS,GAAG;EACxB,MAAM,IAAI,MACR,0EAA0E,QAAQ,IAAI,UAAU,OAAO,oCACzG;CACF;CACA,IAAI,aAAa,OAAO,GAAG;EACzB,MAAM,eAAe,MAAM,KAAK,aAAa,OAAO,CAAC,CAAC,CAAC,KAAK,IAAI,IAAI;EACpE,MAAM,YAAY,IAAI,YAAY,WAAW;EAC7C,UAAU,QAAQ,YAAY;EAC9B,IAAI,YAAY;GACd,SAAS,KACP,UAAU,YAAY;IACpB,QAAQ;IACR,MAAM;IACN,OAAO;IACP,gBAAgB;GAClB,CAAC,CACH;EACF;EACA,cAAc,UAAU,SAAS;CACnC;CACA,IAAI,MAAM,KAAK;CACf,IAAI,cAAc,SAAS,SAAS,GAAG;EACrC,IAAI,SAAS,WAAW,GAAG;GACzB,MAAM,SAAS;EACjB,OAAO;GACL,MAAM,UAAU,SAAS,MAAM,CAAC,CAAC,QAAQ,SAAS,IAAI;EACxD;EACA,IAAI,KAAK;GACP,IAAI,UAAU,CAAC,OAAO;GACtB,IAAI,OAAO;EACb;CACF;CACA,OAAO;EACL,MAAM;EACN;CACF;AACF"}
1
+ {"version":3,"file":"transform.js","names":[],"sources":["esm/worklets/transform.js"],"sourcesContent":["import path from \"node:path\";\nimport MagicString from \"magic-string\";\nimport remapping from \"@jridgewell/remapping\";\nimport { parseSync } from \"oxc-parser\";\nimport {\n bodyStartAfterDirectives,\n findWorkletCandidates,\n hasDirective\n} from \"./autoworklet\";\nimport {\n buildClassFactoryDeclaration,\n classFactoryName,\n findConstructedNames,\n findUnambiguousClassNames,\n findWorkletClasses\n} from \"./classes\";\nimport { createGlobalsSet } from \"./globals\";\nimport { calculateWorkletHash } from \"./hash\";\nimport { getClosureVariables } from \"./scope\";\nimport {\n buildLocalFunction,\n serializeWorkletForUI\n} from \"./serialize\";\nconst FUNCTION_TYPES = /* @__PURE__ */ new Set([\n \"FunctionDeclaration\",\n \"FunctionExpression\",\n \"ArrowFunctionExpression\"\n]);\nfunction prepareWorkletsForReactCompiler(id, code, sourceMaps = false) {\n const cleanId = id.split(\"?\")[0];\n const parsed = parseSync(cleanId, code, {\n sourceType: \"module\",\n lang: /\\.[cm]?ts$/.test(cleanId) ? \"ts\" : cleanId.endsWith(\".tsx\") ? \"tsx\" : \"jsx\"\n });\n if (parsed.errors.length) {\n const error = parsed.errors[0];\n throw new Error(\n error.codeframe || error.message || \"Syntax Error while parsing worklet\"\n );\n }\n const candidates = findWorkletCandidates(parsed.program).filter(\n (candidate) => candidate.isAutoWorklet && !hasDirective(candidate.fnNode, \"worklet\")\n );\n if (!candidates.length) return null;\n const output = new MagicString(code);\n for (const { fnNode } of candidates) {\n const body = fnNode.body;\n if (body.type === \"BlockStatement\") {\n output.appendLeft(body.start + 1, \"'worklet';\");\n } else {\n output.appendLeft(body.start, \"{ 'worklet'; return (\");\n output.appendLeft(body.end, \"); }\");\n }\n }\n return {\n code: output.toString(),\n map: sourceMaps ? output.generateMap({ source: cleanId, hires: true, includeContent: true }) : void 0\n };\n}\nfunction findEnclosingFunction(program, node) {\n let best = void 0;\n const walk = (n) => {\n if (!n || typeof n !== \"object\") return;\n if (Array.isArray(n)) {\n for (const c of n) walk(c);\n return;\n }\n if (typeof n.type !== \"string\") return;\n if (typeof n.start === \"number\" && (n.start > node.start || n.end < node.end)) return;\n if (FUNCTION_TYPES.has(n.type) && n !== node && n.body?.type === \"BlockStatement\" && n.body.start < node.start && n.body.end > node.end && (!best || n.body.start > best.body.start)) {\n best = n;\n }\n for (const key in n) {\n if (key === \"parent\") continue;\n walk(n[key]);\n }\n };\n walk(program);\n return best;\n}\nfunction executeWorkletTransform(id, code, sourceMaps = false, options, resolveVersionFn) {\n const cleanId = id.split(\"?\")[0];\n const lang = /\\.[cm]?ts$/.test(cleanId) ? \"ts\" : cleanId.endsWith(\".tsx\") ? \"tsx\" : \"jsx\";\n const initialParse = parseSync(cleanId, code, {\n sourceType: \"module\",\n lang\n });\n if (initialParse.errors && initialParse.errors.length > 0) {\n const err = initialParse.errors[0];\n throw new Error(err.codeframe || err.message || \"Syntax Error while parsing worklet\");\n }\n const initialCandidates = findWorkletCandidates(initialParse.program);\n const workletClassesEnabled = !options?.disableWorkletClasses && !options?.bundleMode;\n const initialClasses = workletClassesEnabled ? findWorkletClasses(initialParse.program) : [];\n const resolvableClassNames = initialClasses.length > 0 ? findUnambiguousClassNames(initialParse.program, initialClasses) : /* @__PURE__ */ new Set();\n if (initialCandidates.length === 0 && initialClasses.length === 0) {\n let map2 = void 0;\n if (sourceMaps) {\n const ms = new MagicString(code);\n map2 = ms.generateMap({\n source: cleanId,\n file: cleanId,\n hires: true,\n includeContent: true\n });\n }\n return { code, map: map2 };\n }\n const pluginVersion = options?.pluginVersion || (resolveVersionFn ? resolveVersionFn(options?.projectRoot, cleanId) : \"0.0.0\");\n const globals = createGlobalsSet(options?.globals, options?.strictGlobal);\n let location = cleanId;\n if (options?.relativeSourceLocation && options?.projectRoot) {\n location = path.relative(options.projectRoot, cleanId).replace(/\\\\/g, \"/\");\n }\n let currentCode = code;\n const initDataDefs = /* @__PURE__ */ new Map();\n const passMaps = [];\n if (initialClasses.length > 0) {\n const ms = new MagicString(currentCode);\n for (const candidate of initialClasses) {\n const factoryDecl = buildClassFactoryDeclaration(candidate, currentCode);\n const rebound = `const ${candidate.name} = ${classFactoryName(candidate.name)}();`;\n if (candidate.parent?.type === \"ExportNamedDeclaration\") {\n ms.overwrite(\n candidate.parent.start,\n candidate.parent.end,\n `${factoryDecl}\nexport ${rebound}`\n );\n } else if (candidate.parent?.type === \"ExportDefaultDeclaration\") {\n ms.overwrite(\n candidate.parent.start,\n candidate.parent.end,\n `${factoryDecl}\n${rebound}\nexport default ${candidate.name};`\n );\n } else {\n ms.overwrite(\n candidate.node.start,\n candidate.node.end,\n `${factoryDecl}\n${rebound}`\n );\n }\n }\n if (sourceMaps) {\n passMaps.push(\n ms.generateMap({\n source: cleanId,\n file: cleanId,\n hires: true,\n includeContent: true\n })\n );\n }\n currentCode = ms.toString();\n }\n let remainingPassBudget = 100;\n while (remainingPassBudget-- > 0) {\n const parseResult = parseSync(cleanId, currentCode, {\n sourceType: \"module\",\n lang\n });\n if (parseResult.errors && parseResult.errors.length > 0) {\n const err = parseResult.errors[0];\n throw new Error(\n err.codeframe || err.message || \"Syntax Error while parsing worklet\"\n );\n }\n const candidates = findWorkletCandidates(parseResult.program);\n if (candidates.length === 0) {\n break;\n }\n const innermostCandidates = candidates.filter((c) => {\n return !candidates.some(\n (other) => other !== c && other.fnNode.start >= c.fnNode.start && other.fnNode.end <= c.fnNode.end\n );\n });\n if (innermostCandidates.length === 0) {\n throw new Error(\n `[worklets] Cyclic or unresolvable worklet nesting detected in ${cleanId}`\n );\n }\n const ms = new MagicString(currentCode);\n const inlinedInitData = /* @__PURE__ */ new Map();\n for (const candidate of innermostCandidates) {\n let closureVars = hasDirective(candidate.fnNode, \"no-worklet-closure\") ? [] : getClosureVariables(candidate.fnNode, globals);\n const reconstructions = [];\n if (workletClassesEnabled && closureVars.length > 0) {\n const captured = new Set(closureVars);\n const rewriteToFactory = (name) => {\n if (!captured.has(name)) return;\n const factory = classFactoryName(name);\n captured.delete(name);\n captured.add(factory);\n if (!reconstructions.some((r) => r.factory === factory)) {\n reconstructions.push({ name, factory });\n }\n };\n const knownCaptures = [...captured].filter(\n (name) => resolvableClassNames.has(name)\n );\n for (const name of knownCaptures) rewriteToFactory(name);\n for (const constructed of findConstructedNames(candidate.fnNode)) {\n rewriteToFactory(constructed);\n }\n closureVars = [...captured].sort();\n }\n const fnName = candidate.name;\n const serializedCode = serializeWorkletForUI(\n candidate.fnNode,\n currentCode,\n fnName,\n closureVars,\n reconstructions\n );\n const workletHash = calculateWorkletHash(serializedCode);\n const initDataVar = `_worklet_${workletHash}_init_data`;\n const initDataDecl = `var ${initDataVar} = {\n code: ${JSON.stringify(serializedCode)},\n location: ${JSON.stringify(location)}\n};`;\n const enclosingFn = hasDirective(candidate.fnNode, \"limit-init-data-hoisting\") ? findEnclosingFunction(parseResult.program, candidate.fnNode) : void 0;\n if (enclosingFn) {\n const insertAt = bodyStartAfterDirectives(enclosingFn, currentCode);\n let declared = inlinedInitData.get(insertAt);\n if (!declared) {\n declared = /* @__PURE__ */ new Set();\n inlinedInitData.set(insertAt, declared);\n }\n if (!declared.has(initDataVar)) {\n declared.add(initDataVar);\n ms.appendLeft(insertAt, `\n${initDataDecl}\n`);\n }\n } else if (!initDataDefs.has(initDataVar)) {\n initDataDefs.set(initDataVar, initDataDecl);\n }\n const localFnCode = buildLocalFunction(candidate.fnNode, currentCode, fnName);\n const localName = fnName || \"_worklet\";\n const factoryOwners = new Map(reconstructions.map((r) => [r.factory, r.name]));\n const closureValues = closureVars.map((v) => factoryOwners.has(v) ? `${factoryOwners.get(v)}.${v}` : v).join(\", \");\n const iife = `(function () {\n var _e = [new (typeof global !== 'undefined' ? global : globalThis).Error(), 1, -27];\n var ${localName} = ${localFnCode};\n ${localName}.__closure = [${closureValues}];\n ${localName}.__workletHash = ${workletHash};\n ${localName}.__pluginVersion = ${JSON.stringify(pluginVersion)};\n ${localName}.__initData = ${initDataVar};\n ${localName}.__stackDetails = _e;\n return ${localName};\n})()`;\n if (candidate.kind === \"function_declaration\") {\n if (candidate.parent?.type === \"ExportNamedDeclaration\") {\n ms.overwrite(\n candidate.parent.start,\n candidate.parent.end,\n `export var ${candidate.name} = ${iife};`\n );\n } else if (candidate.parent?.type === \"ExportDefaultDeclaration\") {\n ms.overwrite(\n candidate.parent.start,\n candidate.parent.end,\n `var ${candidate.name || \"_defaultWorklet\"} = ${iife};\nexport default ${candidate.name || \"_defaultWorklet\"};`\n );\n } else {\n ms.overwrite(\n candidate.node.start,\n candidate.node.end,\n `var ${candidate.name} = ${iife};`\n );\n }\n } else if (candidate.kind === \"object_method\") {\n ms.overwrite(\n candidate.node.start,\n candidate.node.end,\n `${candidate.name}: ${iife}`\n );\n } else {\n ms.overwrite(candidate.node.start, candidate.node.end, iife);\n }\n }\n if (sourceMaps) {\n passMaps.push(\n ms.generateMap({\n source: cleanId,\n file: cleanId,\n hires: true,\n includeContent: true\n })\n );\n }\n currentCode = ms.toString();\n }\n const finalCheck = parseSync(cleanId, currentCode, { sourceType: \"module\", lang });\n const remaining = findWorkletCandidates(finalCheck.program);\n if (remaining.length > 0) {\n throw new Error(\n `[worklets] Exceeded maximum pass budget while transforming worklets in ${cleanId}. ${remaining.length} worklet(s) remained untransformed.`\n );\n }\n if (initDataDefs.size > 0) {\n const initDataCode = Array.from(initDataDefs.values()).join(\"\\n\") + \"\\n\";\n const msPrepend = new MagicString(currentCode);\n msPrepend.prepend(initDataCode);\n if (sourceMaps) {\n passMaps.push(\n msPrepend.generateMap({\n source: cleanId,\n file: cleanId,\n hires: true,\n includeContent: true\n })\n );\n }\n currentCode = msPrepend.toString();\n }\n let map = void 0;\n if (sourceMaps && passMaps.length > 0) {\n if (passMaps.length === 1) {\n map = passMaps[0];\n } else {\n map = remapping(passMaps.slice().reverse(), () => null);\n }\n if (map) {\n map.sources = [cleanId];\n map.file = cleanId;\n }\n }\n return {\n code: currentCode,\n map\n };\n}\nexport {\n executeWorkletTransform,\n prepareWorkletsForReactCompiler\n};\n//# sourceMappingURL=transform.js.map\n"],"mappings":";;;;;;;;;;;;AAuBA,MAAM,iCAAiC,IAAI,IAAI;CAC7C;CACA;CACA;AACF,CAAC;AACD,SAAS,gCAAgC,IAAI,MAAM,aAAa,OAAO;CACrE,MAAM,UAAU,GAAG,MAA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ACf,IAAI,cAAc,SAAS,SAAS,GAAG;EACrC,IAAI,SAAS,WAAW,GAAG;GACzB,MAAM,SAAS;EACjB,OAAO;GACL,MAAM,UAAU,SAAS,MAAM,CAAC,CAAC,QAAQ,SAAS,IAAI;EACxD;EACA,IAAI,KAAK;GACP,IAAI,UAAU,CAAC,OAAO;GACtB,IAAI,OAAO;EACb;CACF;CACA,OAAO;EACL,MAAM;EACN;CACF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vxrn/compiler",
3
- "version": "2.13.3",
3
+ "version": "2.13.5",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  "./package.json": "./package.json",
@@ -42,8 +42,8 @@
42
42
  "@babel/plugin-transform-regenerator": "^7.28.4",
43
43
  "@jridgewell/remapping": "^2.3.0",
44
44
  "@swc/core": "1.16.18",
45
- "@vxrn/utils": "2.13.3",
46
- "@vxrn/vite-native-client": "2.13.3",
45
+ "@vxrn/utils": "2.13.5",
46
+ "@vxrn/vite-native-client": "2.13.5",
47
47
  "astring": "1.9.0",
48
48
  "babel-plugin-react-compiler": "^1.0.0",
49
49
  "babel-plugin-syntax-hermes-parser": "^0.37.0",
@@ -58,7 +58,7 @@
58
58
  },
59
59
  "devDependencies": {
60
60
  "@jridgewell/trace-mapping": "^0.3.25",
61
- "@tamagui/build": "3.1.10",
61
+ "@tamagui/build": "3.2.3",
62
62
  "depcheck": "^1.4.7",
63
63
  "react-native-worklets": "~0.13.0",
64
64
  "rolldown": "^1.2.8",
@@ -76,7 +76,7 @@
76
76
  "publishConfig": {
77
77
  "access": "public"
78
78
  },
79
- "releaseSourceCommit": "11a01d3bdec7419a1fa2af3297777c65b63ce993",
79
+ "releaseSourceCommit": "f246c464320ead97e89b131b90d6592c3007f505",
80
80
  "repository": {
81
81
  "type": "git",
82
82
  "url": "git+https://github.com/onejs/one.git",
@@ -11,6 +11,26 @@ afterEach(() => {
11
11
  configureVXRNCompilerPlugin({ enableReanimated: false, enableNativeWorklets: false })
12
12
  })
13
13
 
14
+ // moves a worklet into an isolated context the way the ui runtime does: every
15
+ // captured function crosses through its serialized code only. passing a live
16
+ // host function straight in would hide a missing factory, which is how a raw
17
+ // superclass capture once slipped through.
18
+ function transferToUI(value: any, seen = new Map<any, any>()): any {
19
+ if (typeof value !== 'function') return value
20
+ if (seen.has(value)) return seen.get(value)
21
+ if (!value.__initData?.code) {
22
+ throw new Error(`non-serializable captured function: ${value.name}`)
23
+ }
24
+ const ui = runInNewContext(value.__initData.code, {})
25
+ const receiver: any = {}
26
+ const rebuilt = (...args: any[]) => ui.apply(receiver, args)
27
+ seen.set(value, rebuilt)
28
+ receiver.__closure = (value.__closure ?? []).map((item: any) =>
29
+ transferToUI(item, seen)
30
+ )
31
+ return rebuilt
32
+ }
33
+
14
34
  describe('shouldTransformWorklets', () => {
15
35
  it('returns false when enableReanimated is false', () => {
16
36
  configureVXRNCompilerPlugin({ enableReanimated: false, enableNativeWorklets: true })
@@ -333,7 +353,9 @@ export const Picker = (props: { onChange: (v: string) => void }): Node => null
333
353
  )
334
354
  expect(result.code).toContain('__workletHash')
335
355
  expect(result.code).not.toContain('import type')
336
- expect(result.map?.sources).toContain('/app/node_modules/flow-picker/js/Picker.ios.js')
356
+ expect(result.map?.sources).toContain(
357
+ '/app/node_modules/flow-picker/js/Picker.ios.js'
358
+ )
337
359
  const serialized = result.code.match(/code: ("(?:\\.|[^"\\])*")/)?.[1]
338
360
  expect((0, eval)(JSON.parse(serialized!))(21)).toBe(42)
339
361
  })
@@ -849,9 +871,182 @@ export default (codegenNativeComponent<NativeProps>('FlowPicker'): HostComponent
849
871
  runner(sandbox.exports, sandbox.global)
850
872
  expect(sandbox.exports.level1()).toBe(42)
851
873
  })
874
+
875
+ it('serializes a captured worklet class through its class factory', async () => {
876
+ const code = `
877
+ class Counter { __workletClass = true; value = 7; read() { return this.value } }
878
+ globalThis.result = function read() { 'worklet'; return new Counter().read() }
879
+ `
880
+ const result = await transformWorklets('/app/counter.ts', code, false, {
881
+ pluginVersion: '0.13.0',
882
+ })
883
+ expect(result.code).toContain('Counter__classFactory')
884
+ expect(result.code).not.toContain('__workletClass')
885
+
886
+ const sandbox: any = {}
887
+ runInNewContext(`${result.code}\nglobalThis.__testCounter = Counter;`, sandbox)
888
+ const read = sandbox.result
889
+ const Counter = sandbox.__testCounter
890
+ expect(read()).toBe(7)
891
+
892
+ const factory = Counter.Counter__classFactory
893
+ expect(factory.__workletHash).toBeDefined()
894
+ expect(factory.__initData.code).toContain('Counter__classFactory')
895
+ expect(read.__closure).toEqual([factory])
896
+
897
+ const uiFn = runInNewContext(read.__initData.code, {})
898
+ expect(read.__initData.code).toContain('Counter = Counter__classFactory()')
899
+ expect(uiFn.call({ __closure: read.__closure })).toBe(7)
900
+
901
+ const factoryUI = runInNewContext(factory.__initData.code, {})
902
+ const UICounter = factoryUI.call({ __closure: factory.__closure })
903
+ expect(new UICounter().read()).toBe(7)
904
+ })
905
+
906
+ it('matches upstream class factory serialization for captured worklet classes', async () => {
907
+ const code = `
908
+ class Counter { __workletClass = true; value = 7; read() { return this.value } }
909
+ export function read() { 'worklet'; return new Counter().read() }
910
+ `
911
+ const require = createRequire(import.meta.url)
912
+ const upstream = require('@babel/core').transformSync(code, {
913
+ filename: '/app/counter.js',
914
+ babelrc: false,
915
+ configFile: false,
916
+ plugins: [
917
+ [require.resolve('react-native-worklets/plugin'), { disableSourceMaps: true }],
918
+ ],
919
+ })
920
+ const ours = await transformWorklets('/app/counter.js', code, false, {
921
+ pluginVersion: '0.13.0',
922
+ })
923
+ const evaluate = (output: string) =>
924
+ new Function('global', `${output.replace(/\bexport /g, '')}; return read`)(
925
+ globalThis
926
+ )
927
+ const upstreamFn = evaluate(upstream.code)
928
+ const ourFn = evaluate(ours.code)
929
+ for (const fn of [upstreamFn, ourFn]) {
930
+ expect(fn.__closure).toHaveLength(1)
931
+ expect(fn.__closure[0].__workletHash).toBeDefined()
932
+ expect(fn.__closure[0].__initData.code).toBeDefined()
933
+ expect(fn()).toBe(7)
934
+ }
935
+ const upstreamUI = eval(upstreamFn.__initData.code)
936
+ const ourUI = eval(ourFn.__initData.code)
937
+ expect(ourUI.call({ __closure: upstreamFn.__closure })).toBe(7)
938
+ expect(upstreamUI.call({ __closure: ourFn.__closure })).toBe(7)
939
+ })
940
+
941
+ it('captures outer bindings used by a worklet class in the factory closure', async () => {
942
+ const code = `
943
+ const base = 5
944
+ class Adder { __workletClass = true; add(x) { return x + base } }
945
+ export function run(v) { 'worklet'; return new Adder().add(v) }
946
+ `
947
+ const result = await transformWorklets('/app/adder.ts', code, false, {
948
+ pluginVersion: '0.13.0',
949
+ })
950
+ const sandbox: any = {}
951
+ runInNewContext(
952
+ `${result.code.replace('export var run', 'var run')}\nglobalThis.__test = { run, Adder };`,
953
+ sandbox
954
+ )
955
+ const { run, Adder } = sandbox.__test
956
+ expect(Adder.Adder__classFactory.__closure).toEqual([5])
957
+ expect(run.__closure).toEqual([Adder.Adder__classFactory])
958
+ expect(run(2)).toBe(7)
959
+ const uiFn = runInNewContext(run.__initData.code, {})
960
+ expect(uiFn.call({ __closure: run.__closure }, 2)).toBe(7)
961
+ })
962
+
963
+ it('handles inheritance between worklet classes', async () => {
964
+ const code = `
965
+ abstract class Base { __workletClass = true; abstract v: number; who() { return 'base' } }
966
+ class Child extends Base { __workletClass = true; v = 30; who() { return super.who() + '+child' } }
967
+ export function run() { 'worklet'; return new Child().who() + new Child().v }
968
+ `
969
+ const result = await transformWorklets('/app/child.ts', code, false, {
970
+ pluginVersion: '0.13.0',
971
+ })
972
+ expect(result.code).toContain('Child__classFactory')
973
+ const sandbox: any = {}
974
+ runInNewContext(
975
+ `${result.code.replace('export var run', 'var run')}\nglobalThis.__test = { run, Child, Base };`,
976
+ sandbox
977
+ )
978
+ const { run, Child, Base } = sandbox.__test
979
+ expect(Child.Child__classFactory.__workletHash).toBeDefined()
980
+ // the child factory closes over the base factory, never the raw class,
981
+ // so the whole graph crosses to the ui thread through serialized code.
982
+ expect(Child.Child__classFactory.__closure).toEqual([Base.Base__classFactory])
983
+ expect(run.__closure).toEqual([Child.Child__classFactory])
984
+ expect(run()).toBe('base+child30')
985
+ expect(transferToUI(run)()).toBe('base+child30')
986
+ })
987
+
988
+ it.each([{ disableWorkletClasses: true }, { bundleMode: true }])(
989
+ 'honors %s by capturing the raw class',
990
+ async (options) => {
991
+ const code = `
992
+ class Counter { __workletClass = true; value = 7; read() { return this.value } }
993
+ globalThis.result = function read() { 'worklet'; return new Counter().read() }
994
+ `
995
+ const result = await transformWorklets('/app/counter.ts', code, false, options)
996
+ expect(result.code).not.toContain('__classFactory')
997
+ expect(result.code).toContain('__workletClass')
998
+ const sandbox: any = {}
999
+ runInNewContext(`${result.code}\nglobalThis.__testCounter = Counter;`, sandbox)
1000
+ expect(sandbox.result()).toBe(7)
1001
+ expect(sandbox.result.__closure).toEqual([sandbox.__testCounter])
1002
+ }
1003
+ )
1004
+
1005
+ it('keeps source maps working across the class factory transform', async () => {
1006
+ const code = `
1007
+ class Counter { __workletClass = true; value = 7; read() { return this.value } }
1008
+ export function read() { 'worklet'; return new Counter().read() }
1009
+ `
1010
+ const result = await transformWorklets('/app/counter.ts', code, true, {
1011
+ pluginVersion: '0.13.0',
1012
+ })
1013
+ expect(result.code).toContain('Counter__classFactory')
1014
+ expect(result.map).toBeDefined()
1015
+ expect(result.map?.mappings).toBeDefined()
1016
+ expect(result.map?.sources).toContain('/app/counter.ts')
1017
+ })
1018
+
1019
+ it('keeps the native worklets path free of Babel core', async () => {
1020
+ const dir = path.resolve(__dirname, 'worklets')
1021
+ for (const file of fs.readdirSync(dir)) {
1022
+ if (!file.endsWith('.ts') || file.endsWith('.test.ts')) continue
1023
+ const source = fs.readFileSync(path.join(dir, file), 'utf-8')
1024
+ expect(source, file).not.toContain('@babel/core')
1025
+ expect(source, file).not.toMatch(/from ['"]@babel\//)
1026
+ expect(source, file).not.toMatch(/require\(['"]@babel\//)
1027
+ }
1028
+ const result = await transformWorklets(
1029
+ '/app/counter.ts',
1030
+ `class Counter { __workletClass = true; value = 7; read() { return this.value } }
1031
+ export function read() { 'worklet'; return new Counter().read() }`,
1032
+ false
1033
+ )
1034
+ expect(result.code).toContain('Counter__classFactory')
1035
+ })
852
1036
  })
853
1037
 
854
1038
  describe('worklet detection gate', () => {
1039
+ it('accepts files that only define a worklet class', () => {
1040
+ // a marked class in its own file carries no worklet keyword, but the
1041
+ // importing file's worklet reconstructs it from its class factory, so the
1042
+ // defining file must still reach the transform.
1043
+ configureVXRNCompilerPlugin({ enableReanimated: true, enableNativeWorklets: true })
1044
+ const code = `
1045
+ class Counter { __workletClass = true; value = 7; read() { return this.value } }
1046
+ `
1047
+ expect(shouldTransformWorklets({ id: '/app/Counter.ts', code })).toBe(true)
1048
+ })
1049
+
855
1050
  it('accepts files whose only worklets come from gesture callbacks', () => {
856
1051
  // .onBegin/.onEnd/.onTouchesMove are auto-workletized by the transform, so
857
1052
  // a gate that misses them ships those callbacks untransformed.
@@ -13,6 +13,10 @@ import {
13
13
  // untransformed.
14
14
  export const REANIMATED_AUTOWORKLETIZATION_KEYWORDS = [
15
15
  'worklet',
16
+ // a marked class in its own file carries no worklet keyword, but importing
17
+ // files reconstruct it from its factory, so the defining file must reach
18
+ // the transform too.
19
+ '__workletClass',
16
20
  'useAnimatedGestureHandler',
17
21
  'useAnimatedScrollHandler',
18
22
  'useFrameCallback',