@tamagui/static 1.26.0 → 1.26.1

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