@tamagui/static 1.115.0 → 1.115.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 (93) hide show
  1. package/dist/check-dep-versions.js +389 -0
  2. package/dist/check-dep-versions.js.map +6 -0
  3. package/dist/checkDeps.js +26 -0
  4. package/dist/checkDeps.js.map +6 -0
  5. package/dist/constants.js +34 -0
  6. package/dist/constants.js.map +6 -0
  7. package/dist/exports.js +33 -0
  8. package/dist/exports.js.map +6 -0
  9. package/dist/extractor/accessSafe.js +47 -0
  10. package/dist/extractor/accessSafe.js.map +6 -0
  11. package/dist/extractor/babelParse.js +59 -0
  12. package/dist/extractor/babelParse.js.map +6 -0
  13. package/dist/extractor/buildClassName.js +72 -0
  14. package/dist/extractor/buildClassName.js.map +6 -0
  15. package/dist/extractor/bundle.js +133 -0
  16. package/dist/extractor/bundle.js.map +6 -0
  17. package/dist/extractor/bundleConfig.js +350 -0
  18. package/dist/extractor/bundleConfig.js.map +6 -0
  19. package/dist/extractor/createEvaluator.js +54 -0
  20. package/dist/extractor/createEvaluator.js.map +6 -0
  21. package/dist/extractor/createExtractor.js +1217 -0
  22. package/dist/extractor/createExtractor.js.map +6 -0
  23. package/dist/extractor/createLogger.js +32 -0
  24. package/dist/extractor/createLogger.js.map +6 -0
  25. package/dist/extractor/ensureImportingConcat.js +50 -0
  26. package/dist/extractor/ensureImportingConcat.js.map +6 -0
  27. package/dist/extractor/esbuildAliasPlugin.js +36 -0
  28. package/dist/extractor/esbuildAliasPlugin.js.map +6 -0
  29. package/dist/extractor/evaluateAstNode.js +99 -0
  30. package/dist/extractor/evaluateAstNode.js.map +6 -0
  31. package/dist/extractor/extractHelpers.js +109 -0
  32. package/dist/extractor/extractHelpers.js.map +6 -0
  33. package/dist/extractor/extractMediaStyle.js +123 -0
  34. package/dist/extractor/extractMediaStyle.js.map +6 -0
  35. package/dist/extractor/extractToClassNames.js +291 -0
  36. package/dist/extractor/extractToClassNames.js.map +6 -0
  37. package/dist/extractor/extractToNative.js +319 -0
  38. package/dist/extractor/extractToNative.js.map +6 -0
  39. package/dist/extractor/findTopmostFunction.js +32 -0
  40. package/dist/extractor/findTopmostFunction.js.map +6 -0
  41. package/dist/extractor/generatedUid.js +42 -0
  42. package/dist/extractor/generatedUid.js.map +6 -0
  43. package/dist/extractor/getPrefixLogs.js +23 -0
  44. package/dist/extractor/getPrefixLogs.js.map +6 -0
  45. package/dist/extractor/getPropValueFromAttributes.js +65 -0
  46. package/dist/extractor/getPropValueFromAttributes.js.map +6 -0
  47. package/dist/extractor/getSourceModule.js +66 -0
  48. package/dist/extractor/getSourceModule.js.map +6 -0
  49. package/dist/extractor/getStaticBindingsForScope.js +143 -0
  50. package/dist/extractor/getStaticBindingsForScope.js.map +6 -0
  51. package/dist/extractor/getTamaguiConfigPathFromOptionsConfig.js +24 -0
  52. package/dist/extractor/getTamaguiConfigPathFromOptionsConfig.js.map +6 -0
  53. package/dist/extractor/hoistClassNames.js +63 -0
  54. package/dist/extractor/hoistClassNames.js.map +6 -0
  55. package/dist/extractor/literalToAst.js +90 -0
  56. package/dist/extractor/literalToAst.js.map +6 -0
  57. package/dist/extractor/loadFile.js +14 -0
  58. package/dist/extractor/loadFile.js.map +6 -0
  59. package/dist/extractor/loadTamagui.js +263 -0
  60. package/dist/extractor/loadTamagui.js.map +6 -0
  61. package/dist/extractor/logLines.js +30 -0
  62. package/dist/extractor/logLines.js.map +6 -0
  63. package/dist/extractor/normalizeTernaries.js +59 -0
  64. package/dist/extractor/normalizeTernaries.js.map +6 -0
  65. package/dist/extractor/propsToFontFamilyCache.js +34 -0
  66. package/dist/extractor/propsToFontFamilyCache.js.map +6 -0
  67. package/dist/extractor/regenerateConfig.js +111 -0
  68. package/dist/extractor/regenerateConfig.js.map +6 -0
  69. package/dist/extractor/removeUnusedHooks.js +72 -0
  70. package/dist/extractor/removeUnusedHooks.js.map +6 -0
  71. package/dist/extractor/timer.js +38 -0
  72. package/dist/extractor/timer.js.map +6 -0
  73. package/dist/extractor/validHTMLAttributes.js +68 -0
  74. package/dist/extractor/validHTMLAttributes.js.map +6 -0
  75. package/dist/extractor/watchTamaguiConfig.js +57 -0
  76. package/dist/extractor/watchTamaguiConfig.js.map +6 -0
  77. package/dist/getPragmaOptions.js +49 -0
  78. package/dist/getPragmaOptions.js.map +6 -0
  79. package/dist/helpers/memoize.js +33 -0
  80. package/dist/helpers/memoize.js.map +6 -0
  81. package/dist/helpers/requireTamaguiCore.js +30 -0
  82. package/dist/helpers/requireTamaguiCore.js.map +6 -0
  83. package/dist/index.js +30 -0
  84. package/dist/index.js.map +6 -0
  85. package/dist/registerRequire.js +96 -0
  86. package/dist/registerRequire.js.map +6 -0
  87. package/dist/server.js +58 -0
  88. package/dist/server.js.map +6 -0
  89. package/dist/setup.js +1 -0
  90. package/dist/setup.js.map +6 -0
  91. package/dist/types.js +14 -0
  92. package/dist/types.js.map +6 -0
  93. package/package.json +14 -14
