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