@aussieljk/forkbook 0.0.0-stage → 0.0.1-2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (598) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +77 -2
  3. package/assets/addon-vitest/templates/vitest.config.4.template.ts +36 -0
  4. package/assets/browser/favicon-wrapper.svg +46 -0
  5. package/assets/browser/favicon.svg +1 -0
  6. package/assets/browser/nunito-sans-bold-italic.woff2 +0 -0
  7. package/assets/browser/nunito-sans-bold.woff2 +0 -0
  8. package/assets/browser/nunito-sans-italic.woff2 +0 -0
  9. package/assets/browser/nunito-sans-regular.woff2 +0 -0
  10. package/assets/builder-vite/iframe.html +99 -0
  11. package/assets/create/rendererAssets/.eslintrc.json +16 -0
  12. package/assets/create/rendererAssets/common/Configure.mdx +388 -0
  13. package/assets/create/rendererAssets/common/assets/accessibility.png +0 -0
  14. package/assets/create/rendererAssets/common/assets/accessibility.svg +1 -0
  15. package/assets/create/rendererAssets/common/assets/addon-library.png +0 -0
  16. package/assets/create/rendererAssets/common/assets/assets.png +0 -0
  17. package/assets/create/rendererAssets/common/assets/avif-test-image.avif +0 -0
  18. package/assets/create/rendererAssets/common/assets/context.png +0 -0
  19. package/assets/create/rendererAssets/common/assets/discord.svg +1 -0
  20. package/assets/create/rendererAssets/common/assets/docs.png +0 -0
  21. package/assets/create/rendererAssets/common/assets/figma-plugin.png +0 -0
  22. package/assets/create/rendererAssets/common/assets/github.svg +1 -0
  23. package/assets/create/rendererAssets/common/assets/share.png +0 -0
  24. package/assets/create/rendererAssets/common/assets/styling.png +0 -0
  25. package/assets/create/rendererAssets/common/assets/testing.png +0 -0
  26. package/assets/create/rendererAssets/common/assets/theming.png +0 -0
  27. package/assets/create/rendererAssets/common/assets/tutorials.svg +1 -0
  28. package/assets/create/rendererAssets/common/assets/youtube.svg +1 -0
  29. package/assets/create/rendererAssets/common/button.css +30 -0
  30. package/assets/create/rendererAssets/common/header.css +32 -0
  31. package/assets/create/rendererAssets/common/page.css +68 -0
  32. package/assets/create/templates/react-native/index.expo.js +20 -0
  33. package/assets/create/templates/react-native/index.js +25 -0
  34. package/assets/docs/addon-backgrounds.gif +0 -0
  35. package/assets/docs/addon-controls-args-annotated.png +0 -0
  36. package/assets/docs/addon-controls-args-background-color.png +0 -0
  37. package/assets/docs/addon-controls-args-background-string.png +0 -0
  38. package/assets/docs/addon-controls-args-docs.png +0 -0
  39. package/assets/docs/addon-controls-args-logging.png +0 -0
  40. package/assets/docs/addon-controls-args-no-annotation.png +0 -0
  41. package/assets/docs/addon-controls-args-reflow-slider.png +0 -0
  42. package/assets/docs/addon-controls-args-reflow.png +0 -0
  43. package/assets/docs/addon-controls-args-template.png +0 -0
  44. package/assets/docs/addon-controls-expanded.png +0 -0
  45. package/assets/docs/addon-controls-hero.gif +0 -0
  46. package/assets/docs/addon-controls-install.png +0 -0
  47. package/assets/docs/hero.gif +0 -0
  48. package/assets/docs/highlight.png +0 -0
  49. package/assets/docs/message-reference.png +0 -0
  50. package/assets/docs/viewport.png +0 -0
  51. package/assets/react-native/metro-env.d.ts +69 -0
  52. package/assets/server/addon.tsconfig.json +6 -0
  53. package/assets/server/base-preview-body.html +116 -0
  54. package/assets/server/base-preview-head.html +494 -0
  55. package/assets/server/openBrowser.applescript +94 -0
  56. package/assets/server/template.ejs +87 -0
  57. package/dist/.build-stamp +0 -0
  58. package/dist/_browser-chunks/Color-PCLE2J36.js +1025 -0
  59. package/dist/_browser-chunks/DocsRenderer-JXND3PVQ.js +10 -0
  60. package/dist/_browser-chunks/WithTooltip-XSQFTBMB.js +1619 -0
  61. package/dist/_browser-chunks/chunk-2JDQ35OA.js +247 -0
  62. package/dist/_browser-chunks/chunk-2JT76G3E.js +104 -0
  63. package/dist/_browser-chunks/chunk-2MEPHP35.js +17 -0
  64. package/dist/_browser-chunks/chunk-2SCZVUKW.js +24 -0
  65. package/dist/_browser-chunks/chunk-46Z7NGAS.js +41 -0
  66. package/dist/_browser-chunks/chunk-4ATQOMJB.js +30 -0
  67. package/dist/_browser-chunks/chunk-52CW7FF7.js +49 -0
  68. package/dist/_browser-chunks/chunk-5I7E4GMO.js +62 -0
  69. package/dist/_browser-chunks/chunk-5P4QA6MY.js +20 -0
  70. package/dist/_browser-chunks/chunk-5WMXI5GW.js +816 -0
  71. package/dist/_browser-chunks/chunk-66OCZ54D.js +2604 -0
  72. package/dist/_browser-chunks/chunk-6SXYJQST.js +253 -0
  73. package/dist/_browser-chunks/chunk-AYRF6EJB.js +36 -0
  74. package/dist/_browser-chunks/chunk-B4AUNNU4.js +156 -0
  75. package/dist/_browser-chunks/chunk-BCP2FFXF.js +369 -0
  76. package/dist/_browser-chunks/chunk-C3D4HEFY.js +3396 -0
  77. package/dist/_browser-chunks/chunk-CFAOWGL7.js +43 -0
  78. package/dist/_browser-chunks/chunk-CFWWCCZV.js +223 -0
  79. package/dist/_browser-chunks/chunk-CNED6RYH.js +18 -0
  80. package/dist/_browser-chunks/chunk-DRQKCCAG.js +136 -0
  81. package/dist/_browser-chunks/chunk-ECQ75MKQ.js +0 -0
  82. package/dist/_browser-chunks/chunk-EIYAKDGP.js +302 -0
  83. package/dist/_browser-chunks/chunk-ENKK74N4.js +12 -0
  84. package/dist/_browser-chunks/chunk-FENFYI4X.js +698 -0
  85. package/dist/_browser-chunks/chunk-FJGWSWL5.js +155 -0
  86. package/dist/_browser-chunks/chunk-FVSEPWWX.js +2810 -0
  87. package/dist/_browser-chunks/chunk-GNZY6LOW.js +10116 -0
  88. package/dist/_browser-chunks/chunk-IE4ULIOQ.js +14 -0
  89. package/dist/_browser-chunks/chunk-IMSF75WX.js +42 -0
  90. package/dist/_browser-chunks/chunk-IWQGIXJS.js +14 -0
  91. package/dist/_browser-chunks/chunk-JMC7AIKT.js +108 -0
  92. package/dist/_browser-chunks/chunk-JPUOQJUI.js +8 -0
  93. package/dist/_browser-chunks/chunk-JSBKXXXF.js +218 -0
  94. package/dist/_browser-chunks/chunk-JWSKPMPC.js +73 -0
  95. package/dist/_browser-chunks/chunk-JYVGARBG.js +2943 -0
  96. package/dist/_browser-chunks/chunk-KBK7GKBN.js +35 -0
  97. package/dist/_browser-chunks/chunk-KQ7CRO2B.js +108 -0
  98. package/dist/_browser-chunks/chunk-LAWXTSXK.js +18 -0
  99. package/dist/_browser-chunks/chunk-LE2LTDW3.js +14 -0
  100. package/dist/_browser-chunks/chunk-LEVSOOLQ.js +48 -0
  101. package/dist/_browser-chunks/chunk-LV5PIKV4.js +93 -0
  102. package/dist/_browser-chunks/chunk-MDOL7KML.js +56 -0
  103. package/dist/_browser-chunks/chunk-MFMDGWP6.js +34 -0
  104. package/dist/_browser-chunks/chunk-MLBOOZL4.js +67 -0
  105. package/dist/_browser-chunks/chunk-NQUD4B7H.js +91 -0
  106. package/dist/_browser-chunks/chunk-NULBREPZ.js +43 -0
  107. package/dist/_browser-chunks/chunk-NZMVUW5T.js +7 -0
  108. package/dist/_browser-chunks/chunk-OD6IBQCC.js +117 -0
  109. package/dist/_browser-chunks/chunk-ODVJ3XZJ.js +157 -0
  110. package/dist/_browser-chunks/chunk-OQWFVDIN.js +386 -0
  111. package/dist/_browser-chunks/chunk-OVH3USFB.js +20 -0
  112. package/dist/_browser-chunks/chunk-OZZPSYQR.js +14 -0
  113. package/dist/_browser-chunks/chunk-P6PK47TQ.js +1970 -0
  114. package/dist/_browser-chunks/chunk-PFRNG3UC.js +22 -0
  115. package/dist/_browser-chunks/chunk-PJSMZ27A.js +13 -0
  116. package/dist/_browser-chunks/chunk-QC4HFS6K.js +41 -0
  117. package/dist/_browser-chunks/chunk-QDXFODK4.js +274 -0
  118. package/dist/_browser-chunks/chunk-RBCHTR7C.js +28 -0
  119. package/dist/_browser-chunks/chunk-RMYQ3QN3.js +294 -0
  120. package/dist/_browser-chunks/chunk-RNTIV5CE.js +411 -0
  121. package/dist/_browser-chunks/chunk-RSPAQWVJ.js +80 -0
  122. package/dist/_browser-chunks/chunk-S6TK43XQ.js +836 -0
  123. package/dist/_browser-chunks/chunk-SC67XZST.js +18 -0
  124. package/dist/_browser-chunks/chunk-SFVA4SBT.js +683 -0
  125. package/dist/_browser-chunks/chunk-SZYFOQMT.js +25 -0
  126. package/dist/_browser-chunks/chunk-TBJCJXK4.js +18 -0
  127. package/dist/_browser-chunks/chunk-UMDO3KB7.js +205 -0
  128. package/dist/_browser-chunks/chunk-V2G23FV7.js +11 -0
  129. package/dist/_browser-chunks/chunk-V5M7Q4HT.js +88 -0
  130. package/dist/_browser-chunks/chunk-W5M6NPS3.js +198 -0
  131. package/dist/_browser-chunks/chunk-W7NE2JXW.js +84 -0
  132. package/dist/_browser-chunks/chunk-WGVAAM43.js +1110 -0
  133. package/dist/_browser-chunks/chunk-WHQRNHXD.js +8 -0
  134. package/dist/_browser-chunks/chunk-WOSOWBCA.js +12 -0
  135. package/dist/_browser-chunks/chunk-WZ7KR7SH.js +85 -0
  136. package/dist/_browser-chunks/chunk-YEKO6BHJ.js +20 -0
  137. package/dist/_browser-chunks/chunk-YI2IBIQS.js +7 -0
  138. package/dist/_browser-chunks/chunk-YTIT5NA5.js +1966 -0
  139. package/dist/_browser-chunks/chunk-ZEHRUHTA.js +6 -0
  140. package/dist/_browser-chunks/chunk-ZTQ5MEJ5.js +203 -0
  141. package/dist/_browser-chunks/matchers-YLBYSYAF.js +1263 -0
  142. package/dist/_browser-chunks/react-dom-client-4OHE3QDV.js +9 -0
  143. package/dist/_node-chunks/attached-runtime-I2G4WLJI.js +282 -0
  144. package/dist/_node-chunks/builder-manager-VVHYQXCH.js +1661 -0
  145. package/dist/_node-chunks/chunk-2BUPBPFB.js +82 -0
  146. package/dist/_node-chunks/chunk-2DSIDINN.js +884 -0
  147. package/dist/_node-chunks/chunk-2RU7BKEW.js +23 -0
  148. package/dist/_node-chunks/chunk-34EO2PUT.js +26 -0
  149. package/dist/_node-chunks/chunk-3BKIBF5S.js +3008 -0
  150. package/dist/_node-chunks/chunk-3SDUYDXH.js +98 -0
  151. package/dist/_node-chunks/chunk-3T4ZSNPH.js +662 -0
  152. package/dist/_node-chunks/chunk-3W7F2B7P.js +79 -0
  153. package/dist/_node-chunks/chunk-3Y6AAY5H.js +80 -0
  154. package/dist/_node-chunks/chunk-42UWAGPW.js +1193 -0
  155. package/dist/_node-chunks/chunk-4FEANXWU.js +1986 -0
  156. package/dist/_node-chunks/chunk-5DQFEZEA.js +40 -0
  157. package/dist/_node-chunks/chunk-6KEHV53S.js +1218 -0
  158. package/dist/_node-chunks/chunk-6LMWA44H.js +3837 -0
  159. package/dist/_node-chunks/chunk-6YKBRP72.js +20 -0
  160. package/dist/_node-chunks/chunk-7GUDZVRQ.js +110 -0
  161. package/dist/_node-chunks/chunk-B5J7Q7J4.js +21 -0
  162. package/dist/_node-chunks/chunk-BS2WMZMR.js +90 -0
  163. package/dist/_node-chunks/chunk-BSKFCWQD.js +47 -0
  164. package/dist/_node-chunks/chunk-BXVYT7SB.js +36 -0
  165. package/dist/_node-chunks/chunk-CCOTJ4FC.js +688 -0
  166. package/dist/_node-chunks/chunk-CQKMLL5J.js +33 -0
  167. package/dist/_node-chunks/chunk-CXRU72ET.js +63 -0
  168. package/dist/_node-chunks/chunk-DC7DKR5K.js +20 -0
  169. package/dist/_node-chunks/chunk-DHJFTB4K.js +25 -0
  170. package/dist/_node-chunks/chunk-DUR55DJJ.js +1094 -0
  171. package/dist/_node-chunks/chunk-E6YESGLX.js +7032 -0
  172. package/dist/_node-chunks/chunk-EHUNOMDD.js +52345 -0
  173. package/dist/_node-chunks/chunk-ET7PWEO7.js +298 -0
  174. package/dist/_node-chunks/chunk-EWOX7HPJ.js +20 -0
  175. package/dist/_node-chunks/chunk-F3ZFKBHY.js +844 -0
  176. package/dist/_node-chunks/chunk-FK7KGTV7.js +26 -0
  177. package/dist/_node-chunks/chunk-FPZB5OI7.js +35 -0
  178. package/dist/_node-chunks/chunk-FW2HQUBQ.js +25 -0
  179. package/dist/_node-chunks/chunk-FY6UXW6G.js +11 -0
  180. package/dist/_node-chunks/chunk-GEFQN7K3.js +499 -0
  181. package/dist/_node-chunks/chunk-GRBLDJCR.js +989 -0
  182. package/dist/_node-chunks/chunk-H32DYT6P.js +87 -0
  183. package/dist/_node-chunks/chunk-H4PPVMP5.js +23 -0
  184. package/dist/_node-chunks/chunk-HMP2G23X.js +25 -0
  185. package/dist/_node-chunks/chunk-ICPBH3E7.js +59 -0
  186. package/dist/_node-chunks/chunk-IDEL2J23.js +23 -0
  187. package/dist/_node-chunks/chunk-IK4FGZLR.js +223 -0
  188. package/dist/_node-chunks/chunk-JDXXX6LB.js +68 -0
  189. package/dist/_node-chunks/chunk-JGGFYIG5.js +5468 -0
  190. package/dist/_node-chunks/chunk-JPAZLYJ3.js +29 -0
  191. package/dist/_node-chunks/chunk-JZOO7GGC.js +48 -0
  192. package/dist/_node-chunks/chunk-KISMCCP5.js +4744 -0
  193. package/dist/_node-chunks/chunk-LCK4ZQKG.js +115 -0
  194. package/dist/_node-chunks/chunk-LO56I6E2.js +132 -0
  195. package/dist/_node-chunks/chunk-LXBD4UL4.js +104 -0
  196. package/dist/_node-chunks/chunk-MA24JW6C.js +7162 -0
  197. package/dist/_node-chunks/chunk-MK2KYAI6.js +5414 -0
  198. package/dist/_node-chunks/chunk-NDWKJ4CL.js +2102 -0
  199. package/dist/_node-chunks/chunk-NIBT7XDZ.js +168 -0
  200. package/dist/_node-chunks/chunk-NPO45IMH.js +33 -0
  201. package/dist/_node-chunks/chunk-OISX4AGQ.js +414 -0
  202. package/dist/_node-chunks/chunk-OUW6R7C3.js +26 -0
  203. package/dist/_node-chunks/chunk-OWNFOGTA.js +194 -0
  204. package/dist/_node-chunks/chunk-Q7QNUM5H.js +49 -0
  205. package/dist/_node-chunks/chunk-QEQLR22M.js +1877 -0
  206. package/dist/_node-chunks/chunk-RRN2V55B.js +45 -0
  207. package/dist/_node-chunks/chunk-RWFIFGO5.js +144 -0
  208. package/dist/_node-chunks/chunk-RXNJDRGO.js +209 -0
  209. package/dist/_node-chunks/chunk-RZMQ7S3L.js +92 -0
  210. package/dist/_node-chunks/chunk-SIEXZVCR.js +51 -0
  211. package/dist/_node-chunks/chunk-SLWQNBGO.js +2034 -0
  212. package/dist/_node-chunks/chunk-SVTBJ7Q3.js +35 -0
  213. package/dist/_node-chunks/chunk-SWO5CDYU.js +32 -0
  214. package/dist/_node-chunks/chunk-TD5PLLQG.js +121 -0
  215. package/dist/_node-chunks/chunk-TEQGGSP7.js +33 -0
  216. package/dist/_node-chunks/chunk-TFCEV2XX.js +155 -0
  217. package/dist/_node-chunks/chunk-TFEWM4E3.js +1073 -0
  218. package/dist/_node-chunks/chunk-TINO74G5.js +21 -0
  219. package/dist/_node-chunks/chunk-TNJIXE37.js +40 -0
  220. package/dist/_node-chunks/chunk-TWI4GVH7.js +19 -0
  221. package/dist/_node-chunks/chunk-U5W53R2J.js +1011 -0
  222. package/dist/_node-chunks/chunk-UBOGWBEA.js +148 -0
  223. package/dist/_node-chunks/chunk-UMUBKI6E.js +3787 -0
  224. package/dist/_node-chunks/chunk-UVINFLGY.js +56 -0
  225. package/dist/_node-chunks/chunk-V2DY426G.js +1133 -0
  226. package/dist/_node-chunks/chunk-VLOXOXXE.js +45 -0
  227. package/dist/_node-chunks/chunk-W4OMYLSP.js +1297 -0
  228. package/dist/_node-chunks/chunk-WAXVSN3O.js +18 -0
  229. package/dist/_node-chunks/chunk-WCULS5TP.js +3767 -0
  230. package/dist/_node-chunks/chunk-WNZ2UMFM.js +153 -0
  231. package/dist/_node-chunks/chunk-WZJF2OUH.js +74 -0
  232. package/dist/_node-chunks/chunk-XGIUVY52.js +611 -0
  233. package/dist/_node-chunks/chunk-XHL2LVBM.js +415 -0
  234. package/dist/_node-chunks/chunk-XI6B6P47.js +59 -0
  235. package/dist/_node-chunks/chunk-XLP2ZKXV.js +60 -0
  236. package/dist/_node-chunks/chunk-YCMRA6RX.js +95 -0
  237. package/dist/_node-chunks/chunk-YZFWBA5L.js +2700 -0
  238. package/dist/_node-chunks/chunk-ZMAMXQKP.js +4731 -0
  239. package/dist/_node-chunks/chunk-ZWBCQ4MJ.js +110 -0
  240. package/dist/_node-chunks/dist-VTSTZKUB.js +16 -0
  241. package/dist/_node-chunks/globby-OEMHPBFY.js +2884 -0
  242. package/dist/_node-chunks/jiti-NFX6UU74.js +3848 -0
  243. package/dist/_node-chunks/lib-MDVARD7W.js +366 -0
  244. package/dist/_node-chunks/local-runtime-NTKIN2QT.js +78 -0
  245. package/dist/_node-chunks/mdx-plugin-MWISDWDQ.js +5680 -0
  246. package/dist/_node-chunks/monorepo-LIRFMQXE.js +121 -0
  247. package/dist/_node-chunks/monorepo-optimized-tests-relaxed-limits-no-story-deletion-CPDW4XTW.js +121 -0
  248. package/dist/_node-chunks/optimized-tests-HDOLR3EY.js +22 -0
  249. package/dist/_node-chunks/pattern-copy-play-EKHIUAU2.js +807 -0
  250. package/dist/_node-chunks/postinstallAddon-GYGMWDL6.js +20 -0
  251. package/dist/_node-chunks/rehype-external-links-BUN3HUCO.js +121 -0
  252. package/dist/_node-chunks/rehype-slug-PLADX223.js +52 -0
  253. package/dist/_node-chunks/relaxed-limits-GBHW6KIQ.js +117 -0
  254. package/dist/_node-chunks/run-KDTIZNSY.js +103 -0
  255. package/dist/_node-chunks/run-NL66VTNR.js +4532 -0
  256. package/dist/_node-chunks/session-id-KIIVOQLR.js +23 -0
  257. package/dist/_node-chunks/setup-MGC7BQO6.js +278 -0
  258. package/dist/_node-chunks/vitest.config.4.template-JH2THZFG.js +54 -0
  259. package/dist/actions/decorator.d.ts +7 -0
  260. package/dist/actions/decorator.js +43 -0
  261. package/dist/actions/index.d.ts +67 -0
  262. package/dist/actions/index.js +28 -0
  263. package/dist/addon-a11y/index.d.ts +52 -0
  264. package/dist/addon-a11y/index.js +16 -0
  265. package/dist/addon-a11y/manager.js +1429 -0
  266. package/dist/addon-a11y/preset.js +18 -0
  267. package/dist/addon-a11y/preview.d.ts +17 -0
  268. package/dist/addon-a11y/preview.js +15 -0
  269. package/dist/addon-docs/blocks.d.ts +1061 -0
  270. package/dist/addon-docs/blocks.js +2461 -0
  271. package/dist/addon-docs/index.d.ts +236 -0
  272. package/dist/addon-docs/index.js +16 -0
  273. package/dist/addon-docs/manager.js +90 -0
  274. package/dist/addon-docs/mdx-react-shim.d.ts +1 -0
  275. package/dist/addon-docs/mdx-react-shim.js +2 -0
  276. package/dist/addon-docs/preset.js +378 -0
  277. package/dist/addon-docs/preview.d.ts +4 -0
  278. package/dist/addon-docs/preview.js +7 -0
  279. package/dist/addon-links/index.d.ts +22 -0
  280. package/dist/addon-links/index.js +20 -0
  281. package/dist/addon-links/manager.js +14 -0
  282. package/dist/addon-links/preview.d.ts +6 -0
  283. package/dist/addon-links/preview.js +9 -0
  284. package/dist/addon-links/react/index.d.ts +25 -0
  285. package/dist/addon-links/react/index.js +52 -0
  286. package/dist/addon-mcp/preset.js +1345 -0
  287. package/dist/addon-mcp/preview.js +29 -0
  288. package/dist/addon-mcp/tools/preview-stories/preview-stories-app-script.js +1153 -0
  289. package/dist/addon-ondevice-actions/index.d.ts +4 -0
  290. package/dist/addon-ondevice-actions/index.js +7 -0
  291. package/dist/addon-ondevice-actions/register.js +7 -0
  292. package/dist/addon-ondevice-controls/index.d.ts +6 -0
  293. package/dist/addon-ondevice-controls/index.js +14 -0
  294. package/dist/addon-ondevice-controls/register.js +10 -0
  295. package/dist/addon-pseudo-states/index.d.ts +35 -0
  296. package/dist/addon-pseudo-states/index.js +15 -0
  297. package/dist/addon-pseudo-states/manager.js +53 -0
  298. package/dist/addon-pseudo-states/preview.d.ts +9 -0
  299. package/dist/addon-pseudo-states/preview.js +10 -0
  300. package/dist/addon-themes/index.d.ts +80 -0
  301. package/dist/addon-themes/index.js +104 -0
  302. package/dist/addon-themes/manager.js +97 -0
  303. package/dist/addon-themes/postinstall.js +33 -0
  304. package/dist/addon-themes/preview.d.ts +6 -0
  305. package/dist/addon-themes/preview.js +8 -0
  306. package/dist/addon-vitest/constants.d.ts +132 -0
  307. package/dist/addon-vitest/constants.js +66 -0
  308. package/dist/addon-vitest/index.d.ts +4 -0
  309. package/dist/addon-vitest/index.js +8 -0
  310. package/dist/addon-vitest/manager.js +665 -0
  311. package/dist/addon-vitest/node/coverage-reporter.js +1284 -0
  312. package/dist/addon-vitest/node/vitest.js +674 -0
  313. package/dist/addon-vitest/postinstall.js +24 -0
  314. package/dist/addon-vitest/preset.js +943 -0
  315. package/dist/addon-vitest/vitest-plugin/global-setup.js +162 -0
  316. package/dist/addon-vitest/vitest-plugin/index.d.ts +56 -0
  317. package/dist/addon-vitest/vitest-plugin/index.js +463 -0
  318. package/dist/addon-vitest/vitest-plugin/setup-file-with-project-annotations.js +9 -0
  319. package/dist/addon-vitest/vitest-plugin/setup-file.browser.4.js +20 -0
  320. package/dist/addon-vitest/vitest-plugin/setup-file.js +50 -0
  321. package/dist/addon-vitest/vitest-plugin/test-utils.js +128 -0
  322. package/dist/babel/index.d.ts +2301 -0
  323. package/dist/babel/index.js +61 -0
  324. package/dist/backgrounds/index.d.ts +6 -0
  325. package/dist/backgrounds/index.js +15 -0
  326. package/dist/bin/core.js +1705 -0
  327. package/dist/bin/dispatcher.js +43 -0
  328. package/dist/bin/loader.js +115 -0
  329. package/dist/builder-vite/index.d.ts +50 -0
  330. package/dist/builder-vite/index.js +245 -0
  331. package/dist/builder-vite/preset.js +27 -0
  332. package/dist/channels/index.d.ts +2 -0
  333. package/dist/channels/index.js +352 -0
  334. package/dist/chunk-B2t1tGRh.d.ts +284 -0
  335. package/dist/chunk-BCoJQE-f.d.ts +602 -0
  336. package/dist/chunk-BGkgZp-H.d.ts +214 -0
  337. package/dist/chunk-BTVrWliM.d.ts +115 -0
  338. package/dist/chunk-BXLImeLy.d.ts +197 -0
  339. package/dist/chunk-BfBzpgct.d.ts +916 -0
  340. package/dist/chunk-Bpi2tz-6.d.ts +511 -0
  341. package/dist/chunk-BxWufQms.d.ts +142 -0
  342. package/dist/chunk-C-bavsOH.d.ts +34 -0
  343. package/dist/chunk-C2p5r3Vt.d.ts +13001 -0
  344. package/dist/chunk-C6PAgHLT.d.ts +12 -0
  345. package/dist/chunk-CMeX4WRe.d.ts +179 -0
  346. package/dist/chunk-Ct9xd6IM.d.ts +65 -0
  347. package/dist/chunk-CwQKNaYL.d.ts +15 -0
  348. package/dist/chunk-D7DwV41f.d.ts +3622 -0
  349. package/dist/chunk-DEVFdzxR.d.ts +253 -0
  350. package/dist/chunk-DaVb55-_.d.ts +124 -0
  351. package/dist/chunk-DgRNfmj_.d.ts +40 -0
  352. package/dist/chunk-DoIGKY33.d.ts +666 -0
  353. package/dist/chunk-Dr3R0DXk.d.ts +40 -0
  354. package/dist/chunk-DtHByo32.d.ts +55 -0
  355. package/dist/chunk-Dw1z1Pki.d.ts +933 -0
  356. package/dist/chunk-DzuY9DXg.d.ts +79 -0
  357. package/dist/chunk-FjDVzZTj.d.ts +62 -0
  358. package/dist/chunk-Kt1tW-D1.d.ts +59 -0
  359. package/dist/chunk-XP8oHzpE.d.ts +6 -0
  360. package/dist/chunk-gCX81nOr.d.ts +61 -0
  361. package/dist/chunk-pcFXCimE.d.ts +741 -0
  362. package/dist/cli/index.d.ts +1174 -0
  363. package/dist/cli/index.js +5613 -0
  364. package/dist/cli/skills/content/index.d.ts +72 -0
  365. package/dist/cli/skills/content/index.js +335 -0
  366. package/dist/cli/tools/sdk/child-host.d.ts +61 -0
  367. package/dist/cli/tools/sdk/child-host.js +131 -0
  368. package/dist/cli/tools/sdk/index.d.ts +137 -0
  369. package/dist/cli/tools/sdk/index.js +44 -0
  370. package/dist/cli-commands/bin/index.js +25 -0
  371. package/dist/client-logger/index.d.ts +31 -0
  372. package/dist/client-logger/index.js +63 -0
  373. package/dist/common/index.d.ts +1103 -0
  374. package/dist/common/index.js +364 -0
  375. package/dist/components/index.d.ts +1924 -0
  376. package/dist/components/index.js +13759 -0
  377. package/dist/core-events/index.d.ts +155 -0
  378. package/dist/core-events/index.js +136 -0
  379. package/dist/core-server/index.d.ts +2200 -0
  380. package/dist/core-server/index.js +4165 -0
  381. package/dist/core-server/presets/common-manager.css +170 -0
  382. package/dist/core-server/presets/common-manager.js +4168 -0
  383. package/dist/core-server/presets/common-override-preset.js +81 -0
  384. package/dist/core-server/presets/common-preset.js +2187 -0
  385. package/dist/create/bin/index.js +23 -0
  386. package/dist/create/index.js +25 -0
  387. package/dist/csf/csf-utils.d.ts +2 -0
  388. package/dist/csf/csf-utils.js +19 -0
  389. package/dist/csf/index.d.ts +7 -0
  390. package/dist/csf/index.js +2142 -0
  391. package/dist/csf-tools/index.d.ts +1157 -0
  392. package/dist/csf-tools/index.js +736 -0
  393. package/dist/docs-tools/index.d.ts +197 -0
  394. package/dist/docs-tools/index.js +61 -0
  395. package/dist/highlight/index.d.ts +10 -0
  396. package/dist/highlight/index.js +15 -0
  397. package/dist/instrumenter/index.d.ts +113 -0
  398. package/dist/instrumenter/index.js +2595 -0
  399. package/dist/manager/_manager-chunks/globals-runtime-8HkdnU2F.js +6144 -0
  400. package/dist/manager/_manager-chunks/globals-runtime-BIKBO23x.js +3389 -0
  401. package/dist/manager/_manager-chunks/globals-runtime-BdGkqNEt.js +45 -0
  402. package/dist/manager/_manager-chunks/globals-runtime-BmphMP6z.js +1190 -0
  403. package/dist/manager/_manager-chunks/globals-runtime-BvM-NY2g.js +13307 -0
  404. package/dist/manager/_manager-chunks/globals-runtime-C02fvgcd.js +9243 -0
  405. package/dist/manager/_manager-chunks/globals-runtime-DkAPXCvc.js +9766 -0
  406. package/dist/manager/_manager-chunks/globals-runtime-DpNYC-qi.js +5564 -0
  407. package/dist/manager/_manager-chunks/globals-runtime-DtcOnYHR.js +5357 -0
  408. package/dist/manager/_manager-chunks/globals-runtime-DwFqpqya.js +722 -0
  409. package/dist/manager/_manager-chunks/globals-runtime-FC201B7s.js +6837 -0
  410. package/dist/manager/_manager-chunks/globals-runtime-Rp_zjGnh.js +121 -0
  411. package/dist/manager/_manager-chunks/globals-runtime-ZHrQFa3-.js +10463 -0
  412. package/dist/manager/_manager-chunks/globals-runtime-eLPTIfX-.js +7759 -0
  413. package/dist/manager/_manager-chunks/globals-runtime-qKvCZHFY.js +4468 -0
  414. package/dist/manager/_manager-chunks/globals-runtime-sGpNlIJ1.js +5102 -0
  415. package/dist/manager/_manager-chunks/runtime-B1L9TH89.js +452 -0
  416. package/dist/manager/_manager-chunks/runtime-BK0zF7FN.js +22 -0
  417. package/dist/manager/_manager-chunks/runtime-BhkT2CXl.js +1408 -0
  418. package/dist/manager/_manager-chunks/runtime-Bly6WJLN.js +998 -0
  419. package/dist/manager/_manager-chunks/runtime-D0UOWx0U.js +979 -0
  420. package/dist/manager/_manager-chunks/runtime-D94Vq3oR.js +4014 -0
  421. package/dist/manager/_manager-chunks/runtime-DMig8mT7.js +77 -0
  422. package/dist/manager/_manager-chunks/runtime-EITvVbkG.js +46 -0
  423. package/dist/manager/_manager-chunks/runtime-cp5pazY2.js +8936 -0
  424. package/dist/manager/_manager-chunks/runtime-eDVAYF7N.js +6860 -0
  425. package/dist/manager/_manager-chunks/runtime-i-PDAHLR.js +2493 -0
  426. package/dist/manager/globals-runtime.js +2 -0
  427. package/dist/manager/globals.d.ts +23 -0
  428. package/dist/manager/globals.js +26 -0
  429. package/dist/manager/manager-stores.d.ts +2 -0
  430. package/dist/manager/manager-stores.js +19 -0
  431. package/dist/manager/runtime.js +2 -0
  432. package/dist/manager-api/index.d.ts +2 -0
  433. package/dist/manager-api/index.js +3257 -0
  434. package/dist/manager-errors.d.ts +89 -0
  435. package/dist/manager-errors.js +20 -0
  436. package/dist/mcp/index.d.ts +270 -0
  437. package/dist/mcp/index.js +305 -0
  438. package/dist/mocking-utils/index.d.ts +689 -0
  439. package/dist/mocking-utils/index.js +521 -0
  440. package/dist/mocking-utils/mocker-runtime.js +1254 -0
  441. package/dist/nextjs-vite/config/preview.js +3 -0
  442. package/dist/nextjs-vite/export-mocks/cache/index.d.ts +25 -0
  443. package/dist/nextjs-vite/export-mocks/cache/index.js +29 -0
  444. package/dist/nextjs-vite/export-mocks/headers/index.d.ts +37 -0
  445. package/dist/nextjs-vite/export-mocks/headers/index.js +54 -0
  446. package/dist/nextjs-vite/export-mocks/link/index.d.ts +9 -0
  447. package/dist/nextjs-vite/export-mocks/link/index.js +59 -0
  448. package/dist/nextjs-vite/export-mocks/navigation/index.d.ts +28 -0
  449. package/dist/nextjs-vite/export-mocks/navigation/index.js +58 -0
  450. package/dist/nextjs-vite/export-mocks/router/index.d.ts +34 -0
  451. package/dist/nextjs-vite/export-mocks/router/index.js +63 -0
  452. package/dist/nextjs-vite/index.d.ts +92 -0
  453. package/dist/nextjs-vite/index.js +58 -0
  454. package/dist/nextjs-vite/node/index.d.ts +6 -0
  455. package/dist/nextjs-vite/node/index.js +20 -0
  456. package/dist/nextjs-vite/preset.js +648 -0
  457. package/dist/nextjs-vite/preview.d.ts +20 -0
  458. package/dist/nextjs-vite/preview.js +11 -0
  459. package/dist/nextjs-vite/vite-plugin/index.d.ts +6 -0
  460. package/dist/nextjs-vite/vite-plugin/index.js +19 -0
  461. package/dist/nextjs-vite-plugin/index.d.ts +28 -0
  462. package/dist/nextjs-vite-plugin/index.js +923 -0
  463. package/dist/nextjs-vite-plugin/mocks/storybook.global.js +29 -0
  464. package/dist/nextjs-vite-plugin/plugins/next-image/alias/image-context.js +8 -0
  465. package/dist/nextjs-vite-plugin/plugins/next-image/alias/image-default-loader.js +23 -0
  466. package/dist/nextjs-vite-plugin/plugins/next-image/alias/next-image.js +28 -0
  467. package/dist/nextjs-vite-plugin/plugins/next-image/alias/next-legacy-image.js +17 -0
  468. package/dist/nextjs-vite-plugin/plugins/next-mocks/alias/cache/index.js +29 -0
  469. package/dist/nextjs-vite-plugin/plugins/next-mocks/alias/dynamic/index.js +40 -0
  470. package/dist/nextjs-vite-plugin/plugins/next-mocks/alias/headers/index.js +55 -0
  471. package/dist/nextjs-vite-plugin/plugins/next-mocks/alias/link/index.js +63 -0
  472. package/dist/nextjs-vite-plugin/plugins/next-mocks/alias/navigation/index.js +71 -0
  473. package/dist/nextjs-vite-plugin/plugins/next-mocks/alias/router/index.js +74 -0
  474. package/dist/nextjs-vite-plugin/plugins/next-mocks/alias/rsc/server-only.js +7 -0
  475. package/dist/nextjs-vite-plugin/plugins/next-mocks/alias/safe-stable-stringify/index.js +13 -0
  476. package/dist/nextjs-vite-plugin/plugins/next-mocks/compatibility/draft-mode.compat.js +7 -0
  477. package/dist/node-logger/index.d.ts +495 -0
  478. package/dist/node-logger/index.js +42 -0
  479. package/dist/oxc-parser/index.d.ts +99 -0
  480. package/dist/oxc-parser/index.js +275 -0
  481. package/dist/oxc-parser/worker.js +37 -0
  482. package/dist/preview/_chunks/runtime-BIzIdDbb.js +10263 -0
  483. package/dist/preview/_chunks/runtime-BTPtVY1p.js +1102 -0
  484. package/dist/preview/_chunks/runtime-BZSnICCg.js +8484 -0
  485. package/dist/preview/_chunks/runtime-BdGkqNEt.js +45 -0
  486. package/dist/preview/_chunks/runtime-BwSxqk3t.js +63 -0
  487. package/dist/preview/_chunks/runtime-CqHxptiK.js +6143 -0
  488. package/dist/preview/_chunks/runtime-CsV4HZPV.js +5064 -0
  489. package/dist/preview/_chunks/runtime-CxZK_Ln3.js +284 -0
  490. package/dist/preview/_chunks/runtime-DZToXfvO.js +9767 -0
  491. package/dist/preview/_chunks/runtime-DrTjJkPY.js +3872 -0
  492. package/dist/preview/_chunks/runtime-DuHdxMFA.js +387 -0
  493. package/dist/preview/_chunks/runtime-iXdo8CR8.js +3635 -0
  494. package/dist/preview/_chunks/runtime-q3wt0e_N.js +6838 -0
  495. package/dist/preview/globals.d.ts +16 -0
  496. package/dist/preview/globals.js +20 -0
  497. package/dist/preview/runtime.js +6 -0
  498. package/dist/preview-api/index.d.ts +4 -0
  499. package/dist/preview-api/index.js +147 -0
  500. package/dist/preview-errors.d.ts +186 -0
  501. package/dist/preview-errors.js +56 -0
  502. package/dist/react/docgen/docgen-worker.js +38 -0
  503. package/dist/react/entry-preview-argtypes.js +9 -0
  504. package/dist/react/entry-preview-docs.js +12 -0
  505. package/dist/react/entry-preview-rsc.js +11 -0
  506. package/dist/react/entry-preview.js +21 -0
  507. package/dist/react/index.d.ts +119 -0
  508. package/dist/react/index.js +26 -0
  509. package/dist/react/preset.js +301 -0
  510. package/dist/react/preview.d.ts +2 -0
  511. package/dist/react/preview.js +11 -0
  512. package/dist/react-native/bin/get-stories.js +34 -0
  513. package/dist/react-native/index.d.ts +160 -0
  514. package/dist/react-native/index.js +1547 -0
  515. package/dist/react-native/metro/node.d.ts +83 -0
  516. package/dist/react-native/metro/node.js +21 -0
  517. package/dist/react-native/metro/withStorybook.d.ts +2269 -0
  518. package/dist/react-native/metro/withStorybook.js +138 -0
  519. package/dist/react-native/preview.d.ts +6 -0
  520. package/dist/react-native/preview.js +20 -0
  521. package/dist/react-native/scripts/generate.d.ts +22 -0
  522. package/dist/react-native/scripts/generate.js +18 -0
  523. package/dist/react-native/stub.js +20 -0
  524. package/dist/react-native-theming/index.d.ts +175 -0
  525. package/dist/react-native-theming/index.js +2591 -0
  526. package/dist/react-native-ui/index.d.ts +130 -0
  527. package/dist/react-native-ui/index.js +1448 -0
  528. package/dist/react-native-ui-common/index.d.ts +230 -0
  529. package/dist/react-native-ui-common/index.js +514 -0
  530. package/dist/react-vite/index.d.ts +4 -0
  531. package/dist/react-vite/index.js +8 -0
  532. package/dist/react-vite/node/index.d.ts +6 -0
  533. package/dist/react-vite/node/index.js +20 -0
  534. package/dist/react-vite/preset.d.ts +6 -0
  535. package/dist/react-vite/preset.js +21 -0
  536. package/dist/router/index.d.ts +141 -0
  537. package/dist/router/index.js +1217 -0
  538. package/dist/server-errors.d.ts +2 -0
  539. package/dist/server-errors.js +149 -0
  540. package/dist/shared/open-service/index.d.ts +3 -0
  541. package/dist/shared/open-service/index.js +115 -0
  542. package/dist/shared/open-service/services/docgen/worker/docgen-worker.js +75 -0
  543. package/dist/shared/open-service/toolsets/docs/public.d.ts +1296 -0
  544. package/dist/shared/open-service/toolsets/docs/public.js +991 -0
  545. package/dist/telemetry/index.d.ts +314 -0
  546. package/dist/telemetry/index.js +103 -0
  547. package/dist/test/index.d.ts +158 -0
  548. package/dist/test/index.js +19421 -0
  549. package/dist/theming/create.d.ts +15 -0
  550. package/dist/theming/create.js +11 -0
  551. package/dist/theming/index.d.ts +54 -0
  552. package/dist/theming/index.js +511 -0
  553. package/dist/types/index.d.ts +2 -0
  554. package/dist/types/index.js +48 -0
  555. package/dist/viewport/index.d.ts +275 -0
  556. package/dist/viewport/index.js +21 -0
  557. package/package.json +1054 -4
  558. package/template/nextjs-vite/cli/.eslintrc.json +6 -0
  559. package/template/nextjs-vite/cli/js/Button.jsx +42 -0
  560. package/template/nextjs-vite/cli/js/Button.stories.js +49 -0
  561. package/template/nextjs-vite/cli/js/Configure.mdx +470 -0
  562. package/template/nextjs-vite/cli/js/Header.jsx +58 -0
  563. package/template/nextjs-vite/cli/js/Header.stories.js +30 -0
  564. package/template/nextjs-vite/cli/js/Page.jsx +68 -0
  565. package/template/nextjs-vite/cli/js/Page.stories.js +28 -0
  566. package/template/nextjs-vite/cli/ts/Button.stories.ts +54 -0
  567. package/template/nextjs-vite/cli/ts/Button.tsx +39 -0
  568. package/template/nextjs-vite/cli/ts/Configure.mdx +446 -0
  569. package/template/nextjs-vite/cli/ts/Header.stories.ts +34 -0
  570. package/template/nextjs-vite/cli/ts/Header.tsx +54 -0
  571. package/template/nextjs-vite/cli/ts/Page.stories.ts +33 -0
  572. package/template/nextjs-vite/cli/ts/Page.tsx +73 -0
  573. package/template/react/cli/.eslintrc.json +5 -0
  574. package/template/react/cli/js/Button.jsx +39 -0
  575. package/template/react/cli/js/Button.stories.js +49 -0
  576. package/template/react/cli/js/Header.jsx +56 -0
  577. package/template/react/cli/js/Header.stories.js +29 -0
  578. package/template/react/cli/js/Page.jsx +69 -0
  579. package/template/react/cli/js/Page.stories.js +28 -0
  580. package/template/react/cli/ts/Button.stories.ts +54 -0
  581. package/template/react/cli/ts/Button.tsx +37 -0
  582. package/template/react/cli/ts/Header.stories.ts +34 -0
  583. package/template/react/cli/ts/Header.tsx +56 -0
  584. package/template/react/cli/ts/Page.stories.ts +33 -0
  585. package/template/react/cli/ts/Page.tsx +73 -0
  586. package/template/react-vite/cli/.eslintrc.json +5 -0
  587. package/template/react-vite/cli/js/Button.jsx +39 -0
  588. package/template/react-vite/cli/js/Button.stories.js +49 -0
  589. package/template/react-vite/cli/js/Header.jsx +56 -0
  590. package/template/react-vite/cli/js/Header.stories.js +29 -0
  591. package/template/react-vite/cli/js/Page.jsx +69 -0
  592. package/template/react-vite/cli/js/Page.stories.js +28 -0
  593. package/template/react-vite/cli/ts/Button.stories.ts +54 -0
  594. package/template/react-vite/cli/ts/Button.tsx +37 -0
  595. package/template/react-vite/cli/ts/Header.stories.ts +34 -0
  596. package/template/react-vite/cli/ts/Header.tsx +56 -0
  597. package/template/react-vite/cli/ts/Page.stories.ts +33 -0
  598. package/template/react-vite/cli/ts/Page.tsx +73 -0
