@tamagui/static 1.0.1-beta.150 → 1.0.1-beta.153

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 (226) hide show
  1. package/dist/{cjs/constants.js → constants.js} +4 -1
  2. package/dist/{esm/constants.js.map → constants.js.map} +3 -3
  3. package/dist/{cjs/extractor → extractor}/accessSafe.js +13 -2
  4. package/dist/{esm/extractor → extractor}/accessSafe.js.map +2 -2
  5. package/dist/{cjs/extractor → extractor}/babelParse.js +4 -1
  6. package/dist/{cjs/extractor → extractor}/babelParse.js.map +2 -2
  7. package/dist/{cjs/extractor → extractor}/buildClassName.js +19 -4
  8. package/dist/extractor/buildClassName.js.map +7 -0
  9. package/dist/{cjs/extractor → extractor}/createEvaluator.js +7 -4
  10. package/dist/extractor/createEvaluator.js.map +7 -0
  11. package/dist/{cjs/extractor → extractor}/createExtractor.js +186 -64
  12. package/dist/{esm/extractor → extractor}/createExtractor.js.map +4 -4
  13. package/dist/{cjs/extractor → extractor}/ensureImportingConcat.js +21 -6
  14. package/dist/extractor/ensureImportingConcat.js.map +7 -0
  15. package/dist/{cjs/extractor → extractor}/evaluateAstNode.js +13 -4
  16. package/dist/{esm/extractor → extractor}/evaluateAstNode.js.map +2 -2
  17. package/dist/{cjs/extractor → extractor}/extractHelpers.js +8 -3
  18. package/dist/extractor/extractHelpers.js.map +7 -0
  19. package/dist/{cjs/extractor → extractor}/extractMediaStyle.js +22 -6
  20. package/dist/extractor/extractMediaStyle.js.map +7 -0
  21. package/dist/{cjs/extractor → extractor}/extractToClassNames.js +87 -32
  22. package/dist/extractor/extractToClassNames.js.map +7 -0
  23. package/dist/{cjs/extractor → extractor}/findTopmostFunction.js +0 -0
  24. package/dist/{cjs/extractor → extractor}/findTopmostFunction.js.map +2 -2
  25. package/dist/{cjs/extractor → extractor}/generatedUid.js +8 -2
  26. package/dist/{cjs/extractor → extractor}/generatedUid.js.map +3 -3
  27. package/dist/{cjs/extractor → extractor}/getPrefixLogs.js +0 -0
  28. package/dist/extractor/getPrefixLogs.js.map +7 -0
  29. package/dist/{cjs/extractor → extractor}/getPropValueFromAttributes.js +23 -13
  30. package/dist/extractor/getPropValueFromAttributes.js.map +7 -0
  31. package/dist/{cjs/extractor → extractor}/getSourceModule.js +4 -1
  32. package/dist/{esm/extractor → extractor}/getSourceModule.js.map +2 -2
  33. package/dist/{cjs/extractor → extractor}/getStaticBindingsForScope.js +9 -4
  34. package/dist/extractor/getStaticBindingsForScope.js.map +7 -0
  35. package/dist/{cjs/extractor → extractor}/hoistClassNames.js +4 -1
  36. package/dist/{jsx/extractor → extractor}/hoistClassNames.js.map +3 -3
  37. package/dist/{cjs/extractor → extractor}/literalToAst.js +18 -10
  38. package/dist/{jsx/extractor → extractor}/literalToAst.js.map +2 -2
  39. package/dist/{cjs/extractor → extractor}/loadFile.js +0 -0
  40. package/dist/{cjs/extractor → extractor}/loadFile.js.map +1 -1
  41. package/dist/{cjs/extractor → extractor}/loadTamagui.js +34 -7
  42. package/dist/extractor/loadTamagui.js.map +7 -0
  43. package/dist/{cjs/extractor → extractor}/logLines.js +0 -0
  44. package/dist/{cjs/extractor → extractor}/logLines.js.map +2 -2
  45. package/dist/{cjs/extractor → extractor}/normalizeTernaries.js +8 -2
  46. package/dist/extractor/normalizeTernaries.js.map +7 -0
  47. package/dist/{cjs/extractor → extractor}/removeUnusedHooks.js +4 -1
  48. package/dist/{esm/extractor → extractor}/removeUnusedHooks.js.map +2 -2
  49. package/dist/{cjs/extractor → extractor}/timer.js +0 -0
  50. package/dist/{cjs/extractor → extractor}/timer.js.map +1 -1
  51. package/dist/{cjs/extractor → extractor}/validHTMLAttributes.js +0 -0
  52. package/dist/{cjs/extractor → extractor}/validHTMLAttributes.js.map +1 -1
  53. package/dist/{cjs/getPragmaOptions.js → getPragmaOptions.js} +0 -0
  54. package/dist/{cjs/getPragmaOptions.js.map → getPragmaOptions.js.map} +2 -2
  55. package/dist/{cjs/index.js → index.js} +9 -9
  56. package/dist/index.js.map +7 -0
  57. package/dist/{cjs/require.js → require.js} +10 -4
  58. package/dist/require.js.map +7 -0
  59. package/dist/{cjs/types.js → types.js} +0 -0
  60. package/dist/types.js.map +7 -0
  61. package/dist/{cjs/webpackPlugin.js → webpackPlugin.js} +0 -0
  62. package/dist/{cjs/webpackPlugin.js.map → webpackPlugin.js.map} +1 -1
  63. package/package.json +15 -15
  64. package/src/extractor/buildClassName.ts +1 -1
  65. package/src/extractor/createEvaluator.ts +3 -3
  66. package/src/extractor/createExtractor.ts +21 -15
  67. package/src/extractor/ensureImportingConcat.ts +1 -1
  68. package/src/extractor/extractHelpers.ts +4 -3
  69. package/src/extractor/extractMediaStyle.ts +3 -3
  70. package/src/extractor/extractToClassNames.ts +12 -12
  71. package/src/extractor/getPrefixLogs.ts +1 -1
  72. package/src/extractor/getPropValueFromAttributes.ts +2 -2
  73. package/src/extractor/getStaticBindingsForScope.ts +2 -2
  74. package/src/extractor/loadTamagui.ts +27 -5
  75. package/src/extractor/normalizeTernaries.ts +1 -1
  76. package/src/index.ts +9 -10
  77. package/src/require.ts +1 -1
  78. package/src/types.ts +4 -3
  79. package/tamagui.tsconfig.json +5 -0
  80. package/types/extractor/buildClassName.d.ts +1 -1
  81. package/types/extractor/createExtractor.d.ts +4 -4
  82. package/types/extractor/extractHelpers.d.ts +1 -1
  83. package/types/extractor/extractMediaStyle.d.ts +1 -1
  84. package/types/extractor/extractToClassNames.d.ts +2 -2
  85. package/types/extractor/getPrefixLogs.d.ts +1 -1
  86. package/types/extractor/normalizeTernaries.d.ts +1 -1
  87. package/types/index.d.ts +9 -9
  88. package/types/types.d.ts +4 -3
  89. package/dist/cjs/constants.js.map +0 -7
  90. package/dist/cjs/extractor/accessSafe.js.map +0 -7
  91. package/dist/cjs/extractor/buildClassName.js.map +0 -7
  92. package/dist/cjs/extractor/createEvaluator.js.map +0 -7
  93. package/dist/cjs/extractor/createExtractor.js.map +0 -7
  94. package/dist/cjs/extractor/ensureImportingConcat.js.map +0 -7
  95. package/dist/cjs/extractor/evaluateAstNode.js.map +0 -7
  96. package/dist/cjs/extractor/extractHelpers.js.map +0 -7
  97. package/dist/cjs/extractor/extractMediaStyle.js.map +0 -7
  98. package/dist/cjs/extractor/extractToClassNames.js.map +0 -7
  99. package/dist/cjs/extractor/getPrefixLogs.js.map +0 -7
  100. package/dist/cjs/extractor/getPropValueFromAttributes.js.map +0 -7
  101. package/dist/cjs/extractor/getSourceModule.js.map +0 -7
  102. package/dist/cjs/extractor/getStaticBindingsForScope.js.map +0 -7
  103. package/dist/cjs/extractor/hoistClassNames.js.map +0 -7
  104. package/dist/cjs/extractor/literalToAst.js.map +0 -7
  105. package/dist/cjs/extractor/loadTamagui.js.map +0 -7
  106. package/dist/cjs/extractor/normalizeTernaries.js.map +0 -7
  107. package/dist/cjs/extractor/removeUnusedHooks.js.map +0 -7
  108. package/dist/cjs/index.js.map +0 -7
  109. package/dist/cjs/require.js.map +0 -7
  110. package/dist/cjs/types.js.map +0 -7
  111. package/dist/esm/constants.js +0 -17
  112. package/dist/esm/extractor/accessSafe.js +0 -8
  113. package/dist/esm/extractor/babelParse.js +0 -28
  114. package/dist/esm/extractor/babelParse.js.map +0 -7
  115. package/dist/esm/extractor/buildClassName.js +0 -37
  116. package/dist/esm/extractor/buildClassName.js.map +0 -7
  117. package/dist/esm/extractor/createEvaluator.js +0 -52
  118. package/dist/esm/extractor/createEvaluator.js.map +0 -7
  119. package/dist/esm/extractor/createExtractor.js +0 -1374
  120. package/dist/esm/extractor/ensureImportingConcat.js +0 -21
  121. package/dist/esm/extractor/ensureImportingConcat.js.map +0 -7
  122. package/dist/esm/extractor/evaluateAstNode.js +0 -91
  123. package/dist/esm/extractor/extractHelpers.js +0 -97
  124. package/dist/esm/extractor/extractHelpers.js.map +0 -7
  125. package/dist/esm/extractor/extractMediaStyle.js +0 -146
  126. package/dist/esm/extractor/extractMediaStyle.js.map +0 -7
  127. package/dist/esm/extractor/extractToClassNames.js +0 -308
  128. package/dist/esm/extractor/extractToClassNames.js.map +0 -7
  129. package/dist/esm/extractor/findTopmostFunction.js +0 -20
  130. package/dist/esm/extractor/findTopmostFunction.js.map +0 -7
  131. package/dist/esm/extractor/generatedUid.js +0 -25
  132. package/dist/esm/extractor/generatedUid.js.map +0 -7
  133. package/dist/esm/extractor/getPrefixLogs.js +0 -8
  134. package/dist/esm/extractor/getPrefixLogs.js.map +0 -7
  135. package/dist/esm/extractor/getPropValueFromAttributes.js +0 -46
  136. package/dist/esm/extractor/getPropValueFromAttributes.js.map +0 -7
  137. package/dist/esm/extractor/getSourceModule.js +0 -66
  138. package/dist/esm/extractor/getStaticBindingsForScope.js +0 -172
  139. package/dist/esm/extractor/getStaticBindingsForScope.js.map +0 -7
  140. package/dist/esm/extractor/hoistClassNames.js +0 -40
  141. package/dist/esm/extractor/hoistClassNames.js.map +0 -7
  142. package/dist/esm/extractor/literalToAst.js +0 -75
  143. package/dist/esm/extractor/literalToAst.js.map +0 -7
  144. package/dist/esm/extractor/loadFile.js +0 -20
  145. package/dist/esm/extractor/loadFile.js.map +0 -7
  146. package/dist/esm/extractor/loadTamagui.js +0 -255
  147. package/dist/esm/extractor/loadTamagui.js.map +0 -7
  148. package/dist/esm/extractor/logLines.js +0 -20
  149. package/dist/esm/extractor/logLines.js.map +0 -7
  150. package/dist/esm/extractor/normalizeTernaries.js +0 -49
  151. package/dist/esm/extractor/normalizeTernaries.js.map +0 -7
  152. package/dist/esm/extractor/removeUnusedHooks.js +0 -76
  153. package/dist/esm/extractor/timer.js +0 -29
  154. package/dist/esm/extractor/timer.js.map +0 -7
  155. package/dist/esm/extractor/validHTMLAttributes.js +0 -102
  156. package/dist/esm/extractor/validHTMLAttributes.js.map +0 -7
  157. package/dist/esm/getPragmaOptions.js +0 -44
  158. package/dist/esm/getPragmaOptions.js.map +0 -7
  159. package/dist/esm/index.js +0 -17
  160. package/dist/esm/index.js.map +0 -7
  161. package/dist/esm/require.js +0 -62
  162. package/dist/esm/require.js.map +0 -7
  163. package/dist/esm/types.js +0 -1
  164. package/dist/esm/types.js.map +0 -7
  165. package/dist/esm/webpackPlugin.js +0 -11
  166. package/dist/esm/webpackPlugin.js.map +0 -7
  167. package/dist/jsx/constants.js +0 -16
  168. package/dist/jsx/constants.js.map +0 -7
  169. package/dist/jsx/extractor/accessSafe.js +0 -8
  170. package/dist/jsx/extractor/accessSafe.js.map +0 -7
  171. package/dist/jsx/extractor/babelParse.js +0 -28
  172. package/dist/jsx/extractor/babelParse.js.map +0 -7
  173. package/dist/jsx/extractor/buildClassName.js +0 -37
  174. package/dist/jsx/extractor/buildClassName.js.map +0 -7
  175. package/dist/jsx/extractor/createEvaluator.js +0 -52
  176. package/dist/jsx/extractor/createEvaluator.js.map +0 -7
  177. package/dist/jsx/extractor/createExtractor.js +0 -1367
  178. package/dist/jsx/extractor/createExtractor.js.map +0 -7
  179. package/dist/jsx/extractor/ensureImportingConcat.js +0 -21
  180. package/dist/jsx/extractor/ensureImportingConcat.js.map +0 -7
  181. package/dist/jsx/extractor/evaluateAstNode.js +0 -91
  182. package/dist/jsx/extractor/evaluateAstNode.js.map +0 -7
  183. package/dist/jsx/extractor/extractHelpers.js +0 -95
  184. package/dist/jsx/extractor/extractHelpers.js.map +0 -7
  185. package/dist/jsx/extractor/extractMediaStyle.js +0 -145
  186. package/dist/jsx/extractor/extractMediaStyle.js.map +0 -7
  187. package/dist/jsx/extractor/extractToClassNames.js +0 -307
  188. package/dist/jsx/extractor/extractToClassNames.js.map +0 -7
  189. package/dist/jsx/extractor/findTopmostFunction.js +0 -20
  190. package/dist/jsx/extractor/findTopmostFunction.js.map +0 -7
  191. package/dist/jsx/extractor/generatedUid.js +0 -25
  192. package/dist/jsx/extractor/generatedUid.js.map +0 -7
  193. package/dist/jsx/extractor/getPrefixLogs.js +0 -8
  194. package/dist/jsx/extractor/getPrefixLogs.js.map +0 -7
  195. package/dist/jsx/extractor/getPropValueFromAttributes.js +0 -46
  196. package/dist/jsx/extractor/getPropValueFromAttributes.js.map +0 -7
  197. package/dist/jsx/extractor/getSourceModule.js +0 -66
  198. package/dist/jsx/extractor/getSourceModule.js.map +0 -7
  199. package/dist/jsx/extractor/getStaticBindingsForScope.js +0 -172
  200. package/dist/jsx/extractor/getStaticBindingsForScope.js.map +0 -7
  201. package/dist/jsx/extractor/hoistClassNames.js +0 -40
  202. package/dist/jsx/extractor/literalToAst.js +0 -75
  203. package/dist/jsx/extractor/loadFile.js +0 -19
  204. package/dist/jsx/extractor/loadFile.js.map +0 -7
  205. package/dist/jsx/extractor/loadTamagui.js +0 -253
  206. package/dist/jsx/extractor/loadTamagui.js.map +0 -7
  207. package/dist/jsx/extractor/logLines.js +0 -20
  208. package/dist/jsx/extractor/logLines.js.map +0 -7
  209. package/dist/jsx/extractor/normalizeTernaries.js +0 -49
  210. package/dist/jsx/extractor/normalizeTernaries.js.map +0 -7
  211. package/dist/jsx/extractor/removeUnusedHooks.js +0 -75
  212. package/dist/jsx/extractor/removeUnusedHooks.js.map +0 -7
  213. package/dist/jsx/extractor/timer.js +0 -29
  214. package/dist/jsx/extractor/timer.js.map +0 -7
  215. package/dist/jsx/extractor/validHTMLAttributes.js +0 -102
  216. package/dist/jsx/extractor/validHTMLAttributes.js.map +0 -7
  217. package/dist/jsx/getPragmaOptions.js +0 -43
  218. package/dist/jsx/getPragmaOptions.js.map +0 -7
  219. package/dist/jsx/index.js +0 -17
  220. package/dist/jsx/index.js.map +0 -7
  221. package/dist/jsx/require.js +0 -62
  222. package/dist/jsx/require.js.map +0 -7
  223. package/dist/jsx/types.js +0 -1
  224. package/dist/jsx/types.js.map +0 -7
  225. package/dist/jsx/webpackPlugin.js +0 -11
  226. package/dist/jsx/webpackPlugin.js.map +0 -7
