jazz-tools 0.14.28 → 0.15.1

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 (887) hide show
  1. package/.svelte-kit/__package__/Provider.svelte +61 -0
  2. package/.svelte-kit/__package__/Provider.svelte.d.ts +19 -0
  3. package/.svelte-kit/__package__/Provider.svelte.d.ts.map +1 -0
  4. package/.svelte-kit/__package__/auth/PasskeyAuth.svelte.d.ts +11 -0
  5. package/.svelte-kit/__package__/auth/PasskeyAuth.svelte.d.ts.map +1 -0
  6. package/.svelte-kit/__package__/auth/PasskeyAuth.svelte.js +20 -0
  7. package/.svelte-kit/__package__/auth/PasskeyAuthBasicUI.svelte +81 -0
  8. package/.svelte-kit/__package__/auth/PasskeyAuthBasicUI.svelte.d.ts +9 -0
  9. package/.svelte-kit/__package__/auth/PasskeyAuthBasicUI.svelte.d.ts.map +1 -0
  10. package/.svelte-kit/__package__/auth/PassphraseAuth.svelte.d.ts +12 -0
  11. package/.svelte-kit/__package__/auth/PassphraseAuth.svelte.d.ts.map +1 -0
  12. package/.svelte-kit/__package__/auth/PassphraseAuth.svelte.js +30 -0
  13. package/.svelte-kit/__package__/auth/index.d.ts +4 -0
  14. package/.svelte-kit/__package__/auth/index.d.ts.map +1 -0
  15. package/.svelte-kit/__package__/auth/index.js +3 -0
  16. package/.svelte-kit/__package__/auth/useIsAuthenticated.svelte.d.ts +6 -0
  17. package/.svelte-kit/__package__/auth/useIsAuthenticated.svelte.d.ts.map +1 -0
  18. package/.svelte-kit/__package__/auth/useIsAuthenticated.svelte.js +22 -0
  19. package/.svelte-kit/__package__/index.d.ts +6 -0
  20. package/.svelte-kit/__package__/index.d.ts.map +1 -0
  21. package/.svelte-kit/__package__/index.js +5 -0
  22. package/.svelte-kit/__package__/jazz.class.svelte.d.ts +21 -0
  23. package/.svelte-kit/__package__/jazz.class.svelte.d.ts.map +1 -0
  24. package/.svelte-kit/__package__/jazz.class.svelte.js +117 -0
  25. package/.svelte-kit/__package__/jazz.svelte.d.ts +39 -0
  26. package/.svelte-kit/__package__/jazz.svelte.d.ts.map +1 -0
  27. package/.svelte-kit/__package__/jazz.svelte.js +70 -0
  28. package/.svelte-kit/__package__/testing.d.ts +10 -0
  29. package/.svelte-kit/__package__/testing.d.ts.map +1 -0
  30. package/.svelte-kit/__package__/testing.js +23 -0
  31. package/.turbo/turbo-build.log +180 -11
  32. package/CHANGELOG.md +26 -0
  33. package/README.md +2 -2
  34. package/dist/browser/BrowserContextManager.d.ts +31 -0
  35. package/dist/browser/BrowserContextManager.d.ts.map +1 -0
  36. package/dist/browser/auth/LocalStorageKVStore.d.ts +9 -0
  37. package/dist/browser/auth/LocalStorageKVStore.d.ts.map +1 -0
  38. package/dist/browser/auth/PasskeyAuth.d.ts +27 -0
  39. package/dist/browser/auth/PasskeyAuth.d.ts.map +1 -0
  40. package/dist/browser/createBrowserContext.d.ts +47 -0
  41. package/dist/browser/createBrowserContext.d.ts.map +1 -0
  42. package/dist/browser/index.d.ts +23 -0
  43. package/dist/browser/index.d.ts.map +1 -0
  44. package/dist/browser/index.js +469 -0
  45. package/dist/browser/index.js.map +1 -0
  46. package/dist/browser/storageOptions.d.ts +8 -0
  47. package/dist/browser/storageOptions.d.ts.map +1 -0
  48. package/dist/browser/tests/LocalStorageKVStore.test.d.ts +2 -0
  49. package/dist/browser/tests/LocalStorageKVStore.test.d.ts.map +1 -0
  50. package/dist/browser/tests/PasskeyAuth.test.d.ts +2 -0
  51. package/dist/browser/tests/PasskeyAuth.test.d.ts.map +1 -0
  52. package/dist/browser/tests/createInviteLink.test.d.ts +2 -0
  53. package/dist/browser/tests/createInviteLink.test.d.ts.map +1 -0
  54. package/dist/browser/tests/storageOptions.test.d.ts +2 -0
  55. package/dist/browser/tests/storageOptions.test.d.ts.map +1 -0
  56. package/dist/browser/tests/utils.d.ts +11 -0
  57. package/dist/browser/tests/utils.d.ts.map +1 -0
  58. package/dist/browser/utils/export-account-inspector.d.ts +6 -0
  59. package/dist/browser/utils/export-account-inspector.d.ts.map +1 -0
  60. package/dist/browser-media-images/index.d.ts +7 -0
  61. package/dist/browser-media-images/index.d.ts.map +1 -0
  62. package/dist/browser-media-images/index.js +70 -0
  63. package/dist/browser-media-images/index.js.map +1 -0
  64. package/dist/chunk-VBDJM6Z5.js +4938 -0
  65. package/dist/chunk-VBDJM6Z5.js.map +1 -0
  66. package/dist/expo/auth/clerk/index.d.ts +7 -0
  67. package/dist/expo/auth/clerk/index.d.ts.map +1 -0
  68. package/dist/expo/crypto.d.ts +2 -0
  69. package/dist/expo/crypto.d.ts.map +1 -0
  70. package/dist/expo/crypto.js +3 -0
  71. package/dist/expo/crypto.js.map +1 -0
  72. package/dist/expo/index.d.ts +6 -0
  73. package/dist/expo/index.d.ts.map +1 -0
  74. package/dist/expo/index.js +168 -0
  75. package/dist/expo/index.js.map +1 -0
  76. package/dist/expo/provider.d.ts +4 -0
  77. package/dist/expo/provider.d.ts.map +1 -0
  78. package/dist/expo/storage/expo-secure-store-adapter.d.ts +8 -0
  79. package/dist/expo/storage/expo-secure-store-adapter.d.ts.map +1 -0
  80. package/dist/expo/storage/expo-sqlite-adapter.d.ts +18 -0
  81. package/dist/expo/storage/expo-sqlite-adapter.d.ts.map +1 -0
  82. package/dist/expo/testing.d.ts +2 -0
  83. package/dist/expo/testing.d.ts.map +1 -0
  84. package/dist/expo/testing.js +3 -0
  85. package/dist/expo/testing.js.map +1 -0
  86. package/dist/index.d.ts +1 -2
  87. package/dist/index.d.ts.map +1 -1
  88. package/dist/index.js +172 -6
  89. package/dist/index.js.map +1 -1
  90. package/dist/inspector/custom-element-CWW72LEG.js +31971 -0
  91. package/dist/inspector/custom-element-CWW72LEG.js.map +1 -0
  92. package/dist/inspector/custom-element.d.ts +13 -0
  93. package/dist/inspector/custom-element.d.ts.map +1 -0
  94. package/dist/inspector/index.d.ts +12 -0
  95. package/dist/inspector/index.d.ts.map +1 -0
  96. package/dist/inspector/index.js +2053 -0
  97. package/dist/inspector/index.js.map +1 -0
  98. package/dist/inspector/register-custom-element.d.ts +2 -0
  99. package/dist/inspector/register-custom-element.d.ts.map +1 -0
  100. package/dist/inspector/register-custom-element.js +5 -0
  101. package/dist/inspector/register-custom-element.js.map +1 -0
  102. package/dist/inspector/ui/badge.d.ts +4 -0
  103. package/dist/inspector/ui/badge.d.ts.map +1 -0
  104. package/dist/inspector/ui/button.d.ts +9 -0
  105. package/dist/inspector/ui/button.d.ts.map +1 -0
  106. package/dist/inspector/ui/card.d.ts +10 -0
  107. package/dist/inspector/ui/card.d.ts.map +1 -0
  108. package/dist/inspector/ui/global-styles.d.ts +4 -0
  109. package/dist/inspector/ui/global-styles.d.ts.map +1 -0
  110. package/dist/inspector/ui/grid.d.ts +4 -0
  111. package/dist/inspector/ui/grid.d.ts.map +1 -0
  112. package/dist/inspector/ui/heading.d.ts +4 -0
  113. package/dist/inspector/ui/heading.d.ts.map +1 -0
  114. package/dist/inspector/ui/icon.d.ts +30 -0
  115. package/dist/inspector/ui/icon.d.ts.map +1 -0
  116. package/dist/inspector/ui/icons/chevron-down-icon.d.ts +2 -0
  117. package/dist/inspector/ui/icons/chevron-down-icon.d.ts.map +1 -0
  118. package/dist/inspector/ui/icons/delete-icon.d.ts +2 -0
  119. package/dist/inspector/ui/icons/delete-icon.d.ts.map +1 -0
  120. package/dist/inspector/ui/icons/link-icon.d.ts +2 -0
  121. package/dist/inspector/ui/icons/link-icon.d.ts.map +1 -0
  122. package/dist/inspector/ui/input.d.ts +11 -0
  123. package/dist/inspector/ui/input.d.ts.map +1 -0
  124. package/dist/inspector/ui/select.d.ts +5 -0
  125. package/dist/inspector/ui/select.d.ts.map +1 -0
  126. package/dist/inspector/ui/table.d.ts +8 -0
  127. package/dist/inspector/ui/table.d.ts.map +1 -0
  128. package/dist/inspector/ui/text.d.ts +10 -0
  129. package/dist/inspector/ui/text.d.ts.map +1 -0
  130. package/dist/inspector/viewer/account-or-group-text.d.ts +8 -0
  131. package/dist/inspector/viewer/account-or-group-text.d.ts.map +1 -0
  132. package/dist/inspector/viewer/account-view.d.ts +8 -0
  133. package/dist/inspector/viewer/account-view.d.ts.map +1 -0
  134. package/dist/inspector/viewer/breadcrumbs.d.ts +9 -0
  135. package/dist/inspector/viewer/breadcrumbs.d.ts.map +1 -0
  136. package/dist/inspector/viewer/co-stream-view.d.ts +18 -0
  137. package/dist/inspector/viewer/co-stream-view.d.ts.map +1 -0
  138. package/dist/inspector/viewer/grid-view.d.ts +9 -0
  139. package/dist/inspector/viewer/grid-view.d.ts.map +1 -0
  140. package/dist/inspector/viewer/group-view.d.ts +8 -0
  141. package/dist/inspector/viewer/group-view.d.ts.map +1 -0
  142. package/dist/inspector/viewer/inpsector-button.d.ts +6 -0
  143. package/dist/inspector/viewer/inpsector-button.d.ts.map +1 -0
  144. package/dist/inspector/viewer/new-app.d.ts +11 -0
  145. package/dist/inspector/viewer/new-app.d.ts.map +1 -0
  146. package/dist/inspector/viewer/page-stack.d.ts +15 -0
  147. package/dist/inspector/viewer/page-stack.d.ts.map +1 -0
  148. package/dist/inspector/viewer/page.d.ts +16 -0
  149. package/dist/inspector/viewer/page.d.ts.map +1 -0
  150. package/dist/inspector/viewer/raw-data-card.d.ts +5 -0
  151. package/dist/inspector/viewer/raw-data-card.d.ts.map +1 -0
  152. package/dist/inspector/viewer/role-display.d.ts +6 -0
  153. package/dist/inspector/viewer/role-display.d.ts.map +1 -0
  154. package/dist/inspector/viewer/table-viewer.d.ts +9 -0
  155. package/dist/inspector/viewer/table-viewer.d.ts.map +1 -0
  156. package/dist/inspector/viewer/type-icon.d.ts +11 -0
  157. package/dist/inspector/viewer/type-icon.d.ts.map +1 -0
  158. package/dist/inspector/viewer/types.d.ts +7 -0
  159. package/dist/inspector/viewer/types.d.ts.map +1 -0
  160. package/dist/inspector/viewer/use-open-inspector.d.ts +2 -0
  161. package/dist/inspector/viewer/use-open-inspector.d.ts.map +1 -0
  162. package/dist/inspector/viewer/use-page-path.d.ts +10 -0
  163. package/dist/inspector/viewer/use-page-path.d.ts.map +1 -0
  164. package/dist/inspector/viewer/use-resolve-covalue.d.ts +67 -0
  165. package/dist/inspector/viewer/use-resolve-covalue.d.ts.map +1 -0
  166. package/dist/inspector/viewer/value-renderer.d.ts +12 -0
  167. package/dist/inspector/viewer/value-renderer.d.ts.map +1 -0
  168. package/dist/prosemirror/index.d.ts +3 -0
  169. package/dist/prosemirror/index.d.ts.map +1 -0
  170. package/dist/prosemirror/index.js +2185 -0
  171. package/dist/prosemirror/index.js.map +1 -0
  172. package/dist/prosemirror/lib/converter.d.ts +33 -0
  173. package/dist/prosemirror/lib/converter.d.ts.map +1 -0
  174. package/dist/prosemirror/lib/plugin.d.ts +43 -0
  175. package/dist/prosemirror/lib/plugin.d.ts.map +1 -0
  176. package/dist/prosemirror/lib/sync.d.ts +35 -0
  177. package/dist/prosemirror/lib/sync.d.ts.map +1 -0
  178. package/dist/prosemirror/tests/plugin.test.d.ts +2 -0
  179. package/dist/prosemirror/tests/plugin.test.d.ts.map +1 -0
  180. package/dist/react/auth/Clerk.d.ts +7 -0
  181. package/dist/react/auth/Clerk.d.ts.map +1 -0
  182. package/dist/react/auth/DemoAuth.d.ts +5 -0
  183. package/dist/react/auth/DemoAuth.d.ts.map +1 -0
  184. package/dist/react/auth/PasskeyAuth.d.ts +24 -0
  185. package/dist/react/auth/PasskeyAuth.d.ts.map +1 -0
  186. package/dist/react/auth/PassphraseAuth.d.ts +6 -0
  187. package/dist/react/auth/PassphraseAuth.d.ts.map +1 -0
  188. package/dist/react/auth/auth.d.ts +6 -0
  189. package/dist/react/auth/auth.d.ts.map +1 -0
  190. package/dist/react/hooks.d.ts +9 -0
  191. package/dist/react/hooks.d.ts.map +1 -0
  192. package/dist/react/index.d.ts +8 -0
  193. package/dist/react/index.d.ts.map +1 -0
  194. package/dist/react/index.js +698 -0
  195. package/dist/react/index.js.map +1 -0
  196. package/dist/react/media.d.ts +24 -0
  197. package/dist/react/media.d.ts.map +1 -0
  198. package/dist/react/provider.d.ts +10 -0
  199. package/dist/react/provider.d.ts.map +1 -0
  200. package/dist/react/ssr.d.ts +4 -0
  201. package/dist/react/ssr.d.ts.map +1 -0
  202. package/dist/react/ssr.js +25 -0
  203. package/dist/react/ssr.js.map +1 -0
  204. package/dist/react/testing.d.ts +2 -0
  205. package/dist/react/testing.d.ts.map +1 -0
  206. package/dist/react/testing.js +3 -0
  207. package/dist/react/testing.js.map +1 -0
  208. package/dist/react/tests/testUtils.d.ts +14 -0
  209. package/dist/react/tests/testUtils.d.ts.map +1 -0
  210. package/dist/react/tests/useAcceptInvite.test.d.ts +2 -0
  211. package/dist/react/tests/useAcceptInvite.test.d.ts.map +1 -0
  212. package/dist/react-core/auth/DemoAuth.d.ts +17 -0
  213. package/dist/react-core/auth/DemoAuth.d.ts.map +1 -0
  214. package/dist/react-core/auth/PassphraseAuth.d.ts +21 -0
  215. package/dist/react-core/auth/PassphraseAuth.d.ts.map +1 -0
  216. package/dist/react-core/auth/index.d.ts +3 -0
  217. package/dist/react-core/auth/index.d.ts.map +1 -0
  218. package/dist/react-core/chunk-7DYMJ74I.js +12 -0
  219. package/dist/react-core/chunk-7DYMJ74I.js.map +1 -0
  220. package/dist/react-core/hooks.d.ts +17 -0
  221. package/dist/react-core/hooks.d.ts.map +1 -0
  222. package/dist/react-core/index.d.ts +4 -0
  223. package/dist/react-core/index.d.ts.map +1 -0
  224. package/dist/react-core/index.js +302 -0
  225. package/dist/react-core/index.js.map +1 -0
  226. package/dist/react-core/provider.d.ts +5 -0
  227. package/dist/react-core/provider.d.ts.map +1 -0
  228. package/dist/react-core/testing.d.ts +10 -0
  229. package/dist/react-core/testing.d.ts.map +1 -0
  230. package/dist/react-core/testing.js +43 -0
  231. package/dist/react-core/testing.js.map +1 -0
  232. package/dist/react-core/tests/fixtures.d.ts.map +1 -0
  233. package/dist/react-core/tests/testUtils.d.ts +15 -0
  234. package/dist/react-core/tests/testUtils.d.ts.map +1 -0
  235. package/dist/react-core/tests/useAccount.test.d.ts +2 -0
  236. package/dist/react-core/tests/useAccount.test.d.ts.map +1 -0
  237. package/dist/react-core/tests/useCoState.test.d.ts +2 -0
  238. package/dist/react-core/tests/useCoState.test.d.ts.map +1 -0
  239. package/dist/react-core/tests/useInboxSender.test.d.ts +2 -0
  240. package/dist/react-core/tests/useInboxSender.test.d.ts.map +1 -0
  241. package/dist/react-core/tests/useIsAuthenticated.test.d.ts +2 -0
  242. package/dist/react-core/tests/useIsAuthenticated.test.d.ts.map +1 -0
  243. package/dist/react-core/tests/usePassPhraseAuth.test.d.ts +2 -0
  244. package/dist/react-core/tests/usePassPhraseAuth.test.d.ts.map +1 -0
  245. package/dist/react-core/utils.d.ts +4 -0
  246. package/dist/react-core/utils.d.ts.map +1 -0
  247. package/dist/react-native/crypto.d.ts +2 -0
  248. package/dist/react-native/crypto.d.ts.map +1 -0
  249. package/dist/react-native/crypto.js +3 -0
  250. package/dist/react-native/crypto.js.map +1 -0
  251. package/dist/react-native/index.d.ts +5 -0
  252. package/dist/react-native/index.d.ts.map +1 -0
  253. package/dist/react-native/index.js +103 -0
  254. package/dist/react-native/index.js.map +1 -0
  255. package/dist/react-native/provider.d.ts +4 -0
  256. package/dist/react-native/provider.d.ts.map +1 -0
  257. package/dist/react-native/storage/mmkv-store-adapter.d.ts +8 -0
  258. package/dist/react-native/storage/mmkv-store-adapter.d.ts.map +1 -0
  259. package/dist/react-native/storage/op-sqlite-adapter.d.ts +13 -0
  260. package/dist/react-native/storage/op-sqlite-adapter.d.ts.map +1 -0
  261. package/dist/react-native/testing.d.ts +2 -0
  262. package/dist/react-native/testing.d.ts.map +1 -0
  263. package/dist/react-native/testing.js +3 -0
  264. package/dist/react-native/testing.js.map +1 -0
  265. package/dist/react-native-core/ReactNativeContextManager.d.ts +31 -0
  266. package/dist/react-native-core/ReactNativeContextManager.d.ts.map +1 -0
  267. package/dist/react-native-core/auth/DemoAuthUI.d.ts +8 -0
  268. package/dist/react-native-core/auth/DemoAuthUI.d.ts.map +1 -0
  269. package/dist/react-native-core/auth/auth.d.ts +3 -0
  270. package/dist/react-native-core/auth/auth.d.ts.map +1 -0
  271. package/dist/react-native-core/crypto/RNQuickCrypto.d.ts +15 -0
  272. package/dist/react-native-core/crypto/RNQuickCrypto.d.ts.map +1 -0
  273. package/dist/react-native-core/crypto/index.d.ts +2 -0
  274. package/dist/react-native-core/crypto/index.d.ts.map +1 -0
  275. package/dist/react-native-core/crypto.js +65 -0
  276. package/dist/react-native-core/crypto.js.map +1 -0
  277. package/dist/react-native-core/hooks.d.ts +8 -0
  278. package/dist/react-native-core/hooks.d.ts.map +1 -0
  279. package/dist/react-native-core/index.d.ts +9 -0
  280. package/dist/react-native-core/index.d.ts.map +1 -0
  281. package/dist/react-native-core/index.js +653 -0
  282. package/dist/react-native-core/index.js.map +1 -0
  283. package/dist/react-native-core/media.d.ts +24 -0
  284. package/dist/react-native-core/media.d.ts.map +1 -0
  285. package/dist/react-native-core/platform.d.ts +45 -0
  286. package/dist/react-native-core/platform.d.ts.map +1 -0
  287. package/dist/react-native-core/provider.d.ts +10 -0
  288. package/dist/react-native-core/provider.d.ts.map +1 -0
  289. package/dist/react-native-core/storage/kv-store-context.d.ts +17 -0
  290. package/dist/react-native-core/storage/kv-store-context.d.ts.map +1 -0
  291. package/dist/react-native-core/storage/sqlite-react-native.d.ts +9 -0
  292. package/dist/react-native-core/storage/sqlite-react-native.d.ts.map +1 -0
  293. package/dist/react-native-core/testing.js +3 -0
  294. package/dist/react-native-core/testing.js.map +1 -0
  295. package/dist/react-native-media-images/index.d.ts +7 -0
  296. package/dist/react-native-media-images/index.d.ts.map +1 -0
  297. package/dist/react-native-media-images/index.js +177 -0
  298. package/dist/react-native-media-images/index.js.map +1 -0
  299. package/dist/svelte/Provider.svelte +61 -0
  300. package/dist/svelte/Provider.svelte.d.ts +19 -0
  301. package/dist/svelte/Provider.svelte.d.ts.map +1 -0
  302. package/dist/svelte/auth/PasskeyAuth.svelte.d.ts +11 -0
  303. package/dist/svelte/auth/PasskeyAuth.svelte.d.ts.map +1 -0
  304. package/dist/svelte/auth/PasskeyAuth.svelte.js +20 -0
  305. package/dist/svelte/auth/PasskeyAuthBasicUI.svelte +81 -0
  306. package/dist/svelte/auth/PasskeyAuthBasicUI.svelte.d.ts +9 -0
  307. package/dist/svelte/auth/PasskeyAuthBasicUI.svelte.d.ts.map +1 -0
  308. package/dist/svelte/auth/PassphraseAuth.svelte.d.ts +12 -0
  309. package/dist/svelte/auth/PassphraseAuth.svelte.d.ts.map +1 -0
  310. package/dist/svelte/auth/PassphraseAuth.svelte.js +30 -0
  311. package/dist/svelte/auth/index.d.ts +4 -0
  312. package/dist/svelte/auth/index.d.ts.map +1 -0
  313. package/dist/svelte/auth/index.js +3 -0
  314. package/dist/svelte/auth/useIsAuthenticated.svelte.d.ts +6 -0
  315. package/dist/svelte/auth/useIsAuthenticated.svelte.d.ts.map +1 -0
  316. package/dist/svelte/auth/useIsAuthenticated.svelte.js +22 -0
  317. package/dist/svelte/index.d.ts +6 -0
  318. package/dist/svelte/index.d.ts.map +1 -0
  319. package/dist/svelte/index.js +5 -0
  320. package/dist/svelte/jazz.class.svelte.d.ts +21 -0
  321. package/dist/svelte/jazz.class.svelte.d.ts.map +1 -0
  322. package/dist/svelte/jazz.class.svelte.js +117 -0
  323. package/dist/svelte/jazz.svelte.d.ts +39 -0
  324. package/dist/svelte/jazz.svelte.d.ts.map +1 -0
  325. package/dist/svelte/jazz.svelte.js +70 -0
  326. package/dist/svelte/testing.d.ts +10 -0
  327. package/dist/svelte/testing.d.ts.map +1 -0
  328. package/dist/svelte/testing.js +23 -0
  329. package/dist/testing.d.ts +1 -42
  330. package/dist/testing.d.ts.map +1 -1
  331. package/dist/testing.js +2 -2
  332. package/dist/testing.js.map +1 -1
  333. package/dist/tiptap/index.d.ts +11 -0
  334. package/dist/tiptap/index.d.ts.map +1 -0
  335. package/dist/tiptap/index.js +22 -0
  336. package/dist/tiptap/index.js.map +1 -0
  337. package/dist/tools/auth/AuthSecretStorage.d.ts.map +1 -0
  338. package/dist/tools/auth/DemoAuth.d.ts.map +1 -0
  339. package/dist/tools/auth/InMemoryKVStore.d.ts.map +1 -0
  340. package/dist/tools/auth/KvStoreContext.d.ts.map +1 -0
  341. package/dist/tools/auth/PassphraseAuth.d.ts.map +1 -0
  342. package/dist/tools/auth/clerk/getClerkUsername.d.ts +3 -0
  343. package/dist/tools/auth/clerk/getClerkUsername.d.ts.map +1 -0
  344. package/dist/tools/auth/clerk/index.d.ts +25 -0
  345. package/dist/tools/auth/clerk/index.d.ts.map +1 -0
  346. package/dist/tools/auth/clerk/tests/JazzClerkAuth.test.d.ts +2 -0
  347. package/dist/tools/auth/clerk/tests/JazzClerkAuth.test.d.ts.map +1 -0
  348. package/dist/tools/auth/clerk/tests/getClerkUsername.test.d.ts +2 -0
  349. package/dist/tools/auth/clerk/tests/getClerkUsername.test.d.ts.map +1 -0
  350. package/dist/tools/auth/clerk/tests/types.test.d.ts +2 -0
  351. package/dist/tools/auth/clerk/tests/types.test.d.ts.map +1 -0
  352. package/dist/tools/auth/clerk/types.d.ts +32 -0
  353. package/dist/tools/auth/clerk/types.d.ts.map +1 -0
  354. package/dist/tools/coValues/CoValueBase.d.ts.map +1 -0
  355. package/dist/tools/coValues/account.d.ts.map +1 -0
  356. package/dist/tools/coValues/coFeed.d.ts +377 -0
  357. package/dist/tools/coValues/coFeed.d.ts.map +1 -0
  358. package/dist/tools/coValues/coList.d.ts.map +1 -0
  359. package/dist/tools/coValues/coMap.d.ts +625 -0
  360. package/dist/tools/coValues/coMap.d.ts.map +1 -0
  361. package/dist/tools/coValues/coPlainText.d.ts.map +1 -0
  362. package/dist/tools/coValues/coRichText.d.ts.map +1 -0
  363. package/dist/tools/coValues/deepLoading.d.ts.map +1 -0
  364. package/dist/tools/coValues/extensions/imageDef.d.ts.map +1 -0
  365. package/dist/tools/coValues/group.d.ts.map +1 -0
  366. package/dist/tools/coValues/inbox.d.ts.map +1 -0
  367. package/dist/tools/coValues/interfaces.d.ts +116 -0
  368. package/dist/tools/coValues/interfaces.d.ts.map +1 -0
  369. package/dist/tools/coValues/profile.d.ts.map +1 -0
  370. package/dist/tools/coValues/registeredSchemas.d.ts.map +1 -0
  371. package/dist/tools/coValues/schemaUnion.d.ts.map +1 -0
  372. package/dist/tools/exports.d.ts +24 -0
  373. package/dist/tools/exports.d.ts.map +1 -0
  374. package/dist/tools/implementation/ContextManager.d.ts.map +1 -0
  375. package/dist/tools/implementation/activeAccountContext.d.ts.map +1 -0
  376. package/dist/tools/implementation/anonymousJazzAgent.d.ts.map +1 -0
  377. package/dist/tools/implementation/createContext.d.ts.map +1 -0
  378. package/dist/tools/implementation/devtoolsFormatters.d.ts.map +1 -0
  379. package/dist/tools/implementation/errors.d.ts.map +1 -0
  380. package/dist/tools/implementation/inspect.d.ts.map +1 -0
  381. package/dist/tools/implementation/invites.d.ts.map +1 -0
  382. package/dist/tools/implementation/refs.d.ts.map +1 -0
  383. package/dist/tools/implementation/schema.d.ts.map +1 -0
  384. package/dist/tools/implementation/symbols.d.ts.map +1 -0
  385. package/dist/tools/implementation/zodSchema/coExport.d.ts.map +1 -0
  386. package/dist/tools/implementation/zodSchema/runtimeConverters/zodFieldToCoFieldDef.d.ts.map +1 -0
  387. package/dist/tools/implementation/zodSchema/runtimeConverters/zodSchemaToCoSchema.d.ts.map +1 -0
  388. package/dist/tools/implementation/zodSchema/schemaTypes/AccountSchema.d.ts.map +1 -0
  389. package/dist/tools/implementation/zodSchema/schemaTypes/CoFeedSchema.d.ts.map +1 -0
  390. package/dist/tools/implementation/zodSchema/schemaTypes/CoListSchema.d.ts.map +1 -0
  391. package/dist/tools/implementation/zodSchema/schemaTypes/CoMapSchema.d.ts +64 -0
  392. package/dist/tools/implementation/zodSchema/schemaTypes/CoMapSchema.d.ts.map +1 -0
  393. package/dist/tools/implementation/zodSchema/schemaTypes/CoRecordSchema.d.ts.map +1 -0
  394. package/dist/tools/implementation/zodSchema/schemaTypes/FileStreamSchema.d.ts.map +1 -0
  395. package/dist/tools/implementation/zodSchema/schemaTypes/PlainTextSchema.d.ts.map +1 -0
  396. package/dist/tools/implementation/zodSchema/schemaTypes/RichTextSchema.d.ts.map +1 -0
  397. package/dist/tools/implementation/zodSchema/typeConverters/InstanceOfSchema.d.ts.map +1 -0
  398. package/dist/tools/implementation/zodSchema/typeConverters/InstanceOfSchemaCoValuesNullable.d.ts.map +1 -0
  399. package/dist/tools/implementation/zodSchema/typeConverters/InstanceOrPrimitiveOfSchema.d.ts.map +1 -0
  400. package/dist/tools/implementation/zodSchema/typeConverters/InstanceOrPrimitiveOfSchemaCoValuesNullable.d.ts.map +1 -0
  401. package/dist/tools/implementation/zodSchema/unionUtils.d.ts.map +1 -0
  402. package/dist/tools/implementation/zodSchema/zodCo.d.ts.map +1 -0
  403. package/dist/tools/implementation/zodSchema/zodReExport.d.ts.map +1 -0
  404. package/dist/tools/implementation/zodSchema/zodSchema.d.ts.map +1 -0
  405. package/dist/tools/index.d.ts +3 -0
  406. package/dist/tools/index.d.ts.map +1 -0
  407. package/dist/tools/internal.d.ts.map +1 -0
  408. package/dist/tools/lib/cache.d.ts.map +1 -0
  409. package/dist/tools/lib/cache.test.d.ts.map +1 -0
  410. package/dist/tools/lib/migration.d.ts.map +1 -0
  411. package/dist/tools/subscribe/CoValueCoreSubscription.d.ts +15 -0
  412. package/dist/tools/subscribe/CoValueCoreSubscription.d.ts.map +1 -0
  413. package/dist/tools/subscribe/JazzError.d.ts.map +1 -0
  414. package/dist/tools/subscribe/SubscriptionScope.d.ts +47 -0
  415. package/dist/tools/subscribe/SubscriptionScope.d.ts.map +1 -0
  416. package/dist/tools/subscribe/index.d.ts.map +1 -0
  417. package/dist/tools/subscribe/types.d.ts.map +1 -0
  418. package/dist/tools/subscribe/utils.d.ts.map +1 -0
  419. package/dist/tools/testing.d.ts +43 -0
  420. package/dist/tools/testing.d.ts.map +1 -0
  421. package/dist/tools/tests/AuthSecretStorage.test.d.ts.map +1 -0
  422. package/dist/tools/tests/ContextManager.test.d.ts.map +1 -0
  423. package/dist/tools/tests/DemoAuth.test.d.ts.map +1 -0
  424. package/dist/tools/tests/PassphraseAuth.test.d.ts.map +1 -0
  425. package/dist/tools/tests/account.test.d.ts.map +1 -0
  426. package/dist/tools/tests/coFeed.test-d.d.ts.map +1 -0
  427. package/dist/tools/tests/coFeed.test.d.ts.map +1 -0
  428. package/dist/tools/tests/coList.test-d.d.ts.map +1 -0
  429. package/dist/tools/tests/coList.test.d.ts.map +1 -0
  430. package/dist/tools/tests/coMap.record.test-d.d.ts.map +1 -0
  431. package/dist/tools/tests/coMap.record.test.d.ts.map +1 -0
  432. package/dist/tools/tests/coMap.test-d.d.ts.map +1 -0
  433. package/dist/tools/tests/coMap.test.d.ts.map +1 -0
  434. package/dist/tools/tests/coPlainText.test.d.ts.map +1 -0
  435. package/dist/tools/tests/createContext.test.d.ts.map +1 -0
  436. package/dist/tools/tests/deepLoading.test.d.ts.map +1 -0
  437. package/dist/tools/tests/fixtures.d.ts +2 -0
  438. package/dist/tools/tests/fixtures.d.ts.map +1 -0
  439. package/dist/tools/tests/groupsAndAccounts.test.d.ts.map +1 -0
  440. package/dist/tools/tests/imageDef.test.d.ts.map +1 -0
  441. package/dist/tools/tests/inbox.test.d.ts.map +1 -0
  442. package/dist/tools/tests/interfaces.test.d.ts.map +1 -0
  443. package/dist/tools/tests/invites.test.d.ts.map +1 -0
  444. package/dist/tools/tests/load.test.d.ts.map +1 -0
  445. package/dist/tools/tests/patterns/notifications.test.d.ts.map +1 -0
  446. package/dist/tools/tests/patterns/requestToJoin.test.d.ts.map +1 -0
  447. package/dist/tools/tests/schema.test.d.ts.map +1 -0
  448. package/dist/tools/tests/schemaUnion.test.d.ts.map +1 -0
  449. package/dist/tools/tests/subscribe.test.d.ts.map +1 -0
  450. package/dist/tools/tests/testing.test.d.ts.map +1 -0
  451. package/dist/tools/tests/utils.d.ts.map +1 -0
  452. package/dist/tools/tests/zod.test.d.ts.map +1 -0
  453. package/dist/tools/types.d.ts.map +1 -0
  454. package/dist/worker/index.d.ts +25 -0
  455. package/dist/worker/index.d.ts.map +1 -0
  456. package/dist/worker/index.js +93 -0
  457. package/dist/worker/index.js.map +1 -0
  458. package/package.json +193 -11
  459. package/src/browser/BrowserContextManager.ts +85 -0
  460. package/src/browser/auth/LocalStorageKVStore.ts +21 -0
  461. package/src/browser/auth/PasskeyAuth.ts +175 -0
  462. package/src/browser/createBrowserContext.ts +326 -0
  463. package/src/browser/index.ts +72 -0
  464. package/src/browser/storageOptions.ts +17 -0
  465. package/src/browser/tests/LocalStorageKVStore.test.ts +67 -0
  466. package/src/browser/tests/PasskeyAuth.test.ts +242 -0
  467. package/src/browser/tests/createInviteLink.test.ts +18 -0
  468. package/src/browser/tests/storageOptions.test.ts +33 -0
  469. package/src/browser/tests/utils.ts +93 -0
  470. package/src/browser/utils/export-account-inspector.ts +58 -0
  471. package/src/browser-media-images/index.ts +130 -0
  472. package/src/expo/auth/clerk/README.md +44 -0
  473. package/src/expo/auth/clerk/index.tsx +80 -0
  474. package/src/expo/crypto.ts +1 -0
  475. package/src/expo/index.ts +6 -0
  476. package/src/expo/provider.tsx +29 -0
  477. package/src/expo/storage/expo-secure-store-adapter.ts +29 -0
  478. package/src/expo/storage/expo-sqlite-adapter.ts +94 -0
  479. package/src/expo/testing.ts +1 -0
  480. package/src/index.ts +1 -3
  481. package/src/inspector/custom-element.tsx +63 -0
  482. package/src/inspector/index.ts +23 -0
  483. package/src/inspector/register-custom-element.ts +3 -0
  484. package/src/inspector/ui/badge.tsx +20 -0
  485. package/src/inspector/ui/button.tsx +81 -0
  486. package/src/inspector/ui/card.tsx +23 -0
  487. package/src/inspector/ui/global-styles.tsx +74 -0
  488. package/src/inspector/ui/grid.tsx +48 -0
  489. package/src/inspector/ui/heading.tsx +15 -0
  490. package/src/inspector/ui/icon.tsx +71 -0
  491. package/src/inspector/ui/icons/chevron-down-icon.tsx +16 -0
  492. package/src/inspector/ui/icons/delete-icon.tsx +19 -0
  493. package/src/inspector/ui/icons/link-icon.tsx +18 -0
  494. package/src/inspector/ui/input.tsx +51 -0
  495. package/src/inspector/ui/select.tsx +73 -0
  496. package/src/inspector/ui/table.tsx +90 -0
  497. package/src/inspector/ui/text.tsx +62 -0
  498. package/src/inspector/viewer/account-or-group-text.tsx +52 -0
  499. package/src/inspector/viewer/account-view.tsx +34 -0
  500. package/src/inspector/viewer/breadcrumbs.tsx +52 -0
  501. package/src/inspector/viewer/co-stream-view.tsx +374 -0
  502. package/src/inspector/viewer/grid-view.tsx +90 -0
  503. package/src/inspector/viewer/group-view.tsx +67 -0
  504. package/src/inspector/viewer/inpsector-button.tsx +89 -0
  505. package/src/inspector/viewer/new-app.tsx +172 -0
  506. package/src/inspector/viewer/page-stack.tsx +56 -0
  507. package/src/inspector/viewer/page.tsx +199 -0
  508. package/src/inspector/viewer/raw-data-card.tsx +53 -0
  509. package/src/inspector/viewer/role-display.tsx +28 -0
  510. package/src/inspector/viewer/table-viewer.tsx +184 -0
  511. package/src/inspector/viewer/type-icon.tsx +63 -0
  512. package/src/inspector/viewer/types.ts +11 -0
  513. package/src/inspector/viewer/use-open-inspector.ts +18 -0
  514. package/src/inspector/viewer/use-page-path.ts +65 -0
  515. package/src/inspector/viewer/use-resolve-covalue.ts +214 -0
  516. package/src/inspector/viewer/value-renderer.tsx +266 -0
  517. package/src/prosemirror/index.ts +2 -0
  518. package/src/prosemirror/lib/converter.ts +50 -0
  519. package/src/prosemirror/lib/plugin.ts +120 -0
  520. package/src/prosemirror/lib/sync.ts +96 -0
  521. package/src/prosemirror/tests/plugin.test.ts +127 -0
  522. package/src/react/auth/Clerk.tsx +82 -0
  523. package/src/react/auth/DemoAuth.tsx +121 -0
  524. package/src/react/auth/PasskeyAuth.tsx +168 -0
  525. package/src/react/auth/PassphraseAuth.tsx +196 -0
  526. package/src/react/auth/auth.ts +9 -0
  527. package/src/react/hooks.tsx +53 -0
  528. package/src/react/index.ts +16 -0
  529. package/src/react/media.tsx +74 -0
  530. package/src/react/provider.tsx +114 -0
  531. package/src/react/scratch.tsx +50 -0
  532. package/src/react/ssr.ts +25 -0
  533. package/src/react/testing.tsx +1 -0
  534. package/src/react/tests/testUtils.tsx +54 -0
  535. package/src/react/tests/useAcceptInvite.test.ts +55 -0
  536. package/src/react-core/auth/DemoAuth.tsx +47 -0
  537. package/src/react-core/auth/PassphraseAuth.tsx +58 -0
  538. package/src/react-core/auth/index.ts +2 -0
  539. package/src/react-core/hooks.ts +310 -0
  540. package/src/react-core/index.ts +3 -0
  541. package/src/react-core/provider.tsx +11 -0
  542. package/src/react-core/testing.tsx +42 -0
  543. package/src/react-core/tests/testUtils.tsx +65 -0
  544. package/src/react-core/tests/useAccount.test.ts +238 -0
  545. package/src/react-core/tests/useCoState.test.ts +553 -0
  546. package/src/react-core/tests/useDemoAuth.test.tsx +84 -0
  547. package/src/react-core/tests/useInboxSender.test.ts +58 -0
  548. package/src/react-core/tests/useIsAuthenticated.test.ts +34 -0
  549. package/src/react-core/tests/usePassPhraseAuth.test.ts +180 -0
  550. package/src/react-core/utils.ts +28 -0
  551. package/src/react-native/crypto.ts +1 -0
  552. package/src/react-native/index.ts +5 -0
  553. package/src/react-native/provider.tsx +30 -0
  554. package/src/react-native/storage/mmkv-store-adapter.ts +24 -0
  555. package/src/react-native/storage/op-sqlite-adapter.ts +79 -0
  556. package/src/react-native/testing.ts +1 -0
  557. package/src/react-native-core/ReactNativeContextManager.ts +84 -0
  558. package/src/react-native-core/auth/DemoAuthUI.tsx +202 -0
  559. package/src/react-native-core/auth/auth.ts +14 -0
  560. package/src/react-native-core/crypto/RNQuickCrypto.ts +92 -0
  561. package/src/react-native-core/crypto/index.ts +1 -0
  562. package/src/react-native-core/hooks.tsx +64 -0
  563. package/src/react-native-core/index.ts +9 -0
  564. package/src/react-native-core/media.tsx +79 -0
  565. package/src/react-native-core/platform.ts +250 -0
  566. package/src/react-native-core/provider.tsx +115 -0
  567. package/src/react-native-core/storage/sqlite-react-native.ts +19 -0
  568. package/src/react-native-core/testing.tsx +1 -0
  569. package/src/react-native-media-images/index.ts +238 -0
  570. package/src/svelte/Provider.svelte +61 -0
  571. package/src/svelte/auth/PasskeyAuth.svelte.ts +42 -0
  572. package/src/svelte/auth/PasskeyAuthBasicUI.svelte +81 -0
  573. package/src/svelte/auth/PassphraseAuth.svelte.ts +49 -0
  574. package/src/svelte/auth/index.ts +3 -0
  575. package/src/svelte/auth/useIsAuthenticated.svelte.ts +28 -0
  576. package/src/svelte/index.ts +5 -0
  577. package/src/svelte/jazz.class.svelte.ts +172 -0
  578. package/src/svelte/jazz.svelte.ts +109 -0
  579. package/src/svelte/testing.ts +42 -0
  580. package/src/testing.ts +1 -312
  581. package/src/tiptap/index.ts +28 -0
  582. package/src/tools/auth/KvStoreContext.ts +39 -0
  583. package/src/tools/auth/clerk/getClerkUsername.ts +36 -0
  584. package/src/tools/auth/clerk/index.ts +174 -0
  585. package/src/tools/auth/clerk/tests/JazzClerkAuth.test.ts +284 -0
  586. package/src/tools/auth/clerk/tests/getClerkUsername.test.ts +81 -0
  587. package/src/tools/auth/clerk/tests/types.test.ts +49 -0
  588. package/src/tools/auth/clerk/types.ts +56 -0
  589. package/src/tools/coValues/coFeed.ts +981 -0
  590. package/src/tools/coValues/coMap.ts +929 -0
  591. package/src/tools/coValues/interfaces.ts +464 -0
  592. package/src/tools/exports.ts +117 -0
  593. package/src/tools/implementation/zodSchema/schemaTypes/CoMapSchema.ts +188 -0
  594. package/src/tools/implementation/zodSchema/zodCo.ts +370 -0
  595. package/src/tools/index.ts +8 -0
  596. package/src/tools/subscribe/CoValueCoreSubscription.ts +74 -0
  597. package/src/tools/subscribe/SubscriptionScope.ts +626 -0
  598. package/src/tools/testing.ts +301 -0
  599. package/src/tools/tests/coFeed.test.ts +840 -0
  600. package/src/tools/tests/coMap.test.ts +2113 -0
  601. package/src/tools/tests/fixtures.ts +2050 -0
  602. package/src/tools/tests/load.test.ts +117 -0
  603. package/src/worker/index.ts +127 -0
  604. package/tsconfig.json +10 -3
  605. package/tsconfig.svelte.json +6 -0
  606. package/tsup.config.ts +143 -9
  607. package/dist/auth/AuthSecretStorage.d.ts.map +0 -1
  608. package/dist/auth/DemoAuth.d.ts.map +0 -1
  609. package/dist/auth/InMemoryKVStore.d.ts.map +0 -1
  610. package/dist/auth/KvStoreContext.d.ts.map +0 -1
  611. package/dist/auth/PassphraseAuth.d.ts.map +0 -1
  612. package/dist/chunk-AUQIX4E7.js +0 -4827
  613. package/dist/chunk-AUQIX4E7.js.map +0 -1
  614. package/dist/coValues/CoValueBase.d.ts.map +0 -1
  615. package/dist/coValues/account.d.ts.map +0 -1
  616. package/dist/coValues/coFeed.d.ts +0 -368
  617. package/dist/coValues/coFeed.d.ts.map +0 -1
  618. package/dist/coValues/coList.d.ts.map +0 -1
  619. package/dist/coValues/coMap.d.ts +0 -529
  620. package/dist/coValues/coMap.d.ts.map +0 -1
  621. package/dist/coValues/coPlainText.d.ts.map +0 -1
  622. package/dist/coValues/coRichText.d.ts.map +0 -1
  623. package/dist/coValues/deepLoading.d.ts.map +0 -1
  624. package/dist/coValues/extensions/imageDef.d.ts.map +0 -1
  625. package/dist/coValues/group.d.ts.map +0 -1
  626. package/dist/coValues/inbox.d.ts.map +0 -1
  627. package/dist/coValues/interfaces.d.ts +0 -113
  628. package/dist/coValues/interfaces.d.ts.map +0 -1
  629. package/dist/coValues/profile.d.ts.map +0 -1
  630. package/dist/coValues/registeredSchemas.d.ts.map +0 -1
  631. package/dist/coValues/schemaUnion.d.ts.map +0 -1
  632. package/dist/exports.d.ts +0 -23
  633. package/dist/exports.d.ts.map +0 -1
  634. package/dist/implementation/ContextManager.d.ts.map +0 -1
  635. package/dist/implementation/activeAccountContext.d.ts.map +0 -1
  636. package/dist/implementation/anonymousJazzAgent.d.ts.map +0 -1
  637. package/dist/implementation/createContext.d.ts.map +0 -1
  638. package/dist/implementation/devtoolsFormatters.d.ts.map +0 -1
  639. package/dist/implementation/errors.d.ts.map +0 -1
  640. package/dist/implementation/inspect.d.ts.map +0 -1
  641. package/dist/implementation/invites.d.ts.map +0 -1
  642. package/dist/implementation/refs.d.ts.map +0 -1
  643. package/dist/implementation/schema.d.ts.map +0 -1
  644. package/dist/implementation/symbols.d.ts.map +0 -1
  645. package/dist/implementation/zodSchema/coExport.d.ts.map +0 -1
  646. package/dist/implementation/zodSchema/runtimeConverters/zodFieldToCoFieldDef.d.ts.map +0 -1
  647. package/dist/implementation/zodSchema/runtimeConverters/zodSchemaToCoSchema.d.ts.map +0 -1
  648. package/dist/implementation/zodSchema/schemaTypes/AccountSchema.d.ts.map +0 -1
  649. package/dist/implementation/zodSchema/schemaTypes/CoFeedSchema.d.ts.map +0 -1
  650. package/dist/implementation/zodSchema/schemaTypes/CoListSchema.d.ts.map +0 -1
  651. package/dist/implementation/zodSchema/schemaTypes/CoMapSchema.d.ts +0 -52
  652. package/dist/implementation/zodSchema/schemaTypes/CoMapSchema.d.ts.map +0 -1
  653. package/dist/implementation/zodSchema/schemaTypes/CoRecordSchema.d.ts.map +0 -1
  654. package/dist/implementation/zodSchema/schemaTypes/FileStreamSchema.d.ts.map +0 -1
  655. package/dist/implementation/zodSchema/schemaTypes/PlainTextSchema.d.ts.map +0 -1
  656. package/dist/implementation/zodSchema/schemaTypes/RichTextSchema.d.ts.map +0 -1
  657. package/dist/implementation/zodSchema/typeConverters/InstanceOfSchema.d.ts.map +0 -1
  658. package/dist/implementation/zodSchema/typeConverters/InstanceOfSchemaCoValuesNullable.d.ts.map +0 -1
  659. package/dist/implementation/zodSchema/typeConverters/InstanceOrPrimitiveOfSchema.d.ts.map +0 -1
  660. package/dist/implementation/zodSchema/typeConverters/InstanceOrPrimitiveOfSchemaCoValuesNullable.d.ts.map +0 -1
  661. package/dist/implementation/zodSchema/unionUtils.d.ts.map +0 -1
  662. package/dist/implementation/zodSchema/zodCo.d.ts.map +0 -1
  663. package/dist/implementation/zodSchema/zodReExport.d.ts.map +0 -1
  664. package/dist/implementation/zodSchema/zodSchema.d.ts.map +0 -1
  665. package/dist/internal.d.ts.map +0 -1
  666. package/dist/lib/cache.d.ts.map +0 -1
  667. package/dist/lib/cache.test.d.ts.map +0 -1
  668. package/dist/lib/migration.d.ts.map +0 -1
  669. package/dist/subscribe/CoValueCoreSubscription.d.ts +0 -14
  670. package/dist/subscribe/CoValueCoreSubscription.d.ts.map +0 -1
  671. package/dist/subscribe/JazzError.d.ts.map +0 -1
  672. package/dist/subscribe/SubscriptionScope.d.ts +0 -46
  673. package/dist/subscribe/SubscriptionScope.d.ts.map +0 -1
  674. package/dist/subscribe/index.d.ts.map +0 -1
  675. package/dist/subscribe/types.d.ts.map +0 -1
  676. package/dist/subscribe/utils.d.ts.map +0 -1
  677. package/dist/tests/AuthSecretStorage.test.d.ts.map +0 -1
  678. package/dist/tests/ContextManager.test.d.ts.map +0 -1
  679. package/dist/tests/DemoAuth.test.d.ts.map +0 -1
  680. package/dist/tests/PassphraseAuth.test.d.ts.map +0 -1
  681. package/dist/tests/account.test.d.ts.map +0 -1
  682. package/dist/tests/coFeed.test-d.d.ts.map +0 -1
  683. package/dist/tests/coFeed.test.d.ts.map +0 -1
  684. package/dist/tests/coList.test-d.d.ts.map +0 -1
  685. package/dist/tests/coList.test.d.ts.map +0 -1
  686. package/dist/tests/coMap.record.test-d.d.ts.map +0 -1
  687. package/dist/tests/coMap.record.test.d.ts.map +0 -1
  688. package/dist/tests/coMap.test-d.d.ts.map +0 -1
  689. package/dist/tests/coMap.test.d.ts.map +0 -1
  690. package/dist/tests/coPlainText.test.d.ts.map +0 -1
  691. package/dist/tests/createContext.test.d.ts.map +0 -1
  692. package/dist/tests/deepLoading.test.d.ts.map +0 -1
  693. package/dist/tests/fixtures.d.ts.map +0 -1
  694. package/dist/tests/groupsAndAccounts.test.d.ts.map +0 -1
  695. package/dist/tests/imageDef.test.d.ts.map +0 -1
  696. package/dist/tests/inbox.test.d.ts.map +0 -1
  697. package/dist/tests/interfaces.test.d.ts.map +0 -1
  698. package/dist/tests/invites.test.d.ts.map +0 -1
  699. package/dist/tests/load.test.d.ts.map +0 -1
  700. package/dist/tests/patterns/notifications.test.d.ts.map +0 -1
  701. package/dist/tests/patterns/requestToJoin.test.d.ts.map +0 -1
  702. package/dist/tests/schema.test.d.ts.map +0 -1
  703. package/dist/tests/schemaUnion.test.d.ts.map +0 -1
  704. package/dist/tests/subscribe.test.d.ts.map +0 -1
  705. package/dist/tests/testing.test.d.ts.map +0 -1
  706. package/dist/tests/utils.d.ts.map +0 -1
  707. package/dist/tests/zod.test.d.ts.map +0 -1
  708. package/dist/types.d.ts.map +0 -1
  709. package/src/coValues/coFeed.ts +0 -943
  710. package/src/coValues/coMap.ts +0 -825
  711. package/src/coValues/interfaces.ts +0 -454
  712. package/src/exports.ts +0 -108
  713. package/src/implementation/zodSchema/schemaTypes/CoMapSchema.ts +0 -150
  714. package/src/implementation/zodSchema/zodCo.ts +0 -364
  715. package/src/subscribe/CoValueCoreSubscription.ts +0 -71
  716. package/src/subscribe/SubscriptionScope.ts +0 -614
  717. package/src/tests/coFeed.test.ts +0 -771
  718. package/src/tests/coMap.test.ts +0 -1637
  719. package/src/tests/load.test.ts +0 -116
  720. /package/dist/{tests → react-core/tests}/fixtures.d.ts +0 -0
  721. /package/dist/{auth → tools/auth}/AuthSecretStorage.d.ts +0 -0
  722. /package/dist/{auth → tools/auth}/DemoAuth.d.ts +0 -0
  723. /package/dist/{auth → tools/auth}/InMemoryKVStore.d.ts +0 -0
  724. /package/dist/{auth → tools/auth}/KvStoreContext.d.ts +0 -0
  725. /package/dist/{auth → tools/auth}/PassphraseAuth.d.ts +0 -0
  726. /package/dist/{coValues → tools/coValues}/CoValueBase.d.ts +0 -0
  727. /package/dist/{coValues → tools/coValues}/account.d.ts +0 -0
  728. /package/dist/{coValues → tools/coValues}/coList.d.ts +0 -0
  729. /package/dist/{coValues → tools/coValues}/coPlainText.d.ts +0 -0
  730. /package/dist/{coValues → tools/coValues}/coRichText.d.ts +0 -0
  731. /package/dist/{coValues → tools/coValues}/deepLoading.d.ts +0 -0
  732. /package/dist/{coValues → tools/coValues}/extensions/imageDef.d.ts +0 -0
  733. /package/dist/{coValues → tools/coValues}/group.d.ts +0 -0
  734. /package/dist/{coValues → tools/coValues}/inbox.d.ts +0 -0
  735. /package/dist/{coValues → tools/coValues}/profile.d.ts +0 -0
  736. /package/dist/{coValues → tools/coValues}/registeredSchemas.d.ts +0 -0
  737. /package/dist/{coValues → tools/coValues}/schemaUnion.d.ts +0 -0
  738. /package/dist/{implementation → tools/implementation}/ContextManager.d.ts +0 -0
  739. /package/dist/{implementation → tools/implementation}/activeAccountContext.d.ts +0 -0
  740. /package/dist/{implementation → tools/implementation}/anonymousJazzAgent.d.ts +0 -0
  741. /package/dist/{implementation → tools/implementation}/createContext.d.ts +0 -0
  742. /package/dist/{implementation → tools/implementation}/devtoolsFormatters.d.ts +0 -0
  743. /package/dist/{implementation → tools/implementation}/errors.d.ts +0 -0
  744. /package/dist/{implementation → tools/implementation}/inspect.d.ts +0 -0
  745. /package/dist/{implementation → tools/implementation}/invites.d.ts +0 -0
  746. /package/dist/{implementation → tools/implementation}/refs.d.ts +0 -0
  747. /package/dist/{implementation → tools/implementation}/schema.d.ts +0 -0
  748. /package/dist/{implementation → tools/implementation}/symbols.d.ts +0 -0
  749. /package/dist/{implementation → tools/implementation}/zodSchema/coExport.d.ts +0 -0
  750. /package/dist/{implementation → tools/implementation}/zodSchema/runtimeConverters/zodFieldToCoFieldDef.d.ts +0 -0
  751. /package/dist/{implementation → tools/implementation}/zodSchema/runtimeConverters/zodSchemaToCoSchema.d.ts +0 -0
  752. /package/dist/{implementation → tools/implementation}/zodSchema/schemaTypes/AccountSchema.d.ts +0 -0
  753. /package/dist/{implementation → tools/implementation}/zodSchema/schemaTypes/CoFeedSchema.d.ts +0 -0
  754. /package/dist/{implementation → tools/implementation}/zodSchema/schemaTypes/CoListSchema.d.ts +0 -0
  755. /package/dist/{implementation → tools/implementation}/zodSchema/schemaTypes/CoRecordSchema.d.ts +0 -0
  756. /package/dist/{implementation → tools/implementation}/zodSchema/schemaTypes/FileStreamSchema.d.ts +0 -0
  757. /package/dist/{implementation → tools/implementation}/zodSchema/schemaTypes/PlainTextSchema.d.ts +0 -0
  758. /package/dist/{implementation → tools/implementation}/zodSchema/schemaTypes/RichTextSchema.d.ts +0 -0
  759. /package/dist/{implementation → tools/implementation}/zodSchema/typeConverters/InstanceOfSchema.d.ts +0 -0
  760. /package/dist/{implementation → tools/implementation}/zodSchema/typeConverters/InstanceOfSchemaCoValuesNullable.d.ts +0 -0
  761. /package/dist/{implementation → tools/implementation}/zodSchema/typeConverters/InstanceOrPrimitiveOfSchema.d.ts +0 -0
  762. /package/dist/{implementation → tools/implementation}/zodSchema/typeConverters/InstanceOrPrimitiveOfSchemaCoValuesNullable.d.ts +0 -0
  763. /package/dist/{implementation → tools/implementation}/zodSchema/unionUtils.d.ts +0 -0
  764. /package/dist/{implementation → tools/implementation}/zodSchema/zodCo.d.ts +0 -0
  765. /package/dist/{implementation → tools/implementation}/zodSchema/zodReExport.d.ts +0 -0
  766. /package/dist/{implementation → tools/implementation}/zodSchema/zodSchema.d.ts +0 -0
  767. /package/dist/{internal.d.ts → tools/internal.d.ts} +0 -0
  768. /package/dist/{lib → tools/lib}/cache.d.ts +0 -0
  769. /package/dist/{lib → tools/lib}/cache.test.d.ts +0 -0
  770. /package/dist/{lib → tools/lib}/migration.d.ts +0 -0
  771. /package/dist/{subscribe → tools/subscribe}/JazzError.d.ts +0 -0
  772. /package/dist/{subscribe → tools/subscribe}/index.d.ts +0 -0
  773. /package/dist/{subscribe → tools/subscribe}/types.d.ts +0 -0
  774. /package/dist/{subscribe → tools/subscribe}/utils.d.ts +0 -0
  775. /package/dist/{tests → tools/tests}/AuthSecretStorage.test.d.ts +0 -0
  776. /package/dist/{tests → tools/tests}/ContextManager.test.d.ts +0 -0
  777. /package/dist/{tests → tools/tests}/DemoAuth.test.d.ts +0 -0
  778. /package/dist/{tests → tools/tests}/PassphraseAuth.test.d.ts +0 -0
  779. /package/dist/{tests → tools/tests}/account.test.d.ts +0 -0
  780. /package/dist/{tests → tools/tests}/coFeed.test-d.d.ts +0 -0
  781. /package/dist/{tests → tools/tests}/coFeed.test.d.ts +0 -0
  782. /package/dist/{tests → tools/tests}/coList.test-d.d.ts +0 -0
  783. /package/dist/{tests → tools/tests}/coList.test.d.ts +0 -0
  784. /package/dist/{tests → tools/tests}/coMap.record.test-d.d.ts +0 -0
  785. /package/dist/{tests → tools/tests}/coMap.record.test.d.ts +0 -0
  786. /package/dist/{tests → tools/tests}/coMap.test-d.d.ts +0 -0
  787. /package/dist/{tests → tools/tests}/coMap.test.d.ts +0 -0
  788. /package/dist/{tests → tools/tests}/coPlainText.test.d.ts +0 -0
  789. /package/dist/{tests → tools/tests}/createContext.test.d.ts +0 -0
  790. /package/dist/{tests → tools/tests}/deepLoading.test.d.ts +0 -0
  791. /package/dist/{tests → tools/tests}/groupsAndAccounts.test.d.ts +0 -0
  792. /package/dist/{tests → tools/tests}/imageDef.test.d.ts +0 -0
  793. /package/dist/{tests → tools/tests}/inbox.test.d.ts +0 -0
  794. /package/dist/{tests → tools/tests}/interfaces.test.d.ts +0 -0
  795. /package/dist/{tests → tools/tests}/invites.test.d.ts +0 -0
  796. /package/dist/{tests → tools/tests}/load.test.d.ts +0 -0
  797. /package/dist/{tests → tools/tests}/patterns/notifications.test.d.ts +0 -0
  798. /package/dist/{tests → tools/tests}/patterns/requestToJoin.test.d.ts +0 -0
  799. /package/dist/{tests → tools/tests}/schema.test.d.ts +0 -0
  800. /package/dist/{tests → tools/tests}/schemaUnion.test.d.ts +0 -0
  801. /package/dist/{tests → tools/tests}/subscribe.test.d.ts +0 -0
  802. /package/dist/{tests → tools/tests}/testing.test.d.ts +0 -0
  803. /package/dist/{tests → tools/tests}/utils.d.ts +0 -0
  804. /package/dist/{tests → tools/tests}/zod.test.d.ts +0 -0
  805. /package/dist/{types.d.ts → tools/types.d.ts} +0 -0
  806. /package/src/{tests → react-core/tests}/fixtures.ts +0 -0
  807. /package/src/{auth/KvStoreContext.ts → react-native-core/storage/kv-store-context.ts} +0 -0
  808. /package/src/{auth → tools/auth}/AuthSecretStorage.ts +0 -0
  809. /package/src/{auth → tools/auth}/DemoAuth.ts +0 -0
  810. /package/src/{auth → tools/auth}/InMemoryKVStore.ts +0 -0
  811. /package/src/{auth → tools/auth}/PassphraseAuth.ts +0 -0
  812. /package/src/{coValues → tools/coValues}/CoValueBase.ts +0 -0
  813. /package/src/{coValues → tools/coValues}/account.ts +0 -0
  814. /package/src/{coValues → tools/coValues}/coList.ts +0 -0
  815. /package/src/{coValues → tools/coValues}/coPlainText.ts +0 -0
  816. /package/src/{coValues → tools/coValues}/coRichText.ts +0 -0
  817. /package/src/{coValues → tools/coValues}/deepLoading.ts +0 -0
  818. /package/src/{coValues → tools/coValues}/extensions/imageDef.ts +0 -0
  819. /package/src/{coValues → tools/coValues}/group.ts +0 -0
  820. /package/src/{coValues → tools/coValues}/inbox.ts +0 -0
  821. /package/src/{coValues → tools/coValues}/profile.ts +0 -0
  822. /package/src/{coValues → tools/coValues}/registeredSchemas.ts +0 -0
  823. /package/src/{coValues → tools/coValues}/schemaUnion.ts +0 -0
  824. /package/src/{implementation → tools/implementation}/ContextManager.ts +0 -0
  825. /package/src/{implementation → tools/implementation}/activeAccountContext.ts +0 -0
  826. /package/src/{implementation → tools/implementation}/anonymousJazzAgent.ts +0 -0
  827. /package/src/{implementation → tools/implementation}/createContext.ts +0 -0
  828. /package/src/{implementation → tools/implementation}/devtoolsFormatters.ts +0 -0
  829. /package/src/{implementation → tools/implementation}/errors.ts +0 -0
  830. /package/src/{implementation → tools/implementation}/inspect.ts +0 -0
  831. /package/src/{implementation → tools/implementation}/invites.ts +0 -0
  832. /package/src/{implementation → tools/implementation}/refs.ts +0 -0
  833. /package/src/{implementation → tools/implementation}/schema.ts +0 -0
  834. /package/src/{implementation → tools/implementation}/symbols.ts +0 -0
  835. /package/src/{implementation → tools/implementation}/zodSchema/coExport.ts +0 -0
  836. /package/src/{implementation → tools/implementation}/zodSchema/runtimeConverters/zodFieldToCoFieldDef.ts +0 -0
  837. /package/src/{implementation → tools/implementation}/zodSchema/runtimeConverters/zodSchemaToCoSchema.ts +0 -0
  838. /package/src/{implementation → tools/implementation}/zodSchema/schemaTypes/AccountSchema.ts +0 -0
  839. /package/src/{implementation → tools/implementation}/zodSchema/schemaTypes/CoFeedSchema.ts +0 -0
  840. /package/src/{implementation → tools/implementation}/zodSchema/schemaTypes/CoListSchema.ts +0 -0
  841. /package/src/{implementation → tools/implementation}/zodSchema/schemaTypes/CoRecordSchema.ts +0 -0
  842. /package/src/{implementation → tools/implementation}/zodSchema/schemaTypes/FileStreamSchema.ts +0 -0
  843. /package/src/{implementation → tools/implementation}/zodSchema/schemaTypes/PlainTextSchema.ts +0 -0
  844. /package/src/{implementation → tools/implementation}/zodSchema/schemaTypes/RichTextSchema.ts +0 -0
  845. /package/src/{implementation → tools/implementation}/zodSchema/typeConverters/InstanceOfSchema.ts +0 -0
  846. /package/src/{implementation → tools/implementation}/zodSchema/typeConverters/InstanceOfSchemaCoValuesNullable.ts +0 -0
  847. /package/src/{implementation → tools/implementation}/zodSchema/typeConverters/InstanceOrPrimitiveOfSchema.ts +0 -0
  848. /package/src/{implementation → tools/implementation}/zodSchema/typeConverters/InstanceOrPrimitiveOfSchemaCoValuesNullable.ts +0 -0
  849. /package/src/{implementation → tools/implementation}/zodSchema/unionUtils.ts +0 -0
  850. /package/src/{implementation → tools/implementation}/zodSchema/zodReExport.ts +0 -0
  851. /package/src/{implementation → tools/implementation}/zodSchema/zodSchema.ts +0 -0
  852. /package/src/{internal.ts → tools/internal.ts} +0 -0
  853. /package/src/{lib → tools/lib}/cache.test.ts +0 -0
  854. /package/src/{lib → tools/lib}/cache.ts +0 -0
  855. /package/src/{lib → tools/lib}/migration.ts +0 -0
  856. /package/src/{subscribe → tools/subscribe}/JazzError.ts +0 -0
  857. /package/src/{subscribe → tools/subscribe}/index.ts +0 -0
  858. /package/src/{subscribe → tools/subscribe}/types.ts +0 -0
  859. /package/src/{subscribe → tools/subscribe}/utils.ts +0 -0
  860. /package/src/{tests → tools/tests}/AuthSecretStorage.test.ts +0 -0
  861. /package/src/{tests → tools/tests}/ContextManager.test.ts +0 -0
  862. /package/src/{tests → tools/tests}/DemoAuth.test.ts +0 -0
  863. /package/src/{tests → tools/tests}/PassphraseAuth.test.ts +0 -0
  864. /package/src/{tests → tools/tests}/account.test.ts +0 -0
  865. /package/src/{tests → tools/tests}/coFeed.test-d.ts +0 -0
  866. /package/src/{tests → tools/tests}/coList.test-d.ts +0 -0
  867. /package/src/{tests → tools/tests}/coList.test.ts +0 -0
  868. /package/src/{tests → tools/tests}/coMap.record.test-d.ts +0 -0
  869. /package/src/{tests → tools/tests}/coMap.record.test.ts +0 -0
  870. /package/src/{tests → tools/tests}/coMap.test-d.ts +0 -0
  871. /package/src/{tests → tools/tests}/coPlainText.test.ts +0 -0
  872. /package/src/{tests → tools/tests}/createContext.test.ts +0 -0
  873. /package/src/{tests → tools/tests}/deepLoading.test.ts +0 -0
  874. /package/src/{tests → tools/tests}/groupsAndAccounts.test.ts +0 -0
  875. /package/src/{tests → tools/tests}/imageDef.test.ts +0 -0
  876. /package/src/{tests → tools/tests}/inbox.test.ts +0 -0
  877. /package/src/{tests → tools/tests}/interfaces.test.ts +0 -0
  878. /package/src/{tests → tools/tests}/invites.test.ts +0 -0
  879. /package/src/{tests → tools/tests}/patterns/notifications.test.ts +0 -0
  880. /package/src/{tests → tools/tests}/patterns/requestToJoin.test.ts +0 -0
  881. /package/src/{tests → tools/tests}/schema.test.ts +0 -0
  882. /package/src/{tests → tools/tests}/schemaUnion.test.ts +0 -0
  883. /package/src/{tests → tools/tests}/subscribe.test.ts +0 -0
  884. /package/src/{tests → tools/tests}/testing.test.ts +0 -0
  885. /package/src/{tests → tools/tests}/utils.ts +0 -0
  886. /package/src/{tests → tools/tests}/zod.test.ts +0 -0
  887. /package/src/{types.ts → tools/types.ts} +0 -0