@@ -0,0 +1,1217 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf, __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: !0 });
9
+ }, __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from == "object" || typeof from == "function")
11
+ for (let key of __getOwnPropNames(from))
12
+ !__hasOwnProp.call(to, key) && key !== except && __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
13
+ return to;
14
+ };
15
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
16
+ // If the importer is in node compatibility mode or this is not an ESM
17
+ // file that has been converted to a CommonJS file using a Babel-
18
+ // compatible transform (i.e. "__esModule" has not been set), then set
19
+ // "default" to the CommonJS "module.exports" for node compatibility.
20
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: !0 }) : target,
21
+ mod
22
+ )), __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: !0 }), mod);
23
+ var createExtractor_exports = {};
24
+ __export(createExtractor_exports, {
25
+ createExtractor: () => createExtractor
26
+ });
27
+ module.exports = __toCommonJS(createExtractor_exports);
28
+ var import_traverse = __toESM(require("@babel/traverse")), t = __toESM(require("@babel/types")), import_cli_color = require("@tamagui/cli-color"), import_web = require("@tamagui/web"), import_node_path = require("node:path"), reactNativeWebInternals = __toESM(require("@tamagui/react-native-web-internals")), import_constants = require("../constants"), import_requireTamaguiCore = require("../helpers/requireTamaguiCore"), import_createEvaluator = require("./createEvaluator"), import_evaluateAstNode = require("./evaluateAstNode"), import_extractHelpers = require("./extractHelpers"), import_findTopmostFunction = require("./findTopmostFunction"), import_getStaticBindingsForScope = require("./getStaticBindingsForScope"), import_literalToAst = require("./literalToAst"), import_loadTamagui = require("./loadTamagui"), import_logLines = require("./logLines"), import_normalizeTernaries = require("./normalizeTernaries"), import_propsToFontFamilyCache = require("./propsToFontFamilyCache"), import_removeUnusedHooks = require("./removeUnusedHooks"), import_timer = require("./timer"), import_validHTMLAttributes = require("./validHTMLAttributes");
29
+ const UNTOUCHED_PROPS = {
30
+ key: !0,
31
+ style: !0,
32
+ className: !0
33
+ }, createTernary = (x) => x;
34
+ let hasLoggedBaseInfo = !1;
35
+ function isFullyDisabled(props) {
36
+ return props.disableExtraction && props.disableDebugAttr;
37
+ }
38
+ function createExtractor({ logger = console, platform = "web" } = { logger: console }) {
39
+ const INLINE_EXTRACTABLE = {
40
+ ref: "ref",
41
+ key: "key",
42
+ ...platform === "web" && {
43
+ onPress: "onClick",
44
+ onHoverIn: "onMouseEnter",
45
+ onHoverOut: "onMouseLeave",
46
+ onPressIn: "onMouseDown",
47
+ onPressOut: "onMouseUp"
48
+ }
49
+ }, componentState = {
50
+ focus: !1,
51
+ focusVisible: !1,
52
+ hover: !1,
53
+ unmounted: !0,
54
+ press: !1,
55
+ pressIn: !1,
56
+ disabled: !1
57
+ }, styleProps = {
58
+ resolveValues: "variable",
59
+ noClassNames: !1,
60
+ isAnimated: !1
61
+ }, shouldAddDebugProp = (
62
+ // really basic disable this for next.js because it messes with ssr
63
+ !process.env.npm_package_dependencies_next && !0 && process.env.IDENTIFY_TAGS !== "false" && (process.env.NODE_ENV === "development" || process.env.DEBUG || process.env.IDENTIFY_TAGS)
64
+ );
65
+ let projectInfo = null;
66
+ function loadSync(props) {
67
+ return isFullyDisabled(props) ? null : projectInfo ||= (0, import_loadTamagui.loadTamaguiSync)(props);
68
+ }
69
+ async function load(props) {
70
+ return isFullyDisabled(props) ? null : projectInfo ||= await (0, import_loadTamagui.loadTamagui)(props);
71
+ }
72
+ return {
73
+ options: {
74
+ logger
75
+ },
76
+ cleanupBeforeExit: import_getStaticBindingsForScope.cleanupBeforeExit,
77
+ loadTamagui: load,
78
+ loadTamaguiSync: loadSync,
79
+ getTamagui() {
80
+ return projectInfo?.tamaguiConfig;
81
+ },
82
+ parseSync: (f, props) => {
83
+ const projectInfo2 = loadSync(props);
84
+ return parseWithConfig(projectInfo2 || {}, f, props);
85
+ },
86
+ parse: async (f, props) => {
87
+ const projectInfo2 = await load(props);
88
+ return parseWithConfig(projectInfo2 || {}, f, props);
89
+ }
90
+ };
91
+ function parseWithConfig({ components, tamaguiConfig }, fileOrPath, options) {
92
+ const {
93
+ config = "tamagui.config.ts",
94
+ importsWhitelist = ["constants.js"],
95
+ evaluateVars = !0,
96
+ sourcePath = "",
97
+ onExtractTag,
98
+ onStyleRule,
99
+ getFlattenedNode,
100
+ disable,
101
+ disableExtraction,
102
+ disableExtractInlineMedia,
103
+ disableExtractVariables,
104
+ disableDebugAttr,
105
+ enableDynamicEvaluation = !1,
106
+ disableOptimizeHooks,
107
+ includeExtensions = [".ts", ".tsx", ".jsx"],
108
+ extractStyledDefinitions = !1,
109
+ prefixLogs,
110
+ excludeProps,
111
+ platform: platform2,
112
+ ...restProps
113
+ } = options, validHooks = disableOptimizeHooks ? {} : {
114
+ useMedia: !0,
115
+ useTheme: !0
116
+ };
117
+ if (sourcePath.includes(".tamagui-dynamic-eval"))
118
+ return null;
119
+ const {
120
+ normalizeStyle,
121
+ getSplitStyles,
122
+ mediaQueryConfig,
123
+ propMapper,
124
+ proxyThemeVariables,
125
+ pseudoDescriptors
126
+ } = (0, import_requireTamaguiCore.requireTamaguiCore)(platform2);
127
+ let shouldPrintDebug = options.shouldPrintDebug || !1;
128
+ if (disable === !0 || Array.isArray(disable) && disable.includes(sourcePath))
129
+ return null;
130
+ if (!isFullyDisabled(options) && !components)
131
+ throw new Error("Must provide components");
132
+ if (sourcePath && includeExtensions && !includeExtensions.some((ext) => sourcePath.endsWith(ext)))
133
+ return shouldPrintDebug && logger.info(
134
+ `Ignoring file due to includeExtensions: ${sourcePath}, includeExtensions: ${includeExtensions.join(
135
+ ", "
136
+ )}`
137
+ ), null;
138
+ function isValidStyleKey(name, staticConfig) {
139
+ if (!projectInfo)
140
+ throw new Error("Tamagui extractor not loaded yet");
141
+ return platform2 === "native" && name[0] === "$" && mediaQueryConfig[name.slice(1)] ? !1 : !!(staticConfig.validStyles?.[name] || pseudoDescriptors[name] || // don't disable variants or else you lose many things flattening
142
+ staticConfig.variants?.[name] || projectInfo?.tamaguiConfig?.shorthands[name] || name[0] === "$" && mediaQueryConfig[name.slice(1)]);
143
+ }
144
+ const isTargetingHTML = platform2 === "web", ogDebug = shouldPrintDebug, tm = (0, import_timer.timer)(), propsWithFileInfo = {
145
+ ...options,
146
+ sourcePath,
147
+ allLoadedComponents: components ? [...components] : []
148
+ };
149
+ hasLoggedBaseInfo || (hasLoggedBaseInfo = !0, shouldPrintDebug && logger.info(
150
+ [
151
+ "loaded components:",
152
+ propsWithFileInfo.allLoadedComponents.map((comp) => Object.keys(comp.nameToInfo).join(", ")).join(", ")
153
+ ].join(" ")
154
+ ), process.env.DEBUG?.startsWith("tamagui") && logger.info(
155
+ [
156
+ "loaded:",
157
+ propsWithFileInfo.allLoadedComponents.map((x) => x.moduleName)
158
+ ].join(`
159
+ `)
160
+ )), tm.mark("load-tamagui", !!shouldPrintDebug), isFullyDisabled(options) || tamaguiConfig?.themes || (console.error(
161
+ `\u26D4\uFE0F Error: Missing "themes" in your tamagui.config file:
162
+
163
+ You may not need the compiler! Remember you can run Tamagui with no configuration at all.
164
+
165
+ You may have not "export default" your config (you can also "export const config").
166
+
167
+ Or this may be due to duplicated dependency versions:
168
+ - try out https://github.com/bmish/check-dependency-version-consistency to see if there are mis-matches.
169
+ - or search your lockfile for mis-matches.
170
+ `
171
+ ), console.info(" Got config:", tamaguiConfig), process.exit(0));
172
+ const firstThemeName = Object.keys(tamaguiConfig?.themes || {})[0], firstTheme = tamaguiConfig?.themes[firstThemeName] || {};
173
+ if (!firstTheme || typeof firstTheme != "object") {
174
+ const err = `Missing theme ${firstThemeName}, an error occurred when importing your config`;
175
+ throw console.info(err, "Got config:", tamaguiConfig), console.info("Looking for theme:", firstThemeName), new Error(err);
176
+ }
177
+ const proxiedTheme = proxyThemeVariables(firstTheme), themeAccessListeners = /* @__PURE__ */ new Set(), defaultTheme = new Proxy(proxiedTheme, {
178
+ get(target, key) {
179
+ return Reflect.has(target, key) && themeAccessListeners.forEach((cb) => cb(String(key))), Reflect.get(target, key);
180
+ }
181
+ }), body = fileOrPath.type === "Program" ? fileOrPath.get("body") : fileOrPath.program.body;
182
+ isFullyDisabled(options) || Object.keys(components || []).length === 0 && (console.warn(
183
+ "Warning: Tamagui didn't find any valid components (DEBUG=tamagui for more)"
184
+ ), process.env.DEBUG === "tamagui" && console.info("components", Object.keys(components || []), components)), shouldPrintDebug === "verbose" && (logger.info(
185
+ `allLoadedComponent modules ${propsWithFileInfo.allLoadedComponents.map((k) => k.moduleName).join(", ")}`
186
+ ), logger.info(
187
+ `valid import paths: ${JSON.stringify(
188
+ (0, import_extractHelpers.getValidComponentsPaths)(propsWithFileInfo)
189
+ )}`
190
+ ));
191
+ let doesUseValidImport = !1, hasImportedTheme = !1;
192
+ const importDeclarations = [];
193
+ for (const bodyPath of body) {
194
+ if (bodyPath.type !== "ImportDeclaration") continue;
195
+ const node = "node" in bodyPath ? bodyPath.node : bodyPath, moduleName = node.source.value, valid = (0, import_extractHelpers.isValidImport)(propsWithFileInfo, moduleName);
196
+ if (valid && importDeclarations.push(node), shouldPrintDebug === "verbose" && logger.info(` - import ${moduleName} ${valid}`), extractStyledDefinitions && valid && node.specifiers.some((specifier) => specifier.local.name === "styled")) {
197
+ doesUseValidImport = !0;
198
+ break;
199
+ }
200
+ if (valid) {
201
+ const names = node.specifiers.map((specifier) => specifier.local.name), isValidComponent = names.some(
202
+ (name) => !!((0, import_extractHelpers.isValidImport)(propsWithFileInfo, moduleName, name) || validHooks[name])
203
+ );
204
+ if (shouldPrintDebug === "verbose" && logger.info(
205
+ ` - import ${isValidComponent ? "\u2705" : "\u21E3"} - ${names.join(
206
+ ", "
207
+ )} from '${moduleName}' - (valid: ${JSON.stringify(
208
+ (0, import_extractHelpers.getValidComponentsPaths)(propsWithFileInfo)
209
+ )})`
210
+ ), isValidComponent) {
211
+ doesUseValidImport = !0;
212
+ break;
213
+ }
214
+ }
215
+ }
216
+ if (shouldPrintDebug && logger.info(
217
+ `${JSON.stringify({ doesUseValidImport, hasImportedTheme }, null, 2)}
218
+ `
219
+ ), !doesUseValidImport)
220
+ return null;
221
+ function getValidImportedComponent(componentName) {
222
+ const importDeclaration = importDeclarations.find(
223
+ (dec) => dec.specifiers.some((spec) => spec.local.name === componentName)
224
+ );
225
+ return importDeclaration ? (0, import_extractHelpers.getValidImport)(
226
+ propsWithFileInfo,
227
+ importDeclaration.source.value,
228
+ componentName
229
+ ) : null;
230
+ }
231
+ tm.mark("import-check", !!shouldPrintDebug);
232
+ let couldntParse = !1;
233
+ const modifiedComponents = /* @__PURE__ */ new Set(), bindingCache = {}, callTraverse = (a) => fileOrPath.type === "File" ? (0, import_traverse.default)(fileOrPath, a) : fileOrPath.traverse(a), shouldDisableExtraction = disableExtraction === !0 || Array.isArray(disableExtraction) && disableExtraction.includes(sourcePath);
234
+ let programPath = null;
235
+ const res = {
236
+ styled: 0,
237
+ flattened: 0,
238
+ optimized: 0,
239
+ modified: 0,
240
+ found: 0
241
+ }, version = `${Math.random()}`;
242
+ if (callTraverse({
243
+ // @ts-ignore
244
+ Program: {
245
+ enter(path) {
246
+ programPath = path;
247
+ }
248
+ },
249
+ // styled() calls
250
+ CallExpression(path) {
251
+ if (disable || shouldDisableExtraction || extractStyledDefinitions === !1 || !t.isIdentifier(path.node.callee) || path.node.callee.name !== "styled")
252
+ return;
253
+ const variableName = t.isVariableDeclarator(path.parent) && t.isIdentifier(path.parent.id) ? path.parent.id.name : "unknown", parentNode = path.node.arguments[0];
254
+ if (!t.isIdentifier(parentNode))
255
+ return;
256
+ const parentName = parentNode.name, definition = path.node.arguments[1];
257
+ if (!parentName || !definition || !t.isObjectExpression(definition))
258
+ return;
259
+ let Component = getValidImportedComponent(variableName);
260
+ if (!Component) {
261
+ if (enableDynamicEvaluation !== !0)
262
+ return;
263
+ try {
264
+ shouldPrintDebug && logger.info(
265
+ `Unknown component: ${variableName} = styled(${parentName}) attempting dynamic load: ${sourcePath}`
266
+ );
267
+ const out2 = (0, import_loadTamagui.loadTamaguiSync)({
268
+ forceExports: !0,
269
+ components: [sourcePath],
270
+ cacheKey: version
271
+ });
272
+ if (!out2?.components) {
273
+ shouldPrintDebug && logger.info(`Couldn't load, got ${out2}`);
274
+ return;
275
+ }
276
+ if (propsWithFileInfo.allLoadedComponents = [
277
+ ...propsWithFileInfo.allLoadedComponents,
278
+ ...out2.components
279
+ ], Component = out2.components.flatMap((x) => x.nameToInfo[variableName] ?? [])[0], !out2.cached) {
280
+ const foundNames = out2.components?.map((x) => Object.keys(x.nameToInfo).join(", ")).join(", ").trim();
281
+ foundNames && (0, import_cli_color.colorLog)(
282
+ import_cli_color.Color.FgYellow,
283
+ ` | Tamagui found dynamic components: ${foundNames}`
284
+ );
285
+ }
286
+ } catch {
287
+ shouldPrintDebug && logger.info(
288
+ `skip optimize styled(${variableName}), unable to pre-process (DEBUG=tamagui for more)`
289
+ );
290
+ }
291
+ }
292
+ if (!Component) {
293
+ shouldPrintDebug && logger.info(" No component found");
294
+ return;
295
+ }
296
+ const componentSkipProps = /* @__PURE__ */ new Set([
297
+ ...Component.staticConfig.inlineWhenUnflattened || [],
298
+ ...Component.staticConfig.inlineProps || [],
299
+ // for now skip variants, will return to them
300
+ "variants",
301
+ "defaultVariants",
302
+ // skip fontFamily its basically a "variant", important for theme use to be value always
303
+ "fontFamily",
304
+ "name",
305
+ "focusStyle",
306
+ "focusVisibleStyle",
307
+ "disabledStyle",
308
+ "hoverStyle",
309
+ "pressStyle"
310
+ ]), skipped = /* @__PURE__ */ new Set(), styles = {}, staticNamespace = (0, import_getStaticBindingsForScope.getStaticBindingsForScope)(
311
+ path.scope,
312
+ importsWhitelist,
313
+ sourcePath,
314
+ bindingCache,
315
+ shouldPrintDebug
316
+ ), attemptEval = evaluateVars ? (0, import_createEvaluator.createEvaluator)({
317
+ props: propsWithFileInfo,
318
+ staticNamespace,
319
+ sourcePath,
320
+ shouldPrintDebug
321
+ }) : import_evaluateAstNode.evaluateAstNode, attemptEvalSafe = (0, import_createEvaluator.createSafeEvaluator)(attemptEval);
322
+ for (const property of definition.properties) {
323
+ if (!t.isObjectProperty(property) || !t.isIdentifier(property.key) || !isValidStyleKey(property.key.name, Component.staticConfig) || // TODO make pseudos and variants work
324
+ // skip pseudos
325
+ pseudoDescriptors[property.key.name] || // skip variants
326
+ Component.staticConfig.variants?.[property.key.name] || componentSkipProps.has(property.key.name)) {
327
+ skipped.add(property);
328
+ continue;
329
+ }
330
+ const out2 = attemptEvalSafe(property.value);
331
+ out2 === import_constants.FAILED_EVAL ? skipped.add(property) : styles[property.key.name] = out2;
332
+ }
333
+ const out = getSplitStyles(
334
+ styles,
335
+ Component.staticConfig,
336
+ defaultTheme,
337
+ "",
338
+ componentState,
339
+ styleProps,
340
+ void 0,
341
+ void 0,
342
+ void 0,
343
+ shouldPrintDebug
344
+ ), classNames = {
345
+ ...out.classNames
346
+ };
347
+ if (shouldPrintDebug && logger.info(
348
+ [
349
+ `Extracted styled(${variableName})
350
+ `,
351
+ JSON.stringify(styles, null, 2),
352
+ `
353
+ classNames:`,
354
+ JSON.stringify(classNames, null, 2),
355
+ `
356
+ rulesToInsert:`,
357
+ out.rulesToInsert
358
+ ].join(" ")
359
+ ), definition.properties = definition.properties.map((prop) => {
360
+ if (skipped.has(prop) || !t.isObjectProperty(prop) || !t.isIdentifier(prop.key))
361
+ return prop;
362
+ const key = prop.key.name, value = classNames[key];
363
+ return value ? t.objectProperty(t.stringLiteral(key), t.stringLiteral(value)) : prop;
364
+ }), out.rulesToInsert)
365
+ for (const key in out.rulesToInsert) {
366
+ const styleObject = out.rulesToInsert[key];
367
+ onStyleRule?.(
368
+ styleObject[import_web.StyleObjectIdentifier],
369
+ styleObject[import_web.StyleObjectRules]
370
+ );
371
+ }
372
+ res.styled++, shouldPrintDebug && logger.info(`Extracted styled(${variableName})`);
373
+ },
374
+ JSXElement(traversePath) {
375
+ tm.mark("jsx-element", !!shouldPrintDebug);
376
+ const node = traversePath.node.openingElement, ogAttributes = node.attributes.map((attr) => ({ ...attr })), componentName = (0, import_extractHelpers.findComponentName)(traversePath.scope), closingElement = traversePath.node.closingElement;
377
+ if (closingElement && t.isJSXMemberExpression(closingElement?.name) || !t.isJSXIdentifier(node.name)) {
378
+ shouldPrintDebug && logger.info(" skip non-identifier element");
379
+ return;
380
+ }
381
+ const binding = traversePath.scope.getBinding(node.name.name);
382
+ let moduleName = "";
383
+ if (binding && t.isImportDeclaration(binding.path.parent) && (moduleName = binding.path.parent.source.value, !(0, import_extractHelpers.isValidImport)(propsWithFileInfo, moduleName, binding.identifier.name))) {
384
+ shouldPrintDebug && logger.info(
385
+ ` - Binding in component ${componentName} not valid import: "${binding.identifier.name}" isn't in ${moduleName}
386
+ `
387
+ );
388
+ return;
389
+ }
390
+ const component = (0, import_extractHelpers.getValidComponent)(propsWithFileInfo, moduleName, node.name.name);
391
+ if (!component || !component.staticConfig) {
392
+ shouldPrintDebug && logger.info(`
393
+ - No Tamagui conf for: ${node.name.name}
394
+ `);
395
+ return;
396
+ }
397
+ const originalNodeName = node.name.name;
398
+ res.found++;
399
+ const filePath = `./${(0, import_node_path.relative)(process.cwd(), sourcePath)}`, lineNumbers = node.loc ? node.loc.start.line + (node.loc.start.line !== node.loc.end.line ? `-${node.loc.end.line}` : "") : "", codePosition = `${filePath}:${lineNumbers}`, debugPropValue = node.attributes.filter(
400
+ (n) => t.isJSXAttribute(n) && t.isJSXIdentifier(n.name) && n.name.name === "debug"
401
+ ).map((n) => n.value === null ? !0 : t.isStringLiteral(n.value) ? n.value.value : !1)[0];
402
+ if (debugPropValue && (shouldPrintDebug = debugPropValue), shouldPrintDebug && (logger.info(
403
+ `\x1B[33m\x1B[0m ${componentName} | ${codePosition} -------------------`
404
+ ), logger.info(
405
+ [
406
+ "\x1B[1m",
407
+ "\x1B[32m",
408
+ `<${originalNodeName} />`,
409
+ disableDebugAttr ? "" : "\u{1F41B}"
410
+ ].join(" ")
411
+ )), shouldAddDebugProp && !disableDebugAttr && (res.modified++, node.attributes.unshift(
412
+ t.jsxAttribute(t.jsxIdentifier("data-is"), t.stringLiteral(node.name.name))
413
+ ), componentName && node.attributes.unshift(
414
+ t.jsxAttribute(t.jsxIdentifier("data-in"), t.stringLiteral(componentName))
415
+ ), node.attributes.unshift(
416
+ t.jsxAttribute(
417
+ t.jsxIdentifier("data-at"),
418
+ t.stringLiteral(`${(0, import_node_path.basename)(filePath)}:${lineNumbers}`)
419
+ )
420
+ )), shouldDisableExtraction) {
421
+ shouldPrintDebug === "verbose" && logger.info(` \u274C Extraction disabled: ${JSON.stringify(disableExtraction)}
422
+ `);
423
+ return;
424
+ }
425
+ try {
426
+ let evaluateAttribute = function(path) {
427
+ const attribute = path.node, attr = { type: "attr", value: attribute };
428
+ if (t.isJSXSpreadAttribute(attribute)) {
429
+ const arg = attribute.argument, conditional = t.isConditionalExpression(arg) ? (
430
+ // <YStack {...isSmall ? { color: 'red } : { color: 'blue }}
431
+ [arg.test, arg.consequent, arg.alternate]
432
+ ) : t.isLogicalExpression(arg) && arg.operator === "&&" ? (
433
+ // <YStack {...isSmall && { color: 'red }}
434
+ [arg.left, arg.right, null]
435
+ ) : null;
436
+ if (conditional) {
437
+ const [test, alt, cons] = conditional;
438
+ if (!test) throw new Error("no test");
439
+ return [alt, cons].some((side) => side && !isStaticObject(side)) ? (shouldPrintDebug && logger.info(`not extractable ${alt} ${cons}`), attr) : [
440
+ ...createTernariesFromObjectProperties(test, alt) || [],
441
+ ...cons && createTernariesFromObjectProperties(
442
+ t.unaryExpression("!", test),
443
+ cons
444
+ ) || []
445
+ ].map((ternary) => ({
446
+ type: "ternary",
447
+ value: ternary
448
+ }));
449
+ }
450
+ }
451
+ if (t.isJSXSpreadAttribute(attribute) || !attribute.name || typeof attribute.name.name != "string")
452
+ return shouldPrintDebug && logger.info(" ! inlining, spread attr"), inlined.set(`${Math.random()}`, "spread"), attr;
453
+ const name = attribute.name.name;
454
+ if (excludeProps?.has(name))
455
+ return shouldPrintDebug && logger.info([" excluding prop", name].join(" ")), null;
456
+ if (inlineProps.has(name))
457
+ return inlined.set(name, name), shouldPrintDebug && logger.info([" ! inlining, inline prop", name].join(" ")), attr;
458
+ if (UNTOUCHED_PROPS[name])
459
+ return attr;
460
+ if (INLINE_EXTRACTABLE[name])
461
+ return inlined.set(name, INLINE_EXTRACTABLE[name]), attr;
462
+ if (name.startsWith("data-"))
463
+ return attr;
464
+ if ((name === "enterStyle" || name === "exitStyle") && t.isJSXExpressionContainer(attribute?.value))
465
+ return shouldDeopt = !0, attr;
466
+ if (name[0] === "$" && t.isJSXExpressionContainer(attribute?.value)) {
467
+ const shortname = name.slice(1);
468
+ if (mediaQueryConfig[shortname]) {
469
+ if (platform2 === "native" && (shouldDeopt = !0), disableExtractInlineMedia)
470
+ return attr;
471
+ const expression = attribute.value.expression;
472
+ if (!t.isJSXEmptyExpression(expression)) {
473
+ const ternaries2 = createTernariesFromObjectProperties(
474
+ t.stringLiteral(shortname),
475
+ expression,
476
+ {
477
+ inlineMediaQuery: shortname
478
+ }
479
+ );
480
+ if (ternaries2)
481
+ return ternaries2.map((value2) => ({
482
+ type: "ternary",
483
+ value: value2
484
+ }));
485
+ }
486
+ }
487
+ }
488
+ const [value, valuePath] = t.isJSXExpressionContainer(attribute?.value) ? [attribute.value.expression, path.get("value")] : [attribute.value, path.get("value")], remove = () => {
489
+ Array.isArray(valuePath) ? valuePath.map((p) => p.remove()) : valuePath.remove();
490
+ };
491
+ if (name === "ref")
492
+ return shouldPrintDebug && logger.info([" ! inlining, ref", name].join(" ")), inlined.set("ref", "ref"), attr;
493
+ if (name === "tag")
494
+ return {
495
+ type: "attr",
496
+ value: path.node
497
+ };
498
+ if (disableExtractVariables === !0 && value && value.type === "StringLiteral" && value.value[0] === "$")
499
+ return shouldPrintDebug && logger.info(
500
+ [
501
+ ` ! inlining, native disable extract: ${name} =`,
502
+ value.value
503
+ ].join(" ")
504
+ ), inlined.set(name, !0), attr;
505
+ if (name === "theme")
506
+ return inlined.set("theme", attr.value), attr;
507
+ const styleValue = attemptEvalSafe(value);
508
+ if (!variants[name] && !isValidStyleKey(name, staticConfig)) {
509
+ let keys = [name], out = null;
510
+ out = propMapper(name, styleValue, propMapperStyleState), out && (Array.isArray(out) ? (out = Object.fromEntries(out), keys = Object.keys(out)) : (logger.warn("Error expected array but got", out), couldntParse = !0, shouldDeopt = !0)), out && (isTargetingHTML && (out = reactNativeWebInternals.createDOMProps(
511
+ isTextView ? "span" : "div",
512
+ out
513
+ ), delete out.className), keys = Object.keys(out));
514
+ let didInline = !1;
515
+ const attributes = keys.map((key) => {
516
+ const val = out[key];
517
+ return isValidStyleKey(key, staticConfig) ? {
518
+ type: "style",
519
+ value: { [key]: styleValue },
520
+ name: key,
521
+ attr: path.node
522
+ } : import_validHTMLAttributes.validHTMLAttributes[key] || key.startsWith("aria-") || key.startsWith("data-") || // this is debug stuff added by vite / new jsx transform
523
+ key === "__source" || key === "__self" ? attr : (shouldPrintDebug && logger.info(" ! inlining, non-static " + key), didInline = !0, inlined.set(key, val), val);
524
+ });
525
+ return didInline ? (shouldPrintDebug && logger.info(
526
+ ` bailing flattening due to attributes ${attributes.map(
527
+ (x) => x.toString()
528
+ )}`
529
+ ), attr) : attributes;
530
+ }
531
+ if (styleValue !== import_constants.FAILED_EVAL)
532
+ return inlineWhenUnflattened.has(name) && (inlineWhenUnflattenedOGVals[name] = { styleValue, attr }), isValidStyleKey(name, staticConfig) ? (shouldPrintDebug && logger.info(` style: ${name} = ${JSON.stringify(styleValue)}`), name in defaultProps || hasSetOptimized || (res.optimized++, hasSetOptimized = !0), {
533
+ type: "style",
534
+ value: { [name]: styleValue },
535
+ name,
536
+ attr: path.node
537
+ }) : (variants[name] && variantValues.set(name, styleValue), inlined.set(name, !0), attr);
538
+ if (t.isBinaryExpression(value)) {
539
+ shouldPrintDebug && logger.info(` binary expression ${name} = ${value}`);
540
+ const { operator, left, right } = value, lVal = attemptEvalSafe(left), rVal = attemptEvalSafe(right);
541
+ if (shouldPrintDebug && logger.info(
542
+ ` evalBinaryExpression lVal ${String(lVal)}, rVal ${String(rVal)}`
543
+ ), lVal !== import_constants.FAILED_EVAL && t.isConditionalExpression(right)) {
544
+ const ternary = addBinaryConditional(operator, left, right);
545
+ if (ternary) return ternary;
546
+ }
547
+ if (rVal !== import_constants.FAILED_EVAL && t.isConditionalExpression(left)) {
548
+ const ternary = addBinaryConditional(operator, right, left);
549
+ if (ternary) return ternary;
550
+ }
551
+ return shouldPrintDebug && logger.info(" evalBinaryExpression cant extract"), inlined.set(name, !0), attr;
552
+ }
553
+ const staticConditional = getStaticConditional(value);
554
+ if (staticConditional)
555
+ return shouldPrintDebug === "verbose" && logger.info(` static conditional ${name} ${value}`), { type: "ternary", value: staticConditional };
556
+ const staticLogical = getStaticLogical(value);
557
+ if (staticLogical)
558
+ return shouldPrintDebug === "verbose" && logger.info(` static ternary ${name} = ${value}`), { type: "ternary", value: staticLogical };
559
+ if (options.experimentalFlattenDynamicValues && isValidStyleKey(name, staticConfig))
560
+ return {
561
+ type: "dynamic-style",
562
+ value,
563
+ name: tamaguiConfig?.shorthands[name] || name
564
+ };
565
+ return inlined.set(name, !0), shouldPrintDebug && logger.info(` ! inline no match ${name} ${value}`), attr;
566
+ function addBinaryConditional(operator, staticExpr, cond) {
567
+ if (getStaticConditional(cond)) {
568
+ const alt = attemptEval(
569
+ t.binaryExpression(operator, staticExpr, cond.alternate)
570
+ ), cons = attemptEval(
571
+ t.binaryExpression(operator, staticExpr, cond.consequent)
572
+ );
573
+ return shouldPrintDebug && logger.info([" binaryConditional", cond.test, cons, alt].join(" ")), {
574
+ type: "ternary",
575
+ value: {
576
+ test: cond.test,
577
+ remove,
578
+ alternate: { [name]: alt },
579
+ consequent: { [name]: cons }
580
+ }
581
+ };
582
+ }
583
+ return null;
584
+ }
585
+ function getStaticConditional(value2) {
586
+ if (t.isConditionalExpression(value2))
587
+ try {
588
+ const aVal = attemptEval(value2.alternate), cVal = attemptEval(value2.consequent);
589
+ if (shouldPrintDebug) {
590
+ const type = value2.test.type;
591
+ logger.info([" static ternary", type, cVal, aVal].join(" "));
592
+ }
593
+ return {
594
+ test: value2.test,
595
+ remove,
596
+ consequent: { [name]: cVal },
597
+ alternate: { [name]: aVal }
598
+ };
599
+ } catch (err) {
600
+ shouldPrintDebug && logger.info([" cant eval ternary", err.message].join(" "));
601
+ }
602
+ return null;
603
+ }
604
+ function getStaticLogical(value2) {
605
+ if (t.isLogicalExpression(value2) && value2.operator === "&&")
606
+ try {
607
+ const val = attemptEval(value2.right);
608
+ return shouldPrintDebug && logger.info([" staticLogical", value2.left, name, val].join(" ")), {
609
+ test: value2.left,
610
+ remove,
611
+ consequent: { [name]: val },
612
+ alternate: null
613
+ };
614
+ } catch (err) {
615
+ shouldPrintDebug && logger.info([" cant static eval logical", err].join(" "));
616
+ }
617
+ return null;
618
+ }
619
+ }, isStaticObject = function(obj) {
620
+ return t.isObjectExpression(obj) && obj.properties.every((prop) => {
621
+ if (!t.isObjectProperty(prop))
622
+ return logger.info(["not object prop", prop].join(" ")), !1;
623
+ const propName = prop.key.name;
624
+ return !isValidStyleKey(propName, staticConfig) && propName !== "tag" ? (shouldPrintDebug && logger.info([" not a valid style prop!", propName].join(" ")), !1) : !0;
625
+ });
626
+ }, createTernariesFromObjectProperties = function(test, side, ternaryPartial = {}) {
627
+ if (!side)
628
+ return null;
629
+ if (!isStaticObject(side))
630
+ throw new Error("not extractable");
631
+ return side.properties.flatMap((property) => {
632
+ if (!t.isObjectProperty(property))
633
+ throw new Error("expected object property");
634
+ if (t.isIdentifier(property.key)) {
635
+ const key = property.key.name, mediaQueryKey = key.slice(1);
636
+ if (key[0] === "$" && mediaQueryConfig[mediaQueryKey])
637
+ if (t.isExpression(property.value)) {
638
+ const ternaries2 = createTernariesFromObjectProperties(
639
+ t.stringLiteral(mediaQueryKey),
640
+ property.value,
641
+ {
642
+ inlineMediaQuery: mediaQueryKey
643
+ }
644
+ );
645
+ if (ternaries2)
646
+ return ternaries2.map((value) => ({
647
+ ...ternaryPartial,
648
+ ...value,
649
+ // ensure media query test stays on left side (see getMediaQueryTernary)
650
+ test: t.logicalExpression("&&", value.test, test)
651
+ }));
652
+ logger.info(["\u26A0\uFE0F no ternaries?", property].join(" "));
653
+ } else
654
+ logger.info(["\u26A0\uFE0F not expression", property].join(" "));
655
+ }
656
+ if (t.isConditionalExpression(property.value)) {
657
+ const [truthy, falsy] = [
658
+ t.objectExpression([
659
+ t.objectProperty(property.key, property.value.consequent)
660
+ ]),
661
+ t.objectExpression([
662
+ t.objectProperty(property.key, property.value.alternate)
663
+ ])
664
+ ].map((x) => attemptEval(x));
665
+ return [
666
+ createTernary({
667
+ remove() {
668
+ },
669
+ ...ternaryPartial,
670
+ test: t.logicalExpression("&&", test, property.value.test),
671
+ consequent: truthy,
672
+ alternate: null
673
+ }),
674
+ createTernary({
675
+ ...ternaryPartial,
676
+ test: t.logicalExpression(
677
+ "&&",
678
+ test,
679
+ t.unaryExpression("!", property.value.test)
680
+ ),
681
+ consequent: falsy,
682
+ alternate: null,
683
+ remove() {
684
+ }
685
+ })
686
+ ];
687
+ }
688
+ const obj = t.objectExpression([
689
+ t.objectProperty(property.key, property.value)
690
+ ]), consequent = attemptEval(obj);
691
+ return createTernary({
692
+ remove() {
693
+ },
694
+ ...ternaryPartial,
695
+ test,
696
+ consequent,
697
+ alternate: null
698
+ });
699
+ });
700
+ }, mergeToEnd = function(obj, key, val) {
701
+ key in obj && delete obj[key], obj[key] = val;
702
+ }, normalizeStyleWithoutVariants = function(style) {
703
+ let res2 = {};
704
+ for (const key in style)
705
+ if (staticConfig.variants && key in staticConfig.variants)
706
+ mergeToEnd(res2, key, style[key]);
707
+ else {
708
+ const expanded = normalizeStyle({ [key]: style[key] }, !0);
709
+ for (const key2 in expanded)
710
+ mergeToEnd(res2, key2, expanded[key2]);
711
+ }
712
+ return res2;
713
+ }, mergeStyles = function(prev2, next) {
714
+ for (const key in next)
715
+ pseudoDescriptors[key] ? (prev2[key] = prev2[key] || {}, Object.assign(prev2[key], next[key])) : mergeToEnd(prev2, key, next[key]);
716
+ };
717
+ const { staticConfig } = component, defaultProps = { ...staticConfig.defaultProps || {} }, variants = staticConfig.variants || {}, isTextView = staticConfig.isText || !1, validStyles = staticConfig?.validStyles ?? {};
718
+ let tagName = defaultProps.tag ?? (isTextView ? "span" : "div");
719
+ traversePath.get("openingElement").get("attributes").forEach((path) => {
720
+ const attr = path.node;
721
+ if (t.isJSXSpreadAttribute(attr) || attr.name.name !== "tag") return;
722
+ const val = attr.value;
723
+ t.isStringLiteral(val) && (tagName = val.value);
724
+ }), shouldPrintDebug === "verbose" && console.info(` Start tag ${tagName}`);
725
+ const flatNode = getFlattenedNode?.({ isTextView, tag: tagName }), inlineProps = /* @__PURE__ */ new Set([
726
+ // adding some always inline props
727
+ "dataSet",
728
+ ...restProps.inlineProps || [],
729
+ ...staticConfig.inlineProps || []
730
+ ]), deoptProps = /* @__PURE__ */ new Set([
731
+ // always de-opt animation these
732
+ "animation",
733
+ "animateOnly",
734
+ "animatePresence",
735
+ "disableOptimization",
736
+ ...isTargetingHTML ? [] : ["pressStyle", "focusStyle", "focusVisibleStyle", "disabledStyle"],
737
+ // when using a non-CSS driver, de-opt on enterStyle/exitStyle
738
+ ...tamaguiConfig?.animations.isReactNative ? ["enterStyle", "exitStyle"] : []
739
+ ]), inlineWhenUnflattened = /* @__PURE__ */ new Set([
740
+ ...staticConfig.inlineWhenUnflattened || []
741
+ ]), staticNamespace = (0, import_getStaticBindingsForScope.getStaticBindingsForScope)(
742
+ traversePath.scope,
743
+ importsWhitelist,
744
+ sourcePath,
745
+ bindingCache,
746
+ shouldPrintDebug
747
+ ), attemptEval = evaluateVars ? (0, import_createEvaluator.createEvaluator)({
748
+ props: propsWithFileInfo,
749
+ staticNamespace,
750
+ sourcePath,
751
+ traversePath,
752
+ shouldPrintDebug
753
+ }) : import_evaluateAstNode.evaluateAstNode, attemptEvalSafe = (0, import_createEvaluator.createSafeEvaluator)(attemptEval);
754
+ if (shouldPrintDebug && logger.info(` staticNamespace ${Object.keys(staticNamespace).join(", ")}`), couldntParse)
755
+ return;
756
+ tm.mark("jsx-element-flattened", !!shouldPrintDebug);
757
+ let attrs = [], shouldDeopt = !1;
758
+ const inlined = /* @__PURE__ */ new Map(), variantValues = /* @__PURE__ */ new Map();
759
+ let hasSetOptimized = !1;
760
+ const inlineWhenUnflattenedOGVals = {}, propMapperStyleState = {
761
+ staticConfig,
762
+ usedKeys: {},
763
+ classNames: {},
764
+ style: {},
765
+ theme: defaultTheme,
766
+ viewProps: defaultProps,
767
+ conf: tamaguiConfig,
768
+ props: defaultProps,
769
+ componentState,
770
+ styleProps: {
771
+ ...styleProps,
772
+ resolveValues: "auto"
773
+ },
774
+ debug: shouldPrintDebug
775
+ };
776
+ if (attrs = traversePath.get("openingElement").get("attributes").flatMap((path) => {
777
+ try {
778
+ const res2 = evaluateAttribute(path);
779
+ return res2 || path.remove(), res2;
780
+ } catch (err) {
781
+ return shouldPrintDebug && (logger.info(
782
+ [
783
+ "Recoverable error extracting attribute",
784
+ err.message,
785
+ shouldPrintDebug === "verbose" ? err.stack : ""
786
+ ].join(" ")
787
+ ), shouldPrintDebug === "verbose" && logger.info(`node ${path.node?.type}`)), inlined.set(`${Math.random()}`, "spread"), {
788
+ type: "attr",
789
+ value: path.node
790
+ };
791
+ }
792
+ }).flat(4).filter(import_extractHelpers.isPresent), shouldPrintDebug && logger.info(
793
+ [` - attrs (before):
794
+ `, (0, import_logLines.logLines)(attrs.map(import_extractHelpers.attrStr).join(", "))].join(" ")
795
+ ), couldntParse || shouldDeopt) {
796
+ shouldPrintDebug && logger.info(
797
+ [" avoid optimizing:", { couldntParse, shouldDeopt }].join(" ")
798
+ ), node.attributes = ogAttributes;
799
+ return;
800
+ }
801
+ const parentFn = (0, import_findTopmostFunction.findTopmostFunction)(traversePath);
802
+ parentFn && modifiedComponents.add(parentFn);
803
+ const hasSpread = attrs.some(
804
+ (x) => x.type === "attr" && t.isJSXSpreadAttribute(x.value)
805
+ ), hasOnlyStringChildren = !hasSpread && (node.selfClosing || traversePath.node.children && traversePath.node.children.every((x) => x.type === "JSXText"));
806
+ let themeVal = inlined.get("theme");
807
+ platform2 !== "native" && inlined.delete("theme");
808
+ for (const [key] of [...inlined]) {
809
+ const isStaticObjectVariant = staticConfig.variants?.[key] && variantValues.has(key);
810
+ (INLINE_EXTRACTABLE[key] || isStaticObjectVariant) && inlined.delete(key);
811
+ }
812
+ const canFlattenProps = inlined.size === 0;
813
+ let shouldFlatten = !!(flatNode && !shouldDeopt && canFlattenProps && !hasSpread && !staticConfig.isStyledHOC && !staticConfig.isHOC && !staticConfig.isReactNative && staticConfig.neverFlatten !== !0 && (staticConfig.neverFlatten !== "jsx" || hasOnlyStringChildren));
814
+ const usedThemeKeys = /* @__PURE__ */ new Set();
815
+ if (themeAccessListeners.add((key) => {
816
+ disableExtractVariables && (usedThemeKeys.add(key), shouldFlatten = !1, shouldPrintDebug === "verbose" && logger.info([" ! accessing theme key, avoid flatten", key].join(" ")));
817
+ }), shouldFlatten) {
818
+ let skipMap = !1;
819
+ const defaultStyleAttrs = Object.keys(defaultProps).flatMap((key) => {
820
+ if (skipMap) return [];
821
+ const value = defaultProps[key];
822
+ if (key === "theme" && !themeVal)
823
+ return platform2 === "native" && (shouldFlatten = !1, skipMap = !0, inlined.set("theme", { value: t.stringLiteral(value) })), themeVal = { value: t.stringLiteral(value) }, [];
824
+ if (!isValidStyleKey(key, staticConfig))
825
+ return [];
826
+ const name = tamaguiConfig?.shorthands[key] || key;
827
+ if (value === void 0) {
828
+ logger.warn(
829
+ `\u26A0\uFE0F Error evaluating default style for component, prop ${key} ${value}`
830
+ ), shouldDeopt = !0;
831
+ return;
832
+ }
833
+ return name[0] === "$" && mediaQueryConfig[name.slice(1)] ? (defaultProps[key] = void 0, evaluateAttribute({
834
+ node: t.jsxAttribute(
835
+ t.jsxIdentifier(name),
836
+ t.jsxExpressionContainer(
837
+ t.objectExpression(
838
+ Object.keys(value).filter((k) => typeof value[k] < "u").map((k) => t.objectProperty(
839
+ t.identifier(k),
840
+ (0, import_literalToAst.literalToAst)(value[k])
841
+ ))
842
+ )
843
+ )
844
+ )
845
+ })) : {
846
+ type: "style",
847
+ name,
848
+ value: { [name]: value }
849
+ };
850
+ });
851
+ skipMap || defaultStyleAttrs.length && (attrs = [...defaultStyleAttrs, ...attrs]);
852
+ }
853
+ let ternaries = [];
854
+ attrs = attrs.reduce((out, cur) => {
855
+ const next = attrs[attrs.indexOf(cur) + 1];
856
+ if (cur.type === "ternary" && ternaries.push(cur.value), (!next || next.type !== "ternary") && ternaries.length) {
857
+ const normalized = (0, import_normalizeTernaries.normalizeTernaries)(ternaries).map(
858
+ ({ alternate, consequent, ...rest }) => ({
859
+ type: "ternary",
860
+ value: {
861
+ ...rest,
862
+ alternate: alternate || null,
863
+ consequent: consequent || null
864
+ }
865
+ })
866
+ );
867
+ try {
868
+ return [...out, ...normalized];
869
+ } finally {
870
+ shouldPrintDebug && logger.info(
871
+ ` normalizeTernaries (${ternaries.length} => ${normalized.length})`
872
+ ), ternaries = [];
873
+ }
874
+ }
875
+ return cur.type === "ternary" || out.push(cur), out;
876
+ }, []).flat();
877
+ const shouldWrapTheme = shouldFlatten && themeVal;
878
+ if (shouldWrapTheme && (programPath ? (shouldPrintDebug && logger.info([" - wrapping theme", themeVal].join(" ")), attrs = attrs.filter(
879
+ (x) => !(x.type === "attr" && t.isJSXAttribute(x.value) && x.value.name.name === "theme")
880
+ ), hasImportedTheme || (hasImportedTheme = !0, programPath.node.body.push(
881
+ t.importDeclaration(
882
+ [
883
+ t.importSpecifier(
884
+ t.identifier("_TamaguiTheme"),
885
+ t.identifier("Theme")
886
+ )
887
+ ],
888
+ t.stringLiteral("@tamagui/web")
889
+ )
890
+ )), traversePath.replaceWith(
891
+ t.jsxElement(
892
+ t.jsxOpeningElement(t.jsxIdentifier("_TamaguiTheme"), [
893
+ t.jsxAttribute(t.jsxIdentifier("name"), themeVal.value)
894
+ ]),
895
+ t.jsxClosingElement(t.jsxIdentifier("_TamaguiTheme")),
896
+ [traversePath.node]
897
+ )
898
+ )) : console.warn(
899
+ `No program path found, avoiding importing flattening / importing theme in ${sourcePath}`
900
+ )), shouldPrintDebug)
901
+ try {
902
+ logger.info(
903
+ [
904
+ " flatten?",
905
+ shouldFlatten,
906
+ (0, import_extractHelpers.objToStr)({
907
+ hasSpread,
908
+ shouldDeopt,
909
+ canFlattenProps,
910
+ shouldWrapTheme,
911
+ hasOnlyStringChildren
912
+ }),
913
+ "inlined",
914
+ inlined.size,
915
+ [...inlined]
916
+ ].join(" ")
917
+ );
918
+ } catch {
919
+ }
920
+ if (shouldDeopt || !shouldFlatten) {
921
+ shouldPrintDebug && logger.info(`Deopting ${shouldDeopt} ${shouldFlatten}`), node.attributes = ogAttributes;
922
+ return;
923
+ }
924
+ shouldPrintDebug && logger.info(
925
+ [` - attrs (flattened):
926
+ `, (0, import_logLines.logLines)(attrs.map(import_extractHelpers.attrStr).join(", "))].join(
927
+ " "
928
+ )
929
+ );
930
+ let foundStaticProps = {};
931
+ for (const key in attrs) {
932
+ const cur = attrs[key];
933
+ if (cur.type === "style") {
934
+ const expanded = normalizeStyleWithoutVariants(cur.value);
935
+ for (const key2 in expanded)
936
+ mergeToEnd(foundStaticProps, key2, expanded[key2]);
937
+ continue;
938
+ }
939
+ if (cur.type === "attr") {
940
+ if (t.isJSXSpreadAttribute(cur.value) || !t.isJSXIdentifier(cur.value.name))
941
+ continue;
942
+ const key2 = cur.value.name.name, value = attemptEvalSafe(cur.value.value || t.booleanLiteral(!0));
943
+ value !== import_constants.FAILED_EVAL && mergeToEnd(foundStaticProps, key2, value);
944
+ }
945
+ }
946
+ const completeProps = {};
947
+ for (const key in defaultProps)
948
+ key in foundStaticProps || (completeProps[key] = defaultProps[key]);
949
+ for (const key in foundStaticProps)
950
+ completeProps[key] = foundStaticProps[key];
951
+ attrs = attrs.reduce((acc, cur) => {
952
+ if (!cur) return acc;
953
+ if (cur.type === "attr" && !t.isJSXSpreadAttribute(cur.value) && shouldFlatten) {
954
+ const name = cur.value.name.name;
955
+ if (typeof name == "string") {
956
+ if (name === "tag")
957
+ return acc;
958
+ if (variants[name] && variantValues.has(name)) {
959
+ const styleState = {
960
+ ...propMapperStyleState,
961
+ props: completeProps
962
+ };
963
+ let out = Object.fromEntries(
964
+ propMapper(name, variantValues.get(name), styleState) || []
965
+ );
966
+ if (out && isTargetingHTML) {
967
+ const cn = out.className;
968
+ out = reactNativeWebInternals.createDOMProps(
969
+ isTextView ? "span" : "div",
970
+ out
971
+ ), out.className = cn;
972
+ }
973
+ shouldPrintDebug && logger.info([" - expanded variant", name, out].join(" "));
974
+ for (const key2 in out) {
975
+ const value2 = out[key2];
976
+ isValidStyleKey(key2, staticConfig) ? acc.push({
977
+ type: "style",
978
+ value: { [key2]: value2 },
979
+ name: key2,
980
+ attr: cur.value
981
+ }) : acc.push({
982
+ type: "attr",
983
+ value: t.jsxAttribute(
984
+ t.jsxIdentifier(key2),
985
+ t.jsxExpressionContainer(
986
+ typeof value2 == "string" ? t.stringLiteral(value2) : (0, import_literalToAst.literalToAst)(value2)
987
+ )
988
+ )
989
+ });
990
+ }
991
+ }
992
+ }
993
+ }
994
+ if (cur.type !== "style")
995
+ return acc.push(cur), acc;
996
+ let key = Object.keys(cur.value)[0];
997
+ const value = cur.value[key], fullKey = tamaguiConfig?.shorthands[key];
998
+ return fullKey && (cur.value = { [fullKey]: value }, key = fullKey), disableExtractVariables && value[0] === "$" && (usedThemeKeys.has(key) || usedThemeKeys.has(fullKey)) ? (shouldPrintDebug && logger.info([` keeping variable inline: ${key} =`, value].join(" ")), acc.push({
999
+ type: "attr",
1000
+ value: t.jsxAttribute(
1001
+ t.jsxIdentifier(key),
1002
+ t.jsxExpressionContainer(t.stringLiteral(value))
1003
+ )
1004
+ }), acc) : (acc.push(cur), acc);
1005
+ }, []), tm.mark("jsx-element-expanded", !!shouldPrintDebug), shouldPrintDebug && logger.info(
1006
+ [` - attrs (expanded):
1007
+ `, (0, import_logLines.logLines)(attrs.map(import_extractHelpers.attrStr).join(", "))].join(
1008
+ " "
1009
+ )
1010
+ );
1011
+ let prev = null;
1012
+ const getProps = (props, includeProps = !1, debugName = "") => {
1013
+ if (!props)
1014
+ return shouldPrintDebug && logger.info([" getProps() no props"].join(" ")), {};
1015
+ if (excludeProps?.size)
1016
+ for (const key in props)
1017
+ excludeProps.has(key) && (shouldPrintDebug && logger.info([" delete excluded", key].join(" ")), delete props[key]);
1018
+ const before = process.env.IS_STATIC;
1019
+ process.env.IS_STATIC = "is_static";
1020
+ try {
1021
+ const out = getSplitStyles(
1022
+ props,
1023
+ staticConfig,
1024
+ defaultTheme,
1025
+ "",
1026
+ componentState,
1027
+ {
1028
+ ...styleProps,
1029
+ noClassNames: !0,
1030
+ fallbackProps: completeProps
1031
+ },
1032
+ void 0,
1033
+ void 0,
1034
+ void 0,
1035
+ debugPropValue || shouldPrintDebug
1036
+ // options.experimentalFlattenThemesOnNative
1037
+ );
1038
+ let outProps = {
1039
+ ...includeProps ? out.viewProps : {},
1040
+ ...out.style,
1041
+ ...out.pseudos
1042
+ };
1043
+ for (const key in outProps)
1044
+ deoptProps.has(key) && (shouldFlatten = !1);
1045
+ return shouldPrintDebug && (logger.info(`(${debugName})`), logger.info(`
1046
+ getProps (props in): ${(0, import_logLines.logLines)((0, import_extractHelpers.objToStr)(props))}`), logger.info(
1047
+ `
1048
+ getProps (outProps): ${(0, import_logLines.logLines)((0, import_extractHelpers.objToStr)(outProps))}`
1049
+ )), out.fontFamily && ((0, import_propsToFontFamilyCache.setPropsToFontFamily)(outProps, out.fontFamily), shouldPrintDebug && logger.info(`
1050
+ \u{1F4AC} new font fam: ${out.fontFamily}`)), outProps;
1051
+ } catch (err) {
1052
+ return logger.info(["error", err.message, err.stack].join(" ")), {};
1053
+ } finally {
1054
+ process.env.IS_STATIC = before;
1055
+ }
1056
+ };
1057
+ shouldFlatten && attrs.unshift({
1058
+ type: "style",
1059
+ value: defaultProps
1060
+ }), attrs = attrs.reduce((acc, cur) => {
1061
+ if (cur.type === "style") {
1062
+ const key = Object.keys(cur.value)[0], value = cur.value[key];
1063
+ if (
1064
+ // !isStyleAndAttr[key] &&
1065
+ !shouldFlatten && // de-opt if non-style
1066
+ !validStyles[key] && !pseudoDescriptors[key] && !(key.startsWith("data-") || key.startsWith("aria-"))
1067
+ )
1068
+ return shouldPrintDebug && logger.info([" - keeping as non-style", key].join(" ")), prev = cur, acc.push({
1069
+ type: "attr",
1070
+ value: t.jsxAttribute(
1071
+ t.jsxIdentifier(key),
1072
+ t.jsxExpressionContainer(
1073
+ typeof value == "string" ? t.stringLiteral(value) : (0, import_literalToAst.literalToAst)(value)
1074
+ )
1075
+ )
1076
+ }), acc.push(cur), acc;
1077
+ if (prev?.type === "style")
1078
+ return mergeStyles(prev.value, cur.value), acc;
1079
+ }
1080
+ return cur.type === "style" && (prev = cur), acc.push(cur), acc;
1081
+ }, []), shouldPrintDebug && logger.info(
1082
+ [
1083
+ ` - attrs (combined \u{1F500}):
1084
+ `,
1085
+ (0, import_logLines.logLines)(attrs.map(import_extractHelpers.attrStr).join(", "))
1086
+ ].join(" ")
1087
+ );
1088
+ let getStyleError = null;
1089
+ for (const attr of attrs)
1090
+ try {
1091
+ switch (shouldPrintDebug && console.info(` Processing ${attr.type}:`), attr.type) {
1092
+ case "ternary": {
1093
+ const a = getProps(attr.value.alternate, !1, "ternary.alternate"), c = getProps(attr.value.consequent, !1, "ternary.consequent");
1094
+ a && (attr.value.alternate = a), c && (attr.value.consequent = c), shouldPrintDebug && logger.info([" => tern ", (0, import_extractHelpers.attrStr)(attr)].join(" "));
1095
+ continue;
1096
+ }
1097
+ case "style": {
1098
+ const styles = getProps(attr.value, !1, "style");
1099
+ styles && (attr.value = styles), shouldPrintDebug && logger.info(
1100
+ [" * styles (in)", (0, import_logLines.logLines)((0, import_extractHelpers.objToStr)(attr.value))].join(" ")
1101
+ ), shouldPrintDebug && logger.info(
1102
+ [" * styles (out)", (0, import_logLines.logLines)((0, import_extractHelpers.objToStr)(styles))].join(" ")
1103
+ );
1104
+ continue;
1105
+ }
1106
+ case "attr":
1107
+ if (shouldFlatten && t.isJSXAttribute(attr.value)) {
1108
+ const key = attr.value.name.name;
1109
+ if (key === "style" || key === "className" || key === "tag")
1110
+ continue;
1111
+ const value = attemptEvalSafe(
1112
+ attr.value.value || t.booleanLiteral(!0)
1113
+ );
1114
+ if (value !== import_constants.FAILED_EVAL) {
1115
+ const outProps = getProps({ [key]: value }, !0, `attr.${key}`), outKey = Object.keys(outProps)[0];
1116
+ if (outKey) {
1117
+ const outVal = outProps[outKey];
1118
+ attr.value = t.jsxAttribute(
1119
+ t.jsxIdentifier(outKey),
1120
+ t.jsxExpressionContainer(
1121
+ typeof outVal == "string" ? t.stringLiteral(outVal) : (0, import_literalToAst.literalToAst)(outVal)
1122
+ )
1123
+ );
1124
+ }
1125
+ }
1126
+ }
1127
+ }
1128
+ } catch (err) {
1129
+ getStyleError = err;
1130
+ }
1131
+ if (shouldPrintDebug && logger.info(
1132
+ [
1133
+ ` - attrs (ternaries/combined):
1134
+ `,
1135
+ (0, import_logLines.logLines)(attrs.map(import_extractHelpers.attrStr).join(", "))
1136
+ ].join(" ")
1137
+ ), tm.mark("jsx-element-styles", !!shouldPrintDebug), getStyleError)
1138
+ return logger.info([" \u26A0\uFE0F postprocessing error, deopt", getStyleError].join(" ")), node.attributes = ogAttributes, null;
1139
+ const existingStyleKeys = /* @__PURE__ */ new Set();
1140
+ for (let i = attrs.length - 1; i >= 0; i--) {
1141
+ const attr = attrs[i];
1142
+ if (shouldFlatten && attr.type === "attr" && t.isJSXAttribute(attr.value) && t.isJSXIdentifier(attr.value.name)) {
1143
+ const name = attr.value.name.name;
1144
+ INLINE_EXTRACTABLE[name] && (attr.value.name.name = INLINE_EXTRACTABLE[name]);
1145
+ }
1146
+ if (attr.type === "style")
1147
+ for (const key in attr.value)
1148
+ existingStyleKeys.has(key) ? (shouldPrintDebug && logger.info([` >> delete existing ${key}`].join(" ")), delete attr.value[key]) : existingStyleKeys.add(key);
1149
+ attr.type === "dynamic-style" && (existingStyleKeys.has(attr.name) ? attrs[i] = void 0 : existingStyleKeys.add(attr.name));
1150
+ }
1151
+ if (options.experimentalFlattenThemesOnNative && (attrs = attrs.filter(Boolean)), !shouldFlatten && inlineWhenUnflattened.size) {
1152
+ for (const [index, attr] of attrs.entries())
1153
+ if (attr.type === "style")
1154
+ for (const key in attr.value) {
1155
+ if (!inlineWhenUnflattened.has(key)) continue;
1156
+ const val = inlineWhenUnflattenedOGVals[key];
1157
+ val ? (delete attr.value[key], attrs.splice(index - 1, 0, val.attr)) : delete attr.value[key];
1158
+ }
1159
+ }
1160
+ if (attrs = attrs.filter((x) => !((x.type === "style" || x.type === "dynamic-style") && Object.keys(x.value).length === 0)), shouldFlatten && (shouldPrintDebug && logger.info([" [\u2705] flattening", originalNodeName, flatNode].join(" ")), node.name.name = flatNode, res.flattened++, closingElement && (closingElement.name.name = flatNode)), !shouldFlatten && platform2 === "native")
1161
+ return shouldPrintDebug && logger.info(
1162
+ `Disabled flattening except for simple cases on native for now: ${JSON.stringify(
1163
+ {
1164
+ flatNode,
1165
+ shouldDeopt,
1166
+ canFlattenProps,
1167
+ hasSpread,
1168
+ "staticConfig.isStyledHOC": staticConfig.isStyledHOC,
1169
+ "!staticConfig.isHOC": !staticConfig.isHOC,
1170
+ "staticConfig.isReactNative": staticConfig.isReactNative,
1171
+ "staticConfig.neverFlatten": staticConfig.neverFlatten
1172
+ },
1173
+ null,
1174
+ 2
1175
+ )}`
1176
+ ), node.attributes = ogAttributes, null;
1177
+ shouldPrintDebug && (logger.info(
1178
+ [
1179
+ ` - inlined props (${inlined.size}):`,
1180
+ shouldDeopt ? " deopted" : "",
1181
+ hasSpread ? " has spread" : "",
1182
+ staticConfig.neverFlatten ? "neverFlatten" : ""
1183
+ ].join(" ")
1184
+ ), logger.info(` - shouldFlatten/isFlattened: ${shouldFlatten}`), logger.info(` - attrs (end):
1185
+ ${(0, import_logLines.logLines)(attrs.map(import_extractHelpers.attrStr).join(", "))}`)), onExtractTag({
1186
+ parserProps: propsWithFileInfo,
1187
+ attrs,
1188
+ node,
1189
+ lineNumbers,
1190
+ filePath,
1191
+ config: tamaguiConfig,
1192
+ attemptEval,
1193
+ jsxPath: traversePath,
1194
+ originalNodeName,
1195
+ isFlattened: shouldFlatten,
1196
+ programPath,
1197
+ completeProps,
1198
+ staticConfig
1199
+ });
1200
+ } catch (err) {
1201
+ node.attributes = ogAttributes, console.error(
1202
+ `@tamagui/static error, reverting optimization. In ${filePath} ${lineNumbers} on ${originalNodeName}: ${err.message}. For stack trace set environment TAMAGUI_DEBUG=1`
1203
+ ), process.env.TAMAGUI_DEBUG === "1" && console.error(err.stack);
1204
+ } finally {
1205
+ debugPropValue && (shouldPrintDebug = ogDebug);
1206
+ }
1207
+ }
1208
+ }), tm.mark("jsx-done", !!shouldPrintDebug), modifiedComponents.size) {
1209
+ const all = Array.from(modifiedComponents);
1210
+ shouldPrintDebug && logger.info(` [\u{1FA9D}] hook check ${all.length}`);
1211
+ for (const comp of all)
1212
+ (0, import_removeUnusedHooks.removeUnusedHooks)(comp, shouldPrintDebug);
1213
+ }
1214
+ return tm.done(shouldPrintDebug === "verbose"), res;
1215
+ }
1216
+ }
1217
+ //# sourceMappingURL=createExtractor.js.map