@tamagui/static 1.14.1 → 1.14.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (195) hide show
  1. package/dist/cjs/constants.js +52 -1
  2. package/dist/cjs/constants.js.map +2 -2
  3. package/dist/cjs/extractor/accessSafe.js +52 -1
  4. package/dist/cjs/extractor/accessSafe.js.map +2 -2
  5. package/dist/cjs/extractor/babelParse.js +66 -1
  6. package/dist/cjs/extractor/babelParse.js.map +2 -2
  7. package/dist/cjs/extractor/buildClassName.js +99 -1
  8. package/dist/cjs/extractor/buildClassName.js.map +2 -2
  9. package/dist/cjs/extractor/bundle.js +126 -1
  10. package/dist/cjs/extractor/bundle.js.map +2 -2
  11. package/dist/cjs/extractor/createEvaluator.js +86 -1
  12. package/dist/cjs/extractor/createEvaluator.js.map +2 -2
  13. package/dist/cjs/extractor/createExtractor.js +1630 -15
  14. package/dist/cjs/extractor/createExtractor.js.map +2 -2
  15. package/dist/cjs/extractor/ensureImportingConcat.js +64 -1
  16. package/dist/cjs/extractor/ensureImportingConcat.js.map +2 -2
  17. package/dist/cjs/extractor/evaluateAstNode.js +130 -1
  18. package/dist/cjs/extractor/evaluateAstNode.js.map +2 -2
  19. package/dist/cjs/extractor/extractHelpers.js +207 -1
  20. package/dist/cjs/extractor/extractHelpers.js.map +2 -2
  21. package/dist/cjs/extractor/extractMediaStyle.js +193 -1
  22. package/dist/cjs/extractor/extractMediaStyle.js.map +2 -2
  23. package/dist/cjs/extractor/extractToClassNames.js +413 -13
  24. package/dist/cjs/extractor/extractToClassNames.js.map +2 -2
  25. package/dist/cjs/extractor/findTopmostFunction.js +43 -1
  26. package/dist/cjs/extractor/findTopmostFunction.js.map +2 -2
  27. package/dist/cjs/extractor/generatedUid.js +59 -1
  28. package/dist/cjs/extractor/generatedUid.js.map +2 -2
  29. package/dist/cjs/extractor/getPrefixLogs.js +31 -1
  30. package/dist/cjs/extractor/getPrefixLogs.js.map +2 -2
  31. package/dist/cjs/extractor/getPropValueFromAttributes.js +89 -1
  32. package/dist/cjs/extractor/getPropValueFromAttributes.js.map +2 -2
  33. package/dist/cjs/extractor/getSourceModule.js +103 -1
  34. package/dist/cjs/extractor/getSourceModule.js.map +2 -2
  35. package/dist/cjs/extractor/getStaticBindingsForScope.js +225 -1
  36. package/dist/cjs/extractor/getStaticBindingsForScope.js.map +2 -2
  37. package/dist/cjs/extractor/hoistClassNames.js +74 -1
  38. package/dist/cjs/extractor/hoistClassNames.js.map +2 -2
  39. package/dist/cjs/extractor/literalToAst.js +115 -1
  40. package/dist/cjs/extractor/literalToAst.js.map +2 -2
  41. package/dist/cjs/extractor/loadFile.js +20 -2
  42. package/dist/cjs/extractor/loadFile.js.map +2 -2
  43. package/dist/cjs/extractor/loadTamagui.js +432 -15
  44. package/dist/cjs/extractor/loadTamagui.js.map +2 -2
  45. package/dist/cjs/extractor/logLines.js +43 -3
  46. package/dist/cjs/extractor/logLines.js.map +2 -2
  47. package/dist/cjs/extractor/normalizeTernaries.js +85 -1
  48. package/dist/cjs/extractor/normalizeTernaries.js.map +2 -2
  49. package/dist/cjs/extractor/removeUnusedHooks.js +109 -1
  50. package/dist/cjs/extractor/removeUnusedHooks.js.map +2 -2
  51. package/dist/cjs/extractor/timer.js +52 -1
  52. package/dist/cjs/extractor/timer.js.map +2 -2
  53. package/dist/cjs/extractor/validHTMLAttributes.js +126 -1
  54. package/dist/cjs/extractor/validHTMLAttributes.js.map +2 -2
  55. package/dist/cjs/getPragmaOptions.js +67 -2
  56. package/dist/cjs/getPragmaOptions.js.map +2 -2
  57. package/dist/cjs/helpers/memoize.js +45 -1
  58. package/dist/cjs/helpers/memoize.js.map +2 -2
  59. package/dist/cjs/index.js +42 -1
  60. package/dist/cjs/index.js.map +2 -2
  61. package/dist/cjs/require.js +81 -5
  62. package/dist/cjs/require.js.map +2 -2
  63. package/dist/cjs/types.js +16 -1
  64. package/dist/cjs/types.js.map +2 -2
  65. package/dist/cjs/webpackPlugin.js +34 -1
  66. package/dist/cjs/webpackPlugin.js.map +2 -2
  67. package/dist/esm/constants.js +14 -1
  68. package/dist/esm/constants.js.map +2 -2
  69. package/dist/esm/constants.mjs +14 -1
  70. package/dist/esm/constants.mjs.map +2 -2
  71. package/dist/esm/extractor/accessSafe.js +18 -1
  72. package/dist/esm/extractor/accessSafe.js.map +2 -2
  73. package/dist/esm/extractor/accessSafe.mjs +18 -1
  74. package/dist/esm/extractor/accessSafe.mjs.map +2 -2
  75. package/dist/esm/extractor/babelParse.js +31 -1
  76. package/dist/esm/extractor/babelParse.js.map +2 -2
  77. package/dist/esm/extractor/babelParse.mjs +31 -1
  78. package/dist/esm/extractor/babelParse.mjs.map +2 -2
  79. package/dist/esm/extractor/buildClassName.js +64 -1
  80. package/dist/esm/extractor/buildClassName.js.map +2 -2
  81. package/dist/esm/extractor/buildClassName.mjs +64 -1
  82. package/dist/esm/extractor/buildClassName.mjs.map +2 -2
  83. package/dist/esm/extractor/bundle.js +91 -1
  84. package/dist/esm/extractor/bundle.js.map +2 -2
  85. package/dist/esm/extractor/bundle.mjs +91 -1
  86. package/dist/esm/extractor/bundle.mjs.map +2 -2
  87. package/dist/esm/extractor/createEvaluator.js +51 -1
  88. package/dist/esm/extractor/createEvaluator.js.map +2 -2
  89. package/dist/esm/extractor/createEvaluator.mjs +51 -1
  90. package/dist/esm/extractor/createEvaluator.mjs.map +2 -2
  91. package/dist/esm/extractor/createExtractor.js +1613 -15
  92. package/dist/esm/extractor/createExtractor.js.map +2 -2
  93. package/dist/esm/extractor/createExtractor.mjs +1613 -15
  94. package/dist/esm/extractor/createExtractor.mjs.map +2 -2
  95. package/dist/esm/extractor/ensureImportingConcat.js +30 -1
  96. package/dist/esm/extractor/ensureImportingConcat.js.map +2 -2
  97. package/dist/esm/extractor/ensureImportingConcat.mjs +30 -1
  98. package/dist/esm/extractor/ensureImportingConcat.mjs.map +2 -2
  99. package/dist/esm/extractor/evaluateAstNode.js +96 -1
  100. package/dist/esm/extractor/evaluateAstNode.js.map +2 -2
  101. package/dist/esm/extractor/evaluateAstNode.mjs +96 -1
  102. package/dist/esm/extractor/evaluateAstNode.mjs.map +2 -2
  103. package/dist/esm/extractor/extractHelpers.js +161 -1
  104. package/dist/esm/extractor/extractHelpers.js.map +2 -2
  105. package/dist/esm/extractor/extractHelpers.mjs +161 -1
  106. package/dist/esm/extractor/extractHelpers.mjs.map +2 -2
  107. package/dist/esm/extractor/extractMediaStyle.js +158 -1
  108. package/dist/esm/extractor/extractMediaStyle.js.map +2 -2
  109. package/dist/esm/extractor/extractMediaStyle.mjs +158 -1
  110. package/dist/esm/extractor/extractMediaStyle.mjs.map +2 -2
  111. package/dist/esm/extractor/extractToClassNames.js +379 -13
  112. package/dist/esm/extractor/extractToClassNames.js.map +2 -2
  113. package/dist/esm/extractor/extractToClassNames.mjs +379 -13
  114. package/dist/esm/extractor/extractToClassNames.mjs.map +2 -2
  115. package/dist/esm/extractor/findTopmostFunction.js +19 -1
  116. package/dist/esm/extractor/findTopmostFunction.js.map +2 -2
  117. package/dist/esm/extractor/findTopmostFunction.mjs +19 -1
  118. package/dist/esm/extractor/findTopmostFunction.mjs.map +2 -2
  119. package/dist/esm/extractor/generatedUid.js +25 -1
  120. package/dist/esm/extractor/generatedUid.js.map +2 -2
  121. package/dist/esm/extractor/generatedUid.mjs +25 -1
  122. package/dist/esm/extractor/generatedUid.mjs.map +2 -2
  123. package/dist/esm/extractor/getPrefixLogs.js +7 -1
  124. package/dist/esm/extractor/getPrefixLogs.js.map +2 -2
  125. package/dist/esm/extractor/getPrefixLogs.mjs +7 -1
  126. package/dist/esm/extractor/getPrefixLogs.mjs.map +2 -2
  127. package/dist/esm/extractor/getPropValueFromAttributes.js +55 -1
  128. package/dist/esm/extractor/getPropValueFromAttributes.js.map +2 -2
  129. package/dist/esm/extractor/getPropValueFromAttributes.mjs +55 -1
  130. package/dist/esm/extractor/getPropValueFromAttributes.mjs.map +2 -2
  131. package/dist/esm/extractor/getSourceModule.js +69 -1
  132. package/dist/esm/extractor/getSourceModule.js.map +2 -2
  133. package/dist/esm/extractor/getSourceModule.mjs +69 -1
  134. package/dist/esm/extractor/getSourceModule.mjs.map +2 -2
  135. package/dist/esm/extractor/getStaticBindingsForScope.js +190 -1
  136. package/dist/esm/extractor/getStaticBindingsForScope.js.map +2 -2
  137. package/dist/esm/extractor/getStaticBindingsForScope.mjs +190 -1
  138. package/dist/esm/extractor/getStaticBindingsForScope.mjs.map +2 -2
  139. package/dist/esm/extractor/hoistClassNames.js +40 -1
  140. package/dist/esm/extractor/hoistClassNames.js.map +2 -2
  141. package/dist/esm/extractor/hoistClassNames.mjs +40 -1
  142. package/dist/esm/extractor/hoistClassNames.mjs.map +2 -2
  143. package/dist/esm/extractor/literalToAst.js +80 -1
  144. package/dist/esm/extractor/literalToAst.js.map +2 -2
  145. package/dist/esm/extractor/literalToAst.mjs +80 -1
  146. package/dist/esm/extractor/literalToAst.mjs.map +2 -2
  147. package/dist/esm/extractor/loadFile.js +19 -2
  148. package/dist/esm/extractor/loadFile.js.map +2 -2
  149. package/dist/esm/extractor/loadFile.mjs +19 -2
  150. package/dist/esm/extractor/loadFile.mjs.map +2 -2
  151. package/dist/esm/extractor/loadTamagui.js +396 -15
  152. package/dist/esm/extractor/loadTamagui.js.map +2 -2
  153. package/dist/esm/extractor/loadTamagui.mjs +396 -15
  154. package/dist/esm/extractor/loadTamagui.mjs.map +2 -2
  155. package/dist/esm/extractor/logLines.js +19 -3
  156. package/dist/esm/extractor/logLines.js.map +2 -2
  157. package/dist/esm/extractor/logLines.mjs +19 -3
  158. package/dist/esm/extractor/logLines.mjs.map +2 -2
  159. package/dist/esm/extractor/normalizeTernaries.js +51 -1
  160. package/dist/esm/extractor/normalizeTernaries.js.map +2 -2
  161. package/dist/esm/extractor/normalizeTernaries.mjs +51 -1
  162. package/dist/esm/extractor/normalizeTernaries.mjs.map +2 -2
  163. package/dist/esm/extractor/removeUnusedHooks.js +75 -1
  164. package/dist/esm/extractor/removeUnusedHooks.js.map +2 -2
  165. package/dist/esm/extractor/removeUnusedHooks.mjs +75 -1
  166. package/dist/esm/extractor/removeUnusedHooks.mjs.map +2 -2
  167. package/dist/esm/extractor/timer.js +28 -1
  168. package/dist/esm/extractor/timer.js.map +2 -2
  169. package/dist/esm/extractor/timer.mjs +28 -1
  170. package/dist/esm/extractor/timer.mjs.map +2 -2
  171. package/dist/esm/extractor/validHTMLAttributes.js +101 -1
  172. package/dist/esm/extractor/validHTMLAttributes.js.map +2 -2
  173. package/dist/esm/extractor/validHTMLAttributes.mjs +101 -1
  174. package/dist/esm/extractor/validHTMLAttributes.mjs.map +2 -2
  175. package/dist/esm/getPragmaOptions.js +43 -2
  176. package/dist/esm/getPragmaOptions.js.map +2 -2
  177. package/dist/esm/getPragmaOptions.mjs +43 -2
  178. package/dist/esm/getPragmaOptions.mjs.map +2 -2
  179. package/dist/esm/helpers/memoize.js +21 -1
  180. package/dist/esm/helpers/memoize.js.map +2 -2
  181. package/dist/esm/helpers/memoize.mjs +21 -1
  182. package/dist/esm/helpers/memoize.mjs.map +2 -2
  183. package/dist/esm/index.js +15 -1
  184. package/dist/esm/index.js.map +2 -2
  185. package/dist/esm/index.mjs +15 -1
  186. package/dist/esm/index.mjs.map +2 -2
  187. package/dist/esm/require.js +55 -5
  188. package/dist/esm/require.js.map +2 -2
  189. package/dist/esm/require.mjs +55 -5
  190. package/dist/esm/require.mjs.map +2 -2
  191. package/dist/esm/webpackPlugin.js +10 -1
  192. package/dist/esm/webpackPlugin.js.map +2 -2
  193. package/dist/esm/webpackPlugin.mjs +10 -1
  194. package/dist/esm/webpackPlugin.mjs.map +2 -2
  195. package/package.json +14 -14