@@ -0,0 +1,4938 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all) => {
3
+ for (var name in all)
4
+ __defProp(target, name, { get: all[name], enumerable: true });
5
+ };
6
+
7
+ // src/tools/implementation/zodSchema/zodReExport.ts
8
+ var zodReExport_exports = {};
9
+ __export(zodReExport_exports, {
10
+ array: () => array,
11
+ base64: () => base64,
12
+ base64url: () => base64url,
13
+ boolean: () => boolean,
14
+ cidrv4: () => cidrv4,
15
+ cidrv6: () => cidrv6,
16
+ cuid: () => cuid,
17
+ cuid2: () => cuid2,
18
+ date: () => date,
19
+ discriminatedUnion: () => discriminatedUnion,
20
+ email: () => email,
21
+ emoji: () => emoji,
22
+ enum: () => enum2,
23
+ int: () => int,
24
+ int32: () => int32,
25
+ ipv4: () => ipv4,
26
+ ipv6: () => ipv6,
27
+ iso: () => iso,
28
+ json: () => json,
29
+ literal: () => literal,
30
+ nanoid: () => nanoid,
31
+ number: () => number,
32
+ object: () => object,
33
+ optional: () => optional,
34
+ strictObject: () => strictObject,
35
+ string: () => string,
36
+ templateLiteral: () => templateLiteral,
37
+ tuple: () => tuple,
38
+ ulid: () => ulid,
39
+ union: () => union,
40
+ url: () => url,
41
+ uuid: () => uuid,
42
+ z: () => z
43
+ });
44
+ import {
45
+ string,
46
+ number,
47
+ boolean,
48
+ union,
49
+ object,
50
+ array,
51
+ templateLiteral,
52
+ json,
53
+ tuple,
54
+ date,
55
+ emoji,
56
+ base64,
57
+ base64url,
58
+ nanoid,
59
+ cuid,
60
+ cuid2,
61
+ ulid,
62
+ ipv4,
63
+ ipv6,
64
+ email,
65
+ url,
66
+ uuid,
67
+ literal,
68
+ enum as enum2,
69
+ cidrv4,
70
+ cidrv6,
71
+ iso,
72
+ int32,
73
+ strictObject,
74
+ discriminatedUnion,
75
+ int,
76
+ optional,
77
+ z
78
+ } from "zod/v4";
79
+
80
+ // src/tools/coValues/CoValueBase.ts
81
+ import { ControlledAccount, RawAccount } from "cojson";
82
+ var CoValueBase = class {
83
+ get _owner() {
84
+ const schema = this._raw.group instanceof RawAccount ? RegisteredSchemas["Account"] : RegisteredSchemas["Group"];
85
+ return accessChildById(this, this._raw.group.id, {
86
+ ref: schema,
87
+ optional: false
88
+ });
89
+ }
90
+ /** @private */
91
+ get _loadedAs() {
92
+ const agent = this._raw.core.node.getCurrentAgent();
93
+ if (agent instanceof ControlledAccount) {
94
+ return coValuesCache.get(
95
+ agent.account,
96
+ () => anySchemaToCoSchema(RegisteredSchemas["Account"]).fromRaw(
97
+ agent.account
98
+ )
99
+ );
100
+ }
101
+ return new AnonymousJazzAgent(this._raw.core.node);
102
+ }
103
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
104
+ constructor(..._args) {
105
+ Object.defineProperty(this, "_instanceID", {
106
+ value: `instance-${Math.random().toString(36).slice(2)}`,
107
+ enumerable: false
108
+ });
109
+ }
110
+ /** @category Internals */
111
+ static fromRaw(raw) {
112
+ return new this({ fromRaw: raw });
113
+ }
114
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
115
+ toJSON() {
116
+ return {
117
+ id: this.id,
118
+ type: this._type,
119
+ error: "unknown CoValue class"
120
+ };
121
+ }
122
+ [inspect]() {
123
+ return this.toJSON();
124
+ }
125
+ /** @category Type Helpers */
126
+ castAs(schema) {
127
+ const cl = "getCoSchema" in schema ? schema.getCoSchema() : schema;
128
+ if (this.constructor === cl) {
129
+ return this;
130
+ }
131
+ return cl.fromRaw(this._raw);
132
+ }
133
+ };
134
+
135
+ // src/tools/implementation/inspect.ts
136
+ var inspect = Symbol.for("nodejs.util.inspect.custom");
137
+
138
+ // src/tools/implementation/symbols.ts
139
+ var SchemaInit = "$SchemaInit$";
140
+ var ItemsSym = "$items$";
141
+
142
+ // src/tools/coValues/registeredSchemas.ts
143
+ var RegisteredSchemas = {};
144
+
145
+ // src/tools/coValues/coMap.ts
146
+ import {
147
+ cojsonInternals
148
+ } from "cojson";
149
+ var _CoMap = class _CoMap extends CoValueBase {
150
+ /** @internal */
151
+ get _schema() {
152
+ return this.constructor._schema;
153
+ }
154
+ /**
155
+ * The timestamp of the creation time of the CoMap
156
+ */
157
+ get _createdAt() {
158
+ return this._raw.earliestTxMadeAt ?? Number.MAX_SAFE_INTEGER;
159
+ }
160
+ /**
161
+ * The timestamp of the last updated time of the CoMap
162
+ */
163
+ get _lastUpdatedAt() {
164
+ return this._raw.latestTxMadeAt;
165
+ }
166
+ /**
167
+ * If property `prop` is a `coField.ref(...)`, you can use `coMaps._refs.prop` to access
168
+ * the `Ref` instead of the potentially loaded/null value.
169
+ *
170
+ * This allows you to always get the ID or load the value manually.
171
+ *
172
+ * @example
173
+ * ```ts
174
+ * person._refs.pet.id; // => ID<Animal>
175
+ * person._refs.pet.value;
176
+ * // => Animal | null
177
+ * const pet = await person._refs.pet.load();
178
+ * ```
179
+ *
180
+ * @category Content
181
+ **/
182
+ get _refs() {
183
+ return makeRefs(
184
+ this,
185
+ (key) => this._raw.get(key),
186
+ () => {
187
+ const keys = this._raw.keys().filter((key) => {
188
+ const descriptor = this.getDescriptor(key);
189
+ return descriptor && descriptor !== "json" && isRefEncoded(descriptor);
190
+ });
191
+ return keys;
192
+ },
193
+ this._loadedAs,
194
+ (key) => this.getDescriptor(key)
195
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
196
+ );
197
+ }
198
+ /** @internal */
199
+ getEditFromRaw(target, rawEdit, descriptor, key) {
200
+ return {
201
+ value: descriptor === "json" ? rawEdit.value : "encoded" in descriptor ? rawEdit.value === null || rawEdit.value === void 0 ? rawEdit.value : descriptor.encoded.decode(rawEdit.value) : accessChildById(target, rawEdit.value, descriptor),
202
+ ref: descriptor !== "json" && isRefEncoded(descriptor) ? new Ref(
203
+ rawEdit.value,
204
+ target._loadedAs,
205
+ descriptor,
206
+ target
207
+ ) : void 0,
208
+ get by() {
209
+ return rawEdit.by && accessChildById(target, rawEdit.by, {
210
+ ref: Account,
211
+ optional: false
212
+ });
213
+ },
214
+ madeAt: rawEdit.at,
215
+ key
216
+ };
217
+ }
218
+ /** @category Collaboration */
219
+ get _edits() {
220
+ const map = this;
221
+ return new Proxy(
222
+ {},
223
+ {
224
+ get(_target, key) {
225
+ const rawEdit = map._raw.lastEditAt(key);
226
+ if (!rawEdit) return void 0;
227
+ const descriptor = map.getDescriptor(key);
228
+ if (!descriptor) return void 0;
229
+ return {
230
+ ...map.getEditFromRaw(map, rawEdit, descriptor, key),
231
+ get all() {
232
+ return [...map._raw.editsAt(key)].map(
233
+ (rawEdit2) => map.getEditFromRaw(map, rawEdit2, descriptor, key)
234
+ );
235
+ }
236
+ };
237
+ },
238
+ ownKeys(_target) {
239
+ return map._raw.keys();
240
+ },
241
+ getOwnPropertyDescriptor(target, key) {
242
+ return {
243
+ value: Reflect.get(target, key),
244
+ writable: false,
245
+ enumerable: true,
246
+ configurable: true
247
+ };
248
+ }
249
+ }
250
+ );
251
+ }
252
+ /** @internal */
253
+ constructor(options) {
254
+ super();
255
+ if (options) {
256
+ if ("fromRaw" in options) {
257
+ Object.defineProperties(this, {
258
+ id: {
259
+ value: options.fromRaw.id,
260
+ enumerable: false
261
+ },
262
+ _raw: { value: options.fromRaw, enumerable: false }
263
+ });
264
+ } else {
265
+ throw new Error("Invalid CoMap constructor arguments");
266
+ }
267
+ }
268
+ return new Proxy(this, CoMapProxyHandler);
269
+ }
270
+ /**
271
+ * Create a new CoMap with the given initial values and owner.
272
+ *
273
+ * The owner (a Group or Account) determines access rights to the CoMap.
274
+ *
275
+ * The CoMap will immediately be persisted and synced to connected peers.
276
+ *
277
+ * @example
278
+ * ```ts
279
+ * const person = Person.create({
280
+ * name: "Alice",
281
+ * age: 42,
282
+ * pet: cat,
283
+ * }, { owner: friendGroup });
284
+ * ```
285
+ *
286
+ * @category Creation
287
+ **/
288
+ static create(init, options) {
289
+ const instance = new this();
290
+ return instance._createCoMap(init, options);
291
+ }
292
+ /**
293
+ * Return a JSON representation of the `CoMap`
294
+ * @category Content
295
+ */
296
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
297
+ toJSON(_key, processedValues) {
298
+ const result = {
299
+ id: this.id,
300
+ _type: this._type
301
+ };
302
+ for (const key of this._raw.keys()) {
303
+ const tKey = key;
304
+ const descriptor = this.getDescriptor(tKey);
305
+ if (!descriptor) {
306
+ continue;
307
+ }
308
+ if (descriptor == "json" || "encoded" in descriptor) {
309
+ result[key] = this._raw.get(key);
310
+ } else if (isRefEncoded(descriptor)) {
311
+ const id = this._raw.get(key);
312
+ if (processedValues?.includes(id) || id === this.id) {
313
+ result[key] = { _circular: id };
314
+ continue;
315
+ }
316
+ const ref2 = this[tKey];
317
+ if (ref2 && typeof ref2 === "object" && "toJSON" in ref2 && typeof ref2.toJSON === "function") {
318
+ const jsonedRef = ref2.toJSON(tKey, [
319
+ ...processedValues || [],
320
+ this.id
321
+ ]);
322
+ result[key] = jsonedRef;
323
+ }
324
+ } else {
325
+ result[key] = void 0;
326
+ }
327
+ }
328
+ return result;
329
+ }
330
+ [inspect]() {
331
+ return this.toJSON();
332
+ }
333
+ _createCoMap(init, options) {
334
+ const { owner, uniqueness } = parseCoValueCreateOptions(options);
335
+ const raw = this.rawFromInit(init, owner, uniqueness);
336
+ Object.defineProperties(this, {
337
+ id: {
338
+ value: raw.id,
339
+ enumerable: false
340
+ },
341
+ _raw: { value: raw, enumerable: false }
342
+ });
343
+ return this;
344
+ }
345
+ /**
346
+ * Create a new `RawCoMap` from an initialization object
347
+ * @internal
348
+ */
349
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
350
+ rawFromInit(init, owner, uniqueness) {
351
+ const rawOwner = owner._raw;
352
+ const rawInit = {};
353
+ if (init)
354
+ for (const key of Object.keys(init)) {
355
+ const initValue = init[key];
356
+ const descriptor = this.getDescriptor(key);
357
+ if (!descriptor) {
358
+ continue;
359
+ }
360
+ if (descriptor === "json") {
361
+ rawInit[key] = initValue;
362
+ } else if (isRefEncoded(descriptor)) {
363
+ if (initValue) {
364
+ rawInit[key] = initValue.id;
365
+ }
366
+ } else if ("encoded" in descriptor) {
367
+ rawInit[key] = descriptor.encoded.encode(
368
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
369
+ initValue
370
+ );
371
+ }
372
+ }
373
+ return rawOwner.createMap(rawInit, null, "private", uniqueness);
374
+ }
375
+ getDescriptor(key) {
376
+ return this._schema?.[key] || this._schema?.[ItemsSym];
377
+ }
378
+ /**
379
+ * Declare a Record-like CoMap schema, by extending `CoMap.Record(...)` and passing the value schema using `co`. Keys are always `string`.
380
+ *
381
+ * @example
382
+ * ```ts
383
+ * import { coField, CoMap } from "jazz-tools";
384
+ *
385
+ * class ColorToFruitMap extends CoMap.Record(
386
+ * coField.ref(Fruit)
387
+ * ) {}
388
+ *
389
+ * // assume we have map: ColorToFruitMap
390
+ * // and strawberry: Fruit
391
+ * map["red"] = strawberry;
392
+ * ```
393
+ *
394
+ * @category Declaration
395
+ */
396
+ static Record(value) {
397
+ var _a, _b;
398
+ class RecordLikeCoMap extends (_b = _CoMap, _a = ItemsSym, _b) {
399
+ constructor() {
400
+ super(...arguments);
401
+ this[_a] = value;
402
+ }
403
+ }
404
+ return RecordLikeCoMap;
405
+ }
406
+ /**
407
+ * Load a `CoMap` with a given ID, as a given account.
408
+ *
409
+ * `depth` specifies which (if any) fields that reference other CoValues to load as well before resolving.
410
+ * The `DeeplyLoaded` return type guarantees that corresponding referenced CoValues are loaded to the specified depth.
411
+ *
412
+ * You can pass `[]` or `{}` for shallowly loading only this CoMap, or `{ fieldA: depthA, fieldB: depthB }` for recursively loading referenced CoValues.
413
+ *
414
+ * Check out the `load` methods on `CoMap`/`CoList`/`CoFeed`/`Group`/`Account` to see which depth structures are valid to nest.
415
+ *
416
+ * @example
417
+ * ```ts
418
+ * const person = await Person.load(
419
+ * "co_zdsMhHtfG6VNKt7RqPUPvUtN2Ax",
420
+ * { pet: {} }
421
+ * );
422
+ * ```
423
+ *
424
+ * @category Subscription & Loading
425
+ */
426
+ static load(id, options) {
427
+ return loadCoValueWithoutMe(this, id, options);
428
+ }
429
+ static subscribe(id, ...args) {
430
+ const { options, listener } = parseSubscribeRestArgs(args);
431
+ return subscribeToCoValueWithoutMe(this, id, options, listener);
432
+ }
433
+ /** @deprecated Use `CoMap.upsertUnique` and `CoMap.loadUnique` instead. */
434
+ static findUnique(unique, ownerID, as) {
435
+ return _CoMap._findUnique(unique, ownerID, as);
436
+ }
437
+ /** @internal */
438
+ static _findUnique(unique, ownerID, as) {
439
+ as ||= activeAccountContext.get();
440
+ const header = {
441
+ type: "comap",
442
+ ruleset: {
443
+ type: "ownedByGroup",
444
+ group: ownerID
445
+ },
446
+ meta: null,
447
+ uniqueness: unique
448
+ };
449
+ const crypto = as._type === "Anonymous" ? as.node.crypto : as._raw.core.node.crypto;
450
+ return cojsonInternals.idforHeader(header, crypto);
451
+ }
452
+ /**
453
+ * Given some data, updates an existing CoMap or initialises a new one if none exists.
454
+ *
455
+ * Note: This method respects resolve options, and thus can return `null` if the references cannot be resolved.
456
+ *
457
+ * @example
458
+ * ```ts
459
+ * const activeEvent = await Event.upsertUnique(
460
+ * sourceData.identifier,
461
+ * workspace.id,
462
+ * {
463
+ * title: sourceData.title,
464
+ * identifier: sourceData.identifier,
465
+ * external_id: sourceData._id,
466
+ * },
467
+ * workspace
468
+ * );
469
+ * ```
470
+ *
471
+ * @param options The options for creating or loading the CoMap. This includes the intended state of the CoMap, its unique identifier, its owner, and the references to resolve.
472
+ * @returns Either an existing & modified CoMap, or a new initialised CoMap if none exists.
473
+ * @category Subscription & Loading
474
+ */
475
+ static async upsertUnique(options) {
476
+ let mapId = _CoMap._findUnique(options.unique, options.owner.id);
477
+ let map = await loadCoValueWithoutMe(this, mapId, {
478
+ ...options,
479
+ loadAs: options.owner._loadedAs,
480
+ skipRetry: true
481
+ });
482
+ if (!map) {
483
+ const instance = new this();
484
+ map = instance._createCoMap(options.value, {
485
+ owner: options.owner,
486
+ unique: options.unique
487
+ });
488
+ } else {
489
+ map.applyDiff(options.value);
490
+ }
491
+ return await loadCoValueWithoutMe(this, mapId, {
492
+ ...options,
493
+ loadAs: options.owner._loadedAs,
494
+ skipRetry: true
495
+ });
496
+ }
497
+ /**
498
+ * Loads a CoMap by its unique identifier and owner's ID.
499
+ * @param unique The unique identifier of the CoMap to load.
500
+ * @param ownerID The ID of the owner of the CoMap.
501
+ * @param options Additional options for loading the CoMap.
502
+ * @returns The loaded CoMap, or null if unavailable.
503
+ */
504
+ static loadUnique(unique, ownerID, options) {
505
+ return loadCoValueWithoutMe(
506
+ this,
507
+ _CoMap._findUnique(unique, ownerID, options?.loadAs),
508
+ { ...options, skipRetry: true }
509
+ );
510
+ }
511
+ /**
512
+ * Given an already loaded `CoMap`, ensure that the specified fields are loaded to the specified depth.
513
+ *
514
+ * Works like `CoMap.load()`, but you don't need to pass the ID or the account to load as again.
515
+ *
516
+ * @category Subscription & Loading
517
+ */
518
+ ensureLoaded(options) {
519
+ return ensureCoValueLoaded(this, options);
520
+ }
521
+ subscribe(...args) {
522
+ const { options, listener } = parseSubscribeRestArgs(args);
523
+ return subscribeToExistingCoValue(this, options, listener);
524
+ }
525
+ applyDiff(newValues) {
526
+ for (const key in newValues) {
527
+ if (Object.prototype.hasOwnProperty.call(newValues, key)) {
528
+ const tKey = key;
529
+ const descriptor = this.getDescriptor(key);
530
+ if (!descriptor) continue;
531
+ const newValue = newValues[tKey];
532
+ const currentValue = this[tKey];
533
+ if (descriptor === "json" || "encoded" in descriptor) {
534
+ if (currentValue !== newValue) {
535
+ this[tKey] = newValue;
536
+ }
537
+ } else if (isRefEncoded(descriptor)) {
538
+ const currentId = currentValue?.id;
539
+ const newId = newValue?.id;
540
+ if (currentId !== newId) {
541
+ this[tKey] = newValue;
542
+ }
543
+ }
544
+ }
545
+ }
546
+ return this;
547
+ }
548
+ /**
549
+ * Wait for the `CoMap` to be uploaded to the other peers.
550
+ *
551
+ * @category Subscription & Loading
552
+ */
553
+ waitForSync(options) {
554
+ return this._raw.core.waitForSync(options);
555
+ }
556
+ };
557
+ _CoMap.prototype._type = "CoMap";
558
+ var CoMap = _CoMap;
559
+ var CoMapProxyHandler = {
560
+ get(target, key, receiver) {
561
+ if (key === "_schema") {
562
+ return Reflect.get(target, key);
563
+ } else if (key in target) {
564
+ return Reflect.get(target, key, receiver);
565
+ } else {
566
+ if (typeof key !== "string") {
567
+ return void 0;
568
+ }
569
+ const descriptor = target.getDescriptor(key);
570
+ if (!descriptor) {
571
+ return void 0;
572
+ }
573
+ const raw = target._raw.get(key);
574
+ if (descriptor === "json") {
575
+ return raw;
576
+ } else if ("encoded" in descriptor) {
577
+ return raw === void 0 ? void 0 : descriptor.encoded.decode(raw);
578
+ } else if (isRefEncoded(descriptor)) {
579
+ return raw === void 0 || raw === null ? void 0 : accessChildByKey(target, raw, key);
580
+ }
581
+ }
582
+ },
583
+ set(target, key, value, receiver) {
584
+ if ((typeof key === "string" || ItemsSym) && typeof value === "object" && value !== null && SchemaInit in value) {
585
+ target.constructor._schema ||= {};
586
+ target.constructor._schema[key] = value[SchemaInit];
587
+ return true;
588
+ }
589
+ const descriptor = target.getDescriptor(key);
590
+ if (!descriptor) return false;
591
+ if (typeof key === "string") {
592
+ if (descriptor === "json") {
593
+ target._raw.set(key, value);
594
+ } else if ("encoded" in descriptor) {
595
+ target._raw.set(key, descriptor.encoded.encode(value));
596
+ } else if (isRefEncoded(descriptor)) {
597
+ if (value === void 0) {
598
+ if (descriptor.optional) {
599
+ target._raw.set(key, null);
600
+ } else {
601
+ throw new Error(
602
+ `Cannot set required reference ${key} to undefined`
603
+ );
604
+ }
605
+ } else if (value?.id) {
606
+ target._raw.set(key, value.id);
607
+ } else {
608
+ throw new Error(
609
+ `Cannot set reference ${key} to a non-CoValue. Got ${value}`
610
+ );
611
+ }
612
+ }
613
+ return true;
614
+ } else {
615
+ return Reflect.set(target, key, value, receiver);
616
+ }
617
+ },
618
+ defineProperty(target, key, attributes) {
619
+ if ("value" in attributes && typeof attributes.value === "object" && SchemaInit in attributes.value) {
620
+ target.constructor._schema ||= {};
621
+ target.constructor._schema[key] = attributes.value[SchemaInit];
622
+ return true;
623
+ } else {
624
+ return Reflect.defineProperty(target, key, attributes);
625
+ }
626
+ },
627
+ ownKeys(target) {
628
+ const keys = Reflect.ownKeys(target).filter((k) => k !== ItemsSym);
629
+ for (const key of target._raw.keys()) {
630
+ if (!keys.includes(key)) {
631
+ keys.push(key);
632
+ }
633
+ }
634
+ return keys;
635
+ },
636
+ getOwnPropertyDescriptor(target, key) {
637
+ if (key in target) {
638
+ return Reflect.getOwnPropertyDescriptor(target, key);
639
+ } else {
640
+ const descriptor = target.getDescriptor(key);
641
+ if (descriptor || key in target._raw.latest) {
642
+ return {
643
+ enumerable: true,
644
+ configurable: true,
645
+ writable: true
646
+ };
647
+ }
648
+ }
649
+ },
650
+ has(target, key) {
651
+ const descriptor = target.getDescriptor(key);
652
+ if (target._raw && typeof key === "string" && descriptor) {
653
+ return target._raw.get(key) !== void 0;
654
+ } else {
655
+ return Reflect.has(target, key);
656
+ }
657
+ },
658
+ deleteProperty(target, key) {
659
+ const descriptor = target.getDescriptor(key);
660
+ if (typeof key === "string" && descriptor) {
661
+ target._raw.delete(key);
662
+ return true;
663
+ } else {
664
+ return Reflect.deleteProperty(target, key);
665
+ }
666
+ }
667
+ };
668
+ RegisteredSchemas["CoMap"] = CoMap;
669
+
670
+ // src/tools/coValues/coList.ts
671
+ import { ControlledAccount as ControlledAccount2, RawAccount as RawAccount2 } from "cojson";
672
+ import { calcPatch } from "fast-myers-diff";
673
+ var _CoList = class _CoList extends Array {
674
+ /**
675
+ * Declare a `CoList` by subclassing `CoList.Of(...)` and passing the item schema using `co`.
676
+ *
677
+ * @example
678
+ * ```ts
679
+ * class ColorList extends CoList.Of(
680
+ * coField.string
681
+ * ) {}
682
+ * class AnimalList extends CoList.Of(
683
+ * coField.ref(Animal)
684
+ * ) {}
685
+ * ```
686
+ *
687
+ * @category Declaration
688
+ */
689
+ static Of(item) {
690
+ var _a, _b;
691
+ return class CoListOf extends (_b = _CoList, _a = coField.items, _b) {
692
+ constructor() {
693
+ super(...arguments);
694
+ this[_a] = item;
695
+ }
696
+ };
697
+ }
698
+ /**
699
+ * @ignore
700
+ * @deprecated Use UPPERCASE `CoList.Of` instead! */
701
+ static of(..._args) {
702
+ throw new Error("Can't use Array.of with CoLists");
703
+ }
704
+ /** @internal */
705
+ get _schema() {
706
+ return this.constructor._schema;
707
+ }
708
+ /** @category Collaboration */
709
+ get _owner() {
710
+ return this._raw.group instanceof RawAccount2 ? anySchemaToCoSchema(RegisteredSchemas["Account"]).fromRaw(
711
+ this._raw.group
712
+ ) : RegisteredSchemas["Group"].fromRaw(this._raw.group);
713
+ }
714
+ /**
715
+ * If a `CoList`'s items are a `coField.ref(...)`, you can use `coList._refs[i]` to access
716
+ * the `Ref` instead of the potentially loaded/null value.
717
+ *
718
+ * This allows you to always get the ID or load the value manually.
719
+ *
720
+ * @example
721
+ * ```ts
722
+ * animals._refs[0].id; // => ID<Animal>
723
+ * animals._refs[0].value;
724
+ * // => Animal | null
725
+ * const animal = await animals._refs[0].load();
726
+ * ```
727
+ *
728
+ * @category Content
729
+ **/
730
+ get _refs() {
731
+ return makeRefs(
732
+ this,
733
+ (idx) => this._raw.get(idx),
734
+ () => Array.from({ length: this._raw.entries().length }, (_, idx) => idx),
735
+ this._loadedAs,
736
+ (_idx) => this._schema[ItemsSym]
737
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
738
+ );
739
+ }
740
+ get _edits() {
741
+ throw new Error("Not implemented");
742
+ }
743
+ get _loadedAs() {
744
+ const agent = this._raw.core.node.getCurrentAgent();
745
+ if (agent instanceof ControlledAccount2) {
746
+ return coValuesCache.get(
747
+ agent.account,
748
+ () => anySchemaToCoSchema(RegisteredSchemas["Account"]).fromRaw(
749
+ agent.account
750
+ )
751
+ );
752
+ }
753
+ return new AnonymousJazzAgent(this._raw.core.node);
754
+ }
755
+ static get [(ItemsSym, Symbol.species)]() {
756
+ return Array;
757
+ }
758
+ getItemsDescriptor() {
759
+ return this._schema?.[ItemsSym];
760
+ }
761
+ constructor(options) {
762
+ super();
763
+ Object.defineProperty(this, "_instanceID", {
764
+ value: `instance-${Math.random().toString(36).slice(2)}`,
765
+ enumerable: false
766
+ });
767
+ if (options && "fromRaw" in options) {
768
+ Object.defineProperties(this, {
769
+ id: {
770
+ value: options.fromRaw.id,
771
+ enumerable: false
772
+ },
773
+ _raw: { value: options.fromRaw, enumerable: false }
774
+ });
775
+ }
776
+ return new Proxy(this, CoListProxyHandler);
777
+ }
778
+ /**
779
+ * Create a new CoList with the given initial values and owner.
780
+ *
781
+ * The owner (a Group or Account) determines access rights to the CoMap.
782
+ *
783
+ * The CoList will immediately be persisted and synced to connected peers.
784
+ *
785
+ * @example
786
+ * ```ts
787
+ * const colours = ColorList.create(
788
+ * ["red", "green", "blue"],
789
+ * { owner: me }
790
+ * );
791
+ * const animals = AnimalList.create(
792
+ * [cat, dog, fish],
793
+ * { owner: me }
794
+ * );
795
+ * ```
796
+ *
797
+ * @category Creation
798
+ **/
799
+ static create(items, options) {
800
+ const { owner } = parseCoValueCreateOptions(options);
801
+ const instance = new this({ init: items, owner });
802
+ const raw = owner._raw.createList(
803
+ toRawItems(items, instance._schema[ItemsSym])
804
+ );
805
+ Object.defineProperties(instance, {
806
+ id: {
807
+ value: raw.id,
808
+ enumerable: false
809
+ },
810
+ _raw: { value: raw, enumerable: false }
811
+ });
812
+ return instance;
813
+ }
814
+ push(...items) {
815
+ this._raw.appendItems(
816
+ toRawItems(items, this._schema[ItemsSym]),
817
+ void 0,
818
+ "private"
819
+ );
820
+ return this._raw.entries().length;
821
+ }
822
+ unshift(...items) {
823
+ for (const item of toRawItems(items, this._schema[ItemsSym])) {
824
+ this._raw.prepend(item);
825
+ }
826
+ return this._raw.entries().length;
827
+ }
828
+ pop() {
829
+ const last = this[this.length - 1];
830
+ this._raw.delete(this.length - 1);
831
+ return last;
832
+ }
833
+ shift() {
834
+ const first = this[0];
835
+ this._raw.delete(0);
836
+ return first;
837
+ }
838
+ /**
839
+ * Splice the `CoList` at a given index.
840
+ *
841
+ * @param start - The index to start the splice.
842
+ * @param deleteCount - The number of items to delete.
843
+ * @param items - The items to insert.
844
+ */
845
+ splice(start, deleteCount, ...items) {
846
+ const deleted = this.slice(start, start + deleteCount);
847
+ for (let idxToDelete = start + deleteCount - 1; idxToDelete >= start; idxToDelete--) {
848
+ this._raw.delete(idxToDelete);
849
+ }
850
+ const rawItems = toRawItems(items, this._schema[ItemsSym]);
851
+ if (rawItems.length === 0) {
852
+ return deleted;
853
+ }
854
+ if (rawItems.length === 1) {
855
+ const item = rawItems[0];
856
+ if (item === void 0) return deleted;
857
+ if (start === 0) {
858
+ this._raw.prepend(item);
859
+ } else {
860
+ this._raw.append(item, Math.max(start - 1, 0));
861
+ }
862
+ return deleted;
863
+ }
864
+ if (start === 0) {
865
+ for (let i = rawItems.length - 1; i >= 0; i--) {
866
+ const item = rawItems[i];
867
+ if (item === void 0) continue;
868
+ this._raw.prepend(item);
869
+ }
870
+ } else {
871
+ let appendAfter = Math.max(start - 1, 0);
872
+ for (const item of rawItems) {
873
+ if (item === void 0) continue;
874
+ this._raw.append(item, appendAfter);
875
+ appendAfter++;
876
+ }
877
+ }
878
+ return deleted;
879
+ }
880
+ /**
881
+ * Modify the `CoList` to match another list, where the changes are managed internally.
882
+ *
883
+ * @param result - The resolved list of items.
884
+ */
885
+ applyDiff(result) {
886
+ const current = this._raw.asArray();
887
+ const comparator = isRefEncoded(this._schema[ItemsSym]) ? (aIdx, bIdx) => {
888
+ return current[aIdx]?.id === result[bIdx]?.id;
889
+ } : void 0;
890
+ const patches = [...calcPatch(current, result, comparator)];
891
+ for (const [from, to, insert] of patches.reverse()) {
892
+ this.splice(from, to - from, ...insert);
893
+ }
894
+ }
895
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
896
+ toJSON(_key, seenAbove) {
897
+ const itemDescriptor = this._schema[ItemsSym];
898
+ if (itemDescriptor === "json") {
899
+ return this._raw.asArray();
900
+ } else if ("encoded" in itemDescriptor) {
901
+ return this._raw.asArray().map((e) => itemDescriptor.encoded.encode(e));
902
+ } else if (isRefEncoded(itemDescriptor)) {
903
+ return this.map(
904
+ (item, idx) => seenAbove?.includes(item?.id) ? { _circular: item.id } : item?.toJSON(idx + "", [
905
+ ...seenAbove || [],
906
+ this.id
907
+ ])
908
+ );
909
+ } else {
910
+ return [];
911
+ }
912
+ }
913
+ [inspect]() {
914
+ return this.toJSON();
915
+ }
916
+ /** @category Internals */
917
+ static fromRaw(raw) {
918
+ return new this({ fromRaw: raw });
919
+ }
920
+ /** @internal */
921
+ static schema(def) {
922
+ this._schema ||= {};
923
+ Object.assign(this._schema, def);
924
+ }
925
+ /**
926
+ * Load a `CoList` with a given ID, as a given account.
927
+ *
928
+ * `depth` specifies if item CoValue references should be loaded as well before resolving.
929
+ * The `DeeplyLoaded` return type guarantees that corresponding referenced CoValues are loaded to the specified depth.
930
+ *
931
+ * You can pass `[]` or for shallowly loading only this CoList, or `[itemDepth]` for recursively loading referenced CoValues.
932
+ *
933
+ * Check out the `load` methods on `CoMap`/`CoList`/`CoFeed`/`Group`/`Account` to see which depth structures are valid to nest.
934
+ *
935
+ * @example
936
+ * ```ts
937
+ * const animalsWithVets =
938
+ * await ListOfAnimals.load(
939
+ * "co_zdsMhHtfG6VNKt7RqPUPvUtN2Ax",
940
+ * me,
941
+ * [{ vet: {} }]
942
+ * );
943
+ * ```
944
+ *
945
+ * @category Subscription & Loading
946
+ */
947
+ static load(id, options) {
948
+ return loadCoValueWithoutMe(this, id, options);
949
+ }
950
+ static subscribe(id, ...args) {
951
+ const { options, listener } = parseSubscribeRestArgs(args);
952
+ return subscribeToCoValueWithoutMe(this, id, options, listener);
953
+ }
954
+ /**
955
+ * Given an already loaded `CoList`, ensure that items are loaded to the specified depth.
956
+ *
957
+ * Works like `CoList.load()`, but you don't need to pass the ID or the account to load as again.
958
+ *
959
+ * @category Subscription & Loading
960
+ */
961
+ ensureLoaded(options) {
962
+ return ensureCoValueLoaded(this, options);
963
+ }
964
+ subscribe(...args) {
965
+ const { options, listener } = parseSubscribeRestArgs(args);
966
+ return subscribeToExistingCoValue(this, options, listener);
967
+ }
968
+ /** @category Type Helpers */
969
+ castAs(cl) {
970
+ return cl.fromRaw(this._raw);
971
+ }
972
+ /**
973
+ * Wait for the `CoList` to be uploaded to the other peers.
974
+ *
975
+ * @category Subscription & Loading
976
+ */
977
+ waitForSync(options) {
978
+ return this._raw.core.waitForSync(options);
979
+ }
980
+ };
981
+ _CoList.prototype._type = "CoList";
982
+ var CoList = _CoList;
983
+ function toRawItems(items, itemDescriptor) {
984
+ const rawItems = itemDescriptor === "json" ? items : "encoded" in itemDescriptor ? items?.map((e) => itemDescriptor.encoded.encode(e)) : isRefEncoded(itemDescriptor) ? items?.map((v) => {
985
+ if (!v) return null;
986
+ return v.id;
987
+ }) : (() => {
988
+ throw new Error("Invalid element descriptor");
989
+ })();
990
+ return rawItems;
991
+ }
992
+ var CoListProxyHandler = {
993
+ get(target, key, receiver) {
994
+ if (typeof key === "string" && !isNaN(+key)) {
995
+ const itemDescriptor = target._schema[ItemsSym];
996
+ const rawValue = target._raw.get(Number(key));
997
+ if (itemDescriptor === "json") {
998
+ return rawValue;
999
+ } else if ("encoded" in itemDescriptor) {
1000
+ return rawValue === void 0 ? void 0 : itemDescriptor.encoded.decode(rawValue);
1001
+ } else if (isRefEncoded(itemDescriptor)) {
1002
+ return rawValue === void 0 || rawValue === null ? void 0 : accessChildByKey(target, rawValue, key);
1003
+ }
1004
+ } else if (key === "length") {
1005
+ return target._raw.entries().length;
1006
+ } else {
1007
+ return Reflect.get(target, key, receiver);
1008
+ }
1009
+ },
1010
+ set(target, key, value, receiver) {
1011
+ if (key === ItemsSym && typeof value === "object" && SchemaInit in value) {
1012
+ target.constructor._schema ||= {};
1013
+ target.constructor._schema[ItemsSym] = value[SchemaInit];
1014
+ return true;
1015
+ }
1016
+ if (typeof key === "string" && !isNaN(+key)) {
1017
+ const itemDescriptor = target._schema[ItemsSym];
1018
+ let rawValue;
1019
+ if (itemDescriptor === "json") {
1020
+ rawValue = value;
1021
+ } else if ("encoded" in itemDescriptor) {
1022
+ rawValue = itemDescriptor.encoded.encode(value);
1023
+ } else if (isRefEncoded(itemDescriptor)) {
1024
+ if (value === void 0) {
1025
+ if (itemDescriptor.optional) {
1026
+ rawValue = null;
1027
+ } else {
1028
+ throw new Error(
1029
+ `Cannot set required reference ${key} to undefined`
1030
+ );
1031
+ }
1032
+ } else if (value?.id) {
1033
+ rawValue = value.id;
1034
+ } else {
1035
+ throw new Error(
1036
+ `Cannot set reference ${key} to a non-CoValue. Got ${value}`
1037
+ );
1038
+ }
1039
+ }
1040
+ target._raw.replace(Number(key), rawValue);
1041
+ return true;
1042
+ } else {
1043
+ return Reflect.set(target, key, value, receiver);
1044
+ }
1045
+ },
1046
+ defineProperty(target, key, descriptor) {
1047
+ if (descriptor.value && key === ItemsSym && typeof descriptor.value === "object" && SchemaInit in descriptor.value) {
1048
+ target.constructor._schema ||= {};
1049
+ target.constructor._schema[ItemsSym] = descriptor.value[SchemaInit];
1050
+ return true;
1051
+ } else {
1052
+ return Reflect.defineProperty(target, key, descriptor);
1053
+ }
1054
+ },
1055
+ has(target, key) {
1056
+ if (typeof key === "string" && !isNaN(+key)) {
1057
+ return Number(key) < target._raw.entries().length;
1058
+ } else {
1059
+ return Reflect.has(target, key);
1060
+ }
1061
+ }
1062
+ };
1063
+
1064
+ // src/tools/coValues/coFeed.ts
1065
+ import { MAX_RECOMMENDED_TX_SIZE, cojsonInternals as cojsonInternals2 } from "cojson";
1066
+ var _CoFeed = class _CoFeed extends CoValueBase {
1067
+ /**
1068
+ * Declare a `CoFeed` by subclassing `CoFeed.Of(...)` and passing the item schema using a `co` primitive or a `coField.ref`.
1069
+ *
1070
+ * @example
1071
+ * ```ts
1072
+ * class ColorFeed extends CoFeed.Of(coField.string) {}
1073
+ * class AnimalFeed extends CoFeed.Of(coField.ref(Animal)) {}
1074
+ * ```
1075
+ *
1076
+ * @category Declaration
1077
+ */
1078
+ static Of(item) {
1079
+ var _a, _b;
1080
+ const cls = class CoFeedOf extends (_b = _CoFeed, _a = coField.items, _b) {
1081
+ constructor() {
1082
+ super(...arguments);
1083
+ this[_a] = item;
1084
+ }
1085
+ };
1086
+ cls._schema ||= {};
1087
+ cls._schema[ItemsSym] = item[SchemaInit];
1088
+ return cls;
1089
+ }
1090
+ /** @internal */
1091
+ get _schema() {
1092
+ return this.constructor._schema;
1093
+ }
1094
+ /**
1095
+ * The current account's view of this `CoFeed`
1096
+ * @category Content
1097
+ */
1098
+ get byMe() {
1099
+ if (this._loadedAs._type === "Account") {
1100
+ return this.perAccount[this._loadedAs.id];
1101
+ } else {
1102
+ return void 0;
1103
+ }
1104
+ }
1105
+ /**
1106
+ * The per-account view of this `CoFeed`
1107
+ *
1108
+ * @example
1109
+ * ```ts
1110
+ * // Access entries directly by account ID
1111
+ * const aliceEntries = feed[aliceAccount.id];
1112
+ * console.log(aliceEntries.value); // Latest value from Alice
1113
+ *
1114
+ * // Iterate through all accounts' entries
1115
+ * for (const [accountId, entries] of Object.entries(feed)) {
1116
+ * console.log(`Latest entry from ${accountId}:`, entries.value);
1117
+ *
1118
+ * // Access all entries from this account
1119
+ * for (const entry of entries.all) {
1120
+ * console.log(`Entry made at ${entry.madeAt}:`, entry.value);
1121
+ * }
1122
+ * }
1123
+ * ```
1124
+ *
1125
+ * @category Content
1126
+ */
1127
+ get perAccount() {
1128
+ return new Proxy({}, CoStreamPerAccountProxyHandler(this));
1129
+ }
1130
+ /**
1131
+ * The per-session view of this `CoFeed`
1132
+ * @category Content
1133
+ */
1134
+ get perSession() {
1135
+ return new Proxy(
1136
+ {},
1137
+ CoStreamPerSessionProxyHandler(this, this)
1138
+ );
1139
+ }
1140
+ /**
1141
+ * The current session's view of this `CoFeed`
1142
+ *
1143
+ * This is a shortcut for `this.perSession` where the session ID is the current session ID.
1144
+ *
1145
+ * @category Content
1146
+ */
1147
+ get inCurrentSession() {
1148
+ if (this._loadedAs._type === "Account") {
1149
+ return this.perSession[this._loadedAs.sessionID];
1150
+ } else {
1151
+ return void 0;
1152
+ }
1153
+ }
1154
+ constructor(options) {
1155
+ super();
1156
+ if (options && "fromRaw" in options) {
1157
+ Object.defineProperties(this, {
1158
+ id: {
1159
+ value: options.fromRaw.id,
1160
+ enumerable: false
1161
+ },
1162
+ _raw: { value: options.fromRaw, enumerable: false }
1163
+ });
1164
+ }
1165
+ return this;
1166
+ }
1167
+ /**
1168
+ * Create a new `CoFeed`
1169
+ * @category Creation
1170
+ */
1171
+ static create(init, options) {
1172
+ const { owner } = parseCoValueCreateOptions(options);
1173
+ const instance = new this({ init, owner });
1174
+ const raw = owner._raw.createStream();
1175
+ Object.defineProperties(instance, {
1176
+ id: {
1177
+ value: raw.id,
1178
+ enumerable: false
1179
+ },
1180
+ _raw: { value: raw, enumerable: false }
1181
+ });
1182
+ if (init) {
1183
+ instance.push(...init);
1184
+ }
1185
+ return instance;
1186
+ }
1187
+ getItemsDescriptor() {
1188
+ return this._schema?.[ItemsSym];
1189
+ }
1190
+ /**
1191
+ * Push items to this `CoFeed`
1192
+ *
1193
+ * Items are appended to the current session's log. Each session (tab, device, app instance)
1194
+ * maintains its own append-only log, which is then aggregated into the per-account view.
1195
+ *
1196
+ * @example
1197
+ * ```ts
1198
+ * // Adds items to current session's log
1199
+ * feed.push("item1", "item2");
1200
+ *
1201
+ * // View items from current session
1202
+ * console.log(feed.inCurrentSession);
1203
+ *
1204
+ * // View aggregated items from all sessions for current account
1205
+ * console.log(feed.byMe);
1206
+ * ```
1207
+ *
1208
+ * @category Content
1209
+ */
1210
+ push(...items) {
1211
+ for (const item of items) {
1212
+ this.pushItem(item);
1213
+ }
1214
+ }
1215
+ pushItem(item) {
1216
+ const itemDescriptor = this._schema[ItemsSym];
1217
+ if (itemDescriptor === "json") {
1218
+ this._raw.push(item);
1219
+ } else if ("encoded" in itemDescriptor) {
1220
+ this._raw.push(itemDescriptor.encoded.encode(item));
1221
+ } else if (isRefEncoded(itemDescriptor)) {
1222
+ this._raw.push(item.id);
1223
+ }
1224
+ }
1225
+ /**
1226
+ * Get a JSON representation of the `CoFeed`
1227
+ * @category
1228
+ */
1229
+ toJSON() {
1230
+ const itemDescriptor = this._schema[ItemsSym];
1231
+ const mapper = itemDescriptor === "json" ? (v) => v : "encoded" in itemDescriptor ? itemDescriptor.encoded.encode : (v) => v && v.id;
1232
+ return {
1233
+ id: this.id,
1234
+ _type: this._type,
1235
+ ...Object.fromEntries(
1236
+ Object.entries(this).map(([account, entry]) => [
1237
+ account,
1238
+ mapper(entry.value)
1239
+ ])
1240
+ ),
1241
+ in: Object.fromEntries(
1242
+ Object.entries(this.perSession).map(([session, entry]) => [
1243
+ session,
1244
+ mapper(entry.value)
1245
+ ])
1246
+ )
1247
+ };
1248
+ }
1249
+ /** @internal */
1250
+ [(ItemsSym, inspect)]() {
1251
+ return this.toJSON();
1252
+ }
1253
+ /** @internal */
1254
+ static schema(def) {
1255
+ this._schema ||= {};
1256
+ Object.assign(this._schema, def);
1257
+ }
1258
+ /**
1259
+ * Load a `CoFeed`
1260
+ * @category Subscription & Loading
1261
+ */
1262
+ static load(id, options) {
1263
+ return loadCoValueWithoutMe(this, id, options);
1264
+ }
1265
+ static subscribe(id, ...args) {
1266
+ const { options, listener } = parseSubscribeRestArgs(args);
1267
+ return subscribeToCoValueWithoutMe(this, id, options, listener);
1268
+ }
1269
+ /**
1270
+ * Ensure a `CoFeed` is loaded to the specified depth
1271
+ *
1272
+ * @returns A new instance of the same CoFeed that's loaded to the specified depth
1273
+ * @category Subscription & Loading
1274
+ */
1275
+ ensureLoaded(options) {
1276
+ return ensureCoValueLoaded(this, options);
1277
+ }
1278
+ subscribe(...args) {
1279
+ const { options, listener } = parseSubscribeRestArgs(args);
1280
+ return subscribeToExistingCoValue(this, options, listener);
1281
+ }
1282
+ /**
1283
+ * Wait for the `CoFeed` to be uploaded to the other peers.
1284
+ *
1285
+ * @category Subscription & Loading
1286
+ */
1287
+ waitForSync(options) {
1288
+ return this._raw.core.waitForSync(options);
1289
+ }
1290
+ };
1291
+ _CoFeed.prototype._type = "CoStream";
1292
+ var CoFeed = _CoFeed;
1293
+ function entryFromRawEntry(accessFrom, rawEntry, loadedAs, accountID, itemField) {
1294
+ return {
1295
+ get value() {
1296
+ if (itemField === "json") {
1297
+ return rawEntry.value;
1298
+ } else if ("encoded" in itemField) {
1299
+ return itemField.encoded.decode(rawEntry.value);
1300
+ } else if (isRefEncoded(itemField)) {
1301
+ return accessChildById(
1302
+ accessFrom,
1303
+ rawEntry.value,
1304
+ itemField
1305
+ );
1306
+ } else {
1307
+ throw new Error("Invalid item field schema");
1308
+ }
1309
+ },
1310
+ get ref() {
1311
+ if (itemField !== "json" && isRefEncoded(itemField)) {
1312
+ const rawId = rawEntry.value;
1313
+ return new Ref(
1314
+ rawId,
1315
+ loadedAs,
1316
+ itemField,
1317
+ accessFrom
1318
+ );
1319
+ } else {
1320
+ return void 0;
1321
+ }
1322
+ },
1323
+ get by() {
1324
+ return accountID && accessChildById(accessFrom, accountID, {
1325
+ ref: Account,
1326
+ optional: false
1327
+ });
1328
+ },
1329
+ madeAt: rawEntry.at,
1330
+ tx: rawEntry.tx
1331
+ };
1332
+ }
1333
+ var CoStreamPerAccountProxyHandler = (innerTarget) => ({
1334
+ get(_target, key, receiver) {
1335
+ if (typeof key === "string" && key.startsWith("co_")) {
1336
+ const rawEntry = innerTarget._raw.lastItemBy(key);
1337
+ if (!rawEntry) return;
1338
+ const entry = entryFromRawEntry(
1339
+ receiver,
1340
+ rawEntry,
1341
+ innerTarget._loadedAs,
1342
+ key,
1343
+ innerTarget._schema[ItemsSym]
1344
+ );
1345
+ Object.defineProperty(entry, "all", {
1346
+ get: () => {
1347
+ const allRawEntries = innerTarget._raw.itemsBy(key);
1348
+ return function* () {
1349
+ while (true) {
1350
+ const rawEntry2 = allRawEntries.next();
1351
+ if (rawEntry2.done) return;
1352
+ yield entryFromRawEntry(
1353
+ receiver,
1354
+ rawEntry2.value,
1355
+ innerTarget._loadedAs,
1356
+ key,
1357
+ innerTarget._schema[ItemsSym]
1358
+ );
1359
+ }
1360
+ }();
1361
+ }
1362
+ });
1363
+ return entry;
1364
+ } else {
1365
+ return Reflect.get(innerTarget, key, receiver);
1366
+ }
1367
+ },
1368
+ ownKeys(_target) {
1369
+ return Array.from(innerTarget._raw.accounts());
1370
+ },
1371
+ getOwnPropertyDescriptor(_target, key) {
1372
+ if (typeof key === "string" && key.startsWith("co_")) {
1373
+ return {
1374
+ configurable: true,
1375
+ enumerable: true,
1376
+ writable: false
1377
+ };
1378
+ } else {
1379
+ return Reflect.getOwnPropertyDescriptor(innerTarget, key);
1380
+ }
1381
+ }
1382
+ });
1383
+ var CoStreamPerSessionProxyHandler = (innerTarget, accessFrom) => ({
1384
+ get(_target, key, receiver) {
1385
+ if (typeof key === "string" && key.includes("session")) {
1386
+ const sessionID = key;
1387
+ const rawEntry = innerTarget._raw.lastItemIn(sessionID);
1388
+ if (!rawEntry) return;
1389
+ const by = cojsonInternals2.accountOrAgentIDfromSessionID(sessionID);
1390
+ const entry = entryFromRawEntry(
1391
+ accessFrom,
1392
+ rawEntry,
1393
+ innerTarget._loadedAs,
1394
+ cojsonInternals2.isAccountID(by) ? by : void 0,
1395
+ innerTarget._schema[ItemsSym]
1396
+ );
1397
+ Object.defineProperty(entry, "all", {
1398
+ get: () => {
1399
+ const allRawEntries = innerTarget._raw.itemsIn(sessionID);
1400
+ return function* () {
1401
+ while (true) {
1402
+ const rawEntry2 = allRawEntries.next();
1403
+ if (rawEntry2.done) return;
1404
+ yield entryFromRawEntry(
1405
+ accessFrom,
1406
+ rawEntry2.value,
1407
+ innerTarget._loadedAs,
1408
+ cojsonInternals2.isAccountID(by) ? by : void 0,
1409
+ innerTarget._schema[ItemsSym]
1410
+ );
1411
+ }
1412
+ }();
1413
+ }
1414
+ });
1415
+ return entry;
1416
+ } else {
1417
+ return Reflect.get(innerTarget, key, receiver);
1418
+ }
1419
+ },
1420
+ ownKeys() {
1421
+ return innerTarget._raw.sessions();
1422
+ },
1423
+ getOwnPropertyDescriptor(target, key) {
1424
+ if (typeof key === "string" && key.startsWith("co_")) {
1425
+ return {
1426
+ configurable: true,
1427
+ enumerable: true,
1428
+ writable: false
1429
+ };
1430
+ } else {
1431
+ return Reflect.getOwnPropertyDescriptor(target, key);
1432
+ }
1433
+ }
1434
+ });
1435
+ var FileStream = class extends CoValueBase {
1436
+ constructor(options) {
1437
+ super();
1438
+ let raw;
1439
+ if ("fromRaw" in options) {
1440
+ raw = options.fromRaw;
1441
+ } else {
1442
+ const rawOwner = options.owner._raw;
1443
+ raw = rawOwner.createBinaryStream();
1444
+ }
1445
+ Object.defineProperties(this, {
1446
+ id: {
1447
+ value: raw.id,
1448
+ enumerable: false
1449
+ },
1450
+ _type: { value: "BinaryCoStream", enumerable: false },
1451
+ _raw: { value: raw, enumerable: false }
1452
+ });
1453
+ }
1454
+ /**
1455
+ * Create a new empty `FileStream` instance.
1456
+ *
1457
+ * @param options - Configuration options for the new FileStream
1458
+ * @param options.owner - The Account or Group that will own this FileStream and control access rights
1459
+ *
1460
+ * @example
1461
+ * ```typescript
1462
+ * // Create owned by an account
1463
+ * const stream = FileStream.create({ owner: myAccount });
1464
+ *
1465
+ * // Create owned by a group
1466
+ * const stream = FileStream.create({ owner: teamGroup });
1467
+ *
1468
+ * // Create with implicit owner
1469
+ * const stream = FileStream.create(myAccount);
1470
+ * ```
1471
+ *
1472
+ * @remarks
1473
+ * For uploading an existing file or blob, use {@link FileStream.createFromBlob} instead.
1474
+ *
1475
+ * @category Creation
1476
+ */
1477
+ static create(options) {
1478
+ return new this(parseCoValueCreateOptions(options));
1479
+ }
1480
+ getMetadata() {
1481
+ return this._raw.getBinaryStreamInfo();
1482
+ }
1483
+ getChunks(options) {
1484
+ return this._raw.getBinaryChunks(options?.allowUnfinished);
1485
+ }
1486
+ isBinaryStreamEnded() {
1487
+ return this._raw.isBinaryStreamEnded();
1488
+ }
1489
+ start(options) {
1490
+ this._raw.startBinaryStream(options);
1491
+ }
1492
+ push(data) {
1493
+ this._raw.pushBinaryStreamChunk(data);
1494
+ }
1495
+ end() {
1496
+ this._raw.endBinaryStream();
1497
+ }
1498
+ toBlob(options) {
1499
+ const chunks = this.getChunks({
1500
+ allowUnfinished: options?.allowUnfinished
1501
+ });
1502
+ if (!chunks) {
1503
+ return void 0;
1504
+ }
1505
+ return new Blob(chunks.chunks, { type: chunks.mimeType });
1506
+ }
1507
+ /**
1508
+ * Load a `FileStream` as a `Blob`
1509
+ *
1510
+ * @category Content
1511
+ */
1512
+ static async loadAsBlob(id, options) {
1513
+ let stream = await this.load(id, options);
1514
+ return stream?.toBlob({
1515
+ allowUnfinished: options?.allowUnfinished
1516
+ });
1517
+ }
1518
+ static async loadAsBase64(id, options) {
1519
+ const stream = await this.load(id, options);
1520
+ return stream?.asBase64(options);
1521
+ }
1522
+ asBase64(options) {
1523
+ const chunks = this.getChunks(options);
1524
+ if (!chunks) return void 0;
1525
+ const output = [];
1526
+ for (const chunk of chunks.chunks) {
1527
+ for (const byte of chunk) {
1528
+ output.push(String.fromCharCode(byte));
1529
+ }
1530
+ }
1531
+ const base642 = btoa(output.join(""));
1532
+ if (options?.dataURL) {
1533
+ return `data:${chunks.mimeType};base64,${base642}`;
1534
+ }
1535
+ return base642;
1536
+ }
1537
+ /**
1538
+ * Create a `FileStream` from a `Blob` or `File`
1539
+ *
1540
+ * @example
1541
+ * ```ts
1542
+ * import { coField, FileStream } from "jazz-tools";
1543
+ *
1544
+ * const fileStream = await FileStream.createFromBlob(file, {owner: group})
1545
+ * ```
1546
+ * @category Content
1547
+ */
1548
+ static async createFromBlob(blob, options) {
1549
+ const stream = this.create(options);
1550
+ const onProgress = options && "onProgress" in options ? options.onProgress : void 0;
1551
+ const start = Date.now();
1552
+ const data = new Uint8Array(await blob.arrayBuffer());
1553
+ stream.start({
1554
+ mimeType: blob.type,
1555
+ totalSizeBytes: blob.size,
1556
+ fileName: blob instanceof File ? blob.name : void 0
1557
+ });
1558
+ const chunkSize = MAX_RECOMMENDED_TX_SIZE;
1559
+ let lastProgressUpdate = Date.now();
1560
+ for (let idx = 0; idx < data.length; idx += chunkSize) {
1561
+ stream.push(data.slice(idx, idx + chunkSize));
1562
+ if (Date.now() - lastProgressUpdate > 100) {
1563
+ onProgress?.(idx / data.length);
1564
+ lastProgressUpdate = Date.now();
1565
+ }
1566
+ await new Promise((resolve) => setTimeout(resolve, 0));
1567
+ }
1568
+ stream.end();
1569
+ const end = Date.now();
1570
+ console.debug(
1571
+ "Finished creating binary stream in",
1572
+ (end - start) / 1e3,
1573
+ "s - Throughput in MB/s",
1574
+ 1e3 * (blob.size / (end - start)) / (1024 * 1024)
1575
+ );
1576
+ onProgress?.(1);
1577
+ return stream;
1578
+ }
1579
+ /**
1580
+ * Get a JSON representation of the `FileStream`
1581
+ * @category Content
1582
+ */
1583
+ toJSON() {
1584
+ return {
1585
+ id: this.id,
1586
+ _type: this._type,
1587
+ ...this.getChunks()
1588
+ };
1589
+ }
1590
+ /** @internal */
1591
+ [inspect]() {
1592
+ return this.toJSON();
1593
+ }
1594
+ /**
1595
+ * Load a `FileStream`
1596
+ * @category Subscription & Loading
1597
+ */
1598
+ static async load(id, options) {
1599
+ const stream = await loadCoValueWithoutMe(this, id, options);
1600
+ if (!options?.allowUnfinished && !stream?.isBinaryStreamEnded()) {
1601
+ return new Promise((resolve) => {
1602
+ subscribeToCoValueWithoutMe(
1603
+ this,
1604
+ id,
1605
+ options || {},
1606
+ (value, unsubscribe) => {
1607
+ if (value.isBinaryStreamEnded()) {
1608
+ unsubscribe();
1609
+ resolve(value);
1610
+ }
1611
+ }
1612
+ );
1613
+ });
1614
+ }
1615
+ return stream;
1616
+ }
1617
+ static subscribe(id, ...args) {
1618
+ const { options, listener } = parseSubscribeRestArgs(args);
1619
+ return subscribeToCoValueWithoutMe(this, id, options, listener);
1620
+ }
1621
+ /**
1622
+ * An instance method to subscribe to an existing `FileStream`
1623
+ * @category Subscription & Loading
1624
+ */
1625
+ subscribe(listener) {
1626
+ return subscribeToExistingCoValue(this, {}, listener);
1627
+ }
1628
+ /**
1629
+ * Wait for the `FileStream` to be uploaded to the other peers.
1630
+ *
1631
+ * @category Subscription & Loading
1632
+ */
1633
+ waitForSync(options) {
1634
+ return this._raw.core.waitForSync(options);
1635
+ }
1636
+ };
1637
+
1638
+ // src/tools/coValues/account.ts
1639
+ import {
1640
+ ControlledAccount as ControlledAccount3,
1641
+ LocalNode,
1642
+ cojsonInternals as cojsonInternals3
1643
+ } from "cojson";
1644
+ var _Account = class _Account extends CoValueBase {
1645
+ get _schema() {
1646
+ return this.constructor._schema;
1647
+ }
1648
+ get _owner() {
1649
+ return this;
1650
+ }
1651
+ get _loadedAs() {
1652
+ if (this.isLocalNodeOwner) return this;
1653
+ const agent = this._raw.core.node.getCurrentAgent();
1654
+ if (agent instanceof ControlledAccount3) {
1655
+ return coValuesCache.get(
1656
+ agent.account,
1657
+ () => _Account.fromRaw(agent.account)
1658
+ );
1659
+ }
1660
+ return new AnonymousJazzAgent(this._raw.core.node);
1661
+ }
1662
+ getDescriptor(key) {
1663
+ if (key === "profile") {
1664
+ return this._schema.profile;
1665
+ } else if (key === "root") {
1666
+ return this._schema.root;
1667
+ }
1668
+ return void 0;
1669
+ }
1670
+ get _refs() {
1671
+ const profileID = this._raw.get("profile");
1672
+ const rootID = this._raw.get("root");
1673
+ return {
1674
+ profile: profileID ? new Ref(
1675
+ profileID,
1676
+ this._loadedAs,
1677
+ this._schema.profile,
1678
+ this
1679
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1680
+ ) : void 0,
1681
+ root: rootID ? new Ref(
1682
+ rootID,
1683
+ this._loadedAs,
1684
+ this._schema.root,
1685
+ this
1686
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1687
+ ) : void 0
1688
+ };
1689
+ }
1690
+ /**
1691
+ * Whether this account is the currently active account.
1692
+ */
1693
+ get isMe() {
1694
+ return activeAccountContext.get().id === this.id;
1695
+ }
1696
+ constructor(options) {
1697
+ super();
1698
+ if (!("fromRaw" in options)) {
1699
+ throw new Error("Can only construct account from raw or with .create()");
1700
+ }
1701
+ this.isLocalNodeOwner = options.fromRaw.id == options.fromRaw.core.node.getCurrentAgent().id;
1702
+ Object.defineProperties(this, {
1703
+ id: {
1704
+ value: options.fromRaw.id,
1705
+ enumerable: false
1706
+ },
1707
+ _raw: { value: options.fromRaw, enumerable: false },
1708
+ _type: { value: "Account", enumerable: false }
1709
+ });
1710
+ if (this.isLocalNodeOwner) {
1711
+ this.sessionID = options.fromRaw.core.node.currentSessionID;
1712
+ }
1713
+ return new Proxy(this, AccountAndGroupProxyHandler);
1714
+ }
1715
+ myRole() {
1716
+ if (this.isLocalNodeOwner) {
1717
+ return "admin";
1718
+ }
1719
+ }
1720
+ getRoleOf(member) {
1721
+ if (member === "me") {
1722
+ return this.isMe ? "admin" : void 0;
1723
+ }
1724
+ if (member === this.id) {
1725
+ return "admin";
1726
+ }
1727
+ return void 0;
1728
+ }
1729
+ getParentGroups() {
1730
+ return [];
1731
+ }
1732
+ get members() {
1733
+ const ref2 = new Ref(
1734
+ this.id,
1735
+ this._loadedAs,
1736
+ {
1737
+ ref: () => this.constructor,
1738
+ optional: false
1739
+ },
1740
+ this
1741
+ );
1742
+ return [{ id: this.id, role: "admin", ref: ref2, account: this }];
1743
+ }
1744
+ canRead(value) {
1745
+ const role = value._owner.getRoleOf(this.id);
1746
+ return role === "admin" || role === "writer" || role === "reader" || role === "writeOnly";
1747
+ }
1748
+ canWrite(value) {
1749
+ const role = value._owner.getRoleOf(this.id);
1750
+ return role === "admin" || role === "writer" || role === "writeOnly";
1751
+ }
1752
+ canAdmin(value) {
1753
+ return value._owner.getRoleOf(this.id) === "admin";
1754
+ }
1755
+ async acceptInvite(valueID, inviteSecret, coValueClass) {
1756
+ if (!this.isLocalNodeOwner) {
1757
+ throw new Error("Only a controlled account can accept invites");
1758
+ }
1759
+ await this._raw.core.node.acceptInvite(
1760
+ valueID,
1761
+ inviteSecret
1762
+ );
1763
+ return loadCoValue(anySchemaToCoSchema(coValueClass), valueID, {
1764
+ loadAs: this
1765
+ });
1766
+ }
1767
+ /** @private */
1768
+ static async create(options) {
1769
+ const { node } = await LocalNode.withNewlyCreatedAccount({
1770
+ ...options,
1771
+ migration: async (rawAccount, _node, creationProps) => {
1772
+ const account = new this({
1773
+ fromRaw: rawAccount
1774
+ });
1775
+ await account.applyMigration?.(creationProps);
1776
+ }
1777
+ });
1778
+ return this.fromNode(node);
1779
+ }
1780
+ static getMe() {
1781
+ return activeAccountContext.get();
1782
+ }
1783
+ static async createAs(as, options) {
1784
+ const connectedPeers = cojsonInternals3.connectedPeers(
1785
+ "creatingAccount",
1786
+ "createdAccount",
1787
+ { peer1role: "server", peer2role: "client" }
1788
+ );
1789
+ as._raw.core.node.syncManager.addPeer(connectedPeers[1]);
1790
+ const account = await this.create({
1791
+ creationProps: options.creationProps,
1792
+ crypto: as._raw.core.node.crypto,
1793
+ peersToLoadFrom: [connectedPeers[0]]
1794
+ });
1795
+ await account.waitForAllCoValuesSync();
1796
+ return account;
1797
+ }
1798
+ static fromNode(node) {
1799
+ return new this({
1800
+ fromRaw: node.expectCurrentAccount("jazz-tools/Account.fromNode")
1801
+ });
1802
+ }
1803
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1804
+ toJSON() {
1805
+ return {
1806
+ id: this.id,
1807
+ _type: this._type
1808
+ };
1809
+ }
1810
+ [inspect]() {
1811
+ return this.toJSON();
1812
+ }
1813
+ async applyMigration(creationProps) {
1814
+ await this.migrate(creationProps);
1815
+ if (this.profile === void 0 && creationProps) {
1816
+ const profileGroup = RegisteredSchemas["Group"].create({ owner: this });
1817
+ this.profile = Profile.create({ name: creationProps.name }, profileGroup);
1818
+ profileGroup.addMember("everyone", "reader");
1819
+ } else if (this.profile && creationProps) {
1820
+ if (this.profile._owner._type !== "Group") {
1821
+ throw new Error("Profile must be owned by a Group", {
1822
+ cause: `The profile of the account "${this.id}" was created with an Account as owner, which is not allowed.`
1823
+ });
1824
+ }
1825
+ }
1826
+ const node = this._raw.core.node;
1827
+ const profile = node.expectCoValueLoaded(this._raw.get("profile")).getCurrentContent();
1828
+ if (!profile.get("inbox")) {
1829
+ const inboxRoot = createInboxRoot(this);
1830
+ profile.set("inbox", inboxRoot.id);
1831
+ profile.set("inboxInvite", inboxRoot.inviteLink);
1832
+ }
1833
+ }
1834
+ // Placeholder method for subclasses to override
1835
+ migrate(creationProps) {
1836
+ creationProps;
1837
+ }
1838
+ /** @category Subscription & Loading */
1839
+ static load(id, options) {
1840
+ return loadCoValueWithoutMe(this, id, options);
1841
+ }
1842
+ static subscribe(id, ...args) {
1843
+ const { options, listener } = parseSubscribeRestArgs(args);
1844
+ return subscribeToCoValueWithoutMe(this, id, options, listener);
1845
+ }
1846
+ /** @category Subscription & Loading */
1847
+ ensureLoaded(options) {
1848
+ return ensureCoValueLoaded(this, options);
1849
+ }
1850
+ subscribe(...args) {
1851
+ const { options, listener } = parseSubscribeRestArgs(args);
1852
+ return subscribeToExistingCoValue(this, options, listener);
1853
+ }
1854
+ /**
1855
+ * Wait for the `Account` to be uploaded to the other peers.
1856
+ *
1857
+ * @category Subscription & Loading
1858
+ */
1859
+ waitForSync(options) {
1860
+ return this._raw.core.waitForSync(options);
1861
+ }
1862
+ /**
1863
+ * Wait for all the available `CoValues` to be uploaded to the other peers.
1864
+ *
1865
+ * @category Subscription & Loading
1866
+ */
1867
+ waitForAllCoValuesSync(options) {
1868
+ return this._raw.core.node.syncManager.waitForAllCoValuesSync(
1869
+ options?.timeout
1870
+ );
1871
+ }
1872
+ };
1873
+ _Account._schema = {
1874
+ profile: {
1875
+ ref: () => Profile,
1876
+ optional: false
1877
+ },
1878
+ root: {
1879
+ ref: () => RegisteredSchemas["CoMap"],
1880
+ optional: true
1881
+ }
1882
+ };
1883
+ var Account = _Account;
1884
+ var AccountAndGroupProxyHandler = {
1885
+ get(target, key, receiver) {
1886
+ if (key === "profile" || key === "root") {
1887
+ const id = target._raw.get(key);
1888
+ if (id) {
1889
+ return accessChildByKey(target, id, key);
1890
+ } else {
1891
+ return void 0;
1892
+ }
1893
+ } else {
1894
+ return Reflect.get(target, key, receiver);
1895
+ }
1896
+ },
1897
+ set(target, key, value, receiver) {
1898
+ if ((key === "profile" || key === "root") && typeof value === "object" && SchemaInit in value) {
1899
+ target.constructor._schema ||= {};
1900
+ target.constructor._schema[key] = value[SchemaInit];
1901
+ return true;
1902
+ } else if (key === "profile") {
1903
+ if (value) {
1904
+ target._raw.set(
1905
+ "profile",
1906
+ value.id,
1907
+ "trusting"
1908
+ );
1909
+ }
1910
+ return true;
1911
+ } else if (key === "root") {
1912
+ if (value) {
1913
+ target._raw.set("root", value.id);
1914
+ }
1915
+ return true;
1916
+ } else {
1917
+ return Reflect.set(target, key, value, receiver);
1918
+ }
1919
+ },
1920
+ defineProperty(target, key, descriptor) {
1921
+ if ((key === "profile" || key === "root") && typeof descriptor.value === "object" && SchemaInit in descriptor.value) {
1922
+ target.constructor._schema ||= {};
1923
+ target.constructor._schema[key] = descriptor.value[SchemaInit];
1924
+ return true;
1925
+ } else {
1926
+ return Reflect.defineProperty(target, key, descriptor);
1927
+ }
1928
+ }
1929
+ };
1930
+ function isControlledAccount(account) {
1931
+ return account.isLocalNodeOwner;
1932
+ }
1933
+ RegisteredSchemas["Account"] = Account;
1934
+
1935
+ // src/tools/coValues/group.ts
1936
+ var _Group = class _Group extends CoValueBase {
1937
+ get _schema() {
1938
+ return this.constructor._schema;
1939
+ }
1940
+ get _refs() {
1941
+ const profileID = this._raw.get("profile");
1942
+ const rootID = this._raw.get("root");
1943
+ return {
1944
+ profile: profileID ? new Ref(
1945
+ profileID,
1946
+ this._loadedAs,
1947
+ this._schema.profile,
1948
+ this
1949
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1950
+ ) : void 0,
1951
+ root: rootID ? new Ref(
1952
+ rootID,
1953
+ this._loadedAs,
1954
+ this._schema.root,
1955
+ this
1956
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1957
+ ) : void 0
1958
+ };
1959
+ }
1960
+ /** @deprecated Don't use constructor directly, use .create */
1961
+ constructor(options) {
1962
+ super();
1963
+ let raw;
1964
+ if (options && "fromRaw" in options) {
1965
+ raw = options.fromRaw;
1966
+ } else {
1967
+ const initOwner = options.owner;
1968
+ if (!initOwner) throw new Error("No owner provided");
1969
+ if (initOwner._type === "Account" && isControlledAccount(initOwner)) {
1970
+ const rawOwner = initOwner._raw;
1971
+ raw = rawOwner.core.node.createGroup();
1972
+ } else {
1973
+ throw new Error("Can only construct group as a controlled account");
1974
+ }
1975
+ }
1976
+ Object.defineProperties(this, {
1977
+ id: {
1978
+ value: raw.id,
1979
+ enumerable: false
1980
+ },
1981
+ _raw: { value: raw, enumerable: false }
1982
+ });
1983
+ return new Proxy(this, AccountAndGroupProxyHandler);
1984
+ }
1985
+ static create(options) {
1986
+ return new this(parseGroupCreateOptions(options));
1987
+ }
1988
+ myRole() {
1989
+ return this._raw.myRole();
1990
+ }
1991
+ addMember(member, role) {
1992
+ if (member !== "everyone" && member._type === "Group") {
1993
+ if (role === "writeOnly")
1994
+ throw new Error("Cannot add group as member with write-only role");
1995
+ this._raw.extend(member._raw, role);
1996
+ } else if (role !== void 0 && role !== "inherit") {
1997
+ this._raw.addMember(member === "everyone" ? member : member._raw, role);
1998
+ }
1999
+ }
2000
+ removeMember(member) {
2001
+ if (member !== "everyone" && member._type === "Group") {
2002
+ return this._raw.revokeExtend(member._raw);
2003
+ } else {
2004
+ return this._raw.removeMember(
2005
+ member === "everyone" ? member : member._raw
2006
+ );
2007
+ }
2008
+ }
2009
+ get members() {
2010
+ const members = [];
2011
+ const refEncodedAccountSchema = {
2012
+ ref: () => Account,
2013
+ optional: false
2014
+ };
2015
+ for (const accountID of this._raw.getAllMemberKeysSet()) {
2016
+ if (!isAccountID(accountID)) continue;
2017
+ const role = this._raw.roleOf(accountID);
2018
+ if (role === "admin" || role === "writer" || role === "reader" || role === "writeOnly") {
2019
+ const ref2 = new Ref(
2020
+ accountID,
2021
+ this._loadedAs,
2022
+ refEncodedAccountSchema,
2023
+ this
2024
+ );
2025
+ const group = this;
2026
+ members.push({
2027
+ id: accountID,
2028
+ role,
2029
+ ref: ref2,
2030
+ get account() {
2031
+ return accessChildById(group, accountID, refEncodedAccountSchema);
2032
+ }
2033
+ });
2034
+ }
2035
+ }
2036
+ return members;
2037
+ }
2038
+ getRoleOf(member) {
2039
+ if (member === "me") {
2040
+ return this._raw.roleOf(
2041
+ activeAccountContext.get().id
2042
+ );
2043
+ }
2044
+ return this._raw.roleOf(
2045
+ member === "everyone" ? member : member
2046
+ );
2047
+ }
2048
+ /**
2049
+ * Make the group public, so that everyone can read it.
2050
+ * Alias for `addMember("everyone", role)`.
2051
+ *
2052
+ * @param role - Optional: the role to grant to everyone. Defaults to "reader".
2053
+ * @returns The group itself.
2054
+ */
2055
+ makePublic(role = "reader") {
2056
+ this.addMember("everyone", role);
2057
+ return this;
2058
+ }
2059
+ getParentGroups() {
2060
+ return this._raw.getParentGroups().map((group) => _Group.fromRaw(group));
2061
+ }
2062
+ /** @category Identity & Permissions
2063
+ * Gives members of a parent group membership in this group.
2064
+ * @deprecated Use `addMember` instead.
2065
+ * @param parent The group that will gain access to this group.
2066
+ * @param roleMapping The role all members of the parent group should have in this group.
2067
+ * @returns This group.
2068
+ */
2069
+ extend(parent, roleMapping) {
2070
+ this._raw.extend(parent._raw, roleMapping);
2071
+ return this;
2072
+ }
2073
+ /** @category Identity & Permissions
2074
+ * Revokes membership from members a parent group.
2075
+ * @deprecated Use `removeMember` instead.
2076
+ * @param parent The group that will lose access to this group.
2077
+ * @returns This group.
2078
+ */
2079
+ async revokeExtend(parent) {
2080
+ await this._raw.revokeExtend(parent._raw);
2081
+ return this;
2082
+ }
2083
+ /** @category Subscription & Loading */
2084
+ static load(id, options) {
2085
+ return loadCoValueWithoutMe(this, id, options);
2086
+ }
2087
+ static subscribe(id, ...args) {
2088
+ const { options, listener } = parseSubscribeRestArgs(args);
2089
+ return subscribeToCoValueWithoutMe(this, id, options, listener);
2090
+ }
2091
+ /** @category Subscription & Loading */
2092
+ ensureLoaded(options) {
2093
+ return ensureCoValueLoaded(this, options);
2094
+ }
2095
+ subscribe(...args) {
2096
+ const { options, listener } = parseSubscribeRestArgs(args);
2097
+ return subscribeToExistingCoValue(this, options, listener);
2098
+ }
2099
+ /**
2100
+ * Wait for the `Group` to be uploaded to the other peers.
2101
+ *
2102
+ * @category Subscription & Loading
2103
+ */
2104
+ waitForSync(options) {
2105
+ return this._raw.core.waitForSync(options);
2106
+ }
2107
+ };
2108
+ _Group.prototype._type = "Group";
2109
+ _Group._schema = {
2110
+ profile: "json",
2111
+ root: "json"
2112
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2113
+ };
2114
+ Object.defineProperty(_Group.prototype, "_schema", {
2115
+ get: () => _Group._schema
2116
+ });
2117
+ var Group = _Group;
2118
+ RegisteredSchemas["Group"] = Group;
2119
+ function isAccountID(id) {
2120
+ return id.startsWith("co_");
2121
+ }
2122
+
2123
+ // src/tools/coValues/profile.ts
2124
+ var Profile = class extends CoMap {
2125
+ constructor() {
2126
+ super(...arguments);
2127
+ this.name = coField.string;
2128
+ this.inbox = coField.optional.string;
2129
+ this.inboxInvite = coField.optional.string;
2130
+ }
2131
+ /**
2132
+ * Creates a new profile with the given initial values and owner.
2133
+ *
2134
+ * The owner (a Group) determines access rights to the Profile.
2135
+ *
2136
+ * @category Creation
2137
+ */
2138
+ static create(init, options) {
2139
+ const owner = options !== void 0 && "owner" in options ? options.owner : options;
2140
+ if (owner?._type === "Account") {
2141
+ throw new Error("Profiles should be owned by a group");
2142
+ }
2143
+ return super.create(init, options);
2144
+ }
2145
+ };
2146
+
2147
+ // src/tools/coValues/inbox.ts
2148
+ import { RawAccount as RawAccount4 } from "cojson";
2149
+ function createInboxRoot(account) {
2150
+ if (!account.isLocalNodeOwner) {
2151
+ throw new Error("Account is not controlled");
2152
+ }
2153
+ const rawAccount = account._raw;
2154
+ const group = rawAccount.core.node.createGroup();
2155
+ const messagesFeed = group.createStream();
2156
+ const inboxRoot = rawAccount.createMap();
2157
+ const processedFeed = rawAccount.createStream();
2158
+ const failedFeed = rawAccount.createStream();
2159
+ const inviteLink = `${messagesFeed.id}/${group.createInvite("writeOnly")}`;
2160
+ inboxRoot.set("messages", messagesFeed.id);
2161
+ inboxRoot.set("processed", processedFeed.id);
2162
+ inboxRoot.set("failed", failedFeed.id);
2163
+ return {
2164
+ id: inboxRoot.id,
2165
+ inviteLink
2166
+ };
2167
+ }
2168
+ async function createInboxMessage(payload, inboxOwner) {
2169
+ const group = payload._raw.group;
2170
+ if (group instanceof RawAccount4) {
2171
+ throw new Error("Inbox messages should be owned by a group");
2172
+ }
2173
+ group.addMember(inboxOwner, "writer");
2174
+ const message = group.createMap({
2175
+ payload: payload.id,
2176
+ result: void 0,
2177
+ processed: false,
2178
+ error: void 0
2179
+ });
2180
+ await payload._raw.core.waitForSync();
2181
+ await message.core.waitForSync();
2182
+ return message;
2183
+ }
2184
+ var Inbox = class _Inbox {
2185
+ constructor(account, root, messages, processed, failed) {
2186
+ this.processing = /* @__PURE__ */ new Set();
2187
+ this.account = account;
2188
+ this.root = root;
2189
+ this.messages = messages;
2190
+ this.processed = processed;
2191
+ this.failed = failed;
2192
+ }
2193
+ subscribe(Schema, callback, options = {}) {
2194
+ const processed = /* @__PURE__ */ new Set();
2195
+ const failed = /* @__PURE__ */ new Map();
2196
+ const node = this.account._raw.core.node;
2197
+ this.processed.subscribe((stream) => {
2198
+ for (const items of Object.values(stream.items)) {
2199
+ for (const item of items) {
2200
+ processed.add(item.value);
2201
+ }
2202
+ }
2203
+ });
2204
+ const { account } = this;
2205
+ const { retries = 3 } = options;
2206
+ let failTimer = void 0;
2207
+ const clearFailTimer = () => {
2208
+ clearTimeout(failTimer);
2209
+ failTimer = void 0;
2210
+ };
2211
+ const handleNewMessages = (stream) => {
2212
+ clearFailTimer();
2213
+ for (const [sessionID, items] of Object.entries(stream.items)) {
2214
+ const accountID = getAccountIDfromSessionID(sessionID);
2215
+ if (!accountID) {
2216
+ console.warn("Received message from unknown account", sessionID);
2217
+ continue;
2218
+ }
2219
+ for (const item of items) {
2220
+ const txKey = `${sessionID}/${item.tx.txIndex}`;
2221
+ if (!processed.has(txKey) && !this.processing.has(txKey)) {
2222
+ this.processing.add(txKey);
2223
+ const id = item.value;
2224
+ node.load(id).then((message) => {
2225
+ if (message === "unavailable") {
2226
+ return Promise.reject(
2227
+ new Error("Unable to load inbox message " + id)
2228
+ );
2229
+ }
2230
+ return loadCoValue(
2231
+ anySchemaToCoSchema(Schema),
2232
+ message.get("payload"),
2233
+ {
2234
+ loadAs: account
2235
+ }
2236
+ );
2237
+ }).then((value) => {
2238
+ if (!value) {
2239
+ return Promise.reject(
2240
+ new Error("Unable to load inbox message " + id)
2241
+ );
2242
+ }
2243
+ return callback(value, accountID);
2244
+ }).then((result) => {
2245
+ const inboxMessage = node.expectCoValueLoaded(item.value).getCurrentContent();
2246
+ if (result) {
2247
+ inboxMessage.set("result", result.id);
2248
+ }
2249
+ inboxMessage.set("processed", true);
2250
+ this.processed.push(txKey);
2251
+ this.processing.delete(txKey);
2252
+ }).catch((error) => {
2253
+ console.error("Error processing inbox message", error);
2254
+ this.processing.delete(txKey);
2255
+ const errors = failed.get(txKey) ?? [];
2256
+ const stringifiedError = String(error);
2257
+ errors.push(stringifiedError);
2258
+ let inboxMessage;
2259
+ try {
2260
+ inboxMessage = node.expectCoValueLoaded(item.value).getCurrentContent();
2261
+ inboxMessage.set("error", stringifiedError);
2262
+ } catch (error2) {
2263
+ }
2264
+ if (errors.length > retries) {
2265
+ inboxMessage?.set("processed", true);
2266
+ this.processed.push(txKey);
2267
+ this.failed.push({ errors, value: item.value });
2268
+ } else {
2269
+ failed.set(txKey, errors);
2270
+ if (!failTimer) {
2271
+ failTimer = setTimeout(
2272
+ () => handleNewMessages(stream),
2273
+ 100
2274
+ );
2275
+ }
2276
+ }
2277
+ });
2278
+ }
2279
+ }
2280
+ }
2281
+ };
2282
+ const unsubscribe = this.messages.subscribe(handleNewMessages);
2283
+ return () => {
2284
+ unsubscribe();
2285
+ clearFailTimer();
2286
+ };
2287
+ }
2288
+ static async load(account) {
2289
+ const profile = account.profile;
2290
+ if (!profile) {
2291
+ throw new Error("Account profile should already be loaded");
2292
+ }
2293
+ if (!profile.inbox) {
2294
+ throw new Error("The account has not set up their inbox");
2295
+ }
2296
+ const node = account._raw.core.node;
2297
+ const root = await node.load(profile.inbox);
2298
+ if (root === "unavailable") {
2299
+ throw new Error("Inbox not found");
2300
+ }
2301
+ const [messages, processed, failed] = await Promise.all([
2302
+ node.load(root.get("messages")),
2303
+ node.load(root.get("processed")),
2304
+ node.load(root.get("failed"))
2305
+ ]);
2306
+ if (messages === "unavailable" || processed === "unavailable" || failed === "unavailable") {
2307
+ throw new Error("Inbox not found");
2308
+ }
2309
+ return new _Inbox(account, root, messages, processed, failed);
2310
+ }
2311
+ };
2312
+ var InboxSender = class _InboxSender {
2313
+ constructor(currentAccount, owner, messages) {
2314
+ this.currentAccount = currentAccount;
2315
+ this.owner = owner;
2316
+ this.messages = messages;
2317
+ }
2318
+ getOwnerAccount() {
2319
+ return this.owner;
2320
+ }
2321
+ async sendMessage(message) {
2322
+ const inboxMessage = await createInboxMessage(message, this.owner);
2323
+ this.messages.push(inboxMessage.id);
2324
+ return new Promise((resolve, reject) => {
2325
+ inboxMessage.subscribe((message2) => {
2326
+ if (message2.get("processed")) {
2327
+ const error = message2.get("error");
2328
+ if (error) {
2329
+ reject(new Error(error));
2330
+ } else {
2331
+ resolve(
2332
+ message2.get("result")
2333
+ );
2334
+ }
2335
+ }
2336
+ });
2337
+ });
2338
+ }
2339
+ static async load(inboxOwnerID, currentAccount) {
2340
+ currentAccount ||= activeAccountContext.get();
2341
+ const node = currentAccount._raw.core.node;
2342
+ const inboxOwnerRaw = await node.load(
2343
+ inboxOwnerID
2344
+ );
2345
+ if (inboxOwnerRaw === "unavailable") {
2346
+ throw new Error("Failed to load the inbox owner");
2347
+ }
2348
+ const inboxOwnerProfileRaw = await node.load(inboxOwnerRaw.get("profile"));
2349
+ if (inboxOwnerProfileRaw === "unavailable") {
2350
+ throw new Error("Failed to load the inbox owner profile");
2351
+ }
2352
+ if (inboxOwnerProfileRaw.group.roleOf(currentAccount._raw.id) !== "reader" && inboxOwnerProfileRaw.group.roleOf(currentAccount._raw.id) !== "writer" && inboxOwnerProfileRaw.group.roleOf(currentAccount._raw.id) !== "admin") {
2353
+ throw new Error(
2354
+ "Insufficient permissions to access the inbox, make sure its user profile is publicly readable."
2355
+ );
2356
+ }
2357
+ const inboxInvite = inboxOwnerProfileRaw.get("inboxInvite");
2358
+ if (!inboxInvite) {
2359
+ throw new Error("The user has not set up their inbox");
2360
+ }
2361
+ const id = await acceptInvite(inboxInvite, currentAccount);
2362
+ const messages = await node.load(id);
2363
+ if (messages === "unavailable") {
2364
+ throw new Error("Inbox not found");
2365
+ }
2366
+ return new _InboxSender(currentAccount, inboxOwnerRaw, messages);
2367
+ }
2368
+ };
2369
+ async function acceptInvite(invite, account) {
2370
+ account ||= activeAccountContext.get();
2371
+ const id = invite.slice(0, invite.indexOf("/"));
2372
+ const inviteSecret = invite.slice(invite.indexOf("/") + 1);
2373
+ if (!id?.startsWith("co_z") || !inviteSecret.startsWith("inviteSecret_")) {
2374
+ throw new Error("Invalid inbox ticket");
2375
+ }
2376
+ if (!account.isLocalNodeOwner) {
2377
+ throw new Error("Account is not controlled");
2378
+ }
2379
+ await account._raw.core.node.acceptInvite(id, inviteSecret);
2380
+ return id;
2381
+ }
2382
+ function getAccountIDfromSessionID(sessionID) {
2383
+ const until = sessionID.indexOf("_session");
2384
+ const accountID = sessionID.slice(0, until);
2385
+ if (accountID.startsWith("co_z")) {
2386
+ return accountID;
2387
+ }
2388
+ return;
2389
+ }
2390
+
2391
+ // src/tools/coValues/coPlainText.ts
2392
+ import {
2393
+ ControlledAccount as ControlledAccount4,
2394
+ RawAccount as RawAccount5,
2395
+ stringifyOpID
2396
+ } from "cojson";
2397
+ import { calcPatch as calcPatch2 } from "fast-myers-diff";
2398
+
2399
+ // src/tools/lib/cache.ts
2400
+ var weakMap = /* @__PURE__ */ new WeakMap();
2401
+ var coValuesCache = {
2402
+ get: (raw, compute) => {
2403
+ const cached = weakMap.get(raw);
2404
+ if (cached) {
2405
+ return cached;
2406
+ }
2407
+ const computed = compute();
2408
+ weakMap.set(raw, computed);
2409
+ return computed;
2410
+ }
2411
+ };
2412
+
2413
+ // src/tools/coValues/coPlainText.ts
2414
+ var CoPlainText = class extends String {
2415
+ get _owner() {
2416
+ return this._raw.group instanceof RawAccount5 ? Account.fromRaw(this._raw.group) : Group.fromRaw(this._raw.group);
2417
+ }
2418
+ get _loadedAs() {
2419
+ const agent = this._raw.core.node.getCurrentAgent();
2420
+ if (agent instanceof ControlledAccount4) {
2421
+ return coValuesCache.get(
2422
+ agent.account,
2423
+ () => anySchemaToCoSchema(RegisteredSchemas["Account"]).fromRaw(
2424
+ agent.account
2425
+ )
2426
+ );
2427
+ }
2428
+ return new AnonymousJazzAgent(this._raw.core.node);
2429
+ }
2430
+ /** @internal */
2431
+ constructor(options) {
2432
+ if (!options) {
2433
+ super("");
2434
+ return;
2435
+ }
2436
+ if ("fromRaw" in options) {
2437
+ super(options.fromRaw.toString());
2438
+ const raw = options.fromRaw;
2439
+ Object.defineProperties(this, {
2440
+ id: { value: raw.id, enumerable: false },
2441
+ _type: { value: "CoPlainText", enumerable: false },
2442
+ _raw: { value: raw, enumerable: false }
2443
+ });
2444
+ return;
2445
+ }
2446
+ if ("text" in options && "owner" in options) {
2447
+ super(options.text);
2448
+ const raw = options.owner._raw.createPlainText(options.text);
2449
+ Object.defineProperties(this, {
2450
+ id: { value: raw.id, enumerable: false },
2451
+ _type: { value: "CoPlainText", enumerable: false },
2452
+ _raw: { value: raw, enumerable: false }
2453
+ });
2454
+ return;
2455
+ }
2456
+ throw new Error("Invalid constructor arguments");
2457
+ }
2458
+ /**
2459
+ * Create a new `CoPlainText` with the given text and owner.
2460
+ *
2461
+ * The owner (a Group or Account) determines access rights to the CoPlainText.
2462
+ *
2463
+ * The CoPlainText will immediately be persisted and synced to connected peers.
2464
+ *
2465
+ * @example
2466
+ * ```ts
2467
+ * const text = CoPlainText.create("Hello, world!", { owner: me });
2468
+ * ```
2469
+ *
2470
+ * @category Creation
2471
+ */
2472
+ static create(text, options) {
2473
+ const { owner } = parseCoValueCreateOptions(options);
2474
+ return new this({ text, owner });
2475
+ }
2476
+ get length() {
2477
+ return this._raw.toString().length;
2478
+ }
2479
+ toString() {
2480
+ return this._raw.toString();
2481
+ }
2482
+ valueOf() {
2483
+ return this._raw.toString();
2484
+ }
2485
+ toJSON() {
2486
+ return this._raw.toString();
2487
+ }
2488
+ [inspect]() {
2489
+ return this.toJSON();
2490
+ }
2491
+ insertBefore(idx, text) {
2492
+ this._raw.insertBefore(idx, text);
2493
+ }
2494
+ insertAfter(idx, text) {
2495
+ this._raw.insertAfter(idx, text);
2496
+ }
2497
+ deleteRange(range) {
2498
+ this._raw.deleteRange(range);
2499
+ }
2500
+ posBefore(idx) {
2501
+ return this._raw.mapping.opIDbeforeIdx[idx];
2502
+ }
2503
+ posAfter(idx) {
2504
+ return this._raw.mapping.opIDafterIdx[idx];
2505
+ }
2506
+ idxBefore(pos) {
2507
+ return this._raw.mapping.idxBeforeOpID[stringifyOpID(pos)];
2508
+ }
2509
+ idxAfter(pos) {
2510
+ return this._raw.mapping.idxAfterOpID[stringifyOpID(pos)];
2511
+ }
2512
+ static fromRaw(raw) {
2513
+ return new this({ fromRaw: raw });
2514
+ }
2515
+ /**
2516
+ * Apply text, modifying the text in place. Calculates the diff and applies it to the CoValue.
2517
+ *
2518
+ * @category Mutation
2519
+ */
2520
+ applyDiff(other) {
2521
+ const current = this._raw.toString();
2522
+ const currentGraphemes = this._raw.toGraphemes(current);
2523
+ const otherGraphemes = this._raw.toGraphemes(other);
2524
+ const patches = [...calcPatch2(currentGraphemes, otherGraphemes)];
2525
+ for (const [from, to, insert] of patches.reverse()) {
2526
+ if (to > from) {
2527
+ this.deleteRange({ from, to });
2528
+ }
2529
+ if (insert.length > 0) {
2530
+ this.insertBefore(from, this._raw.fromGraphemes(insert));
2531
+ }
2532
+ }
2533
+ }
2534
+ /**
2535
+ * Load a `CoPlainText` with a given ID, as a given account.
2536
+ *
2537
+ * @category Subscription & Loading
2538
+ */
2539
+ static load(id, options) {
2540
+ return loadCoValueWithoutMe(this, id, options);
2541
+ }
2542
+ static subscribe(id, ...args) {
2543
+ const { options, listener } = parseSubscribeRestArgs(args);
2544
+ return subscribeToCoValueWithoutMe(this, id, options, listener);
2545
+ }
2546
+ /**
2547
+ * Given an already loaded `CoPlainText`, subscribe to updates to the `CoPlainText` and ensure that the specified fields are loaded to the specified depth.
2548
+ *
2549
+ * Works like `CoPlainText.subscribe()`, but you don't need to pass the ID or the account to load as again.
2550
+ *
2551
+ * Returns an unsubscribe function that you should call when you no longer need updates.
2552
+ *
2553
+ * @category Subscription & Loading
2554
+ **/
2555
+ subscribe(listener) {
2556
+ return subscribeToExistingCoValue(this, {}, listener);
2557
+ }
2558
+ /**
2559
+ * Allow CoPlainText to behave like a primitive string in most contexts (e.g.,
2560
+ * string concatenation, template literals, React rendering, etc.) by implementing
2561
+ * Symbol.toPrimitive. This eliminates the need to call .toString() explicitly.
2562
+ *
2563
+ * The 'hint' parameter indicates the preferred type of conversion:
2564
+ * - 'string': prefer string conversion
2565
+ * - 'number': prefer number conversion (attempt to parse the text as a number)
2566
+ * - 'default': usually treat as string
2567
+ */
2568
+ [Symbol.toPrimitive](hint) {
2569
+ if (hint === "number") {
2570
+ return Number(this._raw.toString());
2571
+ }
2572
+ return this._raw.toString();
2573
+ }
2574
+ };
2575
+
2576
+ // src/tools/coValues/coRichText.ts
2577
+ var CoRichText = class extends CoPlainText {
2578
+ };
2579
+
2580
+ // src/tools/coValues/schemaUnion.ts
2581
+ var SchemaUnion = class _SchemaUnion extends CoValueBase {
2582
+ /**
2583
+ * Create a new union type from a discriminator function.
2584
+ *
2585
+ * The discriminator function receives the raw data and should return the appropriate concrete class to use for that data.
2586
+ *
2587
+ * When loading a SchemaUnion, the correct subclass will be instantiated based on the discriminator.
2588
+ *
2589
+ * @param discriminator - Function that determines which concrete type to use
2590
+ * @returns A new class that can create/load instances of the union type
2591
+ *
2592
+ * @example
2593
+ * ```ts
2594
+ * const WidgetUnion = SchemaUnion.Of<BaseWidget>((raw) => {
2595
+ * switch (raw.get("type")) {
2596
+ * case "button": return ButtonWidget;
2597
+ * case "slider": return SliderWidget;
2598
+ * default: throw new Error("Unknown widget type");
2599
+ * }
2600
+ * });
2601
+ *
2602
+ * const widget = await loadCoValue(WidgetUnion, id, me, {});
2603
+ *
2604
+ * // You can narrow the returned instance to a subclass by using `instanceof`
2605
+ * if (widget instanceof ButtonWidget) {
2606
+ * console.log(widget.label);
2607
+ * } else if (widget instanceof SliderWidget) {
2608
+ * console.log(widget.min, widget.max);
2609
+ * }
2610
+ * ```
2611
+ *
2612
+ * @category Declaration
2613
+ **/
2614
+ static Of(discriminator) {
2615
+ return class SchemaUnionClass extends _SchemaUnion {
2616
+ static fromRaw(raw) {
2617
+ const ResolvedClass = discriminator(
2618
+ raw
2619
+ );
2620
+ return ResolvedClass.fromRaw(raw);
2621
+ }
2622
+ };
2623
+ }
2624
+ /**
2625
+ * Create an instance from raw data. This is called internally and should not be used directly.
2626
+ * Use {@link SchemaUnion.Of} to create a union type instead.
2627
+ *
2628
+ * @internal
2629
+ */
2630
+ // @ts-ignore
2631
+ static fromRaw(raw) {
2632
+ throw new Error("Not implemented");
2633
+ }
2634
+ };
2635
+
2636
+ // src/tools/implementation/anonymousJazzAgent.ts
2637
+ var AnonymousJazzAgent = class {
2638
+ constructor(node) {
2639
+ this.node = node;
2640
+ this._type = "Anonymous";
2641
+ }
2642
+ };
2643
+
2644
+ // src/tools/implementation/activeAccountContext.ts
2645
+ var ActiveAccountContext = class {
2646
+ constructor() {
2647
+ this.activeAccount = null;
2648
+ this.guestMode = false;
2649
+ }
2650
+ set(account) {
2651
+ this.activeAccount = account;
2652
+ this.guestMode = false;
2653
+ }
2654
+ setGuestMode() {
2655
+ this.activeAccount = null;
2656
+ this.guestMode = true;
2657
+ }
2658
+ maybeGet() {
2659
+ return this.activeAccount;
2660
+ }
2661
+ get() {
2662
+ if (!this.activeAccount) {
2663
+ if (this.guestMode) {
2664
+ throw new Error(
2665
+ "Something that expects a full active account was called in guest mode."
2666
+ );
2667
+ }
2668
+ throw new Error("No active account");
2669
+ }
2670
+ return this.activeAccount;
2671
+ }
2672
+ };
2673
+ var activeAccountContext = new ActiveAccountContext();
2674
+
2675
+ // src/tools/implementation/refs.ts
2676
+ var Ref = class {
2677
+ constructor(id, controlledAccount, schema, parent) {
2678
+ this.id = id;
2679
+ this.controlledAccount = controlledAccount;
2680
+ this.schema = schema;
2681
+ this.parent = parent;
2682
+ if (!isRefEncoded(schema)) {
2683
+ throw new Error("Ref must be constructed with a ref schema");
2684
+ }
2685
+ }
2686
+ async load() {
2687
+ const subscriptionScope = getSubscriptionScope(this.parent);
2688
+ subscriptionScope.subscribeToId(this.id, this.schema);
2689
+ const node = subscriptionScope.childNodes.get(this.id);
2690
+ if (!node) {
2691
+ return null;
2692
+ }
2693
+ const value = node.value;
2694
+ if (value?.type === "loaded") {
2695
+ return value.value;
2696
+ } else {
2697
+ return new Promise((resolve) => {
2698
+ const unsubscribe = node.subscribe((value2) => {
2699
+ if (value2?.type === "loaded") {
2700
+ unsubscribe();
2701
+ resolve(value2.value);
2702
+ } else if (value2?.type === "unavailable") {
2703
+ unsubscribe();
2704
+ resolve(null);
2705
+ } else if (value2?.type === "unauthorized") {
2706
+ unsubscribe();
2707
+ resolve(null);
2708
+ }
2709
+ });
2710
+ });
2711
+ }
2712
+ }
2713
+ get value() {
2714
+ return accessChildById(this.parent, this.id, this.schema);
2715
+ }
2716
+ };
2717
+ function makeRefs(parent, getIdForKey, getKeysWithIds, controlledAccount, refSchemaForKey) {
2718
+ const refs = {};
2719
+ return new Proxy(refs, {
2720
+ get(_target, key) {
2721
+ if (key === Symbol.iterator) {
2722
+ return function* () {
2723
+ for (const key2 of getKeysWithIds()) {
2724
+ yield new Ref(
2725
+ getIdForKey(key2),
2726
+ controlledAccount,
2727
+ refSchemaForKey(key2),
2728
+ parent
2729
+ );
2730
+ }
2731
+ };
2732
+ }
2733
+ if (typeof key === "symbol") return void 0;
2734
+ if (key === "length") {
2735
+ return getKeysWithIds().length;
2736
+ }
2737
+ const id = getIdForKey(key);
2738
+ if (!id) return void 0;
2739
+ return new Ref(
2740
+ id,
2741
+ controlledAccount,
2742
+ refSchemaForKey(key),
2743
+ parent
2744
+ );
2745
+ },
2746
+ ownKeys() {
2747
+ return getKeysWithIds().map((key) => key.toString());
2748
+ },
2749
+ getOwnPropertyDescriptor(target, key) {
2750
+ const id = getIdForKey(key);
2751
+ if (id) {
2752
+ return {
2753
+ enumerable: true,
2754
+ configurable: true,
2755
+ writable: true
2756
+ };
2757
+ } else {
2758
+ return Reflect.getOwnPropertyDescriptor(target, key);
2759
+ }
2760
+ }
2761
+ });
2762
+ }
2763
+
2764
+ // src/tools/implementation/schema.ts
2765
+ var Encoders = {
2766
+ Date: {
2767
+ encode: (value) => value.toISOString(),
2768
+ decode: (value) => new Date(value)
2769
+ },
2770
+ OptionalDate: {
2771
+ encode: (value) => value?.toISOString() || null,
2772
+ decode: (value) => value === null ? void 0 : new Date(value)
2773
+ }
2774
+ };
2775
+ var optional2 = {
2776
+ ref: optionalRef,
2777
+ json() {
2778
+ return { [SchemaInit]: "json" };
2779
+ },
2780
+ encoded(arg) {
2781
+ return { [SchemaInit]: { encoded: arg } };
2782
+ },
2783
+ string: {
2784
+ [SchemaInit]: "json"
2785
+ },
2786
+ number: {
2787
+ [SchemaInit]: "json"
2788
+ },
2789
+ boolean: {
2790
+ [SchemaInit]: "json"
2791
+ },
2792
+ null: {
2793
+ [SchemaInit]: "json"
2794
+ },
2795
+ Date: {
2796
+ [SchemaInit]: { encoded: Encoders.OptionalDate }
2797
+ },
2798
+ literal(..._lit) {
2799
+ return { [SchemaInit]: "json" };
2800
+ }
2801
+ };
2802
+ var coField = {
2803
+ string: {
2804
+ [SchemaInit]: "json"
2805
+ },
2806
+ number: {
2807
+ [SchemaInit]: "json"
2808
+ },
2809
+ boolean: {
2810
+ [SchemaInit]: "json"
2811
+ },
2812
+ null: {
2813
+ [SchemaInit]: "json"
2814
+ },
2815
+ Date: {
2816
+ [SchemaInit]: { encoded: Encoders.Date }
2817
+ },
2818
+ literal(..._lit) {
2819
+ return { [SchemaInit]: "json" };
2820
+ },
2821
+ json() {
2822
+ return { [SchemaInit]: "json" };
2823
+ },
2824
+ encoded(arg) {
2825
+ return { [SchemaInit]: { encoded: arg } };
2826
+ },
2827
+ ref,
2828
+ items: ItemsSym,
2829
+ optional: optional2
2830
+ };
2831
+ function optionalRef(arg) {
2832
+ return ref(arg, { optional: true });
2833
+ }
2834
+ function ref(arg, options) {
2835
+ return {
2836
+ [SchemaInit]: {
2837
+ ref: arg,
2838
+ optional: options?.optional || false
2839
+ }
2840
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2841
+ };
2842
+ }
2843
+ function isRefEncoded(schema) {
2844
+ return typeof schema === "object" && "ref" in schema && "optional" in schema && typeof schema.ref === "function";
2845
+ }
2846
+ function instantiateRefEncoded(schema, raw) {
2847
+ return isCoValueClass(schema.ref) ? schema.ref.fromRaw(raw) : schema.ref(
2848
+ raw
2849
+ ).fromRaw(raw);
2850
+ }
2851
+
2852
+ // src/tools/lib/migration.ts
2853
+ function applyCoValueMigrations(instance) {
2854
+ const node = instance._raw.core.node;
2855
+ const migratedCoValues = node._migratedCoValues ??= /* @__PURE__ */ new Set();
2856
+ if ("migrate" in instance && typeof instance.migrate === "function" && instance._type !== "Account" && !migratedCoValues.has(instance.id)) {
2857
+ migratedCoValues.add(instance.id);
2858
+ const result = instance.migrate?.(instance);
2859
+ if (result && "then" in result) {
2860
+ throw new Error("Migration function cannot be async");
2861
+ }
2862
+ }
2863
+ }
2864
+
2865
+ // src/tools/subscribe/CoValueCoreSubscription.ts
2866
+ var CoValueCoreSubscription = class {
2867
+ constructor(node, id, listener, skipRetry) {
2868
+ this.node = node;
2869
+ this.id = id;
2870
+ this.listener = listener;
2871
+ this.skipRetry = skipRetry;
2872
+ this._unsubscribe = () => {
2873
+ };
2874
+ this.unsubscribed = false;
2875
+ const entry = this.node.getCoValue(this.id);
2876
+ if (entry?.isAvailable()) {
2877
+ this.subscribe(entry.getCurrentContent());
2878
+ } else {
2879
+ this.node.loadCoValueCore(this.id, void 0, skipRetry).then((value) => {
2880
+ if (this.unsubscribed) return;
2881
+ if (value.isAvailable()) {
2882
+ this.subscribe(value.getCurrentContent());
2883
+ } else {
2884
+ this.subscribeToState();
2885
+ this.listener("unavailable");
2886
+ }
2887
+ });
2888
+ }
2889
+ }
2890
+ subscribeToState() {
2891
+ const entry = this.node.getCoValue(this.id);
2892
+ const handleStateChange = (core, unsubFromStateChange2) => {
2893
+ if (this.unsubscribed) {
2894
+ unsubFromStateChange2();
2895
+ return;
2896
+ }
2897
+ if (core.isAvailable()) {
2898
+ this.subscribe(core.getCurrentContent());
2899
+ unsubFromStateChange2();
2900
+ }
2901
+ };
2902
+ const unsubFromStateChange = entry.subscribe(handleStateChange);
2903
+ this._unsubscribe = () => {
2904
+ unsubFromStateChange();
2905
+ };
2906
+ }
2907
+ subscribe(value) {
2908
+ if (this.unsubscribed) return;
2909
+ this._unsubscribe = value.subscribe((value2) => {
2910
+ this.listener(value2);
2911
+ });
2912
+ this.listener(value);
2913
+ }
2914
+ unsubscribe() {
2915
+ if (this.unsubscribed) return;
2916
+ this.unsubscribed = true;
2917
+ this._unsubscribe();
2918
+ }
2919
+ };
2920
+
2921
+ // src/tools/subscribe/JazzError.ts
2922
+ var JazzError = class _JazzError {
2923
+ constructor(id, type, issues) {
2924
+ this.id = id;
2925
+ this.type = type;
2926
+ this.issues = issues;
2927
+ }
2928
+ toString() {
2929
+ return this.issues.map((issue) => {
2930
+ let message = `${issue.message}`;
2931
+ if (this.id) {
2932
+ message += ` from ${this.id}`;
2933
+ }
2934
+ if (issue.path.length > 0) {
2935
+ message += ` on path ${issue.path.join(".")}`;
2936
+ }
2937
+ return message;
2938
+ }).join("\n");
2939
+ }
2940
+ prependPath(item) {
2941
+ if (this.issues.length === 0) {
2942
+ return this;
2943
+ }
2944
+ const issues = this.issues.map((issue) => {
2945
+ return {
2946
+ ...issue,
2947
+ path: [item].concat(issue.path)
2948
+ };
2949
+ });
2950
+ return new _JazzError(this.id, this.type, issues);
2951
+ }
2952
+ };
2953
+
2954
+ // src/tools/subscribe/utils.ts
2955
+ import { RawAccount as RawAccount6 } from "cojson";
2956
+ function getOwnerFromRawValue(raw) {
2957
+ const owner = raw.group;
2958
+ return coValuesCache.get(
2959
+ owner,
2960
+ () => owner instanceof RawAccount6 ? anySchemaToCoSchema(RegisteredSchemas["Account"]).fromRaw(owner) : RegisteredSchemas["Group"].fromRaw(owner)
2961
+ );
2962
+ }
2963
+ function createCoValue(ref2, raw, subscriptionScope) {
2964
+ const freshValueInstance = instantiateRefEncoded(ref2, raw);
2965
+ Object.defineProperty(freshValueInstance, "_subscriptionScope", {
2966
+ value: subscriptionScope,
2967
+ writable: false,
2968
+ enumerable: false,
2969
+ configurable: false
2970
+ });
2971
+ return {
2972
+ type: "loaded",
2973
+ value: freshValueInstance,
2974
+ id: subscriptionScope.id
2975
+ };
2976
+ }
2977
+
2978
+ // src/tools/subscribe/SubscriptionScope.ts
2979
+ var SubscriptionScope = class _SubscriptionScope {
2980
+ constructor(node, resolve, id, schema, skipRetry) {
2981
+ this.node = node;
2982
+ this.id = id;
2983
+ this.schema = schema;
2984
+ this.skipRetry = skipRetry;
2985
+ this.childNodes = /* @__PURE__ */ new Map();
2986
+ this.childValues = /* @__PURE__ */ new Map();
2987
+ this.childErrors = /* @__PURE__ */ new Map();
2988
+ this.validationErrors = /* @__PURE__ */ new Map();
2989
+ this.dirty = false;
2990
+ this.idsSubscribed = /* @__PURE__ */ new Set();
2991
+ this.autoloaded = /* @__PURE__ */ new Set();
2992
+ this.autoloadedKeys = /* @__PURE__ */ new Set();
2993
+ this.skipInvalidKeys = /* @__PURE__ */ new Set();
2994
+ this.totalValidTransactions = 0;
2995
+ this.migrated = false;
2996
+ this.migrating = false;
2997
+ this.silenceUpdates = false;
2998
+ this.handleChildUpdate = (id, value, key) => {
2999
+ if (value.type === "unloaded") {
3000
+ return;
3001
+ }
3002
+ this.childValues.set(id, value);
3003
+ if (value.type === "unavailable" || value.type === "unauthorized") {
3004
+ this.childErrors.set(id, value.prependPath(key ?? id));
3005
+ this.errorFromChildren = this.computeChildErrors();
3006
+ } else if (this.errorFromChildren && this.childErrors.has(id)) {
3007
+ this.childErrors.delete(id);
3008
+ this.errorFromChildren = this.computeChildErrors();
3009
+ }
3010
+ if (this.shouldSendUpdates()) {
3011
+ if (this.value.type === "loaded") {
3012
+ this.updateValue(
3013
+ createCoValue(this.schema, this.value.value._raw, this)
3014
+ );
3015
+ }
3016
+ }
3017
+ this.triggerUpdate();
3018
+ };
3019
+ this.subscribers = /* @__PURE__ */ new Set();
3020
+ this.resolve = resolve;
3021
+ this.value = { type: "unloaded", id };
3022
+ let lastUpdate;
3023
+ this.subscription = new CoValueCoreSubscription(
3024
+ node,
3025
+ id,
3026
+ (value) => {
3027
+ lastUpdate = value;
3028
+ if (skipRetry && value === "unavailable") {
3029
+ this.handleUpdate(value);
3030
+ this.destroy();
3031
+ return;
3032
+ }
3033
+ if (!this.migrated && value !== "unavailable") {
3034
+ if (this.migrating) {
3035
+ return;
3036
+ }
3037
+ this.migrating = true;
3038
+ applyCoValueMigrations(instantiateRefEncoded(this.schema, value));
3039
+ this.migrated = true;
3040
+ this.handleUpdate(lastUpdate);
3041
+ return;
3042
+ }
3043
+ this.handleUpdate(value);
3044
+ },
3045
+ skipRetry
3046
+ );
3047
+ }
3048
+ updateValue(value) {
3049
+ this.value = value;
3050
+ this.dirty = true;
3051
+ }
3052
+ handleUpdate(update) {
3053
+ if (update === "unavailable") {
3054
+ if (this.value.type === "unloaded") {
3055
+ this.updateValue(
3056
+ new JazzError(this.id, "unavailable", [
3057
+ {
3058
+ code: "unavailable",
3059
+ message: "The value is unavailable",
3060
+ params: {
3061
+ id: this.id
3062
+ },
3063
+ path: []
3064
+ }
3065
+ ])
3066
+ );
3067
+ }
3068
+ this.triggerUpdate();
3069
+ return;
3070
+ }
3071
+ const ruleset = update.core.verified.header.ruleset;
3072
+ const hasAccess = ruleset.type !== "ownedByGroup" || getOwnerFromRawValue(update).myRole() !== void 0;
3073
+ if (!hasAccess) {
3074
+ if (this.value.type !== "unauthorized") {
3075
+ this.updateValue(
3076
+ new JazzError(this.id, "unauthorized", [
3077
+ {
3078
+ code: "unauthorized",
3079
+ message: "The current user is not authorized to access this value",
3080
+ params: {
3081
+ id: this.id
3082
+ },
3083
+ path: []
3084
+ }
3085
+ ])
3086
+ );
3087
+ this.triggerUpdate();
3088
+ }
3089
+ return;
3090
+ }
3091
+ this.silenceUpdates = true;
3092
+ if (this.value.type !== "loaded") {
3093
+ this.updateValue(createCoValue(this.schema, update, this));
3094
+ this.loadChildren();
3095
+ } else {
3096
+ const hasChanged = update.totalValidTransactions !== this.totalValidTransactions || // Checking the identity of the _raw value makes us cover the cases where the group
3097
+ // has been updated and the coValues that don't update the totalValidTransactions value (e.g. FileStream)
3098
+ this.value.value._raw !== update;
3099
+ if (this.loadChildren()) {
3100
+ this.updateValue(createCoValue(this.schema, update, this));
3101
+ } else if (hasChanged) {
3102
+ this.updateValue(createCoValue(this.schema, update, this));
3103
+ }
3104
+ }
3105
+ this.totalValidTransactions = update.totalValidTransactions;
3106
+ this.silenceUpdates = false;
3107
+ this.triggerUpdate();
3108
+ }
3109
+ computeChildErrors() {
3110
+ let issues = [];
3111
+ let errorType = "unavailable";
3112
+ if (this.childErrors.size === 0 && this.validationErrors.size === 0) {
3113
+ return void 0;
3114
+ }
3115
+ for (const [key, value] of this.childErrors.entries()) {
3116
+ if (this.autoloaded.has(key)) {
3117
+ continue;
3118
+ }
3119
+ if (this.skipInvalidKeys.has(key)) {
3120
+ continue;
3121
+ }
3122
+ errorType = value.type;
3123
+ if (value.issues) {
3124
+ issues.push(...value.issues);
3125
+ }
3126
+ }
3127
+ for (const [key, value] of this.validationErrors.entries()) {
3128
+ if (this.skipInvalidKeys.has(key)) {
3129
+ continue;
3130
+ }
3131
+ errorType = value.type;
3132
+ if (value.issues) {
3133
+ issues.push(...value.issues);
3134
+ }
3135
+ }
3136
+ if (issues.length) {
3137
+ return new JazzError(this.id, errorType, issues);
3138
+ }
3139
+ return void 0;
3140
+ }
3141
+ shouldSendUpdates() {
3142
+ if (this.value.type === "unloaded") return false;
3143
+ if (this.value.type !== "loaded") return true;
3144
+ for (const value of this.childValues.values()) {
3145
+ if (value.type === "unloaded" && !this.autoloaded.has(value.id)) {
3146
+ return false;
3147
+ }
3148
+ }
3149
+ return true;
3150
+ }
3151
+ getCurrentValue() {
3152
+ if (this.value.type === "unauthorized" || this.value.type === "unavailable") {
3153
+ console.error(this.value.toString());
3154
+ return null;
3155
+ }
3156
+ if (!this.shouldSendUpdates()) {
3157
+ return void 0;
3158
+ }
3159
+ if (this.errorFromChildren) {
3160
+ console.error(this.errorFromChildren.toString());
3161
+ return null;
3162
+ }
3163
+ if (this.value.type === "loaded") {
3164
+ return this.value.value;
3165
+ }
3166
+ return void 0;
3167
+ }
3168
+ triggerUpdate() {
3169
+ if (!this.shouldSendUpdates()) return;
3170
+ if (!this.dirty) return;
3171
+ if (this.subscribers.size === 0) return;
3172
+ if (this.silenceUpdates) return;
3173
+ const error = this.errorFromChildren;
3174
+ const value = this.value;
3175
+ if (error) {
3176
+ this.subscribers.forEach((listener) => listener(error));
3177
+ } else if (value.type !== "unloaded") {
3178
+ this.subscribers.forEach((listener) => listener(value));
3179
+ }
3180
+ this.dirty = false;
3181
+ }
3182
+ subscribe(listener) {
3183
+ this.subscribers.add(listener);
3184
+ return () => {
3185
+ this.subscribers.delete(listener);
3186
+ };
3187
+ }
3188
+ setListener(listener) {
3189
+ this.subscribers.add(listener);
3190
+ this.triggerUpdate();
3191
+ }
3192
+ subscribeToKey(key) {
3193
+ if (this.resolve === true || !this.resolve) {
3194
+ this.resolve = {};
3195
+ }
3196
+ if (this.resolve.$each || key in this.resolve) {
3197
+ return;
3198
+ }
3199
+ const resolve = this.resolve;
3200
+ resolve[key] = true;
3201
+ this.autoloadedKeys.add(key);
3202
+ if (this.value.type !== "loaded") {
3203
+ return;
3204
+ }
3205
+ const value = this.value.value;
3206
+ this.silenceUpdates = true;
3207
+ if (value._type === "CoMap" || value._type === "Account") {
3208
+ const map = value;
3209
+ this.loadCoMapKey(map, key, true);
3210
+ } else if (value._type === "CoList") {
3211
+ const list = value;
3212
+ this.loadCoListKey(list, key, true);
3213
+ }
3214
+ this.silenceUpdates = false;
3215
+ }
3216
+ subscribeToId(id, descriptor) {
3217
+ if (this.idsSubscribed.has(id) || this.childValues.has(id)) {
3218
+ return;
3219
+ }
3220
+ this.idsSubscribed.add(id);
3221
+ this.autoloaded.add(id);
3222
+ this.silenceUpdates = true;
3223
+ this.childValues.set(id, { type: "unloaded", id });
3224
+ const child = new _SubscriptionScope(
3225
+ this.node,
3226
+ true,
3227
+ id,
3228
+ descriptor
3229
+ );
3230
+ this.childNodes.set(id, child);
3231
+ child.setListener((value) => this.handleChildUpdate(id, value));
3232
+ this.silenceUpdates = false;
3233
+ }
3234
+ loadChildren() {
3235
+ const { resolve } = this;
3236
+ if (this.value.type !== "loaded") {
3237
+ return false;
3238
+ }
3239
+ const value = this.value.value;
3240
+ const depth = typeof resolve !== "object" || resolve === null ? {} : resolve;
3241
+ let hasChanged = false;
3242
+ const idsToLoad = new Set(this.idsSubscribed);
3243
+ const coValueType = value._type;
3244
+ if (Object.keys(depth).length > 0) {
3245
+ if (coValueType === "CoMap" || coValueType === "Account") {
3246
+ const map = value;
3247
+ const keys = "$each" in depth ? map._raw.keys() : Object.keys(depth);
3248
+ for (const key of keys) {
3249
+ const id = this.loadCoMapKey(map, key, depth[key] ?? depth.$each);
3250
+ if (id) {
3251
+ idsToLoad.add(id);
3252
+ }
3253
+ }
3254
+ } else if (value._type === "CoList") {
3255
+ const list = value;
3256
+ const descriptor = list.getItemsDescriptor();
3257
+ if (descriptor && isRefEncoded(descriptor)) {
3258
+ list._raw.processNewTransactions();
3259
+ const entries = list._raw.entries();
3260
+ const keys = "$each" in depth ? Object.keys(entries) : Object.keys(depth);
3261
+ for (const key of keys) {
3262
+ const id = this.loadCoListKey(list, key, depth[key] ?? depth.$each);
3263
+ if (id) {
3264
+ idsToLoad.add(id);
3265
+ }
3266
+ }
3267
+ }
3268
+ } else if (value._type === "CoStream") {
3269
+ const stream = value;
3270
+ const descriptor = stream.getItemsDescriptor();
3271
+ if (descriptor && isRefEncoded(descriptor)) {
3272
+ for (const session of stream._raw.sessions()) {
3273
+ const values = stream._raw.items[session] ?? [];
3274
+ for (const [i, item] of values.entries()) {
3275
+ const key = `${session}/${i}`;
3276
+ if (!depth.$each && !depth[key]) {
3277
+ continue;
3278
+ }
3279
+ const id = item.value;
3280
+ if (id) {
3281
+ idsToLoad.add(id);
3282
+ this.loadChildNode(id, depth[key] ?? depth.$each, descriptor);
3283
+ this.validationErrors.delete(key);
3284
+ } else if (!descriptor.optional) {
3285
+ this.validationErrors.set(
3286
+ key,
3287
+ new JazzError(void 0, "unavailable", [
3288
+ {
3289
+ code: "validationError",
3290
+ message: `The ref on position ${key} requested on ${stream.constructor.name} is missing`,
3291
+ params: {},
3292
+ path: [key]
3293
+ }
3294
+ ])
3295
+ );
3296
+ }
3297
+ }
3298
+ }
3299
+ }
3300
+ }
3301
+ }
3302
+ this.errorFromChildren = this.computeChildErrors();
3303
+ for (const id of this.childNodes.keys()) {
3304
+ if (!idsToLoad.has(id)) {
3305
+ hasChanged = true;
3306
+ const childNode = this.childNodes.get(id);
3307
+ if (childNode) {
3308
+ childNode.destroy();
3309
+ }
3310
+ this.childNodes.delete(id);
3311
+ this.childValues.delete(id);
3312
+ }
3313
+ }
3314
+ return hasChanged;
3315
+ }
3316
+ loadCoMapKey(map, key, depth) {
3317
+ if (key === "$onError") {
3318
+ return void 0;
3319
+ }
3320
+ const id = map._raw.get(key);
3321
+ const descriptor = map.getDescriptor(key);
3322
+ if (!descriptor) {
3323
+ this.childErrors.set(
3324
+ key,
3325
+ new JazzError(void 0, "unavailable", [
3326
+ {
3327
+ code: "validationError",
3328
+ message: `The ref ${key} requested on ${map.constructor.name} is not defined in the schema`,
3329
+ params: {},
3330
+ path: [key]
3331
+ }
3332
+ ])
3333
+ );
3334
+ return void 0;
3335
+ }
3336
+ if (isRefEncoded(descriptor)) {
3337
+ if (id) {
3338
+ this.loadChildNode(id, depth, descriptor, key);
3339
+ this.validationErrors.delete(key);
3340
+ return id;
3341
+ } else if (!descriptor.optional) {
3342
+ this.validationErrors.set(
3343
+ key,
3344
+ new JazzError(void 0, "unavailable", [
3345
+ {
3346
+ code: "validationError",
3347
+ message: `The ref ${key} requested on ${map.constructor.name} is missing`,
3348
+ params: {},
3349
+ path: [key]
3350
+ }
3351
+ ])
3352
+ );
3353
+ }
3354
+ }
3355
+ return void 0;
3356
+ }
3357
+ loadCoListKey(list, key, depth) {
3358
+ const descriptor = list.getItemsDescriptor();
3359
+ if (!descriptor || !isRefEncoded(descriptor)) {
3360
+ return void 0;
3361
+ }
3362
+ const entries = list._raw.entries();
3363
+ const entry = entries[Number(key)];
3364
+ if (!entry) {
3365
+ return void 0;
3366
+ }
3367
+ const id = entry.value;
3368
+ if (id) {
3369
+ this.loadChildNode(id, depth, descriptor, key);
3370
+ this.validationErrors.delete(key);
3371
+ return id;
3372
+ } else if (!descriptor.optional) {
3373
+ this.validationErrors.set(
3374
+ key,
3375
+ new JazzError(void 0, "unavailable", [
3376
+ {
3377
+ code: "validationError",
3378
+ message: `The ref on position ${key} requested on ${list.constructor.name} is missing`,
3379
+ params: {},
3380
+ path: [key]
3381
+ }
3382
+ ])
3383
+ );
3384
+ }
3385
+ return void 0;
3386
+ }
3387
+ loadChildNode(id, query, descriptor, key) {
3388
+ if (this.childValues.has(id)) {
3389
+ return;
3390
+ }
3391
+ if (key && this.autoloadedKeys.has(key)) {
3392
+ this.autoloaded.add(id);
3393
+ }
3394
+ const skipInvalid = typeof query === "object" && query.$onError === null;
3395
+ if (skipInvalid) {
3396
+ if (key) {
3397
+ this.skipInvalidKeys.add(key);
3398
+ }
3399
+ this.skipInvalidKeys.add(id);
3400
+ }
3401
+ const resolve = typeof query === "object" && query !== null ? { ...query } : query;
3402
+ this.childValues.set(id, { type: "unloaded", id });
3403
+ const child = new _SubscriptionScope(
3404
+ this.node,
3405
+ resolve,
3406
+ id,
3407
+ descriptor
3408
+ );
3409
+ this.childNodes.set(id, child);
3410
+ child.setListener((value) => this.handleChildUpdate(id, value, key));
3411
+ }
3412
+ destroy() {
3413
+ this.subscription.unsubscribe();
3414
+ this.subscribers.clear();
3415
+ this.childNodes.forEach((child) => child.destroy());
3416
+ }
3417
+ };
3418
+
3419
+ // src/tools/subscribe/index.ts
3420
+ function getSubscriptionScope(value) {
3421
+ const subscriptionScope = value._subscriptionScope;
3422
+ if (subscriptionScope) {
3423
+ return subscriptionScope;
3424
+ }
3425
+ const node = value._raw.core.node;
3426
+ const resolve = true;
3427
+ const id = value.id;
3428
+ const newSubscriptionScope = new SubscriptionScope(node, resolve, id, {
3429
+ ref: value.constructor,
3430
+ optional: false
3431
+ });
3432
+ Object.defineProperty(value, "_subscriptionScope", {
3433
+ value: subscriptionScope,
3434
+ writable: false,
3435
+ enumerable: false,
3436
+ configurable: false
3437
+ });
3438
+ return newSubscriptionScope;
3439
+ }
3440
+ function accessChildByKey(parent, childId, key) {
3441
+ const subscriptionScope = getSubscriptionScope(parent);
3442
+ if (!subscriptionScope.childValues.has(childId)) {
3443
+ subscriptionScope.subscribeToKey(key);
3444
+ }
3445
+ const value = subscriptionScope.childValues.get(childId);
3446
+ if (value?.type === "loaded") {
3447
+ return value.value;
3448
+ } else {
3449
+ return null;
3450
+ }
3451
+ }
3452
+ function accessChildById(parent, childId, schema) {
3453
+ const subscriptionScope = getSubscriptionScope(parent);
3454
+ subscriptionScope.subscribeToId(childId, schema);
3455
+ const value = subscriptionScope.childValues.get(childId);
3456
+ if (value?.type === "loaded") {
3457
+ return value.value;
3458
+ } else {
3459
+ return null;
3460
+ }
3461
+ }
3462
+
3463
+ // src/tools/implementation/createContext.ts
3464
+ import {
3465
+ LocalNode as LocalNode2
3466
+ } from "cojson";
3467
+ async function randomSessionProvider(accountID, crypto) {
3468
+ return {
3469
+ sessionID: crypto.newRandomSessionID(accountID),
3470
+ sessionDone: () => {
3471
+ }
3472
+ };
3473
+ }
3474
+ async function createJazzContextFromExistingCredentials({
3475
+ credentials,
3476
+ peersToLoadFrom,
3477
+ crypto,
3478
+ AccountSchema: PropsAccountSchema,
3479
+ sessionProvider,
3480
+ onLogOut
3481
+ }) {
3482
+ const { sessionID, sessionDone } = await sessionProvider(
3483
+ credentials.accountID,
3484
+ crypto
3485
+ );
3486
+ const CurrentAccountSchema = PropsAccountSchema ?? RegisteredSchemas["Account"];
3487
+ const AccountClass = anySchemaToCoSchema(CurrentAccountSchema);
3488
+ const node = await LocalNode2.withLoadedAccount({
3489
+ accountID: credentials.accountID,
3490
+ accountSecret: credentials.secret,
3491
+ sessionID,
3492
+ peersToLoadFrom,
3493
+ crypto,
3494
+ migration: async (rawAccount, _node, creationProps) => {
3495
+ const account2 = AccountClass.fromRaw(rawAccount);
3496
+ activeAccountContext.set(account2);
3497
+ await account2.applyMigration(creationProps);
3498
+ }
3499
+ });
3500
+ const account = AccountClass.fromNode(node);
3501
+ activeAccountContext.set(account);
3502
+ return {
3503
+ node,
3504
+ account,
3505
+ done: () => {
3506
+ node.gracefulShutdown();
3507
+ sessionDone();
3508
+ },
3509
+ logOut: async () => {
3510
+ node.gracefulShutdown();
3511
+ sessionDone();
3512
+ await onLogOut?.();
3513
+ }
3514
+ };
3515
+ }
3516
+ async function createJazzContextForNewAccount({
3517
+ creationProps,
3518
+ initialAgentSecret,
3519
+ peersToLoadFrom,
3520
+ crypto,
3521
+ AccountSchema: PropsAccountSchema,
3522
+ onLogOut
3523
+ }) {
3524
+ const CurrentAccountSchema = PropsAccountSchema ?? RegisteredSchemas["Account"];
3525
+ const AccountClass = anySchemaToCoSchema(CurrentAccountSchema);
3526
+ const { node } = await LocalNode2.withNewlyCreatedAccount({
3527
+ creationProps,
3528
+ peersToLoadFrom,
3529
+ crypto,
3530
+ initialAgentSecret,
3531
+ migration: async (rawAccount, _node, creationProps2) => {
3532
+ const account2 = AccountClass.fromRaw(rawAccount);
3533
+ activeAccountContext.set(account2);
3534
+ await account2.applyMigration(creationProps2);
3535
+ }
3536
+ });
3537
+ const account = AccountClass.fromNode(node);
3538
+ activeAccountContext.set(account);
3539
+ return {
3540
+ node,
3541
+ account,
3542
+ done: () => {
3543
+ node.gracefulShutdown();
3544
+ },
3545
+ logOut: async () => {
3546
+ node.gracefulShutdown();
3547
+ await onLogOut?.();
3548
+ }
3549
+ };
3550
+ }
3551
+ async function createJazzContext(options) {
3552
+ const crypto = options.crypto;
3553
+ let context;
3554
+ const authSecretStorage = options.authSecretStorage;
3555
+ await authSecretStorage.migrate();
3556
+ const credentials = options.credentials ?? await authSecretStorage.get();
3557
+ if (credentials && !options.newAccountProps) {
3558
+ context = await createJazzContextFromExistingCredentials({
3559
+ credentials: {
3560
+ accountID: credentials.accountID,
3561
+ secret: credentials.accountSecret
3562
+ },
3563
+ peersToLoadFrom: options.peersToLoadFrom,
3564
+ crypto,
3565
+ AccountSchema: options.AccountSchema,
3566
+ sessionProvider: options.sessionProvider,
3567
+ onLogOut: () => {
3568
+ authSecretStorage.clearWithoutNotify();
3569
+ }
3570
+ });
3571
+ } else {
3572
+ const secretSeed = options.crypto.newRandomSecretSeed();
3573
+ const initialAgentSecret = options.newAccountProps?.secret ?? crypto.agentSecretFromSecretSeed(secretSeed);
3574
+ const creationProps = options.newAccountProps?.creationProps ?? {
3575
+ name: options.defaultProfileName ?? "Anonymous user"
3576
+ };
3577
+ context = await createJazzContextForNewAccount({
3578
+ creationProps,
3579
+ initialAgentSecret,
3580
+ peersToLoadFrom: options.peersToLoadFrom,
3581
+ crypto,
3582
+ AccountSchema: options.AccountSchema,
3583
+ onLogOut: async () => {
3584
+ await authSecretStorage.clearWithoutNotify();
3585
+ }
3586
+ });
3587
+ if (!options.newAccountProps) {
3588
+ await authSecretStorage.setWithoutNotify({
3589
+ accountID: context.account.id,
3590
+ secretSeed,
3591
+ accountSecret: context.node.getCurrentAgent().agentSecret,
3592
+ provider: "anonymous"
3593
+ });
3594
+ }
3595
+ }
3596
+ return {
3597
+ ...context,
3598
+ authSecretStorage
3599
+ };
3600
+ }
3601
+ function createAnonymousJazzContext({
3602
+ peersToLoadFrom,
3603
+ crypto
3604
+ }) {
3605
+ const agentSecret = crypto.newRandomAgentSecret();
3606
+ const node = new LocalNode2(
3607
+ agentSecret,
3608
+ crypto.newRandomSessionID(crypto.getAgentID(agentSecret)),
3609
+ crypto
3610
+ );
3611
+ for (const peer of peersToLoadFrom) {
3612
+ node.syncManager.addPeer(peer);
3613
+ }
3614
+ activeAccountContext.setGuestMode();
3615
+ return {
3616
+ agent: new AnonymousJazzAgent(node),
3617
+ done: () => {
3618
+ },
3619
+ logOut: async () => {
3620
+ }
3621
+ };
3622
+ }
3623
+
3624
+ // src/tools/implementation/zodSchema/zodSchema.ts
3625
+ function isZodObject(schema) {
3626
+ return schema.def?.type === "object";
3627
+ }
3628
+ function isZodArray(schema) {
3629
+ return schema.def?.type === "array";
3630
+ }
3631
+ function isZodCustom(schema) {
3632
+ return schema.def?.type === "custom";
3633
+ }
3634
+ function getDef(schema) {
3635
+ return schema.def;
3636
+ }
3637
+
3638
+ // src/tools/implementation/zodSchema/zodCo.ts
3639
+ function enrichCoMapSchema(schema) {
3640
+ const baseCatchall = schema.catchall;
3641
+ const enrichedSchema = Object.assign(schema, {
3642
+ collaborative: true,
3643
+ create: (...args) => {
3644
+ return coSchema.create(...args);
3645
+ },
3646
+ load: (...args) => {
3647
+ return coSchema.load(...args);
3648
+ },
3649
+ subscribe: (...args) => {
3650
+ return coSchema.subscribe(...args);
3651
+ },
3652
+ findUnique: (...args) => {
3653
+ return coSchema.findUnique(...args);
3654
+ },
3655
+ upsertUnique: (...args) => {
3656
+ return coSchema.upsertUnique(...args);
3657
+ },
3658
+ loadUnique: (...args) => {
3659
+ return coSchema.loadUnique(...args);
3660
+ },
3661
+ catchall: (index) => {
3662
+ return enrichCoMapSchema(baseCatchall(index));
3663
+ },
3664
+ withHelpers: (helpers) => {
3665
+ return Object.assign(schema, helpers(schema));
3666
+ },
3667
+ withMigration: (migration) => {
3668
+ coSchema.prototype.migrate = migration;
3669
+ return enrichedSchema;
3670
+ },
3671
+ getCoSchema: () => {
3672
+ return coSchema;
3673
+ }
3674
+ });
3675
+ const coSchema = zodSchemaToCoSchema2(enrichedSchema);
3676
+ return enrichedSchema;
3677
+ }
3678
+ var coMapDefiner = (shape) => {
3679
+ const objectSchema = z.object(shape).meta({
3680
+ collaborative: true
3681
+ });
3682
+ return enrichCoMapSchema(objectSchema);
3683
+ };
3684
+ function enrichAccountSchema(schema) {
3685
+ const enrichedSchema = Object.assign(schema, {
3686
+ collaborative: true,
3687
+ builtin: "Account",
3688
+ create: (...args) => {
3689
+ return coSchema.create(...args);
3690
+ },
3691
+ createAs: (...args) => {
3692
+ return coSchema.createAs(...args);
3693
+ },
3694
+ getMe: (...args) => {
3695
+ return coSchema.getMe(...args);
3696
+ },
3697
+ load: (...args) => {
3698
+ return coSchema.load(...args);
3699
+ },
3700
+ subscribe: (...args) => {
3701
+ return coSchema.subscribe(...args);
3702
+ },
3703
+ withHelpers: (helpers) => {
3704
+ return Object.assign(schema, helpers(schema));
3705
+ },
3706
+ fromRaw: (...args) => {
3707
+ return coSchema.fromRaw(...args);
3708
+ },
3709
+ withMigration: (migration) => {
3710
+ coSchema.prototype.migrate = async function(creationProps) {
3711
+ await migration(this, creationProps);
3712
+ };
3713
+ return enrichedSchema;
3714
+ },
3715
+ getCoSchema: () => {
3716
+ return coSchema;
3717
+ }
3718
+ });
3719
+ const coSchema = zodSchemaToCoSchema2(enrichedSchema);
3720
+ return enrichedSchema;
3721
+ }
3722
+ var coAccountDefiner = (shape = {
3723
+ profile: coMapDefiner({
3724
+ name: z.string(),
3725
+ inbox: z.optional(z.string()),
3726
+ inboxInvite: z.optional(z.string())
3727
+ }),
3728
+ root: coMapDefiner({})
3729
+ }) => {
3730
+ const objectSchema = z.object(shape).meta({
3731
+ collaborative: true
3732
+ });
3733
+ return enrichAccountSchema(objectSchema);
3734
+ };
3735
+ var coRecordDefiner = (_keyType, valueType) => {
3736
+ return coMapDefiner({}).catchall(valueType);
3737
+ };
3738
+ function enrichCoListSchema(schema) {
3739
+ const enrichedSchema = Object.assign(schema, {
3740
+ collaborative: true,
3741
+ create: (...args) => {
3742
+ return coSchema.create(...args);
3743
+ },
3744
+ load: (...args) => {
3745
+ return coSchema.load(...args);
3746
+ },
3747
+ subscribe: (...args) => {
3748
+ return coSchema.subscribe(...args);
3749
+ },
3750
+ withHelpers: (helpers) => {
3751
+ return Object.assign(schema, helpers(schema));
3752
+ },
3753
+ getCoSchema: () => {
3754
+ return coSchema;
3755
+ }
3756
+ });
3757
+ const coSchema = zodSchemaToCoSchema2(enrichedSchema);
3758
+ return enrichedSchema;
3759
+ }
3760
+ var coListDefiner = (element) => {
3761
+ const arraySchema = z.array(element).meta({
3762
+ collaborative: true
3763
+ });
3764
+ return enrichCoListSchema(arraySchema);
3765
+ };
3766
+ var coProfileDefiner = (shape = {}) => {
3767
+ const ehnancedShape = Object.assign(shape ?? {}, {
3768
+ name: z.string(),
3769
+ inbox: z.optional(z.string()),
3770
+ inboxInvite: z.optional(z.string())
3771
+ });
3772
+ return coMapDefiner(ehnancedShape);
3773
+ };
3774
+ function enrichCoFeedSchema(schema, element) {
3775
+ const enrichedSchema = Object.assign(schema, {
3776
+ collaborative: true,
3777
+ builtin: "CoFeed",
3778
+ element,
3779
+ create: (...args) => {
3780
+ return coSchema.create(...args);
3781
+ },
3782
+ load: (...args) => {
3783
+ return coSchema.load(...args);
3784
+ },
3785
+ subscribe: (...args) => {
3786
+ return coSchema.subscribe(...args);
3787
+ },
3788
+ withHelpers: (helpers) => {
3789
+ return Object.assign(schema, helpers(schema));
3790
+ },
3791
+ getCoSchema: () => {
3792
+ return coSchema;
3793
+ }
3794
+ });
3795
+ const coSchema = zodSchemaToCoSchema2(enrichedSchema);
3796
+ return enrichedSchema;
3797
+ }
3798
+ var coFeedDefiner = (element) => {
3799
+ return enrichCoFeedSchema(z.instanceof(CoFeed), element);
3800
+ };
3801
+ function enrichFileStreamSchema(schema) {
3802
+ const enrichedSchema = Object.assign(schema, {
3803
+ collaborative: true,
3804
+ builtin: "FileStream",
3805
+ create: (...args) => {
3806
+ return coSchema.create(...args);
3807
+ },
3808
+ createFromBlob: (...args) => {
3809
+ return coSchema.createFromBlob(...args);
3810
+ },
3811
+ load: (...args) => {
3812
+ return coSchema.load(...args);
3813
+ },
3814
+ loadAsBlob: (...args) => {
3815
+ return coSchema.loadAsBlob(...args);
3816
+ },
3817
+ subscribe: (...args) => {
3818
+ return coSchema.subscribe(...args);
3819
+ },
3820
+ getCoSchema: () => {
3821
+ return coSchema;
3822
+ }
3823
+ });
3824
+ const coSchema = zodSchemaToCoSchema2(enrichedSchema);
3825
+ return enrichedSchema;
3826
+ }
3827
+ var coFileStreamDefiner = () => {
3828
+ return enrichFileStreamSchema(z.instanceof(FileStream));
3829
+ };
3830
+ function enrichPlainTextSchema(schema) {
3831
+ const enrichedSchema = Object.assign(schema, {
3832
+ collaborative: true,
3833
+ builtin: "CoPlainText",
3834
+ create: (...args) => {
3835
+ return coSchema.create(...args);
3836
+ },
3837
+ load: (...args) => {
3838
+ return coSchema.load(...args);
3839
+ },
3840
+ subscribe: (...args) => {
3841
+ return coSchema.subscribe(...args);
3842
+ },
3843
+ fromRaw: (...args) => {
3844
+ return coSchema.fromRaw(...args);
3845
+ },
3846
+ getCoSchema: () => {
3847
+ return coSchema;
3848
+ }
3849
+ });
3850
+ const coSchema = zodSchemaToCoSchema2(enrichedSchema);
3851
+ return enrichedSchema;
3852
+ }
3853
+ var coPlainTextDefiner = () => {
3854
+ return enrichPlainTextSchema(z.instanceof(CoPlainText));
3855
+ };
3856
+ function enrichRichTextSchema(schema) {
3857
+ const enrichedSchema = Object.assign(schema, {
3858
+ collaborative: true,
3859
+ builtin: "CoRichText",
3860
+ create: (...args) => {
3861
+ return coSchema.create(...args);
3862
+ },
3863
+ load: (...args) => {
3864
+ return coSchema.load(...args);
3865
+ },
3866
+ subscribe: (...args) => {
3867
+ return coSchema.subscribe(...args);
3868
+ },
3869
+ getCoSchema: () => {
3870
+ return coSchema;
3871
+ }
3872
+ });
3873
+ const coSchema = zodSchemaToCoSchema2(enrichedSchema);
3874
+ return enrichedSchema;
3875
+ }
3876
+ var coRichTextDefiner = () => {
3877
+ return enrichRichTextSchema(z.instanceof(CoRichText));
3878
+ };
3879
+ var coImageDefiner = () => {
3880
+ return ImageDefinition;
3881
+ };
3882
+
3883
+ // src/tools/implementation/zodSchema/coExport.ts
3884
+ var coExport_exports = {};
3885
+ __export(coExport_exports, {
3886
+ account: () => coAccountDefiner,
3887
+ feed: () => coFeedDefiner,
3888
+ fileStream: () => coFileStreamDefiner,
3889
+ image: () => coImageDefiner,
3890
+ list: () => coListDefiner,
3891
+ map: () => coMapDefiner,
3892
+ plainText: () => coPlainTextDefiner,
3893
+ profile: () => coProfileDefiner,
3894
+ record: () => coRecordDefiner,
3895
+ richText: () => coRichTextDefiner
3896
+ });
3897
+
3898
+ // src/tools/implementation/zodSchema/unionUtils.ts
3899
+ import { RawCoList } from "cojson";
3900
+ function schemaUnionDiscriminatorFor(schema) {
3901
+ if (isUnionOfCoMapsDeeply(schema)) {
3902
+ if (!schema._zod.disc || schema._zod.disc.size == 0) {
3903
+ throw new Error(
3904
+ "z.union() of collaborative types is not supported, use z.discriminatedUnion() instead"
3905
+ );
3906
+ }
3907
+ const discriminator = schema._zod.def.discriminator;
3908
+ const field = schema._zod.disc.get(discriminator);
3909
+ if (!field) {
3910
+ throw new Error(
3911
+ "z.discriminatedUnion() of collaborative types with non-existent discriminator key is not supported"
3912
+ );
3913
+ }
3914
+ for (const value of field.values) {
3915
+ if (typeof value !== "string" && typeof value !== "number") {
3916
+ throw new Error(
3917
+ "z.discriminatedUnion() of collaborative types with non-string or non-number discriminator value is not supported"
3918
+ );
3919
+ }
3920
+ }
3921
+ const availableOptions = [];
3922
+ for (const option of schema._zod.def.options) {
3923
+ if (option._zod.def.type === "object") {
3924
+ availableOptions.push(option);
3925
+ } else if (option._zod.def.type === "union") {
3926
+ for (const subOption of option._zod.def.options) {
3927
+ if (subOption._zod.def.type === "object") {
3928
+ availableOptions.push(subOption);
3929
+ }
3930
+ }
3931
+ } else {
3932
+ throw new Error(
3933
+ "Unsupported zod type in z.discriminatedUnion() of collaborative types"
3934
+ );
3935
+ }
3936
+ }
3937
+ const determineSchema = (_raw) => {
3938
+ if (_raw instanceof RawCoList) {
3939
+ throw new Error(
3940
+ "z.discriminatedUnion() of collaborative types is not supported for CoLists"
3941
+ );
3942
+ }
3943
+ for (const option of availableOptions) {
3944
+ let match = true;
3945
+ for (const key of schema._zod.disc.keys()) {
3946
+ const discriminatorDef = option._zod.def.shape[key];
3947
+ const discriminatorValue = _raw.get(key);
3948
+ if (discriminatorValue && typeof discriminatorValue === "object") {
3949
+ throw new Error("Discriminator must be a primitive value");
3950
+ }
3951
+ if (!discriminatorDef) {
3952
+ if (key === discriminator) {
3953
+ match = false;
3954
+ break;
3955
+ } else {
3956
+ continue;
3957
+ }
3958
+ }
3959
+ if (discriminatorDef._zod.def.type !== "literal") {
3960
+ break;
3961
+ }
3962
+ const literalDef = discriminatorDef._zod.def;
3963
+ if (!Array.from(literalDef.values).includes(discriminatorValue)) {
3964
+ match = false;
3965
+ break;
3966
+ }
3967
+ }
3968
+ if (match) {
3969
+ return zodSchemaToCoSchema2(option);
3970
+ }
3971
+ }
3972
+ throw new Error(
3973
+ "z.discriminatedUnion() of collaborative types with no matching discriminator value found"
3974
+ );
3975
+ };
3976
+ return determineSchema;
3977
+ } else {
3978
+ throw new Error(
3979
+ "z.discriminatedUnion() of non-collaborative types is not supported"
3980
+ );
3981
+ }
3982
+ }
3983
+ function isUnionOfCoMapsDeeply(schema) {
3984
+ if (schema instanceof z.core.$ZodUnion) {
3985
+ return schema._zod.def.options.every(isCoMapOrUnionOfCoMapsDeeply);
3986
+ } else {
3987
+ return false;
3988
+ }
3989
+ }
3990
+ function isCoMapOrUnionOfCoMapsDeeply(schema) {
3991
+ if (schema instanceof z.core.$ZodObject && "collaborative" in schema && schema.collaborative) {
3992
+ return true;
3993
+ } else if (schema instanceof z.core.$ZodUnion) {
3994
+ return schema._zod.def.options.every(isCoMapOrUnionOfCoMapsDeeply);
3995
+ } else {
3996
+ return false;
3997
+ }
3998
+ }
3999
+ function isUnionOfPrimitivesDeeply(schema) {
4000
+ if (schema instanceof z.core.$ZodUnion) {
4001
+ return schema._zod.def.options.every(isUnionOfPrimitivesDeeply);
4002
+ } else {
4003
+ return !("collaborative" in schema);
4004
+ }
4005
+ }
4006
+
4007
+ // src/tools/implementation/zodSchema/runtimeConverters/zodFieldToCoFieldDef.ts
4008
+ function zodFieldToCoFieldDef(schema) {
4009
+ if (isCoValueClass(schema)) {
4010
+ return coField.ref(schema);
4011
+ } else {
4012
+ if ("_zod" in schema) {
4013
+ if (schema._zod.def.type === "optional") {
4014
+ const inner = zodSchemaToCoSchemaOrKeepPrimitive(
4015
+ schema._zod.def.innerType
4016
+ );
4017
+ if (isCoValueClass(inner)) {
4018
+ return coField.ref(inner, { optional: true });
4019
+ } else {
4020
+ return zodFieldToCoFieldDef(inner);
4021
+ }
4022
+ } else if (schema._zod.def.type === "string") {
4023
+ return coField.string;
4024
+ } else if (schema._zod.def.type === "number") {
4025
+ return coField.number;
4026
+ } else if (schema._zod.def.type === "boolean") {
4027
+ return coField.boolean;
4028
+ } else if (schema._zod.def.type === "null") {
4029
+ return coField.null;
4030
+ } else if (schema._zod.def.type === "enum") {
4031
+ return coField.string;
4032
+ } else if (schema._zod.def.type === "readonly") {
4033
+ return zodFieldToCoFieldDef(
4034
+ schema.def.innerType
4035
+ );
4036
+ } else if (schema._zod.def.type === "date") {
4037
+ return coField.optional.Date;
4038
+ } else if (schema._zod.def.type === "template_literal") {
4039
+ return coField.string;
4040
+ } else if (schema._zod.def.type === "lazy") {
4041
+ return zodFieldToCoFieldDef(
4042
+ schema.unwrap()
4043
+ );
4044
+ } else if (schema._zod.def.type === "default" || schema._zod.def.type === "catch") {
4045
+ console.warn(
4046
+ "z.default()/z.catch() are not supported in collaborative schemas. They will be ignored."
4047
+ );
4048
+ return zodFieldToCoFieldDef(
4049
+ schema.def.innerType
4050
+ );
4051
+ } else if (schema._zod.def.type === "literal") {
4052
+ if (schema._zod.def.values.some(
4053
+ (literal2) => typeof literal2 === "undefined"
4054
+ )) {
4055
+ throw new Error("z.literal() with undefined is not supported");
4056
+ }
4057
+ if (schema._zod.def.values.some((literal2) => literal2 === null)) {
4058
+ throw new Error("z.literal() with null is not supported");
4059
+ }
4060
+ if (schema._zod.def.values.some((literal2) => typeof literal2 === "bigint")) {
4061
+ throw new Error("z.literal() with bigint is not supported");
4062
+ }
4063
+ return coField.literal(
4064
+ ...schema._zod.def.values
4065
+ );
4066
+ } else if (schema._zod.def.type === "object" || schema._zod.def.type === "array" || schema._zod.def.type === "tuple") {
4067
+ return coField.json();
4068
+ } else if (schema._zod.def.type === "custom") {
4069
+ if ("builtin" in schema) {
4070
+ return zodFieldToCoFieldDef(schema.builtin);
4071
+ } else {
4072
+ throw new Error(`Unsupported custom zod type`);
4073
+ }
4074
+ } else if (schema._zod.def.type === "union") {
4075
+ if (isUnionOfPrimitivesDeeply(schema)) {
4076
+ return coField.json();
4077
+ } else if (isUnionOfCoMapsDeeply(schema)) {
4078
+ return coField.ref(
4079
+ schemaUnionDiscriminatorFor(schema)
4080
+ );
4081
+ } else {
4082
+ throw new Error(
4083
+ "z.union()/z.discriminatedUnion() of mixed collaborative and non-collaborative types is not supported"
4084
+ );
4085
+ }
4086
+ } else {
4087
+ throw new Error(
4088
+ `Unsupported zod type: ${schema._zod?.def?.type || JSON.stringify(schema)}`
4089
+ );
4090
+ }
4091
+ } else {
4092
+ throw new Error(`Unsupported zod type: ${schema}`);
4093
+ }
4094
+ }
4095
+ }
4096
+
4097
+ // src/tools/implementation/zodSchema/runtimeConverters/zodSchemaToCoSchema.ts
4098
+ var coSchemasForZodSchemas = /* @__PURE__ */ new Map();
4099
+ function tryZodSchemaToCoSchema(schema) {
4100
+ if ("collaborative" in schema && schema.collaborative) {
4101
+ if (coSchemasForZodSchemas.has(schema)) {
4102
+ return coSchemasForZodSchemas.get(schema);
4103
+ }
4104
+ if (isZodObject(schema)) {
4105
+ const def = getDef(schema);
4106
+ const ClassToExtend = "builtin" in schema && schema.builtin === "Account" ? Account : CoMap;
4107
+ const coSchema = class ZCoMap extends ClassToExtend {
4108
+ constructor(options) {
4109
+ super(options);
4110
+ for (const [field, fieldType] of Object.entries(
4111
+ def.shape
4112
+ )) {
4113
+ this[field] = zodFieldToCoFieldDef(
4114
+ zodSchemaToCoSchemaOrKeepPrimitive(fieldType)
4115
+ );
4116
+ }
4117
+ if (def.catchall) {
4118
+ this[coField.items] = zodFieldToCoFieldDef(
4119
+ zodSchemaToCoSchemaOrKeepPrimitive(def.catchall)
4120
+ );
4121
+ }
4122
+ }
4123
+ };
4124
+ coSchemasForZodSchemas.set(schema, coSchema);
4125
+ return coSchema;
4126
+ } else if (isZodArray(schema)) {
4127
+ const def = getDef(schema);
4128
+ const coSchema = class ZCoList extends CoList {
4129
+ constructor(options) {
4130
+ super(options);
4131
+ this[coField.items] = zodFieldToCoFieldDef(
4132
+ zodSchemaToCoSchemaOrKeepPrimitive(def.element)
4133
+ );
4134
+ }
4135
+ };
4136
+ coSchemasForZodSchemas.set(schema, coSchema);
4137
+ return coSchema;
4138
+ } else if (isZodCustom(schema)) {
4139
+ if ("builtin" in schema) {
4140
+ if (schema.builtin === "CoFeed" && "element" in schema) {
4141
+ return CoFeed.Of(
4142
+ zodFieldToCoFieldDef(
4143
+ zodSchemaToCoSchemaOrKeepPrimitive(
4144
+ schema.element
4145
+ )
4146
+ )
4147
+ );
4148
+ } else if (schema.builtin === "FileStream") {
4149
+ return FileStream;
4150
+ } else if (schema.builtin === "CoPlainText") {
4151
+ return CoPlainText;
4152
+ } else if (schema.builtin === "CoRichText") {
4153
+ return CoRichText;
4154
+ } else {
4155
+ throw new Error(`Unsupported builtin type: ${schema.builtin}`);
4156
+ }
4157
+ } else {
4158
+ throw new Error(`Unsupported custom zod type`);
4159
+ }
4160
+ } else {
4161
+ throw new Error(
4162
+ `Unsupported zod CoValue type for top-level schema: ${schema._zod?.def?.type || JSON.stringify(schema, void 0, 2)}`
4163
+ );
4164
+ }
4165
+ } else if (schema instanceof z.core.$ZodDiscriminatedUnion) {
4166
+ if (isUnionOfCoMapsDeeply(schema)) {
4167
+ return SchemaUnion.Of(
4168
+ schemaUnionDiscriminatorFor(schema)
4169
+ );
4170
+ } else {
4171
+ throw new Error(
4172
+ "z.discriminatedUnion() of non-collaborative types is not supported as a top-level schema"
4173
+ );
4174
+ }
4175
+ } else {
4176
+ return null;
4177
+ }
4178
+ }
4179
+ function zodSchemaToCoSchema2(schema) {
4180
+ const coSchema = tryZodSchemaToCoSchema(schema);
4181
+ if (!coSchema) {
4182
+ throw new Error(
4183
+ `Unsupported zod type: ${schema._zod?.def?.type || JSON.stringify(schema)}`
4184
+ );
4185
+ }
4186
+ return coSchema;
4187
+ }
4188
+ function anySchemaToCoSchema(schema) {
4189
+ if (isCoValueClass(schema)) {
4190
+ return schema;
4191
+ } else if ("getCoSchema" in schema) {
4192
+ return schema.getCoSchema();
4193
+ } else if ("def" in schema) {
4194
+ const coSchema = tryZodSchemaToCoSchema(schema);
4195
+ if (!coSchema) {
4196
+ throw new Error(
4197
+ `Unsupported zod type: ${schema.def?.type || JSON.stringify(schema)}`
4198
+ );
4199
+ }
4200
+ return coSchema;
4201
+ }
4202
+ throw new Error(`Unsupported schema: ${JSON.stringify(schema)}`);
4203
+ }
4204
+ function zodSchemaToCoSchemaOrKeepPrimitive(schema) {
4205
+ const coSchema = tryZodSchemaToCoSchema(schema);
4206
+ if (!coSchema) {
4207
+ return schema;
4208
+ }
4209
+ return coSchema;
4210
+ }
4211
+
4212
+ // src/tools/coValues/extensions/imageDef.ts
4213
+ var ImageDefinitionBase = coMapDefiner({
4214
+ originalSize: z.tuple([z.number(), z.number()]),
4215
+ placeholderDataURL: z.string().optional()
4216
+ }).catchall(coFileStreamDefiner());
4217
+ var ImageDefinition = ImageDefinitionBase.withHelpers((Self) => ({
4218
+ highestResAvailable(imageDef, options) {
4219
+ const resolutions = Object.keys(imageDef).filter(
4220
+ (key) => key.match(/^\d+x\d+$/)
4221
+ );
4222
+ let maxWidth = options?.maxWidth;
4223
+ if (options?.targetWidth) {
4224
+ const targetWidth = options.targetWidth;
4225
+ const widths = resolutions.map((res) => Number(res.split("x")[0]));
4226
+ maxWidth = Math.min(...widths.filter((w) => w >= targetWidth));
4227
+ }
4228
+ const validResolutions = resolutions.filter(
4229
+ (key) => maxWidth === void 0 || Number(key.split("x")[0]) <= maxWidth
4230
+ );
4231
+ validResolutions.sort((a, b) => {
4232
+ const aWidth = Number(a.split("x")[0]);
4233
+ const bWidth = Number(b.split("x")[0]);
4234
+ return aWidth - bWidth;
4235
+ });
4236
+ let highestAvailableResolution;
4237
+ for (const resolution of validResolutions) {
4238
+ if (imageDef[resolution] && imageDef[resolution]?.getChunks()) {
4239
+ highestAvailableResolution = resolution;
4240
+ }
4241
+ }
4242
+ return highestAvailableResolution && {
4243
+ res: highestAvailableResolution,
4244
+ stream: imageDef[highestAvailableResolution]
4245
+ };
4246
+ }
4247
+ }));
4248
+
4249
+ // src/tools/implementation/ContextManager.ts
4250
+ import { cojsonInternals as cojsonInternals4 } from "cojson";
4251
+ import { PureJSCrypto } from "cojson/dist/crypto/PureJSCrypto";
4252
+
4253
+ // src/tools/auth/KvStoreContext.ts
4254
+ var KvStoreContext = class _KvStoreContext {
4255
+ constructor() {
4256
+ this.storageInstance = null;
4257
+ }
4258
+ static getInstance() {
4259
+ if (!_KvStoreContext.instance) {
4260
+ _KvStoreContext.instance = new _KvStoreContext();
4261
+ }
4262
+ return _KvStoreContext.instance;
4263
+ }
4264
+ isInitialized() {
4265
+ return this.storageInstance !== null;
4266
+ }
4267
+ initialize(store) {
4268
+ if (!this.storageInstance) {
4269
+ this.storageInstance = store;
4270
+ }
4271
+ }
4272
+ getStorage() {
4273
+ if (!this.storageInstance) {
4274
+ throw new Error("Storage instance is not initialized.");
4275
+ }
4276
+ return this.storageInstance;
4277
+ }
4278
+ };
4279
+ var KvStoreContext_default = KvStoreContext;
4280
+
4281
+ // src/tools/auth/AuthSecretStorage.ts
4282
+ var STORAGE_KEY = "jazz-logged-in-secret";
4283
+ var AuthSecretStorage = class {
4284
+ constructor() {
4285
+ this.listeners = /* @__PURE__ */ new Set();
4286
+ this.isAuthenticated = false;
4287
+ }
4288
+ async migrate() {
4289
+ const kvStore = KvStoreContext_default.getInstance().getStorage();
4290
+ if (!await kvStore.get(STORAGE_KEY)) {
4291
+ const demoAuthSecret = await kvStore.get("demo-auth-logged-in-secret");
4292
+ if (demoAuthSecret) {
4293
+ const parsed = JSON.parse(demoAuthSecret);
4294
+ await kvStore.set(
4295
+ STORAGE_KEY,
4296
+ JSON.stringify({
4297
+ accountID: parsed.accountID,
4298
+ accountSecret: parsed.accountSecret,
4299
+ provider: "demo"
4300
+ })
4301
+ );
4302
+ await kvStore.delete("demo-auth-logged-in-secret");
4303
+ }
4304
+ const clerkAuthSecret = await kvStore.get("jazz-clerk-auth");
4305
+ if (clerkAuthSecret) {
4306
+ const parsed = JSON.parse(clerkAuthSecret);
4307
+ await kvStore.set(
4308
+ STORAGE_KEY,
4309
+ JSON.stringify({
4310
+ accountID: parsed.accountID,
4311
+ accountSecret: parsed.secret,
4312
+ provider: "clerk"
4313
+ })
4314
+ );
4315
+ await kvStore.delete("jazz-clerk-auth");
4316
+ }
4317
+ }
4318
+ const value = await kvStore.get(STORAGE_KEY);
4319
+ if (value) {
4320
+ const parsed = JSON.parse(value);
4321
+ if ("secret" in parsed) {
4322
+ await kvStore.set(
4323
+ STORAGE_KEY,
4324
+ JSON.stringify({
4325
+ accountID: parsed.accountID,
4326
+ secretSeed: parsed.secretSeed,
4327
+ accountSecret: parsed.secret,
4328
+ provider: parsed.provider
4329
+ })
4330
+ );
4331
+ }
4332
+ }
4333
+ }
4334
+ async get() {
4335
+ const kvStore = KvStoreContext_default.getInstance().getStorage();
4336
+ const data = await kvStore.get(STORAGE_KEY);
4337
+ if (!data) return null;
4338
+ const parsed = JSON.parse(data);
4339
+ if (!parsed.accountID || !parsed.accountSecret) {
4340
+ throw new Error("Invalid auth secret storage data");
4341
+ }
4342
+ return {
4343
+ accountID: parsed.accountID,
4344
+ secretSeed: parsed.secretSeed ? new Uint8Array(parsed.secretSeed) : void 0,
4345
+ accountSecret: parsed.accountSecret,
4346
+ provider: parsed.provider
4347
+ };
4348
+ }
4349
+ async setWithoutNotify(payload) {
4350
+ const kvStore = KvStoreContext_default.getInstance().getStorage();
4351
+ await kvStore.set(
4352
+ STORAGE_KEY,
4353
+ JSON.stringify({
4354
+ accountID: payload.accountID,
4355
+ secretSeed: payload.secretSeed ? Array.from(payload.secretSeed) : void 0,
4356
+ accountSecret: payload.accountSecret,
4357
+ provider: payload.provider
4358
+ })
4359
+ );
4360
+ }
4361
+ async set(payload) {
4362
+ this.setWithoutNotify(payload);
4363
+ this.emitUpdate(payload);
4364
+ }
4365
+ getIsAuthenticated(data) {
4366
+ if (!data) return false;
4367
+ return data.provider !== "anonymous";
4368
+ }
4369
+ onUpdate(handler) {
4370
+ this.listeners.add(handler);
4371
+ return () => {
4372
+ this.listeners.delete(handler);
4373
+ };
4374
+ }
4375
+ emitUpdate(data) {
4376
+ const isAuthenticated = this.getIsAuthenticated(data);
4377
+ if (this.isAuthenticated === isAuthenticated) return;
4378
+ this.isAuthenticated = isAuthenticated;
4379
+ for (const listener of this.listeners) {
4380
+ listener(this.isAuthenticated);
4381
+ }
4382
+ }
4383
+ async clearWithoutNotify() {
4384
+ const kvStore = KvStoreContext_default.getInstance().getStorage();
4385
+ await kvStore.delete(STORAGE_KEY);
4386
+ }
4387
+ async clear() {
4388
+ await this.clearWithoutNotify();
4389
+ this.emitUpdate(null);
4390
+ }
4391
+ };
4392
+
4393
+ // src/tools/auth/InMemoryKVStore.ts
4394
+ var InMemoryKVStore = class {
4395
+ constructor() {
4396
+ this.store = {};
4397
+ }
4398
+ async get(key) {
4399
+ const data = this.store[key];
4400
+ if (!data) return null;
4401
+ return data;
4402
+ }
4403
+ async set(key, value) {
4404
+ this.store[key] = value;
4405
+ }
4406
+ async delete(key) {
4407
+ delete this.store[key];
4408
+ }
4409
+ async clearAll() {
4410
+ this.store = {};
4411
+ }
4412
+ };
4413
+
4414
+ // src/tools/implementation/ContextManager.ts
4415
+ function getAnonymousFallback() {
4416
+ const context = createAnonymousJazzContext({
4417
+ peersToLoadFrom: [],
4418
+ crypto: new PureJSCrypto()
4419
+ });
4420
+ return {
4421
+ guest: context.agent,
4422
+ node: context.agent.node,
4423
+ done: () => {
4424
+ },
4425
+ logOut: async () => {
4426
+ },
4427
+ isAuthenticated: false,
4428
+ authenticate: async () => {
4429
+ },
4430
+ register: async () => {
4431
+ throw new Error("Not implemented");
4432
+ }
4433
+ };
4434
+ }
4435
+ var JazzContextManager = class {
4436
+ constructor(opts) {
4437
+ this.authSecretStorage = new AuthSecretStorage();
4438
+ this.keepContextOpen = false;
4439
+ this.logOut = async () => {
4440
+ if (!this.context || !this.props) {
4441
+ return;
4442
+ }
4443
+ await this.props.onLogOut?.();
4444
+ if (this.props.logOutReplacement) {
4445
+ await this.props.logOutReplacement();
4446
+ } else {
4447
+ await this.context.logOut();
4448
+ return this.createContext(this.props);
4449
+ }
4450
+ };
4451
+ this.done = () => {
4452
+ if (!this.context) {
4453
+ return;
4454
+ }
4455
+ this.context.done();
4456
+ };
4457
+ this.shouldMigrateAnonymousAccount = async () => {
4458
+ if (!this.props?.onAnonymousAccountDiscarded) {
4459
+ return false;
4460
+ }
4461
+ const prevCredentials = await this.authSecretStorage.get();
4462
+ const wasAnonymous = this.authSecretStorage.getIsAuthenticated(prevCredentials) === false;
4463
+ return wasAnonymous;
4464
+ };
4465
+ /**
4466
+ * Authenticates the user with the given credentials
4467
+ */
4468
+ this.authenticate = async (credentials) => {
4469
+ if (!this.props) {
4470
+ throw new Error("Props required");
4471
+ }
4472
+ const prevContext = this.context;
4473
+ const migratingAnonymousAccount = await this.shouldMigrateAnonymousAccount();
4474
+ this.keepContextOpen = migratingAnonymousAccount;
4475
+ await this.createContext(this.props, { credentials }).finally(() => {
4476
+ this.keepContextOpen = false;
4477
+ });
4478
+ if (migratingAnonymousAccount) {
4479
+ await this.handleAnonymousAccountMigration(prevContext);
4480
+ }
4481
+ };
4482
+ this.register = async (accountSecret, creationProps) => {
4483
+ if (!this.props) {
4484
+ throw new Error("Props required");
4485
+ }
4486
+ const prevContext = this.context;
4487
+ const migratingAnonymousAccount = await this.shouldMigrateAnonymousAccount();
4488
+ this.keepContextOpen = migratingAnonymousAccount;
4489
+ await this.createContext(this.props, {
4490
+ newAccountProps: {
4491
+ secret: accountSecret,
4492
+ creationProps
4493
+ }
4494
+ }).finally(() => {
4495
+ this.keepContextOpen = false;
4496
+ });
4497
+ if (migratingAnonymousAccount) {
4498
+ await this.handleAnonymousAccountMigration(prevContext);
4499
+ }
4500
+ if (this.context && "me" in this.context) {
4501
+ return this.context.me.id;
4502
+ }
4503
+ throw new Error("The registration hasn't created a new account");
4504
+ };
4505
+ this.listeners = /* @__PURE__ */ new Set();
4506
+ this.subscribe = (callback) => {
4507
+ this.listeners.add(callback);
4508
+ return () => {
4509
+ this.listeners.delete(callback);
4510
+ };
4511
+ };
4512
+ KvStoreContext.getInstance().initialize(this.getKvStore());
4513
+ if (opts?.useAnonymousFallback) {
4514
+ this.value = getAnonymousFallback();
4515
+ }
4516
+ }
4517
+ getKvStore() {
4518
+ return new InMemoryKVStore();
4519
+ }
4520
+ async createContext(props, authProps) {
4521
+ this.props = props;
4522
+ const { promise, resolve } = createResolvablePromise();
4523
+ const prevPromise = this.contextPromise;
4524
+ this.contextPromise = promise;
4525
+ await prevPromise;
4526
+ try {
4527
+ const result = await this.getNewContext(props, authProps);
4528
+ await this.updateContext(props, result, authProps);
4529
+ resolve();
4530
+ } catch (error) {
4531
+ resolve();
4532
+ throw error;
4533
+ }
4534
+ }
4535
+ async getNewContext(props, authProps) {
4536
+ props;
4537
+ authProps;
4538
+ throw new Error("Not implemented");
4539
+ }
4540
+ async updateContext(props, context, authProps) {
4541
+ if (!this.keepContextOpen) {
4542
+ this.context?.done();
4543
+ }
4544
+ this.context = context;
4545
+ this.props = props;
4546
+ this.value = {
4547
+ ...context,
4548
+ node: context.node,
4549
+ authenticate: this.authenticate,
4550
+ register: this.register,
4551
+ logOut: this.logOut
4552
+ };
4553
+ if (authProps?.credentials) {
4554
+ this.authSecretStorage.emitUpdate(authProps.credentials);
4555
+ } else {
4556
+ this.authSecretStorage.emitUpdate(await this.authSecretStorage.get());
4557
+ }
4558
+ this.notify();
4559
+ }
4560
+ propsChanged(props) {
4561
+ props;
4562
+ throw new Error("Not implemented");
4563
+ }
4564
+ getCurrentValue() {
4565
+ return this.value;
4566
+ }
4567
+ setCurrentValue(value) {
4568
+ this.value = value;
4569
+ }
4570
+ getAuthSecretStorage() {
4571
+ return this.authSecretStorage;
4572
+ }
4573
+ async handleAnonymousAccountMigration(prevContext) {
4574
+ if (!this.props) {
4575
+ throw new Error("Props required");
4576
+ }
4577
+ const currentContext = this.context;
4578
+ if (prevContext && currentContext && "me" in prevContext && "me" in currentContext) {
4579
+ const [prevAccountAsPeer, currentAccountAsPeer] = cojsonInternals4.connectedPeers(
4580
+ prevContext.me.id,
4581
+ currentContext.me.id,
4582
+ {
4583
+ peer1role: "client",
4584
+ peer2role: "server"
4585
+ }
4586
+ );
4587
+ prevContext.node.syncManager.addPeer(currentAccountAsPeer);
4588
+ currentContext.node.syncManager.addPeer(prevAccountAsPeer);
4589
+ try {
4590
+ await this.props.onAnonymousAccountDiscarded?.(prevContext.me);
4591
+ await prevContext.me.waitForAllCoValuesSync();
4592
+ } catch (error) {
4593
+ console.error("Error onAnonymousAccountDiscarded", error);
4594
+ }
4595
+ prevAccountAsPeer.outgoing.close();
4596
+ currentAccountAsPeer.outgoing.close();
4597
+ }
4598
+ prevContext?.done();
4599
+ }
4600
+ notify() {
4601
+ for (const listener of this.listeners) {
4602
+ listener();
4603
+ }
4604
+ }
4605
+ };
4606
+ function createResolvablePromise() {
4607
+ let resolve;
4608
+ const promise = new Promise((res) => {
4609
+ resolve = res;
4610
+ });
4611
+ return { promise, resolve };
4612
+ }
4613
+
4614
+ // src/tools/implementation/devtoolsFormatters.ts
4615
+ globalThis.devtoolsFormatters = [
4616
+ {
4617
+ header: (object2) => {
4618
+ if (object2._type === "CoMap") {
4619
+ return ["div", {}, ["span", {}, object2.constructor.name]];
4620
+ } else if (object2._type === "CoList") {
4621
+ return [
4622
+ "div",
4623
+ {},
4624
+ ["span", {}, object2.constructor.name + "(" + object2.length + ") "]
4625
+ ];
4626
+ } else if (object2._type === "Account") {
4627
+ return [
4628
+ "div",
4629
+ {},
4630
+ [
4631
+ "span",
4632
+ {},
4633
+ object2.constructor.name + "(" + object2._refs.profile.value?.name + (object2.isMe ? " ME" : "") + ")"
4634
+ ]
4635
+ ];
4636
+ } else {
4637
+ return null;
4638
+ }
4639
+ },
4640
+ hasBody: function() {
4641
+ return true;
4642
+ },
4643
+ body: function(object2) {
4644
+ if (object2._type === "CoMap" || object2._type === "Account") {
4645
+ return [
4646
+ "div",
4647
+ { style: "margin-left: 15px" },
4648
+ ["div", "id: ", ["object", { object: object2.id }]],
4649
+ ...Object.entries(object2).map(([k, v]) => [
4650
+ "div",
4651
+ { style: "white-space: nowrap;" },
4652
+ ["span", { style: "font-weight: bold; opacity: 0.6" }, k, ": "],
4653
+ ["object", { object: v }],
4654
+ ...typeof object2._schema[k] === "function" ? v === null ? [
4655
+ [
4656
+ "span",
4657
+ { style: "opacity: 0.5" },
4658
+ ` (pending ${object2._schema[k].name} `,
4659
+ ["object", { object: object2._refs[k] }],
4660
+ ")"
4661
+ ]
4662
+ ] : [] : []
4663
+ ])
4664
+ ];
4665
+ } else if (object2._type === "CoList") {
4666
+ return [
4667
+ "div",
4668
+ { style: "margin-left: 15px" },
4669
+ ["div", "id: ", ["object", { object: object2.id }]],
4670
+ ...object2.map((v, i) => [
4671
+ "div",
4672
+ { style: "white-space: nowrap;" },
4673
+ ["span", { style: "font-weight: bold; opacity: 0.6" }, i, ": "],
4674
+ ["object", { object: v }],
4675
+ ...typeof object2._schema[ItemsSym] === "function" ? v === null ? [
4676
+ [
4677
+ "span",
4678
+ { style: "opacity: 0.5" },
4679
+ ` (pending ${object2._schema[ItemsSym].name} `,
4680
+ ["object", { object: object2._refs[i] }],
4681
+ ")"
4682
+ ]
4683
+ ] : [] : []
4684
+ ])
4685
+ ];
4686
+ }
4687
+ }
4688
+ }
4689
+ ];
4690
+
4691
+ // src/tools/coValues/interfaces.ts
4692
+ function isCoValueClass(value) {
4693
+ return typeof value === "function" && value.fromRaw !== void 0;
4694
+ }
4695
+ function loadCoValueWithoutMe(cls, id, options) {
4696
+ return loadCoValue(cls, id, {
4697
+ ...options,
4698
+ loadAs: options?.loadAs ?? activeAccountContext.get()
4699
+ });
4700
+ }
4701
+ function loadCoValue(cls, id, options) {
4702
+ return new Promise((resolve) => {
4703
+ subscribeToCoValue(
4704
+ cls,
4705
+ id,
4706
+ {
4707
+ resolve: options.resolve,
4708
+ loadAs: options.loadAs,
4709
+ syncResolution: true,
4710
+ skipRetry: options.skipRetry,
4711
+ onUnavailable: () => {
4712
+ resolve(null);
4713
+ },
4714
+ onUnauthorized: () => {
4715
+ resolve(null);
4716
+ }
4717
+ },
4718
+ (value, unsubscribe) => {
4719
+ resolve(value);
4720
+ unsubscribe();
4721
+ }
4722
+ );
4723
+ });
4724
+ }
4725
+ async function ensureCoValueLoaded(existing, options) {
4726
+ const response = await loadCoValue(
4727
+ existing.constructor,
4728
+ existing.id,
4729
+ {
4730
+ loadAs: existing._loadedAs,
4731
+ resolve: options?.resolve
4732
+ }
4733
+ );
4734
+ if (!response) {
4735
+ throw new Error("Failed to deeply load CoValue " + existing.id);
4736
+ }
4737
+ return response;
4738
+ }
4739
+ function parseSubscribeRestArgs(args) {
4740
+ if (args.length === 2) {
4741
+ if (typeof args[0] === "object" && args[0] && typeof args[1] === "function") {
4742
+ return {
4743
+ options: {
4744
+ resolve: args[0].resolve,
4745
+ loadAs: args[0].loadAs,
4746
+ onUnauthorized: args[0].onUnauthorized,
4747
+ onUnavailable: args[0].onUnavailable
4748
+ },
4749
+ listener: args[1]
4750
+ };
4751
+ } else {
4752
+ throw new Error("Invalid arguments");
4753
+ }
4754
+ } else {
4755
+ if (typeof args[0] === "function") {
4756
+ return { options: {}, listener: args[0] };
4757
+ } else {
4758
+ throw new Error("Invalid arguments");
4759
+ }
4760
+ }
4761
+ }
4762
+ function subscribeToCoValueWithoutMe(cls, id, options, listener) {
4763
+ return subscribeToCoValue(
4764
+ cls,
4765
+ id,
4766
+ {
4767
+ ...options,
4768
+ loadAs: options.loadAs ?? activeAccountContext.get()
4769
+ },
4770
+ listener
4771
+ );
4772
+ }
4773
+ function subscribeToCoValue(cls, id, options, listener) {
4774
+ const loadAs = options.loadAs ?? activeAccountContext.get();
4775
+ const node = "node" in loadAs ? loadAs.node : loadAs._raw.core.node;
4776
+ const resolve = options.resolve ?? true;
4777
+ let unsubscribed = false;
4778
+ const rootNode = new SubscriptionScope(
4779
+ node,
4780
+ resolve,
4781
+ id,
4782
+ {
4783
+ ref: cls,
4784
+ optional: false
4785
+ },
4786
+ options.skipRetry
4787
+ );
4788
+ const handleUpdate = (value) => {
4789
+ if (unsubscribed) return;
4790
+ if (value.type === "unavailable") {
4791
+ options.onUnavailable?.();
4792
+ console.error(value.toString());
4793
+ } else if (value.type === "unauthorized") {
4794
+ options.onUnauthorized?.();
4795
+ console.error(value.toString());
4796
+ } else if (value.type === "loaded") {
4797
+ listener(value.value, unsubscribe);
4798
+ }
4799
+ };
4800
+ let shouldDefer = !options.syncResolution;
4801
+ rootNode.setListener((value) => {
4802
+ if (shouldDefer) {
4803
+ shouldDefer = false;
4804
+ Promise.resolve().then(() => {
4805
+ handleUpdate(value);
4806
+ });
4807
+ } else {
4808
+ handleUpdate(value);
4809
+ }
4810
+ });
4811
+ function unsubscribe() {
4812
+ unsubscribed = true;
4813
+ rootNode.destroy();
4814
+ }
4815
+ return unsubscribe;
4816
+ }
4817
+ function createCoValueObservable(initialValue = void 0) {
4818
+ let currentValue = initialValue;
4819
+ let subscriberCount = 0;
4820
+ function subscribe(cls, id, options, listener) {
4821
+ subscriberCount++;
4822
+ const unsubscribe = subscribeToCoValue(
4823
+ anySchemaToCoSchema(cls),
4824
+ id,
4825
+ {
4826
+ loadAs: options.loadAs,
4827
+ resolve: options.resolve,
4828
+ onUnavailable: () => {
4829
+ currentValue = null;
4830
+ options.onUnavailable?.();
4831
+ },
4832
+ onUnauthorized: () => {
4833
+ currentValue = null;
4834
+ options.onUnauthorized?.();
4835
+ },
4836
+ syncResolution: options.syncResolution
4837
+ },
4838
+ (value) => {
4839
+ currentValue = value;
4840
+ listener();
4841
+ }
4842
+ );
4843
+ return () => {
4844
+ unsubscribe();
4845
+ subscriberCount--;
4846
+ if (subscriberCount === 0) {
4847
+ currentValue = void 0;
4848
+ }
4849
+ };
4850
+ }
4851
+ const observable = {
4852
+ getCurrentValue: () => currentValue,
4853
+ subscribe
4854
+ };
4855
+ return observable;
4856
+ }
4857
+ function subscribeToExistingCoValue(existing, options, listener) {
4858
+ return subscribeToCoValue(
4859
+ existing.constructor,
4860
+ existing.id,
4861
+ {
4862
+ loadAs: existing._loadedAs,
4863
+ resolve: options?.resolve,
4864
+ onUnavailable: options?.onUnavailable,
4865
+ onUnauthorized: options?.onUnauthorized
4866
+ },
4867
+ listener
4868
+ );
4869
+ }
4870
+ function isAccountInstance(instance) {
4871
+ if (typeof instance !== "object" || instance === null) {
4872
+ return false;
4873
+ }
4874
+ return "_type" in instance && instance._type === "Account";
4875
+ }
4876
+ function parseCoValueCreateOptions(options) {
4877
+ const Group3 = RegisteredSchemas["Group"];
4878
+ if (!options) {
4879
+ return { owner: Group3.create(), uniqueness: void 0 };
4880
+ }
4881
+ if ("_type" in options) {
4882
+ if (options._type === "Account" || options._type === "Group") {
4883
+ return { owner: options, uniqueness: void 0 };
4884
+ }
4885
+ }
4886
+ const uniqueness = options.unique ? { uniqueness: options.unique } : void 0;
4887
+ return {
4888
+ owner: options.owner ?? Group3.create(),
4889
+ uniqueness
4890
+ };
4891
+ }
4892
+ function parseGroupCreateOptions(options) {
4893
+ if (!options) {
4894
+ return { owner: activeAccountContext.get() };
4895
+ }
4896
+ return "_type" in options && isAccountInstance(options) ? { owner: options } : { owner: options.owner ?? activeAccountContext.get() };
4897
+ }
4898
+
4899
+ export {
4900
+ zodReExport_exports,
4901
+ loadCoValue,
4902
+ subscribeToCoValue,
4903
+ createCoValueObservable,
4904
+ CoValueBase,
4905
+ CoMap,
4906
+ CoList,
4907
+ CoFeed,
4908
+ FileStream,
4909
+ Account,
4910
+ isControlledAccount,
4911
+ Group,
4912
+ Profile,
4913
+ Inbox,
4914
+ InboxSender,
4915
+ CoPlainText,
4916
+ CoRichText,
4917
+ SchemaUnion,
4918
+ AnonymousJazzAgent,
4919
+ activeAccountContext,
4920
+ Encoders,
4921
+ coField,
4922
+ SubscriptionScope,
4923
+ randomSessionProvider,
4924
+ createJazzContextFromExistingCredentials,
4925
+ createJazzContextForNewAccount,
4926
+ createJazzContext,
4927
+ createAnonymousJazzContext,
4928
+ coExport_exports,
4929
+ zodSchemaToCoSchema2 as zodSchemaToCoSchema,
4930
+ anySchemaToCoSchema,
4931
+ ImageDefinition,
4932
+ KvStoreContext,
4933
+ AuthSecretStorage,
4934
+ InMemoryKVStore,
4935
+ JazzContextManager
4936
+ };
4937
+ /* istanbul ignore file -- @preserve */
4938
+ //# sourceMappingURL=chunk-VBDJM6Z5.js.map