rnwind 0.0.1 → 0.0.3

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 (330) hide show
  1. package/lib/cjs/core/parser/animation.cjs +427 -0
  2. package/lib/cjs/core/parser/animation.cjs.map +1 -0
  3. package/lib/cjs/core/parser/animation.d.ts +126 -0
  4. package/lib/cjs/core/parser/border-dispatcher.cjs +180 -0
  5. package/lib/cjs/core/parser/border-dispatcher.cjs.map +1 -0
  6. package/lib/cjs/core/parser/border-dispatcher.d.ts +15 -0
  7. package/lib/cjs/core/parser/case-convert.cjs +15 -0
  8. package/lib/cjs/core/parser/case-convert.cjs.map +1 -0
  9. package/lib/cjs/core/parser/case-convert.d.ts +6 -0
  10. package/lib/cjs/core/parser/color-properties-dispatcher.cjs +84 -0
  11. package/lib/cjs/core/parser/color-properties-dispatcher.cjs.map +1 -0
  12. package/lib/cjs/core/parser/color-properties-dispatcher.d.ts +19 -0
  13. package/lib/cjs/core/parser/color.cjs +193 -0
  14. package/lib/cjs/core/parser/color.cjs.map +1 -0
  15. package/lib/cjs/core/parser/color.d.ts +12 -0
  16. package/lib/cjs/core/parser/constants.cjs +21 -0
  17. package/lib/cjs/core/parser/constants.cjs.map +1 -0
  18. package/lib/cjs/core/parser/constants.d.ts +8 -0
  19. package/lib/cjs/core/parser/declaration.cjs +347 -0
  20. package/lib/cjs/core/parser/declaration.cjs.map +1 -0
  21. package/lib/cjs/core/parser/declaration.d.ts +15 -0
  22. package/lib/cjs/core/parser/gradient.cjs +132 -0
  23. package/lib/cjs/core/parser/gradient.cjs.map +1 -0
  24. package/lib/cjs/core/parser/gradient.d.ts +59 -0
  25. package/lib/cjs/core/parser/haptics.cjs +73 -0
  26. package/lib/cjs/core/parser/haptics.cjs.map +1 -0
  27. package/lib/cjs/core/parser/haptics.d.ts +47 -0
  28. package/lib/cjs/core/parser/index.d.ts +8 -0
  29. package/lib/cjs/core/parser/keyframes.cjs +95 -0
  30. package/lib/cjs/core/parser/keyframes.cjs.map +1 -0
  31. package/lib/cjs/core/parser/keyframes.d.ts +26 -0
  32. package/lib/cjs/core/parser/layout-dispatcher.cjs +120 -0
  33. package/lib/cjs/core/parser/layout-dispatcher.cjs.map +1 -0
  34. package/lib/cjs/core/parser/layout-dispatcher.d.ts +14 -0
  35. package/lib/cjs/core/parser/length.cjs +110 -0
  36. package/lib/cjs/core/parser/length.cjs.map +1 -0
  37. package/lib/cjs/core/parser/length.d.ts +51 -0
  38. package/lib/cjs/core/parser/motion-dispatcher.cjs +77 -0
  39. package/lib/cjs/core/parser/motion-dispatcher.cjs.map +1 -0
  40. package/lib/cjs/core/parser/motion-dispatcher.d.ts +11 -0
  41. package/lib/cjs/core/parser/property.cjs +22 -0
  42. package/lib/cjs/core/parser/property.cjs.map +1 -0
  43. package/lib/cjs/core/parser/property.d.ts +8 -0
  44. package/lib/cjs/core/parser/safe-area.cjs +404 -0
  45. package/lib/cjs/core/parser/safe-area.cjs.map +1 -0
  46. package/lib/cjs/core/parser/safe-area.d.ts +39 -0
  47. package/lib/cjs/core/parser/selector.cjs +22 -0
  48. package/lib/cjs/core/parser/selector.cjs.map +1 -0
  49. package/lib/cjs/core/parser/selector.d.ts +11 -0
  50. package/lib/cjs/core/parser/shorthand.cjs +188 -0
  51. package/lib/cjs/core/parser/shorthand.cjs.map +1 -0
  52. package/lib/cjs/core/parser/shorthand.d.ts +67 -0
  53. package/lib/cjs/core/parser/text-truncate.cjs +78 -0
  54. package/lib/cjs/core/parser/text-truncate.cjs.map +1 -0
  55. package/lib/cjs/core/parser/text-truncate.d.ts +44 -0
  56. package/lib/cjs/core/parser/theme-vars.cjs +467 -0
  57. package/lib/cjs/core/parser/theme-vars.cjs.map +1 -0
  58. package/lib/cjs/core/parser/theme-vars.d.ts +82 -0
  59. package/lib/cjs/core/parser/tokens.cjs +486 -0
  60. package/lib/cjs/core/parser/tokens.cjs.map +1 -0
  61. package/lib/cjs/core/parser/tokens.d.ts +45 -0
  62. package/lib/cjs/core/parser/transform.cjs +198 -0
  63. package/lib/cjs/core/parser/transform.cjs.map +1 -0
  64. package/lib/cjs/core/parser/transform.d.ts +36 -0
  65. package/lib/cjs/core/parser/tw-parser.cjs +1680 -0
  66. package/lib/cjs/core/parser/tw-parser.cjs.map +1 -0
  67. package/lib/cjs/core/parser/tw-parser.d.ts +210 -0
  68. package/lib/cjs/core/parser/types.d.ts +37 -0
  69. package/lib/cjs/core/parser/typography-dispatcher.cjs +108 -0
  70. package/lib/cjs/core/parser/typography-dispatcher.cjs.map +1 -0
  71. package/lib/cjs/core/parser/typography-dispatcher.d.ts +11 -0
  72. package/lib/cjs/core/parser/typography.cjs +97 -0
  73. package/lib/cjs/core/parser/typography.cjs.map +1 -0
  74. package/lib/cjs/core/parser/typography.d.ts +43 -0
  75. package/lib/cjs/core/style-builder/build-style.cjs +444 -0
  76. package/lib/cjs/core/style-builder/build-style.cjs.map +1 -0
  77. package/lib/cjs/core/style-builder/build-style.d.ts +54 -0
  78. package/lib/cjs/core/style-builder/index.d.ts +3 -0
  79. package/lib/cjs/core/style-builder/union-builder.cjs +326 -0
  80. package/lib/cjs/core/style-builder/union-builder.cjs.map +1 -0
  81. package/lib/cjs/core/style-builder/union-builder.d.ts +128 -0
  82. package/lib/cjs/core/types.d.ts +14 -0
  83. package/lib/cjs/metro/dts.cjs +127 -0
  84. package/lib/cjs/metro/dts.cjs.map +1 -0
  85. package/lib/cjs/metro/dts.d.ts +16 -0
  86. package/lib/cjs/metro/index.cjs +19 -0
  87. package/lib/cjs/metro/index.cjs.map +1 -0
  88. package/lib/cjs/metro/index.d.ts +9 -0
  89. package/lib/cjs/metro/resolver.cjs +47 -0
  90. package/lib/cjs/metro/resolver.cjs.map +1 -0
  91. package/lib/cjs/metro/resolver.d.ts +22 -0
  92. package/lib/cjs/metro/state.cjs +301 -0
  93. package/lib/cjs/metro/state.cjs.map +1 -0
  94. package/lib/cjs/metro/state.d.ts +88 -0
  95. package/lib/cjs/metro/transform-ast.cjs +1472 -0
  96. package/lib/cjs/metro/transform-ast.cjs.map +1 -0
  97. package/lib/cjs/metro/transform-ast.d.ts +88 -0
  98. package/lib/cjs/metro/transformer.cjs +372 -0
  99. package/lib/cjs/metro/transformer.cjs.map +1 -0
  100. package/lib/cjs/metro/transformer.d.ts +47 -0
  101. package/lib/cjs/metro/warn-unknown-classes.cjs +86 -0
  102. package/lib/cjs/metro/warn-unknown-classes.cjs.map +1 -0
  103. package/lib/cjs/metro/warn-unknown-classes.d.ts +21 -0
  104. package/lib/cjs/metro/with-config.cjs +196 -0
  105. package/lib/cjs/metro/with-config.cjs.map +1 -0
  106. package/lib/cjs/metro/with-config.d.ts +79 -0
  107. package/lib/cjs/runtime/chain-handlers.cjs +37 -0
  108. package/lib/cjs/runtime/chain-handlers.cjs.map +1 -0
  109. package/lib/cjs/runtime/chain-handlers.d.ts +33 -0
  110. package/lib/cjs/runtime/components/rnwind-provider.cjs +98 -0
  111. package/lib/cjs/runtime/components/rnwind-provider.cjs.map +1 -0
  112. package/lib/cjs/runtime/components/rnwind-provider.d.ts +84 -0
  113. package/lib/cjs/runtime/gradient-types.d.ts +58 -0
  114. package/lib/cjs/runtime/haptics.cjs +113 -0
  115. package/lib/cjs/runtime/haptics.cjs.map +1 -0
  116. package/lib/cjs/runtime/haptics.d.ts +48 -0
  117. package/lib/cjs/runtime/hooks/use-css.cjs +21 -0
  118. package/lib/cjs/runtime/hooks/use-css.cjs.map +1 -0
  119. package/lib/cjs/runtime/hooks/use-css.d.ts +11 -0
  120. package/lib/cjs/runtime/hooks/use-interact.cjs +46 -0
  121. package/lib/cjs/runtime/hooks/use-interact.cjs.map +1 -0
  122. package/lib/cjs/runtime/hooks/use-interact.d.ts +42 -0
  123. package/lib/cjs/runtime/hooks/use-scheme.cjs +68 -0
  124. package/lib/cjs/runtime/hooks/use-scheme.cjs.map +1 -0
  125. package/lib/cjs/runtime/hooks/use-scheme.d.ts +34 -0
  126. package/lib/cjs/runtime/index.cjs +45 -0
  127. package/lib/cjs/runtime/index.cjs.map +1 -0
  128. package/lib/cjs/runtime/index.d.ts +27 -0
  129. package/lib/cjs/runtime/interactive-box.cjs +35 -0
  130. package/lib/cjs/runtime/interactive-box.cjs.map +1 -0
  131. package/lib/cjs/runtime/interactive-box.d.ts +40 -0
  132. package/lib/cjs/runtime/lookup-css.cjs +542 -0
  133. package/lib/cjs/runtime/lookup-css.cjs.map +1 -0
  134. package/lib/cjs/runtime/lookup-css.d.ts +164 -0
  135. package/lib/cjs/runtime/types.d.ts +29 -0
  136. package/lib/cjs/testing/index.cjs +367 -0
  137. package/lib/cjs/testing/index.cjs.map +1 -0
  138. package/lib/cjs/testing/index.d.ts +145 -0
  139. package/lib/esm/core/parser/animation.d.ts +126 -0
  140. package/lib/esm/core/parser/animation.mjs +408 -0
  141. package/lib/esm/core/parser/animation.mjs.map +1 -0
  142. package/lib/esm/core/parser/border-dispatcher.d.ts +15 -0
  143. package/lib/esm/core/parser/border-dispatcher.mjs +178 -0
  144. package/lib/esm/core/parser/border-dispatcher.mjs.map +1 -0
  145. package/lib/esm/core/parser/case-convert.d.ts +6 -0
  146. package/lib/esm/core/parser/case-convert.mjs +13 -0
  147. package/lib/esm/core/parser/case-convert.mjs.map +1 -0
  148. package/lib/esm/core/parser/color-properties-dispatcher.d.ts +19 -0
  149. package/lib/esm/core/parser/color-properties-dispatcher.mjs +82 -0
  150. package/lib/esm/core/parser/color-properties-dispatcher.mjs.map +1 -0
  151. package/lib/esm/core/parser/color.d.ts +12 -0
  152. package/lib/esm/core/parser/color.mjs +191 -0
  153. package/lib/esm/core/parser/color.mjs.map +1 -0
  154. package/lib/esm/core/parser/constants.d.ts +8 -0
  155. package/lib/esm/core/parser/constants.mjs +13 -0
  156. package/lib/esm/core/parser/constants.mjs.map +1 -0
  157. package/lib/esm/core/parser/declaration.d.ts +15 -0
  158. package/lib/esm/core/parser/declaration.mjs +345 -0
  159. package/lib/esm/core/parser/declaration.mjs.map +1 -0
  160. package/lib/esm/core/parser/gradient.d.ts +59 -0
  161. package/lib/esm/core/parser/gradient.mjs +130 -0
  162. package/lib/esm/core/parser/gradient.mjs.map +1 -0
  163. package/lib/esm/core/parser/haptics.d.ts +47 -0
  164. package/lib/esm/core/parser/haptics.mjs +71 -0
  165. package/lib/esm/core/parser/haptics.mjs.map +1 -0
  166. package/lib/esm/core/parser/index.d.ts +8 -0
  167. package/lib/esm/core/parser/keyframes.d.ts +26 -0
  168. package/lib/esm/core/parser/keyframes.mjs +91 -0
  169. package/lib/esm/core/parser/keyframes.mjs.map +1 -0
  170. package/lib/esm/core/parser/layout-dispatcher.d.ts +14 -0
  171. package/lib/esm/core/parser/layout-dispatcher.mjs +118 -0
  172. package/lib/esm/core/parser/layout-dispatcher.mjs.map +1 -0
  173. package/lib/esm/core/parser/length.d.ts +51 -0
  174. package/lib/esm/core/parser/length.mjs +104 -0
  175. package/lib/esm/core/parser/length.mjs.map +1 -0
  176. package/lib/esm/core/parser/motion-dispatcher.d.ts +11 -0
  177. package/lib/esm/core/parser/motion-dispatcher.mjs +75 -0
  178. package/lib/esm/core/parser/motion-dispatcher.mjs.map +1 -0
  179. package/lib/esm/core/parser/property.d.ts +8 -0
  180. package/lib/esm/core/parser/property.mjs +20 -0
  181. package/lib/esm/core/parser/property.mjs.map +1 -0
  182. package/lib/esm/core/parser/safe-area.d.ts +39 -0
  183. package/lib/esm/core/parser/safe-area.mjs +402 -0
  184. package/lib/esm/core/parser/safe-area.mjs.map +1 -0
  185. package/lib/esm/core/parser/selector.d.ts +11 -0
  186. package/lib/esm/core/parser/selector.mjs +20 -0
  187. package/lib/esm/core/parser/selector.mjs.map +1 -0
  188. package/lib/esm/core/parser/shorthand.d.ts +67 -0
  189. package/lib/esm/core/parser/shorthand.mjs +180 -0
  190. package/lib/esm/core/parser/shorthand.mjs.map +1 -0
  191. package/lib/esm/core/parser/text-truncate.d.ts +44 -0
  192. package/lib/esm/core/parser/text-truncate.mjs +75 -0
  193. package/lib/esm/core/parser/text-truncate.mjs.map +1 -0
  194. package/lib/esm/core/parser/theme-vars.d.ts +82 -0
  195. package/lib/esm/core/parser/theme-vars.mjs +461 -0
  196. package/lib/esm/core/parser/theme-vars.mjs.map +1 -0
  197. package/lib/esm/core/parser/tokens.d.ts +45 -0
  198. package/lib/esm/core/parser/tokens.mjs +480 -0
  199. package/lib/esm/core/parser/tokens.mjs.map +1 -0
  200. package/lib/esm/core/parser/transform.d.ts +36 -0
  201. package/lib/esm/core/parser/transform.mjs +193 -0
  202. package/lib/esm/core/parser/transform.mjs.map +1 -0
  203. package/lib/esm/core/parser/tw-parser.d.ts +210 -0
  204. package/lib/esm/core/parser/tw-parser.mjs +1678 -0
  205. package/lib/esm/core/parser/tw-parser.mjs.map +1 -0
  206. package/lib/esm/core/parser/types.d.ts +37 -0
  207. package/lib/esm/core/parser/typography-dispatcher.d.ts +11 -0
  208. package/lib/esm/core/parser/typography-dispatcher.mjs +106 -0
  209. package/lib/esm/core/parser/typography-dispatcher.mjs.map +1 -0
  210. package/lib/esm/core/parser/typography.d.ts +43 -0
  211. package/lib/esm/core/parser/typography.mjs +91 -0
  212. package/lib/esm/core/parser/typography.mjs.map +1 -0
  213. package/lib/esm/core/style-builder/build-style.d.ts +54 -0
  214. package/lib/esm/core/style-builder/build-style.mjs +442 -0
  215. package/lib/esm/core/style-builder/build-style.mjs.map +1 -0
  216. package/lib/esm/core/style-builder/index.d.ts +3 -0
  217. package/lib/esm/core/style-builder/union-builder.d.ts +128 -0
  218. package/lib/esm/core/style-builder/union-builder.mjs +324 -0
  219. package/lib/esm/core/style-builder/union-builder.mjs.map +1 -0
  220. package/lib/esm/core/types.d.ts +14 -0
  221. package/lib/esm/metro/dts.d.ts +16 -0
  222. package/lib/esm/metro/dts.mjs +125 -0
  223. package/lib/esm/metro/dts.mjs.map +1 -0
  224. package/lib/esm/metro/index.d.ts +9 -0
  225. package/lib/esm/metro/index.mjs +6 -0
  226. package/lib/esm/metro/index.mjs.map +1 -0
  227. package/lib/esm/metro/resolver.d.ts +22 -0
  228. package/lib/esm/metro/resolver.mjs +43 -0
  229. package/lib/esm/metro/resolver.mjs.map +1 -0
  230. package/lib/esm/metro/state.d.ts +88 -0
  231. package/lib/esm/metro/state.mjs +291 -0
  232. package/lib/esm/metro/state.mjs.map +1 -0
  233. package/lib/esm/metro/transform-ast.d.ts +88 -0
  234. package/lib/esm/metro/transform-ast.mjs +1451 -0
  235. package/lib/esm/metro/transform-ast.mjs.map +1 -0
  236. package/lib/esm/metro/transformer.d.ts +47 -0
  237. package/lib/esm/metro/transformer.mjs +349 -0
  238. package/lib/esm/metro/transformer.mjs.map +1 -0
  239. package/lib/esm/metro/warn-unknown-classes.d.ts +21 -0
  240. package/lib/esm/metro/warn-unknown-classes.mjs +84 -0
  241. package/lib/esm/metro/warn-unknown-classes.mjs.map +1 -0
  242. package/lib/esm/metro/with-config.d.ts +79 -0
  243. package/lib/esm/metro/with-config.mjs +194 -0
  244. package/lib/esm/metro/with-config.mjs.map +1 -0
  245. package/lib/esm/runtime/chain-handlers.d.ts +33 -0
  246. package/lib/esm/runtime/chain-handlers.mjs +34 -0
  247. package/lib/esm/runtime/chain-handlers.mjs.map +1 -0
  248. package/lib/esm/runtime/components/rnwind-provider.d.ts +84 -0
  249. package/lib/esm/runtime/components/rnwind-provider.mjs +94 -0
  250. package/lib/esm/runtime/components/rnwind-provider.mjs.map +1 -0
  251. package/lib/esm/runtime/gradient-types.d.ts +58 -0
  252. package/lib/esm/runtime/haptics.d.ts +48 -0
  253. package/lib/esm/runtime/haptics.mjs +110 -0
  254. package/lib/esm/runtime/haptics.mjs.map +1 -0
  255. package/lib/esm/runtime/hooks/use-css.d.ts +11 -0
  256. package/lib/esm/runtime/hooks/use-css.mjs +19 -0
  257. package/lib/esm/runtime/hooks/use-css.mjs.map +1 -0
  258. package/lib/esm/runtime/hooks/use-interact.d.ts +42 -0
  259. package/lib/esm/runtime/hooks/use-interact.mjs +44 -0
  260. package/lib/esm/runtime/hooks/use-interact.mjs.map +1 -0
  261. package/lib/esm/runtime/hooks/use-scheme.d.ts +34 -0
  262. package/lib/esm/runtime/hooks/use-scheme.mjs +63 -0
  263. package/lib/esm/runtime/hooks/use-scheme.mjs.map +1 -0
  264. package/lib/esm/runtime/index.d.ts +27 -0
  265. package/lib/esm/runtime/index.mjs +18 -0
  266. package/lib/esm/runtime/index.mjs.map +1 -0
  267. package/lib/esm/runtime/interactive-box.d.ts +40 -0
  268. package/lib/esm/runtime/interactive-box.mjs +33 -0
  269. package/lib/esm/runtime/interactive-box.mjs.map +1 -0
  270. package/lib/esm/runtime/lookup-css.d.ts +164 -0
  271. package/lib/esm/runtime/lookup-css.mjs +531 -0
  272. package/lib/esm/runtime/lookup-css.mjs.map +1 -0
  273. package/lib/esm/runtime/types.d.ts +29 -0
  274. package/lib/esm/testing/index.d.ts +145 -0
  275. package/lib/esm/testing/index.mjs +344 -0
  276. package/lib/esm/testing/index.mjs.map +1 -0
  277. package/package.json +80 -13
  278. package/preset.css +1171 -0
  279. package/src/core/parser/animation.ts +404 -0
  280. package/src/core/parser/border-dispatcher.ts +176 -0
  281. package/src/core/parser/case-convert.ts +10 -0
  282. package/src/core/parser/color-properties-dispatcher.ts +78 -0
  283. package/src/core/parser/color.ts +191 -0
  284. package/src/core/parser/constants.ts +11 -0
  285. package/src/core/parser/declaration.ts +340 -0
  286. package/src/core/parser/gradient.ts +148 -0
  287. package/src/core/parser/haptics.ts +88 -0
  288. package/src/core/parser/index.ts +8 -0
  289. package/src/core/parser/keyframes.ts +84 -0
  290. package/src/core/parser/layout-dispatcher.ts +111 -0
  291. package/src/core/parser/length.ts +114 -0
  292. package/src/core/parser/motion-dispatcher.ts +89 -0
  293. package/src/core/parser/property.ts +15 -0
  294. package/src/core/parser/safe-area.ts +404 -0
  295. package/src/core/parser/selector.ts +17 -0
  296. package/src/core/parser/shorthand.ts +182 -0
  297. package/src/core/parser/text-truncate.ts +79 -0
  298. package/src/core/parser/theme-vars.ts +465 -0
  299. package/src/core/parser/tokens.ts +456 -0
  300. package/src/core/parser/transform.ts +195 -0
  301. package/src/core/parser/tw-parser.ts +1828 -0
  302. package/src/core/parser/types.ts +45 -0
  303. package/src/core/parser/typography-dispatcher.ts +97 -0
  304. package/src/core/parser/typography.ts +83 -0
  305. package/src/core/style-builder/build-style.ts +500 -0
  306. package/src/core/style-builder/index.ts +3 -0
  307. package/src/core/style-builder/union-builder.ts +328 -0
  308. package/src/core/types.ts +15 -0
  309. package/src/metro/dts.ts +128 -0
  310. package/src/metro/index.ts +9 -0
  311. package/src/metro/resolver.ts +42 -0
  312. package/src/metro/state.ts +305 -0
  313. package/src/metro/transform-ast.ts +1729 -0
  314. package/src/metro/transformer.ts +372 -0
  315. package/src/metro/warn-unknown-classes.ts +79 -0
  316. package/src/metro/with-config.ts +251 -0
  317. package/src/runtime/chain-handlers.ts +47 -0
  318. package/src/runtime/components/rnwind-provider.tsx +144 -0
  319. package/src/runtime/gradient-types.ts +60 -0
  320. package/src/runtime/haptics.ts +120 -0
  321. package/src/runtime/hooks/use-css.ts +16 -0
  322. package/src/runtime/hooks/use-interact.ts +65 -0
  323. package/src/runtime/hooks/use-scheme.ts +63 -0
  324. package/src/runtime/index.ts +54 -0
  325. package/src/runtime/interactive-box.tsx +57 -0
  326. package/src/runtime/lookup-css.ts +628 -0
  327. package/src/runtime/types.ts +32 -0
  328. package/src/testing/index.ts +507 -0
  329. package/src/types/tailwindcss-node.d.ts +33 -0
  330. package/src/index.ts +0 -1