@@ -1,16 +1,1631 @@
1
- "use strict";var Bt=Object.create;var Te=Object.defineProperty;var Ut=Object.getOwnPropertyDescriptor;var Gt=Object.getOwnPropertyNames;var qt=Object.getPrototypeOf,zt=Object.prototype.hasOwnProperty;var Rt=(i,N)=>{for(var E in N)Te(i,E,{get:N[E],enumerable:!0})},Tt=(i,N,E,ne)=>{if(N&&typeof N=="object"||typeof N=="function")for(let U of Gt(N))!zt.call(i,U)&&U!==E&&Te(i,U,{get:()=>N[U],enumerable:!(ne=Ut(N,U))||ne.enumerable});return i};var At=(i,N,E)=>(E=i!=null?Bt(qt(i)):{},Tt(N||!i||!i.__esModule?Te(E,"default",{value:i,enumerable:!0}):E,i)),Ht=i=>Tt(Te({},"__esModule",{value:!0}),i);var Zt={};Rt(Zt,{createExtractor:()=>Yt});module.exports=Ht(Zt);var Ae=require("path"),Pt=At(require("@babel/traverse")),o=At(require("@babel/types")),g=require("@tamagui/core-node"),Be=require("react-native-web-internals"),ee=require("../constants.js"),te=require("./createEvaluator.js"),Ue=require("./evaluateAstNode.js"),m=require("./extractHelpers.js"),gt=require("./findTopmostFunction.js"),ce=require("./getStaticBindingsForScope.js"),Ge=require("./literalToAst.js"),$e=require("./loadTamagui.js"),V=require("./logLines.js"),It=require("./normalizeTernaries.js"),kt=require("./removeUnusedHooks.js"),Ot=require("./timer.js"),Nt=require("./validHTMLAttributes.js");const Kt={key:!0,style:!0,className:!0},ue={ref:"ref",key:"key",...process.env.TAMAGUI_TARGET==="web"&&{onPress:"onClick",onHoverIn:"onMouseEnter",onHoverOut:"onMouseLeave",onPressIn:"onMouseDown",onPressOut:"onMouseUp"}},Qt={useMedia:!0,useTheme:!0},pn=i=>i.type==="attr",We=i=>i;let $t=!1;function Yt({logger:i=console}={logger:console}){process.env.TAMAGUI_TARGET||(console.log('\u26A0\uFE0F Please set process.env.TAMAGUI_TARGET to either "web" or "native"'),process.exit(1));const N=!process.env.npm_package_dependencies_next&&process.env.TAMAGUI_TARGET!=="native"&&process.env.IDENTIFY_TAGS!=="false"&&(process.env.NODE_ENV==="development"||process.env.DEBUG||process.env.IDENTIFY_TAGS);let E=null;function ne(I){return E||(E=(0,$e.loadTamaguiSync)({config:I.config||"tamagui.config.ts",components:I.components||["tamagui"]}))}async function U(I){return E||(E=await(0,$e.loadTamagui)({config:I.config||"tamagui.config.ts",components:I.components||["tamagui"]}))}return{options:{logger:i},cleanupBeforeExit:ce.cleanupBeforeExit,loadTamagui:U,loadTamaguiSync:ne,getTamagui(){return E==null?void 0:E.tamaguiConfig},parseSync:(I,M)=>{const J=ne(M);return qe(J,I,M)},parse:async(I,M)=>{const J=await U(M);return qe(J,I,M)}};function qe({components:I,tamaguiConfig:M},J,Pe){var st;const{config:en="tamagui.config.ts",importsWhitelist:ze=["constants.js"],evaluateVars:Re=!0,sourcePath:C="",onExtractTag:Ct,onStyleRule:ge,getFlattenedNode:Ie,disable:de,disableExtraction:ke,disableExtractInlineMedia:wt,disableExtractVariables:Oe,disableDebugAttr:He,disableExtractFoundComponents:tn,includeExtensions:Ne=[".ts",".tsx",".jsx"],extractStyledDefinitions:Ke=!1,prefixLogs:nn,excludeProps:K,target:ie,...Qe}=Pe;let r=Pe.shouldPrintDebug||!1;if(de===!0||Array.isArray(de)&&de.includes(C))return null;if(!I)throw new Error("Must provide components");if(C&&Ne&&!Ne.some(a=>C.endsWith(a)))return r&&i.info(`Ignoring file due to includeExtensions: ${C}, includeExtensions: ${Ne.join(", ")}`),null;function q(a,l){var y,S;if(!E)throw new Error("Tamagui extractor not loaded yet");return ie==="native"&&a[0]==="$"&&g.mediaQueryConfig[a.slice(1)]?!1:!!((y=l.validStyles)!=null&&y[a]||g.pseudoDescriptors[a]||(S=l.variants)!=null&&S[a]||E!=null&&E.tamaguiConfig.shorthands[a]||a[0]==="$"&&g.mediaQueryConfig[a.slice(1)])}const Ye=ie==="html",Lt=r,_=(0,Ot.timer)(),D={...Pe,sourcePath:C,allLoadedComponents:[...I]};if(!$t&&($t=!0,r&&i.info(["loaded components:",D.allLoadedComponents.map(a=>Object.keys(a.nameToInfo).join(", ")).join(", ")].join(" ")),(st=process.env.DEBUG)!=null&&st.startsWith("tamagui"))){const a=[...D.allLoadedComponents].map(l=>{const y={...l.nameToInfo};for(const S in y)delete y[S].staticConfig.validStyles;return{...l,nameToInfo:y}});i.info(["loaded:",JSON.stringify(a,null,2)].join(`
2
- `))}_.mark("load-tamagui",!!r);const Ze=Object.keys(M.themes)[0],Ce=M.themes[Ze];(!Ce||typeof Ce!="object")&&(console.error("Missing theme, an error occurred when importing your config"),console.log("Got config:",M),console.log("Looking for theme:",Ze),process.exit(0));const Vt=(0,g.proxyThemeVariables)(Ce),et=new Set,pe=new Proxy(Vt,{get(a,l){return Reflect.has(a,l)&&et.forEach(y=>y(String(l))),Reflect.get(a,l)}}),Mt=J.type==="Program"?J.get("body"):J.program.body;Object.keys(I).length===0&&(console.warn("Warning: Tamagui didn't find any valid components (DEBUG=tamagui for more)"),process.env.DEBUG==="tamagui"&&console.log("components",Object.keys(I),I)),r==="verbose"&&i.info(`allLoadedComponent modules ${D.allLoadedComponents.map(a=>a.moduleName).join(", ")}`);let me=!1,we=!1;const tt=[];for(const a of Mt){if(a.type!=="ImportDeclaration")continue;const l="node"in a?a.node:a,y=l.source.value,S=(0,m.isValidImport)(D,y);if(S&&tt.push(l),Ke&&S&&l.specifiers.some(A=>A.local.name==="styled")){me=!0;break}if(S){const A=l.specifiers.map(L=>L.local.name),$=A.some(L=>Boolean((0,m.isValidImport)(D,y,L)||Qt[L]));if(r==="verbose"&&i.info(`import ${A.join(", ")} from ${y} isValidComponent ${$}`),$){me=!0;break}}}if(r&&i.info(`file: ${C} ${JSON.stringify({doesUseValidImport:me,hasImportedTheme:we})}`),!me)return null;function Dt(a){const l=tt.find(y=>y.specifiers.some(S=>S.local.name===a));return l?(0,m.getValidImport)(D,l.source.value,a):null}_.mark("import-check",!!r);let ye=!1;const Le=new Set,nt={},Ft=a=>J.type==="File"?(0,Pt.default)(J,a):J.traverse(a),it=ke===!0||Array.isArray(ke)&&ke.includes(C);let ve=null;const Q={styled:0,flattened:0,optimized:0,modified:0,found:0};if(Ft({Program:{enter(a){ve=a}},CallExpression(a){var rt;if(de||it||Ke===!1||!o.isIdentifier(a.node.callee)||a.node.callee.name!=="styled")return;const l=o.isVariableDeclarator(a.parent)&&o.isIdentifier(a.parent.id)?a.parent.id.name:"unknown",y=a.node.arguments[0];if(!o.isIdentifier(y))return;const S=y.name,A=a.node.arguments[1];if(!S||!A||!o.isObjectExpression(A))return;const $=Dt(S);if(!$)return;const L=new Set([...$.staticConfig.inlineWhenUnflattened||[],...$.staticConfig.inlineProps||[],...$.staticConfig.deoptProps||[],"variants","defaultVariants","fontFamily","name","focusStyle","hoverStyle","pressStyle"]),z=[],R={},se=(0,ce.getStaticBindingsForScope)(a.scope,ze,C,nt,r),oe=Re?(0,te.createEvaluator)({props:D,staticNamespace:se,sourcePath:C,shouldPrintDebug:r}):Ue.evaluateAstNode,Ve=(0,te.createSafeEvaluator)(oe);for(const T of A.properties){if(!o.isObjectProperty(T)||!o.isIdentifier(T.key)||!q(T.key.name,$.staticConfig)||(rt=$.staticConfig.variants)!=null&&rt[T.key.name]||L.has(T.key.name)){z.push(T);continue}const Y=Ve(T.value);Y===ee.FAILED_EVAL?z.push(T):R[T.key.name]=Y}const W=(0,g.getSplitStyles)(R,$.staticConfig,pe,{focus:!1,hover:!1,unmounted:!0,press:!1,pressIn:!1,resolveVariablesAs:"variable",noClassNames:!1},void 0,void 0,void 0,r),ot={...W.classNames};r&&i.info([`Extracted styled(${l})
3
- `,JSON.stringify(R,null,2),`
4
- rulesToInsert:`,W.rulesToInsert.flatMap(T=>T.rules).join(`
5
- `)].join(" ")),A.properties=z;for(const T in ot){if(L.has(T))continue;const Y=ot[T];A.properties.push(o.objectProperty(o.stringLiteral(T),o.stringLiteral(Y)))}if(W.rulesToInsert)for(const{identifier:T,rules:Y}of W.rulesToInsert)ge==null||ge(T,Y);Q.styled++,r&&i.info(`Extracted styled(${l})`)},JSXElement(a){var at;_.mark("jsx-element",!!r);const l=a.node.openingElement,y=l.attributes.map(f=>({...f})),S=(0,m.findComponentName)(a.scope),A=a.node.closingElement;if(o.isJSXMemberExpression(A==null?void 0:A.name)||!o.isJSXIdentifier(l.name))return;const $=a.scope.getBinding(l.name.name);let L="";if($){if(!o.isImportDeclaration($.path.parent)){r&&i.info(" - Binding not import declaration, skip");return}if(L=$.path.parent.source.value,!(0,m.isValidImport)(D,L,$.identifier.name)){r&&i.info(` - Binding not internal import or from components ${$.identifier.name} in ${L}`);return}}const z=(0,m.getValidComponent)(D,L,l.name.name);if(!z||!z.staticConfig){r&&i.info(` - No Tamagui conf on this: ${l.name.name}`);return}const R=l.name.name;Q.found++;const se=`./${(0,Ae.relative)(process.cwd(),C)}`,oe=l.loc?l.loc.start.line+(l.loc.start.line!==l.loc.end.line?`-${l.loc.end.line}`:""):"",Ve=`${se}:${oe}`,W=l.attributes.filter(f=>o.isJSXAttribute(f)&&o.isJSXIdentifier(f.name)&&f.name.name==="debug").map(f=>f.value===null?!0:o.isStringLiteral(f.value)?f.value.value:!1)[0];if(W&&(r=W),r&&(i.info(`
6
- `),i.info(`\x1B[33m%s\x1B[0m ${S} | ${Ve} -------------------`),i.info(["\x1B[1m","\x1B[32m",`<${R} />`,He?"":"\u{1F41B}"].join(" "))),N&&!He&&(Q.modified++,l.attributes.unshift(o.jsxAttribute(o.jsxIdentifier("data-is"),o.stringLiteral(l.name.name))),S&&l.attributes.unshift(o.jsxAttribute(o.jsxIdentifier("data-in"),o.stringLiteral(S))),l.attributes.unshift(o.jsxAttribute(o.jsxIdentifier("data-at"),o.stringLiteral(`${(0,Ae.basename)(se)}:${oe}`)))),!it)try{let dt=function(t){const e=t.node,n={type:"attr",value:e};if(o.isJSXSpreadAttribute(e)){const c=e.argument,u=o.isConditionalExpression(c)?[c.test,c.consequent,c.alternate]:o.isLogicalExpression(c)&&c.operator==="&&"?[c.left,c.right,null]:null;if(u){const[v,P,x]=u;if(!v)throw new Error("no test");return[P,x].some(w=>w&&!Fe(w))?(r&&i.info(`not extractable ${P} ${x}`),n):[...re(v,P)||[],...x&&re(o.unaryExpression("!",v),x)||[]].map(w=>({type:"ternary",value:w}))}}if(o.isJSXSpreadAttribute(e)||!e.name||typeof e.name.name!="string")return r&&i.info(" ! inlining, spread attr"),h.set(`${Math.random()}`,"spread"),n;const s=e.name.name;if(K!=null&&K.has(s))return r&&i.info([" excluding prop",s].join(" ")),null;if(Xt.has(s))return h.set(s,s),r&&i.info([" ! inlining, inline prop",s].join(" ")),n;if(_t.has(s))return F=!0,h.set(s,s),r&&i.info([" ! inlining, deopted prop",s].join(" ")),n;if(Kt[s])return n;if(ue[s])return h.set(s,ue[s]),n;if(s.startsWith("data-"))return n;if(s[0]==="$"&&o.isJSXExpressionContainer(e==null?void 0:e.value)){const c=s.slice(1);if(g.mediaQueryConfig[c]){if(ie==="native"&&(F=!0),wt)return n;const u=e.value.expression;if(!o.isJSXEmptyExpression(u)){const v=re(o.stringLiteral(c),u,{inlineMediaQuery:c});if(v)return v.map(P=>({type:"ternary",value:P}))}}}const[d,O]=(()=>o.isJSXExpressionContainer(e==null?void 0:e.value)?[e.value.expression,t.get("value")]:[e.value,t.get("value")])(),j=()=>{Array.isArray(O)?O.map(c=>c.remove()):O.remove()};if(s==="ref")return r&&i.info([" ! inlining, ref",s].join(" ")),h.set("ref","ref"),n;if(s==="tag")return{type:"attr",value:t.node};if(Oe===!0&&d&&d.type==="StringLiteral"&&d.value[0]==="$")return r&&i.info([` ! inlining, native disable extract: ${s} =`,d.value].join(" ")),h.set(s,!0),n;if(s==="theme")return h.set("theme",n.value),n;const b=he(d);if(!Me[s]&&!q(s,f)){let c=[s],u=null;u=f.propMapper(s,b,pe,f.defaultProps,{resolveVariablesAs:"auto"},void 0,void 0,r),u&&(Array.isArray(u)?(u=Object.fromEntries(u),c=Object.keys(u)):(i.warn("Error expected array but got",u),ye=!0,F=!0)),u&&(Ye&&(u=(0,Be.createDOMProps)(xe?"span":"div",u),delete u.className),c=Object.keys(u));let v=!1;const P=c.map(x=>{const w=u[x];return q(x,f)?{type:"style",value:{[x]:b},name:x,attr:t.node}:Nt.validHTMLAttributes[x]||x.startsWith("aria-")||x.startsWith("data-")||x==="__source"||x==="__self"?n:(r&&i.info(" ! inlining, non-static "+x),v=!0,h.set(x,w),w)});return v?(r&&i.info(` bailing flattening due to attributes ${P}`),n):P}if(b!==ee.FAILED_EVAL)return De.has(s)&&(ct[s]={styleValue:b,attr:n}),q(s,f)?(r&&i.info(` style: ${s} = ${b}`),s in f.defaultProps||ut||(Q.optimized++,ut=!0),{type:"style",value:{[s]:b},name:s,attr:t.node}):(Me[s]&&je.set(s,b),h.set(s,!0),n);if(o.isBinaryExpression(d)){r&&i.info(` binary expression ${s} = ${d}`);const{operator:c,left:u,right:v}=d,P=he(u),x=he(v);if(r&&i.info(` evalBinaryExpression lVal ${String(P)}, rVal ${String(x)}`),P!==ee.FAILED_EVAL&&o.isConditionalExpression(v)){const w=fe(c,u,v);if(w)return w}if(x!==ee.FAILED_EVAL&&o.isConditionalExpression(u)){const w=fe(c,v,u);if(w)return w}return r&&i.info(" evalBinaryExpression cant extract"),h.set(s,!0),n}const X=St(d);if(X)return r==="verbose"&&i.info(` static conditional ${s} ${d}`),{type:"ternary",value:X};const le=Wt(d);if(le)return r==="verbose"&&i.info(` static ternary ${s} = ${d}`),{type:"ternary",value:le};return h.set(s,!0),r&&i.info(` ! inline no match ${s} ${d}`),n;function fe(c,u,v){if(St(v)){const P=B(o.binaryExpression(c,u,v.alternate)),x=B(o.binaryExpression(c,u,v.consequent));return r&&i.info([" binaryConditional",v.test,x,P].join(" ")),{type:"ternary",value:{test:v.test,remove:j,alternate:{[s]:P},consequent:{[s]:x}}}}return null}function St(c){if(o.isConditionalExpression(c))try{const u=B(c.alternate),v=B(c.consequent);if(r){const P=c.test.type;i.info([" static ternary",P,v,u].join(" "))}return{test:c.test,remove:j,consequent:{[s]:v},alternate:{[s]:u}}}catch(u){r&&i.info([" cant eval ternary",u.message].join(" "))}return null}function Wt(c){if(o.isLogicalExpression(c)&&c.operator==="&&")try{const u=B(c.right);return r&&i.info([" staticLogical",c.left,s,u].join(" ")),{test:c.left,remove:j,consequent:{[s]:u},alternate:null}}catch(u){r&&i.info([" cant static eval logical",u].join(" "))}return null}},Fe=function(t){return o.isObjectExpression(t)&&t.properties.every(e=>{if(!o.isObjectProperty(e))return i.info(["not object prop",e].join(" ")),!1;const n=e.key.name;return!q(n,f)&&n!=="tag"?(r&&i.info([" not a valid style prop!",n].join(" ")),!1):!0})},re=function(t,e,n={}){if(!e)return null;if(!Fe(e))throw new Error("not extractable");return e.properties.flatMap(s=>{if(!o.isObjectProperty(s))throw new Error("expected object property");if(o.isIdentifier(s.key)){const j=s.key.name,b=j.slice(1);if(j[0]==="$"&&g.mediaQueryConfig[b])if(o.isExpression(s.value)){const le=re(o.stringLiteral(b),s.value,{inlineMediaQuery:b});if(le)return le.map(fe=>({...n,...fe,test:o.logicalExpression("&&",fe.test,t)}));i.info(["\u26A0\uFE0F no ternaries?",s].join(" "))}else i.info(["\u26A0\uFE0F not expression",s].join(" "))}if(o.isConditionalExpression(s.value)){const[j,b]=[o.objectExpression([o.objectProperty(s.key,s.value.consequent)]),o.objectExpression([o.objectProperty(s.key,s.value.alternate)])].map(X=>B(X));return[We({remove(){},...n,test:o.logicalExpression("&&",t,s.value.test),consequent:j,alternate:null}),We({...n,test:o.logicalExpression("&&",t,o.unaryExpression("!",s.value.test)),consequent:b,alternate:null,remove(){}})]}const d=o.objectExpression([o.objectProperty(s.key,s.value)]),O=B(d);return We({remove(){},...n,test:t,consequent:O,alternate:null})})},bt=function(t){var s;const e={},n={};for(const d in t)(s=f.variants)!=null&&s[d]?e[d]=t[d]:n[d]=t[d];return{variants:e,styles:n}},ht=function(t){const{variants:e,styles:n}=bt(t);return{...(0,g.expandStyles)(n),...e}},jt=function(t,e){for(const n in e)g.pseudoDescriptors[n]?(t[n]=t[n]||{},Object.assign(t[n],e[n])):t[n]=e[n]};var ot=dt,rt=Fe,T=re,Y=bt,mn=ht,yn=jt;const{staticConfig:f}=z,Me=f.variants||{},xe=f.isText||!1,Jt=(f==null?void 0:f.validStyles)??{};let lt=f.defaultProps.tag??(xe?"span":"div");a.get("openingElement").get("attributes").forEach(t=>{const e=t.node;if(o.isJSXSpreadAttribute(e)||e.name.name!=="tag")return;const n=e.value;o.isStringLiteral(n)&&(lt=n.value)});const be=Ie==null?void 0:Ie({isTextView:xe,tag:lt}),Xt=new Set(["dataSet",...Qe.inlineProps||[],...f.inlineProps||[]]),_t=new Set(["animation",...Qe.deoptProps||[],...f.deoptProps||[]]),De=new Set([...f.inlineWhenUnflattened||[]]),ft=(0,ce.getStaticBindingsForScope)(a.scope,ze,C,nt,r),B=Re?(0,te.createEvaluator)({props:D,staticNamespace:ft,sourcePath:C,traversePath:a,shouldPrintDebug:r}):Ue.evaluateAstNode,he=(0,te.createSafeEvaluator)(B);if(r&&i.info(` staticNamespace ${Object.keys(ft).join(", ")}`),ye)return;_.mark("jsx-element-flattened",!!r);let p=[],F=!1;const h=new Map,je=new Map;let ut=!1;const ct={};if(p=a.get("openingElement").get("attributes").flatMap(t=>{var e;try{const n=dt(t);return _.mark("jsx-element-evaluate-attr",!!r),n||t.remove(),n}catch(n){return r&&(i.info(["Recoverable error extracting attribute",n.message,r==="verbose"?n.stack:""].join(" ")),r==="verbose"&&i.info(`node ${(e=t.node)==null?void 0:e.type}`)),h.set(`${Math.random()}`,"spread"),{type:"attr",value:t.node}}}).flat(4).filter(m.isPresent),r&&i.info([` - attrs (before):
7
- `,(0,V.logLines)(p.map(m.attrStr).join(", "))].join(" ")),ye||F){r&&i.info([" avoid optimizing:",{couldntParse:ye,shouldDeopt:F}].join(" ")),l.attributes=y;return}const pt=(0,gt.findTopmostFunction)(a);pt&&Le.add(pt);let ae=[];p=p.reduce((t,e)=>{const n=p[p.indexOf(e)+1];if(e.type==="ternary"&&ae.push(e.value),(!n||n.type!=="ternary")&&ae.length){const s=(0,It.normalizeTernaries)(ae).map(({alternate:d,consequent:O,...j})=>({type:"ternary",value:{...j,alternate:d||null,consequent:O||null}}));try{return[...t,...s]}finally{r&&i.info(` normalizeTernaries (${ae.length} => ${s.length})`),ae=[]}}return e.type==="ternary"||t.push(e),t},[]).flat();const Ee=p.some(t=>t.type==="attr"&&o.isJSXSpreadAttribute(t.value)),mt=!Ee&&(l.selfClosing||a.node.children&&a.node.children.every(t=>t.type==="JSXText")),Je=h.get("theme");ie!=="native"&&h.delete("theme");for(const[t]of[...h]){const e=((at=f.variants)==null?void 0:at[t])&&je.has(t);(ue[t]||e)&&h.delete(t)}const yt=h.size===0;let k=Boolean(be&&!F&&yt&&!Ee&&f.neverFlatten!==!0&&(f.neverFlatten==="jsx"?mt:!0));const vt=k&&Je,Xe=new Set;if(Oe&&et.add(t=>{k=!1,Xe.add(t),r==="verbose"&&i.info([" ! accessing theme key, avoid flatten",t].join(" "))}),r)try{i.info([" flatten?",k,(0,m.objToStr)({hasSpread:Ee,shouldDeopt:F,canFlattenProps:yt,shouldWrapTheme:vt,hasOnlyStringChildren:mt}),"inlined",h.size,[...h]].join(" "))}catch{}if(k&&vt&&(ve?(r&&i.info([" - wrapping theme",Je].join(" ")),p=p.filter(t=>!(t.type==="attr"&&o.isJSXAttribute(t.value)&&t.value.name.name==="theme")),we||(we=!0,ve.node.body.push(o.importDeclaration([o.importSpecifier(o.identifier("_TamaguiTheme"),o.identifier("Theme"))],o.stringLiteral("@tamagui/core")))),a.replaceWith(o.jsxElement(o.jsxOpeningElement(o.jsxIdentifier("_TamaguiTheme"),[o.jsxAttribute(o.jsxIdentifier("name"),Je.value)]),o.jsxClosingElement(o.jsxIdentifier("_TamaguiTheme")),[a.node]))):console.warn(`No program path found, avoiding importing flattening / importing theme in ${C}`)),k){const t=Object.keys(f.defaultProps).flatMap(e=>{if(!q(e,f))return[];const n=f.defaultProps[e],s=M.shorthands[e]||e;if(n===void 0){i.warn(`\u26A0\uFE0F Error evaluating default style for component, prop ${e} ${n}`),F=!0;return}return{type:"style",name:s,value:{[s]:n}}});t.length&&(p=[...t,...p])}if(F||!k){r&&i.info(`Deopting ${F} ${k}`),l.attributes=y;return}r&&i.info([` - attrs (flattened):
8
- `,(0,V.logLines)(p.map(m.attrStr).join(", "))].join(" "));const xt={noClassNames:!1,focus:!1,hover:!1,unmounted:!1,press:!1,pressIn:!1};let G={};for(const t in p){const e=p[t];if(e.type==="style"){G={...G,...ht(e.value)};continue}if(e.type==="attr"){if(o.isJSXSpreadAttribute(e.value)||!o.isJSXIdentifier(e.value.name))continue;const n=e.value.name.name,s=he(e.value.value||o.booleanLiteral(!0));s!==ee.FAILED_EVAL&&(G={...G,[n]:s})}}const H={};for(const t in f.defaultProps)t in G||(H[t]=f.defaultProps[t]);for(const t in G)H[t]=G[t];p=p.reduce((t,e)=>{if(!e)return t;if(e.type==="attr"&&!o.isJSXSpreadAttribute(e.value)&&k){const O=e.value.name.name;if(typeof O=="string"){if(O==="tag")return t;if(Me[O]&&je.has(O)){let j=Object.fromEntries(f.propMapper(O,je.get(O),pe,H,{...xt,resolveVariablesAs:"auto"},void 0,void 0,r)||[]);if(j&&Ye){const b=j.className;j=(0,Be.createDOMProps)(xe?"span":"div",j),j.className=b}r&&i.info([" - expanded variant",O,j].join(" "));for(const b in j){const X=j[b];q(b,f)?t.push({type:"style",value:{[b]:X},name:b,attr:e.value}):t.push({type:"attr",value:o.jsxAttribute(o.jsxIdentifier(b),o.jsxExpressionContainer(typeof X=="string"?o.stringLiteral(X):(0,Ge.literalToAst)(X)))})}}}}if(e.type!=="style")return t.push(e),t;let n=Object.keys(e.value)[0];const s=e.value[n],d=M.shorthands[n];return d&&(e.value={[d]:s},n=d),Oe&&s[0]==="$"&&(Xe.has(n)||Xe.has(d))?(r&&i.info([` keeping variable inline: ${n} =`,s].join(" ")),t.push({type:"attr",value:o.jsxAttribute(o.jsxIdentifier(n),o.jsxExpressionContainer(o.stringLiteral(s)))}),t):(t.push(e),t)},[]),_.mark("jsx-element-expanded",!!r),r&&i.info([` - attrs (expanded):
9
- `,(0,V.logLines)(p.map(m.attrStr).join(", "))].join(" "));let Z=null;p=p.reduce((t,e)=>{if(e.type==="style"){const n=Object.keys(e.value)[0],s=e.value[n];if(!k&&!Jt[n]&&!g.pseudoDescriptors[n]&&!(n.startsWith("data-")||n.startsWith("aria-")))return r&&i.info([" - keeping as non-style",n].join(" ")),Z=e,t.push({type:"attr",value:o.jsxAttribute(o.jsxIdentifier(n),o.jsxExpressionContainer(typeof s=="string"?o.stringLiteral(s):(0,Ge.literalToAst)(s)))}),t.push(e),t;if((Z==null?void 0:Z.type)==="style")return jt(Z.value,e.value),t}return Z=e,t.push(e),t},[]),r&&(i.info([` - attrs (combined \u{1F500}):
10
- `,(0,V.logLines)(p.map(m.attrStr).join(", "))].join(" ")),i.info([` - defaultProps:
11
- `,(0,V.logLines)((0,m.objToStr)(f.defaultProps))].join(" ")),i.info([` - foundStaticProps:
12
- `,(0,V.logLines)((0,m.objToStr)(G))].join(" ")),i.info([` - completeProps:
13
- `,(0,V.logLines)((0,m.objToStr)(H))].join(" ")));const Se=(t,e="")=>{if(!t||!Object.keys(t).length)return r&&i.info([" getStyles() no props"].join(" ")),{};if(K&&K.size)for(const n in t)K.has(n)&&(r&&i.info([" delete excluded",n].join(" ")),delete t[n]);try{const n=(0,g.getSplitStyles)(t,f,pe,{...xt,fallbackProps:H},void 0,void 0,void 0,W),s={...n.style,...n.pseudos};return r==="verbose"&&(i.info(` getStyles ${e} (props in): ${Object.keys(t)}`),i.info(` getStyles ${e} (outStyle): ${Object.keys(s)}`)),s}catch(n){return i.info(["error",n.message,n.stack].join(" ")),{}}};if(!Se(H,"completeStyles"))throw new Error("Impossible, no styles");let _e=null;for(const t of p)try{switch(t.type){case"ternary":{const e=Se(t.value.alternate,"ternary.alternate"),n=Se(t.value.consequent,"ternary.consequent");e&&(t.value.alternate=e),n&&(t.value.consequent=n),r&&i.info([" => tern ",(0,m.attrStr)(t)].join(" "));continue}case"style":{const e=Se(t.value,"style");e&&(t.value=e),r&&i.info([" * styles (in)",(0,V.logLines)((0,m.objToStr)(t.value))].join(" ")),r&&i.info([" * styles (out)",(0,V.logLines)((0,m.objToStr)(e))].join(" "));continue}}}catch(e){_e=e}if(r&&i.info([` - attrs (ternaries/combined):
14
- `,(0,V.logLines)(p.map(m.attrStr).join(", "))].join(" ")),_.mark("jsx-element-styles",!!r),_e)return i.info([" \u26A0\uFE0F postprocessing error, deopt",_e].join(" ")),l.attributes=y,null;const Et=new Set;for(let t=p.length-1;t>=0;t--){const e=p[t];if(k&&e.type==="attr"&&o.isJSXAttribute(e.value)&&o.isJSXIdentifier(e.value.name)){const n=e.value.name.name;ue[n]&&(e.value.name.name=ue[n])}if(e.type==="style")for(const n in e.value)Et.has(n)?(r&&i.info([` >> delete existing ${n}`].join(" ")),delete e.value[n]):Et.add(n)}if(!k&&De.size){for(const[t,e]of p.entries())if(e.type==="style")for(const n in e.value){if(!De.has(n))continue;const s=ct[n];s?(delete e.value[n],p.splice(t-1,0,s.attr)):delete e.value[n]}}if(k&&(r&&i.info([" [\u2705] flattening",R,be].join(" ")),l.name.name=be,Q.flattened++,A&&(A.name.name=be)),!k&&ie==="native")return r&&i.info("Disabled flattening except for simple cases on native for now"),l.attributes=y,null;r&&(i.info([` - inlined props (${h.size}):`,F?" deopted":"",Ee?" has spread":"",f.neverFlatten?"neverFlatten":""].join(" ")),i.info(` - shouldFlatten/isFlattened: ${k}`),i.info(` - attrs (end):
15
- ${(0,V.logLines)(p.map(m.attrStr).join(", "))}`)),Ct({parserProps:D,attrs:p,node:l,lineNumbers:oe,filePath:se,attemptEval:B,jsxPath:a,originalNodeName:R,isFlattened:k,programPath:ve,completeProps:H,staticConfig:f})}catch(f){l.attributes=y,console.error(`err: ${f}`)}finally{W&&(r=Lt)}}}),_.mark("jsx-done",!!r),Le.size){const a=Array.from(Le);r&&i.info(` [\u{1FA9D}] hook check ${a.length}`);for(const l of a)(0,kt.removeUnusedHooks)(l,r)}return _.done(r==="verbose"),Q}}0&&(module.exports={createExtractor});
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var createExtractor_exports = {};
30
+ __export(createExtractor_exports, {
31
+ createExtractor: () => createExtractor
32
+ });
33
+ module.exports = __toCommonJS(createExtractor_exports);
34
+ var import_path = require("path");
35
+ var import_traverse = __toESM(require("@babel/traverse"));
36
+ var t = __toESM(require("@babel/types"));
37
+ var import_core_node = require("@tamagui/core-node");
38
+ var import_react_native_web_internals = require("react-native-web-internals");
39
+ var import_constants = require("../constants.js");
40
+ var import_createEvaluator = require("./createEvaluator.js");
41
+ var import_evaluateAstNode = require("./evaluateAstNode.js");
42
+ var import_extractHelpers = require("./extractHelpers.js");
43
+ var import_findTopmostFunction = require("./findTopmostFunction.js");
44
+ var import_getStaticBindingsForScope = require("./getStaticBindingsForScope.js");
45
+ var import_literalToAst = require("./literalToAst.js");
46
+ var import_loadTamagui = require("./loadTamagui.js");
47
+ var import_logLines = require("./logLines.js");
48
+ var import_normalizeTernaries = require("./normalizeTernaries.js");
49
+ var import_removeUnusedHooks = require("./removeUnusedHooks.js");
50
+ var import_timer = require("./timer.js");
51
+ var import_validHTMLAttributes = require("./validHTMLAttributes.js");
52
+ const UNTOUCHED_PROPS = {
53
+ key: true,
54
+ style: true,
55
+ className: true
56
+ };
57
+ const INLINE_EXTRACTABLE = {
58
+ ref: "ref",
59
+ key: "key",
60
+ ...process.env.TAMAGUI_TARGET === "web" && {
61
+ onPress: "onClick",
62
+ onHoverIn: "onMouseEnter",
63
+ onHoverOut: "onMouseLeave",
64
+ onPressIn: "onMouseDown",
65
+ onPressOut: "onMouseUp"
66
+ }
67
+ };
68
+ const validHooks = {
69
+ useMedia: true,
70
+ useTheme: true
71
+ };
72
+ const isAttr = (x) => x.type === "attr";
73
+ const createTernary = (x) => x;
74
+ let hasLoggedBaseInfo = false;
75
+ function createExtractor({ logger = console } = { logger: console }) {
76
+ if (!process.env.TAMAGUI_TARGET) {
77
+ console.log('\u26A0\uFE0F Please set process.env.TAMAGUI_TARGET to either "web" or "native"');
78
+ process.exit(1);
79
+ }
80
+ const shouldAddDebugProp = (
81
+ // really basic disable this for next.js because it messes with ssr
82
+ !process.env.npm_package_dependencies_next && process.env.TAMAGUI_TARGET !== "native" && process.env.IDENTIFY_TAGS !== "false" && (process.env.NODE_ENV === "development" || process.env.DEBUG || process.env.IDENTIFY_TAGS)
83
+ );
84
+ let projectInfo = null;
85
+ function loadSync(props) {
86
+ return projectInfo || (projectInfo = (0, import_loadTamagui.loadTamaguiSync)({
87
+ config: props.config || "tamagui.config.ts",
88
+ components: props.components || ["tamagui"]
89
+ }));
90
+ }
91
+ async function load(props) {
92
+ return projectInfo || (projectInfo = await (0, import_loadTamagui.loadTamagui)({
93
+ config: props.config || "tamagui.config.ts",
94
+ components: props.components || ["tamagui"]
95
+ }));
96
+ }
97
+ return {
98
+ options: {
99
+ logger
100
+ },
101
+ cleanupBeforeExit: import_getStaticBindingsForScope.cleanupBeforeExit,
102
+ loadTamagui: load,
103
+ loadTamaguiSync: loadSync,
104
+ getTamagui() {
105
+ return projectInfo == null ? void 0 : projectInfo.tamaguiConfig;
106
+ },
107
+ parseSync: (f, props) => {
108
+ const projectInfo2 = loadSync(props);
109
+ return parseWithConfig(projectInfo2, f, props);
110
+ },
111
+ parse: async (f, props) => {
112
+ const projectInfo2 = await load(props);
113
+ return parseWithConfig(projectInfo2, f, props);
114
+ }
115
+ };
116
+ function parseWithConfig({ components, tamaguiConfig }, fileOrPath, options) {
117
+ var _a;
118
+ const {
119
+ config = "tamagui.config.ts",
120
+ importsWhitelist = ["constants.js"],
121
+ evaluateVars = true,
122
+ sourcePath = "",
123
+ onExtractTag,
124
+ onStyleRule,
125
+ getFlattenedNode,
126
+ disable,
127
+ disableExtraction,
128
+ disableExtractInlineMedia,
129
+ disableExtractVariables,
130
+ disableDebugAttr,
131
+ disableExtractFoundComponents,
132
+ includeExtensions = [".ts", ".tsx", ".jsx"],
133
+ extractStyledDefinitions = false,
134
+ prefixLogs,
135
+ excludeProps,
136
+ target,
137
+ ...restProps
138
+ } = options;
139
+ let shouldPrintDebug = options.shouldPrintDebug || false;
140
+ if (disable === true || Array.isArray(disable) && disable.includes(sourcePath)) {
141
+ return null;
142
+ }
143
+ if (!components) {
144
+ throw new Error(`Must provide components`);
145
+ }
146
+ if (sourcePath && includeExtensions && !includeExtensions.some((ext) => sourcePath.endsWith(ext))) {
147
+ if (shouldPrintDebug) {
148
+ logger.info(
149
+ `Ignoring file due to includeExtensions: ${sourcePath}, includeExtensions: ${includeExtensions.join(
150
+ ", "
151
+ )}`
152
+ );
153
+ }
154
+ return null;
155
+ }
156
+ function isValidStyleKey(name, staticConfig) {
157
+ var _a2, _b;
158
+ if (!projectInfo) {
159
+ throw new Error(`Tamagui extractor not loaded yet`);
160
+ }
161
+ if (target === "native" && name[0] === "$" && import_core_node.mediaQueryConfig[name.slice(1)]) {
162
+ return false;
163
+ }
164
+ return !!(!!((_a2 = staticConfig.validStyles) == null ? void 0 : _a2[name]) || !!import_core_node.pseudoDescriptors[name] || // dont disable variants or else you lose many things flattening
165
+ ((_b = staticConfig.variants) == null ? void 0 : _b[name]) || (projectInfo == null ? void 0 : projectInfo.tamaguiConfig.shorthands[name]) || (name[0] === "$" ? !!import_core_node.mediaQueryConfig[name.slice(1)] : false));
166
+ }
167
+ const isTargetingHTML = target === "html";
168
+ const ogDebug = shouldPrintDebug;
169
+ const tm = (0, import_timer.timer)();
170
+ const propsWithFileInfo = {
171
+ ...options,
172
+ sourcePath,
173
+ allLoadedComponents: [...components]
174
+ };
175
+ if (!hasLoggedBaseInfo) {
176
+ hasLoggedBaseInfo = true;
177
+ if (shouldPrintDebug) {
178
+ logger.info(
179
+ [
180
+ "loaded components:",
181
+ propsWithFileInfo.allLoadedComponents.map((comp) => Object.keys(comp.nameToInfo).join(", ")).join(", ")
182
+ ].join(" ")
183
+ );
184
+ }
185
+ if ((_a = process.env.DEBUG) == null ? void 0 : _a.startsWith("tamagui")) {
186
+ const next = [...propsWithFileInfo.allLoadedComponents].map((info) => {
187
+ const nameToInfo = { ...info.nameToInfo };
188
+ for (const key in nameToInfo) {
189
+ delete nameToInfo[key].staticConfig.validStyles;
190
+ }
191
+ return { ...info, nameToInfo };
192
+ });
193
+ logger.info(["loaded:", JSON.stringify(next, null, 2)].join("\n"));
194
+ }
195
+ }
196
+ tm.mark("load-tamagui", !!shouldPrintDebug);
197
+ const firstThemeName = Object.keys(tamaguiConfig.themes)[0];
198
+ const firstTheme = tamaguiConfig.themes[firstThemeName];
199
+ if (!firstTheme || typeof firstTheme !== "object") {
200
+ console.error(`Missing theme, an error occurred when importing your config`);
201
+ console.log(`Got config:`, tamaguiConfig);
202
+ console.log(`Looking for theme:`, firstThemeName);
203
+ process.exit(0);
204
+ }
205
+ const proxiedTheme = (0, import_core_node.proxyThemeVariables)(firstTheme);
206
+ const themeAccessListeners = /* @__PURE__ */ new Set();
207
+ const defaultTheme = new Proxy(proxiedTheme, {
208
+ get(target2, key) {
209
+ if (Reflect.has(target2, key)) {
210
+ themeAccessListeners.forEach((cb) => cb(String(key)));
211
+ }
212
+ return Reflect.get(target2, key);
213
+ }
214
+ });
215
+ const body = fileOrPath.type === "Program" ? fileOrPath.get("body") : fileOrPath.program.body;
216
+ if (Object.keys(components).length === 0) {
217
+ console.warn(
218
+ `Warning: Tamagui didn't find any valid components (DEBUG=tamagui for more)`
219
+ );
220
+ if (process.env.DEBUG === "tamagui") {
221
+ console.log(`components`, Object.keys(components), components);
222
+ }
223
+ }
224
+ if (shouldPrintDebug === "verbose") {
225
+ logger.info(
226
+ `allLoadedComponent modules ${propsWithFileInfo.allLoadedComponents.map((k) => k.moduleName).join(", ")}`
227
+ );
228
+ }
229
+ let doesUseValidImport = false;
230
+ let hasImportedTheme = false;
231
+ const importDeclarations = [];
232
+ for (const bodyPath of body) {
233
+ if (bodyPath.type !== "ImportDeclaration")
234
+ continue;
235
+ const node = "node" in bodyPath ? bodyPath.node : bodyPath;
236
+ const moduleName = node.source.value;
237
+ const valid = (0, import_extractHelpers.isValidImport)(propsWithFileInfo, moduleName);
238
+ if (valid) {
239
+ importDeclarations.push(node);
240
+ }
241
+ if (extractStyledDefinitions) {
242
+ if (valid) {
243
+ if (node.specifiers.some((specifier) => specifier.local.name === "styled")) {
244
+ doesUseValidImport = true;
245
+ break;
246
+ }
247
+ }
248
+ }
249
+ if (valid) {
250
+ const names = node.specifiers.map((specifier) => specifier.local.name);
251
+ const isValidComponent = names.some(
252
+ (name) => Boolean((0, import_extractHelpers.isValidImport)(propsWithFileInfo, moduleName, name) || validHooks[name])
253
+ );
254
+ if (shouldPrintDebug === "verbose") {
255
+ logger.info(
256
+ `import ${names.join(
257
+ ", "
258
+ )} from ${moduleName} isValidComponent ${isValidComponent}`
259
+ );
260
+ }
261
+ if (isValidComponent) {
262
+ doesUseValidImport = true;
263
+ break;
264
+ }
265
+ }
266
+ }
267
+ if (shouldPrintDebug) {
268
+ logger.info(
269
+ `file: ${sourcePath} ${JSON.stringify({ doesUseValidImport, hasImportedTheme })}`
270
+ );
271
+ }
272
+ if (!doesUseValidImport) {
273
+ return null;
274
+ }
275
+ function getValidImportedComponent(componentName) {
276
+ const importDeclaration = importDeclarations.find(
277
+ (dec) => dec.specifiers.some((spec) => spec.local.name === componentName)
278
+ );
279
+ if (!importDeclaration) {
280
+ return null;
281
+ }
282
+ return (0, import_extractHelpers.getValidImport)(
283
+ propsWithFileInfo,
284
+ importDeclaration.source.value,
285
+ componentName
286
+ );
287
+ }
288
+ tm.mark("import-check", !!shouldPrintDebug);
289
+ let couldntParse = false;
290
+ const modifiedComponents = /* @__PURE__ */ new Set();
291
+ const bindingCache = {};
292
+ const callTraverse = (a) => {
293
+ return fileOrPath.type === "File" ? (0, import_traverse.default)(fileOrPath, a) : fileOrPath.traverse(a);
294
+ };
295
+ const shouldDisableExtraction = disableExtraction === true || Array.isArray(disableExtraction) && disableExtraction.includes(sourcePath);
296
+ let programPath = null;
297
+ const res = {
298
+ styled: 0,
299
+ flattened: 0,
300
+ optimized: 0,
301
+ modified: 0,
302
+ found: 0
303
+ };
304
+ callTraverse({
305
+ // @ts-ignore
306
+ Program: {
307
+ enter(path) {
308
+ programPath = path;
309
+ }
310
+ },
311
+ // styled() calls
312
+ CallExpression(path) {
313
+ var _a2;
314
+ if (disable || shouldDisableExtraction || extractStyledDefinitions === false) {
315
+ return;
316
+ }
317
+ if (!t.isIdentifier(path.node.callee) || path.node.callee.name !== "styled") {
318
+ return;
319
+ }
320
+ const variableName = t.isVariableDeclarator(path.parent) && t.isIdentifier(path.parent.id) ? path.parent.id.name : "unknown";
321
+ const parentNode = path.node.arguments[0];
322
+ if (!t.isIdentifier(parentNode)) {
323
+ return;
324
+ }
325
+ const parentName = parentNode.name;
326
+ const definition = path.node.arguments[1];
327
+ if (!parentName || !definition || !t.isObjectExpression(definition)) {
328
+ return;
329
+ }
330
+ const Component = getValidImportedComponent(parentName);
331
+ if (!Component) {
332
+ return;
333
+ }
334
+ const componentSkipProps = /* @__PURE__ */ new Set([
335
+ ...Component.staticConfig.inlineWhenUnflattened || [],
336
+ ...Component.staticConfig.inlineProps || [],
337
+ ...Component.staticConfig.deoptProps || [],
338
+ // for now skip variants, will return to them
339
+ "variants",
340
+ "defaultVariants",
341
+ // skip fontFamily its basically a "variant", important for theme use to be value always
342
+ "fontFamily",
343
+ "name",
344
+ "focusStyle",
345
+ "hoverStyle",
346
+ "pressStyle"
347
+ ]);
348
+ const skipped = [];
349
+ const styles = {};
350
+ const staticNamespace = (0, import_getStaticBindingsForScope.getStaticBindingsForScope)(
351
+ path.scope,
352
+ importsWhitelist,
353
+ sourcePath,
354
+ bindingCache,
355
+ shouldPrintDebug
356
+ );
357
+ const attemptEval = !evaluateVars ? import_evaluateAstNode.evaluateAstNode : (0, import_createEvaluator.createEvaluator)({
358
+ props: propsWithFileInfo,
359
+ staticNamespace,
360
+ sourcePath,
361
+ shouldPrintDebug
362
+ });
363
+ const attemptEvalSafe = (0, import_createEvaluator.createSafeEvaluator)(attemptEval);
364
+ for (const property of definition.properties) {
365
+ if (!t.isObjectProperty(property) || !t.isIdentifier(property.key) || !isValidStyleKey(property.key.name, Component.staticConfig) || // skip variants
366
+ ((_a2 = Component.staticConfig.variants) == null ? void 0 : _a2[property.key.name]) || componentSkipProps.has(property.key.name)) {
367
+ skipped.push(property);
368
+ continue;
369
+ }
370
+ const out2 = attemptEvalSafe(property.value);
371
+ if (out2 === import_constants.FAILED_EVAL) {
372
+ skipped.push(property);
373
+ } else {
374
+ styles[property.key.name] = out2;
375
+ }
376
+ }
377
+ const out = (0, import_core_node.getSplitStyles)(
378
+ styles,
379
+ Component.staticConfig,
380
+ defaultTheme,
381
+ {
382
+ focus: false,
383
+ hover: false,
384
+ unmounted: true,
385
+ press: false,
386
+ pressIn: false,
387
+ resolveVariablesAs: "variable",
388
+ noClassNames: false
389
+ },
390
+ void 0,
391
+ void 0,
392
+ void 0,
393
+ shouldPrintDebug
394
+ );
395
+ const classNames = {
396
+ ...out.classNames
397
+ };
398
+ if (shouldPrintDebug) {
399
+ logger.info([`Extracted styled(${variableName})
400
+ `, JSON.stringify(styles, null, 2), "\n rulesToInsert:", out.rulesToInsert.flatMap((rule) => rule.rules).join("\n")].join(" "));
401
+ }
402
+ definition.properties = skipped;
403
+ for (const cn in classNames) {
404
+ if (componentSkipProps.has(cn)) {
405
+ continue;
406
+ }
407
+ const val = classNames[cn];
408
+ definition.properties.push(
409
+ t.objectProperty(t.stringLiteral(cn), t.stringLiteral(val))
410
+ );
411
+ }
412
+ if (out.rulesToInsert) {
413
+ for (const { identifier, rules } of out.rulesToInsert) {
414
+ onStyleRule == null ? void 0 : onStyleRule(identifier, rules);
415
+ }
416
+ }
417
+ res.styled++;
418
+ if (shouldPrintDebug) {
419
+ logger.info(`Extracted styled(${variableName})`);
420
+ }
421
+ },
422
+ JSXElement(traversePath) {
423
+ var _a2;
424
+ tm.mark("jsx-element", !!shouldPrintDebug);
425
+ const node = traversePath.node.openingElement;
426
+ const ogAttributes = node.attributes.map((attr) => ({ ...attr }));
427
+ const componentName = (0, import_extractHelpers.findComponentName)(traversePath.scope);
428
+ const closingElement = traversePath.node.closingElement;
429
+ if (t.isJSXMemberExpression(closingElement == null ? void 0 : closingElement.name) || !t.isJSXIdentifier(node.name)) {
430
+ return;
431
+ }
432
+ const binding = traversePath.scope.getBinding(node.name.name);
433
+ let modulePath = "";
434
+ if (binding) {
435
+ if (!t.isImportDeclaration(binding.path.parent)) {
436
+ if (shouldPrintDebug) {
437
+ logger.info(` - Binding not import declaration, skip`);
438
+ }
439
+ return;
440
+ }
441
+ modulePath = binding.path.parent.source.value;
442
+ if (!(0, import_extractHelpers.isValidImport)(propsWithFileInfo, modulePath, binding.identifier.name)) {
443
+ if (shouldPrintDebug) {
444
+ logger.info(
445
+ ` - Binding not internal import or from components ${binding.identifier.name} in ${modulePath}`
446
+ );
447
+ }
448
+ return;
449
+ }
450
+ }
451
+ const component = (0, import_extractHelpers.getValidComponent)(propsWithFileInfo, modulePath, node.name.name);
452
+ if (!component || !component.staticConfig) {
453
+ if (shouldPrintDebug) {
454
+ logger.info(` - No Tamagui conf on this: ${node.name.name}`);
455
+ }
456
+ return;
457
+ }
458
+ const originalNodeName = node.name.name;
459
+ res.found++;
460
+ const filePath = `./${(0, import_path.relative)(process.cwd(), sourcePath)}`;
461
+ const lineNumbers = node.loc ? node.loc.start.line + (node.loc.start.line !== node.loc.end.line ? `-${node.loc.end.line}` : "") : "";
462
+ const codePosition = `${filePath}:${lineNumbers}`;
463
+ const debugPropValue = node.attributes.filter(
464
+ (n) => t.isJSXAttribute(n) && t.isJSXIdentifier(n.name) && n.name.name === "debug"
465
+ ).map((n) => {
466
+ if (n.value === null)
467
+ return true;
468
+ if (t.isStringLiteral(n.value))
469
+ return n.value.value;
470
+ return false;
471
+ })[0];
472
+ if (debugPropValue) {
473
+ shouldPrintDebug = debugPropValue;
474
+ }
475
+ if (shouldPrintDebug) {
476
+ logger.info("\n");
477
+ logger.info(
478
+ `\x1B[33m%s\x1B[0m ${componentName} | ${codePosition} -------------------`
479
+ );
480
+ logger.info(["\x1B[1m", "\x1B[32m", `<${originalNodeName} />`, disableDebugAttr ? "" : "\u{1F41B}"].join(" "));
481
+ }
482
+ if (shouldAddDebugProp && !disableDebugAttr) {
483
+ res.modified++;
484
+ node.attributes.unshift(
485
+ t.jsxAttribute(t.jsxIdentifier("data-is"), t.stringLiteral(node.name.name))
486
+ );
487
+ if (componentName) {
488
+ node.attributes.unshift(
489
+ t.jsxAttribute(t.jsxIdentifier("data-in"), t.stringLiteral(componentName))
490
+ );
491
+ }
492
+ node.attributes.unshift(
493
+ t.jsxAttribute(
494
+ t.jsxIdentifier("data-at"),
495
+ t.stringLiteral(`${(0, import_path.basename)(filePath)}:${lineNumbers}`)
496
+ )
497
+ );
498
+ }
499
+ if (shouldDisableExtraction) {
500
+ return;
501
+ }
502
+ try {
503
+ let evaluateAttribute2 = function(path) {
504
+ const attribute = path.node;
505
+ const attr = { type: "attr", value: attribute };
506
+ if (t.isJSXSpreadAttribute(attribute)) {
507
+ const arg = attribute.argument;
508
+ const conditional = t.isConditionalExpression(arg) ? (
509
+ // <YStack {...isSmall ? { color: 'red } : { color: 'blue }}
510
+ [arg.test, arg.consequent, arg.alternate]
511
+ ) : t.isLogicalExpression(arg) && arg.operator === "&&" ? (
512
+ // <YStack {...isSmall && { color: 'red }}
513
+ [arg.left, arg.right, null]
514
+ ) : null;
515
+ if (conditional) {
516
+ const [test, alt, cons] = conditional;
517
+ if (!test)
518
+ throw new Error(`no test`);
519
+ if ([alt, cons].some((side) => side && !isStaticObject2(side))) {
520
+ if (shouldPrintDebug) {
521
+ logger.info(`not extractable ${alt} ${cons}`);
522
+ }
523
+ return attr;
524
+ }
525
+ return [
526
+ ...createTernariesFromObjectProperties2(test, alt) || [],
527
+ ...cons && createTernariesFromObjectProperties2(
528
+ t.unaryExpression("!", test),
529
+ cons
530
+ ) || []
531
+ ].map((ternary) => ({
532
+ type: "ternary",
533
+ value: ternary
534
+ }));
535
+ }
536
+ }
537
+ if (t.isJSXSpreadAttribute(attribute) || !attribute.name || typeof attribute.name.name !== "string") {
538
+ if (shouldPrintDebug) {
539
+ logger.info(" ! inlining, spread attr");
540
+ }
541
+ inlined.set(`${Math.random()}`, "spread");
542
+ return attr;
543
+ }
544
+ const name = attribute.name.name;
545
+ if (excludeProps == null ? void 0 : excludeProps.has(name)) {
546
+ if (shouldPrintDebug) {
547
+ logger.info([" excluding prop", name].join(" "));
548
+ }
549
+ return null;
550
+ }
551
+ if (inlineProps.has(name)) {
552
+ inlined.set(name, name);
553
+ if (shouldPrintDebug) {
554
+ logger.info([" ! inlining, inline prop", name].join(" "));
555
+ }
556
+ return attr;
557
+ }
558
+ if (deoptProps.has(name)) {
559
+ shouldDeopt = true;
560
+ inlined.set(name, name);
561
+ if (shouldPrintDebug) {
562
+ logger.info([" ! inlining, deopted prop", name].join(" "));
563
+ }
564
+ return attr;
565
+ }
566
+ if (UNTOUCHED_PROPS[name]) {
567
+ return attr;
568
+ }
569
+ if (INLINE_EXTRACTABLE[name]) {
570
+ inlined.set(name, INLINE_EXTRACTABLE[name]);
571
+ return attr;
572
+ }
573
+ if (name.startsWith("data-")) {
574
+ return attr;
575
+ }
576
+ if (name[0] === "$" && t.isJSXExpressionContainer(attribute == null ? void 0 : attribute.value)) {
577
+ const shortname = name.slice(1);
578
+ if (import_core_node.mediaQueryConfig[shortname]) {
579
+ if (target === "native") {
580
+ shouldDeopt = true;
581
+ }
582
+ if (disableExtractInlineMedia) {
583
+ return attr;
584
+ }
585
+ const expression = attribute.value.expression;
586
+ if (!t.isJSXEmptyExpression(expression)) {
587
+ const ternaries2 = createTernariesFromObjectProperties2(
588
+ t.stringLiteral(shortname),
589
+ expression,
590
+ {
591
+ inlineMediaQuery: shortname
592
+ }
593
+ );
594
+ if (ternaries2) {
595
+ return ternaries2.map((value2) => ({
596
+ type: "ternary",
597
+ value: value2
598
+ }));
599
+ }
600
+ }
601
+ }
602
+ }
603
+ const [value, valuePath] = (() => {
604
+ if (t.isJSXExpressionContainer(attribute == null ? void 0 : attribute.value)) {
605
+ return [attribute.value.expression, path.get("value")];
606
+ } else {
607
+ return [attribute.value, path.get("value")];
608
+ }
609
+ })();
610
+ const remove = () => {
611
+ Array.isArray(valuePath) ? valuePath.map((p) => p.remove()) : valuePath.remove();
612
+ };
613
+ if (name === "ref") {
614
+ if (shouldPrintDebug) {
615
+ logger.info([" ! inlining, ref", name].join(" "));
616
+ }
617
+ inlined.set("ref", "ref");
618
+ return attr;
619
+ }
620
+ if (name === "tag") {
621
+ return {
622
+ type: "attr",
623
+ value: path.node
624
+ };
625
+ }
626
+ if (disableExtractVariables === true) {
627
+ if (value) {
628
+ if (value.type === "StringLiteral" && value.value[0] === "$") {
629
+ if (shouldPrintDebug) {
630
+ logger.info(
631
+ [
632
+ ` ! inlining, native disable extract: ${name} =`,
633
+ value.value
634
+ ].join(" ")
635
+ );
636
+ }
637
+ inlined.set(name, true);
638
+ return attr;
639
+ }
640
+ }
641
+ }
642
+ if (name === "theme") {
643
+ inlined.set("theme", attr.value);
644
+ return attr;
645
+ }
646
+ const styleValue = attemptEvalSafe(value);
647
+ if (!variants[name] && !isValidStyleKey(name, staticConfig)) {
648
+ let keys = [name];
649
+ let out = null;
650
+ out = staticConfig.propMapper(
651
+ name,
652
+ styleValue,
653
+ defaultTheme,
654
+ staticConfig.defaultProps,
655
+ { resolveVariablesAs: "auto" },
656
+ void 0,
657
+ void 0,
658
+ shouldPrintDebug
659
+ );
660
+ if (out) {
661
+ if (!Array.isArray(out)) {
662
+ logger.warn(`Error expected array but got`, out);
663
+ couldntParse = true;
664
+ shouldDeopt = true;
665
+ } else {
666
+ out = Object.fromEntries(out);
667
+ keys = Object.keys(out);
668
+ }
669
+ }
670
+ if (out) {
671
+ if (isTargetingHTML) {
672
+ out = (0, import_react_native_web_internals.createDOMProps)(isTextView ? "span" : "div", out);
673
+ delete out.className;
674
+ }
675
+ keys = Object.keys(out);
676
+ }
677
+ let didInline = false;
678
+ const attributes = keys.map((key) => {
679
+ const val = out[key];
680
+ const isStyle = isValidStyleKey(key, staticConfig);
681
+ if (isStyle) {
682
+ return {
683
+ type: "style",
684
+ value: { [key]: styleValue },
685
+ name: key,
686
+ attr: path.node
687
+ };
688
+ }
689
+ if (import_validHTMLAttributes.validHTMLAttributes[key] || key.startsWith("aria-") || key.startsWith("data-") || // this is debug stuff added by vite / new jsx transform
690
+ key === "__source" || key === "__self") {
691
+ return attr;
692
+ }
693
+ if (shouldPrintDebug) {
694
+ logger.info(" ! inlining, non-static " + key);
695
+ }
696
+ didInline = true;
697
+ inlined.set(key, val);
698
+ return val;
699
+ });
700
+ if (didInline) {
701
+ if (shouldPrintDebug) {
702
+ logger.info(` bailing flattening due to attributes ${attributes}`);
703
+ }
704
+ return attr;
705
+ }
706
+ return attributes;
707
+ }
708
+ if (styleValue !== import_constants.FAILED_EVAL) {
709
+ if (inlineWhenUnflattened.has(name)) {
710
+ inlineWhenUnflattenedOGVals[name] = { styleValue, attr };
711
+ }
712
+ if (isValidStyleKey(name, staticConfig)) {
713
+ if (shouldPrintDebug) {
714
+ logger.info(` style: ${name} = ${styleValue}`);
715
+ }
716
+ if (!(name in staticConfig.defaultProps)) {
717
+ if (!hasSetOptimized) {
718
+ res.optimized++;
719
+ hasSetOptimized = true;
720
+ }
721
+ }
722
+ return {
723
+ type: "style",
724
+ value: { [name]: styleValue },
725
+ name,
726
+ attr: path.node
727
+ };
728
+ } else {
729
+ if (variants[name]) {
730
+ variantValues.set(name, styleValue);
731
+ }
732
+ inlined.set(name, true);
733
+ return attr;
734
+ }
735
+ }
736
+ if (t.isBinaryExpression(value)) {
737
+ if (shouldPrintDebug) {
738
+ logger.info(` binary expression ${name} = ${value}`);
739
+ }
740
+ const { operator, left, right } = value;
741
+ const lVal = attemptEvalSafe(left);
742
+ const rVal = attemptEvalSafe(right);
743
+ if (shouldPrintDebug) {
744
+ logger.info(
745
+ ` evalBinaryExpression lVal ${String(lVal)}, rVal ${String(rVal)}`
746
+ );
747
+ }
748
+ if (lVal !== import_constants.FAILED_EVAL && t.isConditionalExpression(right)) {
749
+ const ternary = addBinaryConditional(operator, left, right);
750
+ if (ternary)
751
+ return ternary;
752
+ }
753
+ if (rVal !== import_constants.FAILED_EVAL && t.isConditionalExpression(left)) {
754
+ const ternary = addBinaryConditional(operator, right, left);
755
+ if (ternary)
756
+ return ternary;
757
+ }
758
+ if (shouldPrintDebug) {
759
+ logger.info(` evalBinaryExpression cant extract`);
760
+ }
761
+ inlined.set(name, true);
762
+ return attr;
763
+ }
764
+ const staticConditional = getStaticConditional(value);
765
+ if (staticConditional) {
766
+ if (shouldPrintDebug === "verbose") {
767
+ logger.info(` static conditional ${name} ${value}`);
768
+ }
769
+ return { type: "ternary", value: staticConditional };
770
+ }
771
+ const staticLogical = getStaticLogical(value);
772
+ if (staticLogical) {
773
+ if (shouldPrintDebug === "verbose") {
774
+ logger.info(` static ternary ${name} = ${value}`);
775
+ }
776
+ return { type: "ternary", value: staticLogical };
777
+ }
778
+ inlined.set(name, true);
779
+ if (shouldPrintDebug) {
780
+ logger.info(` ! inline no match ${name} ${value}`);
781
+ }
782
+ return attr;
783
+ function addBinaryConditional(operator, staticExpr, cond) {
784
+ if (getStaticConditional(cond)) {
785
+ const alt = attemptEval(
786
+ t.binaryExpression(operator, staticExpr, cond.alternate)
787
+ );
788
+ const cons = attemptEval(
789
+ t.binaryExpression(operator, staticExpr, cond.consequent)
790
+ );
791
+ if (shouldPrintDebug) {
792
+ logger.info([" binaryConditional", cond.test, cons, alt].join(" "));
793
+ }
794
+ return {
795
+ type: "ternary",
796
+ value: {
797
+ test: cond.test,
798
+ remove,
799
+ alternate: { [name]: alt },
800
+ consequent: { [name]: cons }
801
+ }
802
+ };
803
+ }
804
+ return null;
805
+ }
806
+ function getStaticConditional(value2) {
807
+ if (t.isConditionalExpression(value2)) {
808
+ try {
809
+ const aVal = attemptEval(value2.alternate);
810
+ const cVal = attemptEval(value2.consequent);
811
+ if (shouldPrintDebug) {
812
+ const type = value2.test.type;
813
+ logger.info([" static ternary", type, cVal, aVal].join(" "));
814
+ }
815
+ return {
816
+ test: value2.test,
817
+ remove,
818
+ consequent: { [name]: cVal },
819
+ alternate: { [name]: aVal }
820
+ };
821
+ } catch (err) {
822
+ if (shouldPrintDebug) {
823
+ logger.info([" cant eval ternary", err.message].join(" "));
824
+ }
825
+ }
826
+ }
827
+ return null;
828
+ }
829
+ function getStaticLogical(value2) {
830
+ if (t.isLogicalExpression(value2)) {
831
+ if (value2.operator === "&&") {
832
+ try {
833
+ const val = attemptEval(value2.right);
834
+ if (shouldPrintDebug) {
835
+ logger.info([" staticLogical", value2.left, name, val].join(" "));
836
+ }
837
+ return {
838
+ test: value2.left,
839
+ remove,
840
+ consequent: { [name]: val },
841
+ alternate: null
842
+ };
843
+ } catch (err) {
844
+ if (shouldPrintDebug) {
845
+ logger.info([" cant static eval logical", err].join(" "));
846
+ }
847
+ }
848
+ }
849
+ }
850
+ return null;
851
+ }
852
+ }, isStaticObject2 = function(obj) {
853
+ return t.isObjectExpression(obj) && obj.properties.every((prop) => {
854
+ if (!t.isObjectProperty(prop)) {
855
+ logger.info(["not object prop", prop].join(" "));
856
+ return false;
857
+ }
858
+ const propName = prop.key["name"];
859
+ if (!isValidStyleKey(propName, staticConfig) && propName !== "tag") {
860
+ if (shouldPrintDebug) {
861
+ logger.info([" not a valid style prop!", propName].join(" "));
862
+ }
863
+ return false;
864
+ }
865
+ return true;
866
+ });
867
+ }, createTernariesFromObjectProperties2 = function(test, side, ternaryPartial = {}) {
868
+ if (!side) {
869
+ return null;
870
+ }
871
+ if (!isStaticObject2(side)) {
872
+ throw new Error("not extractable");
873
+ }
874
+ return side.properties.flatMap((property) => {
875
+ if (!t.isObjectProperty(property)) {
876
+ throw new Error("expected object property");
877
+ }
878
+ if (t.isIdentifier(property.key)) {
879
+ const key = property.key.name;
880
+ const mediaQueryKey = key.slice(1);
881
+ const isMediaQuery = key[0] === "$" && import_core_node.mediaQueryConfig[mediaQueryKey];
882
+ if (isMediaQuery) {
883
+ if (t.isExpression(property.value)) {
884
+ const ternaries2 = createTernariesFromObjectProperties2(
885
+ t.stringLiteral(mediaQueryKey),
886
+ property.value,
887
+ {
888
+ inlineMediaQuery: mediaQueryKey
889
+ }
890
+ );
891
+ if (ternaries2) {
892
+ return ternaries2.map((value) => ({
893
+ ...ternaryPartial,
894
+ ...value,
895
+ // ensure media query test stays on left side (see getMediaQueryTernary)
896
+ test: t.logicalExpression("&&", value.test, test)
897
+ }));
898
+ } else {
899
+ logger.info(["\u26A0\uFE0F no ternaries?", property].join(" "));
900
+ }
901
+ } else {
902
+ logger.info(["\u26A0\uFE0F not expression", property].join(" "));
903
+ }
904
+ }
905
+ }
906
+ if (t.isConditionalExpression(property.value)) {
907
+ const [truthy, falsy] = [
908
+ t.objectExpression([
909
+ t.objectProperty(property.key, property.value.consequent)
910
+ ]),
911
+ t.objectExpression([
912
+ t.objectProperty(property.key, property.value.alternate)
913
+ ])
914
+ ].map((x) => attemptEval(x));
915
+ return [
916
+ createTernary({
917
+ remove() {
918
+ },
919
+ ...ternaryPartial,
920
+ test: t.logicalExpression("&&", test, property.value.test),
921
+ consequent: truthy,
922
+ alternate: null
923
+ }),
924
+ createTernary({
925
+ ...ternaryPartial,
926
+ test: t.logicalExpression(
927
+ "&&",
928
+ test,
929
+ t.unaryExpression("!", property.value.test)
930
+ ),
931
+ consequent: falsy,
932
+ alternate: null,
933
+ remove() {
934
+ }
935
+ })
936
+ ];
937
+ }
938
+ const obj = t.objectExpression([
939
+ t.objectProperty(property.key, property.value)
940
+ ]);
941
+ const consequent = attemptEval(obj);
942
+ return createTernary({
943
+ remove() {
944
+ },
945
+ ...ternaryPartial,
946
+ test,
947
+ consequent,
948
+ alternate: null
949
+ });
950
+ });
951
+ }, splitVariants2 = function(style) {
952
+ var _a3;
953
+ const variants2 = {};
954
+ const styles = {};
955
+ for (const key in style) {
956
+ if ((_a3 = staticConfig.variants) == null ? void 0 : _a3[key]) {
957
+ variants2[key] = style[key];
958
+ } else {
959
+ styles[key] = style[key];
960
+ }
961
+ }
962
+ return {
963
+ variants: variants2,
964
+ styles
965
+ };
966
+ }, expandStylesWithoutVariants2 = function(style) {
967
+ const { variants: variants2, styles } = splitVariants2(style);
968
+ return {
969
+ ...(0, import_core_node.expandStyles)(styles),
970
+ ...variants2
971
+ };
972
+ }, mergeStyles2 = function(prev2, next) {
973
+ for (const key in next) {
974
+ if (import_core_node.pseudoDescriptors[key]) {
975
+ prev2[key] = prev2[key] || {};
976
+ Object.assign(prev2[key], next[key]);
977
+ } else {
978
+ prev2[key] = next[key];
979
+ }
980
+ }
981
+ };
982
+ var evaluateAttribute = evaluateAttribute2, isStaticObject = isStaticObject2, createTernariesFromObjectProperties = createTernariesFromObjectProperties2, splitVariants = splitVariants2, expandStylesWithoutVariants = expandStylesWithoutVariants2, mergeStyles = mergeStyles2;
983
+ const { staticConfig } = component;
984
+ const variants = staticConfig.variants || {};
985
+ const isTextView = staticConfig.isText || false;
986
+ const validStyles = (staticConfig == null ? void 0 : staticConfig.validStyles) ?? {};
987
+ let tagName = staticConfig.defaultProps.tag ?? (isTextView ? "span" : "div");
988
+ traversePath.get("openingElement").get("attributes").forEach((path) => {
989
+ const attr = path.node;
990
+ if (t.isJSXSpreadAttribute(attr))
991
+ return;
992
+ if (attr.name.name !== "tag")
993
+ return;
994
+ const val = attr.value;
995
+ if (!t.isStringLiteral(val))
996
+ return;
997
+ tagName = val.value;
998
+ });
999
+ const flatNode = getFlattenedNode == null ? void 0 : getFlattenedNode({ isTextView, tag: tagName });
1000
+ const inlineProps = /* @__PURE__ */ new Set([
1001
+ // adding some always inline props
1002
+ "dataSet",
1003
+ ...restProps.inlineProps || [],
1004
+ ...staticConfig.inlineProps || []
1005
+ ]);
1006
+ const deoptProps = /* @__PURE__ */ new Set([
1007
+ // always de-opt animation
1008
+ "animation",
1009
+ ...restProps.deoptProps || [],
1010
+ ...staticConfig.deoptProps || []
1011
+ ]);
1012
+ const inlineWhenUnflattened = /* @__PURE__ */ new Set([
1013
+ ...staticConfig.inlineWhenUnflattened || []
1014
+ ]);
1015
+ const staticNamespace = (0, import_getStaticBindingsForScope.getStaticBindingsForScope)(
1016
+ traversePath.scope,
1017
+ importsWhitelist,
1018
+ sourcePath,
1019
+ bindingCache,
1020
+ shouldPrintDebug
1021
+ );
1022
+ const attemptEval = !evaluateVars ? import_evaluateAstNode.evaluateAstNode : (0, import_createEvaluator.createEvaluator)({
1023
+ props: propsWithFileInfo,
1024
+ staticNamespace,
1025
+ sourcePath,
1026
+ traversePath,
1027
+ shouldPrintDebug
1028
+ });
1029
+ const attemptEvalSafe = (0, import_createEvaluator.createSafeEvaluator)(attemptEval);
1030
+ if (shouldPrintDebug) {
1031
+ logger.info(` staticNamespace ${Object.keys(staticNamespace).join(", ")}`);
1032
+ }
1033
+ if (couldntParse) {
1034
+ return;
1035
+ }
1036
+ tm.mark("jsx-element-flattened", !!shouldPrintDebug);
1037
+ let attrs = [];
1038
+ let shouldDeopt = false;
1039
+ const inlined = /* @__PURE__ */ new Map();
1040
+ const variantValues = /* @__PURE__ */ new Map();
1041
+ let hasSetOptimized = false;
1042
+ const inlineWhenUnflattenedOGVals = {};
1043
+ attrs = traversePath.get("openingElement").get("attributes").flatMap((path) => {
1044
+ var _a3;
1045
+ try {
1046
+ const res2 = evaluateAttribute2(path);
1047
+ tm.mark("jsx-element-evaluate-attr", !!shouldPrintDebug);
1048
+ if (!res2) {
1049
+ path.remove();
1050
+ }
1051
+ return res2;
1052
+ } catch (err) {
1053
+ if (shouldPrintDebug) {
1054
+ logger.info(
1055
+ [
1056
+ "Recoverable error extracting attribute",
1057
+ err.message,
1058
+ shouldPrintDebug === "verbose" ? err.stack : ""
1059
+ ].join(" ")
1060
+ );
1061
+ if (shouldPrintDebug === "verbose") {
1062
+ logger.info(`node ${(_a3 = path.node) == null ? void 0 : _a3.type}`);
1063
+ }
1064
+ }
1065
+ inlined.set(`${Math.random()}`, "spread");
1066
+ return {
1067
+ type: "attr",
1068
+ value: path.node
1069
+ };
1070
+ }
1071
+ }).flat(4).filter(import_extractHelpers.isPresent);
1072
+ if (shouldPrintDebug) {
1073
+ logger.info(
1074
+ [" - attrs (before):\n", (0, import_logLines.logLines)(attrs.map(import_extractHelpers.attrStr).join(", "))].join(" ")
1075
+ );
1076
+ }
1077
+ if (couldntParse || shouldDeopt) {
1078
+ if (shouldPrintDebug) {
1079
+ logger.info(
1080
+ [` avoid optimizing:`, { couldntParse, shouldDeopt }].join(" ")
1081
+ );
1082
+ }
1083
+ node.attributes = ogAttributes;
1084
+ return;
1085
+ }
1086
+ const parentFn = (0, import_findTopmostFunction.findTopmostFunction)(traversePath);
1087
+ if (parentFn) {
1088
+ modifiedComponents.add(parentFn);
1089
+ }
1090
+ let ternaries = [];
1091
+ attrs = attrs.reduce((out, cur) => {
1092
+ const next = attrs[attrs.indexOf(cur) + 1];
1093
+ if (cur.type === "ternary") {
1094
+ ternaries.push(cur.value);
1095
+ }
1096
+ if ((!next || next.type !== "ternary") && ternaries.length) {
1097
+ const normalized = (0, import_normalizeTernaries.normalizeTernaries)(ternaries).map(
1098
+ ({ alternate, consequent, ...rest }) => {
1099
+ return {
1100
+ type: "ternary",
1101
+ value: {
1102
+ ...rest,
1103
+ alternate: alternate || null,
1104
+ consequent: consequent || null
1105
+ }
1106
+ };
1107
+ }
1108
+ );
1109
+ try {
1110
+ return [...out, ...normalized];
1111
+ } finally {
1112
+ if (shouldPrintDebug) {
1113
+ logger.info(
1114
+ ` normalizeTernaries (${ternaries.length} => ${normalized.length})`
1115
+ );
1116
+ }
1117
+ ternaries = [];
1118
+ }
1119
+ }
1120
+ if (cur.type === "ternary") {
1121
+ return out;
1122
+ }
1123
+ out.push(cur);
1124
+ return out;
1125
+ }, []).flat();
1126
+ const hasSpread = attrs.some(
1127
+ (x) => x.type === "attr" && t.isJSXSpreadAttribute(x.value)
1128
+ );
1129
+ const hasOnlyStringChildren = !hasSpread && (node.selfClosing || traversePath.node.children && traversePath.node.children.every((x) => x.type === "JSXText"));
1130
+ const themeVal = inlined.get("theme");
1131
+ if (target !== "native") {
1132
+ inlined.delete("theme");
1133
+ }
1134
+ for (const [key] of [...inlined]) {
1135
+ const isStaticObjectVariant = ((_a2 = staticConfig.variants) == null ? void 0 : _a2[key]) && variantValues.has(key);
1136
+ if (INLINE_EXTRACTABLE[key] || isStaticObjectVariant) {
1137
+ inlined.delete(key);
1138
+ }
1139
+ }
1140
+ const canFlattenProps = inlined.size === 0;
1141
+ let shouldFlatten = Boolean(
1142
+ flatNode && !shouldDeopt && canFlattenProps && !hasSpread && staticConfig.neverFlatten !== true && (staticConfig.neverFlatten === "jsx" ? hasOnlyStringChildren : true)
1143
+ );
1144
+ const shouldWrapTheme = shouldFlatten && themeVal;
1145
+ const usedThemeKeys = /* @__PURE__ */ new Set();
1146
+ if (disableExtractVariables) {
1147
+ themeAccessListeners.add((key) => {
1148
+ shouldFlatten = false;
1149
+ usedThemeKeys.add(key);
1150
+ if (shouldPrintDebug === "verbose") {
1151
+ logger.info([" ! accessing theme key, avoid flatten", key].join(" "));
1152
+ }
1153
+ });
1154
+ }
1155
+ if (shouldPrintDebug) {
1156
+ try {
1157
+ logger.info([" flatten?", shouldFlatten, (0, import_extractHelpers.objToStr)({ hasSpread, shouldDeopt, canFlattenProps, shouldWrapTheme, hasOnlyStringChildren }), "inlined", inlined.size, [...inlined]].join(" "));
1158
+ } catch {
1159
+ }
1160
+ }
1161
+ if (shouldFlatten && shouldWrapTheme) {
1162
+ if (!programPath) {
1163
+ console.warn(
1164
+ `No program path found, avoiding importing flattening / importing theme in ${sourcePath}`
1165
+ );
1166
+ } else {
1167
+ if (shouldPrintDebug) {
1168
+ logger.info([" - wrapping theme", themeVal].join(" "));
1169
+ }
1170
+ attrs = attrs.filter(
1171
+ (x) => x.type === "attr" && t.isJSXAttribute(x.value) && x.value.name.name === "theme" ? false : true
1172
+ );
1173
+ if (!hasImportedTheme) {
1174
+ hasImportedTheme = true;
1175
+ programPath.node.body.push(
1176
+ t.importDeclaration(
1177
+ [
1178
+ t.importSpecifier(
1179
+ t.identifier("_TamaguiTheme"),
1180
+ t.identifier("Theme")
1181
+ )
1182
+ ],
1183
+ t.stringLiteral("@tamagui/core")
1184
+ )
1185
+ );
1186
+ }
1187
+ traversePath.replaceWith(
1188
+ t.jsxElement(
1189
+ t.jsxOpeningElement(t.jsxIdentifier("_TamaguiTheme"), [
1190
+ t.jsxAttribute(t.jsxIdentifier("name"), themeVal.value)
1191
+ ]),
1192
+ t.jsxClosingElement(t.jsxIdentifier("_TamaguiTheme")),
1193
+ [traversePath.node]
1194
+ )
1195
+ );
1196
+ }
1197
+ }
1198
+ if (shouldFlatten) {
1199
+ const defaultStyleAttrs = Object.keys(staticConfig.defaultProps).flatMap(
1200
+ (key) => {
1201
+ if (!isValidStyleKey(key, staticConfig)) {
1202
+ return [];
1203
+ }
1204
+ const value = staticConfig.defaultProps[key];
1205
+ const name = tamaguiConfig.shorthands[key] || key;
1206
+ if (value === void 0) {
1207
+ logger.warn(
1208
+ `\u26A0\uFE0F Error evaluating default style for component, prop ${key} ${value}`
1209
+ );
1210
+ shouldDeopt = true;
1211
+ return;
1212
+ }
1213
+ const attr = {
1214
+ type: "style",
1215
+ name,
1216
+ value: { [name]: value }
1217
+ };
1218
+ return attr;
1219
+ }
1220
+ );
1221
+ if (defaultStyleAttrs.length) {
1222
+ attrs = [...defaultStyleAttrs, ...attrs];
1223
+ }
1224
+ }
1225
+ if (shouldDeopt || !shouldFlatten) {
1226
+ if (shouldPrintDebug) {
1227
+ logger.info(`Deopting ${shouldDeopt} ${shouldFlatten}`);
1228
+ }
1229
+ node.attributes = ogAttributes;
1230
+ return;
1231
+ }
1232
+ if (shouldPrintDebug) {
1233
+ logger.info(
1234
+ [" - attrs (flattened): \n", (0, import_logLines.logLines)(attrs.map(import_extractHelpers.attrStr).join(", "))].join(
1235
+ " "
1236
+ )
1237
+ );
1238
+ }
1239
+ const state = {
1240
+ noClassNames: false,
1241
+ focus: false,
1242
+ hover: false,
1243
+ unmounted: false,
1244
+ // TODO match logic in createComponent
1245
+ press: false,
1246
+ pressIn: false
1247
+ };
1248
+ let foundStaticProps = {};
1249
+ for (const key in attrs) {
1250
+ const cur = attrs[key];
1251
+ if (cur.type === "style") {
1252
+ foundStaticProps = {
1253
+ ...foundStaticProps,
1254
+ ...expandStylesWithoutVariants2(cur.value)
1255
+ };
1256
+ continue;
1257
+ }
1258
+ if (cur.type === "attr") {
1259
+ if (t.isJSXSpreadAttribute(cur.value)) {
1260
+ continue;
1261
+ }
1262
+ if (!t.isJSXIdentifier(cur.value.name)) {
1263
+ continue;
1264
+ }
1265
+ const key2 = cur.value.name.name;
1266
+ const value = attemptEvalSafe(cur.value.value || t.booleanLiteral(true));
1267
+ if (value !== import_constants.FAILED_EVAL) {
1268
+ foundStaticProps = {
1269
+ ...foundStaticProps,
1270
+ [key2]: value
1271
+ };
1272
+ }
1273
+ }
1274
+ }
1275
+ const completeProps = {};
1276
+ for (const key in staticConfig.defaultProps) {
1277
+ if (!(key in foundStaticProps)) {
1278
+ completeProps[key] = staticConfig.defaultProps[key];
1279
+ }
1280
+ }
1281
+ for (const key in foundStaticProps) {
1282
+ completeProps[key] = foundStaticProps[key];
1283
+ }
1284
+ attrs = attrs.reduce((acc, cur) => {
1285
+ if (!cur)
1286
+ return acc;
1287
+ if (cur.type === "attr" && !t.isJSXSpreadAttribute(cur.value)) {
1288
+ if (shouldFlatten) {
1289
+ const name = cur.value.name.name;
1290
+ if (typeof name === "string") {
1291
+ if (name === "tag") {
1292
+ return acc;
1293
+ }
1294
+ if (variants[name] && variantValues.has(name)) {
1295
+ let out = Object.fromEntries(
1296
+ staticConfig.propMapper(
1297
+ name,
1298
+ variantValues.get(name),
1299
+ defaultTheme,
1300
+ completeProps,
1301
+ { ...state, resolveVariablesAs: "auto" },
1302
+ void 0,
1303
+ void 0,
1304
+ shouldPrintDebug
1305
+ ) || []
1306
+ );
1307
+ if (out && isTargetingHTML) {
1308
+ const cn = out.className;
1309
+ out = (0, import_react_native_web_internals.createDOMProps)(isTextView ? "span" : "div", out);
1310
+ out.className = cn;
1311
+ }
1312
+ if (shouldPrintDebug) {
1313
+ logger.info([" - expanded variant", name, out].join(" "));
1314
+ }
1315
+ for (const key2 in out) {
1316
+ const value2 = out[key2];
1317
+ if (isValidStyleKey(key2, staticConfig)) {
1318
+ acc.push({
1319
+ type: "style",
1320
+ value: { [key2]: value2 },
1321
+ name: key2,
1322
+ attr: cur.value
1323
+ });
1324
+ } else {
1325
+ acc.push({
1326
+ type: "attr",
1327
+ value: t.jsxAttribute(
1328
+ t.jsxIdentifier(key2),
1329
+ t.jsxExpressionContainer(
1330
+ typeof value2 === "string" ? t.stringLiteral(value2) : (0, import_literalToAst.literalToAst)(value2)
1331
+ )
1332
+ )
1333
+ });
1334
+ }
1335
+ }
1336
+ }
1337
+ }
1338
+ }
1339
+ }
1340
+ if (cur.type !== "style") {
1341
+ acc.push(cur);
1342
+ return acc;
1343
+ }
1344
+ let key = Object.keys(cur.value)[0];
1345
+ const value = cur.value[key];
1346
+ const fullKey = tamaguiConfig.shorthands[key];
1347
+ if (fullKey) {
1348
+ cur.value = { [fullKey]: value };
1349
+ key = fullKey;
1350
+ }
1351
+ if (disableExtractVariables) {
1352
+ if (value[0] === "$" && (usedThemeKeys.has(key) || usedThemeKeys.has(fullKey))) {
1353
+ if (shouldPrintDebug) {
1354
+ logger.info([` keeping variable inline: ${key} =`, value].join(" "));
1355
+ }
1356
+ acc.push({
1357
+ type: "attr",
1358
+ value: t.jsxAttribute(
1359
+ t.jsxIdentifier(key),
1360
+ t.jsxExpressionContainer(t.stringLiteral(value))
1361
+ )
1362
+ });
1363
+ return acc;
1364
+ }
1365
+ }
1366
+ acc.push(cur);
1367
+ return acc;
1368
+ }, []);
1369
+ tm.mark("jsx-element-expanded", !!shouldPrintDebug);
1370
+ if (shouldPrintDebug) {
1371
+ logger.info(
1372
+ [" - attrs (expanded): \n", (0, import_logLines.logLines)(attrs.map(import_extractHelpers.attrStr).join(", "))].join(
1373
+ " "
1374
+ )
1375
+ );
1376
+ }
1377
+ let prev = null;
1378
+ attrs = attrs.reduce((acc, cur) => {
1379
+ if (cur.type === "style") {
1380
+ const key = Object.keys(cur.value)[0];
1381
+ const value = cur.value[key];
1382
+ const shouldKeepOriginalAttr = (
1383
+ // !isStyleAndAttr[key] &&
1384
+ !shouldFlatten && // de-opt if non-style
1385
+ !validStyles[key] && !import_core_node.pseudoDescriptors[key] && !(key.startsWith("data-") || key.startsWith("aria-"))
1386
+ );
1387
+ if (shouldKeepOriginalAttr) {
1388
+ if (shouldPrintDebug) {
1389
+ logger.info([" - keeping as non-style", key].join(" "));
1390
+ }
1391
+ prev = cur;
1392
+ acc.push({
1393
+ type: "attr",
1394
+ value: t.jsxAttribute(
1395
+ t.jsxIdentifier(key),
1396
+ t.jsxExpressionContainer(
1397
+ typeof value === "string" ? t.stringLiteral(value) : (0, import_literalToAst.literalToAst)(value)
1398
+ )
1399
+ )
1400
+ });
1401
+ acc.push(cur);
1402
+ return acc;
1403
+ }
1404
+ if ((prev == null ? void 0 : prev.type) === "style") {
1405
+ mergeStyles2(prev.value, cur.value);
1406
+ return acc;
1407
+ }
1408
+ }
1409
+ prev = cur;
1410
+ acc.push(cur);
1411
+ return acc;
1412
+ }, []);
1413
+ if (shouldPrintDebug) {
1414
+ logger.info(
1415
+ [
1416
+ " - attrs (combined \u{1F500}): \n",
1417
+ (0, import_logLines.logLines)(attrs.map(import_extractHelpers.attrStr).join(", "))
1418
+ ].join(" ")
1419
+ );
1420
+ logger.info(
1421
+ [
1422
+ " - defaultProps: \n",
1423
+ (0, import_logLines.logLines)((0, import_extractHelpers.objToStr)(staticConfig.defaultProps))
1424
+ ].join(" ")
1425
+ );
1426
+ logger.info([" - foundStaticProps: \n", (0, import_logLines.logLines)((0, import_extractHelpers.objToStr)(foundStaticProps))].join(" "));
1427
+ logger.info(
1428
+ [" - completeProps: \n", (0, import_logLines.logLines)((0, import_extractHelpers.objToStr)(completeProps))].join(" ")
1429
+ );
1430
+ }
1431
+ const getStyles = (props, debugName = "") => {
1432
+ if (!props || !Object.keys(props).length) {
1433
+ if (shouldPrintDebug)
1434
+ logger.info([" getStyles() no props"].join(" "));
1435
+ return {};
1436
+ }
1437
+ if (excludeProps && !!excludeProps.size) {
1438
+ for (const key in props) {
1439
+ if (excludeProps.has(key)) {
1440
+ if (shouldPrintDebug)
1441
+ logger.info([" delete excluded", key].join(" "));
1442
+ delete props[key];
1443
+ }
1444
+ }
1445
+ }
1446
+ try {
1447
+ const out = (0, import_core_node.getSplitStyles)(
1448
+ props,
1449
+ staticConfig,
1450
+ defaultTheme,
1451
+ {
1452
+ ...state,
1453
+ fallbackProps: completeProps
1454
+ },
1455
+ void 0,
1456
+ void 0,
1457
+ void 0,
1458
+ debugPropValue
1459
+ );
1460
+ const outStyle = {
1461
+ ...out.style,
1462
+ ...out.pseudos
1463
+ };
1464
+ if (shouldPrintDebug === "verbose") {
1465
+ logger.info(` getStyles ${debugName} (props in): ${Object.keys(props)}`);
1466
+ logger.info(` getStyles ${debugName} (outStyle): ${Object.keys(outStyle)}`);
1467
+ }
1468
+ return outStyle;
1469
+ } catch (err) {
1470
+ logger.info(["error", err.message, err.stack].join(" "));
1471
+ return {};
1472
+ }
1473
+ };
1474
+ const completeStyles = getStyles(completeProps, "completeStyles");
1475
+ if (!completeStyles) {
1476
+ throw new Error(`Impossible, no styles`);
1477
+ }
1478
+ let getStyleError = null;
1479
+ for (const attr of attrs) {
1480
+ try {
1481
+ switch (attr.type) {
1482
+ case "ternary": {
1483
+ const a = getStyles(attr.value.alternate, "ternary.alternate");
1484
+ const c = getStyles(attr.value.consequent, "ternary.consequent");
1485
+ if (a)
1486
+ attr.value.alternate = a;
1487
+ if (c)
1488
+ attr.value.consequent = c;
1489
+ if (shouldPrintDebug)
1490
+ logger.info([" => tern ", (0, import_extractHelpers.attrStr)(attr)].join(" "));
1491
+ continue;
1492
+ }
1493
+ case "style": {
1494
+ const styles = getStyles(attr.value, "style");
1495
+ if (styles) {
1496
+ attr.value = styles;
1497
+ }
1498
+ if (shouldPrintDebug)
1499
+ logger.info([" * styles (in)", (0, import_logLines.logLines)((0, import_extractHelpers.objToStr)(attr.value))].join(" "));
1500
+ if (shouldPrintDebug)
1501
+ logger.info([" * styles (out)", (0, import_logLines.logLines)((0, import_extractHelpers.objToStr)(styles))].join(" "));
1502
+ continue;
1503
+ }
1504
+ }
1505
+ } catch (err) {
1506
+ getStyleError = err;
1507
+ }
1508
+ }
1509
+ if (shouldPrintDebug) {
1510
+ logger.info([" - attrs (ternaries/combined):\n", (0, import_logLines.logLines)(attrs.map(import_extractHelpers.attrStr).join(", "))].join(" "));
1511
+ }
1512
+ tm.mark("jsx-element-styles", !!shouldPrintDebug);
1513
+ if (getStyleError) {
1514
+ logger.info([" \u26A0\uFE0F postprocessing error, deopt", getStyleError].join(" "));
1515
+ node.attributes = ogAttributes;
1516
+ return null;
1517
+ }
1518
+ const existingStyleKeys = /* @__PURE__ */ new Set();
1519
+ for (let i = attrs.length - 1; i >= 0; i--) {
1520
+ const attr = attrs[i];
1521
+ if (shouldFlatten) {
1522
+ if (attr.type === "attr") {
1523
+ if (t.isJSXAttribute(attr.value)) {
1524
+ if (t.isJSXIdentifier(attr.value.name)) {
1525
+ const name = attr.value.name.name;
1526
+ if (INLINE_EXTRACTABLE[name]) {
1527
+ attr.value.name.name = INLINE_EXTRACTABLE[name];
1528
+ }
1529
+ }
1530
+ }
1531
+ }
1532
+ }
1533
+ if (attr.type === "style") {
1534
+ for (const key in attr.value) {
1535
+ if (existingStyleKeys.has(key)) {
1536
+ if (shouldPrintDebug) {
1537
+ logger.info([` >> delete existing ${key}`].join(" "));
1538
+ }
1539
+ delete attr.value[key];
1540
+ } else {
1541
+ existingStyleKeys.add(key);
1542
+ }
1543
+ }
1544
+ }
1545
+ }
1546
+ if (!shouldFlatten) {
1547
+ if (inlineWhenUnflattened.size) {
1548
+ for (const [index, attr] of attrs.entries()) {
1549
+ if (attr.type === "style") {
1550
+ for (const key in attr.value) {
1551
+ if (!inlineWhenUnflattened.has(key))
1552
+ continue;
1553
+ const val = inlineWhenUnflattenedOGVals[key];
1554
+ if (val) {
1555
+ delete attr.value[key];
1556
+ attrs.splice(index - 1, 0, val.attr);
1557
+ } else {
1558
+ delete attr.value[key];
1559
+ }
1560
+ }
1561
+ }
1562
+ }
1563
+ }
1564
+ }
1565
+ if (shouldFlatten) {
1566
+ if (shouldPrintDebug) {
1567
+ logger.info([" [\u2705] flattening", originalNodeName, flatNode].join(" "));
1568
+ }
1569
+ node.name.name = flatNode;
1570
+ res.flattened++;
1571
+ if (closingElement) {
1572
+ closingElement.name.name = flatNode;
1573
+ }
1574
+ }
1575
+ const isNativeNotFlat = !shouldFlatten && target === "native";
1576
+ if (isNativeNotFlat) {
1577
+ if (shouldPrintDebug) {
1578
+ logger.info(`Disabled flattening except for simple cases on native for now`);
1579
+ }
1580
+ node.attributes = ogAttributes;
1581
+ return null;
1582
+ }
1583
+ if (shouldPrintDebug) {
1584
+ logger.info([` - inlined props (${inlined.size}):`, shouldDeopt ? " deopted" : "", hasSpread ? " has spread" : "", staticConfig.neverFlatten ? "neverFlatten" : ""].join(" "));
1585
+ logger.info(` - shouldFlatten/isFlattened: ${shouldFlatten}`);
1586
+ logger.info(` - attrs (end):
1587
+ ${(0, import_logLines.logLines)(attrs.map(import_extractHelpers.attrStr).join(", "))}`);
1588
+ }
1589
+ onExtractTag({
1590
+ parserProps: propsWithFileInfo,
1591
+ attrs,
1592
+ node,
1593
+ lineNumbers,
1594
+ filePath,
1595
+ attemptEval,
1596
+ jsxPath: traversePath,
1597
+ originalNodeName,
1598
+ isFlattened: shouldFlatten,
1599
+ programPath,
1600
+ completeProps,
1601
+ staticConfig
1602
+ });
1603
+ } catch (err) {
1604
+ node.attributes = ogAttributes;
1605
+ console.error(`err: ${err}`);
1606
+ } finally {
1607
+ if (debugPropValue) {
1608
+ shouldPrintDebug = ogDebug;
1609
+ }
1610
+ }
1611
+ }
1612
+ });
1613
+ tm.mark("jsx-done", !!shouldPrintDebug);
1614
+ if (modifiedComponents.size) {
1615
+ const all = Array.from(modifiedComponents);
1616
+ if (shouldPrintDebug) {
1617
+ logger.info(` [\u{1FA9D}] hook check ${all.length}`);
1618
+ }
1619
+ for (const comp of all) {
1620
+ (0, import_removeUnusedHooks.removeUnusedHooks)(comp, shouldPrintDebug);
1621
+ }
1622
+ }
1623
+ tm.done(shouldPrintDebug === "verbose");
1624
+ return res;
1625
+ }
1626
+ }
1627
+ // Annotate the CommonJS export names for ESM import in node:
1628
+ 0 && (module.exports = {
1629
+ createExtractor
1630
+ });
16
1631
  //# sourceMappingURL=createExtractor.js.map