@hanzogui/static 2.0.0

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