@@ -0,0 +1,1451 @@
1
+ import * as t from '@babel/types';
2
+ import traverseImport from '@babel/traverse';
3
+ import { createHash } from 'node:crypto';
4
+ import { mayContainTextTruncate, detectTextTruncate } from '../core/parser/text-truncate.mjs';
5
+
6
+ const traverse = traverseImport.default ?? traverseImport;
7
+ /**
8
+ * Name of the internal rnwind context hook the transformer injects at
9
+ * each component top. Must start with `use` + uppercase letter so
10
+ * react-refresh's babel plugin folds it into each component's
11
+ * fast-refresh signature — otherwise stale signatures preserve fiber
12
+ * state across transformer changes and the rendered hook list shifts,
13
+ * which React surfaces as "change in the order of Hooks" runtime errors.
14
+ */
15
+ const USE_RNWIND_INTERNAL = 'useR_';
16
+ /** Internal alias of `useMountHaptic` — emit `_hm` instead of the public name to dodge shadowing. */
17
+ const USE_MOUNT_HAPTIC = '_hm';
18
+ /** Internal alias of `triggerHaptic` — `_ht` so a user-defined `triggerHaptic` won't shadow it. */
19
+ const TRIGGER_HAPTIC = '_ht';
20
+ /** Internal alias of `lookupCss` — `_l` so user can't accidentally shadow at the JSX call sites. */
21
+ const LOOKUP_CSS = '_l';
22
+ /** Package specifier rnwind runtime primitives import from. */
23
+ const RUNTIME_MODULE = 'rnwind';
24
+ /** Local binding name for the rnwind context hook result inside components. */
25
+ const CONTEXT_BINDING = '_t';
26
+ /**
27
+ * Name of the per-instance wrapper component rnwind substitutes for any
28
+ * JSX site that uses active: / focus: variants. One `useInteract()` lives
29
+ * INSIDE each InteractiveBox so siblings never share state — a previous
30
+ * design that called `useInteract()` once per enclosing component caused
31
+ * "press one button, all buttons glow" because every site read the same
32
+ * `_i.state` reference.
33
+ */
34
+ const INTERACTIVE_BOX = '_ib';
35
+ /** Leading variant prefixes that trigger interact wiring. */
36
+ const INTERACTIVE_PREFIXES = ['active:', 'focus:'];
37
+ /**
38
+ * Regex matching the atom-name shape of every `*-safe` utility the
39
+ * rnwind preset ships. Used by the transformer to decide whether a
40
+ * file needs the `const _i = useInsets()` binding injected. Matches
41
+ * three families:
42
+ * - `*-safe` exactly (e.g. `pt-safe`, `inset-safe`).
43
+ * - `*-safe-or-<N>` / `*-safe-offset-<N>` (e.g. `mt-safe-or-4`).
44
+ * - `*-screen-safe` (e.g. `h-screen-safe`, `min-h-screen-safe`).
45
+ *
46
+ * Dynamic className expressions always inject `_i` — we can't inspect
47
+ * the string at build time, and the runtime slow path reads `SAFE_ATOMS`
48
+ * to pick up any user-defined safe utility the preset doesn't cover.
49
+ */
50
+ const SAFE_ATOM_PATTERN = /(?:(?:^|-)safe(?:-or-|-offset-|$))|(?:-screen-safe$)/;
51
+ /**
52
+ * RN host components that NEVER emit press / focus events — wrapping
53
+ * them in `<InteractiveBox>` buys nothing and costs `useInteract()`'s
54
+ * hooks per mount. When the JSX tag is in this set, we skip the
55
+ * wrapper even for dynamic `className={…}` expressions. On a list of
56
+ * 1000 `<View className={rowCls}>` rows this drops 6 × 1000 hook
57
+ * initialisations per mount.
58
+ *
59
+ * The set is intentionally conservative — anything not listed keeps
60
+ * the wrapper. Custom components, `Animated.View`, and
61
+ * `Pressable`/`TextInput` all still get interactive variants on
62
+ * dynamic className.
63
+ */
64
+ const NON_INTERACTIVE_HOST_TAGS = new Set([
65
+ 'View',
66
+ 'Text',
67
+ 'ScrollView',
68
+ 'SafeAreaView',
69
+ 'Image',
70
+ 'ImageBackground',
71
+ 'FlatList',
72
+ 'SectionList',
73
+ 'VirtualizedList',
74
+ 'KeyboardAvoidingView',
75
+ 'ActivityIndicator',
76
+ 'RefreshControl',
77
+ 'Fragment',
78
+ ]);
79
+ /**
80
+ * Built-in prefix that's always active — covers the React Native
81
+ * ecosystem's `contentContainerStyle` pattern on ScrollView / FlatList /
82
+ * SectionList. Users who pass `classNamePrefixes` get their list merged
83
+ * on top, never replacing this.
84
+ */
85
+ const DEFAULT_CLASSNAME_PREFIXES = ['contentContainer'];
86
+ /**
87
+ * Module specifiers whose JSX exports are "host-like" — they consume
88
+ * `style` directly (and own no opaque component logic that depends on
89
+ * receiving the raw `className` string). For tags imported from these
90
+ * sources the transformer rewrites `className="…"` → `style={lookupCss(…)}`
91
+ * at build time, so the runtime cost is zero.
92
+ *
93
+ * For tags from ANY other source the transformer leaves `className`
94
+ * alone — the importing component receives the raw string and decides
95
+ * what to do with it (forward to an inner host, reshape, route a slice
96
+ * to `contentContainerStyle`, …). This is what makes patterns like
97
+ * `<MyButton className="px-4 bg-primary" />` work without rnwind
98
+ * stealing the prop before the component sees it.
99
+ *
100
+ * Users extend the list via `withRnwindConfig`'s `hostSources` option.
101
+ */
102
+ const DEFAULT_HOST_SOURCES = [
103
+ 'react-native',
104
+ 'react-native-reanimated',
105
+ 'react-native-svg',
106
+ 'react-native-gesture-handler',
107
+ 'react-native-safe-area-context',
108
+ 'expo-linear-gradient',
109
+ 'expo-image',
110
+ 'expo-blur',
111
+ 'expo-symbols',
112
+ '@shopify/flash-list',
113
+ '@shopify/react-native-skia',
114
+ 'lottie-react-native',
115
+ ];
116
+ /**
117
+ * Whether a JSX tag name is lowercase. Lowercase tags don't appear in
118
+ * native React Native userland — but if one shows up (web target via
119
+ * `react-native-web`, mdx, etc.) treat it as a host so the rewrite
120
+ * engages instead of silently dropping the className.
121
+ * @param name JSX tag identifier text.
122
+ * @returns True for ASCII-lowercase first character.
123
+ */
124
+ function isLowercaseTag(name) {
125
+ const code = name.codePointAt(0);
126
+ return code !== undefined && code >= 97 && code <= 122;
127
+ }
128
+ /**
129
+ * Walk a JSX opening element's tag name node into a dotted string
130
+ * (`Animated.View`, `Foo.Bar.Baz`). Returns `null` for namespaced names
131
+ * (`<svg:rect>` — invalid in RN; we skip them).
132
+ * @param name JSXOpeningElement name node.
133
+ * @returns Dotted tag text, or null.
134
+ */
135
+ function jsxTagText(name) {
136
+ if (t.isJSXIdentifier(name))
137
+ return name.name;
138
+ if (t.isJSXMemberExpression(name)) {
139
+ const left = jsxTagText(name.object);
140
+ return left ? `${left}.${name.property.name}` : null;
141
+ }
142
+ return null;
143
+ }
144
+ /**
145
+ * Leftmost identifier of a (possibly dotted) tag — used to look up its import source.
146
+ * @param tagText
147
+ */
148
+ function leftmostIdentifier(tagText) {
149
+ const dot = tagText.indexOf('.');
150
+ return dot === -1 ? tagText : tagText.slice(0, dot);
151
+ }
152
+ /**
153
+ * Build the per-file host lookup. Walks every `import` declaration once
154
+ * to map every locally-bound name to its source module. A JSX tag is a
155
+ * host when:
156
+ * 1. its full text matches an entry in `extraHostComponents` (verbatim),
157
+ * 2. its leftmost identifier was imported from a `hostSources` module,
158
+ * 3. it's a lowercase tag (web targets, defensive).
159
+ *
160
+ * Anything else is custom and the transformer leaves its className alone.
161
+ * @param ast File AST.
162
+ * @param extraHostSources User-supplied additional host module specifiers.
163
+ * @param extraHostComponents User-supplied additional host component names.
164
+ * @returns Lookup callback.
165
+ */
166
+ function buildHostLookup(ast, extraHostSources, extraHostComponents) {
167
+ const importSourceByLocal = new Map();
168
+ for (const node of ast.program.body) {
169
+ if (!t.isImportDeclaration(node))
170
+ continue;
171
+ const source = node.source.value;
172
+ for (const spec of node.specifiers) {
173
+ if (t.isImportDefaultSpecifier(spec) || t.isImportSpecifier(spec) || t.isImportNamespaceSpecifier(spec)) {
174
+ importSourceByLocal.set(spec.local.name, source);
175
+ }
176
+ }
177
+ }
178
+ // Recognise module-local host aliases — common pattern in React Native:
179
+ // const AnimatedTextInput = Animated.createAnimatedComponent(TextInput)
180
+ // const Animated = createAnimatedComponent(View)
181
+ // The local binding wraps a host underneath so its className must still
182
+ // be rewritten. Without this every `<AnimatedTextInput className="…" />`
183
+ // site looked custom and the className silently dropped.
184
+ const localHostAliases = collectCreateAnimatedComponentAliases(ast);
185
+ const hostSources = new Set([...DEFAULT_HOST_SOURCES, ...(extraHostSources ?? [])]);
186
+ const hostComponents = new Set(extraHostComponents);
187
+ return (tagText) => {
188
+ if (isLowercaseTag(tagText))
189
+ return true;
190
+ if (hostComponents.has(tagText))
191
+ return true;
192
+ const left = leftmostIdentifier(tagText);
193
+ if (localHostAliases.has(left))
194
+ return true;
195
+ const source = importSourceByLocal.get(left);
196
+ return source !== undefined && hostSources.has(source);
197
+ };
198
+ }
199
+ /**
200
+ * Walk top-level `const X = createAnimatedComponent(Y)` /
201
+ * `Animated.createAnimatedComponent(Y)` declarations and return the set
202
+ * of local names so the host-lookup recognises them. Reanimated +
203
+ * RN-core `Animated.createAnimatedComponent` are the only creators in
204
+ * common use; matching by callee-name covers both shapes without
205
+ * needing import-source resolution.
206
+ * @param ast File AST.
207
+ * @returns Set of locally-bound names that wrap a host component.
208
+ */
209
+ function collectCreateAnimatedComponentAliases(ast) {
210
+ const aliases = new Set();
211
+ for (const node of ast.program.body) {
212
+ const declaration = t.isExportNamedDeclaration(node) ? node.declaration : node;
213
+ if (!t.isVariableDeclaration(declaration))
214
+ continue;
215
+ for (const decl of declaration.declarations) {
216
+ if (!t.isIdentifier(decl.id) || !decl.init)
217
+ continue;
218
+ if (!isCreateAnimatedComponentCall(decl.init))
219
+ continue;
220
+ aliases.add(decl.id.name);
221
+ }
222
+ }
223
+ return aliases;
224
+ }
225
+ /**
226
+ * True for `createAnimatedComponent(...)` and `<x>.createAnimatedComponent(...)` calls.
227
+ * @param expr
228
+ */
229
+ function isCreateAnimatedComponentCall(expr) {
230
+ if (!t.isCallExpression(expr))
231
+ return false;
232
+ const { callee } = expr;
233
+ if (t.isIdentifier(callee) && callee.name === 'createAnimatedComponent')
234
+ return true;
235
+ if (t.isMemberExpression(callee) && t.isIdentifier(callee.property) && callee.property.name === 'createAnimatedComponent')
236
+ return true;
237
+ return false;
238
+ }
239
+ /**
240
+ * Mutate an already-parsed Babel AST in place:
241
+ * - Rewrite every JSX `className="…"` / `className={expr}` attribute to
242
+ * `style={lookupCss(<ref|expr>, _s, <existingStyle>)}`. Static string
243
+ * literals get a module-scope `const _c_<hash> = Object.freeze(['a',
244
+ * 'b'])` hoist so React sees an identity-stable array across renders.
245
+ * - Preserve any adjacent `style={…}` prop — it becomes the third
246
+ * argument so user inline styles keep working (and trump atoms).
247
+ * - Inject `const _s = useScheme()` at the top of the enclosing
248
+ * function component (idempotent — one injection per component).
249
+ * - Prepend `import { lookupCss, useScheme } from 'rnwind'`.
250
+ * - Prepend a side-effect `import 'rnwind/__generated/style'` so the
251
+ * union registry is loaded before any hoist runs.
252
+ * @param ast Babel File AST (usually handed to us by Metro).
253
+ * @param options Extra inputs — side-effect import specifiers + parser metadata.
254
+ * @returns Transform outcome flags + the hoist table.
255
+ */
256
+ function transformAst(ast, options) {
257
+ const hoister = createHoister();
258
+ const gradientHoister = createGradientHoister();
259
+ const literals = [];
260
+ const prefixSet = buildPrefixSet(options.classNamePrefixes);
261
+ const hapticHoister = createHapticHoister();
262
+ const isHostTag = buildHostLookup(ast, options.hostSources, options.hostComponents);
263
+ const rewriteCtx = {
264
+ needsInsets: false,
265
+ gradientAtoms: options.gradientAtoms ?? EMPTY_GRADIENT_ATOMS,
266
+ gradientHoister,
267
+ hapticAtoms: options.hapticAtoms ?? EMPTY_HAPTIC_ATOMS,
268
+ hapticHoister,
269
+ mountByComponent: new Map(),
270
+ needsHapticsHook: false,
271
+ };
272
+ let touched = false;
273
+ let usedLookupCss = false;
274
+ let usedInteractiveBox = false;
275
+ // Per-element host classification, captured the first time we see each
276
+ // JSXOpeningElement. Necessary because the InteractiveBox wrap mutates
277
+ // `parent.name` in-place from the original tag → `_ib`; sibling
278
+ // attributes processed AFTER the swap would otherwise re-classify off
279
+ // the now-meaningless `_ib` name and skip rewrites they should do
280
+ // (e.g. `contentContainerClassName` next to an `active:` className on
281
+ // the same `<ScrollView>`).
282
+ const customElements = new WeakSet();
283
+ const classifiedElements = new WeakSet();
284
+ traverse(ast, {
285
+ JSXAttribute(attributePath) {
286
+ const { node } = attributePath;
287
+ if (!t.isJSXIdentifier(node.name))
288
+ return;
289
+ const target = classifyAttributeName(node.name.name, prefixSet);
290
+ if (!target)
291
+ return;
292
+ // Skip className rewrite when the parent JSX tag is a custom
293
+ // component (not imported from a known host source). Custom
294
+ // components own their `className` prop — the transformer would
295
+ // steal the string from under them otherwise. The literal still
296
+ // appears in source text, so oxide still discovers its atoms via
297
+ // the project scan; the inner host that ultimately consumes the
298
+ // forwarded className gets rewritten by ITS file's transform.
299
+ const { parent } = attributePath;
300
+ if (t.isJSXOpeningElement(parent)) {
301
+ if (!classifiedElements.has(parent)) {
302
+ classifiedElements.add(parent);
303
+ const tagText = jsxTagText(parent.name);
304
+ if (tagText !== null && !isHostTag(tagText))
305
+ customElements.add(parent);
306
+ }
307
+ if (customElements.has(parent))
308
+ return;
309
+ }
310
+ const rewritten = rewriteClassNameAttribute(attributePath, hoister, literals, rewriteCtx, target);
311
+ if (!rewritten)
312
+ return;
313
+ touched = true;
314
+ if (rewritten.injectedInteract)
315
+ usedInteractiveBox = true;
316
+ else
317
+ usedLookupCss = true;
318
+ },
319
+ });
320
+ if (!touched && options.styleSpecifiers.length === 0)
321
+ return { touched: false, hoistedArrays: hoister.entries, literals };
322
+ // Inject `useMountHaptic(<hoisted>)` per component that had bare
323
+ // haptic atoms. Done post-traversal so we know every aggregated
324
+ // request up front and can hoist one frozen array per component.
325
+ injectMountHapticCalls(rewriteCtx);
326
+ const usedMountHaptic = rewriteCtx.mountByComponent.size > 0;
327
+ prependRuntimeImports(ast, {
328
+ usedLookupCss,
329
+ usedInteractiveBox,
330
+ usedMountHaptic,
331
+ usedTriggerHaptic: rewriteCtx.needsHapticsHook,
332
+ touched,
333
+ }, options.styleSpecifiers);
334
+ if (hoister.entries.size > 0)
335
+ injectHoistedConsts(ast, hoister.entries);
336
+ if (gradientHoister.entries.size > 0)
337
+ injectGradientConsts(ast, gradientHoister.entries);
338
+ if (hapticHoister.entries.size > 0)
339
+ injectHapticConsts(ast, hapticHoister.entries);
340
+ return { touched, hoistedArrays: hoister.entries, literals };
341
+ }
342
+ /** Default empty gradient-atoms map used when callers don't supply one. */
343
+ const EMPTY_GRADIENT_ATOMS = new Map();
344
+ /** Default empty haptic-atoms map used when callers don't supply one. */
345
+ const EMPTY_HAPTIC_ATOMS = new Map();
346
+ /**
347
+ * Merge the built-in default prefix with the caller-supplied list. The
348
+ * default (`contentContainer`) is always present; user entries are
349
+ * additive. Returned as a Set so the hot-path visitor classifies one
350
+ * attribute in O(1).
351
+ * @param userPrefixes Extra prefixes the caller wants active.
352
+ * @returns Sorted effective prefix set.
353
+ */
354
+ function buildPrefixSet(userPrefixes) {
355
+ const out = new Set(DEFAULT_CLASSNAME_PREFIXES);
356
+ if (userPrefixes)
357
+ for (const prefix of userPrefixes)
358
+ out.add(prefix);
359
+ return out;
360
+ }
361
+ /**
362
+ * Decide whether a JSX attribute name is one the transformer should
363
+ * rewrite, and derive the replacement prop name when it is.
364
+ *
365
+ * `className` is the classic path. `<prefix>ClassName` where `prefix`
366
+ * is in the active set becomes `<prefix>Style`. Everything else returns
367
+ * `null` and the visitor moves on.
368
+ * @param name JSXAttribute's identifier text.
369
+ * @param prefixes Effective prefix set for this transform.
370
+ * @returns Rewrite target record, or `null` when the attribute is not ours.
371
+ */
372
+ function classifyAttributeName(name, prefixes) {
373
+ if (name === 'className')
374
+ return { kind: 'className', styleProp: 'style' };
375
+ if (!name.endsWith('ClassName'))
376
+ return null;
377
+ const prefix = name.slice(0, -'ClassName'.length);
378
+ if (prefix.length === 0 || !prefixes.has(prefix))
379
+ return null;
380
+ return { kind: 'prefix', styleProp: `${prefix}Style` };
381
+ }
382
+ /**
383
+ * Rewrite one `className` JSXAttribute node.
384
+ *
385
+ * Two paths:
386
+ * - **Non-interactive** (literal with no `active:` / `focus:` tokens):
387
+ * emit `style={lookupCss(<ref|expr>, _s [, userStyle])}` inline on
388
+ * the existing tag. The JSX site keeps its original component.
389
+ * - **Interactive** (literal with an interactive token OR any dynamic
390
+ * expression): replace the JSXElement's tag with `<InteractiveBox>`,
391
+ * move the original tag into a `_rw.as` spec prop, and forward all
392
+ * other attributes untouched. Each InteractiveBox instance calls
393
+ * `useInteract()` internally so sibling elements don't share state.
394
+ *
395
+ * If the element has a sibling `style={…}` attribute it's removed and
396
+ * its expression threads through as the user-style merge source.
397
+ * @param attributePath The JSXAttribute path.
398
+ * @param hoister Per-file hoist table.
399
+ * @param literals Output array — each static literal gets pushed so the
400
+ * caller can feed them into the parser / atom ledger.
401
+ * @param rewriteCtx
402
+ * @param target
403
+ * @returns Outcome flags, or `null` when the attribute was unrewritable.
404
+ */
405
+ function rewriteClassNameAttribute(attributePath, hoister, literals, rewriteCtx, target) {
406
+ const { node } = attributePath;
407
+ const { value } = node;
408
+ if (!value)
409
+ return null;
410
+ const { parent } = attributePath;
411
+ if (!t.isJSXOpeningElement(parent))
412
+ return null;
413
+ // The rewrite emits references to `_t` (the `useR_()` binding). That
414
+ // binding can only live in a component body — so if this JSX site has
415
+ // no enclosing component (e.g. a top-level `const renderItem = (...) =>
416
+ // <View className=.../>` helper), bail and leave className untouched
417
+ // rather than emit a dangling `_t`. Checked BEFORE any mutation
418
+ // (hoist, sibling-style drop) so a bail leaves the AST pristine.
419
+ if (!hasComponentBody(attributePath))
420
+ return null;
421
+ const buildResult = buildFirstArgument(value, hoister, literals, rewriteCtx);
422
+ if (!buildResult)
423
+ return null;
424
+ const userStyleExpr = extractAndDropSiblingStyle(parent, target.styleProp);
425
+ // Single context binding `_t = _r()` — carries scheme, fontScale,
426
+ // insets together so React tracks all three as render deps via one
427
+ // useContext read.
428
+ const ctxBinding = injectContextHook(attributePath);
429
+ applyDerivedJsxAttributes(attributePath, parent, buildResult, target, rewriteCtx);
430
+ // Prefixed rewrites (`<prefix>ClassName`) target a passive sub-surface
431
+ // that can't receive press / focus — skip the InteractiveBox wrapper
432
+ // even for dynamic expressions. Only the plain `className` path is
433
+ // eligible for InteractiveBox routing.
434
+ if (target.kind === 'className' && buildResult.mayBeInteractive && isTagInteractive(parent.name)) {
435
+ rewriteAsInteractiveBox(attributePath, parent, buildResult.expression, ctxBinding, userStyleExpr);
436
+ return { injectedInteract: true };
437
+ }
438
+ const args = [buildResult.expression, t.identifier(ctxBinding)];
439
+ // 3rd arg = userStyle (sibling style={…}). 4th arg = interactState
440
+ // (always undefined in the non-interactive branch).
441
+ if (userStyleExpr)
442
+ args.push(userStyleExpr);
443
+ const call = t.callExpression(t.identifier(LOOKUP_CSS), args);
444
+ attributePath.replaceWith(t.jsxAttribute(t.jsxIdentifier(target.styleProp), t.jsxExpressionContainer(call)));
445
+ return { injectedInteract: false };
446
+ }
447
+ /**
448
+ * Apply every JSX attribute + side-effect derived from a parsed
449
+ * className literal: gradient props, truncate props, mount-haptic
450
+ * aggregation, and event-haptic handler chaining. Collected in one
451
+ * helper so {@link rewriteClassNameAttribute} stays under the
452
+ * complexity cap.
453
+ * @param attributePath Path of the className attribute being rewritten.
454
+ * @param parent Opening element to mutate.
455
+ * @param result Per-literal derived state.
456
+ * @param target Rewrite target (only `className`-kind gets derived attrs).
457
+ * @param rewriteCtx Rewrite-wide state.
458
+ */
459
+ function applyDerivedJsxAttributes(attributePath, parent, result, target, rewriteCtx) {
460
+ if (target.kind !== 'className')
461
+ return;
462
+ if (result.gradientAttrs)
463
+ appendGradientAttributes(parent, result.gradientAttrs);
464
+ if (result.truncateAttrs)
465
+ appendGradientAttributes(parent, result.truncateAttrs);
466
+ if (result.mountHaptics)
467
+ recordMountHaptics(attributePath, result.mountHaptics, rewriteCtx);
468
+ if (result.eventHaptics)
469
+ injectEventHapticHandlers(attributePath, parent, result.eventHaptics, rewriteCtx);
470
+ }
471
+ /**
472
+ * Splice class-derived JSX attributes (`colors={…}` / `start={…}` /
473
+ * `end={…}` for gradients; `numberOfLines=` / `ellipsizeMode=` for
474
+ * truncate) into a JSXOpeningElement's attribute list — but only when
475
+ * the developer hasn't already written that attribute themselves.
476
+ *
477
+ * **User attrs always win.** If a hand-written `colors={USER}` is
478
+ * present, the class-derived hoist is dropped on the floor for that
479
+ * specific attribute. Same rule for every derived prop, applied
480
+ * per-attribute so the user can override one slot (e.g. `start={…}`)
481
+ * and let rnwind fill in the others. Documented in
482
+ * `docs/architecture.md`.
483
+ * @param opening JSXOpeningElement to mutate.
484
+ * @param gradientAttributes Freshly built JSX attributes.
485
+ */
486
+ function appendGradientAttributes(opening, gradientAttributes) {
487
+ const userAttributeNames = new Set();
488
+ for (const attribute of opening.attributes) {
489
+ if (!t.isJSXAttribute(attribute))
490
+ continue;
491
+ if (!t.isJSXIdentifier(attribute.name))
492
+ continue;
493
+ userAttributeNames.add(attribute.name.name);
494
+ }
495
+ for (const derived of gradientAttributes) {
496
+ if (!t.isJSXIdentifier(derived.name))
497
+ continue;
498
+ if (userAttributeNames.has(derived.name.name))
499
+ continue;
500
+ opening.attributes.push(derived);
501
+ }
502
+ }
503
+ /**
504
+ * Whether a JSX tag can fire press / focus events. Pure host-tag check
505
+ * against {@link NON_INTERACTIVE_HOST_TAGS}: anything in the set is
506
+ * definitely non-interactive; anything else (custom component,
507
+ * `Animated.View`, etc.) is treated as potentially interactive so the
508
+ * InteractiveBox wrapper is still applied.
509
+ * @param name JSXOpeningElement name node.
510
+ * @returns `true` when the tag might emit press / focus events.
511
+ */
512
+ function isTagInteractive(name) {
513
+ if (t.isJSXIdentifier(name))
514
+ return !NON_INTERACTIVE_HOST_TAGS.has(name.name);
515
+ // Member expressions (`Animated.View`, `Foo.Bar`): conservatively
516
+ // treat as interactive since the outer object's semantics are opaque.
517
+ return true;
518
+ }
519
+ /**
520
+ * Replace the JSXElement's tag with `<InteractiveBox>`, packing the
521
+ * original tag, the className ref / expression, the scheme binding, and
522
+ * any user style into a single `_rw` spec prop. All other attributes
523
+ * forward through unchanged.
524
+ *
525
+ * The replacement keeps the element's children — only the opening /
526
+ * closing tag name changes, plus the className attribute is replaced by
527
+ * `_rw` (and a preceding `style` attribute was already spliced out).
528
+ * @param attributePath JSXAttribute path for the className being rewritten.
529
+ * @param opening JSXOpeningElement the attribute lives on.
530
+ * @param classNameExpr The first-arg expression (hoisted ref or dynamic).
531
+ * @param schemeBinding Name of the `_s = useScheme()` binding.
532
+ * @param ctxBinding
533
+ * @param userStyleExpr Optional user style spliced from a sibling `style={…}`.
534
+ * @param insetsBinding `_i = useInsets()` binding name when the rewrite needs insets, else null.
535
+ * @param fontScaleBinding `_fs = useFontScale()` binding name — always present since every rewrite injects it.
536
+ */
537
+ function rewriteAsInteractiveBox(attributePath, opening, classNameExpr, ctxBinding, userStyleExpr) {
538
+ const originalTagExpr = jsxNameToExpression(opening.name);
539
+ const rwProperties = [
540
+ t.objectProperty(t.identifier('as'), originalTagExpr),
541
+ t.objectProperty(t.identifier('cn'), classNameExpr),
542
+ t.objectProperty(t.identifier('t'), t.identifier(ctxBinding)),
543
+ ];
544
+ if (userStyleExpr)
545
+ rwProperties.push(t.objectProperty(t.identifier('us'), userStyleExpr));
546
+ const rwAttribute = t.jsxAttribute(t.jsxIdentifier('_rw'), t.jsxExpressionContainer(t.objectExpression(rwProperties)));
547
+ // Swap the className attribute out for `_rw`, keeping it at the
548
+ // attribute's original position so any surrounding spread attrs stay
549
+ // honouring the user's intended order.
550
+ attributePath.replaceWith(rwAttribute);
551
+ opening.name = t.jsxIdentifier(INTERACTIVE_BOX);
552
+ const jsxElement = findParentJsxElement(attributePath);
553
+ if (jsxElement?.closingElement)
554
+ jsxElement.closingElement.name = t.jsxIdentifier(INTERACTIVE_BOX);
555
+ }
556
+ /**
557
+ * Walk from a JSXAttribute path up to its JSXElement ancestor.
558
+ * @param attributePath JSXAttribute path.
559
+ * @returns The enclosing JSXElement, or `null` when the shape is unexpected.
560
+ */
561
+ function findParentJsxElement(attributePath) {
562
+ const openingPath = attributePath.parentPath;
563
+ if (!openingPath)
564
+ return null;
565
+ const elementPath = openingPath.parentPath;
566
+ if (!elementPath)
567
+ return null;
568
+ const { node } = elementPath;
569
+ return t.isJSXElement(node) ? node : null;
570
+ }
571
+ /**
572
+ * Convert a JSX opening-element name (identifier or member expression)
573
+ * into a regular JS expression we can splice into the `_rw.as` object
574
+ * property. `<Animated.View>` → `Animated.View`, `<Pressable>` →
575
+ * `Pressable`.
576
+ * @param name JSXOpeningElement name node.
577
+ * @returns Equivalent identifier / member-expression node.
578
+ */
579
+ function jsxNameToExpression(name) {
580
+ if (t.isJSXIdentifier(name))
581
+ return t.identifier(name.name);
582
+ if (t.isJSXMemberExpression(name)) {
583
+ return t.memberExpression(jsxNameToExpression(name.object), t.identifier(name.property.name));
584
+ }
585
+ throw new Error(`rnwind: unsupported JSX tag shape "${name.type ?? 'unknown'}" for interactive className`);
586
+ }
587
+ /**
588
+ * Decide what the first arg of the rewritten `lookupCss(...)` call
589
+ * should be:
590
+ * - Static string literal (`"…"` or `{"…"}` or static template): tokenize,
591
+ * push literal text for the ledger, return a hoisted const reference.
592
+ * - Dynamic expression: forward the expression unchanged; runtime
593
+ * tokenizes the string result at render time.
594
+ * @param value Attribute's value node (StringLiteral or JSXExpressionContainer).
595
+ * @param hoister Hoist table.
596
+ * @param literals Output array for static literals.
597
+ * @param rewriteCtx
598
+ * @returns The first-arg expression + interact-eligibility flag, or `null`.
599
+ */
600
+ function buildFirstArgument(value, hoister, literals, rewriteCtx) {
601
+ if (t.isStringLiteral(value))
602
+ return literalResult(value.value, hoister, literals, rewriteCtx);
603
+ if (!t.isJSXExpressionContainer(value))
604
+ return null;
605
+ const { expression } = value;
606
+ if (t.isJSXEmptyExpression(expression))
607
+ return null;
608
+ if (t.isStringLiteral(expression))
609
+ return literalResult(expression.value, hoister, literals, rewriteCtx);
610
+ if (t.isTemplateLiteral(expression) && expression.expressions.length === 0 && expression.quasis[0]) {
611
+ const text = expression.quasis[0].value.cooked ?? expression.quasis[0].value.raw;
612
+ return literalResult(text, hoister, literals, rewriteCtx);
613
+ }
614
+ // Dynamic expression — can't inspect atoms at build time. Assume safe
615
+ // is possible and pull in `_i` so the runtime can resolve any
616
+ // `*-safe` class a consumer composes at runtime. The runtime fast
617
+ // path is still taken when the dynamic string resolves to a plain
618
+ // non-safe atom list (SAFE_ATOMS index check gates the slow path).
619
+ rewriteCtx.needsInsets = true;
620
+ return { expression: expression, mayBeInteractive: true, needsInsets: true };
621
+ }
622
+ /**
623
+ * Package a literal classname into a hoisted atom-array ref and scan it
624
+ * for interactive prefixes (`active:`, `focus:`) + safe-area patterns.
625
+ * Pre-scanned literals without any interactive tokens skip the (small
626
+ * but measurable) cost of injecting a `useInteract()` hook; literals
627
+ * without any `*-safe` token skip the insets arg, keeping the runtime
628
+ * fast path engaged.
629
+ * @param text Raw classname string.
630
+ * @param hoister Hoist table.
631
+ * @param literals Output array for literal-text sink.
632
+ * @param rewriteCtx Rewrite-wide state; updated when any atom needs insets.
633
+ * @returns The expression + per-rewrite flags.
634
+ */
635
+ function literalResult(text, hoister, literals, rewriteCtx) {
636
+ literals.push(text);
637
+ const atoms = tokenize(text);
638
+ const { gradientAttrs, remaining: afterGradient } = extractGradientSpec(atoms, rewriteCtx);
639
+ const { truncateAttrs, remaining: afterTruncate } = extractTextTruncateSpec(afterGradient);
640
+ const { mountHaptics, eventHaptics, remaining } = extractHapticSpec(afterTruncate, rewriteCtx);
641
+ const mayBeInteractive = remaining.some((atom) => INTERACTIVE_PREFIXES.some((prefix) => atom.startsWith(prefix)));
642
+ const needsInsets = remaining.some((atom) => SAFE_ATOM_PATTERN.test(atom));
643
+ if (needsInsets)
644
+ rewriteCtx.needsInsets = true;
645
+ return {
646
+ expression: hoister.refFor(remaining),
647
+ mayBeInteractive,
648
+ needsInsets,
649
+ gradientAttrs: gradientAttrs.length > 0 ? gradientAttrs : undefined,
650
+ truncateAttrs: truncateAttrs.length > 0 ? truncateAttrs : undefined,
651
+ mountHaptics: mountHaptics.length > 0 ? mountHaptics : undefined,
652
+ eventHaptics: eventHaptics.length > 0 ? eventHaptics : undefined,
653
+ };
654
+ }
655
+ /**
656
+ * Scan the atom list for gradient roles (direction + from/via/to
657
+ * colours), strip those atoms out, and produce the JSX attributes the
658
+ * rewrite will splice onto the opening element:
659
+ * colors={_g_<hash>} start={_gs_<hash>} end={_ge_<hash>}
660
+ * When the atom list doesn't contain a complete gradient (no direction
661
+ * OR no colour stops), the gradient atoms pass through untouched —
662
+ * they'd resolve to `{}` in the runtime anyway. This keeps the
663
+ * transform conservative.
664
+ * @param atoms Tokenised atom list from the literal.
665
+ * @param rewriteCtx Rewrite-wide state (for the hoister).
666
+ * @returns The gradient JSX attrs (possibly empty) and the non-gradient remainder.
667
+ */
668
+ function extractGradientSpec(atoms, rewriteCtx) {
669
+ const { gradientAtoms } = rewriteCtx;
670
+ if (gradientAtoms.size === 0)
671
+ return { gradientAttrs: [], remaining: atoms };
672
+ let direction = null;
673
+ let from = null;
674
+ let via = null;
675
+ let to = null;
676
+ const remaining = [];
677
+ for (const atom of atoms) {
678
+ const info = gradientAtoms.get(atom);
679
+ if (!info) {
680
+ remaining.push(atom);
681
+ continue;
682
+ }
683
+ switch (info.role) {
684
+ case 'direction': {
685
+ direction = info.dir;
686
+ break;
687
+ }
688
+ case 'from': {
689
+ from = info.color;
690
+ break;
691
+ }
692
+ case 'via': {
693
+ via = info.color;
694
+ break;
695
+ }
696
+ case 'to': {
697
+ {
698
+ to = info.color;
699
+ // No default
700
+ }
701
+ break;
702
+ }
703
+ }
704
+ // Gradient atoms deliberately drop from `remaining` — they're
705
+ // consumed at build time and don't need a runtime style slot.
706
+ }
707
+ if (direction === null || direction === 'unknown' || (from === null && to === null)) {
708
+ // No recognisable gradient — put atoms back so they at least
709
+ // attempt to resolve through lookupCss.
710
+ return { gradientAttrs: [], remaining: atoms };
711
+ }
712
+ const colors = gradientColors(from, via, to);
713
+ const points = directionToPoints(direction);
714
+ const colorsRef = rewriteCtx.gradientHoister.refForColors(colors);
715
+ const startRef = rewriteCtx.gradientHoister.refForPoint(points.start, 'start');
716
+ const endRef = rewriteCtx.gradientHoister.refForPoint(points.end, 'end');
717
+ const attributes = [
718
+ t.jsxAttribute(t.jsxIdentifier('colors'), t.jsxExpressionContainer(colorsRef)),
719
+ t.jsxAttribute(t.jsxIdentifier('start'), t.jsxExpressionContainer(startRef)),
720
+ t.jsxAttribute(t.jsxIdentifier('end'), t.jsxExpressionContainer(endRef)),
721
+ ];
722
+ return { gradientAttrs: attributes, remaining };
723
+ }
724
+ /**
725
+ * Scan the atom list for text-truncate utilities (`truncate`,
726
+ * `line-clamp-<N>`, `line-clamp-none`, `text-ellipsis`, `text-clip`),
727
+ * strip them out, and produce the JSX attributes the rewrite will
728
+ * splice onto the opening element: `numberOfLines={N}` and/or
729
+ * `ellipsizeMode="tail"|"clip"`.
730
+ *
731
+ * Merge rule mirrors Tailwind's cascade — later atoms override earlier
732
+ * ones. `numberOfLines: 0` (the `line-clamp-none` reset) suppresses
733
+ * emission entirely; a standalone `text-ellipsis` / `text-clip` with no
734
+ * companion line count also emits nothing because `ellipsizeMode`
735
+ * alone has no effect on RN `<Text>`.
736
+ * @param atoms Tokenised atom list.
737
+ * @returns The truncate JSX attrs (possibly empty) and the non-truncate remainder.
738
+ */
739
+ function extractTextTruncateSpec(atoms) {
740
+ if (!mayContainTextTruncate(atoms))
741
+ return { truncateAttrs: [], remaining: atoms };
742
+ let numberOfLines;
743
+ let ellipsizeMode;
744
+ const remaining = [];
745
+ for (const atom of atoms) {
746
+ const info = detectTextTruncate(atom);
747
+ if (!info) {
748
+ remaining.push(atom);
749
+ continue;
750
+ }
751
+ const { numberOfLines: infoLines, ellipsizeMode: infoMode } = info;
752
+ if (infoLines !== undefined)
753
+ numberOfLines = infoLines;
754
+ if (infoMode !== undefined)
755
+ ellipsizeMode = infoMode;
756
+ }
757
+ const attributes = buildTruncateAttributes(numberOfLines, ellipsizeMode);
758
+ return { truncateAttrs: attributes, remaining };
759
+ }
760
+ /**
761
+ * Assemble JSXAttribute nodes for the resolved truncate props. Drops
762
+ * `numberOfLines` when zero (reset) and drops `ellipsizeMode` when not
763
+ * paired with a positive line count — matching RN's behaviour where
764
+ * `ellipsizeMode` needs `numberOfLines` to do anything.
765
+ * @param numberOfLines Resolved clamp count, or undefined.
766
+ * @param ellipsizeMode Resolved ellipsize mode, or undefined.
767
+ * @returns Zero, one, or two JSX attributes.
768
+ */
769
+ function buildTruncateAttributes(numberOfLines, ellipsizeMode) {
770
+ const attributes = [];
771
+ if (numberOfLines !== undefined && numberOfLines > 0) {
772
+ attributes.push(t.jsxAttribute(t.jsxIdentifier('numberOfLines'), t.jsxExpressionContainer(t.numericLiteral(numberOfLines))));
773
+ if (ellipsizeMode !== undefined) {
774
+ attributes.push(t.jsxAttribute(t.jsxIdentifier('ellipsizeMode'), t.stringLiteral(ellipsizeMode)));
775
+ }
776
+ }
777
+ return attributes;
778
+ }
779
+ /**
780
+ * Map of variant-prefix → trigger. Bare atoms (no colon) resolve to
781
+ * `'mount'` through {@link extractHapticSpec}; these entries cover the
782
+ * explicit `active:` / `focus:` / `hover:` cases.
783
+ */
784
+ const HAPTIC_VARIANT_TRIGGER = {
785
+ active: 'pressIn',
786
+ focus: 'focus',
787
+ hover: 'hover',
788
+ };
789
+ /** Map a non-mount haptic trigger to the JSX event prop it chains onto. */
790
+ const HAPTIC_EVENT_PROP = {
791
+ pressIn: 'onPressIn',
792
+ pressOut: 'onPressOut',
793
+ focus: 'onFocus',
794
+ hover: 'onMouseEnter',
795
+ };
796
+ /**
797
+ * Scan atom list for haptic utilities. Bare `haptic-*` → mount trigger;
798
+ * `active:haptic-*` / `focus:haptic-*` / `hover:haptic-*` → the matching
799
+ * event trigger. Matched atoms are stripped from the remainder so the
800
+ * runtime style resolver never tries to look up `--rnwind-haptic`.
801
+ * @param atoms Post-gradient, post-truncate atom list.
802
+ * @param rewriteCtx Rewrite-wide state (for the haptic-atom map).
803
+ * @returns Mount + event haptic entries, plus the non-haptic remainder.
804
+ */
805
+ function extractHapticSpec(atoms, rewriteCtx) {
806
+ const { hapticAtoms } = rewriteCtx;
807
+ if (hapticAtoms.size === 0)
808
+ return { mountHaptics: [], eventHaptics: [], remaining: atoms };
809
+ const mountHaptics = [];
810
+ const eventHaptics = [];
811
+ const remaining = [];
812
+ for (const atom of atoms) {
813
+ const resolved = resolveHapticAtom(atom, hapticAtoms);
814
+ if (!resolved) {
815
+ remaining.push(atom);
816
+ continue;
817
+ }
818
+ if (resolved.trigger === 'mount')
819
+ mountHaptics.push(resolved.request);
820
+ else
821
+ eventHaptics.push({ request: resolved.request, trigger: resolved.trigger });
822
+ }
823
+ return { mountHaptics, eventHaptics, remaining };
824
+ }
825
+ /**
826
+ * Classify one atom against the parser's haptic map. A colon-free atom
827
+ * maps to `'mount'`; `active:` / `focus:` / `hover:` prefixes map to
828
+ * the matching event trigger. Other prefixes return `null` so they
829
+ * fall through to the regular style path.
830
+ * @param atom Atom name, possibly variant-prefixed.
831
+ * @param hapticAtoms Parser-surfaced haptic metadata.
832
+ * @returns `{request, trigger}` on match, null otherwise.
833
+ */
834
+ function resolveHapticAtom(atom, hapticAtoms) {
835
+ // Direct lookup first — Tailwind v4 registers the variant-prefixed
836
+ // class (e.g. `active:haptic-medium`) as its own rule, and the
837
+ // parser's nested-rule walk surfaces the marker under that key.
838
+ const direct = hapticAtoms.get(atom);
839
+ if (direct) {
840
+ const colon = atom.indexOf(':');
841
+ if (colon === -1)
842
+ return { request: direct, trigger: 'mount' };
843
+ const trigger = HAPTIC_VARIANT_TRIGGER[atom.slice(0, colon)];
844
+ if (trigger)
845
+ return { request: direct, trigger };
846
+ return null;
847
+ }
848
+ // Fallback — try stripping a known variant prefix and looking up
849
+ // the bare class. Handles cases where the parser only registered
850
+ // the base utility (the variant rule may be missing if only the
851
+ // bare class is otherwise used in the theme).
852
+ const colon = atom.indexOf(':');
853
+ if (colon === -1)
854
+ return null;
855
+ const prefix = atom.slice(0, colon);
856
+ const trigger = HAPTIC_VARIANT_TRIGGER[prefix];
857
+ if (!trigger)
858
+ return null;
859
+ const bare = hapticAtoms.get(atom.slice(colon + 1));
860
+ if (!bare)
861
+ return null;
862
+ return { request: bare, trigger };
863
+ }
864
+ /**
865
+ * Append mount-haptic requests to the aggregate keyed by the JSX site's
866
+ * enclosing component body. Post-traversal the transformer injects one
867
+ * `useMountHaptic(<hoisted>)` call per component.
868
+ * @param attributePath The JSXAttribute path the haptic came from.
869
+ * @param requests Mount requests gathered from this literal.
870
+ * @param rewriteCtx Rewrite-wide state.
871
+ */
872
+ function recordMountHaptics(attributePath, requests, rewriteCtx) {
873
+ const body = findComponentBody(attributePath);
874
+ if (!body)
875
+ return;
876
+ const bucket = rewriteCtx.mountByComponent.get(body.node);
877
+ if (bucket) {
878
+ bucket.push(...requests);
879
+ return;
880
+ }
881
+ rewriteCtx.mountByComponent.set(body.node, [...requests]);
882
+ }
883
+ /**
884
+ * Splice one chained event handler per event-haptic entry onto the
885
+ * JSXOpeningElement. Each handler calls `triggerHaptic(_h, <request>,
886
+ * '<trigger>')` and then forwards to any pre-existing user handler.
887
+ * @param attributePath Path of the className attribute being rewritten.
888
+ * @param opening Opening element to mutate.
889
+ * @param entries Event-haptic entries.
890
+ * @param rewriteCtx Rewrite-wide state (for the hoister).
891
+ */
892
+ function injectEventHapticHandlers(attributePath, opening, entries, rewriteCtx) {
893
+ // Make sure `_t = _r()` is in scope — haptic dispatcher reads `_t.onHaptics`.
894
+ injectContextHook(attributePath);
895
+ rewriteCtx.needsHapticsHook = true;
896
+ const byTrigger = new Map();
897
+ for (const { request, trigger } of entries) {
898
+ const list = byTrigger.get(trigger);
899
+ if (list)
900
+ list.push(request);
901
+ else
902
+ byTrigger.set(trigger, [request]);
903
+ }
904
+ for (const [trigger, requests] of byTrigger) {
905
+ const eventProperty = HAPTIC_EVENT_PROP[trigger];
906
+ const existing = extractAndDropSiblingStyle(opening, eventProperty);
907
+ const handler = buildChainedHapticHandler(rewriteCtx, requests, trigger, existing);
908
+ opening.attributes.push(t.jsxAttribute(t.jsxIdentifier(eventProperty), t.jsxExpressionContainer(handler)));
909
+ }
910
+ }
911
+ /**
912
+ * Build the inline arrow body for one chained handler — dispatch every
913
+ * request in `requests` via `triggerHaptic`, then forward the event to
914
+ * the user-supplied handler (if any) via `existing?.(event)`.
915
+ * @param rewriteCtx Rewrite-wide state.
916
+ * @param requests Requests that share this trigger.
917
+ * @param trigger Lifecycle trigger this handler fires on.
918
+ * @param existing User-supplied event handler expression, or null.
919
+ * @returns ArrowFunctionExpression ready to splice into a JSXAttribute.
920
+ */
921
+ function buildChainedHapticHandler(rewriteCtx, requests, trigger, existing) {
922
+ const eventId = t.identifier('_e');
923
+ const body = [];
924
+ for (const request of requests) {
925
+ const ref = rewriteCtx.hapticHoister.refForRequest(request);
926
+ body.push(t.expressionStatement(t.callExpression(t.identifier(TRIGGER_HAPTIC), [
927
+ t.memberExpression(t.identifier(CONTEXT_BINDING), t.identifier('onHaptics')),
928
+ ref,
929
+ t.stringLiteral(trigger),
930
+ ])));
931
+ }
932
+ if (existing) {
933
+ body.push(t.expressionStatement(t.optionalCallExpression(existing, [eventId], true)));
934
+ }
935
+ return t.arrowFunctionExpression([eventId], t.blockStatement(body));
936
+ }
937
+ /**
938
+ * Walk the aggregated `mountByComponent` map and inject a single
939
+ * `useMountHaptic(<hoisted requests>)` call per component body.
940
+ * The hoist yields a stable `const _hm_<hash>` referencing a frozen
941
+ * array of request objects.
942
+ * @param rewriteCtx Rewrite-wide state.
943
+ */
944
+ function injectMountHapticCalls(rewriteCtx) {
945
+ for (const [body, requests] of rewriteCtx.mountByComponent) {
946
+ const ref = rewriteCtx.hapticHoister.refForRequestList(requests);
947
+ const declaration = t.expressionStatement(t.callExpression(t.identifier(USE_MOUNT_HAPTIC), [ref]));
948
+ body.body.unshift(declaration);
949
+ }
950
+ }
951
+ /**
952
+ * Derive a stable cache key for one {@link HapticRequest}. Keys are
953
+ * used both for hoister interning and mount-list digesting.
954
+ * @param request Haptic request.
955
+ * @returns Canonical key text.
956
+ */
957
+ function keyForHapticRequest(request) {
958
+ if (request.kind === 'impact')
959
+ return `impact:${request.style}`;
960
+ if (request.kind === 'notification')
961
+ return `notification:${request.type}`;
962
+ return 'selection';
963
+ }
964
+ /**
965
+ * Build the haptic hoist table. Single requests and mount-request
966
+ * lists each get their own module-scope frozen const so component
967
+ * bodies only reference stable identifiers — no per-render allocation.
968
+ * @returns HapticHoister API.
969
+ */
970
+ function createHapticHoister() {
971
+ const pool = createInternPool();
972
+ const refForRequest = (request) => pool.intern('_hr', `req:${keyForHapticRequest(request)}`, { kind: 'request', request });
973
+ const refForRequestList = (requests) => pool.intern('_hm', `list:${requests.map((request) => keyForHapticRequest(request)).join('|')}`, {
974
+ kind: 'list',
975
+ requests,
976
+ });
977
+ return { refForRequest, refForRequestList, entries: pool.entries };
978
+ }
979
+ /**
980
+ * Generic intern-pool: one shared cache for module-scope consts keyed
981
+ * by an arbitrary string. Returns a stable `t.Identifier` per key and
982
+ * records `{name → entry}` for the emitter pass.
983
+ * @returns Intern API.
984
+ */
985
+ function createInternPool() {
986
+ const byKey = new Map();
987
+ const entries = new Map();
988
+ const intern = (prefix, key, entry) => {
989
+ const existing = byKey.get(key);
990
+ if (existing)
991
+ return existing;
992
+ const hash = createHash('sha256').update(key).digest('hex').slice(0, 12);
993
+ const name = `${prefix}_${hash}`;
994
+ const ident = t.identifier(name);
995
+ byKey.set(key, ident);
996
+ entries.set(name, entry);
997
+ return ident;
998
+ };
999
+ return { intern, entries };
1000
+ }
1001
+ /**
1002
+ * Emit `const _hr_<hash> = Object.freeze({...})` and `const _hm_<hash>
1003
+ * = Object.freeze([{...}, ...])` statements at module scope — one per
1004
+ * hoister entry.
1005
+ * @param ast Babel File AST.
1006
+ * @param entries Hoister entries.
1007
+ */
1008
+ function injectHapticConsts(ast, entries) {
1009
+ const declarations = [];
1010
+ for (const [name, entry] of entries) {
1011
+ if (entry.kind === 'request') {
1012
+ declarations.push(t.variableDeclaration('const', [
1013
+ t.variableDeclarator(t.identifier(name), freezeExpression(requestLiteral(entry.request))),
1014
+ ]));
1015
+ }
1016
+ else {
1017
+ declarations.push(t.variableDeclaration('const', [
1018
+ t.variableDeclarator(t.identifier(name), freezeExpression(t.arrayExpression(entry.requests.map((request) => freezeExpression(requestLiteral(request)))))),
1019
+ ]));
1020
+ }
1021
+ }
1022
+ ast.program.body.unshift(...declarations);
1023
+ }
1024
+ /**
1025
+ * Build an `Object.freeze(...)` call around the given expression.
1026
+ * @param value Expression to freeze.
1027
+ * @returns CallExpression node.
1028
+ */
1029
+ function freezeExpression(value) {
1030
+ return t.callExpression(t.memberExpression(t.identifier('Object'), t.identifier('freeze')), [value]);
1031
+ }
1032
+ /**
1033
+ * Build an object-literal representation of a {@link HapticRequest} —
1034
+ * `{kind: 'impact', style: 'Light'}` etc.
1035
+ * @param request Haptic request.
1036
+ * @returns ObjectExpression node.
1037
+ */
1038
+ function requestLiteral(request) {
1039
+ const properties = [
1040
+ t.objectProperty(t.identifier('kind'), t.stringLiteral(request.kind)),
1041
+ ];
1042
+ if (request.kind === 'impact')
1043
+ properties.push(t.objectProperty(t.identifier('style'), t.stringLiteral(request.style)));
1044
+ else if (request.kind === 'notification')
1045
+ properties.push(t.objectProperty(t.identifier('type'), t.stringLiteral(request.type)));
1046
+ return t.objectExpression(properties);
1047
+ }
1048
+ /**
1049
+ * Normalise the `from/via/to` triple into the array
1050
+ * `<LinearGradient colors={…}>` expects: drop `null` entries while
1051
+ * keeping the source order.
1052
+ * @param from Hex colour for `from-*`, or null.
1053
+ * @param via Hex colour for `via-*`, or null.
1054
+ * @param to Hex colour for `to-*`, or null.
1055
+ * @returns Colour array (at least one entry guaranteed by the caller).
1056
+ */
1057
+ function gradientColors(from, via, to) {
1058
+ const out = [];
1059
+ if (from !== null)
1060
+ out.push(from);
1061
+ if (via !== null)
1062
+ out.push(via);
1063
+ if (to !== null)
1064
+ out.push(to);
1065
+ return out;
1066
+ }
1067
+ /**
1068
+ * Map Tailwind's stock direction tag to the `(start, end)` pair of
1069
+ * unit-square points expo-linear-gradient expects. Pure constants —
1070
+ * the same as NativeWind and the wider RN-gradient community.
1071
+ * @param dir Compact direction tag from the parser.
1072
+ * @returns Start + end point records.
1073
+ */
1074
+ function directionToPoints(dir) {
1075
+ switch (dir) {
1076
+ case 'to-r': {
1077
+ return { start: { x: 0, y: 0.5 }, end: { x: 1, y: 0.5 } };
1078
+ }
1079
+ case 'to-l': {
1080
+ return { start: { x: 1, y: 0.5 }, end: { x: 0, y: 0.5 } };
1081
+ }
1082
+ case 'to-t': {
1083
+ return { start: { x: 0.5, y: 1 }, end: { x: 0.5, y: 0 } };
1084
+ }
1085
+ case 'to-b': {
1086
+ return { start: { x: 0.5, y: 0 }, end: { x: 0.5, y: 1 } };
1087
+ }
1088
+ case 'to-tr': {
1089
+ return { start: { x: 0, y: 1 }, end: { x: 1, y: 0 } };
1090
+ }
1091
+ case 'to-tl': {
1092
+ return { start: { x: 1, y: 1 }, end: { x: 0, y: 0 } };
1093
+ }
1094
+ case 'to-br': {
1095
+ return { start: { x: 0, y: 0 }, end: { x: 1, y: 1 } };
1096
+ }
1097
+ case 'to-bl': {
1098
+ return { start: { x: 1, y: 0 }, end: { x: 0, y: 1 } };
1099
+ }
1100
+ default: {
1101
+ return { start: { x: 0, y: 0.5 }, end: { x: 1, y: 0.5 } };
1102
+ }
1103
+ }
1104
+ }
1105
+ /**
1106
+ * Look for a sibling style attribute on the same JSXOpeningElement, drop
1107
+ * it, and return its expression for the caller to pass as the `lookupCss`
1108
+ * third arg. The attribute name is parameterised so the prefix path can
1109
+ * pull `contentContainerStyle` (et al.) instead of plain `style`.
1110
+ * @param parent JSXOpeningElement containing the className we're rewriting.
1111
+ * @param styleProp The exact sibling attribute name to look for.
1112
+ * @param styleProperty
1113
+ * @returns Expression from the dropped attribute, or `null`.
1114
+ */
1115
+ function extractAndDropSiblingStyle(parent, styleProperty) {
1116
+ const { attributes } = parent;
1117
+ for (let index = 0; index < attributes.length; index += 1) {
1118
+ const attribute = attributes[index];
1119
+ if (!t.isJSXAttribute(attribute))
1120
+ continue;
1121
+ if (!t.isJSXIdentifier(attribute.name) || attribute.name.name !== styleProperty)
1122
+ continue;
1123
+ const { value } = attribute;
1124
+ if (!value || !t.isJSXExpressionContainer(value))
1125
+ return null;
1126
+ const { expression } = value;
1127
+ if (t.isJSXEmptyExpression(expression))
1128
+ return null;
1129
+ attributes.splice(index, 1);
1130
+ return expression;
1131
+ }
1132
+ return null;
1133
+ }
1134
+ const INJECTED = new WeakSet();
1135
+ /**
1136
+ * Walk up from the rewrite site to the nearest enclosing function
1137
+ * component and inject `const _t = _r()` at the top of its body. This
1138
+ * is the SINGLE rnwind context binding — `_t` carries scheme,
1139
+ * fontScale, insets, etc. Idempotent per component.
1140
+ * @param path Path of any node inside the component's JSX.
1141
+ * @returns The binding name (`_t`).
1142
+ */
1143
+ function injectContextHook(path) {
1144
+ const componentBody = findComponentBody(path);
1145
+ if (!componentBody)
1146
+ return CONTEXT_BINDING;
1147
+ if (INJECTED.has(componentBody.node))
1148
+ return CONTEXT_BINDING;
1149
+ INJECTED.add(componentBody.node);
1150
+ const declaration = t.variableDeclaration('const', [
1151
+ t.variableDeclarator(t.identifier(CONTEXT_BINDING), t.callExpression(t.identifier(USE_RNWIND_INTERNAL), [])),
1152
+ ]);
1153
+ componentBody.unshiftContainer('body', declaration);
1154
+ return CONTEXT_BINDING;
1155
+ }
1156
+ /**
1157
+ * Whether `path` sits inside a recognised function component — i.e.
1158
+ * {@link injectContextHook} would find a body to host `const _t =
1159
+ * useR_()`. Pure lookup that mirrors {@link findComponentBody}'s walk
1160
+ * but performs NO body promotion, so a caller can bail before mutating
1161
+ * when the answer is no.
1162
+ * @param path Rewrite-site path.
1163
+ * @returns True when an enclosing component function exists.
1164
+ */
1165
+ function hasComponentBody(path) {
1166
+ let current = path;
1167
+ while (current) {
1168
+ const fn = current.findParent((parent) => parent.isFunction());
1169
+ if (!fn)
1170
+ return false;
1171
+ if (isComponentFunction(fn))
1172
+ return true;
1173
+ current = fn;
1174
+ }
1175
+ return false;
1176
+ }
1177
+ /**
1178
+ * Walk up from `path` to the nearest recognised function component.
1179
+ * Accepts:
1180
+ * - `function Capital() {}` declarations.
1181
+ * - `const Capital = () => …` / `const Capital = function () {}` bindings.
1182
+ * - `forwardRef(…)` / `memo(…)` argument callbacks.
1183
+ * - `export default function () {}`.
1184
+ *
1185
+ * Arrow components with expression bodies get promoted to block bodies
1186
+ * so the hook can be `unshift`ed.
1187
+ * @param path Starting path.
1188
+ * @returns BlockStatement path of the component's body, or `null`.
1189
+ */
1190
+ function findComponentBody(path) {
1191
+ let current = path;
1192
+ while (current) {
1193
+ const fn = current.findParent((parent) => parent.isFunction());
1194
+ if (!fn)
1195
+ return null;
1196
+ if (isComponentFunction(fn))
1197
+ return ensureBlockBody(fn);
1198
+ current = fn;
1199
+ }
1200
+ return null;
1201
+ }
1202
+ /**
1203
+ * Classify a function path as a React component per the three accepted
1204
+ * shapes (PascalCase decl, PascalCase var assignment, forwardRef/memo
1205
+ * argument, default export).
1206
+ * @param fn Function-like path.
1207
+ * @returns Whether the path is a React function component.
1208
+ */
1209
+ function isComponentFunction(fn) {
1210
+ if (fn.isFunctionDeclaration()) {
1211
+ const { id } = fn.node;
1212
+ if (!id)
1213
+ return isExportDefaultValue(fn);
1214
+ return isPascalCase(id.name);
1215
+ }
1216
+ if (fn.isArrowFunctionExpression() || fn.isFunctionExpression()) {
1217
+ return isAssignedToPascalCase(fn) || isHocArgument(fn) || isExportDefaultValue(fn);
1218
+ }
1219
+ return false;
1220
+ }
1221
+ /**
1222
+ * Whether this function is the value of an `export default`.
1223
+ * @param fn Babel path pointing at the function node.
1224
+ * @returns True when the node is directly the default export value.
1225
+ */
1226
+ function isExportDefaultValue(fn) {
1227
+ const { parent } = fn;
1228
+ if (t.isExportDefaultDeclaration(parent))
1229
+ return parent.declaration === fn.node;
1230
+ return false;
1231
+ }
1232
+ /**
1233
+ * Whether this arrow/function-expression is the init of `const Capital = …`.
1234
+ * @param fn Babel path pointing at the function node.
1235
+ * @returns True when the enclosing declarator's id starts with an uppercase letter.
1236
+ */
1237
+ function isAssignedToPascalCase(fn) {
1238
+ const { parent } = fn;
1239
+ if (!t.isVariableDeclarator(parent))
1240
+ return false;
1241
+ if (!t.isIdentifier(parent.id))
1242
+ return false;
1243
+ return isPascalCase(parent.id.name);
1244
+ }
1245
+ /**
1246
+ * Whether this fn is the first argument to `forwardRef(...)` / `memo(...)`.
1247
+ * @param fn Babel path pointing at the function node.
1248
+ * @returns True when wrapped by a recognized React HOC call.
1249
+ */
1250
+ function isHocArgument(fn) {
1251
+ const { parent } = fn;
1252
+ if (!t.isCallExpression(parent))
1253
+ return false;
1254
+ if (parent.arguments[0] !== fn.node)
1255
+ return false;
1256
+ const { callee } = parent;
1257
+ if (!t.isIdentifier(callee))
1258
+ return false;
1259
+ return callee.name === 'forwardRef' || callee.name === 'memo';
1260
+ }
1261
+ /**
1262
+ * Identifier-starts-with-uppercase — Conventional React component marker.
1263
+ * @param name Identifier text.
1264
+ * @returns True when the first character is `A`–`Z`.
1265
+ */
1266
+ function isPascalCase(name) {
1267
+ const first = name.charAt(0);
1268
+ return first >= 'A' && first <= 'Z';
1269
+ }
1270
+ /**
1271
+ * Promote an expression-bodied arrow to a block so we can unshift statements in.
1272
+ * @param fn Babel path at the function / arrow whose body should be a block.
1273
+ * @returns The path, mutated in place when the body was an expression.
1274
+ */
1275
+ function ensureBlockBody(fn) {
1276
+ const bodyPath = fn.get('body');
1277
+ if (Array.isArray(bodyPath))
1278
+ throw new Error('rnwind: unexpected multi-body function node');
1279
+ if (bodyPath.isBlockStatement())
1280
+ return bodyPath;
1281
+ const node = bodyPath.node;
1282
+ bodyPath.replaceWith(t.blockStatement([t.returnStatement(node)]));
1283
+ return bodyPath;
1284
+ }
1285
+ /**
1286
+ * Build a per-file hoist table. Every unique source-order atom list gets
1287
+ * one module-scope `const _c_<hash> = Object.freeze(['a', 'b'])`. Order
1288
+ * is part of the hash key — `className="a b"` and `className="b a"`
1289
+ * intentionally produce different hoisted consts because RN's style
1290
+ * flatten is order-dependent (later atoms override earlier ones for
1291
+ * conflicting props). Canonicalizing by sort would collapse
1292
+ * `opacity-100 opacity-0` and `opacity-0 opacity-100` to the same atom
1293
+ * list and silently break the user's intended last-wins override.
1294
+ * @returns Hoister API.
1295
+ */
1296
+ function createHoister() {
1297
+ const byKey = new Map();
1298
+ const entries = new Map();
1299
+ const refFor = (atoms) => {
1300
+ const ordered = [...atoms];
1301
+ const canonical = ordered.join('\0');
1302
+ const hit = byKey.get(canonical);
1303
+ if (hit)
1304
+ return t.identifier(hit.name);
1305
+ const hash = createHash('sha256').update(canonical).digest('hex').slice(0, 12);
1306
+ const name = `_c_${hash}`;
1307
+ byKey.set(canonical, { name, atoms: ordered });
1308
+ entries.set(name, ordered);
1309
+ return t.identifier(name);
1310
+ };
1311
+ return { refFor, entries };
1312
+ }
1313
+ /**
1314
+ * Build the gradient hoist table. Colour arrays and `(x,y)` point
1315
+ * records each get their own module-scope `const _g_<hash>` so the
1316
+ * JSX site references a stable identity — `<LinearGradient
1317
+ * colors={_g_hash}>`'s prop never changes across renders, which lets
1318
+ * React's prop-diff short-circuit and keeps native-side gradient
1319
+ * rebuilds off the hot path.
1320
+ * @returns GradientHoister API.
1321
+ */
1322
+ function createGradientHoister() {
1323
+ const pool = createInternPool();
1324
+ const refForColors = (colors) => pool.intern('_g', `colors:${colors.join('|')}`, { kind: 'colors', colors });
1325
+ const refForPoint = (point, role) => {
1326
+ const prefix = role === 'start' ? '_gs' : '_ge';
1327
+ return pool.intern(prefix, `point:${point.x},${point.y}`, { kind: 'point', point });
1328
+ };
1329
+ return { refForColors, refForPoint, entries: pool.entries };
1330
+ }
1331
+ /**
1332
+ * Prepend the runtime + style imports to the file's program body.
1333
+ * Only the specifiers actually used by the rewritten code are added
1334
+ * — a file with only interactive rewrites skips `lookupCss` entirely
1335
+ * (it lives inside InteractiveBox) and vice versa.
1336
+ * @param ast File AST.
1337
+ * @param flags Which runtime symbols the rewritten code references.
1338
+ * @param styleSpecifiers Side-effect import specifiers (style.js + keyframes.js).
1339
+ */
1340
+ function prependRuntimeImports(ast, flags, styleSpecifiers) {
1341
+ const heads = [];
1342
+ for (const specifier of styleSpecifiers) {
1343
+ heads.push(t.importDeclaration([], t.stringLiteral(specifier)));
1344
+ }
1345
+ if (flags.touched) {
1346
+ heads.push(t.importDeclaration(buildRuntimeSpecifiers(flags), t.stringLiteral(RUNTIME_MODULE)));
1347
+ }
1348
+ if (heads.length > 0)
1349
+ ast.program.body.unshift(...heads);
1350
+ }
1351
+ /**
1352
+ * Build the import specifiers for the `rnwind` runtime module — only
1353
+ * symbols the rewritten code actually references. Extracted from
1354
+ * {@link prependRuntimeImports} to keep cognitive complexity low.
1355
+ * @param flags Per-file usage flags.
1356
+ * @returns The import specifiers to splice into the runtime import.
1357
+ */
1358
+ function buildRuntimeSpecifiers(flags) {
1359
+ const specifiers = [];
1360
+ const named = (name) => {
1361
+ specifiers.push(t.importSpecifier(t.identifier(name), t.identifier(name)));
1362
+ };
1363
+ if (flags.usedLookupCss)
1364
+ named(LOOKUP_CSS);
1365
+ named(USE_RNWIND_INTERNAL);
1366
+ if (flags.usedMountHaptic)
1367
+ named(USE_MOUNT_HAPTIC);
1368
+ if (flags.usedTriggerHaptic)
1369
+ named(TRIGGER_HAPTIC);
1370
+ if (flags.usedInteractiveBox)
1371
+ named(INTERACTIVE_BOX);
1372
+ return specifiers;
1373
+ }
1374
+ /**
1375
+ * Splice hoisted `const _c_<hash> = ['flex-1', 'bg-primary', ...]`
1376
+ * atom-list declarations into the file right after the imports so
1377
+ * every JSX rewrite site sees them in scope.
1378
+ *
1379
+ * The JSX site references the const as `lookupCss(_c0, _s, userStyle,
1380
+ * …)`. The runtime caches its resolved style array per
1381
+ * (hoist, scheme, stateIndex) against a global version counter, so
1382
+ * subsequent renders return the SAME array reference — zero
1383
+ * allocation on the hot path.
1384
+ * @param ast File AST.
1385
+ * @param entries Hoist table (const name → atom names).
1386
+ */
1387
+ function injectHoistedConsts(ast, entries) {
1388
+ const decls = [];
1389
+ for (const [name, atoms] of entries) {
1390
+ const array = t.arrayExpression(atoms.map((atom) => t.stringLiteral(atom)));
1391
+ decls.push(t.variableDeclaration('const', [t.variableDeclarator(t.identifier(name), array)]));
1392
+ }
1393
+ spliceAfterImports(ast, decls);
1394
+ }
1395
+ /**
1396
+ * Splice gradient const declarations after the imports. Each entry is
1397
+ * either `colors` (frozen string array) or a `point` ({x, y} object
1398
+ * literal) so `<LinearGradient>` gets a stable ref for every gradient
1399
+ * shape.
1400
+ * @param ast File AST to mutate.
1401
+ * @param entries Gradient-hoister entries.
1402
+ */
1403
+ function injectGradientConsts(ast, entries) {
1404
+ const decls = [];
1405
+ for (const [name, entry] of entries) {
1406
+ const init = entry.kind === 'colors'
1407
+ ? t.callExpression(t.memberExpression(t.identifier('Object'), t.identifier('freeze')), [
1408
+ t.arrayExpression(entry.colors.map((c) => t.stringLiteral(c))),
1409
+ ])
1410
+ : t.callExpression(t.memberExpression(t.identifier('Object'), t.identifier('freeze')), [
1411
+ t.objectExpression([
1412
+ t.objectProperty(t.identifier('x'), t.numericLiteral(entry.point.x)),
1413
+ t.objectProperty(t.identifier('y'), t.numericLiteral(entry.point.y)),
1414
+ ]),
1415
+ ]);
1416
+ decls.push(t.variableDeclaration('const', [t.variableDeclarator(t.identifier(name), init)]));
1417
+ }
1418
+ spliceAfterImports(ast, decls);
1419
+ }
1420
+ /**
1421
+ * Insert a block of declarations right after the last import in the
1422
+ * program body. Shared helper for atom-hoist and gradient-hoist.
1423
+ * @param ast File AST.
1424
+ * @param decls Declarations to splice in (already-built statements).
1425
+ */
1426
+ function spliceAfterImports(ast, decls) {
1427
+ if (decls.length === 0)
1428
+ return;
1429
+ const { body } = ast.program;
1430
+ let index = 0;
1431
+ while (index < body.length && t.isImportDeclaration(body[index]))
1432
+ index += 1;
1433
+ body.splice(index, 0, ...decls);
1434
+ }
1435
+ /**
1436
+ * Tokenize a classname literal — split on whitespace, drop empties.
1437
+ * Mirrors what Tailwind + the runtime tokenizer expect.
1438
+ * @param literal Raw classname text.
1439
+ * @returns Atom names in document order.
1440
+ */
1441
+ function tokenize(literal) {
1442
+ const out = [];
1443
+ for (const piece of literal.split(/\s+/)) {
1444
+ if (piece.length > 0)
1445
+ out.push(piece);
1446
+ }
1447
+ return out;
1448
+ }
1449
+
1450
+ export { transformAst };
1451
+ //# sourceMappingURL=transform-ast.mjs.map