@@ -0,0 +1,3396 @@
1
+ import {
2
+ invariant
3
+ } from "./chunk-IWQGIXJS.js";
4
+ import {
5
+ require_ansi_to_html,
6
+ resolveViewport,
7
+ toResolvedViewportDimensions
8
+ } from "./chunk-FENFYI4X.js";
9
+ import {
10
+ isTestEnvironment,
11
+ pauseAnimations,
12
+ waitForAnimations
13
+ } from "./chunk-WZ7KR7SH.js";
14
+ import {
15
+ Tag,
16
+ mockChannel
17
+ } from "./chunk-CFAOWGL7.js";
18
+ import {
19
+ createBrowserStaticLoader,
20
+ getService,
21
+ registerService
22
+ } from "./chunk-YTIT5NA5.js";
23
+ import {
24
+ parse,
25
+ stringify
26
+ } from "./chunk-SFVA4SBT.js";
27
+ import {
28
+ require_memoizerific
29
+ } from "./chunk-DRQKCCAG.js";
30
+ import {
31
+ SNIPPET_RENDERED
32
+ } from "./chunk-66OCZ54D.js";
33
+ import {
34
+ combineParameters,
35
+ inferArgTypes,
36
+ inferControls
37
+ } from "./chunk-ODVJ3XZJ.js";
38
+ import {
39
+ mapValues
40
+ } from "./chunk-2JDQ35OA.js";
41
+ import {
42
+ isEqual
43
+ } from "./chunk-B4AUNNU4.js";
44
+ import {
45
+ isPlainObject
46
+ } from "./chunk-JWSKPMPC.js";
47
+ import {
48
+ MINIMAL_VIEWPORTS,
49
+ PARAM_KEY
50
+ } from "./chunk-QDXFODK4.js";
51
+ import {
52
+ __toESM
53
+ } from "./chunk-IMSF75WX.js";
54
+
55
+ // src/preview-api/modules/addons/main.ts
56
+ import {
57
+ getChannel as readInstalledChannel,
58
+ setChannel as installStorybookChannel
59
+ } from "@aussieljk/forkbook/internal/channels";
60
+ var AddonStore = class {
61
+ constructor() {
62
+ this.getChannel = () => {
63
+ if (this.channel)
64
+ return this.channel;
65
+ let installed = readInstalledChannel();
66
+ return installed ? (this.channel = installed, this.resolve(), this.channel) : mockChannel();
67
+ };
68
+ this.ready = () => this.promise;
69
+ this.hasChannel = () => !!this.channel || !!readInstalledChannel();
70
+ this.setChannel = (channel) => {
71
+ this.channel = channel, installStorybookChannel(channel), this.resolve();
72
+ };
73
+ this.promise = new Promise((res) => {
74
+ this.resolve = () => res(this.getChannel());
75
+ });
76
+ }
77
+ }, KEY = "__STORYBOOK_ADDONS_PREVIEW";
78
+ function getAddonsStore() {
79
+ return globalThis[KEY] || (globalThis[KEY] = new AddonStore()), globalThis[KEY];
80
+ }
81
+ var addons = getAddonsStore();
82
+
83
+ // src/preview-api/modules/addons/hooks.ts
84
+ import { logger } from "@aussieljk/forkbook/internal/client-logger";
85
+ import {
86
+ FORCE_RE_RENDER,
87
+ RESET_STORY_ARGS,
88
+ STORY_RENDERED,
89
+ UPDATE_GLOBALS,
90
+ UPDATE_STORY_ARGS
91
+ } from "@aussieljk/forkbook/internal/core-events";
92
+ import { global } from "@storybook/global";
93
+ var HooksContext = class {
94
+ constructor() {
95
+ this.hookListsMap = void 0;
96
+ this.mountedDecorators = void 0;
97
+ this.prevMountedDecorators = void 0;
98
+ this.currentHooks = void 0;
99
+ this.nextHookIndex = void 0;
100
+ this.currentPhase = void 0;
101
+ this.currentEffects = void 0;
102
+ this.prevEffects = void 0;
103
+ this.currentDecoratorName = void 0;
104
+ this.hasUpdates = void 0;
105
+ this.currentContext = void 0;
106
+ this.renderListener = (storyId) => {
107
+ storyId === this.currentContext?.id && (this.triggerEffects(), this.currentContext = null, this.removeRenderListeners());
108
+ };
109
+ this.init();
110
+ }
111
+ init() {
112
+ this.hookListsMap = /* @__PURE__ */ new WeakMap(), this.mountedDecorators = /* @__PURE__ */ new Set(), this.prevMountedDecorators = /* @__PURE__ */ new Set(), this.currentHooks = [], this.nextHookIndex = 0, this.currentPhase = "NONE", this.currentEffects = [], this.prevEffects = [], this.currentDecoratorName = null, this.hasUpdates = !1, this.currentContext = null;
113
+ }
114
+ clean() {
115
+ this.prevEffects.forEach((effect) => {
116
+ effect.destroy && effect.destroy();
117
+ }), this.init(), this.removeRenderListeners();
118
+ }
119
+ getNextHook() {
120
+ let hook = this.currentHooks[this.nextHookIndex];
121
+ return this.nextHookIndex += 1, hook;
122
+ }
123
+ triggerEffects() {
124
+ this.prevEffects.forEach((effect) => {
125
+ !this.currentEffects.includes(effect) && effect.destroy && effect.destroy();
126
+ }), this.currentEffects.forEach((effect) => {
127
+ this.prevEffects.includes(effect) || (effect.destroy = effect.create());
128
+ }), this.prevEffects = this.currentEffects, this.currentEffects = [];
129
+ }
130
+ addRenderListeners() {
131
+ this.removeRenderListeners(), addons.getChannel().on(STORY_RENDERED, this.renderListener);
132
+ }
133
+ removeRenderListeners() {
134
+ addons.getChannel().removeListener(STORY_RENDERED, this.renderListener);
135
+ }
136
+ };
137
+ function hookify(fn) {
138
+ let hookified = (...args) => {
139
+ let { hooks } = typeof args[0] == "function" ? args[1] : args[0], prevPhase = hooks.currentPhase, prevHooks = hooks.currentHooks, prevNextHookIndex = hooks.nextHookIndex, prevDecoratorName = hooks.currentDecoratorName;
140
+ hooks.currentDecoratorName = fn.name, hooks.prevMountedDecorators.has(fn) ? (hooks.currentPhase = "UPDATE", hooks.currentHooks = hooks.hookListsMap.get(fn) || []) : (hooks.currentPhase = "MOUNT", hooks.currentHooks = [], hooks.hookListsMap.set(fn, hooks.currentHooks), hooks.prevMountedDecorators.add(fn)), hooks.nextHookIndex = 0;
141
+ let prevContext = global.FORKBOOK_HOOKS_CONTEXT;
142
+ global.FORKBOOK_HOOKS_CONTEXT = hooks;
143
+ let result = fn(...args);
144
+ if (global.FORKBOOK_HOOKS_CONTEXT = prevContext, hooks.currentPhase === "UPDATE" && hooks.getNextHook() != null)
145
+ throw new Error(
146
+ "Rendered fewer hooks than expected. This may be caused by an accidental early return statement."
147
+ );
148
+ return hooks.currentPhase = prevPhase, hooks.currentHooks = prevHooks, hooks.nextHookIndex = prevNextHookIndex, hooks.currentDecoratorName = prevDecoratorName, result;
149
+ };
150
+ return hookified.originalFn = fn, hookified;
151
+ }
152
+ var numberOfRenders = 0, RENDER_LIMIT = 25, applyHooks = (applyDecorators) => (storyFn, decorators) => {
153
+ let decorated = applyDecorators(
154
+ hookify(storyFn),
155
+ decorators.map((decorator) => hookify(decorator))
156
+ );
157
+ return (context) => {
158
+ let { hooks } = context;
159
+ hooks.prevMountedDecorators ??= /* @__PURE__ */ new Set(), hooks.mountedDecorators = /* @__PURE__ */ new Set([storyFn, ...decorators]), hooks.currentContext = context, hooks.hasUpdates = !1;
160
+ let result = decorated(context);
161
+ for (numberOfRenders = 1; hooks.hasUpdates; )
162
+ if (hooks.hasUpdates = !1, hooks.currentEffects = [], result = decorated(context), numberOfRenders += 1, numberOfRenders > RENDER_LIMIT)
163
+ throw new Error(
164
+ "Too many re-renders. Forkbook limits the number of renders to prevent an infinite loop."
165
+ );
166
+ return hooks.addRenderListeners(), result;
167
+ };
168
+ }, areDepsEqual = (deps, nextDeps) => deps.length === nextDeps.length && deps.every((dep, i) => dep === nextDeps[i]), invalidHooksError = () => new Error(
169
+ `Forkbook preview hooks can only be called inside decorators and story functions.
170
+
171
+ When combining Forkbook hooks (e.g. useArgs) with framework hooks (e.g. React's useState, useEffect, useRef) in the same render function, use Forkbook's equivalents from '@aussieljk/forkbook/preview-api' instead: useState, useEffect, useRef, useMemo, useCallback, useReducer.`
172
+ );
173
+ function getHooksContextOrNull() {
174
+ return global.FORKBOOK_HOOKS_CONTEXT || null;
175
+ }
176
+ function getHooksContextOrThrow() {
177
+ let hooks = getHooksContextOrNull();
178
+ if (hooks == null)
179
+ throw invalidHooksError();
180
+ return hooks;
181
+ }
182
+ function useHook(name, callback, deps) {
183
+ let hooks = getHooksContextOrThrow();
184
+ if (hooks.currentPhase === "MOUNT") {
185
+ deps != null && !Array.isArray(deps) && logger.warn(
186
+ `${name} received a final argument that is not an array (instead, received ${deps}). When specified, the final argument must be an array.`
187
+ );
188
+ let hook = { name, deps };
189
+ return hooks.currentHooks.push(hook), callback(hook), hook;
190
+ }
191
+ if (hooks.currentPhase === "UPDATE") {
192
+ let hook = hooks.getNextHook();
193
+ if (hook == null)
194
+ throw new Error("Rendered more hooks than during the previous render.");
195
+ return hook.name !== name && logger.warn(
196
+ `Forkbook has detected a change in the order of Hooks${hooks.currentDecoratorName ? ` called by ${hooks.currentDecoratorName}` : ""}. This will lead to bugs and errors if not fixed.`
197
+ ), deps != null && hook.deps == null && logger.warn(
198
+ `${name} received a final argument during this render, but not during the previous render. Even though the final argument is optional, its type cannot change between renders.`
199
+ ), deps != null && hook.deps != null && deps.length !== hook.deps.length && logger.warn(`The final argument passed to ${name} changed size between renders. The order and size of this array must remain constant.
200
+ Previous: ${hook.deps}
201
+ Incoming: ${deps}`), (deps == null || hook.deps == null || !areDepsEqual(deps, hook.deps)) && (callback(hook), hook.deps = deps), hook;
202
+ }
203
+ throw invalidHooksError();
204
+ }
205
+ function useMemoLike(name, nextCreate, deps) {
206
+ let { memoizedState } = useHook(
207
+ name,
208
+ (hook) => {
209
+ hook.memoizedState = nextCreate();
210
+ },
211
+ deps
212
+ );
213
+ return memoizedState;
214
+ }
215
+ function useMemo(nextCreate, deps) {
216
+ return useMemoLike("useMemo", nextCreate, deps);
217
+ }
218
+ function useCallback(callback, deps) {
219
+ return useMemoLike("useCallback", () => callback, deps);
220
+ }
221
+ function useRefLike(name, initialValue) {
222
+ return useMemoLike(name, () => ({ current: initialValue }), []);
223
+ }
224
+ function useRef(initialValue) {
225
+ return useRefLike("useRef", initialValue);
226
+ }
227
+ function triggerUpdate() {
228
+ let hooks = getHooksContextOrNull();
229
+ if (hooks != null && hooks.currentPhase !== "NONE")
230
+ hooks.hasUpdates = !0;
231
+ else
232
+ try {
233
+ addons.getChannel().emit(FORCE_RE_RENDER);
234
+ } catch {
235
+ logger.warn("State updates of Forkbook preview hooks work only in browser");
236
+ }
237
+ }
238
+ function useStateLike(name, initialState) {
239
+ let stateRef = useRefLike(
240
+ name,
241
+ // @ts-expect-error S type should never be function, but there's no way to tell that to TypeScript
242
+ typeof initialState == "function" ? initialState() : initialState
243
+ ), setState = (update) => {
244
+ stateRef.current = typeof update == "function" ? update(stateRef.current) : update, triggerUpdate();
245
+ };
246
+ return [stateRef.current, setState];
247
+ }
248
+ function useState(initialState) {
249
+ return useStateLike("useState", initialState);
250
+ }
251
+ function useReducer(reducer, initialArg, init) {
252
+ let initialState = init != null ? () => init(initialArg) : initialArg, [state, setState] = useStateLike("useReducer", initialState);
253
+ return [state, (action) => setState((prevState) => reducer(prevState, action))];
254
+ }
255
+ function useEffect(create, deps) {
256
+ let hooks = getHooksContextOrThrow(), effect = useMemoLike("useEffect", () => ({ create }), deps);
257
+ hooks.currentEffects.includes(effect) || hooks.currentEffects.push(effect);
258
+ }
259
+ function useChannel(eventMap, deps = []) {
260
+ let channel = addons.getChannel();
261
+ return useEffect(() => (Object.entries(eventMap).forEach(([type, listener]) => channel.on(type, listener)), () => {
262
+ Object.entries(eventMap).forEach(
263
+ ([type, listener]) => channel.removeListener(type, listener)
264
+ );
265
+ }), [...Object.keys(eventMap), ...deps]), useCallback(channel.emit.bind(channel), [channel]);
266
+ }
267
+ function useStoryContext() {
268
+ let { currentContext } = getHooksContextOrThrow();
269
+ if (currentContext == null)
270
+ throw invalidHooksError();
271
+ return currentContext;
272
+ }
273
+ function useParameter(parameterKey, defaultValue) {
274
+ let { parameters } = useStoryContext();
275
+ if (parameterKey)
276
+ return parameters[parameterKey] ?? defaultValue;
277
+ }
278
+ function useArgs() {
279
+ let channel = addons.getChannel(), { id: storyId, args } = useStoryContext(), updateArgs = useCallback(
280
+ (updatedArgs) => channel.emit(UPDATE_STORY_ARGS, { storyId, updatedArgs }),
281
+ [channel, storyId]
282
+ ), resetArgs = useCallback(
283
+ (argNames) => channel.emit(RESET_STORY_ARGS, { storyId, argNames }),
284
+ [channel, storyId]
285
+ );
286
+ return [args, updateArgs, resetArgs];
287
+ }
288
+ function useGlobals() {
289
+ let channel = addons.getChannel(), { globals } = useStoryContext(), updateGlobals = useCallback(
290
+ (newGlobals) => channel.emit(UPDATE_GLOBALS, { globals: newGlobals }),
291
+ [channel]
292
+ );
293
+ return [globals, updateGlobals];
294
+ }
295
+
296
+ // src/preview-api/modules/addons/make-decorator.ts
297
+ var makeDecorator = ({
298
+ name,
299
+ parameterName,
300
+ wrapper,
301
+ skipIfNoParametersOrOptions = !1
302
+ }) => {
303
+ let decorator = (options) => (storyFn, context) => {
304
+ let parameters = context.parameters && context.parameters[parameterName];
305
+ return parameters && parameters.disable || skipIfNoParametersOrOptions && !options && !parameters ? storyFn(context) : wrapper(storyFn, context, {
306
+ options,
307
+ parameters
308
+ });
309
+ };
310
+ return (...args) => typeof args[0] == "function" ? decorator()(...args) : (...innerArgs) => {
311
+ if (innerArgs.length > 1)
312
+ return args.length > 1 ? decorator(args)(...innerArgs) : decorator(...args)(...innerArgs);
313
+ throw new Error(
314
+ `Passing stories directly into ${name}() is not allowed,
315
+ instead use addDecorator(${name}) and pass options with the '${parameterName}' parameter`
316
+ );
317
+ };
318
+ };
319
+
320
+ // src/preview-api/modules/store/StoryStore.ts
321
+ import {
322
+ CalledExtractOnStoreError,
323
+ MissingStoryFromCsfFileError
324
+ } from "@aussieljk/forkbook/internal/preview-errors";
325
+ var import_memoizerific2 = __toESM(require_memoizerific(), 1);
326
+
327
+ // src/preview-api/modules/store/ArgsStore.ts
328
+ import { global as global2 } from "@storybook/global";
329
+
330
+ // src/preview-api/modules/store/args.ts
331
+ import { once } from "@aussieljk/forkbook/internal/client-logger";
332
+ import { dedent } from "ts-dedent";
333
+ var INCOMPATIBLE = /* @__PURE__ */ Symbol("incompatible"), map = (arg, argType) => {
334
+ let type = argType.type;
335
+ if (arg == null || !type || argType.mapping)
336
+ return arg;
337
+ switch (type.name) {
338
+ case "string":
339
+ return String(arg);
340
+ case "enum":
341
+ return arg;
342
+ case "number":
343
+ return Number(arg);
344
+ case "boolean":
345
+ return String(arg) === "true";
346
+ case "array":
347
+ return !type.value || !Array.isArray(arg) ? INCOMPATIBLE : arg.reduce((acc, item, index) => {
348
+ let mapped = map(item, { type: type.value });
349
+ return mapped !== INCOMPATIBLE && (acc[index] = mapped), acc;
350
+ }, new Array(arg.length));
351
+ case "object":
352
+ return typeof arg == "string" || typeof arg == "number" ? arg : !type.value || typeof arg != "object" ? INCOMPATIBLE : Object.entries(arg).reduce((acc, [key, val]) => {
353
+ let mapped = map(val, { type: type.value[key] });
354
+ return mapped === INCOMPATIBLE ? acc : Object.assign(acc, { [key]: mapped });
355
+ }, {});
356
+ case "other":
357
+ return typeof arg == "string" || typeof arg == "number" || typeof arg == "boolean" ? arg : INCOMPATIBLE;
358
+ default:
359
+ return INCOMPATIBLE;
360
+ }
361
+ }, mapArgsToTypes = (args, argTypes) => Object.entries(args).reduce((acc, [key, value]) => {
362
+ if (!argTypes[key])
363
+ return acc;
364
+ let mapped = map(value, argTypes[key]);
365
+ return mapped === INCOMPATIBLE ? acc : Object.assign(acc, { [key]: mapped });
366
+ }, {}), combineArgs = (value, update) => Array.isArray(value) && Array.isArray(update) ? update.reduce(
367
+ (acc, upd, index) => (acc[index] = combineArgs(value[index], update[index]), acc),
368
+ [...value]
369
+ ).filter((v) => v !== void 0) : !isPlainObject(value) || !isPlainObject(update) ? update : Object.keys({ ...value, ...update }).reduce((acc, key) => {
370
+ if (key in update) {
371
+ let combined = combineArgs(value[key], update[key]);
372
+ combined !== void 0 && (acc[key] = combined);
373
+ } else
374
+ acc[key] = value[key];
375
+ return acc;
376
+ }, {}), validateOptions = (args, argTypes) => Object.entries(argTypes).reduce((acc, [key, { options }]) => {
377
+ function allowArg() {
378
+ return key in args && (acc[key] = args[key]), acc;
379
+ }
380
+ if (!options)
381
+ return allowArg();
382
+ if (!Array.isArray(options))
383
+ return once.error(dedent`
384
+ Invalid argType: '${key}.options' should be an array.
385
+
386
+ More info: https://storybook.js.org/docs/api/arg-types?ref=error
387
+ `), allowArg();
388
+ if (options.some((opt) => opt && ["object", "function"].includes(typeof opt)))
389
+ return once.error(dedent`
390
+ Invalid argType: '${key}.options' should only contain primitives. Use a 'mapping' for complex values.
391
+
392
+ More info: https://storybook.js.org/docs/writing-stories/args?ref=error#mapping-to-complex-arg-values
393
+ `), allowArg();
394
+ let isArray = Array.isArray(args[key]), invalidIndex = isArray && args[key].findIndex((val) => !options.includes(val)), isValidArray = isArray && invalidIndex === -1;
395
+ if (args[key] === void 0 || options.includes(args[key]) || isValidArray)
396
+ return allowArg();
397
+ let field = isArray ? `${key}[${invalidIndex}]` : key, supportedOptions = options.map((opt) => typeof opt == "string" ? `'${opt}'` : String(opt)).join(", ");
398
+ return once.warn(`Received illegal value for '${field}'. Supported options: ${supportedOptions}`), acc;
399
+ }, {}), DEEPLY_EQUAL = /* @__PURE__ */ Symbol("Deeply equal"), deepDiff = (value, update) => {
400
+ if (typeof value != typeof update)
401
+ return update;
402
+ if (isEqual(value, update))
403
+ return DEEPLY_EQUAL;
404
+ if (Array.isArray(value) && Array.isArray(update)) {
405
+ let res = update.reduce((acc, upd, index) => {
406
+ let diff = deepDiff(value[index], upd);
407
+ return diff !== DEEPLY_EQUAL && (acc[index] = diff), acc;
408
+ }, new Array(update.length));
409
+ return update.length >= value.length ? res : res.concat(new Array(value.length - update.length).fill(void 0));
410
+ }
411
+ return isPlainObject(value) && isPlainObject(update) ? Object.keys({ ...value, ...update }).reduce((acc, key) => {
412
+ let diff = deepDiff(value?.[key], update?.[key]);
413
+ return diff === DEEPLY_EQUAL ? acc : Object.assign(acc, { [key]: diff });
414
+ }, {}) : update;
415
+ }, UNTARGETED = "UNTARGETED";
416
+ function groupArgsByTarget({
417
+ args,
418
+ argTypes
419
+ }) {
420
+ let groupedArgs = {};
421
+ return Object.entries(args).forEach(([name, value]) => {
422
+ let { target = UNTARGETED } = argTypes[name] || {};
423
+ groupedArgs[target] = groupedArgs[target] || {}, groupedArgs[target][name] = value;
424
+ }), groupedArgs;
425
+ }
426
+
427
+ // src/preview-api/modules/store/ArgsStore.ts
428
+ function deleteUndefined(obj) {
429
+ return Object.keys(obj).forEach((key) => obj[key] === void 0 && delete obj[key]), obj;
430
+ }
431
+ var argTypesForValidation = (story) => global2.FEATURES?.docgenServer ? inferArgTypes({
432
+ id: story.id,
433
+ argTypes: story.argTypes,
434
+ initialArgs: story.initialArgs
435
+ }) : story.argTypes, ArgsStore = class {
436
+ constructor() {
437
+ this.initialArgsByStoryId = {};
438
+ this.argsByStoryId = {};
439
+ }
440
+ get(storyId) {
441
+ if (!(storyId in this.argsByStoryId))
442
+ throw new Error(`No args known for ${storyId} -- has it been rendered yet?`);
443
+ return this.argsByStoryId[storyId];
444
+ }
445
+ setInitial(story) {
446
+ if (!this.initialArgsByStoryId[story.id])
447
+ this.initialArgsByStoryId[story.id] = story.initialArgs, this.argsByStoryId[story.id] = story.initialArgs;
448
+ else if (this.initialArgsByStoryId[story.id] !== story.initialArgs) {
449
+ let delta = deepDiff(this.initialArgsByStoryId[story.id], this.argsByStoryId[story.id]);
450
+ this.initialArgsByStoryId[story.id] = story.initialArgs, this.argsByStoryId[story.id] = story.initialArgs, delta !== DEEPLY_EQUAL && this.updateFromDelta(story, delta);
451
+ }
452
+ }
453
+ updateFromDelta(story, delta) {
454
+ let validatedDelta = validateOptions(delta, argTypesForValidation(story));
455
+ this.argsByStoryId[story.id] = combineArgs(this.argsByStoryId[story.id], validatedDelta);
456
+ }
457
+ updateFromPersisted(story, persisted) {
458
+ let mappedPersisted = mapArgsToTypes(persisted, argTypesForValidation(story));
459
+ return this.updateFromDelta(story, mappedPersisted);
460
+ }
461
+ update(storyId, argsUpdate) {
462
+ if (!(storyId in this.argsByStoryId))
463
+ throw new Error(`No args known for ${storyId} -- has it been rendered yet?`);
464
+ this.argsByStoryId[storyId] = deleteUndefined({
465
+ ...this.argsByStoryId[storyId],
466
+ ...argsUpdate
467
+ });
468
+ }
469
+ };
470
+
471
+ // src/preview-api/modules/store/GlobalsStore.ts
472
+ import { logger as logger2 } from "@aussieljk/forkbook/internal/client-logger";
473
+ var GlobalsStore = class {
474
+ constructor({
475
+ globals = {},
476
+ globalTypes = {}
477
+ }) {
478
+ this.set({ globals, globalTypes });
479
+ }
480
+ set({ globals = {}, globalTypes = {} }) {
481
+ let delta = this.initialGlobals && deepDiff(this.initialGlobals, this.globals);
482
+ this.allowedGlobalNames = /* @__PURE__ */ new Set([...Object.keys(globals), ...Object.keys(globalTypes)]), this.initialGlobals = { ...globals }, this.globals = this.initialGlobals, delta && delta !== DEEPLY_EQUAL && this.updateFromPersisted(delta);
483
+ }
484
+ filterAllowedGlobals(globals) {
485
+ return Object.entries(globals).reduce((acc, [key, value]) => (this.allowedGlobalNames.has(key) ? acc[key] = value : logger2.warn(
486
+ `Attempted to set a global (${key}) that is not defined in initial globals or globalTypes`
487
+ ), acc), {});
488
+ }
489
+ updateFromPersisted(persisted) {
490
+ let allowedUrlGlobals = this.filterAllowedGlobals(persisted);
491
+ this.globals = { ...this.globals, ...allowedUrlGlobals };
492
+ }
493
+ get() {
494
+ return this.globals;
495
+ }
496
+ update(newGlobals) {
497
+ this.globals = { ...this.globals, ...this.filterAllowedGlobals(newGlobals) };
498
+ for (let key in newGlobals)
499
+ newGlobals[key] === void 0 && (this.globals[key] = this.initialGlobals[key]);
500
+ }
501
+ };
502
+
503
+ // src/preview-api/modules/store/StoryIndexStore.ts
504
+ var import_memoizerific = __toESM(require_memoizerific(), 1);
505
+ import { MissingStoryAfterHmrError } from "@aussieljk/forkbook/internal/preview-errors";
506
+ var getImportPathMap = (0, import_memoizerific.default)(1)(
507
+ (entries) => Object.values(entries).reduce(
508
+ (acc, entry) => (acc[entry.importPath] = acc[entry.importPath] || entry, acc),
509
+ {}
510
+ )
511
+ ), StoryIndexStore = class {
512
+ constructor({ entries } = { v: 5, entries: {} }) {
513
+ this.entries = entries;
514
+ }
515
+ entryFromSpecifier(specifier) {
516
+ let entries = Object.values(this.entries);
517
+ if (specifier === "*")
518
+ return entries[0];
519
+ if (typeof specifier == "string")
520
+ return this.entries[specifier] ? this.entries[specifier] : entries.find((entry) => entry.id.startsWith(specifier));
521
+ let { name, title } = specifier;
522
+ return entries.find((entry) => entry.name === name && entry.title === title);
523
+ }
524
+ storyIdToEntry(storyId) {
525
+ let storyEntry = this.entries[storyId];
526
+ if (!storyEntry)
527
+ throw new MissingStoryAfterHmrError({ storyId });
528
+ return storyEntry;
529
+ }
530
+ importPathToEntry(importPath) {
531
+ return getImportPathMap(this.entries)[importPath];
532
+ }
533
+ };
534
+
535
+ // src/preview-api/modules/store/csf/normalizeInputTypes.ts
536
+ var normalizeType = (type) => typeof type == "string" ? { name: type } : type, normalizeControl = (control) => typeof control == "string" ? { type: control, disable: !1 } : control && typeof control == "object" && "type" in control && !("disable" in control) ? { ...control, disable: !1 } : control, normalizeInputType = (inputType, key) => {
537
+ let { type, control, ...rest } = inputType, normalized = {
538
+ name: key,
539
+ ...rest
540
+ };
541
+ return type && (normalized.type = normalizeType(type)), control ? normalized.control = normalizeControl(control) : control === !1 && (normalized.control = { disable: !0 }), normalized;
542
+ }, normalizeInputTypes = (inputTypes) => mapValues(inputTypes, normalizeInputType);
543
+
544
+ // src/preview-api/modules/store/csf/normalizeStory.ts
545
+ import { storyNameFromExport, toId } from "@aussieljk/forkbook/internal/csf";
546
+
547
+ // src/preview-api/modules/store/csf/normalizeArrays.ts
548
+ var normalizeArrays = (array) => Array.isArray(array) ? array : array ? [array] : [];
549
+
550
+ // src/preview-api/modules/store/csf/normalizeStory.ts
551
+ function normalizeStory(key, storyAnnotations, meta) {
552
+ let storyObject = storyAnnotations, userStoryFn = typeof storyAnnotations == "function" ? storyAnnotations : null, exportName = storyNameFromExport(key), name = typeof storyObject != "function" && storyObject.name || storyObject.storyName || exportName, decorators = normalizeArrays(storyObject.decorators), parameters = { ...storyObject.parameters }, args = { ...storyObject.args }, argTypes = { ...storyObject.argTypes }, loaders = normalizeArrays(storyObject.loaders), beforeEach = normalizeArrays(storyObject.beforeEach), afterEach = normalizeArrays(storyObject.afterEach), { render, play, tags = [], globals = {} } = storyObject, id = parameters.__id || toId(meta.id, exportName);
553
+ return {
554
+ moduleExport: storyAnnotations,
555
+ id,
556
+ name,
557
+ tags,
558
+ decorators,
559
+ parameters,
560
+ args,
561
+ argTypes: normalizeInputTypes(argTypes),
562
+ loaders,
563
+ beforeEach,
564
+ afterEach,
565
+ globals,
566
+ ...render && { render },
567
+ ...userStoryFn && { userStoryFn },
568
+ ...play && { play }
569
+ };
570
+ }
571
+
572
+ // src/preview-api/modules/store/csf/processCSFFile.ts
573
+ import { logger as logger3 } from "@aussieljk/forkbook/internal/client-logger";
574
+ import {
575
+ getStoryChildren,
576
+ isExportStory,
577
+ isStory,
578
+ toTestId
579
+ } from "@aussieljk/forkbook/internal/csf";
580
+
581
+ // src/preview-api/modules/store/csf/normalizeComponentAnnotations.ts
582
+ import { sanitize } from "@aussieljk/forkbook/internal/csf";
583
+ function normalizeComponentAnnotations(defaultExport, title = defaultExport.title, importPath) {
584
+ let { id, argTypes } = defaultExport;
585
+ return {
586
+ id: sanitize(id || title),
587
+ ...defaultExport,
588
+ title,
589
+ ...argTypes && { argTypes: normalizeInputTypes(argTypes) },
590
+ parameters: {
591
+ fileName: importPath,
592
+ ...defaultExport.parameters
593
+ }
594
+ };
595
+ }
596
+
597
+ // src/preview-api/modules/store/csf/processCSFFile.ts
598
+ var checkGlobals = (parameters) => {
599
+ let { globals, globalTypes } = parameters;
600
+ (globals || globalTypes) && logger3.error(
601
+ "Global args/argTypes can only be set globally",
602
+ JSON.stringify({
603
+ globals,
604
+ globalTypes
605
+ })
606
+ );
607
+ }, checkDisallowedParameters = (parameters) => {
608
+ parameters && checkGlobals(parameters);
609
+ };
610
+ function processCSFFile(moduleExports, importPath, title) {
611
+ let { default: defaultExport, __namedExportsOrder, ...namedExports } = moduleExports, factoryStory = Object.values(namedExports).find((it) => isStory(it));
612
+ if (factoryStory) {
613
+ let meta2 = normalizeComponentAnnotations(factoryStory.meta.input, title, importPath);
614
+ checkDisallowedParameters(meta2.parameters);
615
+ let csfFile2 = { meta: meta2, stories: {}, moduleExports };
616
+ return Object.keys(namedExports).forEach((key) => {
617
+ if (isExportStory(key, meta2) && isStory(namedExports[key])) {
618
+ let story = namedExports[key], storyMeta = normalizeStory(key, story.input, meta2);
619
+ checkDisallowedParameters(storyMeta.parameters), csfFile2.stories[storyMeta.id] = storyMeta, getStoryChildren(story).forEach((child) => {
620
+ let name = child.input.name, childId = toTestId(storyMeta.id, name);
621
+ child.input.parameters ??= {}, child.input.parameters.__id = childId, csfFile2.stories[childId] = normalizeStory(name, child.input, meta2);
622
+ });
623
+ }
624
+ }), csfFile2.projectAnnotations = factoryStory.meta.preview.composed, csfFile2;
625
+ }
626
+ let meta = normalizeComponentAnnotations(
627
+ defaultExport,
628
+ title,
629
+ importPath
630
+ );
631
+ checkDisallowedParameters(meta.parameters);
632
+ let csfFile = { meta, stories: {}, moduleExports };
633
+ return Object.keys(namedExports).forEach((key) => {
634
+ if (isExportStory(key, meta)) {
635
+ let storyMeta = normalizeStory(key, namedExports[key], meta);
636
+ checkDisallowedParameters(storyMeta.parameters), csfFile.stories[storyMeta.id] = storyMeta;
637
+ }
638
+ }), csfFile;
639
+ }
640
+
641
+ // src/preview-api/modules/store/csf/prepareStory.ts
642
+ import {
643
+ combineTags,
644
+ includeConditionalArg
645
+ } from "@aussieljk/forkbook/internal/csf";
646
+ import { NoRenderFunctionError } from "@aussieljk/forkbook/internal/preview-errors";
647
+ import { global as global3 } from "@storybook/global";
648
+ import { global as globalThis2 } from "@storybook/global";
649
+
650
+ // src/preview-api/modules/preview-web/render/mount-utils.ts
651
+ function mountDestructured(playFunction) {
652
+ return playFunction != null && getUsedProps(playFunction).includes("mount");
653
+ }
654
+ function getUsedProps(fn) {
655
+ let [, args, body] = fn.toString().match(/[^(]*\(([^)]+)\)(?:.*{([^]+)})?/) || [];
656
+ if (!args)
657
+ return [];
658
+ let [firstArg] = splitByComma(args);
659
+ if (!firstArg)
660
+ return [];
661
+ let [, destructuredProps] = firstArg.match(/^{([^]+)}$/) || [];
662
+ if (destructuredProps)
663
+ return splitByComma(stripComments(destructuredProps)).map(
664
+ (prop) => prop.replace(/:.*|=.*/g, "").trim()
665
+ );
666
+ if (!firstArg.match(/^[a-z_$][0-9a-z_$]*$/i))
667
+ return [];
668
+ let escapedArg = firstArg.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), [, destructuredArg] = body?.trim()?.match(new RegExp(`^(?:const|let|var)\\s*{([^}]+)}\\s*=\\s*${escapedArg};`)) || [];
669
+ return destructuredArg ? splitByComma(stripComments(destructuredArg)).map(
670
+ (prop) => prop.replace(/:.*|=.*/g, "").trim()
671
+ ) : [];
672
+ }
673
+ function stripComments(s) {
674
+ return s = s.replace(/\/\/.*$/gm, ""), s = s.replace(/\/\*[\s\S]*?\*\//g, ""), s;
675
+ }
676
+ function splitByComma(s) {
677
+ let result = [], stack = [], start = 0;
678
+ for (let i = 0; i < s.length; i++)
679
+ if (s[i] === "{" || s[i] === "[")
680
+ stack.push(s[i] === "{" ? "}" : "]");
681
+ else if (s[i] === stack[stack.length - 1])
682
+ stack.pop();
683
+ else if (!stack.length && s[i] === ",") {
684
+ let token = s.substring(start, i).trim();
685
+ token && result.push(token), start = i + 1;
686
+ }
687
+ let lastToken = s.substring(start).trim();
688
+ return lastToken && result.push(lastToken), result;
689
+ }
690
+
691
+ // src/preview-api/modules/store/decorators.ts
692
+ function decorateStory(storyFn, decorator, bindWithContext) {
693
+ let boundStoryFunction = bindWithContext(storyFn);
694
+ return (context) => decorator(boundStoryFunction, context);
695
+ }
696
+ function sanitizeStoryContextUpdate({
697
+ componentId,
698
+ title,
699
+ kind,
700
+ id,
701
+ name,
702
+ story,
703
+ parameters,
704
+ initialArgs,
705
+ argTypes,
706
+ ...update
707
+ } = {}) {
708
+ return update;
709
+ }
710
+ function defaultDecorateStory(storyFn, decorators) {
711
+ let contextStore = {}, bindWithContext = (decoratedStoryFn) => (update) => {
712
+ if (!contextStore.value)
713
+ throw new Error("Decorated function called without init");
714
+ return contextStore.value = {
715
+ ...contextStore.value,
716
+ ...sanitizeStoryContextUpdate(update)
717
+ }, decoratedStoryFn(contextStore.value);
718
+ }, decoratedWithContextStore = decorators.reduce(
719
+ (story, decorator) => decorateStory(story, decorator, bindWithContext),
720
+ storyFn
721
+ );
722
+ return (context) => (contextStore.value = context, decoratedWithContextStore(context));
723
+ }
724
+
725
+ // src/preview-api/modules/store/csf/prepareStory.ts
726
+ function prepareStory(storyAnnotations, componentAnnotations, projectAnnotations) {
727
+ let { moduleExport, id, name } = storyAnnotations || {}, partialAnnotations = preparePartialAnnotations(
728
+ storyAnnotations,
729
+ componentAnnotations,
730
+ projectAnnotations
731
+ ), applyLoaders = async (context) => {
732
+ let loaded = {};
733
+ for (let loaders of [
734
+ normalizeArrays(projectAnnotations.loaders),
735
+ normalizeArrays(componentAnnotations.loaders),
736
+ normalizeArrays(storyAnnotations.loaders)
737
+ ]) {
738
+ if (context.abortSignal.aborted)
739
+ return loaded;
740
+ let loadResults = await Promise.all(loaders.map((loader) => loader(context)));
741
+ Object.assign(loaded, ...loadResults);
742
+ }
743
+ return loaded;
744
+ }, applyBeforeEach = async (context) => {
745
+ let cleanupCallbacks = new Array();
746
+ for (let beforeEach of [
747
+ ...normalizeArrays(projectAnnotations.beforeEach),
748
+ ...normalizeArrays(componentAnnotations.beforeEach),
749
+ ...normalizeArrays(storyAnnotations.beforeEach)
750
+ ]) {
751
+ if (context.abortSignal.aborted)
752
+ return cleanupCallbacks;
753
+ let cleanup = await beforeEach(context);
754
+ cleanup && cleanupCallbacks.push(cleanup);
755
+ }
756
+ return cleanupCallbacks;
757
+ }, applyAfterEach = async (context) => {
758
+ let reversedFinalizers = [
759
+ ...normalizeArrays(projectAnnotations.afterEach),
760
+ ...normalizeArrays(componentAnnotations.afterEach),
761
+ ...normalizeArrays(storyAnnotations.afterEach)
762
+ ].reverse();
763
+ for (let finalizer of reversedFinalizers) {
764
+ if (context.abortSignal.aborted)
765
+ return;
766
+ await finalizer(context);
767
+ }
768
+ }, undecoratedStoryFn = (context) => context.originalStoryFn(context.args, context), { applyDecorators = defaultDecorateStory, runStep } = projectAnnotations, decorators = [
769
+ ...normalizeArrays(storyAnnotations?.decorators),
770
+ ...normalizeArrays(componentAnnotations?.decorators),
771
+ ...normalizeArrays(projectAnnotations?.decorators)
772
+ ], render = storyAnnotations?.userStoryFn || storyAnnotations?.render || componentAnnotations.render || projectAnnotations.render, decoratedStoryFn = applyHooks(applyDecorators)(undecoratedStoryFn, decorators), unboundStoryFn = (context) => decoratedStoryFn(context), playFunction = storyAnnotations?.play ?? componentAnnotations?.play, usesMount = mountDestructured(playFunction);
773
+ if (!render && !usesMount)
774
+ throw new NoRenderFunctionError({ id });
775
+ let defaultMount = (context) => async () => (await context.renderToCanvas(), context.canvas), mount = storyAnnotations.mount ?? componentAnnotations.mount ?? projectAnnotations.mount ?? defaultMount, testingLibraryRender = projectAnnotations.testingLibraryRender;
776
+ return {
777
+ storyGlobals: {},
778
+ ...partialAnnotations,
779
+ moduleExport,
780
+ id,
781
+ name,
782
+ story: name,
783
+ originalStoryFn: render,
784
+ undecoratedStoryFn,
785
+ unboundStoryFn,
786
+ applyLoaders,
787
+ applyBeforeEach,
788
+ applyAfterEach,
789
+ playFunction,
790
+ runStep,
791
+ mount,
792
+ testingLibraryRender,
793
+ renderToCanvas: projectAnnotations.renderToCanvas,
794
+ usesMount
795
+ };
796
+ }
797
+ function prepareMeta(componentAnnotations, projectAnnotations, moduleExport) {
798
+ return {
799
+ ...preparePartialAnnotations(void 0, componentAnnotations, projectAnnotations),
800
+ moduleExport
801
+ };
802
+ }
803
+ function preparePartialAnnotations(storyAnnotations, componentAnnotations, projectAnnotations) {
804
+ let defaultTags = [Tag.DEV, Tag.TEST], extraTags = globalThis2.DOCS_OPTIONS?.autodocs === !0 ? [Tag.AUTODOCS] : [], overrideTags = storyAnnotations?.tags?.includes(Tag.TEST_FN) ? [`!${Tag.AUTODOCS}`] : [], tags = combineTags(
805
+ ...defaultTags,
806
+ ...extraTags,
807
+ ...projectAnnotations.tags ?? [],
808
+ ...componentAnnotations.tags ?? [],
809
+ ...overrideTags,
810
+ ...storyAnnotations?.tags ?? []
811
+ ), parameters = combineParameters(
812
+ projectAnnotations.parameters,
813
+ componentAnnotations.parameters,
814
+ storyAnnotations?.parameters
815
+ ), { argTypesEnhancers = [], argsEnhancers = [] } = projectAnnotations, passedArgTypes = combineParameters(
816
+ projectAnnotations.argTypes,
817
+ componentAnnotations.argTypes,
818
+ storyAnnotations?.argTypes
819
+ );
820
+ if (storyAnnotations) {
821
+ let render = storyAnnotations?.userStoryFn || storyAnnotations?.render || componentAnnotations.render || projectAnnotations.render;
822
+ parameters.__isArgsStory = render && render.length > 0;
823
+ }
824
+ let passedArgs = {
825
+ ...projectAnnotations.args,
826
+ ...componentAnnotations.args,
827
+ ...storyAnnotations?.args
828
+ }, storyGlobals = {
829
+ ...componentAnnotations.globals,
830
+ ...storyAnnotations?.globals
831
+ }, contextForEnhancers = {
832
+ componentId: componentAnnotations.id,
833
+ title: componentAnnotations.title,
834
+ kind: componentAnnotations.title,
835
+ // Back compat
836
+ id: storyAnnotations?.id || componentAnnotations.id,
837
+ // if there's no story name, we create a fake one since enhancers expect a name
838
+ name: storyAnnotations?.name || "__meta",
839
+ story: storyAnnotations?.name || "__meta",
840
+ // Back compat
841
+ component: componentAnnotations.component,
842
+ subcomponents: componentAnnotations.subcomponents,
843
+ tags,
844
+ parameters,
845
+ initialArgs: passedArgs,
846
+ argTypes: passedArgTypes,
847
+ storyGlobals
848
+ };
849
+ contextForEnhancers.argTypes = argTypesEnhancers.filter((enhancer) => !(global3.FEATURES?.docgenServer && enhancer.secondPass)).reduce(
850
+ (accumulatedArgTypes, enhancer) => enhancer({ ...contextForEnhancers, argTypes: accumulatedArgTypes }),
851
+ contextForEnhancers.argTypes
852
+ );
853
+ let initialArgsBeforeEnhancers = { ...passedArgs };
854
+ contextForEnhancers.initialArgs = [...argsEnhancers].reduce(
855
+ (accumulatedArgs, enhancer) => ({
856
+ ...accumulatedArgs,
857
+ ...enhancer({
858
+ ...contextForEnhancers,
859
+ initialArgs: accumulatedArgs
860
+ })
861
+ }),
862
+ initialArgsBeforeEnhancers
863
+ );
864
+ let { name, story, ...withoutStoryIdentifiers } = contextForEnhancers;
865
+ return withoutStoryIdentifiers;
866
+ }
867
+ function prepareContext(context) {
868
+ let { args: unmappedArgs } = context, targetedContext = {
869
+ ...context,
870
+ allArgs: void 0,
871
+ argsByTarget: void 0
872
+ };
873
+ if (global3.FEATURES?.argTypeTargetsV7) {
874
+ let argsByTarget = groupArgsByTarget(context);
875
+ targetedContext = {
876
+ ...context,
877
+ allArgs: context.args,
878
+ argsByTarget,
879
+ args: argsByTarget[UNTARGETED] || {}
880
+ };
881
+ }
882
+ let mappedArgs = Object.entries(targetedContext.args).reduce((acc, [key, val]) => {
883
+ if (!targetedContext.argTypes[key]?.mapping)
884
+ return acc[key] = val, acc;
885
+ let mappingFn = (originalValue) => {
886
+ let mapping = targetedContext.argTypes[key].mapping;
887
+ return mapping && originalValue in mapping ? mapping[originalValue] : originalValue;
888
+ };
889
+ return acc[key] = Array.isArray(val) ? val.map(mappingFn) : mappingFn(val), acc;
890
+ }, {}), includedArgs = Object.entries(mappedArgs).reduce((acc, [key, val]) => {
891
+ let argType = targetedContext.argTypes[key] || {};
892
+ return includeConditionalArg(argType, mappedArgs, targetedContext.globals) && (acc[key] = val), acc;
893
+ }, {});
894
+ return { ...targetedContext, unmappedArgs, args: includedArgs };
895
+ }
896
+
897
+ // src/preview-api/modules/store/csf/hideArgTypes.ts
898
+ import { ArgTypesRemovedFromStoryContextError } from "@aussieljk/forkbook/internal/preview-errors";
899
+ var HIDDEN_KEY = "argTypes";
900
+ function hideArgTypes(context) {
901
+ return new Proxy(context, {
902
+ get(target, key, receiver) {
903
+ if (key === HIDDEN_KEY)
904
+ throw new ArgTypesRemovedFromStoryContextError({ storyId: target.id });
905
+ return key === "context" ? receiver : Reflect.get(target, key, receiver);
906
+ },
907
+ has(target, key) {
908
+ return key !== HIDDEN_KEY && Reflect.has(target, key);
909
+ },
910
+ ownKeys(target) {
911
+ return Reflect.ownKeys(target).filter((key) => key !== HIDDEN_KEY);
912
+ },
913
+ getOwnPropertyDescriptor(target, key) {
914
+ return key === HIDDEN_KEY ? void 0 : Reflect.getOwnPropertyDescriptor(target, key);
915
+ }
916
+ });
917
+ }
918
+
919
+ // src/preview-api/modules/store/csf/normalizeProjectAnnotations.ts
920
+ function normalizeProjectAnnotations({
921
+ argTypes,
922
+ argTypesEnhancers,
923
+ decorators,
924
+ loaders,
925
+ beforeEach,
926
+ afterEach,
927
+ initialGlobals,
928
+ ...annotations
929
+ }) {
930
+ return {
931
+ ...argTypes && { argTypes: normalizeInputTypes(argTypes) },
932
+ decorators: normalizeArrays(decorators),
933
+ loaders: normalizeArrays(loaders),
934
+ beforeEach: normalizeArrays(beforeEach),
935
+ afterEach: normalizeArrays(afterEach),
936
+ argTypesEnhancers: [
937
+ ...argTypesEnhancers || [],
938
+ inferArgTypes,
939
+ // There's an architectural decision to be made regarding embedded addons in core:
940
+ //
941
+ // Option 1: Keep embedded addons but ensure consistency by moving addon-specific code
942
+ // (like inferControls) to live alongside the addon code itself. This maintains the
943
+ // concept of core addons while improving code organization.
944
+ //
945
+ // Option 2: Fully integrate these addons into core, potentially moving UI components
946
+ // into the manager and treating them as core features rather than addons. This is a
947
+ // bigger architectural change requiring careful consideration.
948
+ //
949
+ // For now, we're keeping inferControls here as we need time to properly evaluate
950
+ // these options and their implications.
951
+ //
952
+ // TODO: Make an architectural decision on the handling of core addons
953
+ inferControls
954
+ ],
955
+ initialGlobals,
956
+ ...annotations
957
+ };
958
+ }
959
+
960
+ // src/preview-api/modules/store/csf/beforeAll.ts
961
+ var composeBeforeAllHooks = (hooks) => async () => {
962
+ let cleanups2 = [];
963
+ for (let hook of hooks) {
964
+ let cleanup = await hook();
965
+ cleanup && cleanups2.unshift(cleanup);
966
+ }
967
+ return async () => {
968
+ for (let cleanup of cleanups2)
969
+ await cleanup();
970
+ };
971
+ };
972
+
973
+ // src/preview-api/modules/store/csf/stepRunners.ts
974
+ function composeStepRunners(stepRunners) {
975
+ return async (label, play, playContext) => {
976
+ await stepRunners.reduceRight(
977
+ (innerPlay, stepRunner) => async () => stepRunner(label, innerPlay, playContext),
978
+ async () => play(playContext)
979
+ )();
980
+ };
981
+ }
982
+
983
+ // src/preview-api/modules/store/csf/composeConfigs.ts
984
+ function getField(moduleExportList, field) {
985
+ return moduleExportList.map((xs) => xs.default?.[field] ?? xs[field]).filter(Boolean);
986
+ }
987
+ function getArrayField(moduleExportList, field) {
988
+ return getField(moduleExportList, field).reduce((prev, cur) => {
989
+ let normalized = normalizeArrays(cur);
990
+ return [...prev, ...normalized];
991
+ }, []);
992
+ }
993
+ function getObjectField(moduleExportList, field) {
994
+ return Object.assign({}, ...getField(moduleExportList, field));
995
+ }
996
+ function getSingletonField(moduleExportList, field) {
997
+ return getField(moduleExportList, field).pop();
998
+ }
999
+ function composeConfigs(moduleExportList) {
1000
+ let allArgTypeEnhancers = getArrayField(moduleExportList, "argTypesEnhancers"), stepRunners = getField(moduleExportList, "runStep"), beforeAllHooks = getArrayField(moduleExportList, "beforeAll");
1001
+ return {
1002
+ parameters: combineParameters(...getField(moduleExportList, "parameters")),
1003
+ decorators: getArrayField([...moduleExportList].reverse(), "decorators"),
1004
+ args: getObjectField(moduleExportList, "args"),
1005
+ argsEnhancers: getArrayField(moduleExportList, "argsEnhancers"),
1006
+ argTypes: getObjectField(moduleExportList, "argTypes"),
1007
+ argTypesEnhancers: [
1008
+ ...allArgTypeEnhancers.filter((e) => !e.secondPass),
1009
+ ...allArgTypeEnhancers.filter((e) => e.secondPass)
1010
+ ],
1011
+ initialGlobals: getObjectField(moduleExportList, "initialGlobals"),
1012
+ globalTypes: getObjectField(moduleExportList, "globalTypes"),
1013
+ loaders: getArrayField(moduleExportList, "loaders"),
1014
+ beforeAll: composeBeforeAllHooks(beforeAllHooks),
1015
+ beforeEach: getArrayField(moduleExportList, "beforeEach"),
1016
+ afterEach: getArrayField(moduleExportList, "afterEach"),
1017
+ render: getSingletonField(moduleExportList, "render"),
1018
+ renderToCanvas: getSingletonField(moduleExportList, "renderToCanvas"),
1019
+ applyDecorators: getSingletonField(moduleExportList, "applyDecorators"),
1020
+ runStep: composeStepRunners(stepRunners),
1021
+ tags: getArrayField(moduleExportList, "tags"),
1022
+ mount: getSingletonField(moduleExportList, "mount"),
1023
+ testingLibraryRender: getSingletonField(moduleExportList, "testingLibraryRender")
1024
+ };
1025
+ }
1026
+
1027
+ // src/preview-api/modules/store/csf/composeProjectAnnotationsWithCore.ts
1028
+ import {
1029
+ getCoreAnnotations,
1030
+ hasCoreAnnotations,
1031
+ markAsComposedWithCoreAnnotations
1032
+ } from "@aussieljk/forkbook/internal/csf";
1033
+ function composeProjectAnnotationsWithCore(annotations) {
1034
+ let definedAnnotations = annotations.filter(Boolean), alreadyComposedWithCore = definedAnnotations.some(
1035
+ (annotation) => hasCoreAnnotations(annotation)
1036
+ );
1037
+ return markAsComposedWithCoreAnnotations(
1038
+ composeConfigs(
1039
+ alreadyComposedWithCore ? definedAnnotations : [...getCoreAnnotations(), ...definedAnnotations]
1040
+ )
1041
+ );
1042
+ }
1043
+
1044
+ // src/preview-api/modules/store/csf/portable-stories.ts
1045
+ import { isExportStory as isExportStory2 } from "@aussieljk/forkbook/internal/csf";
1046
+ import {
1047
+ MountMustBeDestructuredError,
1048
+ ProjectAnnotationsAlreadyAppliedError
1049
+ } from "@aussieljk/forkbook/internal/preview-errors";
1050
+
1051
+ // src/preview-api/modules/store/reporter-api.ts
1052
+ var ReporterAPI = class {
1053
+ constructor() {
1054
+ this.reports = [];
1055
+ }
1056
+ async addReport(report) {
1057
+ this.reports.push(report);
1058
+ }
1059
+ };
1060
+
1061
+ // src/preview-api/modules/store/csf/csf-factory-utils.ts
1062
+ import { isMeta, isStory as isStory2 } from "@aussieljk/forkbook/internal/csf";
1063
+ function getCsfFactoryAnnotations(story, meta, projectAnnotations) {
1064
+ return isStory2(story) ? {
1065
+ story: story.input,
1066
+ meta: story.meta.input,
1067
+ preview: story.meta.preview.composed
1068
+ } : { story, meta: isMeta(meta) ? meta.input : meta, preview: projectAnnotations };
1069
+ }
1070
+
1071
+ // src/preview-api/modules/store/csf/portable-stories.ts
1072
+ function setDefaultProjectAnnotations(_defaultProjectAnnotations) {
1073
+ globalThis.defaultProjectAnnotations = _defaultProjectAnnotations;
1074
+ }
1075
+ var DEFAULT_STORY_TITLE = "ComposedStory", DEFAULT_STORY_NAME = "Unnamed Story";
1076
+ function setProjectAnnotations(projectAnnotations) {
1077
+ if (globalThis.__STORYBOOK_ADDON_VITEST_PROJECT_ANNOTATIONS_APPLIED__)
1078
+ throw new ProjectAnnotationsAlreadyAppliedError();
1079
+ globalThis.__STORYBOOK_SET_PROJECT_ANNOTATIONS_CALLED__ = !0;
1080
+ let annotations = Array.isArray(projectAnnotations) ? projectAnnotations : [projectAnnotations];
1081
+ return globalThis.globalProjectAnnotations = composeProjectAnnotationsWithCore([
1082
+ globalThis.defaultProjectAnnotations ?? {},
1083
+ ...annotations
1084
+ ]), globalThis.globalProjectAnnotations ?? {};
1085
+ }
1086
+ var cleanups = [];
1087
+ function composeStory(storyAnnotations, componentAnnotations, projectAnnotations, defaultConfig, exportsName) {
1088
+ if (storyAnnotations === void 0)
1089
+ throw new Error("Expected a story but received undefined.");
1090
+ componentAnnotations.title = componentAnnotations.title ?? DEFAULT_STORY_TITLE;
1091
+ let normalizedComponentAnnotations = normalizeComponentAnnotations(componentAnnotations), storyName = exportsName || storyAnnotations.storyName || storyAnnotations.name || DEFAULT_STORY_NAME, normalizedStory = normalizeStory(
1092
+ storyName,
1093
+ storyAnnotations,
1094
+ normalizedComponentAnnotations
1095
+ ), normalizedProjectAnnotations = normalizeProjectAnnotations(
1096
+ composeConfigs([
1097
+ defaultConfig ?? globalThis.globalProjectAnnotations ?? {},
1098
+ projectAnnotations ?? {}
1099
+ ])
1100
+ ), story = prepareStory(
1101
+ normalizedStory,
1102
+ normalizedComponentAnnotations,
1103
+ normalizedProjectAnnotations
1104
+ ), globals = {
1105
+ ...normalizedProjectAnnotations.initialGlobals,
1106
+ ...story.storyGlobals
1107
+ }, reporting = new ReporterAPI(), initializeContext = () => {
1108
+ let context = prepareContext({
1109
+ hooks: new HooksContext(),
1110
+ globals,
1111
+ args: { ...story.initialArgs },
1112
+ viewMode: "story",
1113
+ reporting,
1114
+ loaded: {},
1115
+ abortSignal: new AbortController().signal,
1116
+ step: (label, play2) => story.runStep(label, play2, hideArgTypes(context)),
1117
+ canvasElement: null,
1118
+ canvas: {},
1119
+ userEvent: {},
1120
+ globalTypes: normalizedProjectAnnotations.globalTypes,
1121
+ ...story,
1122
+ context: null,
1123
+ mount: null
1124
+ });
1125
+ return context.parameters.__isPortableStory = !0, context.context = context, story.renderToCanvas && (context.renderToCanvas = async () => {
1126
+ let unmount = await story.renderToCanvas?.(
1127
+ {
1128
+ componentId: story.componentId,
1129
+ title: story.title,
1130
+ id: story.id,
1131
+ name: story.name,
1132
+ tags: story.tags,
1133
+ showMain: () => {
1134
+ },
1135
+ showError: (error) => {
1136
+ throw new Error(`${error.title}
1137
+ ${error.description}`);
1138
+ },
1139
+ showException: (error) => {
1140
+ throw error;
1141
+ },
1142
+ forceRemount: !0,
1143
+ storyContext: context,
1144
+ storyFn: () => story.unboundStoryFn(context),
1145
+ unboundStoryFn: story.unboundStoryFn
1146
+ },
1147
+ context.canvasElement
1148
+ );
1149
+ unmount && cleanups.push(unmount);
1150
+ let hooks = context.hooks;
1151
+ cleanups.push(() => hooks.clean()), hooks.renderListener(context.id);
1152
+ }), context.mount = story.mount(context), context;
1153
+ }, loadedContext, play = async (extraContext) => {
1154
+ let context = initializeContext();
1155
+ return context.canvasElement ??= globalThis?.document?.body, loadedContext && (context.loaded = loadedContext.loaded), Object.assign(context, extraContext), story.playFunction(hideArgTypes(context));
1156
+ }, run = (extraContext) => {
1157
+ let context = initializeContext();
1158
+ return Object.assign(context, extraContext), runStory(story, context);
1159
+ }, playFunction = story.playFunction ? play : void 0;
1160
+ return Object.assign(
1161
+ function(extraArgs) {
1162
+ let context = initializeContext();
1163
+ return loadedContext && (context.loaded = loadedContext.loaded), context.args = {
1164
+ ...context.initialArgs,
1165
+ ...extraArgs
1166
+ }, story.unboundStoryFn(context);
1167
+ },
1168
+ {
1169
+ id: story.id,
1170
+ storyName,
1171
+ load: async () => {
1172
+ for (let callback of [...cleanups].reverse())
1173
+ await callback();
1174
+ cleanups.length = 0;
1175
+ let context = initializeContext(), hookContext = hideArgTypes(context);
1176
+ context.loaded = await story.applyLoaders(hookContext), cleanups.push(...(await story.applyBeforeEach(hookContext)).filter(Boolean)), loadedContext = context;
1177
+ },
1178
+ globals,
1179
+ args: story.initialArgs,
1180
+ parameters: story.parameters,
1181
+ argTypes: story.argTypes,
1182
+ play: playFunction,
1183
+ run,
1184
+ reporting,
1185
+ tags: story.tags
1186
+ }
1187
+ );
1188
+ }
1189
+ var defaultComposeStory = (story, component, project, exportsName) => composeStory(story, component, project, {}, exportsName);
1190
+ function composeStories(storiesImport, globalConfig, composeStoryFn = defaultComposeStory) {
1191
+ let { default: metaExport, __esModule, __namedExportsOrder, ...stories } = storiesImport, meta = metaExport;
1192
+ return Object.entries(stories).reduce(
1193
+ (storiesMap, [exportsName, story]) => {
1194
+ let { story: storyAnnotations, meta: componentAnnotations } = getCsfFactoryAnnotations(story);
1195
+ return !meta && componentAnnotations && (meta = componentAnnotations), isExportStory2(exportsName, meta) ? Object.assign(storiesMap, {
1196
+ [exportsName]: composeStoryFn(storyAnnotations, meta, globalConfig, exportsName)
1197
+ }) : storiesMap;
1198
+ },
1199
+ {}
1200
+ );
1201
+ }
1202
+ async function runStory(story, context) {
1203
+ for (let callback of [...cleanups].reverse())
1204
+ await callback();
1205
+ cleanups.length = 0;
1206
+ let hookContext = hideArgTypes(context);
1207
+ if (!context.canvasElement) {
1208
+ let container = document.createElement("div");
1209
+ globalThis?.document?.body?.appendChild(container), context.canvasElement = container, cleanups.push(() => {
1210
+ globalThis?.document?.body?.contains(container) && globalThis?.document?.body?.removeChild(container);
1211
+ });
1212
+ }
1213
+ if (context.loaded = await story.applyLoaders(hookContext), context.abortSignal.aborted)
1214
+ return;
1215
+ cleanups.push(...(await story.applyBeforeEach(hookContext)).filter(Boolean));
1216
+ let playFunction = story.playFunction, isMountDestructured = story.usesMount;
1217
+ if (isMountDestructured || await context.mount(), context.abortSignal.aborted)
1218
+ return;
1219
+ playFunction && (isMountDestructured || (context.mount = async () => {
1220
+ throw new MountMustBeDestructuredError({ playFunction: playFunction.toString() });
1221
+ }), await playFunction(hookContext));
1222
+ let cleanUp;
1223
+ isTestEnvironment() ? cleanUp = pauseAnimations() : await waitForAnimations(context.abortSignal);
1224
+ try {
1225
+ await story.applyAfterEach(hookContext);
1226
+ } finally {
1227
+ await cleanUp?.();
1228
+ }
1229
+ }
1230
+
1231
+ // src/preview-api/modules/store/StoryStore.ts
1232
+ function composeProjectAnnotations(projectAnnotations) {
1233
+ return normalizeProjectAnnotations(composeProjectAnnotationsWithCore([projectAnnotations]));
1234
+ }
1235
+ var CSF_CACHE_SIZE = 1e3, STORY_CACHE_SIZE = 1e4, StoryStore = class {
1236
+ constructor(storyIndex, importFn, projectAnnotations) {
1237
+ this.importFn = importFn;
1238
+ this.storyIndex = new StoryIndexStore(storyIndex), this.projectAnnotations = composeProjectAnnotations(projectAnnotations);
1239
+ let { initialGlobals, globalTypes } = this.projectAnnotations;
1240
+ this.args = new ArgsStore(), this.userGlobals = new GlobalsStore({ globals: initialGlobals, globalTypes }), this.hooks = {}, this.cleanupCallbacks = {}, this.processCSFFileWithCache = (0, import_memoizerific2.default)(CSF_CACHE_SIZE)(processCSFFile), this.prepareMetaWithCache = (0, import_memoizerific2.default)(CSF_CACHE_SIZE)(prepareMeta), this.prepareStoryWithCache = (0, import_memoizerific2.default)(STORY_CACHE_SIZE)(prepareStory);
1241
+ }
1242
+ setProjectAnnotations(projectAnnotations) {
1243
+ this.projectAnnotations = normalizeProjectAnnotations(projectAnnotations);
1244
+ let { initialGlobals, globalTypes } = projectAnnotations;
1245
+ this.userGlobals.set({ globals: initialGlobals, globalTypes });
1246
+ }
1247
+ // This means that one of the CSF files has changed.
1248
+ // If the `importFn` has changed, we will invalidate both caches.
1249
+ // If the `storyIndex` data has changed, we may or may not invalidate the caches, depending
1250
+ // on whether we've loaded the relevant files yet.
1251
+ async onStoriesChanged({
1252
+ importFn,
1253
+ storyIndex
1254
+ }) {
1255
+ importFn && (this.importFn = importFn), storyIndex && (this.storyIndex.entries = storyIndex.entries), this.cachedCSFFiles && await this.cacheAllCSFFiles();
1256
+ }
1257
+ // Get an entry from the index, waiting on initialization if necessary
1258
+ async storyIdToEntry(storyId) {
1259
+ return this.storyIndex.storyIdToEntry(storyId);
1260
+ }
1261
+ // To load a single CSF file to service a story we need to look up the importPath in the index
1262
+ async loadCSFFileByStoryId(storyId) {
1263
+ let { importPath, title } = this.storyIndex.storyIdToEntry(storyId), moduleExports = await this.importFn(importPath);
1264
+ return this.processCSFFileWithCache(moduleExports, importPath, title);
1265
+ }
1266
+ async loadAllCSFFiles() {
1267
+ let importPaths = {};
1268
+ return Object.entries(this.storyIndex.entries).forEach(([storyId, { importPath }]) => {
1269
+ importPaths[importPath] = storyId;
1270
+ }), (await Promise.all(
1271
+ Object.entries(importPaths).map(async ([importPath, storyId]) => ({
1272
+ importPath,
1273
+ csfFile: await this.loadCSFFileByStoryId(storyId)
1274
+ }))
1275
+ )).reduce(
1276
+ (acc, { importPath, csfFile }) => (acc[importPath] = csfFile, acc),
1277
+ {}
1278
+ );
1279
+ }
1280
+ async cacheAllCSFFiles() {
1281
+ this.cachedCSFFiles = await this.loadAllCSFFiles();
1282
+ }
1283
+ preparedMetaFromCSFFile({ csfFile }) {
1284
+ let componentAnnotations = csfFile.meta;
1285
+ return this.prepareMetaWithCache(
1286
+ componentAnnotations,
1287
+ this.projectAnnotations,
1288
+ csfFile.moduleExports.default
1289
+ );
1290
+ }
1291
+ // Load the CSF file for a story and prepare the story from it and the project annotations.
1292
+ async loadStory({ storyId }) {
1293
+ let csfFile = await this.loadCSFFileByStoryId(storyId);
1294
+ return this.storyFromCSFFile({ storyId, csfFile });
1295
+ }
1296
+ // This function is synchronous for convenience -- often times if you have a CSF file already
1297
+ // it is easier not to have to await `loadStory`.
1298
+ storyFromCSFFile({
1299
+ storyId,
1300
+ csfFile
1301
+ }) {
1302
+ let storyAnnotations = csfFile.stories[storyId];
1303
+ if (!storyAnnotations)
1304
+ throw new MissingStoryFromCsfFileError({ storyId });
1305
+ let componentAnnotations = csfFile.meta, story = this.prepareStoryWithCache(
1306
+ storyAnnotations,
1307
+ componentAnnotations,
1308
+ csfFile.projectAnnotations ?? this.projectAnnotations
1309
+ );
1310
+ return this.args.setInitial(story), this.hooks[story.id] = this.hooks[story.id] || new HooksContext(), story;
1311
+ }
1312
+ // If we have a CSF file we can get all the stories from it synchronously
1313
+ componentStoriesFromCSFFile({
1314
+ csfFile
1315
+ }) {
1316
+ return Object.keys(this.storyIndex.entries).filter((storyId) => !!csfFile.stories[storyId]).map((storyId) => this.storyFromCSFFile({ storyId, csfFile }));
1317
+ }
1318
+ async loadEntry(id) {
1319
+ let entry = await this.storyIdToEntry(id), storyImports = entry.type === "docs" ? entry.storiesImports : [], [entryExports, ...csfFiles] = await Promise.all([
1320
+ this.importFn(entry.importPath),
1321
+ ...storyImports.map((storyImportPath) => {
1322
+ let firstStoryEntry = this.storyIndex.importPathToEntry(storyImportPath);
1323
+ return this.loadCSFFileByStoryId(firstStoryEntry.id);
1324
+ })
1325
+ ]);
1326
+ return { entryExports, csfFiles };
1327
+ }
1328
+ // A prepared story does not include args, globals or hooks. These are stored in the story store
1329
+ // and updated separately to the (immutable) story.
1330
+ getStoryContext(story, { forceInitialArgs = !1 } = {}) {
1331
+ let userGlobals = this.userGlobals.get(), { initialGlobals } = this.userGlobals, reporting = new ReporterAPI();
1332
+ return prepareContext({
1333
+ ...story,
1334
+ args: forceInitialArgs ? story.initialArgs : this.args.get(story.id),
1335
+ initialGlobals,
1336
+ globalTypes: this.projectAnnotations.globalTypes,
1337
+ userGlobals,
1338
+ reporting,
1339
+ globals: {
1340
+ ...userGlobals,
1341
+ ...story.storyGlobals
1342
+ },
1343
+ hooks: this.hooks[story.id]
1344
+ });
1345
+ }
1346
+ addCleanupCallbacks(story, ...callbacks) {
1347
+ this.cleanupCallbacks[story.id] = (this.cleanupCallbacks[story.id] || []).concat(callbacks);
1348
+ }
1349
+ async cleanupStory(story) {
1350
+ this.hooks[story.id].clean();
1351
+ let callbacks = this.cleanupCallbacks[story.id];
1352
+ if (callbacks)
1353
+ for (let callback of [...callbacks].reverse())
1354
+ await callback();
1355
+ delete this.cleanupCallbacks[story.id];
1356
+ }
1357
+ extract(options = { includeDocsOnly: !1 }) {
1358
+ let { cachedCSFFiles } = this;
1359
+ if (console.log("extract: extracting stories", cachedCSFFiles), !cachedCSFFiles)
1360
+ throw new CalledExtractOnStoreError();
1361
+ let stories = Object.entries(this.storyIndex.entries).reduce(
1362
+ (acc, [storyId, entry]) => {
1363
+ if (entry.type === "docs")
1364
+ return acc;
1365
+ let csfFile = cachedCSFFiles[entry.importPath], story = this.storyFromCSFFile({ storyId, csfFile });
1366
+ return !options.includeDocsOnly && story.parameters.docsOnly || (acc[storyId] = Object.entries(story).reduce(
1367
+ (storyAcc, [key, value]) => key === "story" && entry.subtype === "test" ? { ...storyAcc, story: entry.parentName } : key === "moduleExport" || typeof value == "function" ? storyAcc : Array.isArray(value) ? Object.assign(storyAcc, { [key]: value.slice().sort() }) : Object.assign(storyAcc, { [key]: value }),
1368
+ {
1369
+ args: story.initialArgs,
1370
+ globals: {
1371
+ ...this.userGlobals.initialGlobals,
1372
+ ...this.userGlobals.globals,
1373
+ ...story.storyGlobals
1374
+ },
1375
+ storyId: entry.parent ? entry.parent : storyId
1376
+ }
1377
+ )), acc;
1378
+ },
1379
+ {}
1380
+ );
1381
+ return console.log("extract: stories", stories), stories;
1382
+ }
1383
+ };
1384
+
1385
+ // ../../node_modules/slash/index.js
1386
+ function slash(path) {
1387
+ return path.startsWith("\\\\?\\") ? path : path.replace(/\\/g, "/");
1388
+ }
1389
+
1390
+ // src/shared/story-index/autoTitle.ts
1391
+ var sanitize2 = (parts) => {
1392
+ if (parts.length === 0)
1393
+ return parts;
1394
+ let last = parts[parts.length - 1], lastStripped = last?.replace(/(?:[.](?:story|stories))?([.][^.]+)$/i, "");
1395
+ if (parts.length === 1)
1396
+ return [lastStripped];
1397
+ let nextToLast = parts[parts.length - 2];
1398
+ return lastStripped && nextToLast && lastStripped.toLowerCase() === nextToLast.toLowerCase() ? [...parts.slice(0, -2), lastStripped] : lastStripped && (/^(story|stories)([.][^.]+)$/i.test(last) || /^index$/i.test(lastStripped)) ? parts.slice(0, -1) : [...parts.slice(0, -1), lastStripped];
1399
+ };
1400
+ function pathJoin(paths) {
1401
+ return paths.flatMap((p) => p.split("/")).filter(Boolean).join("/");
1402
+ }
1403
+ var userOrAutoTitleFromSpecifier = (fileName, entry, userTitle) => {
1404
+ let { directory, importPathMatcher, titlePrefix = "" } = entry || {}, normalizedFileName = slash(String(fileName));
1405
+ if (importPathMatcher.exec(normalizedFileName)) {
1406
+ if (!userTitle) {
1407
+ let suffix = normalizedFileName.replace(directory, ""), parts = pathJoin([titlePrefix, suffix]).split("/");
1408
+ return parts = sanitize2(parts), parts.join("/");
1409
+ }
1410
+ return titlePrefix ? pathJoin([titlePrefix, userTitle]) : userTitle;
1411
+ }
1412
+ }, userOrAutoTitle = (fileName, storiesEntries, userTitle) => {
1413
+ for (let i = 0; i < storiesEntries.length; i += 1) {
1414
+ let title = userOrAutoTitleFromSpecifier(fileName, storiesEntries[i], userTitle);
1415
+ if (title)
1416
+ return title;
1417
+ }
1418
+ return userTitle || void 0;
1419
+ };
1420
+
1421
+ // src/shared/story-index/sortStories.ts
1422
+ import { dedent as dedent2 } from "ts-dedent";
1423
+
1424
+ // src/shared/story-index/storySort.ts
1425
+ var STORY_KIND_PATH_SEPARATOR = /\s*\/\s*/, storySort = (options = {}) => (a, b) => {
1426
+ if (a.title === b.title && !options.includeNames)
1427
+ return 0;
1428
+ let method = options.method || "configure", order = options.order || [], storyTitleA = a.title.trim().split(STORY_KIND_PATH_SEPARATOR), storyTitleB = b.title.trim().split(STORY_KIND_PATH_SEPARATOR);
1429
+ options.includeNames && (storyTitleA.push(a.name), storyTitleB.push(b.name));
1430
+ let depth = 0;
1431
+ for (; storyTitleA[depth] || storyTitleB[depth]; ) {
1432
+ if (!storyTitleA[depth])
1433
+ return -1;
1434
+ if (!storyTitleB[depth])
1435
+ return 1;
1436
+ let nameA = storyTitleA[depth], nameB = storyTitleB[depth];
1437
+ if (nameA !== nameB) {
1438
+ let indexA = order.indexOf(nameA), indexB = order.indexOf(nameB), indexWildcard = order.indexOf("*");
1439
+ return indexA !== -1 || indexB !== -1 ? (indexA === -1 && (indexWildcard !== -1 ? indexA = indexWildcard : indexA = order.length), indexB === -1 && (indexWildcard !== -1 ? indexB = indexWildcard : indexB = order.length), indexA - indexB) : method === "configure" ? 0 : nameA.localeCompare(nameB, options.locales ? options.locales : void 0, {
1440
+ numeric: !0,
1441
+ sensitivity: "accent"
1442
+ });
1443
+ }
1444
+ let index = order.indexOf(nameA);
1445
+ index === -1 && (index = order.indexOf("*"));
1446
+ let nestedOrder = order[index + 1];
1447
+ order = index !== -1 && Array.isArray(nestedOrder) ? nestedOrder : [], depth += 1;
1448
+ }
1449
+ return 0;
1450
+ };
1451
+
1452
+ // src/shared/story-index/sortStories.ts
1453
+ var toComparator = (storySortParameter) => typeof storySortParameter == "function" ? storySortParameter : storySort(
1454
+ Array.isArray(storySortParameter) ? { order: storySortParameter } : storySortParameter
1455
+ );
1456
+ var sortStoriesCommon = (stories, storySortParameter, fileNameOrder) => (storySortParameter ? stories.sort(toComparator(storySortParameter)) : stories.sort(
1457
+ (s1, s2) => fileNameOrder.indexOf(s1.importPath) - fileNameOrder.indexOf(s2.importPath)
1458
+ ), stories), sortStoriesV7 = (stories, storySortParameter, fileNameOrder) => {
1459
+ try {
1460
+ return sortStoriesCommon(stories, storySortParameter, fileNameOrder);
1461
+ } catch (err) {
1462
+ throw new Error(dedent2`
1463
+ Error sorting stories with sort parameter ${storySortParameter}:
1464
+
1465
+ > ${err.message}
1466
+
1467
+ Are you using a V6-style sort function in V7 mode?
1468
+
1469
+ More info: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#v7-style-story-sort
1470
+ `);
1471
+ }
1472
+ };
1473
+
1474
+ // src/preview-api/modules/preview-web/Preview.tsx
1475
+ import { deprecate, logger as logger4 } from "@aussieljk/forkbook/internal/client-logger";
1476
+ import {
1477
+ ARGTYPES_INFO_REQUEST,
1478
+ ARGTYPES_INFO_RESPONSE,
1479
+ CONFIG_ERROR,
1480
+ FORCE_REMOUNT,
1481
+ FORCE_RE_RENDER as FORCE_RE_RENDER2,
1482
+ GLOBALS_UPDATED,
1483
+ PREVIEW_INITIALIZED,
1484
+ RESET_STORY_ARGS as RESET_STORY_ARGS2,
1485
+ SET_GLOBALS,
1486
+ STORY_ARGS_UPDATED,
1487
+ STORY_HOT_UPDATED,
1488
+ STORY_INDEX_INVALIDATED,
1489
+ UPDATE_GLOBALS as UPDATE_GLOBALS2,
1490
+ UPDATE_STORY_ARGS as UPDATE_STORY_ARGS2
1491
+ } from "@aussieljk/forkbook/internal/core-events";
1492
+ import {
1493
+ CalledPreviewMethodBeforeInitializationError,
1494
+ MissingRenderToCanvasError,
1495
+ StoryIndexFetchError,
1496
+ StoryStoreAccessedBeforeInitializationError
1497
+ } from "@aussieljk/forkbook/internal/preview-errors";
1498
+ import { global as global4 } from "@storybook/global";
1499
+
1500
+ // src/preview-api/modules/preview-web/render/StoryRender.ts
1501
+ import {
1502
+ PLAY_FUNCTION_THREW_EXCEPTION,
1503
+ STORY_FINISHED,
1504
+ STORY_RENDERED as STORY_RENDERED2,
1505
+ STORY_RENDER_PHASE_CHANGED,
1506
+ UNHANDLED_ERRORS_WHILE_PLAYING
1507
+ } from "@aussieljk/forkbook/internal/core-events";
1508
+ import {
1509
+ MountMustBeDestructuredError as MountMustBeDestructuredError2,
1510
+ NoStoryMountedError
1511
+ } from "@aussieljk/forkbook/internal/preview-errors";
1512
+
1513
+ // src/preview-api/modules/preview-web/render/Render.ts
1514
+ var PREPARE_ABORTED = new Error("prepareAborted");
1515
+
1516
+ // src/preview-api/modules/preview-web/render/StoryRender.ts
1517
+ var { AbortController: AbortController2 } = globalThis;
1518
+ function serializeError(error) {
1519
+ try {
1520
+ let { name = "Error", message = String(error), stack } = error;
1521
+ return { name, message, stack };
1522
+ } catch {
1523
+ return { name: "Error", message: String(error) };
1524
+ }
1525
+ }
1526
+ var StoryRender = class {
1527
+ constructor(channel, store, renderToScreen, callbacks, id, viewMode, renderOptions = { autoplay: !0, forceInitialArgs: !1 }, story) {
1528
+ this.channel = channel;
1529
+ this.store = store;
1530
+ this.renderToScreen = renderToScreen;
1531
+ this.callbacks = callbacks;
1532
+ this.id = id;
1533
+ this.viewMode = viewMode;
1534
+ this.renderOptions = renderOptions;
1535
+ this.type = "story";
1536
+ this.notYetRendered = !0;
1537
+ this.rerenderEnqueued = !1;
1538
+ this.disableKeyListeners = !1;
1539
+ this.teardownRender = () => {
1540
+ };
1541
+ this.torndown = !1;
1542
+ this.abortController = new AbortController2(), this.renderId = Date.now(), story && (this.story = story, this.phase = "preparing");
1543
+ }
1544
+ async runPhase(signal, phase, phaseFn) {
1545
+ this.phase = phase, this.channel.emit(STORY_RENDER_PHASE_CHANGED, {
1546
+ newPhase: this.phase,
1547
+ renderId: this.renderId,
1548
+ storyId: this.id
1549
+ }), phaseFn && (await phaseFn(), this.checkIfAborted(signal));
1550
+ }
1551
+ checkIfAborted(signal) {
1552
+ return signal.aborted && // A remount replaces the controller; the superseded cycle must not report into the new one.
1553
+ signal === this.abortController.signal && !["finished", "aborted", "errored"].includes(this.phase) && (this.phase = "aborted", this.channel.emit(STORY_RENDER_PHASE_CHANGED, {
1554
+ newPhase: this.phase,
1555
+ renderId: this.renderId,
1556
+ storyId: this.id
1557
+ })), signal.aborted;
1558
+ }
1559
+ async prepare() {
1560
+ if (await this.runPhase(this.abortController.signal, "preparing", async () => {
1561
+ this.story = await this.store.loadStory({ storyId: this.id });
1562
+ }), this.abortController.signal.aborted)
1563
+ throw await this.store.cleanupStory(this.story), PREPARE_ABORTED;
1564
+ }
1565
+ // The two story "renders" are equal and have both loaded the same story
1566
+ isEqual(other) {
1567
+ return !!(this.id === other.id && this.story && this.story === other.story);
1568
+ }
1569
+ isPreparing() {
1570
+ return ["preparing"].includes(this.phase);
1571
+ }
1572
+ isPending() {
1573
+ return ["loading", "beforeEach", "rendering", "playing", "afterEach"].includes(
1574
+ this.phase
1575
+ );
1576
+ }
1577
+ async renderToElement(canvasElement) {
1578
+ return this.canvasElement = canvasElement, this.render({ initial: !0, forceRemount: !0 });
1579
+ }
1580
+ storyContext() {
1581
+ if (!this.story)
1582
+ throw new Error("Cannot call storyContext before preparing");
1583
+ let { forceInitialArgs } = this.renderOptions;
1584
+ return this.store.getStoryContext(this.story, { forceInitialArgs });
1585
+ }
1586
+ async render({
1587
+ initial = !1,
1588
+ forceRemount = !1
1589
+ } = {}) {
1590
+ let { canvasElement } = this;
1591
+ if (!this.story)
1592
+ throw new Error("cannot render when not prepared");
1593
+ let story = this.story;
1594
+ if (!canvasElement)
1595
+ throw new Error("cannot render when canvasElement is unset");
1596
+ let {
1597
+ id,
1598
+ componentId,
1599
+ title,
1600
+ name,
1601
+ tags,
1602
+ applyLoaders,
1603
+ applyBeforeEach,
1604
+ applyAfterEach,
1605
+ unboundStoryFn,
1606
+ playFunction,
1607
+ runStep
1608
+ } = story;
1609
+ forceRemount && !initial && (this.cancelRender(), this.abortController = new AbortController2());
1610
+ let abortSignal = this.abortController.signal, mounted = !1, isMountDestructured = story.usesMount;
1611
+ try {
1612
+ let context = {
1613
+ ...this.storyContext(),
1614
+ viewMode: this.viewMode,
1615
+ abortSignal,
1616
+ canvasElement,
1617
+ loaded: {},
1618
+ step: (label, play) => runStep(label, play, hookContext),
1619
+ context: null,
1620
+ canvas: {},
1621
+ userEvent: {},
1622
+ renderToCanvas: async () => {
1623
+ let teardown = await this.renderToScreen(renderContext, canvasElement);
1624
+ this.teardownRender = teardown || (() => {
1625
+ }), mounted = !0;
1626
+ },
1627
+ // The story provides (set in a renderer) a mount function that is a higher order function
1628
+ // (context) => (...args) => Canvas
1629
+ //
1630
+ // Before assigning it to the context, we resolve the context dependency,
1631
+ // so that a user can just call it as await mount(...args) in their play function.
1632
+ mount: async (...args) => {
1633
+ this.callbacks.showStoryDuringRender?.();
1634
+ let mountReturn = null;
1635
+ return await this.runPhase(abortSignal, "rendering", async () => {
1636
+ mountReturn = await story.mount(context)(...args);
1637
+ }), isMountDestructured && await this.runPhase(abortSignal, "playing"), mountReturn;
1638
+ }
1639
+ };
1640
+ context.context = context;
1641
+ let hookContext = hideArgTypes(context), renderContext = {
1642
+ componentId,
1643
+ title,
1644
+ kind: title,
1645
+ id,
1646
+ name,
1647
+ story: name,
1648
+ tags,
1649
+ ...this.callbacks,
1650
+ showError: (error) => (this.phase = "errored", this.callbacks.showError(error)),
1651
+ showException: (error) => (this.phase = "errored", this.callbacks.showException(error)),
1652
+ forceRemount: forceRemount || this.notYetRendered,
1653
+ storyContext: context,
1654
+ storyFn: () => unboundStoryFn(context),
1655
+ unboundStoryFn
1656
+ };
1657
+ if (await this.runPhase(abortSignal, "loading", async () => {
1658
+ context.loaded = await applyLoaders(hookContext);
1659
+ }), abortSignal.aborted)
1660
+ return;
1661
+ let cleanupCallbacks = await applyBeforeEach(hookContext);
1662
+ if (this.store.addCleanupCallbacks(story, ...cleanupCallbacks), this.checkIfAborted(abortSignal) || (!mounted && !isMountDestructured && await context.mount(), this.notYetRendered = !1, abortSignal.aborted))
1663
+ return;
1664
+ let ignoreUnhandledErrors = this.story.parameters?.test?.dangerouslyIgnoreUnhandledErrors === !0, unhandledErrors = /* @__PURE__ */ new Set(), onError = (event) => {
1665
+ event.error && unhandledErrors.add(event.error);
1666
+ }, onUnhandledRejection = (event) => {
1667
+ event.reason && unhandledErrors.add(event.reason);
1668
+ };
1669
+ if (this.renderOptions.autoplay && forceRemount && playFunction && this.phase !== "errored") {
1670
+ window?.addEventListener?.("error", onError), window?.addEventListener?.("unhandledrejection", onUnhandledRejection), this.disableKeyListeners = !0;
1671
+ try {
1672
+ if (isMountDestructured ? await playFunction(hookContext) : (context.mount = async () => {
1673
+ throw new MountMustBeDestructuredError2({ playFunction: playFunction.toString() });
1674
+ }, await this.runPhase(abortSignal, "playing", async () => playFunction(hookContext))), !mounted)
1675
+ throw new NoStoryMountedError();
1676
+ this.checkIfAborted(abortSignal), !ignoreUnhandledErrors && unhandledErrors.size > 0 ? await this.runPhase(abortSignal, "errored") : await this.runPhase(abortSignal, "played");
1677
+ } catch (error) {
1678
+ if (this.callbacks.showStoryDuringRender?.(), await this.runPhase(abortSignal, "errored", async () => {
1679
+ this.channel.emit(PLAY_FUNCTION_THREW_EXCEPTION, serializeError(error));
1680
+ }), this.story.parameters.throwPlayFunctionExceptions !== !1)
1681
+ throw error;
1682
+ console.error(error);
1683
+ }
1684
+ if (!ignoreUnhandledErrors && unhandledErrors.size > 0 && this.channel.emit(
1685
+ UNHANDLED_ERRORS_WHILE_PLAYING,
1686
+ Array.from(unhandledErrors).map(serializeError)
1687
+ ), this.disableKeyListeners = !1, window?.removeEventListener?.("unhandledrejection", onUnhandledRejection), window?.removeEventListener?.("error", onError), abortSignal.aborted)
1688
+ return;
1689
+ }
1690
+ if (await this.runPhase(abortSignal, "completing", async () => {
1691
+ isTestEnvironment() ? this.store.addCleanupCallbacks(story, pauseAnimations()) : await waitForAnimations(abortSignal);
1692
+ }), abortSignal.aborted)
1693
+ return;
1694
+ await this.runPhase(abortSignal, "completed", async () => {
1695
+ this.channel.emit(STORY_RENDERED2, id);
1696
+ }), this.phase !== "errored" && await this.runPhase(abortSignal, "afterEach", async () => {
1697
+ await applyAfterEach(hookContext);
1698
+ });
1699
+ let hasUnhandledErrors = !ignoreUnhandledErrors && unhandledErrors.size > 0, hasSomeReportsFailed = context.reporting.reports.some(
1700
+ (report) => report.status === "failed"
1701
+ ), hasStoryErrored = hasUnhandledErrors || hasSomeReportsFailed;
1702
+ await this.runPhase(
1703
+ abortSignal,
1704
+ "finished",
1705
+ async () => this.channel.emit(STORY_FINISHED, {
1706
+ storyId: id,
1707
+ status: hasStoryErrored ? "error" : "success",
1708
+ reporters: context.reporting.reports
1709
+ })
1710
+ );
1711
+ } catch (err) {
1712
+ this.phase = "errored", this.callbacks.showException(err), await this.runPhase(
1713
+ abortSignal,
1714
+ "finished",
1715
+ async () => this.channel.emit(STORY_FINISHED, {
1716
+ storyId: id,
1717
+ status: "error",
1718
+ reporters: []
1719
+ })
1720
+ );
1721
+ }
1722
+ this.rerenderEnqueued && (this.rerenderEnqueued = !1, this.render());
1723
+ }
1724
+ /**
1725
+ * Rerender the story. If the story is currently pending (loading/rendering), the rerender will be
1726
+ * enqueued, and will be executed after the current render is completed. Rerendering while playing
1727
+ * will not be enqueued, and will be executed immediately, to support rendering args changes while
1728
+ * playing.
1729
+ */
1730
+ async rerender() {
1731
+ if (this.isPending() && this.phase !== "playing")
1732
+ this.rerenderEnqueued = !0;
1733
+ else
1734
+ return this.render();
1735
+ }
1736
+ async remount() {
1737
+ return await this.teardown(), this.render({ forceRemount: !0 });
1738
+ }
1739
+ // If the story is torn down (either a new story is rendered or the docs page removes it)
1740
+ // we need to consider the fact that the initial render may not be finished
1741
+ // (possibly the loaders or the play function are still running). We use the controller
1742
+ // as a method to abort them, ASAP, but this is not foolproof as we cannot control what
1743
+ // happens inside the user's code.
1744
+ cancelRender() {
1745
+ this.abortController.abort();
1746
+ }
1747
+ cancelPlayFunction() {
1748
+ this.phase === "playing" && (this.abortController.abort(), this.runPhase(this.abortController.signal, "aborted"));
1749
+ }
1750
+ async teardown({ keepRenderedDom = !1 } = {}) {
1751
+ this.torndown = !0, this.cancelRender(), this.story && await this.store.cleanupStory(this.story);
1752
+ for (let i = 0; i < 3; i += 1) {
1753
+ if (!this.isPending()) {
1754
+ keepRenderedDom || await this.teardownRender();
1755
+ return;
1756
+ }
1757
+ await new Promise((resolve) => setTimeout(resolve, 0));
1758
+ }
1759
+ window?.location?.reload?.(), await new Promise(() => {
1760
+ });
1761
+ }
1762
+ };
1763
+
1764
+ // src/preview-api/modules/preview-web/Preview.tsx
1765
+ var { fetch } = global4, STORY_INDEX_PATH = "./index.json", Preview = class {
1766
+ constructor(importFn, getProjectAnnotations, channel = addons.getChannel(), shouldInitialize = !0) {
1767
+ this.importFn = importFn;
1768
+ this.getProjectAnnotations = getProjectAnnotations;
1769
+ this.channel = channel;
1770
+ this.storyRenders = [];
1771
+ this.storeInitializationPromise = new Promise((resolve, reject) => {
1772
+ this.resolveStoreInitializationPromise = resolve, this.rejectStoreInitializationPromise = reject;
1773
+ }), shouldInitialize && this.initialize();
1774
+ }
1775
+ // Create a proxy object for `__STORYBOOK_STORY_STORE__` and `__STORYBOOK_PREVIEW__.storyStore`
1776
+ // That proxies through to the store once ready, and errors beforehand. This means we can set
1777
+ // `__STORYBOOK_STORY_STORE__ = __STORYBOOK_PREVIEW__.storyStore` without having to wait, and
1778
+ // similarly integrators can access the `storyStore` on the preview at any time, although
1779
+ // it is considered deprecated and we will no longer allow access in 9.0
1780
+ get storyStore() {
1781
+ return new Proxy(
1782
+ {},
1783
+ {
1784
+ get: (_, method) => {
1785
+ if (this.storyStoreValue)
1786
+ return deprecate("Accessing the Story Store is deprecated and will be removed in 9.0"), this.storyStoreValue[method];
1787
+ throw new StoryStoreAccessedBeforeInitializationError();
1788
+ }
1789
+ }
1790
+ );
1791
+ }
1792
+ // INITIALIZATION
1793
+ async initialize() {
1794
+ this.setupListeners();
1795
+ try {
1796
+ let projectAnnotations = await this.getProjectAnnotationsOrRenderError();
1797
+ await this.runBeforeAllHook(projectAnnotations), await this.initializeWithProjectAnnotations(projectAnnotations);
1798
+ let userAgent = globalThis?.navigator?.userAgent;
1799
+ await this.channel.emit(PREVIEW_INITIALIZED, { userAgent });
1800
+ } catch (err) {
1801
+ this.rejectStoreInitializationPromise(err);
1802
+ }
1803
+ }
1804
+ ready() {
1805
+ return this.storeInitializationPromise;
1806
+ }
1807
+ setupListeners() {
1808
+ this.channel.on(STORY_INDEX_INVALIDATED, this.onStoryIndexChanged.bind(this)), this.channel.on(UPDATE_GLOBALS2, this.onUpdateGlobals.bind(this)), this.channel.on(UPDATE_STORY_ARGS2, this.onUpdateArgs.bind(this)), this.channel.on(ARGTYPES_INFO_REQUEST, this.onRequestArgTypesInfo.bind(this)), this.channel.on(RESET_STORY_ARGS2, this.onResetArgs.bind(this)), this.channel.on(FORCE_RE_RENDER2, this.onForceReRender.bind(this)), this.channel.on(FORCE_REMOUNT, this.onForceRemount.bind(this)), this.channel.on(STORY_HOT_UPDATED, this.onStoryHotUpdated.bind(this));
1809
+ }
1810
+ async getProjectAnnotationsOrRenderError() {
1811
+ try {
1812
+ let projectAnnotations = composeProjectAnnotationsWithCore([
1813
+ await this.getProjectAnnotations()
1814
+ ]);
1815
+ if (this.renderToCanvas = projectAnnotations.renderToCanvas, !this.renderToCanvas)
1816
+ throw new MissingRenderToCanvasError();
1817
+ return projectAnnotations;
1818
+ } catch (err) {
1819
+ throw this.renderPreviewEntryError("Error reading preview.js:", err), err;
1820
+ }
1821
+ }
1822
+ // If initialization gets as far as project annotations, this function runs.
1823
+ async initializeWithProjectAnnotations(projectAnnotations) {
1824
+ this.projectAnnotationsBeforeInitialization = projectAnnotations;
1825
+ try {
1826
+ let storyIndex = await this.getStoryIndexFromServer();
1827
+ return this.initializeWithStoryIndex(storyIndex);
1828
+ } catch (err) {
1829
+ throw this.renderPreviewEntryError("Error loading story index:", err), err;
1830
+ }
1831
+ }
1832
+ async runBeforeAllHook(projectAnnotations) {
1833
+ try {
1834
+ await this.beforeAllCleanup?.(), this.beforeAllCleanup = await projectAnnotations.beforeAll?.();
1835
+ } catch (err) {
1836
+ throw this.renderPreviewEntryError("Error in beforeAll hook:", err), err;
1837
+ }
1838
+ }
1839
+ async getStoryIndexFromServer() {
1840
+ let result = await fetch(STORY_INDEX_PATH);
1841
+ if (result.status === 200)
1842
+ return result.json();
1843
+ throw new StoryIndexFetchError({ text: await result.text() });
1844
+ }
1845
+ // If initialization gets as far as the story index, this function runs.
1846
+ initializeWithStoryIndex(storyIndex) {
1847
+ if (!this.projectAnnotationsBeforeInitialization)
1848
+ throw new Error("Cannot call initializeWithStoryIndex until project annotations resolve");
1849
+ this.storyStoreValue = new StoryStore(
1850
+ storyIndex,
1851
+ this.importFn,
1852
+ this.projectAnnotationsBeforeInitialization
1853
+ ), delete this.projectAnnotationsBeforeInitialization, this.setInitialGlobals(), this.resolveStoreInitializationPromise();
1854
+ }
1855
+ async setInitialGlobals() {
1856
+ this.emitGlobals();
1857
+ }
1858
+ emitGlobals() {
1859
+ if (!this.storyStoreValue)
1860
+ throw new CalledPreviewMethodBeforeInitializationError({ methodName: "emitGlobals" });
1861
+ let payload = {
1862
+ globals: this.storyStoreValue.userGlobals.get() || {},
1863
+ globalTypes: this.storyStoreValue.projectAnnotations.globalTypes || {}
1864
+ };
1865
+ this.channel.emit(SET_GLOBALS, payload);
1866
+ }
1867
+ // EVENT HANDLERS
1868
+ // This happens when a config file gets reloaded
1869
+ async onGetProjectAnnotationsChanged({
1870
+ getProjectAnnotations
1871
+ }) {
1872
+ delete this.previewEntryError, this.getProjectAnnotations = getProjectAnnotations;
1873
+ let projectAnnotations = await this.getProjectAnnotationsOrRenderError();
1874
+ if (await this.runBeforeAllHook(projectAnnotations), !this.storyStoreValue) {
1875
+ await this.initializeWithProjectAnnotations(projectAnnotations);
1876
+ return;
1877
+ }
1878
+ this.storyStoreValue.setProjectAnnotations(projectAnnotations), this.emitGlobals();
1879
+ }
1880
+ async onStoryIndexChanged() {
1881
+ if (delete this.previewEntryError, !(!this.storyStoreValue && !this.projectAnnotationsBeforeInitialization))
1882
+ try {
1883
+ let storyIndex = await this.getStoryIndexFromServer();
1884
+ if (this.projectAnnotationsBeforeInitialization) {
1885
+ this.initializeWithStoryIndex(storyIndex);
1886
+ return;
1887
+ }
1888
+ await this.onStoriesChanged({ storyIndex });
1889
+ } catch (err) {
1890
+ throw this.renderPreviewEntryError("Error loading story index:", err), err;
1891
+ }
1892
+ }
1893
+ // This happens when a glob gets HMR-ed
1894
+ async onStoriesChanged({
1895
+ importFn,
1896
+ storyIndex
1897
+ }) {
1898
+ if (!this.storyStoreValue)
1899
+ throw new CalledPreviewMethodBeforeInitializationError({ methodName: "onStoriesChanged" });
1900
+ await this.storyStoreValue.onStoriesChanged({ importFn, storyIndex });
1901
+ }
1902
+ async onUpdateGlobals({
1903
+ globals: updatedGlobals,
1904
+ currentStory
1905
+ }) {
1906
+ if (this.storyStoreValue || await this.storeInitializationPromise, !this.storyStoreValue)
1907
+ throw new CalledPreviewMethodBeforeInitializationError({ methodName: "onUpdateGlobals" });
1908
+ if (this.storyStoreValue.userGlobals.update(updatedGlobals), currentStory) {
1909
+ let { initialGlobals, storyGlobals, userGlobals, globals } = this.storyStoreValue.getStoryContext(currentStory);
1910
+ this.channel.emit(GLOBALS_UPDATED, {
1911
+ initialGlobals,
1912
+ userGlobals,
1913
+ storyGlobals,
1914
+ globals
1915
+ });
1916
+ } else {
1917
+ let { initialGlobals, globals } = this.storyStoreValue.userGlobals;
1918
+ this.channel.emit(GLOBALS_UPDATED, {
1919
+ initialGlobals,
1920
+ userGlobals: globals,
1921
+ storyGlobals: {},
1922
+ globals
1923
+ });
1924
+ }
1925
+ await Promise.all(this.storyRenders.map((r) => r.rerender()));
1926
+ }
1927
+ async onUpdateArgs({ storyId, updatedArgs }) {
1928
+ if (!this.storyStoreValue)
1929
+ throw new CalledPreviewMethodBeforeInitializationError({ methodName: "onUpdateArgs" });
1930
+ this.storyStoreValue.args.update(storyId, updatedArgs), await Promise.all(
1931
+ this.storyRenders.filter((r) => r.id === storyId && !r.renderOptions.forceInitialArgs).map(
1932
+ (r) => (
1933
+ // We only run the play function, with in a force remount.
1934
+ // But when mount is destructured, the rendering happens inside of the play function.
1935
+ r.story && r.story.usesMount ? r.remount() : r.rerender()
1936
+ )
1937
+ )
1938
+ ), this.channel.emit(STORY_ARGS_UPDATED, {
1939
+ storyId,
1940
+ args: this.storyStoreValue.args.get(storyId)
1941
+ });
1942
+ }
1943
+ async onRequestArgTypesInfo({ id, payload }) {
1944
+ try {
1945
+ await this.storeInitializationPromise;
1946
+ let story = await this.storyStoreValue?.loadStory(payload);
1947
+ this.channel.emit(ARGTYPES_INFO_RESPONSE, {
1948
+ id,
1949
+ success: !0,
1950
+ payload: { argTypes: story?.argTypes || {} },
1951
+ error: null
1952
+ });
1953
+ } catch (e) {
1954
+ this.channel.emit(ARGTYPES_INFO_RESPONSE, {
1955
+ id,
1956
+ success: !1,
1957
+ error: e?.message
1958
+ });
1959
+ }
1960
+ }
1961
+ async onResetArgs({ storyId, argNames }) {
1962
+ if (!this.storyStoreValue)
1963
+ throw new CalledPreviewMethodBeforeInitializationError({ methodName: "onResetArgs" });
1964
+ let story = this.storyRenders.find((r) => r.id === storyId)?.story || await this.storyStoreValue.loadStory({ storyId }), updatedArgs = (argNames || [
1965
+ .../* @__PURE__ */ new Set([
1966
+ ...Object.keys(story.initialArgs),
1967
+ ...Object.keys(this.storyStoreValue.args.get(storyId))
1968
+ ])
1969
+ ]).reduce((acc, argName) => (acc[argName] = story.initialArgs[argName], acc), {});
1970
+ await this.onUpdateArgs({ storyId, updatedArgs });
1971
+ }
1972
+ // ForceReRender does not include a story id, so we simply must
1973
+ // re-render all stories in case they are relevant
1974
+ async onForceReRender() {
1975
+ await Promise.all(this.storyRenders.map((r) => r.rerender()));
1976
+ }
1977
+ async onForceRemount({ storyId }) {
1978
+ await Promise.all(this.storyRenders.filter((r) => r.id === storyId).map((r) => r.remount()));
1979
+ }
1980
+ async onStoryHotUpdated() {
1981
+ await Promise.all(this.storyRenders.map((r) => r.cancelPlayFunction()));
1982
+ }
1983
+ // Used by docs to render a story to a given element
1984
+ // Note this short-circuits the `prepare()` phase of the StoryRender,
1985
+ // main to be consistent with the previous behaviour. In the future,
1986
+ // we will change it to go ahead and load the story, which will end up being
1987
+ // "instant", although async.
1988
+ renderStoryToElement(story, element, callbacks, options) {
1989
+ if (!this.renderToCanvas || !this.storyStoreValue)
1990
+ throw new CalledPreviewMethodBeforeInitializationError({
1991
+ methodName: "renderStoryToElement"
1992
+ });
1993
+ let render = new StoryRender(
1994
+ this.channel,
1995
+ this.storyStoreValue,
1996
+ this.renderToCanvas,
1997
+ callbacks,
1998
+ story.id,
1999
+ "docs",
2000
+ options,
2001
+ story
2002
+ );
2003
+ return render.renderToElement(element), this.storyRenders.push(render), async () => {
2004
+ await this.teardownRender(render);
2005
+ };
2006
+ }
2007
+ async teardownRender(render, { viewModeChanged } = {}) {
2008
+ this.storyRenders = this.storyRenders.filter((r) => r !== render), await render?.teardown?.({ viewModeChanged });
2009
+ }
2010
+ // API
2011
+ async loadStory({ storyId }) {
2012
+ if (!this.storyStoreValue)
2013
+ throw new CalledPreviewMethodBeforeInitializationError({ methodName: "loadStory" });
2014
+ return this.storyStoreValue.loadStory({ storyId });
2015
+ }
2016
+ getStoryContext(story, { forceInitialArgs = !1 } = {}) {
2017
+ if (!this.storyStoreValue)
2018
+ throw new CalledPreviewMethodBeforeInitializationError({ methodName: "getStoryContext" });
2019
+ return this.storyStoreValue.getStoryContext(story, { forceInitialArgs });
2020
+ }
2021
+ async extract(options) {
2022
+ if (!this.storyStoreValue)
2023
+ throw new CalledPreviewMethodBeforeInitializationError({ methodName: "extract" });
2024
+ if (this.previewEntryError)
2025
+ throw this.previewEntryError;
2026
+ return await this.storyStoreValue.cacheAllCSFFiles(), this.storyStoreValue.extract(options);
2027
+ }
2028
+ // UTILITIES
2029
+ renderPreviewEntryError(reason, err) {
2030
+ this.previewEntryError = err, logger4.error(reason), logger4.error(err), this.channel.emit(CONFIG_ERROR, err);
2031
+ }
2032
+ };
2033
+
2034
+ // src/preview-api/modules/preview-web/PreviewWeb.tsx
2035
+ import { global as global9 } from "@storybook/global";
2036
+
2037
+ // src/preview-api/modules/preview-web/PreviewWithSelection.tsx
2038
+ import { logger as logger5 } from "@aussieljk/forkbook/internal/client-logger";
2039
+ import {
2040
+ CURRENT_STORY_WAS_SET,
2041
+ DOCS_PREPARED,
2042
+ GLOBALS_UPDATED as GLOBALS_UPDATED2,
2043
+ NAVIGATE_URL,
2044
+ PRELOAD_ENTRIES,
2045
+ PREVIEW_KEYDOWN,
2046
+ SET_CURRENT_STORY,
2047
+ STORY_CHANGED,
2048
+ STORY_ERRORED,
2049
+ STORY_MISSING,
2050
+ STORY_PREPARED,
2051
+ STORY_RENDER_PHASE_CHANGED as STORY_RENDER_PHASE_CHANGED3,
2052
+ STORY_SPECIFIED,
2053
+ STORY_THREW_EXCEPTION,
2054
+ STORY_UNCHANGED,
2055
+ UPDATE_QUERY_PARAMS
2056
+ } from "@aussieljk/forkbook/internal/core-events";
2057
+ import {
2058
+ CalledPreviewMethodBeforeInitializationError as CalledPreviewMethodBeforeInitializationError2,
2059
+ EmptyIndexError,
2060
+ MdxFileWithNoCsfReferencesError,
2061
+ NoStoryMatchError
2062
+ } from "@aussieljk/forkbook/internal/preview-errors";
2063
+
2064
+ // src/shared/utils/story-index-filters.ts
2065
+ function isMdxEntry({ tags }) {
2066
+ return tags?.includes(Tag.UNATTACHED_MDX) || tags?.includes(Tag.ATTACHED_MDX);
2067
+ }
2068
+
2069
+ // src/preview-api/modules/preview-web/embedMode.ts
2070
+ var shouldEmbed = ({ search }) => new URLSearchParams(search).get("embed") === "true", shouldAutoplay = ({ search }) => !shouldEmbed({ search });
2071
+
2072
+ // src/preview-api/modules/preview-web/getEmbedResizeViewport.ts
2073
+ var getEmbedResizeViewport = (storyStore, render, reference) => {
2074
+ if (!storyStore || !render?.story)
2075
+ return;
2076
+ let { globals, storyGlobals, userGlobals, parameters } = storyStore.getStoryContext(
2077
+ render.story
2078
+ ), viewportParameters = parameters[PARAM_KEY];
2079
+ return toResolvedViewportDimensions(
2080
+ resolveViewport({
2081
+ globals,
2082
+ storyGlobals,
2083
+ userGlobals,
2084
+ options: viewportParameters?.options ?? MINIMAL_VIEWPORTS,
2085
+ disable: viewportParameters?.disable ?? !1,
2086
+ viewMode: "story"
2087
+ }),
2088
+ reference
2089
+ );
2090
+ };
2091
+
2092
+ // src/preview-api/modules/preview-web/render/CsfDocsRender.ts
2093
+ import { DOCS_RENDERED } from "@aussieljk/forkbook/internal/core-events";
2094
+
2095
+ // src/preview-api/modules/preview-web/docs-context/DocsContext.ts
2096
+ import { isStory as isStory3 } from "@aussieljk/forkbook/internal/csf";
2097
+ import { dedent as dedent3 } from "ts-dedent";
2098
+ var DocsContext = class {
2099
+ constructor(channel, store, renderStoryToElement, csfFiles) {
2100
+ this.channel = channel;
2101
+ this.store = store;
2102
+ this.renderStoryToElement = renderStoryToElement;
2103
+ this.storyIdByName = (storyName) => {
2104
+ let storyId = this.nameToStoryId.get(storyName);
2105
+ if (storyId)
2106
+ return storyId;
2107
+ throw new Error(`No story found with that name: ${storyName}`);
2108
+ };
2109
+ this.componentStories = () => this.componentStoriesValue;
2110
+ this.getComponentId = (component) => {
2111
+ for (let csfFile of new Set(this.exportsToCSFFile.values()))
2112
+ if (csfFile.meta.component === component)
2113
+ return csfFile.meta.id;
2114
+ };
2115
+ this.componentStoriesFromCSFFile = (csfFile) => this.store.componentStoriesFromCSFFile({ csfFile });
2116
+ this.storyById = (storyId) => {
2117
+ if (!storyId) {
2118
+ if (!this.primaryStory)
2119
+ throw new Error(
2120
+ "No primary story defined for docs entry. Did you forget to use `<Meta>`?"
2121
+ );
2122
+ return this.primaryStory;
2123
+ }
2124
+ let csfFile = this.storyIdToCSFFile.get(storyId);
2125
+ if (!csfFile)
2126
+ throw new Error(`Called \`storyById\` for story that was never loaded: ${storyId}`);
2127
+ return this.store.storyFromCSFFile({ storyId, csfFile });
2128
+ };
2129
+ this.getStoryContext = (story) => ({
2130
+ ...this.store.getStoryContext(story),
2131
+ loaded: {},
2132
+ viewMode: "docs"
2133
+ });
2134
+ this.loadStory = (id) => this.store.loadStory({ storyId: id });
2135
+ this.componentStoriesValue = [], this.storyIdToCSFFile = /* @__PURE__ */ new Map(), this.exportToStory = /* @__PURE__ */ new Map(), this.exportsToCSFFile = /* @__PURE__ */ new Map(), this.nameToStoryId = /* @__PURE__ */ new Map(), this.attachedCSFFiles = /* @__PURE__ */ new Set(), csfFiles.forEach((csfFile, index) => {
2136
+ this.referenceCSFFile(csfFile);
2137
+ });
2138
+ }
2139
+ // This docs entry references this CSF file and can synchronously load the stories, as well
2140
+ // as reference them by module export. If the CSF is part of the "component" stories, they
2141
+ // can also be referenced by name and are in the componentStories list.
2142
+ referenceCSFFile(csfFile) {
2143
+ this.exportsToCSFFile.set(csfFile.moduleExports, csfFile), "default" in csfFile.moduleExports && this.exportsToCSFFile.set(csfFile.moduleExports.default, csfFile), this.store.componentStoriesFromCSFFile({ csfFile }).forEach((story) => {
2144
+ let annotation = csfFile.stories[story.id];
2145
+ this.storyIdToCSFFile.set(annotation.id, csfFile), this.exportToStory.set(annotation.moduleExport, story);
2146
+ });
2147
+ }
2148
+ attachCSFFile(csfFile) {
2149
+ if (!this.exportsToCSFFile.has(csfFile.moduleExports))
2150
+ throw new Error("Cannot attach a CSF file that has not been referenced");
2151
+ if (this.attachedCSFFiles.has(csfFile))
2152
+ return;
2153
+ this.attachedCSFFiles.add(csfFile), this.store.componentStoriesFromCSFFile({ csfFile }).forEach((story) => {
2154
+ this.nameToStoryId.set(story.name, story.id), this.componentStoriesValue.push(story), this.primaryStory || (this.primaryStory = story);
2155
+ });
2156
+ }
2157
+ referenceMeta(metaExports, attach) {
2158
+ let resolved = this.resolveModuleExport(metaExports);
2159
+ if (resolved.type !== "meta")
2160
+ throw new Error(
2161
+ "<Meta of={} /> must reference a CSF file module export or meta export. Did you mistakenly reference your component instead of your CSF file?"
2162
+ );
2163
+ attach && this.attachCSFFile(resolved.csfFile);
2164
+ }
2165
+ get projectAnnotations() {
2166
+ let { projectAnnotations } = this.store;
2167
+ if (!projectAnnotations)
2168
+ throw new Error("Can't get projectAnnotations from DocsContext before they are initialized");
2169
+ return projectAnnotations;
2170
+ }
2171
+ resolveAttachedModuleExportType(moduleExportType) {
2172
+ if (moduleExportType === "story") {
2173
+ if (!this.primaryStory)
2174
+ throw new Error(
2175
+ "No primary story attached to this docs file, did you forget to use <Meta of={} />?"
2176
+ );
2177
+ return { type: "story", story: this.primaryStory };
2178
+ }
2179
+ if (this.attachedCSFFiles.size === 0)
2180
+ throw new Error(
2181
+ "No CSF file attached to this docs file, did you forget to use <Meta of={} />?"
2182
+ );
2183
+ let firstAttachedCSFFile = Array.from(this.attachedCSFFiles)[0];
2184
+ if (moduleExportType === "meta")
2185
+ return { type: "meta", csfFile: firstAttachedCSFFile };
2186
+ let { component } = firstAttachedCSFFile.meta;
2187
+ if (!component)
2188
+ throw new Error(
2189
+ "Attached CSF file does not defined a component, did you forget to export one?"
2190
+ );
2191
+ return { type: "component", component };
2192
+ }
2193
+ resolveModuleExport(moduleExportOrType) {
2194
+ let csfFile = this.exportsToCSFFile.get(moduleExportOrType);
2195
+ if (!csfFile && moduleExportOrType && typeof moduleExportOrType == "object" && "default" in moduleExportOrType && (csfFile = this.exportsToCSFFile.get(moduleExportOrType.default)), !csfFile && moduleExportOrType && typeof moduleExportOrType == "object" && !isStory3(moduleExportOrType)) {
2196
+ let matchedCSFFile;
2197
+ for (let exportValue of Object.values(moduleExportOrType)) {
2198
+ let story2 = this.exportToStory.get(
2199
+ isStory3(exportValue) ? exportValue.input : exportValue
2200
+ );
2201
+ if (!story2)
2202
+ continue;
2203
+ let storyCSFFile = this.storyIdToCSFFile.get(story2.id);
2204
+ if (storyCSFFile) {
2205
+ if (!matchedCSFFile)
2206
+ matchedCSFFile = storyCSFFile;
2207
+ else if (matchedCSFFile !== storyCSFFile) {
2208
+ matchedCSFFile = void 0;
2209
+ break;
2210
+ }
2211
+ }
2212
+ }
2213
+ csfFile = matchedCSFFile;
2214
+ }
2215
+ if (csfFile)
2216
+ return { type: "meta", csfFile };
2217
+ let story = this.exportToStory.get(
2218
+ isStory3(moduleExportOrType) ? moduleExportOrType.input : moduleExportOrType
2219
+ );
2220
+ return story ? { type: "story", story } : { type: "component", component: moduleExportOrType };
2221
+ }
2222
+ resolveOf(moduleExportOrType, validTypes = []) {
2223
+ let resolved;
2224
+ if (["component", "meta", "story"].includes(moduleExportOrType)) {
2225
+ let type = moduleExportOrType;
2226
+ resolved = this.resolveAttachedModuleExportType(type);
2227
+ } else
2228
+ resolved = this.resolveModuleExport(moduleExportOrType);
2229
+ if (validTypes.length && !validTypes.includes(resolved.type)) {
2230
+ let prettyType = resolved.type === "component" ? "component or unknown" : resolved.type;
2231
+ throw new Error(dedent3`Invalid value passed to the 'of' prop. The value was resolved to a '${prettyType}' type but the only types for this block are: ${validTypes.join(
2232
+ ", "
2233
+ )}.
2234
+ - Did you pass a component to the 'of' prop when the block only supports a story or a meta?
2235
+ - ... or vice versa?
2236
+ - Did you pass a story, CSF file or meta to the 'of' prop that is not indexed, ie. is not targeted by the 'stories' globs in the main configuration?`);
2237
+ }
2238
+ switch (resolved.type) {
2239
+ case "component":
2240
+ return {
2241
+ ...resolved,
2242
+ projectAnnotations: this.projectAnnotations
2243
+ };
2244
+ case "meta":
2245
+ return {
2246
+ ...resolved,
2247
+ preparedMeta: this.store.preparedMetaFromCSFFile({ csfFile: resolved.csfFile })
2248
+ };
2249
+ default:
2250
+ return resolved;
2251
+ }
2252
+ }
2253
+ };
2254
+
2255
+ // src/preview-api/modules/preview-web/render/CsfDocsRender.ts
2256
+ var CsfDocsRender = class {
2257
+ constructor(channel, store, entry, callbacks) {
2258
+ this.channel = channel;
2259
+ this.store = store;
2260
+ this.entry = entry;
2261
+ this.callbacks = callbacks;
2262
+ this.type = "docs";
2263
+ this.subtype = "csf";
2264
+ this.torndown = !1;
2265
+ this.disableKeyListeners = !1;
2266
+ this.preparing = !1;
2267
+ this.id = entry.id, this.renderId = Date.now();
2268
+ }
2269
+ isPreparing() {
2270
+ return this.preparing;
2271
+ }
2272
+ async prepare() {
2273
+ this.preparing = !0;
2274
+ let { entryExports, csfFiles = [] } = await this.store.loadEntry(this.id);
2275
+ if (this.torndown)
2276
+ throw PREPARE_ABORTED;
2277
+ let { importPath, title } = this.entry, primaryCsfFile = this.store.processCSFFileWithCache(
2278
+ entryExports,
2279
+ importPath,
2280
+ title
2281
+ ), primaryStoryId = Object.keys(primaryCsfFile.stories)[0];
2282
+ this.story = this.store.storyFromCSFFile({ storyId: primaryStoryId, csfFile: primaryCsfFile }), this.csfFiles = [primaryCsfFile, ...csfFiles], this.preparing = !1;
2283
+ }
2284
+ isEqual(other) {
2285
+ return !!(this.id === other.id && this.story && this.story === other.story);
2286
+ }
2287
+ docsContext(renderStoryToElement) {
2288
+ if (!this.csfFiles)
2289
+ throw new Error("Cannot render docs before preparing");
2290
+ let docsContext = new DocsContext(
2291
+ this.channel,
2292
+ this.store,
2293
+ renderStoryToElement,
2294
+ this.csfFiles
2295
+ );
2296
+ return this.csfFiles.forEach((csfFile) => docsContext.attachCSFFile(csfFile)), docsContext.filterByAutodocs = !isMdxEntry(this.entry), docsContext;
2297
+ }
2298
+ async renderToElement(canvasElement, renderStoryToElement) {
2299
+ if (!this.story || !this.csfFiles)
2300
+ throw new Error("Cannot render docs before preparing");
2301
+ let docsContext = this.docsContext(renderStoryToElement), { docs: docsParameter } = this.story.parameters || {};
2302
+ if (!docsParameter)
2303
+ throw new Error(
2304
+ "Cannot render a story in viewMode=docs if `@aussieljk/forkbook/addon-docs` is not installed"
2305
+ );
2306
+ let renderer = await docsParameter.renderer(), { render } = renderer, renderDocs = async () => {
2307
+ try {
2308
+ await render(docsContext, docsParameter, canvasElement), this.channel.emit(DOCS_RENDERED, this.id);
2309
+ } catch (err) {
2310
+ this.callbacks.showException(err);
2311
+ }
2312
+ };
2313
+ return this.rerender = async () => renderDocs(), this.teardownRender = async ({ viewModeChanged }) => {
2314
+ !viewModeChanged || !canvasElement || renderer.unmount(canvasElement);
2315
+ }, renderDocs();
2316
+ }
2317
+ async teardown({ viewModeChanged } = {}) {
2318
+ this.teardownRender?.({ viewModeChanged }), this.torndown = !0;
2319
+ }
2320
+ };
2321
+
2322
+ // src/preview-api/modules/preview-web/render/MdxDocsRender.ts
2323
+ import { DOCS_RENDERED as DOCS_RENDERED2 } from "@aussieljk/forkbook/internal/core-events";
2324
+ var MdxDocsRender = class {
2325
+ constructor(channel, store, entry, callbacks) {
2326
+ this.channel = channel;
2327
+ this.store = store;
2328
+ this.entry = entry;
2329
+ this.callbacks = callbacks;
2330
+ this.type = "docs";
2331
+ this.subtype = "mdx";
2332
+ this.torndown = !1;
2333
+ this.disableKeyListeners = !1;
2334
+ this.preparing = !1;
2335
+ this.id = entry.id, this.renderId = Date.now();
2336
+ }
2337
+ isPreparing() {
2338
+ return this.preparing;
2339
+ }
2340
+ async prepare() {
2341
+ this.preparing = !0;
2342
+ let { entryExports, csfFiles = [] } = await this.store.loadEntry(this.id);
2343
+ if (this.torndown)
2344
+ throw PREPARE_ABORTED;
2345
+ if (this.csfFiles = csfFiles, this.exports = entryExports, this.attachedCsfFile = void 0, this.attachedStory = void 0, this.entry.tags?.includes(Tag.ATTACHED_MDX)) {
2346
+ this.attachedCsfFile = csfFiles[0];
2347
+ let primaryStoryId = this.attachedCsfFile && Object.keys(this.attachedCsfFile.stories)[0];
2348
+ this.attachedCsfFile && primaryStoryId && (this.attachedStory = this.store.storyFromCSFFile({
2349
+ storyId: primaryStoryId,
2350
+ csfFile: this.attachedCsfFile
2351
+ }));
2352
+ }
2353
+ this.preparing = !1;
2354
+ }
2355
+ isEqual(other) {
2356
+ return !!(this.id === other.id && this.exports && this.exports === other.exports);
2357
+ }
2358
+ docsContext(renderStoryToElement) {
2359
+ if (!this.csfFiles)
2360
+ throw new Error("Cannot render docs before preparing");
2361
+ let docsContext = new DocsContext(
2362
+ this.channel,
2363
+ this.store,
2364
+ renderStoryToElement,
2365
+ this.csfFiles
2366
+ );
2367
+ return this.attachedCsfFile && docsContext.attachCSFFile(this.attachedCsfFile), docsContext.filterByAutodocs = !isMdxEntry(this.entry), docsContext;
2368
+ }
2369
+ async renderToElement(canvasElement, renderStoryToElement) {
2370
+ if (!this.exports || !this.csfFiles || !this.store.projectAnnotations)
2371
+ throw new Error("Cannot render docs before preparing");
2372
+ let docsContext = this.docsContext(renderStoryToElement), { docs } = this.store.projectAnnotations.parameters ?? {}, baseDocsParameter = this.attachedStory?.parameters?.docs ?? docs;
2373
+ if (!baseDocsParameter)
2374
+ throw new Error(
2375
+ "Cannot render a story in viewMode=docs if `@aussieljk/forkbook/addon-docs` is not installed"
2376
+ );
2377
+ let docsParameter = { ...baseDocsParameter, page: this.exports.default }, renderer = await baseDocsParameter.renderer(), { render } = renderer, renderDocs = async () => {
2378
+ try {
2379
+ await render(docsContext, docsParameter, canvasElement), this.channel.emit(DOCS_RENDERED2, this.id);
2380
+ } catch (err) {
2381
+ this.callbacks.showException(err);
2382
+ }
2383
+ };
2384
+ return this.rerender = async () => renderDocs(), this.teardownRender = async ({ viewModeChanged } = {}) => {
2385
+ !viewModeChanged || !canvasElement || (renderer.unmount(canvasElement), this.torndown = !0);
2386
+ }, renderDocs();
2387
+ }
2388
+ async teardown({ viewModeChanged } = {}) {
2389
+ this.teardownRender?.({ viewModeChanged }), this.torndown = !0;
2390
+ }
2391
+ };
2392
+
2393
+ // src/preview-api/modules/preview-web/setupContentResizeBroadcast.ts
2394
+ import { global as global6 } from "@storybook/global";
2395
+
2396
+ // src/shared/constants/iframe-resize.ts
2397
+ var IFRAME_RESIZE_CONTEXT = "iframe.resize", IFRAME_RESIZE_REQUEST_CONTEXT = "iframe.resize.request";
2398
+ var iframeResizeViewportsEqual = (left, right) => left === right ? !0 : !left || !right ? !left && !right : left.name === right.name && left.value === right.value && left.width === right.width && left.height === right.height;
2399
+
2400
+ // src/preview-api/modules/preview-web/setupStoryFreezer.ts
2401
+ import {
2402
+ STORY_HOT_UPDATED as STORY_HOT_UPDATED2,
2403
+ STORY_RENDER_PHASE_CHANGED as STORY_RENDER_PHASE_CHANGED2
2404
+ } from "@aussieljk/forkbook/internal/core-events";
2405
+ import { global as global5 } from "@storybook/global";
2406
+ var FREEZE_STYLE_ID = "storybook-freeze-after-finished", PRE_FREEZE_STYLE_ID = "storybook-freeze-end-frame-preload", tryReplaceProperty = (target, key, value) => {
2407
+ try {
2408
+ let descriptor = Object.getOwnPropertyDescriptor(target, key);
2409
+ if (descriptor?.configurable === !1) {
2410
+ descriptor.writable && Reflect.set(target, key, value);
2411
+ return;
2412
+ }
2413
+ Object.defineProperty(target, key, { configurable: !0, writable: !0, value });
2414
+ } catch {
2415
+ }
2416
+ }, getQueryParam = (search, key) => new URLSearchParams(search).get(key), shouldFreeze = ({ search }) => {
2417
+ let freeze = getQueryParam(search, "freeze"), viewMode = getQueryParam(search, "viewMode") ?? "story";
2418
+ return freeze === "finished" && viewMode === "story";
2419
+ }, stripScriptElements = (documentRef) => {
2420
+ Array.from(documentRef.querySelectorAll("script")).forEach((script) => {
2421
+ script.remove();
2422
+ });
2423
+ }, stripInlineEventHandlers = (documentRef) => {
2424
+ Array.from(documentRef.querySelectorAll("*")).forEach((element) => {
2425
+ Array.from(element.attributes).filter((attr) => attr.name.toLowerCase().startsWith("on")).forEach((attr) => {
2426
+ element.removeAttribute(attr.name);
2427
+ });
2428
+ });
2429
+ }, addFreezeStyles = (documentRef) => {
2430
+ if (documentRef.getElementById(FREEZE_STYLE_ID))
2431
+ return;
2432
+ let style = documentRef.createElement("style");
2433
+ style.id = FREEZE_STYLE_ID, style.textContent = `
2434
+ *, *::before, *::after {
2435
+ animation-play-state: paused !important;
2436
+ transition: none !important;
2437
+ caret-color: transparent !important;
2438
+ }
2439
+ `, documentRef.head?.appendChild(style);
2440
+ }, addPreFreezeStyles = (documentRef) => {
2441
+ if (documentRef.getElementById(PRE_FREEZE_STYLE_ID))
2442
+ return;
2443
+ let style = documentRef.createElement("style");
2444
+ style.id = PRE_FREEZE_STYLE_ID, style.textContent = `
2445
+ *, *::before, *::after {
2446
+ animation-delay: 0s !important;
2447
+ animation-direction: reverse !important;
2448
+ animation-play-state: paused !important;
2449
+ transition: none !important;
2450
+ caret-color: transparent !important;
2451
+ }
2452
+ `, documentRef.head?.appendChild(style);
2453
+ }, finishAndPauseAnimations = (documentRef) => {
2454
+ if (typeof documentRef.getAnimations != "function")
2455
+ return;
2456
+ documentRef.getAnimations().forEach((animation) => {
2457
+ try {
2458
+ animation.finish();
2459
+ } catch {
2460
+ }
2461
+ try {
2462
+ animation.pause();
2463
+ } catch {
2464
+ }
2465
+ });
2466
+ }, blockInteractions = (documentRef) => {
2467
+ let blockedEvents = [
2468
+ "click",
2469
+ "dblclick",
2470
+ "mousedown",
2471
+ "mouseup",
2472
+ "pointerdown",
2473
+ "pointerup",
2474
+ "touchstart",
2475
+ "touchend",
2476
+ "keydown",
2477
+ "keyup",
2478
+ "keypress",
2479
+ "input",
2480
+ "change",
2481
+ "submit"
2482
+ ], stopEvent = (event) => {
2483
+ event.stopImmediatePropagation(), event.stopPropagation(), event.cancelable && event.preventDefault();
2484
+ };
2485
+ blockedEvents.forEach((eventName) => {
2486
+ documentRef.addEventListener(eventName, stopEvent, { capture: !0 });
2487
+ });
2488
+ }, createStoryFreezer = (windowRef, documentRef) => {
2489
+ let frozen = !1, freezing = !1, trackedTimeouts = /* @__PURE__ */ new Set(), trackedIntervals = /* @__PURE__ */ new Set(), trackedRafs = /* @__PURE__ */ new Set(), originalSetTimeout = windowRef.setTimeout.bind(windowRef), originalClearTimeout = windowRef.clearTimeout.bind(windowRef), originalSetInterval = windowRef.setInterval.bind(windowRef), originalClearInterval = windowRef.clearInterval.bind(windowRef), originalRequestAnimationFrame = windowRef.requestAnimationFrame.bind(windowRef), originalCancelAnimationFrame = windowRef.cancelAnimationFrame.bind(windowRef), originalQueueMicrotask = typeof windowRef.queueMicrotask == "function" ? windowRef.queueMicrotask.bind(windowRef) : (callback) => {
2490
+ originalSetTimeout(callback, 0);
2491
+ }, setTimeoutWrapper = ((handler, timeout, ...args) => {
2492
+ if (frozen || freezing)
2493
+ return -1;
2494
+ let timerId = originalSetTimeout(handler, timeout, ...args);
2495
+ return trackedTimeouts.add(timerId), timerId;
2496
+ }), clearTimeoutWrapper = ((id) => (id !== void 0 && trackedTimeouts.delete(id), originalClearTimeout(id))), setIntervalWrapper = ((handler, timeout, ...args) => {
2497
+ if (frozen || freezing)
2498
+ return -1;
2499
+ let timerId = originalSetInterval(handler, timeout, ...args);
2500
+ return trackedIntervals.add(timerId), timerId;
2501
+ }), clearIntervalWrapper = ((id) => (id !== void 0 && trackedIntervals.delete(id), originalClearInterval(id))), requestAnimationFrameWrapper = ((callback) => {
2502
+ if (frozen || freezing)
2503
+ return -1;
2504
+ let rafId = originalRequestAnimationFrame(callback);
2505
+ return trackedRafs.add(rafId), rafId;
2506
+ }), cancelAnimationFrameWrapper = ((id) => (trackedRafs.delete(id), originalCancelAnimationFrame(id))), queueMicrotaskWrapper = ((callback) => {
2507
+ frozen || freezing || originalQueueMicrotask(callback);
2508
+ });
2509
+ return tryReplaceProperty(windowRef, "setTimeout", setTimeoutWrapper), tryReplaceProperty(windowRef, "clearTimeout", clearTimeoutWrapper), tryReplaceProperty(windowRef, "setInterval", setIntervalWrapper), tryReplaceProperty(windowRef, "clearInterval", clearIntervalWrapper), tryReplaceProperty(windowRef, "requestAnimationFrame", requestAnimationFrameWrapper), tryReplaceProperty(windowRef, "cancelAnimationFrame", cancelAnimationFrameWrapper), tryReplaceProperty(windowRef, "queueMicrotask", queueMicrotaskWrapper), { freeze: () => {
2510
+ if (!(frozen || freezing)) {
2511
+ freezing = !0;
2512
+ try {
2513
+ trackedTimeouts.forEach((timerId) => {
2514
+ originalClearTimeout(timerId);
2515
+ }), trackedIntervals.forEach((intervalId) => {
2516
+ originalClearInterval(intervalId);
2517
+ }), trackedRafs.forEach((rafId) => {
2518
+ originalCancelAnimationFrame(rafId);
2519
+ }), trackedTimeouts.clear(), trackedIntervals.clear(), trackedRafs.clear(), finishAndPauseAnimations(documentRef), stripScriptElements(documentRef), addFreezeStyles(documentRef), stripInlineEventHandlers(documentRef), blockInteractions(documentRef);
2520
+ } finally {
2521
+ frozen = !0;
2522
+ }
2523
+ }
2524
+ } };
2525
+ }, setupStoryFreezer = (channel, options = {}) => {
2526
+ let windowRef = global5.window, documentRef = global5.document;
2527
+ if (!windowRef || !documentRef || !shouldFreeze({ search: documentRef.location.search }))
2528
+ return !1;
2529
+ addPreFreezeStyles(documentRef);
2530
+ let freezer = createStoryFreezer(windowRef, documentRef), notifiedFrozen = !1;
2531
+ return channel.on(STORY_RENDER_PHASE_CHANGED2, ({ newPhase }) => {
2532
+ if (newPhase === "finished") {
2533
+ let runFreeze = () => {
2534
+ notifiedFrozen || (freezer.freeze(), notifiedFrozen = !0, options.onFrozen?.());
2535
+ };
2536
+ typeof windowRef.queueMicrotask == "function" ? windowRef.queueMicrotask(runFreeze) : windowRef.setTimeout(runFreeze, 0);
2537
+ }
2538
+ }), channel.on(STORY_HOT_UPDATED2, () => {
2539
+ windowRef.location.reload();
2540
+ }), !0;
2541
+ };
2542
+
2543
+ // src/preview-api/modules/preview-web/setupContentResizeBroadcast.ts
2544
+ var EMBED_STYLE_ID = "storybook-embed-sizing", EMBED_UI_STYLE_ID = "storybook-embed-ui", IGNORE_TAGS = /* @__PURE__ */ new Set([
2545
+ "area",
2546
+ "base",
2547
+ "body",
2548
+ "head",
2549
+ "link",
2550
+ "map",
2551
+ "meta",
2552
+ "nobr",
2553
+ "optgroup",
2554
+ "option",
2555
+ "script",
2556
+ "style",
2557
+ "template",
2558
+ "title",
2559
+ "track",
2560
+ "wbr"
2561
+ ]), REPLACED_OR_CONTROL_TAGS = /* @__PURE__ */ new Set([
2562
+ "button",
2563
+ "canvas",
2564
+ "embed",
2565
+ "iframe",
2566
+ "img",
2567
+ "input",
2568
+ "object",
2569
+ "select",
2570
+ "svg",
2571
+ "textarea",
2572
+ "video"
2573
+ ]), BLOCK_LEVEL_TAGS = [
2574
+ "address",
2575
+ "article",
2576
+ "aside",
2577
+ "blockquote",
2578
+ "details",
2579
+ "dialog",
2580
+ "div",
2581
+ "dl",
2582
+ "fieldset",
2583
+ "figcaption",
2584
+ "figure",
2585
+ "footer",
2586
+ "form",
2587
+ "h1",
2588
+ "h2",
2589
+ "h3",
2590
+ "h4",
2591
+ "h5",
2592
+ "h6",
2593
+ "header",
2594
+ "hr",
2595
+ "li",
2596
+ "main",
2597
+ "nav",
2598
+ "ol",
2599
+ "p",
2600
+ "pre",
2601
+ "section",
2602
+ "table",
2603
+ "ul"
2604
+ ], descendantSelector = `* ${Array.from(IGNORE_TAGS).map((tag) => `:not(${tag})`).join("")}`, isTransparentColor = (color) => {
2605
+ if (!color || color === "transparent")
2606
+ return !0;
2607
+ let match = color.match(/rgba?\(\s*[\d.]+\s*,\s*[\d.]+\s*,\s*[\d.]+\s*(?:,\s*([\d.]+)\s*)?\)/);
2608
+ return match ? (match[1] !== void 0 ? parseFloat(match[1]) : 1) === 0 : !1;
2609
+ }, hasVisibleDecoration = (style) => {
2610
+ if (style.backgroundImage && style.backgroundImage !== "none" || !isTransparentColor(style.backgroundColor))
2611
+ return !0;
2612
+ for (let property of [
2613
+ "borderTopWidth",
2614
+ "borderRightWidth",
2615
+ "borderBottomWidth",
2616
+ "borderLeftWidth"
2617
+ ])
2618
+ if (parseFloat(style[property]) > 0)
2619
+ return !0;
2620
+ for (let property of ["paddingTop", "paddingRight", "paddingBottom", "paddingLeft"])
2621
+ if (parseFloat(style[property]) > 0)
2622
+ return !0;
2623
+ return style.boxShadow && style.boxShadow !== "none" ? !0 : parseFloat(style.outlineWidth) > 0;
2624
+ }, isReplacedOrControl = (element) => REPLACED_OR_CONTROL_TAGS.has(element.tagName.toLowerCase()), hasDirectText = (element) => {
2625
+ for (let node of element.childNodes)
2626
+ if (node.nodeType === Node.TEXT_NODE && node.textContent?.trim())
2627
+ return !0;
2628
+ return !1;
2629
+ }, isStretchedToParent = (element) => {
2630
+ let parent = element.parentElement;
2631
+ if (!parent)
2632
+ return !1;
2633
+ let elementRect = element.getBoundingClientRect(), parentRect = parent.getBoundingClientRect();
2634
+ return elementRect.width > 0 && Math.abs(elementRect.width - parentRect.width) < 1;
2635
+ }, hasExplicitWidth = (style) => {
2636
+ let { width } = style;
2637
+ return !width || width === "auto" ? !1 : width !== "fit-content" && width !== "max-content" && width !== "min-content";
2638
+ }, coversViewport = (element) => {
2639
+ let rect = element.getBoundingClientRect();
2640
+ return rect.width >= window.innerWidth - 1 && rect.height >= window.innerHeight - 1 && rect.top <= 1 && rect.left <= 1;
2641
+ }, isViewportOverlayUnderlay = (element) => {
2642
+ let style = window.getComputedStyle(element);
2643
+ return style.position !== "fixed" && style.position !== "absolute" || hasVisibleDecoration(style) || isReplacedOrControl(element) || hasDirectText(element) ? !1 : coversViewport(element);
2644
+ }, isPassThroughContainer = (element) => {
2645
+ let style = window.getComputedStyle(element);
2646
+ return style.display === "contents" ? !0 : hasVisibleDecoration(style) || isReplacedOrControl(element) || hasDirectText(element) || hasExplicitWidth(style) ? !1 : isStretchedToParent(element);
2647
+ }, shouldExcludeFromMeasurement = (element) => isPassThroughContainer(element) || isViewportOverlayUnderlay(element), getMeasurableElements = (elements) => {
2648
+ let all = [...elements], measurable = all.filter((element) => !shouldExcludeFromMeasurement(element));
2649
+ return measurable.length > 0 ? measurable : all;
2650
+ }, getBodyPadding = (documentRef) => {
2651
+ let style = window.getComputedStyle(documentRef.body);
2652
+ return {
2653
+ top: parseFloat(style.paddingTop) || 0,
2654
+ right: parseFloat(style.paddingRight) || 0,
2655
+ bottom: parseFloat(style.paddingBottom) || 0,
2656
+ left: parseFloat(style.paddingLeft) || 0
2657
+ };
2658
+ }, getDimensions = (elements, documentRef) => {
2659
+ let minTop = 1 / 0, minLeft = 1 / 0, maxBottom = 0, maxRight = 0;
2660
+ for (let element of getMeasurableElements(elements)) {
2661
+ let rect = element.getBoundingClientRect(), computedStyle = window.getComputedStyle(element), marginTop = parseFloat(computedStyle.marginTop) || 0, marginLeft = parseFloat(computedStyle.marginLeft) || 0, marginBottom = parseFloat(computedStyle.marginBottom) || 0, marginRight = parseFloat(computedStyle.marginRight) || 0;
2662
+ minTop = Math.min(minTop, rect.top - marginTop), minLeft = Math.min(minLeft, rect.left - marginLeft), maxBottom = Math.max(maxBottom, rect.bottom + marginBottom), maxRight = Math.max(maxRight, rect.right + marginRight);
2663
+ }
2664
+ let padding = getBodyPadding(documentRef), contentWidth = maxRight - minLeft, contentHeight = maxBottom - minTop;
2665
+ return {
2666
+ width: Math.ceil(contentWidth + padding.left + padding.right),
2667
+ height: Math.ceil(contentHeight + padding.top + padding.bottom)
2668
+ };
2669
+ }, getTrackedElements = () => {
2670
+ let elements = /* @__PURE__ */ new Set(), nodes = [
2671
+ ...Array.from(document.getElementById("storybook-root")?.children || []),
2672
+ ...Array.from(document.body.children).filter((child) => !child.id.startsWith("storybook-"))
2673
+ ];
2674
+ for (let node of nodes)
2675
+ if (node instanceof Element && !IGNORE_TAGS.has(node.tagName.toLowerCase())) {
2676
+ elements.add(node);
2677
+ for (let descendant of Array.from(node.querySelectorAll(descendantSelector)))
2678
+ elements.add(descendant);
2679
+ }
2680
+ return elements;
2681
+ }, injectEmbedSizingStyles = (documentRef) => {
2682
+ if (documentRef.getElementById(EMBED_STYLE_ID))
2683
+ return;
2684
+ let style = documentRef.createElement("style");
2685
+ style.id = EMBED_STYLE_ID, style.textContent = `${`:where(#storybook-root > :is(${BLOCK_LEVEL_TAGS.join(", ")}))`} {
2686
+ width: fit-content;
2687
+ max-width: 100%;
2688
+ }`, documentRef.head.appendChild(style);
2689
+ }, removeEmbedSizingStyles = (documentRef) => {
2690
+ documentRef.getElementById(EMBED_STYLE_ID)?.remove();
2691
+ }, injectEmbedUiStyles = (documentRef) => {
2692
+ if (documentRef.getElementById(EMBED_UI_STYLE_ID))
2693
+ return;
2694
+ let style = documentRef.createElement("style");
2695
+ style.id = EMBED_UI_STYLE_ID, style.textContent = `
2696
+ .sb-preparing-story,
2697
+ .sb-preparing-docs {
2698
+ display: none !important;
2699
+ }
2700
+ `, documentRef.head.appendChild(style);
2701
+ }, lastDimensions = null, sendResizeMessage = (elements, windowRef, documentRef, getViewport) => {
2702
+ if (!elements.size)
2703
+ return;
2704
+ injectEmbedSizingStyles(documentRef);
2705
+ let dimensions = getDimensions(elements, documentRef);
2706
+ removeEmbedSizingStyles(documentRef);
2707
+ let viewport = getViewport?.();
2708
+ if (dimensions.width === lastDimensions?.width && dimensions.height === lastDimensions?.height && iframeResizeViewportsEqual(viewport, lastDimensions?.viewport))
2709
+ return;
2710
+ let message = JSON.stringify({
2711
+ src: windowRef.location.toString(),
2712
+ context: IFRAME_RESIZE_CONTEXT,
2713
+ width: dimensions.width,
2714
+ height: dimensions.height,
2715
+ ...viewport ? { viewport } : {}
2716
+ });
2717
+ lastDimensions = { ...dimensions, viewport };
2718
+ try {
2719
+ windowRef.parent !== windowRef && windowRef.parent.postMessage(message, "*");
2720
+ } catch {
2721
+ }
2722
+ }, debounce = (callback) => {
2723
+ let rafId = null, debounced = () => {
2724
+ rafId !== null && cancelAnimationFrame(rafId), rafId = requestAnimationFrame(() => {
2725
+ callback(), rafId = null;
2726
+ });
2727
+ };
2728
+ return debounced.cancel = () => {
2729
+ rafId !== null && (cancelAnimationFrame(rafId), rafId = null);
2730
+ }, debounced;
2731
+ }, setupContentResizeBroadcast = (options = {}) => {
2732
+ let { getViewport } = options, windowRef = global6.window, documentRef = global6.document;
2733
+ if (!windowRef || !documentRef)
2734
+ return {};
2735
+ if (!shouldEmbed({ search: documentRef.location.search }))
2736
+ return {};
2737
+ lastDimensions = null;
2738
+ let freezing = shouldFreeze({ search: documentRef.location.search });
2739
+ freezing && injectEmbedUiStyles(documentRef);
2740
+ let contentFrozen = !1, measureAndSend = () => {
2741
+ let elements = getTrackedElements();
2742
+ sendResizeMessage(elements, windowRef, documentRef, getViewport);
2743
+ }, onParentMessage = (event) => {
2744
+ if (event.source === windowRef.parent)
2745
+ try {
2746
+ if ((typeof event.data == "string" ? JSON.parse(event.data) : event.data)?.context === IFRAME_RESIZE_REQUEST_CONTEXT) {
2747
+ if (freezing && !contentFrozen)
2748
+ return;
2749
+ lastDimensions = null, measureAndSend();
2750
+ }
2751
+ } catch {
2752
+ }
2753
+ };
2754
+ windowRef.addEventListener("message", onParentMessage);
2755
+ let cleanups2 = [
2756
+ () => windowRef.removeEventListener("message", onParentMessage)
2757
+ ];
2758
+ if (freezing)
2759
+ return {
2760
+ onContentFrozen: () => {
2761
+ contentFrozen = !0, measureAndSend();
2762
+ },
2763
+ cleanup: () => cleanups2.forEach((fn) => fn())
2764
+ };
2765
+ let trackedElements = getTrackedElements(), debouncedUpdate = debounce(() => sendResizeMessage(trackedElements, windowRef, documentRef, getViewport)), resizeObserver = new ResizeObserver(debouncedUpdate);
2766
+ for (let element of trackedElements)
2767
+ resizeObserver.observe(element);
2768
+ let mutationObserver = new MutationObserver(() => {
2769
+ debouncedUpdate();
2770
+ let updatedElements = getTrackedElements();
2771
+ for (let element of updatedElements)
2772
+ trackedElements.has(element) || (resizeObserver.observe(element), trackedElements.add(element));
2773
+ for (let element of trackedElements)
2774
+ updatedElements.has(element) || (resizeObserver.unobserve(element), trackedElements.delete(element));
2775
+ });
2776
+ return mutationObserver.observe(documentRef.body, {
2777
+ childList: !0,
2778
+ subtree: !0
2779
+ }), windowRef.addEventListener("resize", debouncedUpdate), cleanups2.push(
2780
+ () => debouncedUpdate.cancel(),
2781
+ () => resizeObserver.disconnect(),
2782
+ () => mutationObserver.disconnect(),
2783
+ () => windowRef.removeEventListener("resize", debouncedUpdate)
2784
+ ), measureAndSend(), { cleanup: () => cleanups2.forEach((fn) => fn()) };
2785
+ };
2786
+
2787
+ // src/preview-api/modules/preview-web/PreviewWithSelection.tsx
2788
+ var globalWindow = globalThis;
2789
+ function focusInInput(event) {
2790
+ let target = event.composedPath && event.composedPath()[0] || event.target;
2791
+ return /input|textarea/i.test(target.tagName) || target.getAttribute("contenteditable") !== null;
2792
+ }
2793
+ function isStoryRender(r) {
2794
+ return r.type === "story";
2795
+ }
2796
+ function isDocsRender(r) {
2797
+ return r.type === "docs";
2798
+ }
2799
+ function isCsfDocsRender(r) {
2800
+ return isDocsRender(r) && r.subtype === "csf";
2801
+ }
2802
+ var PreviewWithSelection = class extends Preview {
2803
+ constructor(importFn, getProjectAnnotations, selectionStore, view) {
2804
+ super(importFn, getProjectAnnotations, void 0, !1);
2805
+ this.importFn = importFn;
2806
+ this.getProjectAnnotations = getProjectAnnotations;
2807
+ this.selectionStore = selectionStore;
2808
+ this.view = view;
2809
+ this.initialize();
2810
+ }
2811
+ setupListeners() {
2812
+ super.setupListeners(), globalWindow.onkeydown = this.onKeydown.bind(this);
2813
+ let { onContentFrozen } = setupContentResizeBroadcast({
2814
+ getViewport: () => {
2815
+ let render = this.currentRender;
2816
+ if (!(!render || !isStoryRender(render)))
2817
+ return getEmbedResizeViewport(this.storyStoreValue, render, {
2818
+ width: globalWindow.innerWidth,
2819
+ height: globalWindow.innerHeight
2820
+ });
2821
+ }
2822
+ });
2823
+ setupStoryFreezer(this.channel, { onFrozen: onContentFrozen }), this.channel.on(SET_CURRENT_STORY, this.onSetCurrentStory.bind(this)), this.channel.on(UPDATE_QUERY_PARAMS, this.onUpdateQueryParams.bind(this)), this.channel.on(PRELOAD_ENTRIES, this.onPreloadStories.bind(this)), this.channel.on(NAVIGATE_URL, this.onNavigateUrl.bind(this));
2824
+ }
2825
+ // The manager emits NAVIGATE_URL for in-page (`#hash`) navigation, e.g. when a docs heading is
2826
+ // selected in search while its page is already rendered. Nothing re-renders in that case, so the
2827
+ // view scrolls to the anchor explicitly.
2828
+ onNavigateUrl(url) {
2829
+ url.startsWith("#") && this.view.scrollToAnchor?.(url);
2830
+ }
2831
+ async setInitialGlobals() {
2832
+ if (!this.storyStoreValue)
2833
+ throw new CalledPreviewMethodBeforeInitializationError2({ methodName: "setInitialGlobals" });
2834
+ let { globals } = this.selectionStore.selectionSpecifier || {};
2835
+ globals && this.storyStoreValue.userGlobals.updateFromPersisted(globals), this.emitGlobals();
2836
+ }
2837
+ // If initialization gets as far as the story index, this function runs.
2838
+ async initializeWithStoryIndex(storyIndex) {
2839
+ return await super.initializeWithStoryIndex(storyIndex), this.selectSpecifiedStory();
2840
+ }
2841
+ // Use the selection specifier to choose a story, then render it
2842
+ async selectSpecifiedStory() {
2843
+ if (!this.storyStoreValue)
2844
+ throw new CalledPreviewMethodBeforeInitializationError2({
2845
+ methodName: "selectSpecifiedStory"
2846
+ });
2847
+ if (this.selectionStore.selection) {
2848
+ await this.renderSelection();
2849
+ return;
2850
+ }
2851
+ if (!this.selectionStore.selectionSpecifier) {
2852
+ this.renderMissingStory();
2853
+ return;
2854
+ }
2855
+ let { storySpecifier, args } = this.selectionStore.selectionSpecifier, entry = this.storyStoreValue.storyIndex.entryFromSpecifier(storySpecifier);
2856
+ if (!entry) {
2857
+ storySpecifier === "*" ? this.renderStoryLoadingException(storySpecifier, new EmptyIndexError()) : this.renderStoryLoadingException(
2858
+ storySpecifier,
2859
+ new NoStoryMatchError({ storySpecifier: storySpecifier.toString() })
2860
+ );
2861
+ return;
2862
+ }
2863
+ let { id: storyId, type: viewMode } = entry;
2864
+ this.selectionStore.setSelection({ storyId, viewMode }), this.channel.emit(STORY_SPECIFIED, this.selectionStore.selection), this.channel.emit(CURRENT_STORY_WAS_SET, this.selectionStore.selection), await this.renderSelection({ persistedArgs: args });
2865
+ }
2866
+ // EVENT HANDLERS
2867
+ // This happens when a config file gets reloaded
2868
+ async onGetProjectAnnotationsChanged({
2869
+ getProjectAnnotations
2870
+ }) {
2871
+ await super.onGetProjectAnnotationsChanged({ getProjectAnnotations }), this.selectionStore.selection && this.renderSelection();
2872
+ }
2873
+ // This happens when a glob gets HMR-ed
2874
+ async onStoriesChanged({
2875
+ importFn,
2876
+ storyIndex
2877
+ }) {
2878
+ await super.onStoriesChanged({ importFn, storyIndex }), this.selectionStore.selection ? await this.renderSelection() : await this.selectSpecifiedStory();
2879
+ }
2880
+ onKeydown(event) {
2881
+ if (!this.storyRenders.find((r) => r.disableKeyListeners) && !focusInInput(event)) {
2882
+ let { altKey, ctrlKey, metaKey, shiftKey, key, code, keyCode } = event;
2883
+ this.channel.emit(PREVIEW_KEYDOWN, {
2884
+ event: { altKey, ctrlKey, metaKey, shiftKey, key, code, keyCode }
2885
+ });
2886
+ }
2887
+ }
2888
+ async onSetCurrentStory(selection) {
2889
+ this.selectionStore.setSelection({ viewMode: "story", ...selection }), await this.storeInitializationPromise, this.channel.emit(CURRENT_STORY_WAS_SET, this.selectionStore.selection), this.renderSelection();
2890
+ }
2891
+ onUpdateQueryParams(queryParams) {
2892
+ this.selectionStore.setQueryParams(queryParams);
2893
+ }
2894
+ async onUpdateGlobals({ globals }) {
2895
+ let currentStory = this.currentRender instanceof StoryRender && this.currentRender.story || void 0;
2896
+ super.onUpdateGlobals({ globals, currentStory }), (this.currentRender instanceof MdxDocsRender || this.currentRender instanceof CsfDocsRender) && await this.currentRender.rerender?.();
2897
+ }
2898
+ async onUpdateArgs({ storyId, updatedArgs }) {
2899
+ super.onUpdateArgs({ storyId, updatedArgs });
2900
+ }
2901
+ async onPreloadStories({ ids }) {
2902
+ await this.storeInitializationPromise, this.storyStoreValue && await Promise.allSettled(ids.map((id) => this.storyStoreValue?.loadEntry(id)));
2903
+ }
2904
+ // RENDERING
2905
+ // We can either have:
2906
+ // - a story selected in "story" viewMode,
2907
+ // in which case we render it to the root element, OR
2908
+ // - a story selected in "docs" viewMode,
2909
+ // in which case we render the docsPage for that story
2910
+ async renderSelection({ persistedArgs } = {}) {
2911
+ let { renderToCanvas } = this;
2912
+ if (!this.storyStoreValue || !renderToCanvas)
2913
+ throw new CalledPreviewMethodBeforeInitializationError2({ methodName: "renderSelection" });
2914
+ let { selection } = this.selectionStore;
2915
+ if (!selection)
2916
+ throw new Error("Cannot call renderSelection as no selection was made");
2917
+ let { storyId } = selection, entry;
2918
+ try {
2919
+ entry = await this.storyStoreValue.storyIdToEntry(storyId);
2920
+ } catch (err) {
2921
+ this.currentRender && await this.teardownRender(this.currentRender), this.renderStoryLoadingException(storyId, err);
2922
+ return;
2923
+ }
2924
+ let storyIdChanged = this.currentSelection?.storyId !== storyId, viewModeChanged = this.currentRender?.type !== entry.type;
2925
+ (storyIdChanged || viewModeChanged) && (entry.type === "story" ? this.view.showPreparingStory({ immediate: viewModeChanged }) : this.view.showPreparingDocs({ immediate: viewModeChanged })), this.currentRender?.isPreparing() && await this.teardownRender(this.currentRender);
2926
+ let render;
2927
+ entry.type === "story" ? render = new StoryRender(
2928
+ this.channel,
2929
+ this.storyStoreValue,
2930
+ renderToCanvas,
2931
+ this.mainStoryCallbacks(storyId),
2932
+ storyId,
2933
+ "story",
2934
+ { autoplay: shouldAutoplay({ search: globalWindow.location?.search ?? "" }) }
2935
+ ) : isMdxEntry(entry) ? render = new MdxDocsRender(
2936
+ this.channel,
2937
+ this.storyStoreValue,
2938
+ entry,
2939
+ this.mainStoryCallbacks(storyId)
2940
+ ) : render = new CsfDocsRender(
2941
+ this.channel,
2942
+ this.storyStoreValue,
2943
+ entry,
2944
+ this.mainStoryCallbacks(storyId)
2945
+ );
2946
+ let lastSelection = this.currentSelection;
2947
+ this.currentSelection = selection;
2948
+ let lastRender = this.currentRender;
2949
+ this.currentRender = render;
2950
+ try {
2951
+ await render.prepare();
2952
+ } catch (err) {
2953
+ lastRender && await this.teardownRender(lastRender), err !== PREPARE_ABORTED && this.renderStoryLoadingException(storyId, err);
2954
+ return;
2955
+ }
2956
+ let implementationChanged = !storyIdChanged && lastRender && !render.isEqual(lastRender);
2957
+ if (persistedArgs && isStoryRender(render) && (invariant(!!render.story), this.storyStoreValue.args.updateFromPersisted(render.story, persistedArgs)), lastRender && !lastRender.torndown && !storyIdChanged && !implementationChanged && !viewModeChanged) {
2958
+ this.currentRender = lastRender, this.channel.emit(STORY_UNCHANGED, storyId), this.view.showMain();
2959
+ return;
2960
+ }
2961
+ if (lastRender && await this.teardownRender(lastRender, {
2962
+ viewModeChanged,
2963
+ // On a same-story re-render, the previous DOM stays mounted until the new render
2964
+ // replaces it in place, so the document never collapses and scroll is preserved.
2965
+ keepRenderedDom: !storyIdChanged && !viewModeChanged
2966
+ }), lastSelection && (storyIdChanged || viewModeChanged) && this.channel.emit(STORY_CHANGED, storyId), isStoryRender(render)) {
2967
+ invariant(!!render.story);
2968
+ let {
2969
+ parameters,
2970
+ initialArgs,
2971
+ argTypes,
2972
+ unmappedArgs,
2973
+ initialGlobals,
2974
+ userGlobals,
2975
+ storyGlobals,
2976
+ globals
2977
+ } = this.storyStoreValue.getStoryContext(render.story);
2978
+ this.channel.emit(STORY_PREPARED, {
2979
+ id: storyId,
2980
+ parameters,
2981
+ initialArgs,
2982
+ argTypes,
2983
+ args: unmappedArgs
2984
+ }), this.channel.emit(GLOBALS_UPDATED2, { userGlobals, storyGlobals, globals, initialGlobals });
2985
+ } else {
2986
+ let { parameters } = this.storyStoreValue.projectAnnotations, { initialGlobals, globals } = this.storyStoreValue.userGlobals;
2987
+ if (this.channel.emit(GLOBALS_UPDATED2, {
2988
+ globals,
2989
+ initialGlobals,
2990
+ storyGlobals: {},
2991
+ userGlobals: globals
2992
+ }), isCsfDocsRender(render) || render.entry.tags?.includes(Tag.ATTACHED_MDX)) {
2993
+ if (!render.csfFiles)
2994
+ throw new MdxFileWithNoCsfReferencesError({ storyId });
2995
+ ({ parameters } = this.storyStoreValue.preparedMetaFromCSFFile({
2996
+ csfFile: render.csfFiles[0]
2997
+ }));
2998
+ }
2999
+ this.channel.emit(DOCS_PREPARED, {
3000
+ id: storyId,
3001
+ parameters
3002
+ });
3003
+ }
3004
+ isStoryRender(render) ? (invariant(!!render.story), this.storyRenders.push(render), this.currentRender.renderToElement(
3005
+ this.view.prepareForStory(render.story, {
3006
+ scrollReset: storyIdChanged || viewModeChanged
3007
+ })
3008
+ )) : this.currentRender.renderToElement(
3009
+ this.view.prepareForDocs({ scrollReset: storyIdChanged || viewModeChanged }),
3010
+ // This argument is used for docs, which is currently only compatible with HTMLElements
3011
+ this.renderStoryToElement.bind(this)
3012
+ );
3013
+ }
3014
+ async teardownRender(render, {
3015
+ viewModeChanged = !1,
3016
+ keepRenderedDom = !1
3017
+ } = {}) {
3018
+ this.storyRenders = this.storyRenders.filter((r) => r !== render), await render?.teardown?.({ viewModeChanged, keepRenderedDom });
3019
+ }
3020
+ // UTILITIES
3021
+ mainStoryCallbacks(storyId) {
3022
+ return {
3023
+ showStoryDuringRender: () => this.view.showStoryDuringRender(),
3024
+ showMain: () => this.view.showMain(),
3025
+ showError: (err) => this.renderError(storyId, err),
3026
+ showException: (err) => this.renderException(storyId, err)
3027
+ };
3028
+ }
3029
+ renderPreviewEntryError(reason, err) {
3030
+ super.renderPreviewEntryError(reason, err), this.view.showErrorDisplay(err);
3031
+ }
3032
+ renderMissingStory() {
3033
+ this.view.showNoPreview(), this.channel.emit(STORY_MISSING);
3034
+ }
3035
+ renderStoryLoadingException(storySpecifier, err) {
3036
+ logger5.error(err), this.view.showErrorDisplay(err), this.channel.emit(STORY_MISSING, storySpecifier);
3037
+ }
3038
+ // renderException is used if we fail to render the story and it is uncaught by the app layer
3039
+ renderException(storyId, error) {
3040
+ let { name = "Error", message = String(error), stack } = error, renderId = this.currentRender?.renderId;
3041
+ this.channel.emit(STORY_THREW_EXCEPTION, { name, message, stack }), this.channel.emit(STORY_RENDER_PHASE_CHANGED3, { newPhase: "errored", renderId, storyId }), this.view.showErrorDisplay(error), logger5.error(`Error rendering story '${storyId}':`), logger5.error(error);
3042
+ }
3043
+ // renderError is used by the various app layers to inform the user they have done something
3044
+ // wrong -- for instance returned the wrong thing from a story
3045
+ renderError(storyId, { title, description }) {
3046
+ let renderId = this.currentRender?.renderId;
3047
+ this.channel.emit(STORY_ERRORED, { title, description }), this.channel.emit(STORY_RENDER_PHASE_CHANGED3, { newPhase: "errored", renderId, storyId }), this.view.showErrorDisplay({ message: title, stack: description }), logger5.error(`Error rendering story ${title}: ${description}`);
3048
+ }
3049
+ };
3050
+
3051
+ // src/preview-api/modules/preview-web/UrlStore.ts
3052
+ import { global as global7 } from "@storybook/global";
3053
+
3054
+ // src/preview-api/modules/preview-web/parseArgsParam.ts
3055
+ import { once as once2 } from "@aussieljk/forkbook/internal/client-logger";
3056
+ import { dedent as dedent4 } from "ts-dedent";
3057
+ var VALIDATION_REGEXP = /^[a-zA-Z0-9 _-]*$/, NUMBER_REGEXP = /^-?[0-9]+(\.[0-9]+)?$/, HEX_REGEXP = /^#([a-f0-9]{3,4}|[a-f0-9]{6}|[a-f0-9]{8})$/i, COLOR_REGEXP = /^(rgba?|hsla?)\(([0-9]{1,3}),\s?([0-9]{1,3})%?,\s?([0-9]{1,3})%?,?\s?([0-9](\.[0-9]{1,2})?)?\)$/i, validateArgs = (key = "", value) => key === null || key === "" || !VALIDATION_REGEXP.test(key) ? !1 : value == null || value instanceof Date || typeof value == "number" || typeof value == "boolean" ? !0 : typeof value == "string" ? VALIDATION_REGEXP.test(value) || NUMBER_REGEXP.test(value) || HEX_REGEXP.test(value) || COLOR_REGEXP.test(value) : Array.isArray(value) ? value.every((v) => validateArgs(key, v)) : isPlainObject(value) ? Object.entries(value).every(([k, v]) => validateArgs(k, v)) : !1, QUERY_OPTIONS = {
3058
+ delimiter: ";",
3059
+ // we're parsing a single query param
3060
+ nesting: !0,
3061
+ arrayRepeat: !0,
3062
+ arrayRepeatSyntax: "bracket",
3063
+ nestingSyntax: "js",
3064
+ // objects are encoded using dot notation
3065
+ valueDeserializer(str) {
3066
+ if (str.startsWith("!")) {
3067
+ if (str === "!undefined")
3068
+ return;
3069
+ if (str === "!null")
3070
+ return null;
3071
+ if (str === "!true")
3072
+ return !0;
3073
+ if (str === "!false")
3074
+ return !1;
3075
+ if (str.startsWith("!date(") && str.endsWith(")"))
3076
+ return new Date(str.replaceAll(" ", "+").slice(6, -1));
3077
+ if (str.startsWith("!hex(") && str.endsWith(")"))
3078
+ return `#${str.slice(5, -1)}`;
3079
+ let color = str.slice(1).match(COLOR_REGEXP);
3080
+ if (color)
3081
+ return str.startsWith("!rgba") || str.startsWith("!RGBA") ? `${color[1]}(${color[2]}, ${color[3]}, ${color[4]}, ${color[5]})` : str.startsWith("!hsla") || str.startsWith("!HSLA") ? `${color[1]}(${color[2]}, ${color[3]}%, ${color[4]}%, ${color[5]})` : str.startsWith("!rgb") || str.startsWith("!RGB") ? `${color[1]}(${color[2]}, ${color[3]}, ${color[4]})` : `${color[1]}(${color[2]}, ${color[3]}%, ${color[4]}%)`;
3082
+ }
3083
+ return NUMBER_REGEXP.test(str) ? Number(str) : str;
3084
+ }
3085
+ }, parseArgsParam = (argsString) => {
3086
+ let parts = argsString.split(";").map((part) => part.replace("=", "~").replace(":", "="));
3087
+ return Object.entries(parse(parts.join(";"), QUERY_OPTIONS)).reduce((acc, [key, value]) => validateArgs(key, value) ? Object.assign(acc, { [key]: value }) : (once2.warn(dedent4`
3088
+ Omitted potentially unsafe URL args.
3089
+
3090
+ More info: https://storybook.js.org/docs/writing-stories/args?ref=error#setting-args-through-the-url
3091
+ `), acc), {});
3092
+ };
3093
+
3094
+ // src/preview-api/modules/preview-web/UrlStore.ts
3095
+ var { history, document: document2 } = global7, PATH_REGEX = /^\/(story|docs)\/(.+)/;
3096
+ function pathToId(path) {
3097
+ let match = (path || "").match(PATH_REGEX);
3098
+ if (!match)
3099
+ throw new Error(`Invalid path '${path}', must start with '/story/' or '/docs/'`);
3100
+ return match[2];
3101
+ }
3102
+ function pathToViewMode(path) {
3103
+ return (path || "").match(PATH_REGEX)?.[1];
3104
+ }
3105
+ var getQueryString = ({
3106
+ selection,
3107
+ extraParams
3108
+ }) => {
3109
+ let search = document2?.location.search.slice(1), { path, selectedKind, selectedStory, ...rest } = parse(search);
3110
+ return `?${stringify({
3111
+ ...rest,
3112
+ ...extraParams,
3113
+ ...selection && { id: selection.storyId, viewMode: selection.viewMode }
3114
+ })}`;
3115
+ }, setPath = (selection) => {
3116
+ if (!selection)
3117
+ return;
3118
+ let query = getQueryString({ selection }), { hash = "" } = document2.location;
3119
+ document2.title = selection.storyId, history.replaceState({}, "", `${document2.location.pathname}${query}${hash}`);
3120
+ }, isObject = (val) => val != null && typeof val == "object" && Array.isArray(val) === !1, getFirstString = (v) => {
3121
+ if (v !== void 0) {
3122
+ if (typeof v == "string")
3123
+ return v;
3124
+ if (Array.isArray(v))
3125
+ return getFirstString(v[0]);
3126
+ if (isObject(v))
3127
+ return getFirstString(
3128
+ Object.values(v).filter(Boolean)
3129
+ );
3130
+ }
3131
+ }, getSelectionSpecifierFromPath = () => {
3132
+ if (typeof document2 < "u") {
3133
+ let queryStr = document2.location.search.slice(1), query = parse(queryStr), args = typeof query.args == "string" ? parseArgsParam(query.args) : void 0, globals = typeof query.globals == "string" ? parseArgsParam(query.globals) : void 0, path = getFirstString(query.path), viewMode = getFirstString(query.viewMode);
3134
+ if (typeof viewMode != "string" || !viewMode)
3135
+ viewMode = path && pathToViewMode(path) || "story";
3136
+ else if (!viewMode.match(/docs|story/))
3137
+ return null;
3138
+ let storyId = path ? pathToId(path) : getFirstString(query.id);
3139
+ if (storyId)
3140
+ return { storySpecifier: storyId, args, globals, viewMode };
3141
+ }
3142
+ return null;
3143
+ }, UrlStore = class {
3144
+ constructor() {
3145
+ this.selectionSpecifier = getSelectionSpecifierFromPath();
3146
+ }
3147
+ setSelection(selection) {
3148
+ this.selection = selection, setPath(this.selection);
3149
+ }
3150
+ setQueryParams(queryParams) {
3151
+ let query = getQueryString({ extraParams: queryParams }), { hash = "" } = document2.location;
3152
+ history.replaceState({}, "", `${document2.location.pathname}${query}${hash}`);
3153
+ }
3154
+ };
3155
+
3156
+ // src/preview-api/modules/preview-web/WebView.ts
3157
+ var import_ansi_to_html = __toESM(require_ansi_to_html(), 1);
3158
+ import { logger as logger6 } from "@aussieljk/forkbook/internal/client-logger";
3159
+ import { global as global8 } from "@storybook/global";
3160
+ import { dedent as dedent5 } from "ts-dedent";
3161
+ var { document: document3 } = global8, PREPARING_DELAY = 100, Mode = /* @__PURE__ */ ((Mode2) => (Mode2.MAIN = "MAIN", Mode2.NOPREVIEW = "NOPREVIEW", Mode2.PREPARING_STORY = "PREPARING_STORY", Mode2.PREPARING_DOCS = "PREPARING_DOCS", Mode2.ERROR = "ERROR", Mode2))(Mode || {}), classes = {
3162
+ PREPARING_STORY: "sb-show-preparing-story",
3163
+ PREPARING_DOCS: "sb-show-preparing-docs",
3164
+ MAIN: "sb-show-main",
3165
+ NOPREVIEW: "sb-show-nopreview",
3166
+ ERROR: "sb-show-errordisplay"
3167
+ }, layoutClassMap = {
3168
+ centered: "sb-main-centered",
3169
+ fullscreen: "sb-main-fullscreen",
3170
+ padded: "sb-main-padded"
3171
+ }, ansiConverter = new import_ansi_to_html.default({
3172
+ escapeXML: !0
3173
+ }), WebView = class {
3174
+ constructor() {
3175
+ this.testing = !1;
3176
+ if (typeof document3 < "u") {
3177
+ let { __SPECIAL_TEST_PARAMETER__ } = parse(document3.location.search.slice(1));
3178
+ switch (__SPECIAL_TEST_PARAMETER__) {
3179
+ case "preparing-story": {
3180
+ this.showPreparingStory(), this.testing = !0;
3181
+ break;
3182
+ }
3183
+ case "preparing-docs": {
3184
+ this.showPreparingDocs(), this.testing = !0;
3185
+ break;
3186
+ }
3187
+ default:
3188
+ }
3189
+ }
3190
+ }
3191
+ // Get ready to render a story, returning the element to render to
3192
+ prepareForStory(story, { scrollReset = !0 } = {}) {
3193
+ this.showStory(), this.applyLayout(story.parameters.layout), scrollReset && (document3.documentElement.scrollTop = 0, document3.documentElement.scrollLeft = 0);
3194
+ let storyRoot = this.storyRoot();
3195
+ return this.applyHtmlLang(storyRoot, story.parameters.htmlLang), storyRoot;
3196
+ }
3197
+ storyRoot() {
3198
+ return document3.getElementById("storybook-root");
3199
+ }
3200
+ prepareForDocs({ scrollReset = !0 } = {}) {
3201
+ return this.showMain(), this.showDocs(), this.applyLayout("fullscreen"), scrollReset && (document3.documentElement.scrollTop = 0, document3.documentElement.scrollLeft = 0), this.docsRoot();
3202
+ }
3203
+ docsRoot() {
3204
+ return document3.getElementById("storybook-docs");
3205
+ }
3206
+ scrollToAnchor(hash) {
3207
+ document3.getElementById(decodeURIComponent(hash.substring(1)))?.scrollIntoView({ behavior: "smooth" });
3208
+ }
3209
+ applyLayout(layout = "padded") {
3210
+ if (layout === "none") {
3211
+ document3.body.classList.remove(this.currentLayoutClass), this.currentLayoutClass = null;
3212
+ return;
3213
+ }
3214
+ this.checkIfLayoutExists(layout);
3215
+ let layoutClass = layoutClassMap[layout];
3216
+ document3.body.classList.remove(this.currentLayoutClass), document3.body.classList.add(layoutClass), this.currentLayoutClass = layoutClass;
3217
+ }
3218
+ /**
3219
+ * Injects a BCP-47 lang attribute to the story root, or removes it if `lang` is null.
3220
+ */
3221
+ applyHtmlLang(element, lang) {
3222
+ lang ? element.setAttribute("lang", lang) : element.removeAttribute("lang");
3223
+ }
3224
+ checkIfLayoutExists(layout) {
3225
+ layoutClassMap[layout] || logger6.warn(
3226
+ dedent5`
3227
+ The desired layout: ${layout} is not a valid option.
3228
+ The possible options are: ${Object.keys(layoutClassMap).join(", ")}, none.
3229
+ `
3230
+ );
3231
+ }
3232
+ showMode(mode) {
3233
+ clearTimeout(this.preparingTimeout), Object.keys(Mode).forEach((otherMode) => {
3234
+ otherMode === mode ? document3.body.classList.add(classes[otherMode]) : document3.body.classList.remove(classes[otherMode]);
3235
+ });
3236
+ }
3237
+ showErrorDisplay({ message = "", stack = "" }) {
3238
+ let header = message, detail = stack, parts = message.split(`
3239
+ `);
3240
+ parts.length > 1 && ([header] = parts, detail = parts.slice(1).join(`
3241
+ `).replace(/^\n/, "")), document3.getElementById("error-message").innerHTML = ansiConverter.toHtml(header), document3.getElementById("error-stack").innerHTML = ansiConverter.toHtml(detail), this.showMode("ERROR" /* ERROR */);
3242
+ }
3243
+ showNoPreview() {
3244
+ this.testing || (this.showMode("NOPREVIEW" /* NOPREVIEW */), this.storyRoot()?.setAttribute("hidden", "true"), this.docsRoot()?.setAttribute("hidden", "true"));
3245
+ }
3246
+ showPreparingStory({ immediate = !1 } = {}) {
3247
+ clearTimeout(this.preparingTimeout), immediate ? this.showMode("PREPARING_STORY" /* PREPARING_STORY */) : this.preparingTimeout = setTimeout(
3248
+ () => this.showMode("PREPARING_STORY" /* PREPARING_STORY */),
3249
+ PREPARING_DELAY
3250
+ );
3251
+ }
3252
+ showPreparingDocs({ immediate = !1 } = {}) {
3253
+ clearTimeout(this.preparingTimeout), immediate ? this.showMode("PREPARING_DOCS" /* PREPARING_DOCS */) : this.preparingTimeout = setTimeout(() => this.showMode("PREPARING_DOCS" /* PREPARING_DOCS */), PREPARING_DELAY);
3254
+ }
3255
+ showMain() {
3256
+ this.showMode("MAIN" /* MAIN */);
3257
+ }
3258
+ showDocs() {
3259
+ this.storyRoot().setAttribute("hidden", "true"), this.docsRoot().removeAttribute("hidden");
3260
+ }
3261
+ showStory() {
3262
+ this.docsRoot().setAttribute("hidden", "true"), this.storyRoot().removeAttribute("hidden");
3263
+ }
3264
+ showStoryDuringRender() {
3265
+ document3.body.classList.add(classes.MAIN);
3266
+ }
3267
+ };
3268
+
3269
+ // src/preview-api/modules/preview-web/PreviewWeb.tsx
3270
+ var PreviewWeb = class extends PreviewWithSelection {
3271
+ constructor(importFn, getProjectAnnotations) {
3272
+ super(importFn, getProjectAnnotations, new UrlStore(), new WebView());
3273
+ this.importFn = importFn;
3274
+ this.getProjectAnnotations = getProjectAnnotations;
3275
+ global9.__STORYBOOK_PREVIEW__ = this;
3276
+ }
3277
+ };
3278
+
3279
+ // src/preview-api/modules/preview-web/simulate-pageload.ts
3280
+ import { global as global10 } from "@storybook/global";
3281
+ var { document: document4 } = global10, runScriptTypes = [
3282
+ "application/javascript",
3283
+ "application/ecmascript",
3284
+ "application/x-ecmascript",
3285
+ "application/x-javascript",
3286
+ "text/ecmascript",
3287
+ "text/javascript",
3288
+ "text/javascript1.0",
3289
+ "text/javascript1.1",
3290
+ "text/javascript1.2",
3291
+ "text/javascript1.3",
3292
+ "text/javascript1.4",
3293
+ "text/javascript1.5",
3294
+ "text/jscript",
3295
+ "text/livescript",
3296
+ "text/x-ecmascript",
3297
+ "text/x-javascript",
3298
+ // Support modern javascript
3299
+ "module"
3300
+ ], SCRIPT = "script", SCRIPTS_ROOT_ID = "scripts-root";
3301
+ function simulateDOMContentLoaded() {
3302
+ let DOMContentLoadedEvent = document4.createEvent("Event");
3303
+ DOMContentLoadedEvent.initEvent("DOMContentLoaded", !0, !0), document4.dispatchEvent(DOMContentLoadedEvent);
3304
+ }
3305
+ function insertScript($script, callback, $scriptRoot) {
3306
+ let scriptEl = document4.createElement("script");
3307
+ scriptEl.type = $script.type === "module" ? "module" : "text/javascript", $script.src ? (scriptEl.onload = callback, scriptEl.onerror = callback, scriptEl.src = $script.src) : scriptEl.textContent = $script.innerText, $scriptRoot ? $scriptRoot.appendChild(scriptEl) : document4.head.appendChild(scriptEl), $script.parentNode.removeChild($script), $script.src || callback();
3308
+ }
3309
+ function insertScriptsSequentially(scriptsToExecute, callback, index = 0) {
3310
+ scriptsToExecute[index](() => {
3311
+ index++, index === scriptsToExecute.length ? callback() : insertScriptsSequentially(scriptsToExecute, callback, index);
3312
+ });
3313
+ }
3314
+ function simulatePageLoad($container) {
3315
+ let $scriptsRoot = document4.getElementById(SCRIPTS_ROOT_ID);
3316
+ $scriptsRoot ? $scriptsRoot.innerHTML = "" : ($scriptsRoot = document4.createElement("div"), $scriptsRoot.id = SCRIPTS_ROOT_ID, document4.body.appendChild($scriptsRoot));
3317
+ let $scripts = Array.from($container.querySelectorAll(SCRIPT));
3318
+ if ($scripts.length) {
3319
+ let scriptsToExecute = [];
3320
+ $scripts.forEach(($script) => {
3321
+ let typeAttr = $script.getAttribute("type");
3322
+ (!typeAttr || runScriptTypes.includes(typeAttr)) && scriptsToExecute.push((callback) => insertScript($script, callback, $scriptsRoot));
3323
+ }), scriptsToExecute.length && insertScriptsSequentially(scriptsToExecute, simulateDOMContentLoaded, void 0);
3324
+ } else
3325
+ simulateDOMContentLoaded();
3326
+ }
3327
+
3328
+ // src/preview-api/modules/preview-web/emitTransformCode.ts
3329
+ async function emitTransformCode(source, context, warning) {
3330
+ let transform = context.parameters?.docs?.source?.transform, { id, unmappedArgs } = context, transformed = transform && source ? transform?.(source, context) : source, result = transformed ? await transformed : void 0;
3331
+ addons.getChannel().emit(SNIPPET_RENDERED, {
3332
+ id,
3333
+ source: result,
3334
+ args: unmappedArgs,
3335
+ warning
3336
+ });
3337
+ }
3338
+
3339
+ // src/shared/open-service/preview.ts
3340
+ var getService2 = getService;
3341
+ function registerService2(definition, registration) {
3342
+ return registerService(definition, registration, {
3343
+ staticLoader: createBrowserStaticLoader()
3344
+ });
3345
+ }
3346
+
3347
+ export {
3348
+ addons,
3349
+ HooksContext,
3350
+ applyHooks,
3351
+ useMemo,
3352
+ useCallback,
3353
+ useRef,
3354
+ useState,
3355
+ useReducer,
3356
+ useEffect,
3357
+ useChannel,
3358
+ useStoryContext,
3359
+ useParameter,
3360
+ useArgs,
3361
+ useGlobals,
3362
+ makeDecorator,
3363
+ combineArgs,
3364
+ normalizeArrays,
3365
+ normalizeStory,
3366
+ mountDestructured,
3367
+ decorateStory,
3368
+ sanitizeStoryContextUpdate,
3369
+ defaultDecorateStory,
3370
+ prepareStory,
3371
+ prepareMeta,
3372
+ normalizeProjectAnnotations,
3373
+ composeStepRunners,
3374
+ composeConfigs,
3375
+ ReporterAPI,
3376
+ getCsfFactoryAnnotations,
3377
+ setDefaultProjectAnnotations,
3378
+ setProjectAnnotations,
3379
+ composeStory,
3380
+ composeStories,
3381
+ StoryStore,
3382
+ userOrAutoTitleFromSpecifier,
3383
+ userOrAutoTitle,
3384
+ sortStoriesV7,
3385
+ Preview,
3386
+ DocsContext,
3387
+ PreviewWithSelection,
3388
+ UrlStore,
3389
+ WebView,
3390
+ PreviewWeb,
3391
+ simulateDOMContentLoaded,
3392
+ simulatePageLoad,
3393
+ emitTransformCode,
3394
+ getService2 as getService,
3395
+ registerService2 as registerService
3396
+ };