@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,1986 @@
1
+ import CJS_COMPAT_NODE_URL_ro17f80mg6k from 'node:url';
2
+ import CJS_COMPAT_NODE_PATH_ro17f80mg6k from 'node:path';
3
+ import CJS_COMPAT_NODE_MODULE_ro17f80mg6k from "node:module";
4
+
5
+ var __filename = CJS_COMPAT_NODE_URL_ro17f80mg6k.fileURLToPath(import.meta.url);
6
+ var __dirname = CJS_COMPAT_NODE_PATH_ro17f80mg6k.dirname(__filename);
7
+ var require = CJS_COMPAT_NODE_MODULE_ro17f80mg6k.createRequire(import.meta.url);
8
+
9
+ // ------------------------------------------------------------
10
+ // end of CJS compatibility banner, injected by Forkbook's esbuild configuration
11
+ // ------------------------------------------------------------
12
+ import {
13
+ nanoid
14
+ } from "./chunk-TEQGGSP7.js";
15
+ import {
16
+ isEqual
17
+ } from "./chunk-OWNFOGTA.js";
18
+ import {
19
+ deserializeError,
20
+ serializeError
21
+ } from "./chunk-3W7F2B7P.js";
22
+ import {
23
+ OpenServiceAsyncRecipeError,
24
+ OpenServiceAsyncSchemaError,
25
+ OpenServiceCyclicStateError,
26
+ OpenServiceInternalServiceError,
27
+ OpenServiceInvalidStaticPathError,
28
+ OpenServiceLoadedDrainExceededError,
29
+ OpenServiceMissingChannelError,
30
+ OpenServiceMissingServiceError,
31
+ OpenServiceOperationNameCollisionError,
32
+ OpenServiceRemoteCommandConfigDriftError,
33
+ OpenServiceRemoteCommandDisconnectedError,
34
+ OpenServiceRemoteCommandUnhandledError,
35
+ OpenServiceUnimplementedOperationError,
36
+ OpenServiceValidationError
37
+ } from "./chunk-U5W53R2J.js";
38
+
39
+ // src/channels/main.ts
40
+ var isMulti = (args) => args.transports !== void 0, generateRandomId = () => Math.random().toString(16).slice(2), Channel = class {
41
+ constructor(input = {}) {
42
+ this.sender = generateRandomId();
43
+ this.events = {};
44
+ this.data = {};
45
+ this.transports = [];
46
+ this.isAsync = input.async || !1, isMulti(input) ? (this.transports = input.transports || [], this.transports.forEach((t2) => {
47
+ t2.setHandler((event) => this.handleEvent(event));
48
+ })) : this.transports = input.transport ? [input.transport] : [], this.transports.forEach((t2) => {
49
+ t2.setHandler((event) => this.handleEvent(event));
50
+ });
51
+ }
52
+ get hasTransport() {
53
+ return this.transports.length > 0;
54
+ }
55
+ addListener(eventName, listener) {
56
+ this.events[eventName] = this.events[eventName] || [], this.events[eventName].push(listener);
57
+ }
58
+ emit(eventName, ...args) {
59
+ let event = { type: eventName, args, from: this.sender }, options = {};
60
+ args.length >= 1 && args[0] && args[0].options && (options = args[0].options);
61
+ let handler = () => {
62
+ this.transports.forEach((t2) => {
63
+ t2.send(event, options);
64
+ }), this.handleEvent(event);
65
+ };
66
+ this.isAsync ? setImmediate(handler) : handler();
67
+ }
68
+ last(eventName) {
69
+ return this.data[eventName];
70
+ }
71
+ eventNames() {
72
+ return Object.keys(this.events);
73
+ }
74
+ listenerCount(eventName) {
75
+ let listeners = this.listeners(eventName);
76
+ return listeners ? listeners.length : 0;
77
+ }
78
+ listeners(eventName) {
79
+ return this.events[eventName] || void 0;
80
+ }
81
+ once(eventName, listener) {
82
+ let onceListener = this.onceListener(eventName, listener);
83
+ this.addListener(eventName, onceListener);
84
+ }
85
+ removeAllListeners(eventName) {
86
+ eventName ? this.events[eventName] && delete this.events[eventName] : this.events = {};
87
+ }
88
+ removeListener(eventName, listener) {
89
+ let listeners = this.listeners(eventName);
90
+ listeners && (this.events[eventName] = listeners.filter((l3) => l3 !== listener));
91
+ }
92
+ on(eventName, listener) {
93
+ this.addListener(eventName, listener);
94
+ }
95
+ off(eventName, listener) {
96
+ this.removeListener(eventName, listener);
97
+ }
98
+ /**
99
+ * Deliver an event to local listeners without sending it to this channel's transports.
100
+ */
101
+ receive(event) {
102
+ this.handleEvent(event);
103
+ }
104
+ handleEvent(event) {
105
+ let listeners = this.listeners(event.type);
106
+ listeners && listeners.length && listeners.forEach((fn) => {
107
+ fn.apply(event, event.args);
108
+ }), this.data[event.type] = event.args;
109
+ }
110
+ onceListener(eventName, listener) {
111
+ let onceListener = (...args) => (this.removeListener(eventName, onceListener), listener(...args));
112
+ return onceListener;
113
+ }
114
+ };
115
+
116
+ // src/channels/channel-slot.ts
117
+ var channel;
118
+ function syncGlobalSlot(next) {
119
+ globalThis.__STORYBOOK_ADDONS_CHANNEL__ = next;
120
+ }
121
+ function getChannel() {
122
+ let fromGlobal = globalThis.__STORYBOOK_ADDONS_CHANNEL__;
123
+ return fromGlobal && (channel = fromGlobal), channel ?? null;
124
+ }
125
+ function setChannel(next) {
126
+ channel = next ?? void 0, syncGlobalSlot(channel);
127
+ }
128
+ function installNoopChannel() {
129
+ setChannel(new Channel({}));
130
+ }
131
+ function ensureChannel() {
132
+ getChannel() || installNoopChannel();
133
+ }
134
+ typeof window > "u" && ensureChannel();
135
+
136
+ // src/shared/open-service/service-channel.ts
137
+ import * as v from "valibot";
138
+
139
+ // src/shared/open-service/plain-object.ts
140
+ var FORBIDDEN_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]), MAX_DEPTH = 256;
141
+ function isReservedKey(key) {
142
+ return FORBIDDEN_KEYS.has(key) || key.startsWith("$");
143
+ }
144
+ function hasOwn(obj, key) {
145
+ return Object.prototype.hasOwnProperty.call(obj, key);
146
+ }
147
+ function isPlainObject(value) {
148
+ return typeof value == "object" && value !== null && !Array.isArray(value);
149
+ }
150
+ function clonePlain(value, depth = 0) {
151
+ if (value === null || typeof value != "object")
152
+ return value;
153
+ if (depth > MAX_DEPTH)
154
+ throw new OpenServiceCyclicStateError();
155
+ if (Array.isArray(value))
156
+ return value.map((entry) => clonePlain(entry, depth + 1));
157
+ let copy = {};
158
+ for (let key of Object.keys(value)) {
159
+ let entry = value[key];
160
+ isReservedKey(key) || entry === void 0 || (copy[key] = clonePlain(entry, depth + 1));
161
+ }
162
+ return copy;
163
+ }
164
+
165
+ // src/shared/open-service/service-channel.ts
166
+ var SERVICE_SYNC_REQUEST = "services:sync-request", SERVICE_SYNC_REPLY = "services:sync-reply", SERVICE_ENTRY = "services:entry", SERVICE_COMMAND_INVOKE = "services:command-invoke", SERVICE_COMMAND_ACK = "services:command-ack", SERVICE_COMMAND_RESULT = "services:command-result", SERVICE_COMMAND_ERROR = "services:command-error", SERVICE_COMMAND_UNHANDLED = "services:command-unhandled", stateSnapshotSchema = v.custom(isPlainObject), nonNegativeSafeInteger = v.pipe(v.number(), v.safeInteger(), v.minValue(0)), positiveSafeInteger = v.pipe(v.number(), v.safeInteger(), v.minValue(1)), RFC_6901_ENCODED_SEGMENT = /^(?:[^~]|~[01])*$/;
167
+ function decodeSegment(encoded) {
168
+ return encoded.replaceAll("~1", "/").replaceAll("~0", "~");
169
+ }
170
+ function encodePointer(segments) {
171
+ return segments.map((segment) => `/${segment.replaceAll("~", "~0").replaceAll("/", "~1")}`).join("");
172
+ }
173
+ function decodePointer(pointer) {
174
+ return pointer === "" ? [] : pointer.slice(1).split("/").map(decodeSegment);
175
+ }
176
+ function isRfc6901Pointer(pointer) {
177
+ return pointer.startsWith("/") ? pointer.slice(1).split("/").every((encoded) => RFC_6901_ENCODED_SEGMENT.test(encoded) && !isReservedKey(decodeSegment(encoded))) : !1;
178
+ }
179
+ var jsonPointerSchema = v.pipe(v.string(), v.check(isRfc6901Pointer)), jsonPatchOperationSchema = v.variant("op", [
180
+ v.object({ op: v.literal("add"), path: jsonPointerSchema, value: v.unknown() }),
181
+ v.object({ op: v.literal("replace"), path: jsonPointerSchema, value: v.unknown() }),
182
+ v.object({ op: v.literal("remove"), path: jsonPointerSchema })
183
+ ]), entryStampSchema = v.object({
184
+ seq: positiveSafeInteger,
185
+ runtimeId: v.string(),
186
+ counter: positiveSafeInteger
187
+ });
188
+ function entryStampKey(stamp) {
189
+ return `${stamp.seq}:${stamp.runtimeId}:${stamp.counter}`;
190
+ }
191
+ var entrySchema = v.object({
192
+ serviceId: v.string(),
193
+ stamp: entryStampSchema,
194
+ command: v.string(),
195
+ patch: v.pipe(v.array(jsonPatchOperationSchema), v.minLength(1))
196
+ }), frontierSchema = v.object({
197
+ vector: v.record(v.string(), nonNegativeSafeInteger),
198
+ clock: nonNegativeSafeInteger
199
+ }), syncRequestSchema = v.object({
200
+ serviceId: v.string(),
201
+ runtimeId: v.string(),
202
+ frontier: frontierSchema
203
+ }), syncReplySchema = v.object({
204
+ serviceId: v.string(),
205
+ runtimeId: v.string(),
206
+ frontier: frontierSchema,
207
+ state: stateSnapshotSchema
208
+ }), commandInvokeSchema = v.object({
209
+ serviceId: v.string(),
210
+ commandName: v.string(),
211
+ input: v.optional(v.unknown()),
212
+ callId: v.string(),
213
+ runtimeId: v.string()
214
+ }), commandAckSchema = v.object({
215
+ serviceId: v.string(),
216
+ callId: v.string(),
217
+ runtimeId: v.string()
218
+ }), commandUnhandledSchema = v.object({
219
+ serviceId: v.string(),
220
+ callId: v.string()
221
+ }), commandResultSchema = v.object({
222
+ serviceId: v.string(),
223
+ callId: v.string(),
224
+ result: v.optional(v.unknown()),
225
+ runtimeId: v.string()
226
+ }), commandErrorSchema = v.object({
227
+ serviceId: v.string(),
228
+ callId: v.string(),
229
+ error: v.custom(
230
+ (value) => typeof value == "object" && value !== null && !Array.isArray(value)
231
+ ),
232
+ runtimeId: v.string()
233
+ });
234
+ function generateRuntimeId() {
235
+ return nanoid();
236
+ }
237
+ function generateCallId() {
238
+ return nanoid();
239
+ }
240
+
241
+ // ../../node_modules/@preact/signals-core/dist/signals-core.mjs
242
+ var i = /* @__PURE__ */ Symbol.for("preact-signals");
243
+ function t() {
244
+ if (e > 1) {
245
+ e--;
246
+ return;
247
+ }
248
+ let i3, t2 = !1;
249
+ for ((function() {
250
+ let i4 = f;
251
+ for (f = void 0; i4 !== void 0; ) {
252
+ let t3 = i4.S;
253
+ if (t3.v === i4.v) for (let n3 = t3.t; n3 !== void 0; n3 = n3.x) n3.i === i4.i && (n3.i = t3.i);
254
+ i4 = i4.o;
255
+ }
256
+ })(); h !== void 0; ) {
257
+ let n3 = h;
258
+ for (h = void 0, c++; n3 !== void 0; ) {
259
+ let o3 = n3.u;
260
+ if (n3.u = void 0, n3.f &= -3, !(8 & n3.f) && w(n3)) try {
261
+ n3.c();
262
+ } catch (n4) {
263
+ t2 || (i3 = n4, t2 = !0);
264
+ }
265
+ n3 = o3;
266
+ }
267
+ }
268
+ if (c = 0, e--, t2) throw i3;
269
+ }
270
+ function n(i3) {
271
+ if (e > 0) return i3();
272
+ d = ++u, e++;
273
+ try {
274
+ return i3();
275
+ } finally {
276
+ t();
277
+ }
278
+ }
279
+ var o, s, h;
280
+ function r(i3) {
281
+ let t2 = o, n3 = s;
282
+ o = void 0, s = void 0;
283
+ try {
284
+ return i3();
285
+ } finally {
286
+ o = t2, s = n3;
287
+ }
288
+ }
289
+ var f, e = 0, c = 0, u = 0, d = 0, v2 = 0;
290
+ function l(i3) {
291
+ if (o === void 0) return;
292
+ let t2 = i3.n;
293
+ if (t2 === void 0 || t2.t !== o)
294
+ return t2 = { i: 0, S: i3, p: o.s, n: void 0, t: o, e: void 0, x: void 0, r: t2 }, o.s !== void 0 && (o.s.n = t2), o.s = t2, i3.n = t2, 32 & o.f && i3.S(t2), t2;
295
+ if (t2.i === -1)
296
+ return t2.i = 0, t2.n !== void 0 && (t2.n.p = t2.p, t2.p !== void 0 && (t2.p.n = t2.n), t2.p = o.s, t2.n = void 0, o.s.n = t2, o.s = t2), t2;
297
+ }
298
+ function a(i3, t2) {
299
+ this.v = i3, this.i = 0, this.n = void 0, this.t = void 0, this.l = 0, this.W = t2?.watched, this.Z = t2?.unwatched, this.name = t2?.name;
300
+ }
301
+ a.prototype.brand = i;
302
+ a.prototype.h = function() {
303
+ return !0;
304
+ };
305
+ a.prototype.S = function(i3) {
306
+ let t2 = this.t;
307
+ t2 !== i3 && i3.e === void 0 && (i3.x = t2, this.t = i3, t2 !== void 0 ? t2.e = i3 : r(() => {
308
+ var i4;
309
+ (i4 = this.W) == null || i4.call(this);
310
+ }));
311
+ };
312
+ a.prototype.U = function(i3) {
313
+ if (this.t !== void 0) {
314
+ let t2 = i3.e, n3 = i3.x;
315
+ t2 !== void 0 && (t2.x = n3, i3.e = void 0), n3 !== void 0 && (n3.e = t2, i3.x = void 0), i3 === this.t && (this.t = n3, n3 === void 0 && r(() => {
316
+ var i4;
317
+ (i4 = this.Z) == null || i4.call(this);
318
+ }));
319
+ }
320
+ };
321
+ a.prototype.subscribe = function(i3) {
322
+ return j(() => {
323
+ let t2 = this.value;
324
+ r(() => i3(t2));
325
+ }, { name: "sub" });
326
+ };
327
+ a.prototype.valueOf = function() {
328
+ return this.value;
329
+ };
330
+ a.prototype.toString = function() {
331
+ return this.value + "";
332
+ };
333
+ a.prototype.toJSON = function() {
334
+ return this.value;
335
+ };
336
+ a.prototype.peek = function() {
337
+ return r(() => this.value);
338
+ };
339
+ Object.defineProperty(a.prototype, "value", { get() {
340
+ let i3 = l(this);
341
+ return i3 !== void 0 && (i3.i = this.i), this.v;
342
+ }, set(i3) {
343
+ if (i3 !== this.v) {
344
+ if (c > 100) throw new Error("Cycle detected");
345
+ (function(i4) {
346
+ e !== 0 && c === 0 && i4.l !== d && (i4.l = d, f = { S: i4, v: i4.v, i: i4.i, o: f });
347
+ })(this), this.v = i3, this.i++, v2++, e++;
348
+ try {
349
+ for (let i4 = this.t; i4 !== void 0; i4 = i4.x) i4.t.N();
350
+ } finally {
351
+ t();
352
+ }
353
+ }
354
+ } });
355
+ function y(i3, t2) {
356
+ return new a(i3, t2);
357
+ }
358
+ function w(i3) {
359
+ for (let t2 = i3.s; t2 !== void 0; t2 = t2.n) if (t2.S.i !== t2.i || !t2.S.h() || t2.S.i !== t2.i) return !0;
360
+ return !1;
361
+ }
362
+ function _(i3) {
363
+ for (let t2 = i3.s; t2 !== void 0; t2 = t2.n) {
364
+ let n3 = t2.S.n;
365
+ if (n3 !== void 0 && (t2.r = n3), t2.S.n = t2, t2.i = -1, t2.n === void 0) {
366
+ i3.s = t2;
367
+ break;
368
+ }
369
+ }
370
+ }
371
+ function b(i3) {
372
+ let t2, n3 = i3.s;
373
+ for (; n3 !== void 0; ) {
374
+ let i4 = n3.p;
375
+ n3.i === -1 ? (n3.S.U(n3), i4 !== void 0 && (i4.n = n3.n), n3.n !== void 0 && (n3.n.p = i4)) : t2 = n3, n3.S.n = n3.r, n3.r !== void 0 && (n3.r = void 0), n3 = i4;
376
+ }
377
+ i3.s = t2;
378
+ }
379
+ function p(i3, t2) {
380
+ a.call(this, void 0, t2), this.x = i3, this.s = void 0, this.g = v2 - 1, this.f = 4;
381
+ }
382
+ p.prototype = new a();
383
+ p.prototype.h = function() {
384
+ if (this.f &= -3, 1 & this.f) return !1;
385
+ if ((36 & this.f) == 32 || (this.f &= -5, this.g === v2)) return !0;
386
+ if (this.g = v2, this.f |= 1, this.i > 0 && !w(this))
387
+ return this.f &= -2, !0;
388
+ let i3 = o;
389
+ try {
390
+ _(this), o = this;
391
+ let i4 = this.x();
392
+ (16 & this.f || this.v !== i4 || this.i === 0) && (this.v = i4, this.f &= -17, this.i++);
393
+ } catch (i4) {
394
+ this.v = i4, this.f |= 16, this.i++;
395
+ }
396
+ return o = i3, b(this), this.f &= -2, !0;
397
+ };
398
+ p.prototype.S = function(i3) {
399
+ if (this.t === void 0) {
400
+ this.f |= 36;
401
+ for (let i4 = this.s; i4 !== void 0; i4 = i4.n) i4.S.S(i4);
402
+ }
403
+ a.prototype.S.call(this, i3);
404
+ };
405
+ p.prototype.U = function(i3) {
406
+ if (this.t !== void 0 && (a.prototype.U.call(this, i3), this.t === void 0)) {
407
+ this.f &= -33;
408
+ for (let i4 = this.s; i4 !== void 0; i4 = i4.n) i4.S.U(i4);
409
+ }
410
+ };
411
+ p.prototype.N = function() {
412
+ if (!(2 & this.f)) {
413
+ this.f |= 6;
414
+ for (let i3 = this.t; i3 !== void 0; i3 = i3.x) i3.t.N();
415
+ }
416
+ };
417
+ Object.defineProperty(p.prototype, "value", { get() {
418
+ if (1 & this.f) throw new Error("Cycle detected");
419
+ let i3 = l(this);
420
+ if (this.h(), i3 !== void 0 && (i3.i = this.i), 16 & this.f) throw this.v;
421
+ return this.v;
422
+ } });
423
+ function g(i3, t2) {
424
+ return new p(i3, t2);
425
+ }
426
+ function S(i3) {
427
+ let n3 = i3.m;
428
+ if (i3.m = void 0, typeof n3 == "function") {
429
+ e++;
430
+ let s3 = o;
431
+ o = void 0;
432
+ try {
433
+ n3();
434
+ } catch (t2) {
435
+ throw i3.f &= -2, i3.f |= 8, m(i3), t2;
436
+ } finally {
437
+ o = s3, t();
438
+ }
439
+ }
440
+ }
441
+ function m(i3) {
442
+ for (let t2 = i3.s; t2 !== void 0; t2 = t2.n) t2.S.U(t2);
443
+ i3.x = void 0, i3.s = void 0, S(i3);
444
+ }
445
+ function x(i3) {
446
+ if (o !== this) throw new Error("Out-of-order effect");
447
+ b(this), o = i3, this.f &= -2, 8 & this.f && m(this), t();
448
+ }
449
+ function E(i3, t2) {
450
+ this.x = i3, this.m = void 0, this.s = void 0, this.u = void 0, this.f = 32, this.name = t2?.name, s && s.push(this);
451
+ }
452
+ E.prototype.c = function() {
453
+ let i3 = this.S();
454
+ try {
455
+ if (8 & this.f || this.x === void 0) return;
456
+ let t2 = this.x();
457
+ typeof t2 == "function" && (this.m = t2);
458
+ } finally {
459
+ i3();
460
+ }
461
+ };
462
+ E.prototype.S = function() {
463
+ if (1 & this.f) throw new Error("Cycle detected");
464
+ this.f |= 1, this.f &= -9, S(this), _(this), e++;
465
+ let i3 = o;
466
+ return o = this, x.bind(this, i3);
467
+ };
468
+ E.prototype.N = function() {
469
+ 2 & this.f || (this.f |= 2, this.u = h, h = this);
470
+ };
471
+ E.prototype.d = function() {
472
+ this.f |= 8, 1 & this.f || m(this);
473
+ };
474
+ E.prototype.dispose = function() {
475
+ this.d();
476
+ };
477
+ function j(i3, t2) {
478
+ let n3 = new E(i3, t2);
479
+ try {
480
+ n3.c();
481
+ } catch (i4) {
482
+ throw n3.d(), i4;
483
+ }
484
+ let o3 = n3.d.bind(n3);
485
+ return o3[Symbol.dispose] = o3, o3;
486
+ }
487
+
488
+ // ../../node_modules/deepsignal/core/dist/deepsignal-core.mjs
489
+ var n2 = /* @__PURE__ */ new WeakMap(), s2 = /* @__PURE__ */ new WeakMap(), a2 = /* @__PURE__ */ new WeakMap(), o2 = /* @__PURE__ */ new WeakSet(), l2 = /* @__PURE__ */ new WeakMap(), c2 = /^\$/, f2 = Object.getOwnPropertyDescriptor, g2 = !1, u2 = (e2) => {
490
+ if (!R(e2)) throw new Error("This object can't be observed.");
491
+ return s2.has(e2) || s2.set(e2, p2(e2, v3)), s2.get(e2);
492
+ }, i2 = (e2, t2) => {
493
+ g2 = !0;
494
+ let r2 = e2[t2];
495
+ try {
496
+ g2 = !1;
497
+ } catch {
498
+ }
499
+ return r2;
500
+ };
501
+ var p2 = (e2, t2) => {
502
+ let r2 = new Proxy(e2, t2);
503
+ return o2.add(r2), r2;
504
+ }, y2 = () => {
505
+ throw new Error("Don't mutate the signals directly.");
506
+ }, w2 = (e2) => (o3, l3, u3) => {
507
+ var i3;
508
+ if (g2) return Reflect.get(o3, l3, u3);
509
+ let h2 = e2 || l3[0] === "$";
510
+ if (!e2 && h2 && Array.isArray(o3)) {
511
+ if (l3 === "$") return a2.has(o3) || a2.set(o3, p2(o3, d2)), a2.get(o3);
512
+ h2 = l3 === "$length";
513
+ }
514
+ n2.has(u3) || n2.set(u3, /* @__PURE__ */ new Map());
515
+ let y3 = n2.get(u3), w3 = h2 ? l3.replace(c2, "") : l3;
516
+ if (y3.has(w3) || typeof ((i3 = f2(o3, w3)) == null ? void 0 : i3.get) != "function") {
517
+ let e3 = Reflect.get(o3, w3, u3);
518
+ if (h2 && typeof e3 == "function") return;
519
+ if (typeof w3 == "symbol" && b2.has(w3)) return e3;
520
+ y3.has(w3) || (R(e3) && (s2.has(e3) || s2.set(e3, p2(e3, v3)), e3 = s2.get(e3)), y3.set(w3, y(e3)));
521
+ } else y3.set(w3, g(() => Reflect.get(o3, w3, u3)));
522
+ return h2 ? y3.get(w3) : y3.get(w3).value;
523
+ }, v3 = { get: w2(!1), set(r2, a3, o3, g3) {
524
+ var u3;
525
+ if (typeof ((u3 = f2(r2, a3)) == null ? void 0 : u3.set) == "function") return Reflect.set(r2, a3, o3, g3);
526
+ n2.has(g3) || n2.set(g3, /* @__PURE__ */ new Map());
527
+ let i3 = n2.get(g3);
528
+ if (a3[0] === "$") {
529
+ o3 instanceof a || y2();
530
+ let t2 = a3.replace(c2, "");
531
+ return i3.set(t2, o3), Reflect.set(r2, t2, o3.peek(), g3);
532
+ }
533
+ {
534
+ let e2 = o3;
535
+ R(o3) && (s2.has(o3) || s2.set(o3, p2(o3, v3)), e2 = s2.get(o3));
536
+ let n3 = !(a3 in r2), c3 = Reflect.set(r2, a3, o3, g3);
537
+ return i3.has(a3) ? i3.get(a3).value = e2 : i3.set(a3, y(e2)), n3 && l2.has(r2) && l2.get(r2).value++, Array.isArray(r2) && i3.has("length") && (i3.get("length").value = r2.length), c3;
538
+ }
539
+ }, deleteProperty(e2, t2) {
540
+ t2[0] === "$" && y2();
541
+ let r2 = n2.get(s2.get(e2)), a3 = Reflect.deleteProperty(e2, t2);
542
+ return r2 && r2.has(t2) && (r2.get(t2).value = void 0), l2.has(e2) && l2.get(e2).value++, a3;
543
+ }, ownKeys: (e2) => (l2.has(e2) || l2.set(e2, y(0)), l2._ = l2.get(e2).value, Reflect.ownKeys(e2)) }, d2 = { get: w2(!0), set: y2, deleteProperty: y2 }, b2 = new Set(Object.getOwnPropertyNames(Symbol).map((e2) => Symbol[e2]).filter((e2) => typeof e2 == "symbol")), m2 = /* @__PURE__ */ new Set([Object, Array]), R = (e2) => typeof e2 == "object" && e2 !== null && m2.has(e2.constructor) && !o2.has(e2);
544
+
545
+ // src/shared/open-service/patch-recorder.ts
546
+ function peekProp(obj, key) {
547
+ return i2(obj, key);
548
+ }
549
+ function isPrimitive(value) {
550
+ return value === null || typeof value != "object";
551
+ }
552
+ function ownValue(inner, name) {
553
+ let existed = hasOwn(inner, name);
554
+ return { existed, firstValue: existed ? clonePlain(peekProp(inner, name)) : void 0 };
555
+ }
556
+ var activeDrafts = /* @__PURE__ */ new WeakMap();
557
+ function readPath(root, segments) {
558
+ let current = root;
559
+ for (let segment of segments) {
560
+ if (current === null || typeof current != "object")
561
+ return { found: !1, value: void 0 };
562
+ if (!hasOwn(current, segment))
563
+ return { found: !1, value: void 0 };
564
+ current = peekProp(current, segment);
565
+ }
566
+ return { found: !0, value: current };
567
+ }
568
+ function recordPatch(state, mutate, author) {
569
+ let activeDraft = activeDrafts.get(state);
570
+ if (activeDraft) {
571
+ let nested = mutate(activeDraft);
572
+ if (isThenable(nested))
573
+ throw Promise.resolve(nested).catch(() => {
574
+ }), new OpenServiceAsyncRecipeError();
575
+ return;
576
+ }
577
+ let root = state, touches = /* @__PURE__ */ new Map(), order = [], wrapperByTarget = /* @__PURE__ */ new WeakMap(), targetByWrapper = /* @__PURE__ */ new WeakMap(), revokes = [], preRecipeValue = (segments) => {
578
+ let { found, value } = readPath(root, segments);
579
+ if (!found)
580
+ return { existed: !1, firstValue: void 0 };
581
+ let snapshot = clonePlain(value), prefix = encodePointer(segments);
582
+ for (let pointer of order.toReversed()) {
583
+ if (!pointer.startsWith(`${prefix}/`))
584
+ continue;
585
+ let descendant = touches.get(pointer), parent = snapshot, relative = descendant.segments.slice(segments.length);
586
+ for (let segment of relative.slice(0, -1))
587
+ parent = parent !== null && typeof parent == "object" ? parent[segment] : void 0;
588
+ if (parent === null || typeof parent != "object")
589
+ continue;
590
+ let key = relative[relative.length - 1];
591
+ descendant.existed ? parent[key] = clonePlain(descendant.firstValue) : delete parent[key];
592
+ }
593
+ return { existed: !0, firstValue: snapshot };
594
+ }, note = (segments, capture) => {
595
+ let pointer = encodePointer(segments);
596
+ if (touches.has(pointer))
597
+ return;
598
+ let prefix = `${pointer}/`, subsumesEarlierTouch = order.some((recorded) => recorded.startsWith(prefix));
599
+ touches.set(pointer, {
600
+ segments,
601
+ ...subsumesEarlierTouch ? preRecipeValue(segments) : capture()
602
+ }), order.push(pointer);
603
+ }, noteArray = (arrayRoot) => {
604
+ note(arrayRoot.path, () => ({ existed: !0, firstValue: clonePlain(arrayRoot.target) }));
605
+ }, storedValue = (value) => value === null || typeof value != "object" ? value : clonePlain(targetByWrapper.get(value) ?? value), isUnchangedAssignment = (inner, name, value) => {
606
+ if (!hasOwn(inner, name))
607
+ return !1;
608
+ if (Object.is(peekProp(inner, name), value))
609
+ return !0;
610
+ if (value !== null && typeof value == "object") {
611
+ let target = targetByWrapper.get(value);
612
+ return target !== void 0 && Object.is(Reflect.get(inner, name), target);
613
+ }
614
+ return !1;
615
+ }, wrap = (target, path, arrayRoot) => {
616
+ let cached = wrapperByTarget.get(target);
617
+ if (cached)
618
+ return cached;
619
+ let effectiveArrayRoot = arrayRoot ?? (Array.isArray(target) ? { path, target } : null), { proxy, revoke } = Proxy.revocable(target, {
620
+ get(inner, key) {
621
+ if (typeof key == "symbol")
622
+ return Reflect.get(inner, key);
623
+ if (FORBIDDEN_KEYS.has(key) || key.startsWith("$"))
624
+ return;
625
+ let value = Reflect.get(inner, key);
626
+ return typeof value == "function" ? value : value !== null && typeof value == "object" ? wrap(value, path.concat(String(key)), effectiveArrayRoot) : value;
627
+ },
628
+ set(inner, key, value) {
629
+ if (typeof key == "symbol")
630
+ return Reflect.set(inner, key, value);
631
+ let name = String(key);
632
+ if (FORBIDDEN_KEYS.has(name))
633
+ return !0;
634
+ if (name.startsWith("$")) {
635
+ let plain = name.slice(1);
636
+ return FORBIDDEN_KEYS.has(plain) ? !0 : (note(path.concat(plain), () => ownValue(inner, plain)), Reflect.set(inner, key, value));
637
+ }
638
+ if (isUnchangedAssignment(inner, name, value))
639
+ return !0;
640
+ if (effectiveArrayRoot)
641
+ return noteArray(effectiveArrayRoot), Reflect.set(inner, name, storedValue(value));
642
+ let segments = path.concat(name);
643
+ return value === void 0 ? hasOwn(inner, name) ? (note(segments, () => ownValue(inner, name)), Reflect.deleteProperty(inner, name)) : !0 : (note(segments, () => ownValue(inner, name)), Reflect.set(inner, name, storedValue(value)));
644
+ },
645
+ deleteProperty(inner, key) {
646
+ if (typeof key == "symbol")
647
+ return Reflect.deleteProperty(inner, key);
648
+ let name = String(key);
649
+ return FORBIDDEN_KEYS.has(name) ? !0 : name.startsWith("$") ? Reflect.deleteProperty(inner, key) : hasOwn(inner, name) ? effectiveArrayRoot ? (noteArray(effectiveArrayRoot), Reflect.deleteProperty(inner, name)) : (note(path.concat(name), () => ownValue(inner, name)), Reflect.deleteProperty(inner, name)) : !0;
650
+ }
651
+ });
652
+ return revokes.push(revoke), wrapperByTarget.set(target, proxy), targetByWrapper.set(proxy, target), proxy;
653
+ }, flush = () => {
654
+ let touched = new Set(order), ops = [], inverse = [];
655
+ for (let pointer of order) {
656
+ let touch = touches.get(pointer);
657
+ if (touch.segments.some((_2, index) => index === 0 ? !1 : touched.has(encodePointer(touch.segments.slice(0, index)))))
658
+ continue;
659
+ let { found, value } = readPath(root, touch.segments);
660
+ if (!found) {
661
+ touch.existed && (ops.push({ op: "remove", path: pointer }), inverse.push({ op: "add", path: pointer, value: touch.firstValue }));
662
+ continue;
663
+ }
664
+ isPrimitive(value) && Object.is(value, touch.firstValue) || (ops.push({
665
+ op: touch.existed ? "replace" : "add",
666
+ path: pointer,
667
+ value: clonePlain(value)
668
+ }), inverse.push(
669
+ touch.existed ? { op: "replace", path: pointer, value: touch.firstValue } : { op: "remove", path: pointer }
670
+ ));
671
+ }
672
+ return { ops, inverse };
673
+ };
674
+ n(() => {
675
+ r(() => {
676
+ let draft = wrap(state, [], null);
677
+ activeDrafts.set(state, draft);
678
+ try {
679
+ let result = mutate(draft);
680
+ if (isThenable(result))
681
+ throw Promise.resolve(result).catch(() => {
682
+ }), new OpenServiceAsyncRecipeError();
683
+ } finally {
684
+ activeDrafts.delete(state);
685
+ for (let revoke of revokes)
686
+ revoke();
687
+ let recorded = flush();
688
+ recorded.ops.length > 0 && author(recorded);
689
+ }
690
+ });
691
+ });
692
+ }
693
+ function isThenable(value) {
694
+ return value !== null && typeof value == "object" && typeof value.then == "function";
695
+ }
696
+
697
+ // src/shared/open-service/query-state.ts
698
+ function buildQueryState(data, lifecycle) {
699
+ let isPending = lifecycle.status === "pending", isLoading = lifecycle.loadStatus === "loading";
700
+ return {
701
+ data,
702
+ error: lifecycle.error,
703
+ status: lifecycle.status,
704
+ loadStatus: lifecycle.loadStatus,
705
+ isPending,
706
+ isSuccess: lifecycle.status === "success",
707
+ isError: lifecycle.status === "error",
708
+ isLoading,
709
+ isInitialLoading: isPending && isLoading && data === void 0,
710
+ isRefreshing: isLoading && !isPending
711
+ };
712
+ }
713
+ function toError(value) {
714
+ return value instanceof Error ? value : new Error(String(value));
715
+ }
716
+
717
+ // src/shared/open-service/service-validation.ts
718
+ function rethrowAsync(error) {
719
+ queueMicrotask(() => {
720
+ throw error;
721
+ });
722
+ }
723
+ async function validateSchema(schema, value, meta) {
724
+ let validationResult = await schema["~standard"].validate(value);
725
+ if (validationResult.issues)
726
+ throw new OpenServiceValidationError({ ...meta, issues: validationResult.issues });
727
+ return validationResult.value;
728
+ }
729
+ function validateSchemaSync(schema, value, meta) {
730
+ let validationResult = schema["~standard"].validate(value);
731
+ if (validationResult instanceof Promise)
732
+ throw new OpenServiceAsyncSchemaError({
733
+ kind: meta.kind,
734
+ serviceId: meta.serviceId,
735
+ name: meta.name,
736
+ phase: meta.phase
737
+ });
738
+ if (validationResult.issues)
739
+ throw new OpenServiceValidationError({ ...meta, issues: validationResult.issues });
740
+ return validationResult.value;
741
+ }
742
+
743
+ // src/shared/open-service/query-runtime.ts
744
+ var MAX_DRAIN_ITERATIONS = 32, inFlightLoads = /* @__PURE__ */ new Map(), nextLoadScopeSequence = 0, nextLoadScopeId = () => String(nextLoadScopeSequence += 1), activeHandlerLoadSession, EMPTY_SET = /* @__PURE__ */ new Set();
745
+ function stableHash(value) {
746
+ let encode = (raw) => {
747
+ if (raw === void 0)
748
+ return { __t: "undefined" };
749
+ if (raw === null || typeof raw != "object")
750
+ return raw;
751
+ if (Array.isArray(raw))
752
+ return raw.map(encode);
753
+ let sorted = {};
754
+ for (let k of Object.keys(raw).sort())
755
+ sorted[k] = encode(raw[k]);
756
+ return { __t: "object", value: sorted };
757
+ };
758
+ return JSON.stringify(encode(value));
759
+ }
760
+ function makeInFlightKey(loadScopeId, loadKey) {
761
+ return `${loadScopeId}::${loadKey}`;
762
+ }
763
+ function makeLoadKey(serviceId, queryName, validatedInput) {
764
+ return `${serviceId}::${queryName}::${stableHash(validatedInput)}`;
765
+ }
766
+ function surfaceRejections(settlements) {
767
+ let rejections = settlements.filter((s3) => s3.status === "rejected");
768
+ if (rejections.length === 0)
769
+ return;
770
+ let [first, ...rest] = rejections.map((r2) => r2.reason);
771
+ if (rest.length > 0 && first instanceof Error && Reflect.get(first, "cause") === void 0)
772
+ try {
773
+ Reflect.set(first, "cause", { aggregated: rest });
774
+ } catch {
775
+ }
776
+ throw first;
777
+ }
778
+ async function drainCollector(collector, settledKeys, serviceId, queryName) {
779
+ let iterations = 0;
780
+ for (; collector.size > 0; ) {
781
+ if (iterations++ > MAX_DRAIN_ITERATIONS)
782
+ throw new OpenServiceLoadedDrainExceededError({
783
+ serviceId,
784
+ name: queryName,
785
+ iterations: MAX_DRAIN_ITERATIONS
786
+ });
787
+ let pending = [...collector];
788
+ collector.clear();
789
+ let settlements = await Promise.allSettled(pending.map((entry) => entry.promise));
790
+ if (settledKeys)
791
+ for (let entry of pending)
792
+ settledKeys.add(entry.key);
793
+ surfaceRejections(settlements);
794
+ }
795
+ }
796
+ function detachSnapshot(value) {
797
+ return value === null || typeof value != "object" ? value : JSON.parse(JSON.stringify(value));
798
+ }
799
+ function validateQueryInput(refs, queryName, queryDef, input) {
800
+ return validateSchemaSync(queryDef.input, input, {
801
+ kind: "query",
802
+ serviceId: refs.serviceId,
803
+ name: queryName,
804
+ phase: "input"
805
+ });
806
+ }
807
+ function validateQueryOutput(refs, queryName, queryDef, output) {
808
+ return validateSchemaSync(queryDef.output, output, {
809
+ kind: "query",
810
+ serviceId: refs.serviceId,
811
+ name: queryName,
812
+ phase: "output"
813
+ });
814
+ }
815
+ function runHandlerSync(refs, queryName, queryDef, validatedInput, selfQueries, getService2) {
816
+ if (!queryDef.handler)
817
+ throw new OpenServiceUnimplementedOperationError({
818
+ kind: "query",
819
+ serviceId: refs.serviceId,
820
+ name: queryName
821
+ });
822
+ let handlerCtx = { self: {
823
+ get state() {
824
+ return refs.state;
825
+ },
826
+ queries: selfQueries
827
+ }, getService: getService2 };
828
+ return queryDef.handler(validatedInput, handlerCtx);
829
+ }
830
+ function createQueryGet(refs, queryName, queryDef, selfQueries, fireLoad) {
831
+ return function(input) {
832
+ let validatedInput = validateQueryInput(
833
+ refs,
834
+ queryName,
835
+ queryDef,
836
+ arguments.length === 0 ? void 0 : input
837
+ );
838
+ return queryDef.load && fireLoad?.(validatedInput), validateQueryOutput(
839
+ refs,
840
+ queryName,
841
+ queryDef,
842
+ runHandlerSync(
843
+ refs,
844
+ queryName,
845
+ queryDef,
846
+ validatedInput,
847
+ selfQueries,
848
+ refs.registryApi.getService
849
+ )
850
+ );
851
+ };
852
+ }
853
+ function triggerLoad(refs, queryName, queryDef, validatedInput, loadKey, parentAncestorChain) {
854
+ let inFlightKey = makeInFlightKey(refs.loadScopeId, loadKey), existing = inFlightLoads.get(inFlightKey);
855
+ if (existing)
856
+ return existing;
857
+ let extendedChain = new Set(parentAncestorChain);
858
+ extendedChain.add(loadKey);
859
+ let promise = Promise.resolve().then(() => runLoadBody(refs, queryName, queryDef, validatedInput, extendedChain)).finally(() => {
860
+ inFlightLoads.get(inFlightKey) === promise && inFlightLoads.delete(inFlightKey);
861
+ });
862
+ return inFlightLoads.set(inFlightKey, promise), promise;
863
+ }
864
+ async function runLoadBody(refs, queryName, queryDef, validatedInput, ancestorChain) {
865
+ if (!queryDef.load)
866
+ return;
867
+ let collector = /* @__PURE__ */ new Set(), wrappedQueries = buildLoadWrappedQueries(refs, ancestorChain, collector), loadCtx = { self: {
868
+ get state() {
869
+ return refs.state;
870
+ },
871
+ queries: wrappedQueries,
872
+ commands: refs.getLoadCommands()
873
+ }, getService: refs.registryApi.getService };
874
+ await Promise.resolve(queryDef.load(validatedInput, loadCtx)), await drainCollector(collector, void 0, refs.serviceId, queryName);
875
+ }
876
+ async function runReactiveLoad(refs, queryName, queryDef, validatedInput, isCurrent) {
877
+ if (!queryDef.load)
878
+ return;
879
+ let loadCtx = { self: {
880
+ get state() {
881
+ return refs.state;
882
+ },
883
+ // Reactive-load reads must keep dependency loads warm. `.get()` on a default query is a pure
884
+ // read and never fires a load, so the body sees fire-and-forget wrappers instead: reading a
885
+ // dependency triggers its load (deduped while in flight) without awaiting a drain.
886
+ queries: refs.reactiveLoadQueries,
887
+ commands: refs.buildGatedCommands(isCurrent)
888
+ }, getService: refs.registryApi.getService };
889
+ await Promise.resolve(queryDef.load(validatedInput, loadCtx));
890
+ }
891
+ function buildReactiveLoadQueries(refs) {
892
+ let wrappedQueries = {};
893
+ for (let [name, queryDef] of refs.queryDefinitions) {
894
+ let defaultQuery = refs.defaultQueries[name], get = createQueryGet(refs, name, queryDef, wrappedQueries, (validatedInput) => {
895
+ let loadKey = makeLoadKey(refs.serviceId, name, validatedInput);
896
+ triggerLoad(refs, name, queryDef, validatedInput, loadKey, EMPTY_SET).catch(rethrowAsync);
897
+ });
898
+ wrappedQueries[name] = {
899
+ get,
900
+ loaded: defaultQuery.loaded,
901
+ subscribe: defaultQuery.subscribe
902
+ };
903
+ }
904
+ return wrappedQueries;
905
+ }
906
+ function buildLoadWrappedQueries(refs, ancestorChain, collector) {
907
+ let wrappedQueries = {};
908
+ for (let [name, queryDef] of refs.queryDefinitions) {
909
+ let defaultQuery = refs.defaultQueries[name], wrapped = {
910
+ get: createQueryGet(refs, name, queryDef, wrappedQueries, (validatedInput) => {
911
+ let loadKey = makeLoadKey(refs.serviceId, name, validatedInput), promise = triggerLoad(refs, name, queryDef, validatedInput, loadKey, ancestorChain);
912
+ ancestorChain.has(loadKey) || collector.add({ key: loadKey, promise });
913
+ }),
914
+ loaded(input) {
915
+ return runLoaded(
916
+ refs,
917
+ name,
918
+ queryDef,
919
+ arguments.length === 0 ? void 0 : input,
920
+ ancestorChain
921
+ );
922
+ },
923
+ subscribe: defaultQuery.subscribe
924
+ };
925
+ wrappedQueries[name] = wrapped;
926
+ }
927
+ return wrappedQueries;
928
+ }
929
+ async function runLoaded(refs, queryName, queryDef, rawInput, parentAncestorChain = EMPTY_SET) {
930
+ let validatedInput = validateQueryInput(refs, queryName, queryDef, rawInput), loadKey = makeLoadKey(refs.serviceId, queryName, validatedInput), ancestorChain = new Set(parentAncestorChain);
931
+ ancestorChain.add(loadKey);
932
+ let session = {
933
+ ancestorChain,
934
+ collector: /* @__PURE__ */ new Set(),
935
+ settledKeys: /* @__PURE__ */ new Set()
936
+ };
937
+ if (queryDef.load && !parentAncestorChain.has(loadKey)) {
938
+ let promise = triggerLoad(
939
+ refs,
940
+ queryName,
941
+ queryDef,
942
+ validatedInput,
943
+ loadKey,
944
+ parentAncestorChain
945
+ );
946
+ session.collector.add({ key: loadKey, promise });
947
+ }
948
+ let iterations = 0, hasMoreWork = !0;
949
+ for (; hasMoreWork; ) {
950
+ if (iterations++ > MAX_DRAIN_ITERATIONS)
951
+ throw new OpenServiceLoadedDrainExceededError({
952
+ serviceId: refs.serviceId,
953
+ name: queryName,
954
+ iterations: MAX_DRAIN_ITERATIONS
955
+ });
956
+ for (; session.collector.size > 0; ) {
957
+ let pending = [...session.collector];
958
+ session.collector.clear();
959
+ let settlements = await Promise.allSettled(pending.map((entry) => entry.promise));
960
+ for (let entry of pending)
961
+ session.settledKeys.add(entry.key);
962
+ surfaceRejections(settlements);
963
+ }
964
+ let previousSession2 = activeHandlerLoadSession;
965
+ activeHandlerLoadSession = session;
966
+ try {
967
+ runHandlerSync(
968
+ refs,
969
+ queryName,
970
+ queryDef,
971
+ validatedInput,
972
+ refs.defaultQueries,
973
+ refs.registryApi.getService
974
+ );
975
+ } catch {
976
+ } finally {
977
+ activeHandlerLoadSession = previousSession2;
978
+ }
979
+ hasMoreWork = session.collector.size > 0;
980
+ }
981
+ let previousSession = activeHandlerLoadSession;
982
+ activeHandlerLoadSession = session;
983
+ try {
984
+ return validateQueryOutput(
985
+ refs,
986
+ queryName,
987
+ queryDef,
988
+ runHandlerSync(
989
+ refs,
990
+ queryName,
991
+ queryDef,
992
+ validatedInput,
993
+ refs.defaultQueries,
994
+ refs.registryApi.getService
995
+ )
996
+ );
997
+ } finally {
998
+ activeHandlerLoadSession = previousSession;
999
+ }
1000
+ }
1001
+ function createDefaultQuery(refs, queryName, queryDef) {
1002
+ let resolveInput = (input, argsLength) => argsLength === 0 ? void 0 : input;
1003
+ return {
1004
+ get: createQueryGet(refs, queryName, queryDef, refs.defaultQueries, (validatedInput) => {
1005
+ let session = activeHandlerLoadSession;
1006
+ if (!session)
1007
+ return;
1008
+ let loadKey = makeLoadKey(refs.serviceId, queryName, validatedInput);
1009
+ if (!session.ancestorChain.has(loadKey) && !session.settledKeys.has(loadKey)) {
1010
+ let promise = triggerLoad(
1011
+ refs,
1012
+ queryName,
1013
+ queryDef,
1014
+ validatedInput,
1015
+ loadKey,
1016
+ session.ancestorChain
1017
+ );
1018
+ session.collector.add({ key: loadKey, promise });
1019
+ }
1020
+ }),
1021
+ loaded(input) {
1022
+ return runLoaded(refs, queryName, queryDef, resolveInput(input, arguments.length));
1023
+ },
1024
+ subscribe: ((...args) => {
1025
+ if (args.length === 1 && typeof args[0] == "function")
1026
+ return subscribeToQuery(
1027
+ refs,
1028
+ queryName,
1029
+ queryDef,
1030
+ void 0,
1031
+ void 0,
1032
+ args[0]
1033
+ );
1034
+ if (args.length === 2 && typeof args[0] == "function" && typeof args[1] == "function")
1035
+ return subscribeToQuery(
1036
+ refs,
1037
+ queryName,
1038
+ queryDef,
1039
+ void 0,
1040
+ args[0],
1041
+ args[1]
1042
+ );
1043
+ let [input, selectorOrCallback, maybeCallback] = args;
1044
+ return subscribeToQuery(
1045
+ refs,
1046
+ queryName,
1047
+ queryDef,
1048
+ input,
1049
+ maybeCallback ? selectorOrCallback : void 0,
1050
+ maybeCallback ?? selectorOrCallback
1051
+ );
1052
+ })
1053
+ };
1054
+ }
1055
+ function subscribeToQuery(refs, queryName, queryDef, rawInput, selector, callback) {
1056
+ let active = !0, validatedInput;
1057
+ try {
1058
+ validatedInput = validateQueryInput(refs, queryName, queryDef, rawInput);
1059
+ } catch (error) {
1060
+ return callback(
1061
+ buildQueryState(void 0, { status: "error", error: toError(error), loadStatus: "idle" })
1062
+ ), () => {
1063
+ active = !1;
1064
+ };
1065
+ }
1066
+ let lifecycle = y({
1067
+ status: queryDef.load ? "pending" : "success",
1068
+ error: void 0,
1069
+ loadStatus: "idle"
1070
+ }), loadTeardown;
1071
+ if (queryDef.load) {
1072
+ let epoch = 0;
1073
+ loadTeardown = j(() => {
1074
+ let myEpoch = ++epoch, isCurrent = () => myEpoch === epoch, previous = r(() => lifecycle.value);
1075
+ lifecycle.value = {
1076
+ status: previous.status,
1077
+ error: previous.error,
1078
+ loadStatus: "loading"
1079
+ }, runReactiveLoad(refs, queryName, queryDef, validatedInput, isCurrent).then(
1080
+ () => {
1081
+ isCurrent() && (lifecycle.value = { status: "success", error: void 0, loadStatus: "idle" });
1082
+ },
1083
+ (error) => {
1084
+ isCurrent() && (lifecycle.value = { status: "error", error: toError(error), loadStatus: "idle" });
1085
+ }
1086
+ );
1087
+ });
1088
+ }
1089
+ let comp = g(() => {
1090
+ let output = runHandlerSync(
1091
+ refs,
1092
+ queryName,
1093
+ queryDef,
1094
+ validatedInput,
1095
+ refs.defaultQueries,
1096
+ refs.registryApi.getService
1097
+ );
1098
+ if (selector) {
1099
+ let validated = r(() => validateQueryOutput(refs, queryName, queryDef, output));
1100
+ return selector(output), detachSnapshot(selector(validated));
1101
+ }
1102
+ return detachSnapshot(validateQueryOutput(refs, queryName, queryDef, output));
1103
+ }), hasEmitted = !1, lastEmitted, lastData, teardown = j(() => {
1104
+ let life = lifecycle.value, data, status = life.status, error = life.error;
1105
+ try {
1106
+ data = comp.value, lastData = data;
1107
+ } catch (handlerError) {
1108
+ data = lastData, status = "error", error = toError(handlerError);
1109
+ }
1110
+ if (!active)
1111
+ return;
1112
+ let state = buildQueryState(data, { status, error, loadStatus: life.loadStatus });
1113
+ hasEmitted && isEqual(state, lastEmitted) || (hasEmitted = !0, lastEmitted = state, callback(state));
1114
+ });
1115
+ return () => {
1116
+ active = !1, teardown(), loadTeardown?.();
1117
+ };
1118
+ }
1119
+ function buildQueries(refs) {
1120
+ let result = {};
1121
+ for (let [name, queryDef] of refs.queryDefinitions)
1122
+ result[name] = createDefaultQuery(refs, name, queryDef);
1123
+ return result;
1124
+ }
1125
+
1126
+ // src/shared/open-service/service-sync.ts
1127
+ import { logger } from "@aussieljk/forkbook/internal/client-logger";
1128
+
1129
+ // src/shared/open-service/json-patch.ts
1130
+ function parentAt(root, segments) {
1131
+ let current = root;
1132
+ for (let index = 0; index < segments.length - 1; index += 1) {
1133
+ let segment = segments[index];
1134
+ if (isReservedKey(segment) || !isPlainObject(current) || !hasOwn(current, segment))
1135
+ return;
1136
+ current = current[segment];
1137
+ }
1138
+ if (isPlainObject(current))
1139
+ return { parent: current, key: segments[segments.length - 1] };
1140
+ }
1141
+ var MissingParentError = class extends Error {
1142
+ constructor(path) {
1143
+ super(`Missing parent for JSON Patch path ${path}`), this.name = "MissingParentError", this.path = path;
1144
+ }
1145
+ };
1146
+ function applyJsonPatch(target, patch, onMissingRemove) {
1147
+ let undo = [], inverse = [], currentPath = "";
1148
+ try {
1149
+ for (let operation of patch)
1150
+ currentPath = operation.path, applyOne(target, operation, undo, inverse, onMissingRemove);
1151
+ return { ok: !0, inverse: inverse.toReversed() };
1152
+ } catch (error) {
1153
+ for (let revert of undo.toReversed())
1154
+ revert();
1155
+ return error instanceof MissingParentError ? { ok: !1, path: error.path } : { ok: !1, path: currentPath };
1156
+ }
1157
+ }
1158
+ function applyOne(target, operation, undo, inverse, onMissingRemove) {
1159
+ if (!isRfc6901Pointer(operation.path))
1160
+ throw new MissingParentError(operation.path);
1161
+ let location = parentAt(target, decodePointer(operation.path));
1162
+ if (!location || isReservedKey(location.key))
1163
+ throw new MissingParentError(operation.path);
1164
+ let { parent, key } = location;
1165
+ switch (operation.op) {
1166
+ case "add":
1167
+ case "replace": {
1168
+ let existed = hasOwn(parent, key), previous = existed ? clonePlain(parent[key]) : void 0;
1169
+ parent[key] = clonePlain(operation.value), undo.push(() => {
1170
+ existed ? parent[key] = previous : delete parent[key];
1171
+ }), existed ? inverse.push({ op: "replace", path: operation.path, value: previous }) : inverse.push({ op: "remove", path: operation.path });
1172
+ return;
1173
+ }
1174
+ case "remove": {
1175
+ if (!hasOwn(parent, key)) {
1176
+ onMissingRemove(operation.path);
1177
+ return;
1178
+ }
1179
+ let previous = clonePlain(parent[key]);
1180
+ delete parent[key], undo.push(() => {
1181
+ parent[key] = previous;
1182
+ }), inverse.push({ op: "add", path: operation.path, value: previous });
1183
+ return;
1184
+ }
1185
+ default: {
1186
+ let exhaustive = operation;
1187
+ }
1188
+ }
1189
+ }
1190
+
1191
+ // src/shared/open-service/service-sync.ts
1192
+ var DEFAULT_LOG_MAX_AGE_MS = 15e3, DEFAULT_LOG_MAX_ENTRIES = 256;
1193
+ function vectorCounter(vector, runtimeId) {
1194
+ return vector[runtimeId] ?? 0;
1195
+ }
1196
+ function isEmptyVector(vector) {
1197
+ for (let value of Object.values(vector))
1198
+ if (value > 0)
1199
+ return !1;
1200
+ return !0;
1201
+ }
1202
+ function vectorDominates(left, right) {
1203
+ if (isEmptyVector(right))
1204
+ return !isEmptyVector(left);
1205
+ let keys = /* @__PURE__ */ new Set([...Object.keys(left), ...Object.keys(right)]), greater = !1;
1206
+ for (let key of keys) {
1207
+ let leftCount = vectorCounter(left, key), rightCount = vectorCounter(right, key);
1208
+ if (leftCount < rightCount)
1209
+ return !1;
1210
+ leftCount > rightCount && (greater = !0);
1211
+ }
1212
+ return greater;
1213
+ }
1214
+ function vectorsEqual(left, right) {
1215
+ let keys = /* @__PURE__ */ new Set([...Object.keys(left), ...Object.keys(right)]);
1216
+ for (let key of keys)
1217
+ if (vectorCounter(left, key) !== vectorCounter(right, key))
1218
+ return !1;
1219
+ return !0;
1220
+ }
1221
+ function vectorsConcurrent(left, right) {
1222
+ return !vectorDominates(left, right) && !vectorDominates(right, left) && !vectorsEqual(left, right);
1223
+ }
1224
+ function formatFrontier(frontier) {
1225
+ let body = Object.keys(frontier.vector).sort().map((key) => `${key}:${frontier.vector[key]}`).join(",");
1226
+ return `{clock:${frontier.clock} vector:{${body}}}`;
1227
+ }
1228
+ function compareStamps(left, right) {
1229
+ return left.seq !== right.seq ? left.seq < right.seq ? -1 : 1 : left.runtimeId !== right.runtimeId ? left.runtimeId < right.runtimeId ? -1 : 1 : 0;
1230
+ }
1231
+ function applyStatePatch(target, source, options) {
1232
+ mergeInto(target, clonePlain(source), options.preserveMissingKeys);
1233
+ }
1234
+ function mergeInto(target, source, preserveMissingKeys) {
1235
+ if (!preserveMissingKeys)
1236
+ for (let key of Object.keys(target))
1237
+ hasOwn(source, key) || delete target[key];
1238
+ for (let key of Object.keys(source)) {
1239
+ let sourceValue = source[key], targetValue = target[key];
1240
+ isPlainObject(sourceValue) && isPlainObject(targetValue) ? mergeInto(targetValue, sourceValue, preserveMissingKeys) : targetValue !== sourceValue && (target[key] = sourceValue);
1241
+ }
1242
+ }
1243
+ function createReconciler(options) {
1244
+ let { serviceId, setState } = options, logWindow = {
1245
+ maxAgeMs: options.window?.maxAgeMs ?? DEFAULT_LOG_MAX_AGE_MS,
1246
+ maxEntries: options.window?.maxEntries ?? DEFAULT_LOG_MAX_ENTRIES
1247
+ }, clock = 0, snapshotSeq = 0, vector = /* @__PURE__ */ new Map(), log = [], logKeys = /* @__PURE__ */ new Set(), dropped = /* @__PURE__ */ new Set(), floor, vectorRecord = () => Object.fromEntries(vector), vectorOf = (runtimeId) => vector.get(runtimeId) ?? 0, hasStamp = (stamp) => logKeys.has(entryStampKey(stamp)), silentMissingRemove = () => {
1248
+ }, patchPaths = (patch) => patch.map((operation) => operation.path).join(","), undoEntry = (current, entry) => {
1249
+ let result = applyJsonPatch(current, entry.inverse, silentMissingRemove);
1250
+ result.ok || logger.warn(
1251
+ `Open-service sync: undo failed. service=${serviceId} stamp=${entryStampKey(entry.stamp)} path=${result.path} command=${entry.command}`
1252
+ );
1253
+ }, redoEntry = (current, entry) => {
1254
+ let result = applyJsonPatch(current, entry.patch, silentMissingRemove);
1255
+ entry.inverse = result.ok ? result.inverse : [], result.ok || logger.warn(
1256
+ `Open-service sync: replay failed. service=${serviceId} stamp=${entryStampKey(entry.stamp)} path=${result.path} command=${entry.command}`
1257
+ );
1258
+ }, undoToIndex = (current, index) => {
1259
+ let undone = [];
1260
+ for (let cursor = log.length - 1; cursor >= index; cursor -= 1) {
1261
+ let entry = log[cursor];
1262
+ undoEntry(current, entry), undone.push(entry);
1263
+ }
1264
+ return undone;
1265
+ }, redoUndone = (current, undone) => {
1266
+ for (let cursor = undone.length - 1; cursor >= 0; cursor -= 1)
1267
+ redoEntry(current, undone[cursor]);
1268
+ }, insertIndexFor = (stamp) => {
1269
+ let index = 0;
1270
+ for (; index < log.length && compareStamps(log[index].stamp, stamp) < 0; )
1271
+ index += 1;
1272
+ return index;
1273
+ }, tryAdvanceVector = (stamp) => {
1274
+ if (stamp.counter !== vectorOf(stamp.runtimeId) + 1)
1275
+ return;
1276
+ let counters = /* @__PURE__ */ new Set();
1277
+ for (let entry of log)
1278
+ entry.stamp.runtimeId === stamp.runtimeId && counters.add(entry.stamp.counter);
1279
+ let next = stamp.counter;
1280
+ for (; counters.has(next + 1); )
1281
+ next += 1;
1282
+ vector.set(stamp.runtimeId, next);
1283
+ }, evict = (now) => {
1284
+ let minKeepIndex = Math.max(0, log.length - logWindow.maxEntries), kept = [];
1285
+ for (let index = 0; index < log.length; index += 1) {
1286
+ let entry = log[index], amongNewest = index >= minKeepIndex, young = now - entry.appliedAt < logWindow.maxAgeMs;
1287
+ amongNewest || young ? kept.push(entry) : (logKeys.delete(entryStampKey(entry.stamp)), (floor === void 0 || compareStamps(entry.stamp, floor) > 0) && (floor = entry.stamp));
1288
+ }
1289
+ kept.length !== log.length && (log.length = 0, log.push(...kept));
1290
+ }, remember = (entry) => {
1291
+ logKeys.add(entryStampKey(entry.stamp)), tryAdvanceVector(entry.stamp), evict(entry.appliedAt);
1292
+ }, appendOrInsert = (entry, index) => {
1293
+ index === log.length ? log.push(entry) : log.splice(index, 0, entry), remember(entry);
1294
+ }, advanceClock = (seq) => {
1295
+ seq > clock && (clock = seq);
1296
+ };
1297
+ return {
1298
+ get clock() {
1299
+ return clock;
1300
+ },
1301
+ get vector() {
1302
+ return vectorRecord();
1303
+ },
1304
+ get frontier() {
1305
+ return { vector: vectorRecord(), clock };
1306
+ },
1307
+ get log() {
1308
+ return log.map(({ stamp, command, patch }) => ({ stamp, command, patch }));
1309
+ },
1310
+ has(stamp) {
1311
+ return hasStamp(stamp);
1312
+ },
1313
+ advanceLocal(runtimeId, authored) {
1314
+ let stamp = {
1315
+ seq: clock + 1,
1316
+ runtimeId,
1317
+ counter: vectorOf(runtimeId) + 1
1318
+ };
1319
+ advanceClock(stamp.seq);
1320
+ let now = Date.now(), entry = {
1321
+ stamp,
1322
+ command: authored.command,
1323
+ patch: [...authored.patch],
1324
+ inverse: [...authored.inverse],
1325
+ appliedAt: now
1326
+ };
1327
+ return appendOrInsert(entry, log.length), stamp;
1328
+ },
1329
+ tryInstall(frontier, state) {
1330
+ advanceClock(frontier.clock);
1331
+ let localVector = vectorRecord();
1332
+ if (!vectorDominates(frontier.vector, localVector))
1333
+ return vectorsConcurrent(frontier.vector, localVector) ? "concurrent" : "not-ahead";
1334
+ snapshotSeq = frontier.clock;
1335
+ let remaining = [];
1336
+ for (let entry of log)
1337
+ if (!(entry.stamp.counter <= vectorCounter(frontier.vector, entry.stamp.runtimeId))) {
1338
+ if (entry.stamp.seq <= frontier.clock) {
1339
+ logger.warn(
1340
+ `Open-service sync: uncovered entry at or below the reply clock dropped on install. service=${serviceId} stamp=${entryStampKey(entry.stamp)} clock=${frontier.clock} paths=${patchPaths(entry.patch)} command=${entry.command}`
1341
+ );
1342
+ continue;
1343
+ }
1344
+ remaining.push(entry);
1345
+ }
1346
+ return setState((current) => {
1347
+ applyStatePatch(current, state, { preserveMissingKeys: !1 }), logKeys.clear(), dropped.clear(), log.length = 0, floor = void 0, vector.clear();
1348
+ for (let [runtimeId, counter] of Object.entries(frontier.vector))
1349
+ counter > 0 && vector.set(runtimeId, counter);
1350
+ for (let entry of remaining) {
1351
+ let replayed = { ...entry };
1352
+ redoEntry(current, replayed), log.push(replayed), remember(replayed);
1353
+ }
1354
+ }), "installed";
1355
+ },
1356
+ tryPlaceEntry(incoming) {
1357
+ let { stamp, command, patch } = incoming, key = entryStampKey(stamp);
1358
+ if (advanceClock(stamp.seq), hasStamp(stamp) || dropped.has(key) || stamp.counter <= vectorOf(stamp.runtimeId))
1359
+ return "duplicate";
1360
+ if (stamp.seq <= snapshotSeq || floor && compareStamps(stamp, floor) <= 0) {
1361
+ let floorLabel = floor ? `,${entryStampKey(floor)}` : "";
1362
+ return logger.warn(
1363
+ `Open-service sync: entry beyond the log window. service=${serviceId} stamps=${key}${floorLabel} paths=${patchPaths(patch)} command=${command}`
1364
+ ), dropped.add(key), "beyond-window";
1365
+ }
1366
+ let gap = stamp.counter > vectorOf(stamp.runtimeId) + 1, index = insertIndexFor(stamp), now = Date.now(), failedPath;
1367
+ return setState((current) => {
1368
+ let inverse = [], undone = index === log.length ? [] : undoToIndex(current, index), result = applyJsonPatch(current, patch, (path) => {
1369
+ logger.debug(
1370
+ `Open-service sync: remove of missing key. service=${serviceId} stamp=${key} path=${path} command=${command}`
1371
+ );
1372
+ });
1373
+ result.ok ? inverse = result.inverse : failedPath = result.path, redoUndone(current, undone), appendOrInsert({ stamp, command, patch: [...patch], inverse, appliedAt: now }, index);
1374
+ }), failedPath !== void 0 && logger.warn(
1375
+ `Open-service sync: entry did not apply, kept as a no-op. service=${serviceId} stamp=${key} path=${failedPath} command=${command}`
1376
+ ), gap && logger.warn(
1377
+ `Open-service sync: gap in writer counters. service=${serviceId} stamps=${key} paths=${patchPaths(patch)} command=${command}`
1378
+ ), gap ? "gap" : failedPath !== void 0 ? "unapplied" : "accepted";
1379
+ }
1380
+ };
1381
+ }
1382
+
1383
+ // src/shared/open-service/service-runtime.ts
1384
+ function normalizeStaticStoragePath(serviceId, name, rawPath) {
1385
+ let segments = rawPath.replaceAll("\\", "/").split("/").filter((segment) => segment.length > 0 && segment !== ".");
1386
+ if (segments.length === 0 || segments.some((segment) => segment === ".."))
1387
+ throw new OpenServiceInvalidStaticPathError({ serviceId, name, path: rawPath });
1388
+ return segments.join("/");
1389
+ }
1390
+ function resolveStaticPath(serviceId, name, queryDef, input) {
1391
+ let rawPath = queryDef.staticPath(input), relativePath = normalizeStaticStoragePath(serviceId, name, rawPath);
1392
+ return `${serviceId}/${relativePath}`;
1393
+ }
1394
+ function buildCommands(serviceId, commands, createCommandCtx) {
1395
+ return Object.fromEntries(
1396
+ Object.entries(commands).map(([name, def]) => [
1397
+ name,
1398
+ async (input) => {
1399
+ if (!def.handler)
1400
+ throw new OpenServiceUnimplementedOperationError({
1401
+ kind: "command",
1402
+ serviceId,
1403
+ name
1404
+ });
1405
+ let validatedInput = await validateSchema(def.input, input, {
1406
+ kind: "command",
1407
+ serviceId,
1408
+ name,
1409
+ phase: "input"
1410
+ }), output = await def.handler(validatedInput, createCommandCtx(name));
1411
+ return validateSchema(def.output, output, {
1412
+ kind: "command",
1413
+ serviceId,
1414
+ name,
1415
+ phase: "output"
1416
+ });
1417
+ }
1418
+ ])
1419
+ );
1420
+ }
1421
+ function buildQueryDefinitionsWithStaticLoader(serviceId, queries, staticLoader, applyLocal) {
1422
+ return new Map(
1423
+ Object.entries(queries).map(([name, queryDef]) => {
1424
+ if (!queryDef.staticPath)
1425
+ return [name, queryDef];
1426
+ let { staticPath } = queryDef;
1427
+ return [
1428
+ name,
1429
+ {
1430
+ ...queryDef,
1431
+ load: async (input) => {
1432
+ let logicalPath = resolveStaticPath(serviceId, name, { staticPath }, input), snapshot = await staticLoader(logicalPath, {
1433
+ serviceId,
1434
+ queryName: name,
1435
+ input
1436
+ });
1437
+ applyLocal((state) => {
1438
+ applyStatePatch(state, snapshot, {
1439
+ preserveMissingKeys: !0
1440
+ });
1441
+ });
1442
+ }
1443
+ }
1444
+ ];
1445
+ })
1446
+ );
1447
+ }
1448
+ function createServiceRuntime(def, runtimeOptions, initialState = def.initialState) {
1449
+ let rawState = clonePlain(initialState), state = u2(rawState), getStateSnapshot = () => structuredClone(rawState), { registryApi, staticLoader } = runtimeOptions, author = () => {
1450
+ }, applyLocal = (mutate) => {
1451
+ n(() => {
1452
+ mutate(state);
1453
+ });
1454
+ }, writeState = (command, mutate) => {
1455
+ recordPatch(
1456
+ state,
1457
+ mutate,
1458
+ (recorded) => author({ command, ...recorded })
1459
+ );
1460
+ }, defaultQueries = {}, reactiveLoadQueries = {}, createCommandSelf = (setState, commandsForSelf) => ({
1461
+ get state() {
1462
+ return state;
1463
+ },
1464
+ setState,
1465
+ queries: defaultQueries,
1466
+ get commands() {
1467
+ return commandsForSelf();
1468
+ }
1469
+ }), commands = buildCommands(def.id, def.commands, (commandName) => ({
1470
+ self: createCommandSelf(
1471
+ (mutate) => writeState(commandName, mutate),
1472
+ () => commands
1473
+ ),
1474
+ getService: registryApi.getService
1475
+ })), loadCommands = commands, remoteCommandNames = /* @__PURE__ */ new Set(), queryDefinitions = staticLoader ? buildQueryDefinitionsWithStaticLoader(
1476
+ def.id,
1477
+ def.queries,
1478
+ staticLoader,
1479
+ applyLocal
1480
+ ) : new Map(
1481
+ Object.entries(def.queries)
1482
+ ), buildGatedCommands = (isCurrent) => {
1483
+ let gated = buildCommands(
1484
+ def.id,
1485
+ def.commands,
1486
+ (commandName) => ({
1487
+ self: createCommandSelf(
1488
+ (mutate) => {
1489
+ isCurrent() && writeState(commandName, mutate);
1490
+ },
1491
+ () => gated
1492
+ ),
1493
+ getService: registryApi.getService
1494
+ })
1495
+ );
1496
+ return remoteCommandNames.size === 0 ? gated : Object.fromEntries(
1497
+ Object.keys(def.commands).map((name) => [
1498
+ name,
1499
+ remoteCommandNames.has(name) ? loadCommands[name] : gated[name]
1500
+ ])
1501
+ );
1502
+ }, loadScopeId = nextLoadScopeId(), refs = {
1503
+ serviceId: def.id,
1504
+ loadScopeId,
1505
+ state,
1506
+ registryApi,
1507
+ queryDefinitions,
1508
+ defaultQueries,
1509
+ reactiveLoadQueries,
1510
+ getLoadCommands: () => loadCommands,
1511
+ buildGatedCommands
1512
+ }, builtQueries = buildQueries(refs);
1513
+ for (let [name, query] of Object.entries(builtQueries))
1514
+ defaultQueries[name] = query;
1515
+ for (let [name, query] of Object.entries(buildReactiveLoadQueries(refs)))
1516
+ reactiveLoadQueries[name] = query;
1517
+ let queries = defaultQueries, queryCtx = { self: {
1518
+ get state() {
1519
+ return state;
1520
+ },
1521
+ queries: defaultQueries
1522
+ }, getService: registryApi.getService }, loadCtxForStatic = {
1523
+ self: {
1524
+ get state() {
1525
+ return state;
1526
+ },
1527
+ queries: defaultQueries,
1528
+ commands
1529
+ },
1530
+ getService: registryApi.getService
1531
+ };
1532
+ return {
1533
+ getStateSnapshot,
1534
+ applyLocal,
1535
+ attachEntryAuthor: (next) => {
1536
+ author = next;
1537
+ },
1538
+ queryCtx,
1539
+ loadCtxForStatic,
1540
+ commands,
1541
+ queries,
1542
+ runLoadOnce: async (queryName, validatedInput) => {
1543
+ let queryDef = queryDefinitions.get(queryName);
1544
+ if (!queryDef || !queryDef.load)
1545
+ return;
1546
+ let loadKey = makeLoadKey(def.id, queryName, validatedInput), ancestorChain = /* @__PURE__ */ new Set([loadKey]), inFlightKey = makeInFlightKey(loadScopeId, loadKey), promise = Promise.resolve().then(() => runLoadBody(refs, queryName, queryDef, validatedInput, ancestorChain)).finally(() => {
1547
+ inFlightLoads.get(inFlightKey) === promise && inFlightLoads.delete(inFlightKey);
1548
+ });
1549
+ inFlightLoads.set(inFlightKey, promise), await promise;
1550
+ },
1551
+ attachChannelCommands: (channelCommands, implementedCommandNames) => {
1552
+ loadCommands = channelCommands, remoteCommandNames.clear();
1553
+ for (let name of Object.keys(def.commands))
1554
+ implementedCommandNames.has(name) || remoteCommandNames.add(name);
1555
+ }
1556
+ };
1557
+ }
1558
+
1559
+ // src/shared/open-service/service-transport.ts
1560
+ import * as v4 from "valibot";
1561
+ import { logger as logger2 } from "@aussieljk/forkbook/internal/client-logger";
1562
+ var REMOTE_COMMAND_ACK_TIMEOUT_MS = 300, SYNC_REQUEST_SILENCE_MS = 1e3;
1563
+ function createEntryAuthor(context) {
1564
+ let { serviceId, ownRuntimeId, reconciler, channel: channel2 } = context;
1565
+ return ({ command, ops, inverse }) => {
1566
+ let stamp = reconciler.advanceLocal(ownRuntimeId, { command, patch: ops, inverse });
1567
+ channel2.emit(SERVICE_ENTRY, {
1568
+ serviceId,
1569
+ stamp,
1570
+ command,
1571
+ patch: ops
1572
+ });
1573
+ };
1574
+ }
1575
+ function connectRuntimeToChannel(context) {
1576
+ let { serviceId, ownRuntimeId, reconciler, getSnapshot, channel: channel2, relay } = context, requestOutstanding = !1, withinReplyWindow = !1, repairQueued = !1, silenceTimer, forwardedReplyKey, clearSilenceTimer = () => {
1577
+ silenceTimer !== void 0 && (clearTimeout(silenceTimer), silenceTimer = void 0);
1578
+ }, emitSyncRequest = () => {
1579
+ if (requestOutstanding) {
1580
+ repairQueued = !0;
1581
+ return;
1582
+ }
1583
+ requestOutstanding = !0, withinReplyWindow = !0, repairQueued = !1, channel2.emit(SERVICE_SYNC_REQUEST, {
1584
+ serviceId,
1585
+ runtimeId: ownRuntimeId,
1586
+ frontier: reconciler.frontier
1587
+ }), clearSilenceTimer(), silenceTimer = setTimeout(() => {
1588
+ silenceTimer = void 0, withinReplyWindow = !1, settleOutstandingRequest();
1589
+ }, SYNC_REQUEST_SILENCE_MS);
1590
+ }, settleOutstandingRequest = () => {
1591
+ let queued = repairQueued;
1592
+ requestOutstanding = !1, queued && emitSyncRequest();
1593
+ }, onSyncRequest = (payload) => {
1594
+ let request = v4.safeParse(syncRequestSchema, payload);
1595
+ !request.success || request.output.serviceId !== serviceId || request.output.runtimeId === ownRuntimeId || vectorDominates(reconciler.vector, request.output.frontier.vector) && channel2.emit(SERVICE_SYNC_REPLY, {
1596
+ serviceId,
1597
+ runtimeId: ownRuntimeId,
1598
+ frontier: reconciler.frontier,
1599
+ state: getSnapshot()
1600
+ });
1601
+ }, onSyncReply = (payload) => {
1602
+ let snapshot = v4.safeParse(syncReplySchema, payload);
1603
+ if (!snapshot.success || snapshot.output.serviceId !== serviceId || snapshot.output.runtimeId === ownRuntimeId)
1604
+ return;
1605
+ let replyKey = `${snapshot.output.runtimeId}:${formatFrontier(snapshot.output.frontier)}`;
1606
+ if (replyKey === forwardedReplyKey)
1607
+ return;
1608
+ let outcome;
1609
+ try {
1610
+ outcome = reconciler.tryInstall(snapshot.output.frontier, snapshot.output.state);
1611
+ } finally {
1612
+ let settled = outcome ?? "installed";
1613
+ settled === "concurrent" && withinReplyWindow && (logger2.warn(
1614
+ `Open-service sync: concurrent snapshot reply dropped. service=${serviceId} local=${formatFrontier(reconciler.frontier)} reply=${formatFrontier(snapshot.output.frontier)}`
1615
+ ), repairQueued = !0), settleOutstandingRequest(), settled === "installed" && relay && (forwardedReplyKey = replyKey, channel2.emit(SERVICE_SYNC_REPLY, payload));
1616
+ }
1617
+ }, onEntry = (payload) => {
1618
+ let parsed = v4.safeParse(entrySchema, payload);
1619
+ if (!parsed.success || parsed.output.serviceId !== serviceId)
1620
+ return;
1621
+ let outcome;
1622
+ try {
1623
+ outcome = reconciler.tryPlaceEntry(parsed.output);
1624
+ } finally {
1625
+ let placed = outcome ?? (reconciler.has(parsed.output.stamp) ? "unapplied" : void 0), logged = placed === "accepted" || placed === "gap" || placed === "unapplied", needsRepair = placed === "gap" || placed === "beyond-window" || placed === "unapplied";
1626
+ (logged || placed === "beyond-window") && relay && channel2.emit(SERVICE_ENTRY, payload), needsRepair && emitSyncRequest();
1627
+ }
1628
+ };
1629
+ return channel2.on(SERVICE_SYNC_REQUEST, onSyncRequest), channel2.on(SERVICE_SYNC_REPLY, onSyncReply), channel2.on(SERVICE_ENTRY, onEntry), emitSyncRequest(), () => {
1630
+ channel2.off(SERVICE_SYNC_REQUEST, onSyncRequest), channel2.off(SERVICE_SYNC_REPLY, onSyncReply), channel2.off(SERVICE_ENTRY, onEntry), repairQueued = !1, requestOutstanding = !1, withinReplyWindow = !1, clearSilenceTimer();
1631
+ };
1632
+ }
1633
+ function connectCommandTransport(context) {
1634
+ let {
1635
+ serviceId,
1636
+ ownRuntimeId,
1637
+ channel: channel2,
1638
+ localCommands,
1639
+ implementedCommandNames,
1640
+ commandNames,
1641
+ delegated
1642
+ } = context, dispatchesLocally = (commandName) => !delegated && implementedCommandNames.has(commandName), pending = /* @__PURE__ */ new Map(), settle = (callId, apply) => {
1643
+ let entry = pending.get(callId);
1644
+ entry && (pending.delete(callId), clearTimeout(entry.noAckTimer), apply(entry));
1645
+ }, onInvoke = (payload) => {
1646
+ let parsed = v4.safeParse(commandInvokeSchema, payload);
1647
+ if (!parsed.success || parsed.output.serviceId !== serviceId)
1648
+ return;
1649
+ let invoke = parsed.output;
1650
+ if (!dispatchesLocally(invoke.commandName)) {
1651
+ !delegated && invoke.runtimeId !== ownRuntimeId && channel2.emit(SERVICE_COMMAND_UNHANDLED, {
1652
+ serviceId,
1653
+ callId: invoke.callId
1654
+ });
1655
+ return;
1656
+ }
1657
+ channel2.emit(SERVICE_COMMAND_ACK, {
1658
+ serviceId,
1659
+ callId: invoke.callId,
1660
+ runtimeId: ownRuntimeId
1661
+ }), setTimeout(() => {
1662
+ Promise.resolve().then(() => localCommands[invoke.commandName](invoke.input)).then(
1663
+ (result) => {
1664
+ channel2.emit(SERVICE_COMMAND_RESULT, {
1665
+ serviceId,
1666
+ callId: invoke.callId,
1667
+ result,
1668
+ runtimeId: ownRuntimeId
1669
+ });
1670
+ },
1671
+ (error) => {
1672
+ channel2.emit(SERVICE_COMMAND_ERROR, {
1673
+ serviceId,
1674
+ callId: invoke.callId,
1675
+ error: serializeError(error),
1676
+ runtimeId: ownRuntimeId
1677
+ });
1678
+ }
1679
+ );
1680
+ }, 0);
1681
+ }, onResult = (payload) => {
1682
+ let result = v4.safeParse(commandResultSchema, payload);
1683
+ !result.success || result.output.serviceId !== serviceId || settle(result.output.callId, (entry) => entry.resolve(result.output.result));
1684
+ }, onError = (payload) => {
1685
+ let failure = v4.safeParse(commandErrorSchema, payload);
1686
+ !failure.success || failure.output.serviceId !== serviceId || settle(failure.output.callId, (entry) => entry.reject(deserializeError(failure.output.error)));
1687
+ }, onAck = (payload) => {
1688
+ let ack = v4.safeParse(commandAckSchema, payload);
1689
+ if (!ack.success || ack.output.serviceId !== serviceId)
1690
+ return;
1691
+ let entry = pending.get(ack.output.callId);
1692
+ entry && clearTimeout(entry.noAckTimer);
1693
+ }, onUnhandled = (payload) => {
1694
+ let report = v4.safeParse(commandUnhandledSchema, payload);
1695
+ !report.success || report.output.serviceId !== serviceId || !delegated || settle(
1696
+ report.output.callId,
1697
+ (entry) => entry.reject(
1698
+ new OpenServiceRemoteCommandConfigDriftError({
1699
+ serviceId,
1700
+ commandName: entry.commandName
1701
+ })
1702
+ )
1703
+ );
1704
+ };
1705
+ channel2.on(SERVICE_COMMAND_INVOKE, onInvoke), channel2.on(SERVICE_COMMAND_RESULT, onResult), channel2.on(SERVICE_COMMAND_ERROR, onError), channel2.on(SERVICE_COMMAND_ACK, onAck), channel2.on(SERVICE_COMMAND_UNHANDLED, onUnhandled);
1706
+ let requestRemote = (commandName, input) => {
1707
+ let callId = generateCallId();
1708
+ return new Promise((resolve, reject) => {
1709
+ let noAckTimer = setTimeout(() => {
1710
+ settle(
1711
+ callId,
1712
+ (entry) => entry.reject(
1713
+ new OpenServiceRemoteCommandUnhandledError({
1714
+ serviceId,
1715
+ commandName: entry.commandName,
1716
+ delegated
1717
+ })
1718
+ )
1719
+ );
1720
+ }, REMOTE_COMMAND_ACK_TIMEOUT_MS);
1721
+ pending.set(callId, { commandName, resolve, reject, noAckTimer }), channel2.emit(SERVICE_COMMAND_INVOKE, {
1722
+ serviceId,
1723
+ commandName,
1724
+ input,
1725
+ callId,
1726
+ runtimeId: ownRuntimeId
1727
+ });
1728
+ });
1729
+ }, commands = {};
1730
+ for (let name of commandNames)
1731
+ commands[name] = dispatchesLocally(name) ? localCommands[name] : (input) => requestRemote(name, input);
1732
+ return {
1733
+ commands,
1734
+ disconnect: () => {
1735
+ channel2.off(SERVICE_COMMAND_INVOKE, onInvoke), channel2.off(SERVICE_COMMAND_RESULT, onResult), channel2.off(SERVICE_COMMAND_ERROR, onError), channel2.off(SERVICE_COMMAND_ACK, onAck), channel2.off(SERVICE_COMMAND_UNHANDLED, onUnhandled);
1736
+ for (let [, entry] of pending)
1737
+ clearTimeout(entry.noAckTimer), entry.reject(new OpenServiceRemoteCommandDisconnectedError({ serviceId }));
1738
+ pending.clear();
1739
+ }
1740
+ };
1741
+ }
1742
+ function connectUnknownServiceReporter(context) {
1743
+ let { channel: channel2, isServiceRegistered, isDelegated } = context, onInvoke = (payload) => {
1744
+ let parsed = v4.safeParse(commandInvokeSchema, payload);
1745
+ !parsed.success || isDelegated() || isServiceRegistered(parsed.output.serviceId) || channel2.emit(SERVICE_COMMAND_UNHANDLED, {
1746
+ serviceId: parsed.output.serviceId,
1747
+ callId: parsed.output.callId
1748
+ });
1749
+ };
1750
+ return channel2.on(SERVICE_COMMAND_INVOKE, onInvoke), () => {
1751
+ channel2.off(SERVICE_COMMAND_INVOKE, onInvoke);
1752
+ };
1753
+ }
1754
+ function connectServiceToChannel(context) {
1755
+ let {
1756
+ serviceId,
1757
+ ownRuntimeId,
1758
+ reconciler,
1759
+ getSnapshot,
1760
+ channel: channel2,
1761
+ relay,
1762
+ commands,
1763
+ implementedCommandNames,
1764
+ commandNames,
1765
+ delegated,
1766
+ runtime
1767
+ } = context;
1768
+ runtime.attachEntryAuthor(createEntryAuthor({ serviceId, ownRuntimeId, reconciler, channel: channel2 }));
1769
+ let commandTransport = connectCommandTransport({
1770
+ serviceId,
1771
+ ownRuntimeId,
1772
+ channel: channel2,
1773
+ localCommands: commands,
1774
+ implementedCommandNames,
1775
+ commandNames,
1776
+ delegated
1777
+ }), disconnectSync = connectRuntimeToChannel({
1778
+ serviceId,
1779
+ ownRuntimeId,
1780
+ reconciler,
1781
+ getSnapshot,
1782
+ channel: channel2,
1783
+ relay
1784
+ });
1785
+ return runtime.attachChannelCommands(
1786
+ commandTransport.commands,
1787
+ delegated ? /* @__PURE__ */ new Set() : implementedCommandNames
1788
+ ), {
1789
+ commands: commandTransport.commands,
1790
+ disconnect: () => {
1791
+ disconnectSync(), commandTransport.disconnect();
1792
+ }
1793
+ };
1794
+ }
1795
+
1796
+ // src/shared/open-service/service-registry.ts
1797
+ var REGISTRY_SYMBOL = /* @__PURE__ */ Symbol.for("storybook.open-service.registry");
1798
+ function getInventory() {
1799
+ let registryGlobal = globalThis;
1800
+ return registryGlobal[REGISTRY_SYMBOL] ??= {
1801
+ entries: /* @__PURE__ */ new Map(),
1802
+ delegatedMode: !1,
1803
+ everRegisteredIds: /* @__PURE__ */ new Set()
1804
+ }, registryGlobal[REGISTRY_SYMBOL];
1805
+ }
1806
+ function getRegistry() {
1807
+ return getInventory().entries;
1808
+ }
1809
+ function setDelegatedMode(enabled) {
1810
+ getInventory().delegatedMode = enabled;
1811
+ }
1812
+ function isDelegatedMode() {
1813
+ return getInventory().delegatedMode;
1814
+ }
1815
+ function ensureUnknownServiceReporter(channel2) {
1816
+ let inventory = getInventory();
1817
+ inventory.unknownServiceReporter?.channel !== channel2 && (inventory.unknownServiceReporter?.disconnect(), inventory.unknownServiceReporter = {
1818
+ channel: channel2,
1819
+ disconnect: connectUnknownServiceReporter({
1820
+ channel: channel2,
1821
+ isServiceRegistered: (serviceId) => inventory.everRegisteredIds.has(serviceId),
1822
+ isDelegated: () => inventory.delegatedMode
1823
+ })
1824
+ });
1825
+ }
1826
+ function assertUniqueOperationNames(definition) {
1827
+ let duplicateName = Object.keys(definition.queries).find(
1828
+ (name) => Object.hasOwn(definition.commands, name)
1829
+ );
1830
+ if (duplicateName)
1831
+ throw new OpenServiceOperationNameCollisionError({
1832
+ serviceId: definition.id,
1833
+ operationName: duplicateName
1834
+ });
1835
+ }
1836
+ function describeDefinition(definition) {
1837
+ return {
1838
+ id: definition.id,
1839
+ description: definition.description,
1840
+ queries: Object.fromEntries(
1841
+ Object.entries(definition.queries).filter(([, query]) => !query.internal).map(([name, query]) => [
1842
+ name,
1843
+ {
1844
+ name,
1845
+ description: query.description,
1846
+ input: query.input,
1847
+ output: query.output,
1848
+ ...query.staticPath ? { staticPath: !0 } : {}
1849
+ }
1850
+ ])
1851
+ ),
1852
+ commands: Object.fromEntries(
1853
+ Object.entries(definition.commands).filter(([, command]) => !command.internal).map(([name, command]) => [
1854
+ name,
1855
+ {
1856
+ name,
1857
+ description: command.description,
1858
+ input: command.input,
1859
+ output: command.output
1860
+ }
1861
+ ])
1862
+ )
1863
+ };
1864
+ }
1865
+ function summarizeDescriptor(descriptor) {
1866
+ return {
1867
+ id: descriptor.id,
1868
+ description: descriptor.description,
1869
+ queryNames: Object.keys(descriptor.queries),
1870
+ commandNames: Object.keys(descriptor.commands)
1871
+ };
1872
+ }
1873
+ function applyRegistration(definition, registration) {
1874
+ return registration ? {
1875
+ ...definition,
1876
+ queries: Object.fromEntries(
1877
+ Object.entries(definition.queries).map(([name, query]) => {
1878
+ let override = registration.queries?.[name];
1879
+ return [
1880
+ name,
1881
+ override && "staticInputs" in override ? { ...query, staticInputs: override.staticInputs } : query
1882
+ ];
1883
+ })
1884
+ ),
1885
+ commands: Object.fromEntries(
1886
+ Object.entries(definition.commands).map(([name, command]) => {
1887
+ let override = registration.commands?.[name];
1888
+ return [
1889
+ name,
1890
+ override && "handler" in override ? { ...command, handler: override.handler } : command
1891
+ ];
1892
+ })
1893
+ )
1894
+ } : definition;
1895
+ }
1896
+ var serviceRegistryApi = {
1897
+ listServices,
1898
+ describeService,
1899
+ getService
1900
+ };
1901
+ function registerService(definition, registration, { relay = !1, staticLoader, window: window2 } = {}) {
1902
+ assertUniqueOperationNames(definition);
1903
+ let registry = getRegistry(), existingEntry = registry.get(definition.id);
1904
+ if (existingEntry)
1905
+ return existingEntry.instance;
1906
+ let ownRuntimeId = generateRuntimeId(), resolvedDefinition = applyRegistration(definition, registration), runtime = createServiceRuntime(resolvedDefinition, {
1907
+ registryApi: serviceRegistryApi,
1908
+ staticLoader
1909
+ }), reconciler = createReconciler({
1910
+ serviceId: definition.id,
1911
+ setState: (mutate) => runtime.applyLocal((state) => mutate(state)),
1912
+ window: window2
1913
+ }), getSnapshot = () => runtime.getStateSnapshot(), descriptor = describeDefinition(resolvedDefinition), channel2 = getChannel();
1914
+ if (!channel2)
1915
+ throw new OpenServiceMissingChannelError({ serviceId: definition.id });
1916
+ getInventory().everRegisteredIds.add(definition.id), ensureUnknownServiceReporter(channel2);
1917
+ let implementedCommandNames = new Set(
1918
+ Object.entries(resolvedDefinition.commands).filter(([, command]) => typeof command.handler == "function").map(([name]) => name)
1919
+ ), { commands, disconnect } = connectServiceToChannel({
1920
+ serviceId: definition.id,
1921
+ ownRuntimeId,
1922
+ reconciler,
1923
+ getSnapshot,
1924
+ channel: channel2,
1925
+ relay: isDelegatedMode() ? !1 : relay,
1926
+ commands: runtime.commands,
1927
+ implementedCommandNames,
1928
+ commandNames: Object.keys(resolvedDefinition.commands),
1929
+ delegated: isDelegatedMode(),
1930
+ runtime
1931
+ }), instance = {
1932
+ queries: runtime.queries,
1933
+ commands,
1934
+ ...serviceRegistryApi
1935
+ };
1936
+ return registry.set(definition.id, {
1937
+ definition: resolvedDefinition,
1938
+ instance,
1939
+ descriptor,
1940
+ summary: summarizeDescriptor(descriptor),
1941
+ disconnect
1942
+ }), instance;
1943
+ }
1944
+ function getRegisteredServices() {
1945
+ return Array.from(getRegistry().values(), ({ definition }) => definition);
1946
+ }
1947
+ async function listServices() {
1948
+ return Array.from(getRegistry().values()).filter(({ definition }) => !definition.internal).map(({ summary }) => summary);
1949
+ }
1950
+ async function describeService(serviceId) {
1951
+ let entry = getRegistry().get(serviceId);
1952
+ if (!entry)
1953
+ throw new OpenServiceMissingServiceError({ serviceId });
1954
+ return entry.descriptor;
1955
+ }
1956
+ function getService(serviceId, options) {
1957
+ let entry = getRegistry().get(serviceId);
1958
+ if (!entry)
1959
+ throw new OpenServiceMissingServiceError({ serviceId });
1960
+ if (entry.definition.internal && !options?.internal)
1961
+ throw new OpenServiceInternalServiceError({ serviceId });
1962
+ return entry.instance;
1963
+ }
1964
+ function clearRegistry() {
1965
+ let inventory = getInventory();
1966
+ for (let entry of inventory.entries.values())
1967
+ entry.disconnect();
1968
+ inventory.entries.clear(), inventory.delegatedMode = !1, inventory.everRegisteredIds.clear(), inventory.unknownServiceReporter?.disconnect(), inventory.unknownServiceReporter = void 0;
1969
+ }
1970
+
1971
+ export {
1972
+ Channel,
1973
+ getChannel,
1974
+ setChannel,
1975
+ validateSchema,
1976
+ resolveStaticPath,
1977
+ createServiceRuntime,
1978
+ setDelegatedMode,
1979
+ serviceRegistryApi,
1980
+ registerService,
1981
+ getRegisteredServices,
1982
+ listServices,
1983
+ describeService,
1984
+ getService,
1985
+ clearRegistry
1986
+ };