@@ -1,1374 +0,0 @@
1
- import { basename, relative } from "path";
2
- import traverse from "@babel/traverse";
3
- import * as t from "@babel/types";
4
- import {
5
- createDOMProps,
6
- expandStyles,
7
- getSplitStyles,
8
- getStylesAtomic,
9
- mediaQueryConfig,
10
- proxyThemeVariables,
11
- pseudoDescriptors
12
- } from "@tamagui/core-node";
13
- import { FAILED_EVAL } from "../constants";
14
- import { createEvaluator, createSafeEvaluator } from "./createEvaluator";
15
- import { evaluateAstNode } from "./evaluateAstNode";
16
- import { attrStr, findComponentName, isInsideTamagui, isPresent, objToStr } from "./extractHelpers";
17
- import { findTopmostFunction } from "./findTopmostFunction";
18
- import { cleanupBeforeExit, getStaticBindingsForScope } from "./getStaticBindingsForScope";
19
- import { literalToAst } from "./literalToAst";
20
- import { loadTamagui, loadTamaguiSync } from "./loadTamagui";
21
- import { logLines } from "./logLines";
22
- import { normalizeTernaries } from "./normalizeTernaries";
23
- import { removeUnusedHooks } from "./removeUnusedHooks";
24
- import { timer } from "./timer";
25
- import { validHTMLAttributes } from "./validHTMLAttributes";
26
- const UNTOUCHED_PROPS = {
27
- key: true,
28
- style: true,
29
- className: true
30
- };
31
- const INLINE_EXTRACTABLE = {
32
- ref: "ref",
33
- key: "key",
34
- ...process.env.TAMAGUI_TARGET === "web" && {
35
- onPress: "onClick",
36
- onHoverIn: "onMouseEnter",
37
- onHoverOut: "onMouseLeave",
38
- onPressIn: "onMouseDown",
39
- onPressOut: "onMouseUp"
40
- }
41
- };
42
- const validHooks = {
43
- useMedia: true,
44
- useTheme: true
45
- };
46
- const isAttr = (x) => x.type === "attr";
47
- const createTernary = (x) => x;
48
- function createExtractor({ logger = console } = { logger: console }) {
49
- if (!process.env.TAMAGUI_TARGET) {
50
- console.log('\u26A0\uFE0F Please set process.env.TAMAGUI_TARGET to either "web" or "native"');
51
- process.exit(1);
52
- }
53
- const shouldAddDebugProp = !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);
54
- let projectInfo = null;
55
- function loadSync(props) {
56
- return projectInfo ||= loadTamaguiSync({
57
- config: props.config || "tamagui.config.ts",
58
- components: props.components || ["tamagui"]
59
- });
60
- }
61
- async function load(props) {
62
- return projectInfo ||= await loadTamagui({
63
- config: props.config || "tamagui.config.ts",
64
- components: props.components || ["tamagui"]
65
- });
66
- }
67
- return {
68
- options: {
69
- logger
70
- },
71
- cleanupBeforeExit,
72
- loadTamagui: load,
73
- loadTamaguiSync: loadSync,
74
- getTamagui() {
75
- return projectInfo == null ? void 0 : projectInfo.tamaguiConfig;
76
- },
77
- parseSync: (f, props) => {
78
- const projectInfo2 = loadSync(props);
79
- return parseWithConfig(projectInfo2, f, props);
80
- },
81
- parse: async (f, props) => {
82
- const projectInfo2 = await load(props);
83
- return parseWithConfig(projectInfo2, f, props);
84
- }
85
- };
86
- function isValidStyleKey(name, staticConfig) {
87
- var _a, _b;
88
- if (!projectInfo) {
89
- throw new Error(`Tamagui extractor not loaded yet`);
90
- }
91
- return !!(!!((_a = staticConfig.validStyles) == null ? void 0 : _a[name]) || !!pseudoDescriptors[name] || ((_b = staticConfig.variants) == null ? void 0 : _b[name]) || (projectInfo == null ? void 0 : projectInfo.tamaguiConfig.shorthands[name]) || (name[0] === "$" ? !!mediaQueryConfig[name.slice(1)] : false));
92
- }
93
- function parseWithConfig({ components, tamaguiConfig }, fileOrPath, {
94
- config = "tamagui.config.ts",
95
- importsWhitelist = ["constants.js"],
96
- evaluateVars = true,
97
- shouldPrintDebug = false,
98
- sourcePath = "",
99
- onExtractTag,
100
- onStyleRule,
101
- getFlattenedNode,
102
- disable,
103
- disableExtraction,
104
- disableExtractInlineMedia,
105
- disableExtractVariables,
106
- disableDebugAttr,
107
- extractStyledDefinitions = false,
108
- prefixLogs,
109
- excludeProps,
110
- target,
111
- ...props
112
- }) {
113
- if (disable) {
114
- return null;
115
- }
116
- if (sourcePath === "") {
117
- throw new Error(`Must provide a source file name`);
118
- }
119
- if (!components) {
120
- throw new Error(`Must provide components`);
121
- }
122
- const isTargetingHTML = target === "html";
123
- const ogDebug = shouldPrintDebug;
124
- const tm = timer();
125
- if (shouldPrintDebug === "verbose") {
126
- console.log("tamagui.config.ts:", { components, config });
127
- }
128
- tm.mark("load-tamagui", !!shouldPrintDebug);
129
- const proxiedTheme = proxyThemeVariables(tamaguiConfig.themes[Object.keys(tamaguiConfig.themes)[0]]);
130
- const themeAccessListeners = /* @__PURE__ */ new Set();
131
- const defaultTheme = new Proxy(proxiedTheme, {
132
- get(target2, key) {
133
- if (key[0] === "$") {
134
- themeAccessListeners.forEach((cb) => cb(String(key)));
135
- }
136
- return Reflect.get(target2, key);
137
- }
138
- });
139
- const body = fileOrPath.type === "Program" ? fileOrPath.get("body") : fileOrPath.program.body;
140
- const isInternalImport = (importStr) => {
141
- return isInsideTamagui(sourcePath) && importStr[0] === ".";
142
- };
143
- const validComponents = Object.keys(components).filter((key) => {
144
- var _a;
145
- return key[0].toUpperCase() === key[0] && !!((_a = components[key]) == null ? void 0 : _a.staticConfig);
146
- }).reduce((obj, name) => {
147
- obj[name] = components[name];
148
- return obj;
149
- }, {});
150
- if (shouldPrintDebug === "verbose") {
151
- logger.info(`validComponents ${Object.keys(validComponents).join(", ")}`);
152
- }
153
- let doesUseValidImport = false;
154
- let hasImportedTheme = false;
155
- for (const bodyPath of body) {
156
- if (bodyPath.type !== "ImportDeclaration")
157
- continue;
158
- const node = "node" in bodyPath ? bodyPath.node : bodyPath;
159
- const from = node.source.value;
160
- const isValidImport = props.components.includes(from) || isInternalImport(from) || from === "@tamagui/core" || from === "tamagui";
161
- if (extractStyledDefinitions) {
162
- if (isValidImport) {
163
- if (node.specifiers.some((specifier) => {
164
- return specifier.local.name === "styled";
165
- })) {
166
- doesUseValidImport = true;
167
- break;
168
- }
169
- }
170
- }
171
- if (isValidImport) {
172
- const isValidComponent = node.specifiers.some((specifier) => {
173
- const name = specifier.local.name;
174
- return !!(validComponents[name] || validHooks[name]);
175
- });
176
- if (shouldPrintDebug === "verbose") {
177
- logger.info(`import from ${from} isValidComponent ${isValidComponent}`);
178
- }
179
- if (isValidComponent) {
180
- doesUseValidImport = true;
181
- break;
182
- }
183
- }
184
- }
185
- if (shouldPrintDebug) {
186
- logger.info(`source: ${sourcePath} doesUseValidImport ${doesUseValidImport}`);
187
- }
188
- if (!doesUseValidImport) {
189
- return null;
190
- }
191
- tm.mark("import-check", !!shouldPrintDebug);
192
- let couldntParse = false;
193
- const modifiedComponents = /* @__PURE__ */ new Set();
194
- const bindingCache = {};
195
- const callTraverse = (a) => {
196
- return fileOrPath.type === "File" ? traverse(fileOrPath, a) : fileOrPath.traverse(a);
197
- };
198
- let programPath;
199
- const res = {
200
- styled: 0,
201
- flattened: 0,
202
- optimized: 0,
203
- modified: 0,
204
- found: 0
205
- };
206
- callTraverse({
207
- Program: {
208
- enter(path) {
209
- programPath = path;
210
- }
211
- },
212
- CallExpression(path) {
213
- var _a, _b;
214
- if (disable || disableExtraction || extractStyledDefinitions === false) {
215
- return;
216
- }
217
- if (!t.isIdentifier(path.node.callee) || path.node.callee.name !== "styled") {
218
- return;
219
- }
220
- const name = t.isVariableDeclarator(path.parent) && t.isIdentifier(path.parent.id) ? path.parent.id.name : "unknown";
221
- const definition = path.node.arguments[1];
222
- if (!name || !definition || !t.isObjectExpression(definition)) {
223
- return;
224
- }
225
- let Component = validComponents[name];
226
- if (!Component) {
227
- if (shouldPrintDebug) {
228
- logger.info(`Didn't recognize styled(${name}), ${name} isn't in design system provided to tamagui.config.ts. Will attempt to build isolated and analyze.. ${programPath}`);
229
- }
230
- const out2 = loadTamaguiSync({
231
- components: [sourcePath]
232
- });
233
- if ((_a = out2.components) == null ? void 0 : _a[name]) {
234
- Object.assign(validComponents, out2.components);
235
- }
236
- Component = validComponents[name];
237
- if (shouldPrintDebug) {
238
- logger.info([`Loaded`, Object.keys(out2.components).join(", "), !!Component].join(" "));
239
- }
240
- }
241
- if (!Component) {
242
- return;
243
- }
244
- const componentSkipProps = /* @__PURE__ */ new Set([
245
- ...Component.staticConfig.inlineWhenUnflattened || [],
246
- ...Component.staticConfig.inlineProps || [],
247
- ...Component.staticConfig.deoptProps || [],
248
- "variants",
249
- "defaultVariants",
250
- "fontFamily",
251
- "name"
252
- ]);
253
- const skipped = [];
254
- const styles = {};
255
- const staticNamespace = getStaticBindingsForScope(path.scope, importsWhitelist, sourcePath, bindingCache, shouldPrintDebug);
256
- const attemptEval = !evaluateVars ? evaluateAstNode : createEvaluator({
257
- tamaguiConfig,
258
- staticNamespace,
259
- sourcePath,
260
- shouldPrintDebug
261
- });
262
- const attemptEvalSafe = createSafeEvaluator(attemptEval);
263
- for (const property of definition.properties) {
264
- if (!t.isObjectProperty(property) || !t.isIdentifier(property.key) || !isValidStyleKey(property.key.name, Component.staticConfig) || ((_b = Component.staticConfig.variants) == null ? void 0 : _b[property.key.name]) || componentSkipProps.has(property.key.name)) {
265
- skipped.push(property);
266
- continue;
267
- }
268
- const out2 = attemptEvalSafe(property.value);
269
- if (out2 === FAILED_EVAL) {
270
- skipped.push(property);
271
- } else {
272
- styles[property.key.name] = out2;
273
- }
274
- }
275
- const out = getSplitStyles(styles, Component.staticConfig, defaultTheme, {
276
- focus: false,
277
- hover: false,
278
- mounted: false,
279
- press: false,
280
- pressIn: false,
281
- resolveVariablesAs: "variable"
282
- });
283
- const classNames = {
284
- ...out.classNames
285
- };
286
- const atomics = getStylesAtomic(out.style);
287
- for (const atomic of atomics) {
288
- out.rulesToInsert = out.rulesToInsert || [];
289
- out.rulesToInsert.push(atomic);
290
- classNames[atomic.property] = atomic.identifier;
291
- }
292
- if (shouldPrintDebug) {
293
- logger.info([`Extracted styled(${name})
294
- `, JSON.stringify(styles, null, 2), "\n=>\n", out.rulesToInsert.flatMap((rule) => rule.rules).join("\n")].join(" "));
295
- }
296
- definition.properties = skipped;
297
- for (const cn in classNames) {
298
- if (componentSkipProps.has(cn)) {
299
- continue;
300
- }
301
- const val = classNames[cn];
302
- definition.properties.push(t.objectProperty(t.stringLiteral(cn), t.stringLiteral(val)));
303
- }
304
- if (out.rulesToInsert) {
305
- for (const { identifier, rules } of out.rulesToInsert) {
306
- onStyleRule == null ? void 0 : onStyleRule(identifier, rules);
307
- }
308
- }
309
- res.styled++;
310
- if (shouldPrintDebug) {
311
- logger.info(`Extracted styled(${name})`);
312
- }
313
- },
314
- JSXElement(traversePath) {
315
- var _a, _b, _c;
316
- tm.mark("jsx-element", !!shouldPrintDebug);
317
- const node = traversePath.node.openingElement;
318
- const ogAttributes = node.attributes;
319
- const componentName = findComponentName(traversePath.scope);
320
- const closingElement = traversePath.node.closingElement;
321
- if (t.isJSXMemberExpression(closingElement == null ? void 0 : closingElement.name) || !t.isJSXIdentifier(node.name)) {
322
- return;
323
- }
324
- const binding = traversePath.scope.getBinding(node.name.name);
325
- if (binding) {
326
- if (!t.isImportDeclaration(binding.path.parent)) {
327
- return;
328
- }
329
- const source = binding.path.parent.source;
330
- if (!props.components.includes(source.value) && !isInternalImport(source.value)) {
331
- return;
332
- }
333
- if (!validComponents[binding.identifier.name]) {
334
- return;
335
- }
336
- }
337
- const component = validComponents[node.name.name];
338
- if (!component || !component.staticConfig) {
339
- return;
340
- }
341
- const originalNodeName = node.name.name;
342
- res.found++;
343
- const filePath = `./${relative(process.cwd(), sourcePath)}`;
344
- const lineNumbers = node.loc ? node.loc.start.line + (node.loc.start.line !== node.loc.end.line ? `-${node.loc.end.line}` : "") : "";
345
- const codePosition = `${filePath}:${lineNumbers}`;
346
- const debugPropValue = node.attributes.filter((n) => t.isJSXAttribute(n) && t.isJSXIdentifier(n.name) && n.name.name === "debug").map((n) => {
347
- if (n.value === null)
348
- return true;
349
- if (t.isStringLiteral(n.value))
350
- return n.value.value;
351
- return false;
352
- })[0];
353
- if (debugPropValue) {
354
- shouldPrintDebug = debugPropValue;
355
- }
356
- if (shouldPrintDebug) {
357
- logger.info("\n");
358
- logger.info(`\x1B[33m%s\x1B[0m ${componentName} | ${codePosition} -------------------`);
359
- logger.info(["\x1B[1m", "\x1B[32m", `<${originalNodeName} />`, disableDebugAttr ? "" : "\u{1F41B}"].join(" "));
360
- }
361
- if (shouldAddDebugProp && !disableDebugAttr) {
362
- res.modified++;
363
- node.attributes.unshift(t.jsxAttribute(t.jsxIdentifier("data-is"), t.stringLiteral(node.name.name)));
364
- if (componentName) {
365
- node.attributes.unshift(t.jsxAttribute(t.jsxIdentifier("data-in"), t.stringLiteral(componentName)));
366
- }
367
- node.attributes.unshift(t.jsxAttribute(t.jsxIdentifier("data-at"), t.stringLiteral(`${basename(filePath)}:${lineNumbers}`)));
368
- }
369
- if (disableExtraction) {
370
- return;
371
- }
372
- try {
373
- let evaluateAttribute2 = function(path) {
374
- const attribute = path.node;
375
- const attr = { type: "attr", value: attribute };
376
- if (t.isJSXSpreadAttribute(attribute)) {
377
- const arg = attribute.argument;
378
- const conditional = t.isConditionalExpression(arg) ? [arg.test, arg.consequent, arg.alternate] : t.isLogicalExpression(arg) && arg.operator === "&&" ? [arg.left, arg.right, null] : null;
379
- if (conditional) {
380
- const [test, alt, cons] = conditional;
381
- if (!test)
382
- throw new Error(`no test`);
383
- if ([alt, cons].some((side) => side && !isExtractable2(side))) {
384
- if (shouldPrintDebug) {
385
- logger.info(`not extractable ${alt} ${cons}`);
386
- }
387
- return attr;
388
- }
389
- return [
390
- ...createTernariesFromObjectProperties2(test, alt) || [],
391
- ...cons && createTernariesFromObjectProperties2(t.unaryExpression("!", test), cons) || []
392
- ].map((ternary) => ({
393
- type: "ternary",
394
- value: ternary
395
- }));
396
- }
397
- }
398
- if (t.isJSXSpreadAttribute(attribute) || !attribute.name || typeof attribute.name.name !== "string") {
399
- if (shouldPrintDebug) {
400
- logger.info(" ! inlining, spread attr");
401
- }
402
- inlined.set(`${Math.random()}`, "spread");
403
- return attr;
404
- }
405
- const name = attribute.name.name;
406
- if (excludeProps == null ? void 0 : excludeProps.has(name)) {
407
- if (shouldPrintDebug) {
408
- logger.info([" excluding prop", name].join(" "));
409
- }
410
- return null;
411
- }
412
- if (inlineProps.has(name)) {
413
- inlined.set(name, name);
414
- if (shouldPrintDebug) {
415
- logger.info([" ! inlining, inline prop", name].join(" "));
416
- }
417
- return attr;
418
- }
419
- if (deoptProps.has(name)) {
420
- shouldDeopt = true;
421
- inlined.set(name, name);
422
- if (shouldPrintDebug) {
423
- logger.info([" ! inlining, deopted prop", name].join(" "));
424
- }
425
- return attr;
426
- }
427
- if (UNTOUCHED_PROPS[name]) {
428
- return attr;
429
- }
430
- if (INLINE_EXTRACTABLE[name]) {
431
- inlined.set(name, INLINE_EXTRACTABLE[name]);
432
- return attr;
433
- }
434
- if (name.startsWith("data-")) {
435
- return attr;
436
- }
437
- if (name[0] === "$" && t.isJSXExpressionContainer(attribute == null ? void 0 : attribute.value)) {
438
- if (disableExtractInlineMedia) {
439
- return attr;
440
- }
441
- const shortname = name.slice(1);
442
- if (mediaQueryConfig[shortname]) {
443
- const expression = attribute.value.expression;
444
- if (!t.isJSXEmptyExpression(expression)) {
445
- const ternaries2 = createTernariesFromObjectProperties2(t.stringLiteral(shortname), expression, {
446
- inlineMediaQuery: shortname
447
- });
448
- if (ternaries2) {
449
- return ternaries2.map((value2) => ({
450
- type: "ternary",
451
- value: value2
452
- }));
453
- }
454
- }
455
- }
456
- }
457
- const [value, valuePath] = (() => {
458
- if (t.isJSXExpressionContainer(attribute == null ? void 0 : attribute.value)) {
459
- return [attribute.value.expression, path.get("value")];
460
- } else {
461
- return [attribute.value, path.get("value")];
462
- }
463
- })();
464
- const remove = () => {
465
- Array.isArray(valuePath) ? valuePath.map((p) => p.remove()) : valuePath.remove();
466
- };
467
- if (name === "ref") {
468
- if (shouldPrintDebug) {
469
- logger.info([" ! inlining, ref", name].join(" "));
470
- }
471
- inlined.set("ref", "ref");
472
- return attr;
473
- }
474
- if (name === "tag") {
475
- return {
476
- type: "attr",
477
- value: path.node
478
- };
479
- }
480
- if (disableExtractVariables) {
481
- if (value) {
482
- if (value.type === "StringLiteral" && value.value[0] === "$") {
483
- if (shouldPrintDebug) {
484
- logger.info([` ! inlining, native disable extract: ${name} =`, value.value].join(" "));
485
- }
486
- inlined.set(name, true);
487
- return attr;
488
- }
489
- }
490
- }
491
- if (name === "theme") {
492
- inlined.set("theme", attr.value);
493
- return attr;
494
- }
495
- const styleValue = attemptEvalSafe(value);
496
- if (!variants[name] && !isValidStyleKey(name, staticConfig)) {
497
- let keys = [name];
498
- let out = null;
499
- out = staticConfig.propMapper(name, styleValue, defaultTheme, staticConfig.defaultProps, { resolveVariablesAs: "auto" }, void 0, void 0, shouldPrintDebug);
500
- if (out) {
501
- if (!Array.isArray(out)) {
502
- logger.warn(`Error expected array but got`, out);
503
- couldntParse = true;
504
- shouldDeopt = true;
505
- } else {
506
- out = Object.fromEntries(out);
507
- keys = Object.keys(out);
508
- }
509
- }
510
- if (out) {
511
- if (isTargetingHTML) {
512
- out = createDOMProps(isTextView ? "span" : "div", out);
513
- delete out.className;
514
- }
515
- keys = Object.keys(out);
516
- }
517
- let didInline = false;
518
- const attributes = keys.map((key) => {
519
- const val = out[key];
520
- if (isValidStyleKey(key, staticConfig)) {
521
- return {
522
- type: "style",
523
- value: { [key]: styleValue },
524
- name: key,
525
- attr: path.node
526
- };
527
- }
528
- if (validHTMLAttributes[key] || key.startsWith("aria-") || key.startsWith("data-")) {
529
- return attr;
530
- }
531
- if (shouldPrintDebug) {
532
- logger.info(" ! inlining, non-static " + key);
533
- }
534
- didInline = true;
535
- inlined.set(key, val);
536
- return val;
537
- });
538
- if (didInline) {
539
- if (shouldPrintDebug) {
540
- logger.info(` bailing flattening due to attributes ${attributes}`);
541
- }
542
- return attr;
543
- }
544
- return attributes;
545
- }
546
- if (styleValue !== FAILED_EVAL) {
547
- if (inlineWhenUnflattened.has(name)) {
548
- inlineWhenUnflattenedOGVals[name] = { styleValue, attr };
549
- }
550
- if (isValidStyleKey(name, staticConfig)) {
551
- if (shouldPrintDebug) {
552
- logger.info(` style: ${name} = ${styleValue}`);
553
- }
554
- if (!(name in staticConfig.defaultProps)) {
555
- if (!hasSetOptimized) {
556
- res.optimized++;
557
- hasSetOptimized = true;
558
- }
559
- }
560
- return {
561
- type: "style",
562
- value: { [name]: styleValue },
563
- name,
564
- attr: path.node
565
- };
566
- } else {
567
- if (variants[name]) {
568
- variantValues.set(name, styleValue);
569
- }
570
- inlined.set(name, true);
571
- return attr;
572
- }
573
- }
574
- if (t.isBinaryExpression(value)) {
575
- if (shouldPrintDebug) {
576
- logger.info(` binary expression ${name} = ${value}`);
577
- }
578
- const { operator, left, right } = value;
579
- const lVal = attemptEvalSafe(left);
580
- const rVal = attemptEvalSafe(right);
581
- if (shouldPrintDebug) {
582
- logger.info(` evalBinaryExpression lVal ${String(lVal)}, rVal ${String(rVal)}`);
583
- }
584
- if (lVal !== FAILED_EVAL && t.isConditionalExpression(right)) {
585
- const ternary = addBinaryConditional(operator, left, right);
586
- if (ternary)
587
- return ternary;
588
- }
589
- if (rVal !== FAILED_EVAL && t.isConditionalExpression(left)) {
590
- const ternary = addBinaryConditional(operator, right, left);
591
- if (ternary)
592
- return ternary;
593
- }
594
- if (shouldPrintDebug) {
595
- logger.info(` evalBinaryExpression cant extract`);
596
- }
597
- inlined.set(name, true);
598
- return attr;
599
- }
600
- const staticConditional = getStaticConditional(value);
601
- if (staticConditional) {
602
- if (shouldPrintDebug === "verbose") {
603
- logger.info(` static conditional ${name} ${value}`);
604
- }
605
- return { type: "ternary", value: staticConditional };
606
- }
607
- const staticLogical = getStaticLogical(value);
608
- if (staticLogical) {
609
- if (shouldPrintDebug === "verbose") {
610
- logger.info(` static ternary ${name} = ${value}`);
611
- }
612
- return { type: "ternary", value: staticLogical };
613
- }
614
- inlined.set(name, true);
615
- if (shouldPrintDebug) {
616
- logger.info(` ! inline no match ${name} ${value}`);
617
- }
618
- return attr;
619
- function addBinaryConditional(operator, staticExpr, cond) {
620
- if (getStaticConditional(cond)) {
621
- const alt = attemptEval(t.binaryExpression(operator, staticExpr, cond.alternate));
622
- const cons = attemptEval(t.binaryExpression(operator, staticExpr, cond.consequent));
623
- if (shouldPrintDebug) {
624
- logger.info([" binaryConditional", cond.test, cons, alt].join(" "));
625
- }
626
- return {
627
- type: "ternary",
628
- value: {
629
- test: cond.test,
630
- remove,
631
- alternate: { [name]: alt },
632
- consequent: { [name]: cons }
633
- }
634
- };
635
- }
636
- return null;
637
- }
638
- function getStaticConditional(value2) {
639
- if (t.isConditionalExpression(value2)) {
640
- try {
641
- const aVal = attemptEval(value2.alternate);
642
- const cVal = attemptEval(value2.consequent);
643
- if (shouldPrintDebug) {
644
- const type = value2.test.type;
645
- logger.info([" static ternary", type, cVal, aVal].join(" "));
646
- }
647
- return {
648
- test: value2.test,
649
- remove,
650
- consequent: { [name]: cVal },
651
- alternate: { [name]: aVal }
652
- };
653
- } catch (err) {
654
- if (shouldPrintDebug) {
655
- logger.info([" cant eval ternary", err.message].join(" "));
656
- }
657
- }
658
- }
659
- return null;
660
- }
661
- function getStaticLogical(value2) {
662
- if (t.isLogicalExpression(value2)) {
663
- if (value2.operator === "&&") {
664
- try {
665
- const val = attemptEval(value2.right);
666
- if (shouldPrintDebug) {
667
- logger.info([" staticLogical", value2.left, name, val].join(" "));
668
- }
669
- return {
670
- test: value2.left,
671
- remove,
672
- consequent: { [name]: val },
673
- alternate: null
674
- };
675
- } catch (err) {
676
- if (shouldPrintDebug) {
677
- logger.info([" cant static eval logical", err].join(" "));
678
- }
679
- }
680
- }
681
- }
682
- return null;
683
- }
684
- }, isExtractable2 = function(obj) {
685
- return t.isObjectExpression(obj) && obj.properties.every((prop) => {
686
- if (!t.isObjectProperty(prop)) {
687
- logger.info(["not object prop", prop].join(" "));
688
- return false;
689
- }
690
- const propName = prop.key["name"];
691
- if (!isValidStyleKey(propName, staticConfig) && propName !== "tag") {
692
- if (shouldPrintDebug) {
693
- logger.info([" not a valid style prop!", propName].join(" "));
694
- }
695
- return false;
696
- }
697
- return true;
698
- });
699
- }, createTernariesFromObjectProperties2 = function(test, side, ternaryPartial = {}) {
700
- if (!side) {
701
- return null;
702
- }
703
- if (!isExtractable2(side)) {
704
- throw new Error("not extractable");
705
- }
706
- return side.properties.flatMap((property) => {
707
- if (!t.isObjectProperty(property)) {
708
- throw new Error("expected object property");
709
- }
710
- if (t.isIdentifier(property.key)) {
711
- const key = property.key.name;
712
- const mediaQueryKey = key.slice(1);
713
- const isMediaQuery = key[0] === "$" && mediaQueryConfig[mediaQueryKey];
714
- if (isMediaQuery) {
715
- if (t.isExpression(property.value)) {
716
- const ternaries2 = createTernariesFromObjectProperties2(t.stringLiteral(mediaQueryKey), property.value, {
717
- inlineMediaQuery: mediaQueryKey
718
- });
719
- if (ternaries2) {
720
- return ternaries2.map((value) => ({
721
- ...ternaryPartial,
722
- ...value,
723
- test: t.logicalExpression("&&", value.test, test)
724
- }));
725
- } else {
726
- logger.info(["\u26A0\uFE0F no ternaries?", property].join(" "));
727
- }
728
- } else {
729
- logger.info(["\u26A0\uFE0F not expression", property].join(" "));
730
- }
731
- }
732
- }
733
- if (t.isConditionalExpression(property.value)) {
734
- const [truthy, falsy] = [
735
- t.objectExpression([t.objectProperty(property.key, property.value.consequent)]),
736
- t.objectExpression([t.objectProperty(property.key, property.value.alternate)])
737
- ].map((x) => attemptEval(x));
738
- return [
739
- createTernary({
740
- remove() {
741
- },
742
- ...ternaryPartial,
743
- test: t.logicalExpression("&&", test, property.value.test),
744
- consequent: truthy,
745
- alternate: null
746
- }),
747
- createTernary({
748
- ...ternaryPartial,
749
- test: t.logicalExpression("&&", test, t.unaryExpression("!", property.value.test)),
750
- consequent: falsy,
751
- alternate: null,
752
- remove() {
753
- }
754
- })
755
- ];
756
- }
757
- const obj = t.objectExpression([t.objectProperty(property.key, property.value)]);
758
- const consequent = attemptEval(obj);
759
- return createTernary({
760
- remove() {
761
- },
762
- ...ternaryPartial,
763
- test,
764
- consequent,
765
- alternate: null
766
- });
767
- });
768
- }, splitVariants2 = function(style) {
769
- var _a2;
770
- const variants2 = {};
771
- const styles = {};
772
- for (const key in style) {
773
- if ((_a2 = staticConfig.variants) == null ? void 0 : _a2[key]) {
774
- variants2[key] = style[key];
775
- } else {
776
- styles[key] = style[key];
777
- }
778
- }
779
- return {
780
- variants: variants2,
781
- styles
782
- };
783
- }, expandStylesWithoutVariants2 = function(style) {
784
- const { variants: variants2, styles } = splitVariants2(style);
785
- return {
786
- ...expandStyles(styles),
787
- ...variants2
788
- };
789
- }, mergeStyles2 = function(prev2, nextIn) {
790
- const next = expandStylesWithoutVariants2(nextIn);
791
- for (const key in next) {
792
- if (pseudoDescriptors[key]) {
793
- prev2[key] = prev2[key] || {};
794
- if (shouldPrintDebug) {
795
- if (!next[key] || !prev2[key]) {
796
- logger.info(["warn: missing", key, prev2, next].join(" "));
797
- }
798
- }
799
- Object.assign(prev2[key], next[key]);
800
- } else {
801
- prev2[key] = next[key];
802
- }
803
- }
804
- };
805
- var evaluateAttribute = evaluateAttribute2, isExtractable = isExtractable2, createTernariesFromObjectProperties = createTernariesFromObjectProperties2, splitVariants = splitVariants2, expandStylesWithoutVariants = expandStylesWithoutVariants2, mergeStyles = mergeStyles2;
806
- const { staticConfig } = component;
807
- const variants = staticConfig.variants || {};
808
- const isTextView = staticConfig.isText || false;
809
- const validStyles = (staticConfig == null ? void 0 : staticConfig.validStyles) ?? {};
810
- let tagName = staticConfig.defaultProps.tag ?? (isTextView ? "span" : "div");
811
- traversePath.get("openingElement").get("attributes").forEach((path) => {
812
- const attr = path.node;
813
- if (t.isJSXSpreadAttribute(attr))
814
- return;
815
- if (attr.name.name !== "tag")
816
- return;
817
- const val = attr.value;
818
- if (!t.isStringLiteral(val))
819
- return;
820
- tagName = val.value;
821
- });
822
- const flatNode = getFlattenedNode({ isTextView, tag: tagName });
823
- const inlineProps = /* @__PURE__ */ new Set([
824
- ...props.inlineProps || [],
825
- ...staticConfig.inlineProps || []
826
- ]);
827
- const deoptProps = /* @__PURE__ */ new Set([
828
- "animation",
829
- ...props.deoptProps || [],
830
- ...staticConfig.deoptProps || []
831
- ]);
832
- const inlineWhenUnflattened = /* @__PURE__ */ new Set([...staticConfig.inlineWhenUnflattened || []]);
833
- const staticNamespace = getStaticBindingsForScope(traversePath.scope, importsWhitelist, sourcePath, bindingCache, shouldPrintDebug);
834
- const attemptEval = !evaluateVars ? evaluateAstNode : createEvaluator({
835
- tamaguiConfig,
836
- staticNamespace,
837
- sourcePath,
838
- traversePath,
839
- shouldPrintDebug
840
- });
841
- const attemptEvalSafe = createSafeEvaluator(attemptEval);
842
- if (shouldPrintDebug) {
843
- logger.info(` staticNamespace ${Object.keys(staticNamespace).join(", ")}`);
844
- }
845
- const flattenedAttrs = [];
846
- traversePath.get("openingElement").get("attributes").forEach((path) => {
847
- const attr = path.node;
848
- if (!t.isJSXSpreadAttribute(attr)) {
849
- flattenedAttrs.push(attr);
850
- return;
851
- }
852
- let arg;
853
- try {
854
- arg = attemptEval(attr.argument);
855
- } catch (e) {
856
- if (shouldPrintDebug) {
857
- logger.info([" couldnt parse spread", e.message].join(" "));
858
- }
859
- flattenedAttrs.push(attr);
860
- return;
861
- }
862
- if (arg !== void 0) {
863
- try {
864
- if (typeof arg !== "object" || arg == null) {
865
- if (shouldPrintDebug) {
866
- logger.info([" non object or null arg", arg].join(" "));
867
- }
868
- flattenedAttrs.push(attr);
869
- } else {
870
- for (const k in arg) {
871
- const value = arg[k];
872
- if (!value && typeof value === "object") {
873
- logger.error(["Unhandled null prop", k, value, arg].join(" "));
874
- continue;
875
- }
876
- flattenedAttrs.push(t.jsxAttribute(t.jsxIdentifier(k), t.jsxExpressionContainer(literalToAst(value))));
877
- }
878
- }
879
- } catch (err) {
880
- logger.warn(`cant parse spread, caught err ${err}`);
881
- couldntParse = true;
882
- }
883
- }
884
- });
885
- if (couldntParse) {
886
- return;
887
- }
888
- tm.mark("jsx-element-flattened", !!shouldPrintDebug);
889
- node.attributes = flattenedAttrs;
890
- let attrs = [];
891
- let shouldDeopt = false;
892
- const inlined = /* @__PURE__ */ new Map();
893
- const variantValues = /* @__PURE__ */ new Map();
894
- let hasSetOptimized = false;
895
- const inlineWhenUnflattenedOGVals = {};
896
- attrs = traversePath.get("openingElement").get("attributes").flatMap((path) => {
897
- try {
898
- const res2 = evaluateAttribute2(path);
899
- tm.mark("jsx-element-evaluate-attr", !!shouldPrintDebug);
900
- if (!res2) {
901
- path.remove();
902
- }
903
- return res2;
904
- } catch (err) {
905
- if (shouldPrintDebug) {
906
- logger.info(["Error extracting attribute", err.message, err.stack].join(" "));
907
- logger.info(`node ${path.node}`);
908
- }
909
- inlined.set(`${Math.random()}`, "spread");
910
- return {
911
- type: "attr",
912
- value: path.node
913
- };
914
- }
915
- }).flat(4).filter(isPresent);
916
- if (shouldPrintDebug) {
917
- logger.info([" - attrs (before):\n", logLines(attrs.map(attrStr).join(", "))].join(" "));
918
- }
919
- node.attributes = attrs.filter(isAttr).map((x) => x.value);
920
- if (couldntParse || shouldDeopt) {
921
- if (shouldPrintDebug) {
922
- logger.info([` avoid optimizing:`, { couldntParse, shouldDeopt }].join(" "));
923
- }
924
- node.attributes = ogAttributes;
925
- return;
926
- }
927
- const parentFn = findTopmostFunction(traversePath);
928
- if (parentFn) {
929
- modifiedComponents.add(parentFn);
930
- }
931
- let ternaries = [];
932
- attrs = attrs.reduce((out, cur) => {
933
- const next = attrs[attrs.indexOf(cur) + 1];
934
- if (cur.type === "ternary") {
935
- ternaries.push(cur.value);
936
- }
937
- if ((!next || next.type !== "ternary") && ternaries.length) {
938
- const normalized = normalizeTernaries(ternaries).map(({ alternate, consequent, ...rest }) => {
939
- return {
940
- type: "ternary",
941
- value: {
942
- ...rest,
943
- alternate: alternate || null,
944
- consequent: consequent || null
945
- }
946
- };
947
- });
948
- try {
949
- return [...out, ...normalized];
950
- } finally {
951
- if (shouldPrintDebug) {
952
- logger.info(` normalizeTernaries (${ternaries.length} => ${normalized.length})`);
953
- }
954
- ternaries = [];
955
- }
956
- }
957
- if (cur.type === "ternary") {
958
- return out;
959
- }
960
- out.push(cur);
961
- return out;
962
- }, []).flat();
963
- const hasSpread = node.attributes.some((x) => t.isJSXSpreadAttribute(x));
964
- const hasOnlyStringChildren = !hasSpread && (node.selfClosing || traversePath.node.children && traversePath.node.children.every((x) => x.type === "JSXText"));
965
- const themeVal = inlined.get("theme");
966
- inlined.delete("theme");
967
- for (const [key] of [...inlined]) {
968
- const isExtractableVariant = ((_a = staticConfig.variants) == null ? void 0 : _a[key]) && variantValues.has(key);
969
- if (INLINE_EXTRACTABLE[key] || isExtractableVariant) {
970
- inlined.delete(key);
971
- }
972
- }
973
- const canFlattenProps = inlined.size === 0;
974
- let shouldFlatten = !shouldDeopt && canFlattenProps && !hasSpread && staticConfig.neverFlatten !== true && (staticConfig.neverFlatten === "jsx" ? hasOnlyStringChildren : true);
975
- const shouldWrapTheme = shouldFlatten && themeVal;
976
- if (disableExtractVariables) {
977
- themeAccessListeners.add((key) => {
978
- shouldFlatten = false;
979
- if (shouldPrintDebug) {
980
- logger.info([" ! accessing theme key, avoid flatten", key].join(" "));
981
- }
982
- });
983
- }
984
- if (shouldPrintDebug) {
985
- logger.info([" - flatten?", objToStr({ hasSpread, shouldDeopt, shouldFlatten, canFlattenProps, shouldWrapTheme, hasOnlyStringChildren }), "inlined", [...inlined]].join(" "));
986
- }
987
- if (shouldFlatten && shouldWrapTheme) {
988
- if (shouldPrintDebug) {
989
- logger.info([" - wrapping theme", themeVal].join(" "));
990
- }
991
- attrs = attrs.filter((x) => x.type === "attr" && t.isJSXAttribute(x.value) && x.value.name.name === "theme" ? false : true);
992
- if (!hasImportedTheme) {
993
- hasImportedTheme = true;
994
- programPath.node.body.push(t.importDeclaration([t.importSpecifier(t.identifier("_TamaguiTheme"), t.identifier("Theme"))], t.stringLiteral("@tamagui/core")));
995
- }
996
- traversePath.replaceWith(t.jsxElement(t.jsxOpeningElement(t.jsxIdentifier("_TamaguiTheme"), [
997
- t.jsxAttribute(t.jsxIdentifier("name"), themeVal.value)
998
- ]), t.jsxClosingElement(t.jsxIdentifier("_TamaguiTheme")), [traversePath.node]));
999
- }
1000
- if (shouldFlatten) {
1001
- const defaultStyleAttrs = Object.keys(staticConfig.defaultProps).flatMap((key) => {
1002
- if (!isValidStyleKey(key, staticConfig)) {
1003
- return [];
1004
- }
1005
- const value = staticConfig.defaultProps[key];
1006
- const name = tamaguiConfig.shorthands[key] || key;
1007
- if (value === void 0) {
1008
- logger.warn(`\u26A0\uFE0F Error evaluating default style for component, prop ${key} ${value}`);
1009
- shouldDeopt = true;
1010
- return;
1011
- }
1012
- const attr = {
1013
- type: "style",
1014
- name,
1015
- value: { [name]: value }
1016
- };
1017
- return attr;
1018
- });
1019
- if (defaultStyleAttrs.length) {
1020
- attrs = [...defaultStyleAttrs, ...attrs];
1021
- }
1022
- }
1023
- if (shouldDeopt) {
1024
- node.attributes = ogAttributes;
1025
- return;
1026
- }
1027
- const ensureOverridden = {};
1028
- if (!shouldFlatten) {
1029
- for (const cur of attrs) {
1030
- if (cur.type === "style") {
1031
- for (const key in cur.value) {
1032
- const shouldEnsureOverridden = !!((_b = staticConfig.ensureOverriddenProp) == null ? void 0 : _b[key]);
1033
- const isSetInAttrsAlready = attrs.some((x) => x.type === "attr" && x.value.type === "JSXAttribute" && x.value.name.name === key);
1034
- if (!isSetInAttrsAlready) {
1035
- const isVariant = !!((_c = staticConfig.variants) == null ? void 0 : _c[cur.name || ""]);
1036
- if (isVariant || shouldEnsureOverridden) {
1037
- ensureOverridden[key] = true;
1038
- }
1039
- }
1040
- }
1041
- }
1042
- }
1043
- }
1044
- if (shouldPrintDebug) {
1045
- logger.info([" - attrs (flattened): \n", logLines(attrs.map(attrStr).join(", "))].join(" "));
1046
- logger.info([" - ensureOverriden:", Object.keys(ensureOverridden).join(", ")].join(" "));
1047
- }
1048
- const state = {
1049
- noClassNames: false,
1050
- focus: false,
1051
- hover: false,
1052
- mounted: true,
1053
- press: false,
1054
- pressIn: false
1055
- };
1056
- let foundStaticProps = {};
1057
- for (const key in attrs) {
1058
- const cur = attrs[key];
1059
- if (cur.type === "style") {
1060
- foundStaticProps = {
1061
- ...foundStaticProps,
1062
- ...expandStylesWithoutVariants2(cur.value)
1063
- };
1064
- continue;
1065
- }
1066
- if (cur.type === "attr") {
1067
- if (t.isJSXSpreadAttribute(cur.value)) {
1068
- continue;
1069
- }
1070
- if (!t.isJSXIdentifier(cur.value.name)) {
1071
- continue;
1072
- }
1073
- const key2 = cur.value.name.name;
1074
- const value = attemptEvalSafe(cur.value.value || t.booleanLiteral(true));
1075
- if (value !== FAILED_EVAL) {
1076
- foundStaticProps = {
1077
- ...foundStaticProps,
1078
- [key2]: value
1079
- };
1080
- }
1081
- }
1082
- }
1083
- const completeProps = {};
1084
- for (const key in staticConfig.defaultProps) {
1085
- if (!(key in foundStaticProps)) {
1086
- completeProps[key] = staticConfig.defaultProps[key];
1087
- }
1088
- }
1089
- for (const key in foundStaticProps) {
1090
- completeProps[key] = foundStaticProps[key];
1091
- }
1092
- attrs = attrs.reduce((acc, cur) => {
1093
- if (!cur)
1094
- return acc;
1095
- if (cur.type === "attr" && !t.isJSXSpreadAttribute(cur.value)) {
1096
- if (shouldFlatten) {
1097
- const name = cur.value.name.name;
1098
- if (typeof name === "string") {
1099
- if (name === "tag") {
1100
- return acc;
1101
- }
1102
- if (variants[name] && variantValues.has(name)) {
1103
- let out = Object.fromEntries(staticConfig.propMapper(name, variantValues.get(name), defaultTheme, completeProps, { ...state, resolveVariablesAs: "auto" }, void 0, void 0, shouldPrintDebug) || []);
1104
- if (out && isTargetingHTML) {
1105
- const cn = out.className;
1106
- out = createDOMProps(isTextView ? "span" : "div", out);
1107
- out.className = cn;
1108
- }
1109
- if (shouldPrintDebug) {
1110
- logger.info([" - expanded variant", name, out].join(" "));
1111
- }
1112
- for (const key2 in out) {
1113
- const value2 = out[key2];
1114
- if (isValidStyleKey(key2, staticConfig)) {
1115
- acc.push({
1116
- type: "style",
1117
- value: { [key2]: value2 },
1118
- name: key2,
1119
- attr: cur.value
1120
- });
1121
- } else {
1122
- acc.push({
1123
- type: "attr",
1124
- value: t.jsxAttribute(t.jsxIdentifier(key2), t.jsxExpressionContainer(typeof value2 === "string" ? t.stringLiteral(value2) : literalToAst(value2)))
1125
- });
1126
- }
1127
- }
1128
- }
1129
- }
1130
- }
1131
- }
1132
- if (cur.type !== "style") {
1133
- acc.push(cur);
1134
- return acc;
1135
- }
1136
- let key = Object.keys(cur.value)[0];
1137
- const value = cur.value[key];
1138
- const fullKey = tamaguiConfig.shorthands[key];
1139
- if (fullKey) {
1140
- cur.value = { [fullKey]: value };
1141
- key = fullKey;
1142
- }
1143
- if (disableExtractVariables) {
1144
- if (value[0] === "$") {
1145
- if (shouldPrintDebug) {
1146
- logger.info([` keeping variable inline: ${key} =`, value].join(" "));
1147
- }
1148
- acc.push({
1149
- type: "attr",
1150
- value: t.jsxAttribute(t.jsxIdentifier(key), t.jsxExpressionContainer(t.stringLiteral(value)))
1151
- });
1152
- return acc;
1153
- }
1154
- }
1155
- acc.push(cur);
1156
- return acc;
1157
- }, []);
1158
- tm.mark("jsx-element-expanded", !!shouldPrintDebug);
1159
- if (shouldPrintDebug) {
1160
- logger.info([" - attrs (expanded): \n", logLines(attrs.map(attrStr).join(", "))].join(" "));
1161
- }
1162
- let prev = null;
1163
- attrs = attrs.reduce((acc, cur) => {
1164
- if (cur.type === "style") {
1165
- const key = Object.keys(cur.value)[0];
1166
- const value = cur.value[key];
1167
- const shouldKeepOriginalAttr = !shouldFlatten && !validStyles[key] && !pseudoDescriptors[key] && !key.startsWith("data-");
1168
- if (shouldKeepOriginalAttr) {
1169
- if (shouldPrintDebug) {
1170
- logger.info([" - keeping as non-style", key].join(" "));
1171
- }
1172
- prev = cur;
1173
- acc.push({
1174
- type: "attr",
1175
- value: t.jsxAttribute(t.jsxIdentifier(key), t.jsxExpressionContainer(typeof value === "string" ? t.stringLiteral(value) : literalToAst(value)))
1176
- });
1177
- acc.push(cur);
1178
- return acc;
1179
- }
1180
- if (ensureOverridden[key]) {
1181
- acc.push({
1182
- type: "attr",
1183
- value: cur.attr || t.jsxAttribute(t.jsxIdentifier(key), t.jsxExpressionContainer(t.nullLiteral()))
1184
- });
1185
- }
1186
- if ((prev == null ? void 0 : prev.type) === "style") {
1187
- mergeStyles2(prev.value, cur.value);
1188
- return acc;
1189
- }
1190
- }
1191
- prev = cur;
1192
- acc.push(cur);
1193
- return acc;
1194
- }, []);
1195
- if (shouldPrintDebug) {
1196
- logger.info([" - attrs (combined \u{1F500}): \n", logLines(attrs.map(attrStr).join(", "))].join(" "));
1197
- logger.info([" - defaultProps: \n", logLines(objToStr(staticConfig.defaultProps))].join(" "));
1198
- logger.info([" - foundStaticProps: \n", logLines(objToStr(foundStaticProps))].join(" "));
1199
- logger.info([" - completeProps: \n", logLines(objToStr(completeProps))].join(" "));
1200
- }
1201
- const getStyles = (props2, debugName = "") => {
1202
- if (!props2 || !Object.keys(props2).length) {
1203
- if (shouldPrintDebug)
1204
- logger.info([" getStyles() no props"].join(" "));
1205
- return {};
1206
- }
1207
- if (excludeProps && !!excludeProps.size) {
1208
- for (const key in props2) {
1209
- if (excludeProps.has(key)) {
1210
- if (shouldPrintDebug)
1211
- logger.info([" delete excluded", key].join(" "));
1212
- delete props2[key];
1213
- }
1214
- }
1215
- }
1216
- try {
1217
- const out = getSplitStyles(props2, staticConfig, defaultTheme, {
1218
- ...state,
1219
- fallbackProps: completeProps
1220
- }, void 0, props2["debug"]);
1221
- const outStyle = {
1222
- ...out.style,
1223
- ...out.pseudos
1224
- };
1225
- return outStyle;
1226
- } catch (err) {
1227
- logger.info(["error", err.message, err.stack].join(" "));
1228
- return {};
1229
- }
1230
- };
1231
- const completeStyles = getStyles(completeProps, "completeStyles");
1232
- if (!completeStyles) {
1233
- throw new Error(`Impossible, no styles`);
1234
- }
1235
- let getStyleError = null;
1236
- for (const attr of attrs) {
1237
- try {
1238
- switch (attr.type) {
1239
- case "ternary": {
1240
- const a = getStyles(attr.value.alternate, "ternary.alternate");
1241
- const c = getStyles(attr.value.consequent, "ternary.consequent");
1242
- if (a)
1243
- attr.value.alternate = a;
1244
- if (c)
1245
- attr.value.consequent = c;
1246
- if (shouldPrintDebug)
1247
- logger.info([" => tern ", attrStr(attr)].join(" "));
1248
- continue;
1249
- }
1250
- case "style": {
1251
- const styles = getStyles(attr.value, "style");
1252
- if (styles) {
1253
- attr.value = styles;
1254
- }
1255
- if (shouldPrintDebug)
1256
- logger.info([" * styles (in)", logLines(objToStr(attr.value))].join(" "));
1257
- if (shouldPrintDebug)
1258
- logger.info([" * styles (out)", logLines(objToStr(styles))].join(" "));
1259
- continue;
1260
- }
1261
- }
1262
- } catch (err) {
1263
- getStyleError = err;
1264
- }
1265
- }
1266
- if (shouldPrintDebug) {
1267
- logger.info([" - attrs (ternaries/combined):\n", logLines(attrs.map(attrStr).join(", "))].join(" "));
1268
- }
1269
- tm.mark("jsx-element-styles", !!shouldPrintDebug);
1270
- if (getStyleError) {
1271
- logger.info([" \u26A0\uFE0F postprocessing error, deopt", getStyleError].join(" "));
1272
- node.attributes = ogAttributes;
1273
- return node;
1274
- }
1275
- const existingStyleKeys = /* @__PURE__ */ new Set();
1276
- for (let i = attrs.length - 1; i >= 0; i--) {
1277
- const attr = attrs[i];
1278
- if (shouldFlatten) {
1279
- if (attr.type === "attr") {
1280
- if (t.isJSXAttribute(attr.value)) {
1281
- if (t.isJSXIdentifier(attr.value.name)) {
1282
- const name = attr.value.name.name;
1283
- if (INLINE_EXTRACTABLE[name]) {
1284
- attr.value.name.name = INLINE_EXTRACTABLE[name];
1285
- }
1286
- }
1287
- }
1288
- }
1289
- }
1290
- if (attr.type === "style") {
1291
- for (const key in attr.value) {
1292
- if (existingStyleKeys.has(key)) {
1293
- if (shouldPrintDebug) {
1294
- logger.info([` >> delete existing ${key}`].join(" "));
1295
- }
1296
- delete attr.value[key];
1297
- } else {
1298
- existingStyleKeys.add(key);
1299
- }
1300
- }
1301
- }
1302
- }
1303
- if (!shouldFlatten) {
1304
- if (inlineWhenUnflattened.size) {
1305
- for (const [index, attr] of attrs.entries()) {
1306
- if (attr.type === "style") {
1307
- for (const key in attr.value) {
1308
- if (!inlineWhenUnflattened.has(key))
1309
- continue;
1310
- const val = inlineWhenUnflattenedOGVals[key];
1311
- if (val) {
1312
- delete attr.value[key];
1313
- attrs.splice(index - 1, 0, val.attr);
1314
- } else {
1315
- delete attr.value[key];
1316
- }
1317
- }
1318
- }
1319
- }
1320
- }
1321
- }
1322
- if (shouldFlatten) {
1323
- if (shouldPrintDebug) {
1324
- logger.info([" [\u2705] flattening", originalNodeName, flatNode].join(" "));
1325
- }
1326
- node.name.name = flatNode;
1327
- res.flattened++;
1328
- if (closingElement) {
1329
- closingElement.name.name = flatNode;
1330
- }
1331
- }
1332
- if (shouldPrintDebug) {
1333
- logger.info([` \u274A\u274A inline props (${inlined.size}):`, shouldDeopt ? " deopted" : "", hasSpread ? " has spread" : "", staticConfig.neverFlatten ? "neverFlatten" : ""].join(" "));
1334
- logger.info(` - attrs (end):
1335
- ${logLines(attrs.map(attrStr).join(", "))}`);
1336
- }
1337
- onExtractTag({
1338
- attrs,
1339
- node,
1340
- lineNumbers,
1341
- filePath,
1342
- attemptEval,
1343
- jsxPath: traversePath,
1344
- originalNodeName,
1345
- isFlattened: shouldFlatten,
1346
- programPath,
1347
- completeProps,
1348
- staticConfig
1349
- });
1350
- } finally {
1351
- if (debugPropValue) {
1352
- shouldPrintDebug = ogDebug;
1353
- }
1354
- }
1355
- }
1356
- });
1357
- tm.mark("jsx-done", !!shouldPrintDebug);
1358
- if (modifiedComponents.size) {
1359
- const all = Array.from(modifiedComponents);
1360
- if (shouldPrintDebug) {
1361
- logger.info(` [\u{1FA9D}] hook check ${all.length}`);
1362
- }
1363
- for (const comp of all) {
1364
- removeUnusedHooks(comp, shouldPrintDebug);
1365
- }
1366
- }
1367
- tm.done(shouldPrintDebug === "verbose");
1368
- return res;
1369
- }
1370
- }
1371
- export {
1372
- createExtractor
1373
- };
1374
- //# sourceMappingURL=createExtractor.js.map