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