@sidekickdb/core 0.0.0 → 2.0.0

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 (583) hide show
  1. package/.tshy/build.json +8 -0
  2. package/.tshy/commonjs.json +16 -0
  3. package/.tshy/esm.json +15 -0
  4. package/LICENSE.md +202 -0
  5. package/NOTICE +27 -0
  6. package/README.md +25 -2
  7. package/__example__/standalone.esm.html +23 -0
  8. package/__example__/standalone.umd.html +21 -0
  9. package/__tests__/src/Reactor.test.ts +480 -0
  10. package/__tests__/src/auth-extra-fields.e2e.test.ts +160 -0
  11. package/__tests__/src/cookieSync.e2e.test.ts +165 -0
  12. package/__tests__/src/data/movies/attrs.json +145 -0
  13. package/__tests__/src/data/movies/triples.json +1507 -0
  14. package/__tests__/src/data/zeneca/attrs.json +251 -0
  15. package/__tests__/src/data/zeneca/triples.json +15854 -0
  16. package/__tests__/src/dataForQueryMemo.test.ts +136 -0
  17. package/__tests__/src/datalog.test.ts +175 -0
  18. package/__tests__/src/devtool.test.ts +48 -0
  19. package/__tests__/src/endpoints.test.ts +228 -0
  20. package/__tests__/src/infiniteQuery.e2e.test.ts +454 -0
  21. package/__tests__/src/instaml.test.ts +1593 -0
  22. package/__tests__/src/instaql.bench.ts +34 -0
  23. package/__tests__/src/instaql.test.ts +1388 -0
  24. package/__tests__/src/instaqlInference.test.ts +243 -0
  25. package/__tests__/src/notifyScope.test.ts +1145 -0
  26. package/__tests__/src/queryValidation.test.ts +1033 -0
  27. package/__tests__/src/schema.test.ts +641 -0
  28. package/__tests__/src/serializeSchema.test.ts +123 -0
  29. package/__tests__/src/simple.e2e.test.ts +10 -0
  30. package/__tests__/src/storageUpload.test.ts +70 -0
  31. package/__tests__/src/store.test.ts +718 -0
  32. package/__tests__/src/transactionValidation.test.ts +450 -0
  33. package/__tests__/src/typeUtils.ts +39 -0
  34. package/__tests__/src/utils/PersistedObject.test.ts +529 -0
  35. package/__tests__/src/utils/dates.test.ts +82 -0
  36. package/__tests__/src/utils/e2e.ts +95 -0
  37. package/__tests__/src/utils/msw.ts +3 -0
  38. package/__tests__/src/utils/object.test.ts +78 -0
  39. package/__tests__/src/utils/weakHash.test.ts +68 -0
  40. package/__tests__/src/utils/weakHashLegacy.test.ts +22 -0
  41. package/__tests__/src/vite.env.d.ts +1 -0
  42. package/dist/commonjs/Connection.d.ts +93 -0
  43. package/dist/commonjs/Connection.d.ts.map +1 -0
  44. package/dist/commonjs/Connection.js +194 -0
  45. package/dist/commonjs/Connection.js.map +1 -0
  46. package/dist/commonjs/InMemoryStorage.d.ts +11 -0
  47. package/dist/commonjs/InMemoryStorage.d.ts.map +1 -0
  48. package/dist/commonjs/InMemoryStorage.js +29 -0
  49. package/dist/commonjs/InMemoryStorage.js.map +1 -0
  50. package/dist/commonjs/IndexedDBStorage.d.ts +18 -0
  51. package/dist/commonjs/IndexedDBStorage.d.ts.map +1 -0
  52. package/dist/commonjs/IndexedDBStorage.js +341 -0
  53. package/dist/commonjs/IndexedDBStorage.js.map +1 -0
  54. package/dist/commonjs/InstantError.d.ts +7 -0
  55. package/dist/commonjs/InstantError.d.ts.map +1 -0
  56. package/dist/commonjs/InstantError.js +28 -0
  57. package/dist/commonjs/InstantError.js.map +1 -0
  58. package/dist/commonjs/Reactor.d.ts +445 -0
  59. package/dist/commonjs/Reactor.d.ts.map +1 -0
  60. package/dist/commonjs/Reactor.js +2471 -0
  61. package/dist/commonjs/Reactor.js.map +1 -0
  62. package/dist/commonjs/StorageAPI.d.ts +40 -0
  63. package/dist/commonjs/StorageAPI.d.ts.map +1 -0
  64. package/dist/commonjs/StorageAPI.js +82 -0
  65. package/dist/commonjs/StorageAPI.js.map +1 -0
  66. package/dist/commonjs/Stream.d.ts +121 -0
  67. package/dist/commonjs/Stream.d.ts.map +1 -0
  68. package/dist/commonjs/Stream.js +819 -0
  69. package/dist/commonjs/Stream.js.map +1 -0
  70. package/dist/commonjs/SyncTable.d.ts +145 -0
  71. package/dist/commonjs/SyncTable.d.ts.map +1 -0
  72. package/dist/commonjs/SyncTable.js +564 -0
  73. package/dist/commonjs/SyncTable.js.map +1 -0
  74. package/dist/commonjs/WindowNetworkListener.d.ts +5 -0
  75. package/dist/commonjs/WindowNetworkListener.d.ts.map +1 -0
  76. package/dist/commonjs/WindowNetworkListener.js +23 -0
  77. package/dist/commonjs/WindowNetworkListener.js.map +1 -0
  78. package/dist/commonjs/__types__/fieldsTypeTest.d.ts +2 -0
  79. package/dist/commonjs/__types__/fieldsTypeTest.d.ts.map +1 -0
  80. package/dist/commonjs/__types__/fieldsTypeTest.js +68 -0
  81. package/dist/commonjs/__types__/fieldsTypeTest.js.map +1 -0
  82. package/dist/commonjs/__types__/typeUtils.d.ts +20 -0
  83. package/dist/commonjs/__types__/typeUtils.d.ts.map +1 -0
  84. package/dist/commonjs/__types__/typeUtils.js +5 -0
  85. package/dist/commonjs/__types__/typeUtils.js.map +1 -0
  86. package/dist/commonjs/__types__/useDatesTypeTest.d.ts +2 -0
  87. package/dist/commonjs/__types__/useDatesTypeTest.d.ts.map +1 -0
  88. package/dist/commonjs/__types__/useDatesTypeTest.js +55 -0
  89. package/dist/commonjs/__types__/useDatesTypeTest.js.map +1 -0
  90. package/dist/commonjs/attrTypes.d.ts +26 -0
  91. package/dist/commonjs/attrTypes.d.ts.map +1 -0
  92. package/dist/commonjs/attrTypes.js +3 -0
  93. package/dist/commonjs/attrTypes.js.map +1 -0
  94. package/dist/commonjs/authAPI.d.ts +65 -0
  95. package/dist/commonjs/authAPI.d.ts.map +1 -0
  96. package/dist/commonjs/authAPI.js +114 -0
  97. package/dist/commonjs/authAPI.js.map +1 -0
  98. package/dist/commonjs/clientTypes.d.ts +41 -0
  99. package/dist/commonjs/clientTypes.d.ts.map +1 -0
  100. package/dist/commonjs/clientTypes.js +3 -0
  101. package/dist/commonjs/clientTypes.js.map +1 -0
  102. package/dist/commonjs/coreTypes.d.ts +34 -0
  103. package/dist/commonjs/coreTypes.d.ts.map +1 -0
  104. package/dist/commonjs/coreTypes.js +3 -0
  105. package/dist/commonjs/coreTypes.js.map +1 -0
  106. package/dist/commonjs/createRouteHandler.d.ts +8 -0
  107. package/dist/commonjs/createRouteHandler.d.ts.map +1 -0
  108. package/dist/commonjs/createRouteHandler.js +56 -0
  109. package/dist/commonjs/createRouteHandler.js.map +1 -0
  110. package/dist/commonjs/datalog.d.ts +8 -0
  111. package/dist/commonjs/datalog.d.ts.map +1 -0
  112. package/dist/commonjs/datalog.js +106 -0
  113. package/dist/commonjs/datalog.js.map +1 -0
  114. package/dist/commonjs/devtool.d.ts +4 -0
  115. package/dist/commonjs/devtool.d.ts.map +1 -0
  116. package/dist/commonjs/devtool.js +191 -0
  117. package/dist/commonjs/devtool.js.map +1 -0
  118. package/dist/commonjs/endpoints.d.ts +35 -0
  119. package/dist/commonjs/endpoints.d.ts.map +1 -0
  120. package/dist/commonjs/endpoints.js +80 -0
  121. package/dist/commonjs/endpoints.js.map +1 -0
  122. package/dist/commonjs/framework.d.ts +81 -0
  123. package/dist/commonjs/framework.d.ts.map +1 -0
  124. package/dist/commonjs/framework.js +284 -0
  125. package/dist/commonjs/framework.js.map +1 -0
  126. package/dist/commonjs/helperTypes.d.ts +76 -0
  127. package/dist/commonjs/helperTypes.d.ts.map +1 -0
  128. package/dist/commonjs/helperTypes.js +3 -0
  129. package/dist/commonjs/helperTypes.js.map +1 -0
  130. package/dist/commonjs/index.d.ts +614 -0
  131. package/dist/commonjs/index.d.ts.map +1 -0
  132. package/dist/commonjs/index.js +677 -0
  133. package/dist/commonjs/index.js.map +1 -0
  134. package/dist/commonjs/infiniteQuery.d.ts +26 -0
  135. package/dist/commonjs/infiniteQuery.d.ts.map +1 -0
  136. package/dist/commonjs/infiniteQuery.js +438 -0
  137. package/dist/commonjs/infiniteQuery.js.map +1 -0
  138. package/dist/commonjs/instaml.d.ts +18 -0
  139. package/dist/commonjs/instaml.d.ts.map +1 -0
  140. package/dist/commonjs/instaml.js +584 -0
  141. package/dist/commonjs/instaml.js.map +1 -0
  142. package/dist/commonjs/instaql.d.ts +13 -0
  143. package/dist/commonjs/instaql.d.ts.map +1 -0
  144. package/dist/commonjs/instaql.js +670 -0
  145. package/dist/commonjs/instaql.js.map +1 -0
  146. package/dist/commonjs/instatx.d.ts +128 -0
  147. package/dist/commonjs/instatx.d.ts.map +1 -0
  148. package/dist/commonjs/instatx.js +102 -0
  149. package/dist/commonjs/instatx.js.map +1 -0
  150. package/dist/commonjs/model/instaqlResult.d.ts +8 -0
  151. package/dist/commonjs/model/instaqlResult.d.ts.map +1 -0
  152. package/dist/commonjs/model/instaqlResult.js +28 -0
  153. package/dist/commonjs/model/instaqlResult.js.map +1 -0
  154. package/dist/commonjs/notifyScope.d.ts +32 -0
  155. package/dist/commonjs/notifyScope.d.ts.map +1 -0
  156. package/dist/commonjs/notifyScope.js +306 -0
  157. package/dist/commonjs/notifyScope.js.map +1 -0
  158. package/dist/commonjs/package.json +3 -0
  159. package/dist/commonjs/parseSchemaFromJSON.d.ts +3 -0
  160. package/dist/commonjs/parseSchemaFromJSON.d.ts.map +1 -0
  161. package/dist/commonjs/parseSchemaFromJSON.js +147 -0
  162. package/dist/commonjs/parseSchemaFromJSON.js.map +1 -0
  163. package/dist/commonjs/presence.d.ts +51 -0
  164. package/dist/commonjs/presence.d.ts.map +1 -0
  165. package/dist/commonjs/presence.js +55 -0
  166. package/dist/commonjs/presence.js.map +1 -0
  167. package/dist/commonjs/presenceTypes.d.ts +10 -0
  168. package/dist/commonjs/presenceTypes.d.ts.map +1 -0
  169. package/dist/commonjs/presenceTypes.js +5 -0
  170. package/dist/commonjs/presenceTypes.js.map +1 -0
  171. package/dist/commonjs/queryTypes.d.ts +272 -0
  172. package/dist/commonjs/queryTypes.d.ts.map +1 -0
  173. package/dist/commonjs/queryTypes.js +5 -0
  174. package/dist/commonjs/queryTypes.js.map +1 -0
  175. package/dist/commonjs/queryValidation.d.ts +6 -0
  176. package/dist/commonjs/queryValidation.d.ts.map +1 -0
  177. package/dist/commonjs/queryValidation.js +293 -0
  178. package/dist/commonjs/queryValidation.js.map +1 -0
  179. package/dist/commonjs/reactorTypes.d.ts +30 -0
  180. package/dist/commonjs/reactorTypes.d.ts.map +1 -0
  181. package/dist/commonjs/reactorTypes.js +3 -0
  182. package/dist/commonjs/reactorTypes.js.map +1 -0
  183. package/dist/commonjs/routeHandlerProtocol.d.ts +20 -0
  184. package/dist/commonjs/routeHandlerProtocol.d.ts.map +1 -0
  185. package/dist/commonjs/routeHandlerProtocol.js +3 -0
  186. package/dist/commonjs/routeHandlerProtocol.js.map +1 -0
  187. package/dist/commonjs/rulesTypes.d.ts +86 -0
  188. package/dist/commonjs/rulesTypes.d.ts.map +1 -0
  189. package/dist/commonjs/rulesTypes.js +3 -0
  190. package/dist/commonjs/rulesTypes.js.map +1 -0
  191. package/dist/commonjs/sanityCheckQueries.d.ts +19 -0
  192. package/dist/commonjs/sanityCheckQueries.d.ts.map +1 -0
  193. package/dist/commonjs/sanityCheckQueries.js +156 -0
  194. package/dist/commonjs/sanityCheckQueries.js.map +1 -0
  195. package/dist/commonjs/schema.d.ts +73 -0
  196. package/dist/commonjs/schema.d.ts.map +1 -0
  197. package/dist/commonjs/schema.js +132 -0
  198. package/dist/commonjs/schema.js.map +1 -0
  199. package/dist/commonjs/schemaTypes.d.ts +245 -0
  200. package/dist/commonjs/schemaTypes.d.ts.map +1 -0
  201. package/dist/commonjs/schemaTypes.js +116 -0
  202. package/dist/commonjs/schemaTypes.js.map +1 -0
  203. package/dist/commonjs/store.d.ts +90 -0
  204. package/dist/commonjs/store.d.ts.map +1 -0
  205. package/dist/commonjs/store.js +745 -0
  206. package/dist/commonjs/store.js.map +1 -0
  207. package/dist/commonjs/transactionValidation.d.ts +8 -0
  208. package/dist/commonjs/transactionValidation.d.ts.map +1 -0
  209. package/dist/commonjs/transactionValidation.js +137 -0
  210. package/dist/commonjs/transactionValidation.js.map +1 -0
  211. package/dist/commonjs/utils/Deferred.d.ts +9 -0
  212. package/dist/commonjs/utils/Deferred.d.ts.map +1 -0
  213. package/dist/commonjs/utils/Deferred.js +22 -0
  214. package/dist/commonjs/utils/Deferred.js.map +1 -0
  215. package/dist/commonjs/utils/PersistedObject.d.ts +81 -0
  216. package/dist/commonjs/utils/PersistedObject.d.ts.map +1 -0
  217. package/dist/commonjs/utils/PersistedObject.js +469 -0
  218. package/dist/commonjs/utils/PersistedObject.js.map +1 -0
  219. package/dist/commonjs/utils/dates.d.ts +2 -0
  220. package/dist/commonjs/utils/dates.d.ts.map +1 -0
  221. package/dist/commonjs/utils/dates.js +215 -0
  222. package/dist/commonjs/utils/dates.js.map +1 -0
  223. package/dist/commonjs/utils/error.d.ts +3 -0
  224. package/dist/commonjs/utils/error.d.ts.map +1 -0
  225. package/dist/commonjs/utils/error.js +13 -0
  226. package/dist/commonjs/utils/error.js.map +1 -0
  227. package/dist/commonjs/utils/fetch.d.ts +126 -0
  228. package/dist/commonjs/utils/fetch.d.ts.map +1 -0
  229. package/dist/commonjs/utils/fetch.js +37 -0
  230. package/dist/commonjs/utils/fetch.js.map +1 -0
  231. package/dist/commonjs/utils/flags.d.ts +5 -0
  232. package/dist/commonjs/utils/flags.d.ts.map +1 -0
  233. package/dist/commonjs/utils/flags.js +16 -0
  234. package/dist/commonjs/utils/flags.js.map +1 -0
  235. package/dist/commonjs/utils/id.d.ts +4 -0
  236. package/dist/commonjs/utils/id.d.ts.map +1 -0
  237. package/dist/commonjs/utils/id.js +29 -0
  238. package/dist/commonjs/utils/id.js.map +1 -0
  239. package/dist/commonjs/utils/linkIndex.d.ts +8 -0
  240. package/dist/commonjs/utils/linkIndex.d.ts.map +1 -0
  241. package/dist/commonjs/utils/linkIndex.js +21 -0
  242. package/dist/commonjs/utils/linkIndex.js.map +1 -0
  243. package/dist/commonjs/utils/log.d.ts +7 -0
  244. package/dist/commonjs/utils/log.d.ts.map +1 -0
  245. package/dist/commonjs/utils/log.js +17 -0
  246. package/dist/commonjs/utils/log.js.map +1 -0
  247. package/dist/commonjs/utils/object.d.ts +17 -0
  248. package/dist/commonjs/utils/object.d.ts.map +1 -0
  249. package/dist/commonjs/utils/object.js +157 -0
  250. package/dist/commonjs/utils/object.js.map +1 -0
  251. package/dist/commonjs/utils/pgtime.d.ts +198 -0
  252. package/dist/commonjs/utils/pgtime.d.ts.map +1 -0
  253. package/dist/commonjs/utils/pgtime.js +201 -0
  254. package/dist/commonjs/utils/pgtime.js.map +1 -0
  255. package/dist/commonjs/utils/pick.d.ts +2 -0
  256. package/dist/commonjs/utils/pick.d.ts.map +1 -0
  257. package/dist/commonjs/utils/pick.js +13 -0
  258. package/dist/commonjs/utils/pick.js.map +1 -0
  259. package/dist/commonjs/utils/strings.d.ts +2 -0
  260. package/dist/commonjs/utils/strings.d.ts.map +1 -0
  261. package/dist/commonjs/utils/strings.js +19 -0
  262. package/dist/commonjs/utils/strings.js.map +1 -0
  263. package/dist/commonjs/utils/weakHash.d.ts +16 -0
  264. package/dist/commonjs/utils/weakHash.d.ts.map +1 -0
  265. package/dist/commonjs/utils/weakHash.js +75 -0
  266. package/dist/commonjs/utils/weakHash.js.map +1 -0
  267. package/dist/commonjs/utils/weakHashLegacy.d.ts +8 -0
  268. package/dist/commonjs/utils/weakHashLegacy.d.ts.map +1 -0
  269. package/dist/commonjs/utils/weakHashLegacy.js +76 -0
  270. package/dist/commonjs/utils/weakHashLegacy.js.map +1 -0
  271. package/dist/commonjs/version.d.ts +3 -0
  272. package/dist/commonjs/version.d.ts.map +1 -0
  273. package/dist/commonjs/version.js +5 -0
  274. package/dist/commonjs/version.js.map +1 -0
  275. package/dist/commonjs/warningToggle.d.ts +3 -0
  276. package/dist/commonjs/warningToggle.d.ts.map +1 -0
  277. package/dist/commonjs/warningToggle.js +9 -0
  278. package/dist/commonjs/warningToggle.js.map +1 -0
  279. package/dist/esm/Connection.d.ts +93 -0
  280. package/dist/esm/Connection.d.ts.map +1 -0
  281. package/dist/esm/Connection.js +189 -0
  282. package/dist/esm/Connection.js.map +1 -0
  283. package/dist/esm/InMemoryStorage.d.ts +11 -0
  284. package/dist/esm/InMemoryStorage.d.ts.map +1 -0
  285. package/dist/esm/InMemoryStorage.js +26 -0
  286. package/dist/esm/InMemoryStorage.js.map +1 -0
  287. package/dist/esm/IndexedDBStorage.d.ts +18 -0
  288. package/dist/esm/IndexedDBStorage.d.ts.map +1 -0
  289. package/dist/esm/IndexedDBStorage.js +338 -0
  290. package/dist/esm/IndexedDBStorage.js.map +1 -0
  291. package/dist/esm/InstantError.d.ts +7 -0
  292. package/dist/esm/InstantError.d.ts.map +1 -0
  293. package/dist/esm/InstantError.js +24 -0
  294. package/dist/esm/InstantError.js.map +1 -0
  295. package/dist/esm/Reactor.d.ts +445 -0
  296. package/dist/esm/Reactor.d.ts.map +1 -0
  297. package/dist/esm/Reactor.js +2431 -0
  298. package/dist/esm/Reactor.js.map +1 -0
  299. package/dist/esm/StorageAPI.d.ts +40 -0
  300. package/dist/esm/StorageAPI.d.ts.map +1 -0
  301. package/dist/esm/StorageAPI.js +75 -0
  302. package/dist/esm/StorageAPI.js.map +1 -0
  303. package/dist/esm/Stream.d.ts +121 -0
  304. package/dist/esm/Stream.d.ts.map +1 -0
  305. package/dist/esm/Stream.js +812 -0
  306. package/dist/esm/Stream.js.map +1 -0
  307. package/dist/esm/SyncTable.d.ts +145 -0
  308. package/dist/esm/SyncTable.d.ts.map +1 -0
  309. package/dist/esm/SyncTable.js +524 -0
  310. package/dist/esm/SyncTable.js.map +1 -0
  311. package/dist/esm/WindowNetworkListener.d.ts +5 -0
  312. package/dist/esm/WindowNetworkListener.d.ts.map +1 -0
  313. package/dist/esm/WindowNetworkListener.js +20 -0
  314. package/dist/esm/WindowNetworkListener.js.map +1 -0
  315. package/dist/esm/__types__/fieldsTypeTest.d.ts +2 -0
  316. package/dist/esm/__types__/fieldsTypeTest.d.ts.map +1 -0
  317. package/dist/esm/__types__/fieldsTypeTest.js +66 -0
  318. package/dist/esm/__types__/fieldsTypeTest.js.map +1 -0
  319. package/dist/esm/__types__/typeUtils.d.ts +20 -0
  320. package/dist/esm/__types__/typeUtils.d.ts.map +1 -0
  321. package/dist/esm/__types__/typeUtils.js +4 -0
  322. package/dist/esm/__types__/typeUtils.js.map +1 -0
  323. package/dist/esm/__types__/useDatesTypeTest.d.ts +2 -0
  324. package/dist/esm/__types__/useDatesTypeTest.d.ts.map +1 -0
  325. package/dist/esm/__types__/useDatesTypeTest.js +53 -0
  326. package/dist/esm/__types__/useDatesTypeTest.js.map +1 -0
  327. package/dist/esm/attrTypes.d.ts +26 -0
  328. package/dist/esm/attrTypes.d.ts.map +1 -0
  329. package/dist/esm/attrTypes.js +2 -0
  330. package/dist/esm/attrTypes.js.map +1 -0
  331. package/dist/esm/authAPI.d.ts +65 -0
  332. package/dist/esm/authAPI.d.ts.map +1 -0
  333. package/dist/esm/authAPI.js +104 -0
  334. package/dist/esm/authAPI.js.map +1 -0
  335. package/dist/esm/clientTypes.d.ts +41 -0
  336. package/dist/esm/clientTypes.d.ts.map +1 -0
  337. package/dist/esm/clientTypes.js +2 -0
  338. package/dist/esm/clientTypes.js.map +1 -0
  339. package/dist/esm/coreTypes.d.ts +34 -0
  340. package/dist/esm/coreTypes.d.ts.map +1 -0
  341. package/dist/esm/coreTypes.js +2 -0
  342. package/dist/esm/coreTypes.js.map +1 -0
  343. package/dist/esm/createRouteHandler.d.ts +8 -0
  344. package/dist/esm/createRouteHandler.d.ts.map +1 -0
  345. package/dist/esm/createRouteHandler.js +52 -0
  346. package/dist/esm/createRouteHandler.js.map +1 -0
  347. package/dist/esm/datalog.d.ts +8 -0
  348. package/dist/esm/datalog.d.ts.map +1 -0
  349. package/dist/esm/datalog.js +100 -0
  350. package/dist/esm/datalog.js.map +1 -0
  351. package/dist/esm/devtool.d.ts +4 -0
  352. package/dist/esm/devtool.d.ts.map +1 -0
  353. package/dist/esm/devtool.js +154 -0
  354. package/dist/esm/devtool.js.map +1 -0
  355. package/dist/esm/endpoints.d.ts +35 -0
  356. package/dist/esm/endpoints.d.ts.map +1 -0
  357. package/dist/esm/endpoints.js +73 -0
  358. package/dist/esm/endpoints.js.map +1 -0
  359. package/dist/esm/framework.d.ts +81 -0
  360. package/dist/esm/framework.d.ts.map +1 -0
  361. package/dist/esm/framework.js +244 -0
  362. package/dist/esm/framework.js.map +1 -0
  363. package/dist/esm/helperTypes.d.ts +76 -0
  364. package/dist/esm/helperTypes.d.ts.map +1 -0
  365. package/dist/esm/helperTypes.js +2 -0
  366. package/dist/esm/helperTypes.js.map +1 -0
  367. package/dist/esm/index.d.ts +614 -0
  368. package/dist/esm/index.d.ts.map +1 -0
  369. package/dist/esm/index.js +655 -0
  370. package/dist/esm/index.js.map +1 -0
  371. package/dist/esm/infiniteQuery.d.ts +26 -0
  372. package/dist/esm/infiniteQuery.d.ts.map +1 -0
  373. package/dist/esm/infiniteQuery.js +433 -0
  374. package/dist/esm/infiniteQuery.js.map +1 -0
  375. package/dist/esm/instaml.d.ts +18 -0
  376. package/dist/esm/instaml.d.ts.map +1 -0
  377. package/dist/esm/instaml.js +577 -0
  378. package/dist/esm/instaml.js.map +1 -0
  379. package/dist/esm/instaql.d.ts +13 -0
  380. package/dist/esm/instaql.d.ts.map +1 -0
  381. package/dist/esm/instaql.js +633 -0
  382. package/dist/esm/instaql.js.map +1 -0
  383. package/dist/esm/instatx.d.ts +128 -0
  384. package/dist/esm/instatx.d.ts.map +1 -0
  385. package/dist/esm/instatx.js +94 -0
  386. package/dist/esm/instatx.js.map +1 -0
  387. package/dist/esm/model/instaqlResult.d.ts +8 -0
  388. package/dist/esm/model/instaqlResult.d.ts.map +1 -0
  389. package/dist/esm/model/instaqlResult.js +25 -0
  390. package/dist/esm/model/instaqlResult.js.map +1 -0
  391. package/dist/esm/notifyScope.d.ts +32 -0
  392. package/dist/esm/notifyScope.d.ts.map +1 -0
  393. package/dist/esm/notifyScope.js +300 -0
  394. package/dist/esm/notifyScope.js.map +1 -0
  395. package/dist/esm/package.json +3 -0
  396. package/dist/esm/parseSchemaFromJSON.d.ts +3 -0
  397. package/dist/esm/parseSchemaFromJSON.d.ts.map +1 -0
  398. package/dist/esm/parseSchemaFromJSON.js +143 -0
  399. package/dist/esm/parseSchemaFromJSON.js.map +1 -0
  400. package/dist/esm/presence.d.ts +51 -0
  401. package/dist/esm/presence.d.ts.map +1 -0
  402. package/dist/esm/presence.js +51 -0
  403. package/dist/esm/presence.js.map +1 -0
  404. package/dist/esm/presenceTypes.d.ts +10 -0
  405. package/dist/esm/presenceTypes.d.ts.map +1 -0
  406. package/dist/esm/presenceTypes.js +4 -0
  407. package/dist/esm/presenceTypes.js.map +1 -0
  408. package/dist/esm/queryTypes.d.ts +272 -0
  409. package/dist/esm/queryTypes.d.ts.map +1 -0
  410. package/dist/esm/queryTypes.js +4 -0
  411. package/dist/esm/queryTypes.js.map +1 -0
  412. package/dist/esm/queryValidation.d.ts +6 -0
  413. package/dist/esm/queryValidation.d.ts.map +1 -0
  414. package/dist/esm/queryValidation.js +288 -0
  415. package/dist/esm/queryValidation.js.map +1 -0
  416. package/dist/esm/reactorTypes.d.ts +30 -0
  417. package/dist/esm/reactorTypes.d.ts.map +1 -0
  418. package/dist/esm/reactorTypes.js +2 -0
  419. package/dist/esm/reactorTypes.js.map +1 -0
  420. package/dist/esm/routeHandlerProtocol.d.ts +20 -0
  421. package/dist/esm/routeHandlerProtocol.d.ts.map +1 -0
  422. package/dist/esm/routeHandlerProtocol.js +2 -0
  423. package/dist/esm/routeHandlerProtocol.js.map +1 -0
  424. package/dist/esm/rulesTypes.d.ts +86 -0
  425. package/dist/esm/rulesTypes.d.ts.map +1 -0
  426. package/dist/esm/rulesTypes.js +2 -0
  427. package/dist/esm/rulesTypes.js.map +1 -0
  428. package/dist/esm/sanityCheckQueries.d.ts +19 -0
  429. package/dist/esm/sanityCheckQueries.d.ts.map +1 -0
  430. package/dist/esm/sanityCheckQueries.js +153 -0
  431. package/dist/esm/sanityCheckQueries.js.map +1 -0
  432. package/dist/esm/schema.d.ts +73 -0
  433. package/dist/esm/schema.d.ts.map +1 -0
  434. package/dist/esm/schema.js +129 -0
  435. package/dist/esm/schema.js.map +1 -0
  436. package/dist/esm/schemaTypes.d.ts +245 -0
  437. package/dist/esm/schemaTypes.d.ts.map +1 -0
  438. package/dist/esm/schemaTypes.js +107 -0
  439. package/dist/esm/schemaTypes.js.map +1 -0
  440. package/dist/esm/store.d.ts +90 -0
  441. package/dist/esm/store.d.ts.map +1 -0
  442. package/dist/esm/store.js +723 -0
  443. package/dist/esm/store.js.map +1 -0
  444. package/dist/esm/transactionValidation.d.ts +8 -0
  445. package/dist/esm/transactionValidation.d.ts.map +1 -0
  446. package/dist/esm/transactionValidation.js +131 -0
  447. package/dist/esm/transactionValidation.js.map +1 -0
  448. package/dist/esm/utils/Deferred.d.ts +9 -0
  449. package/dist/esm/utils/Deferred.d.ts.map +1 -0
  450. package/dist/esm/utils/Deferred.js +18 -0
  451. package/dist/esm/utils/Deferred.js.map +1 -0
  452. package/dist/esm/utils/PersistedObject.d.ts +81 -0
  453. package/dist/esm/utils/PersistedObject.d.ts.map +1 -0
  454. package/dist/esm/utils/PersistedObject.js +464 -0
  455. package/dist/esm/utils/PersistedObject.js.map +1 -0
  456. package/dist/esm/utils/dates.d.ts +2 -0
  457. package/dist/esm/utils/dates.d.ts.map +1 -0
  458. package/dist/esm/utils/dates.js +212 -0
  459. package/dist/esm/utils/dates.js.map +1 -0
  460. package/dist/esm/utils/error.d.ts +3 -0
  461. package/dist/esm/utils/error.d.ts.map +1 -0
  462. package/dist/esm/utils/error.js +9 -0
  463. package/dist/esm/utils/error.js.map +1 -0
  464. package/dist/esm/utils/fetch.d.ts +126 -0
  465. package/dist/esm/utils/fetch.d.ts.map +1 -0
  466. package/dist/esm/utils/fetch.js +32 -0
  467. package/dist/esm/utils/fetch.js.map +1 -0
  468. package/dist/esm/utils/flags.d.ts +5 -0
  469. package/dist/esm/utils/flags.d.ts.map +1 -0
  470. package/dist/esm/utils/flags.js +11 -0
  471. package/dist/esm/utils/flags.js.map +1 -0
  472. package/dist/esm/utils/id.d.ts +4 -0
  473. package/dist/esm/utils/id.d.ts.map +1 -0
  474. package/dist/esm/utils/id.js +26 -0
  475. package/dist/esm/utils/id.js.map +1 -0
  476. package/dist/esm/utils/linkIndex.d.ts +8 -0
  477. package/dist/esm/utils/linkIndex.d.ts.map +1 -0
  478. package/dist/esm/utils/linkIndex.js +18 -0
  479. package/dist/esm/utils/linkIndex.js.map +1 -0
  480. package/dist/esm/utils/log.d.ts +7 -0
  481. package/dist/esm/utils/log.d.ts.map +1 -0
  482. package/dist/esm/utils/log.js +14 -0
  483. package/dist/esm/utils/log.js.map +1 -0
  484. package/dist/esm/utils/object.d.ts +17 -0
  485. package/dist/esm/utils/object.d.ts.map +1 -0
  486. package/dist/esm/utils/object.js +144 -0
  487. package/dist/esm/utils/object.js.map +1 -0
  488. package/dist/esm/utils/pgtime.d.ts +198 -0
  489. package/dist/esm/utils/pgtime.d.ts.map +1 -0
  490. package/dist/esm/utils/pgtime.js +198 -0
  491. package/dist/esm/utils/pgtime.js.map +1 -0
  492. package/dist/esm/utils/pick.d.ts +2 -0
  493. package/dist/esm/utils/pick.d.ts.map +1 -0
  494. package/dist/esm/utils/pick.js +10 -0
  495. package/dist/esm/utils/pick.js.map +1 -0
  496. package/dist/esm/utils/strings.d.ts +2 -0
  497. package/dist/esm/utils/strings.d.ts.map +1 -0
  498. package/dist/esm/utils/strings.js +16 -0
  499. package/dist/esm/utils/strings.js.map +1 -0
  500. package/dist/esm/utils/weakHash.d.ts +16 -0
  501. package/dist/esm/utils/weakHash.d.ts.map +1 -0
  502. package/dist/esm/utils/weakHash.js +72 -0
  503. package/dist/esm/utils/weakHash.js.map +1 -0
  504. package/dist/esm/utils/weakHashLegacy.d.ts +8 -0
  505. package/dist/esm/utils/weakHashLegacy.d.ts.map +1 -0
  506. package/dist/esm/utils/weakHashLegacy.js +73 -0
  507. package/dist/esm/utils/weakHashLegacy.js.map +1 -0
  508. package/dist/esm/version.d.ts +3 -0
  509. package/dist/esm/version.d.ts.map +1 -0
  510. package/dist/esm/version.js +3 -0
  511. package/dist/esm/version.js.map +1 -0
  512. package/dist/esm/warningToggle.d.ts +3 -0
  513. package/dist/esm/warningToggle.d.ts.map +1 -0
  514. package/dist/esm/warningToggle.js +5 -0
  515. package/dist/esm/warningToggle.js.map +1 -0
  516. package/dist/standalone/index.js +8740 -0
  517. package/dist/standalone/index.umd.cjs +7 -0
  518. package/package.json +81 -3
  519. package/src/Connection.ts +277 -0
  520. package/src/InMemoryStorage.ts +34 -0
  521. package/src/IndexedDBStorage.ts +387 -0
  522. package/src/InstantError.ts +28 -0
  523. package/src/Reactor.js +2921 -0
  524. package/src/StorageAPI.ts +156 -0
  525. package/src/Stream.ts +1164 -0
  526. package/src/SyncTable.ts +919 -0
  527. package/src/WindowNetworkListener.js +19 -0
  528. package/src/__types__/fieldsTypeTest.ts +113 -0
  529. package/src/__types__/typeUtils.ts +39 -0
  530. package/src/__types__/useDatesTypeTest.ts +69 -0
  531. package/src/attrTypes.ts +29 -0
  532. package/src/authAPI.ts +205 -0
  533. package/src/clientTypes.ts +28 -0
  534. package/src/coreTypes.ts +58 -0
  535. package/src/createRouteHandler.ts +66 -0
  536. package/src/datalog.js +116 -0
  537. package/src/devtool.ts +186 -0
  538. package/src/endpoints.ts +101 -0
  539. package/src/framework.ts +395 -0
  540. package/src/helperTypes.ts +115 -0
  541. package/src/index.ts +1283 -0
  542. package/src/infiniteQuery.ts +602 -0
  543. package/src/instaml.ts +714 -0
  544. package/src/instaql.ts +952 -0
  545. package/src/instatx.ts +265 -0
  546. package/src/model/instaqlResult.js +25 -0
  547. package/src/notifyScope.ts +343 -0
  548. package/src/parseSchemaFromJSON.ts +176 -0
  549. package/src/presence.ts +123 -0
  550. package/src/presenceTypes.ts +19 -0
  551. package/src/queryTypes.ts +721 -0
  552. package/src/queryValidation.ts +535 -0
  553. package/src/reactorTypes.ts +33 -0
  554. package/src/routeHandlerProtocol.ts +24 -0
  555. package/src/rulesTypes.ts +122 -0
  556. package/src/sanityCheckQueries.ts +189 -0
  557. package/src/schema.ts +194 -0
  558. package/src/schemaTypes.ts +642 -0
  559. package/src/store.ts +949 -0
  560. package/src/transactionValidation.ts +204 -0
  561. package/src/utils/Deferred.ts +20 -0
  562. package/src/utils/PersistedObject.ts +589 -0
  563. package/src/utils/dates.ts +258 -0
  564. package/src/utils/error.ts +9 -0
  565. package/src/utils/fetch.ts +129 -0
  566. package/src/utils/flags.ts +14 -0
  567. package/src/utils/id.ts +28 -0
  568. package/src/utils/linkIndex.ts +33 -0
  569. package/src/utils/log.ts +23 -0
  570. package/src/utils/object.js +176 -0
  571. package/src/utils/pgtime.ts +199 -0
  572. package/src/utils/pick.js +9 -0
  573. package/src/utils/strings.ts +19 -0
  574. package/src/utils/weakHash.ts +77 -0
  575. package/src/utils/weakHashLegacy.ts +75 -0
  576. package/src/version.ts +3 -0
  577. package/src/warningToggle.ts +5 -0
  578. package/tsconfig.cjs.dev.json +15 -0
  579. package/tsconfig.dev.json +14 -0
  580. package/tsconfig.json +13 -0
  581. package/tsconfig.test.json +5 -0
  582. package/vite.config.ts +19 -0
  583. package/vitest.config.ts +75 -0
@@ -0,0 +1,2471 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.COOKIE_SYNC_LAST_UPDATED_KEY = exports.STATUS = void 0;
40
+ // @ts-check
41
+ const weakHash_ts_1 = __importDefault(require("./utils/weakHash.js"));
42
+ const weakHashLegacy_ts_1 = __importDefault(require("./utils/weakHashLegacy.js"));
43
+ const instaql_ts_1 = __importDefault(require("./instaql.js"));
44
+ const instaml = __importStar(require("./instaml.js"));
45
+ const s = __importStar(require("./store.js"));
46
+ const id_ts_1 = __importDefault(require("./utils/id.js"));
47
+ const IndexedDBStorage_ts_1 = __importDefault(require("./IndexedDBStorage.js"));
48
+ const WindowNetworkListener_js_1 = __importDefault(require("./WindowNetworkListener.js"));
49
+ const authAPI = __importStar(require("./authAPI.js"));
50
+ const StorageApi = __importStar(require("./StorageAPI.js"));
51
+ const flags = __importStar(require("./utils/flags.js"));
52
+ const presence_ts_1 = require("./presence.js");
53
+ const Deferred_ts_1 = require("./utils/Deferred.js");
54
+ const PersistedObject_ts_1 = require("./utils/PersistedObject.js");
55
+ const instaqlResult_js_1 = require("./model/instaqlResult.js");
56
+ const object_js_1 = require("./utils/object.js");
57
+ const linkIndex_ts_1 = require("./utils/linkIndex.js");
58
+ const version_ts_1 = __importDefault(require("./version.js"));
59
+ const mutative_1 = require("mutative");
60
+ const log_ts_1 = __importDefault(require("./utils/log.js"));
61
+ const queryValidation_ts_1 = require("./queryValidation.js");
62
+ const transactionValidation_ts_1 = require("./transactionValidation.js");
63
+ const notifyScope_ts_1 = require("./notifyScope.js");
64
+ const InstantError_ts_1 = require("./InstantError.js");
65
+ const fetch_ts_1 = require("./utils/fetch.js");
66
+ const uuid_1 = require("uuid");
67
+ const Connection_ts_1 = require("./Connection.js");
68
+ const SyncTable_ts_1 = require("./SyncTable.js");
69
+ const Stream_ts_1 = require("./Stream.js");
70
+ /** @typedef {import('./utils/log.ts').Logger} Logger */
71
+ /** @typedef {import('./Connection.ts').Connection} Connection */
72
+ /** @typedef {import('./Connection.ts').TransportType} TransportType */
73
+ /** @typedef {import('./Connection.ts').EventSourceConstructor} EventSourceConstructor */
74
+ /** @typedef {import('./reactorTypes.ts').QuerySub} QuerySub */
75
+ /** @typedef {import('./reactorTypes.ts').QuerySubInStorage} QuerySubInStorage */
76
+ /** @typedef {import('./clientTypes.ts').User} User */
77
+ /** @typedef {import('./clientTypes.ts').AuthState} AuthState */
78
+ /** @typedef {import('./framework.ts').FrameworkClient} FrameworkClient */
79
+ exports.STATUS = {
80
+ CONNECTING: 'connecting',
81
+ OPENED: 'opened',
82
+ AUTHENTICATED: 'authenticated',
83
+ CLOSED: 'closed',
84
+ ERRORED: 'errored',
85
+ };
86
+ const QUERY_ONCE_TIMEOUT = 30_000;
87
+ const PENDING_TX_CLEANUP_TIMEOUT = 30_000;
88
+ const PENDING_MUTATION_CLEANUP_THRESHOLD = 200;
89
+ const ONE_MIN_MS = 1_000 * 60;
90
+ const ONE_DAY_MS = ONE_MIN_MS * 60 * 24;
91
+ exports.COOKIE_SYNC_LAST_UPDATED_KEY = 'lastSyncedUserCookie';
92
+ // Param that the backend adds if this is an oauth redirect
93
+ const OAUTH_REDIRECT_PARAM = '_instant_oauth_redirect';
94
+ const OAUTH_EXTRA_FIELDS_ID_PARAM = '_instant_extra_fields_id';
95
+ const oauthExtraFieldsKey = 'oauthExtraFields';
96
+ const currentUserKey = `currentUser`;
97
+ /**
98
+ * @param {Object} config
99
+ * @param {TransportType} config.transportType
100
+ * @param {string} config.appId
101
+ * @param {string} config.apiURI
102
+ * @param {string} config.wsURI
103
+ * @param {EventSourceConstructor} config.EventSourceImpl
104
+ * @returns {WSConnection | SSEConnection}
105
+ */
106
+ function createTransport({ transportType, appId, apiURI, wsURI, EventSourceImpl, }) {
107
+ if (!EventSourceImpl) {
108
+ return new Connection_ts_1.WSConnection(`${wsURI}?app_id=${appId}`);
109
+ }
110
+ switch (transportType) {
111
+ case 'ws':
112
+ return new Connection_ts_1.WSConnection(`${wsURI}?app_id=${appId}`);
113
+ case 'sse':
114
+ return new Connection_ts_1.SSEConnection(EventSourceImpl, `${apiURI}/runtime/sse?app_id=${appId}`);
115
+ default:
116
+ throw new Error('Unknown transport type ' + transportType);
117
+ }
118
+ }
119
+ function isClient() {
120
+ const hasWindow = typeof window !== 'undefined';
121
+ // this checks if we are running in a chrome extension
122
+ // @ts-expect-error
123
+ const isChrome = typeof chrome !== 'undefined';
124
+ return hasWindow || isChrome;
125
+ }
126
+ const ignoreLogging = {
127
+ 'set-presence': true,
128
+ 'set-presence-ok': true,
129
+ 'refresh-presence': true,
130
+ 'patch-presence': true,
131
+ };
132
+ /**
133
+ * @param {QuerySubInStorage} x
134
+ * @param {boolean | null} useDateObjects
135
+ * @returns {QuerySub}
136
+ */
137
+ function querySubFromStorage(x, useDateObjects) {
138
+ const v = typeof x === 'string' ? JSON.parse(x) : x;
139
+ if (v?.result?.store) {
140
+ const attrsStore = s.attrsStoreFromJSON(v.result.attrsStore, v.result.store);
141
+ if (attrsStore) {
142
+ const storeJSON = v.result.store;
143
+ v.result.store = s.fromJSON(attrsStore, {
144
+ ...storeJSON,
145
+ useDateObjects: useDateObjects,
146
+ });
147
+ v.result.attrsStore = attrsStore;
148
+ }
149
+ }
150
+ return v;
151
+ }
152
+ /**
153
+ *
154
+ * @param {string} _key
155
+ * @param {QuerySub} sub
156
+ * @returns QuerySubInStorage
157
+ */
158
+ function querySubToStorage(_key, sub) {
159
+ const { result, ...rest } = sub;
160
+ const jsonSub = /** @type {import('./reactorTypes.ts').QuerySubInStorage} */ (rest);
161
+ if (result) {
162
+ /** @type {import('./reactorTypes.ts').QuerySubResultInStorage} */
163
+ const jsonResult = {
164
+ ...result,
165
+ store: s.toJSON(result.store),
166
+ attrsStore: result.attrsStore.toJSON(),
167
+ };
168
+ jsonSub.result = jsonResult;
169
+ }
170
+ return jsonSub;
171
+ }
172
+ function kvFromStorage(key, x) {
173
+ switch (key) {
174
+ case 'pendingMutations':
175
+ return new Map(typeof x === 'string' ? JSON.parse(x) : x);
176
+ default:
177
+ return x;
178
+ }
179
+ }
180
+ function kvToStorage(key, x) {
181
+ switch (key) {
182
+ case 'pendingMutations':
183
+ return [...x.entries()];
184
+ default:
185
+ return x;
186
+ }
187
+ }
188
+ function onMergeQuerySub(_k, storageSub, inMemorySub) {
189
+ const storageResult = storageSub?.result;
190
+ const memoryResult = inMemorySub?.result;
191
+ if (storageResult && !memoryResult && inMemorySub) {
192
+ inMemorySub.result = storageResult;
193
+ }
194
+ return inMemorySub || storageSub;
195
+ }
196
+ function sortedMutationEntries(entries) {
197
+ return [...entries].sort((a, b) => {
198
+ const [ka, muta] = a;
199
+ const [kb, mutb] = b;
200
+ const a_order = muta.order || 0;
201
+ const b_order = mutb.order || 0;
202
+ if (a_order == b_order) {
203
+ return ka < kb ? -1 : ka > kb ? 1 : 0;
204
+ }
205
+ return a_order - b_order;
206
+ });
207
+ }
208
+ /**
209
+ * @template {import('./presence.ts').RoomSchemaShape} [RoomSchema = {}]
210
+ */
211
+ class Reactor {
212
+ /** @type {s.AttrsStore | undefined} */
213
+ attrs;
214
+ _isOnline = true;
215
+ _isShutdown = false;
216
+ status = exports.STATUS.CONNECTING;
217
+ /** @type {PersistedObject<string, QuerySub, QuerySubInStorage>} */
218
+ querySubs;
219
+ /** @type {PersistedObject} */
220
+ kv;
221
+ /** @type {SyncTable} */
222
+ _syncTable;
223
+ /** @type {InstantStream} */
224
+ _instantStream;
225
+ /** @type {Record<string, Array<{ q: any, cb: (data: any) => any }>>} */
226
+ queryCbs = {};
227
+ /** @type {Record<string, Array<{ q: any, eventId: string, dfd: Deferred }>>} */
228
+ queryOnceDfds = {};
229
+ authCbs = [];
230
+ attrsCbs = [];
231
+ mutationErrorCbs = [];
232
+ connectionStatusCbs = [];
233
+ appStatusCbs = [];
234
+ /**
235
+ * Carries the raw server status off the public type: `disabled` is an
236
+ * operator-level state we don't surface to apps.
237
+ * @type {import('./clientTypes.ts').AppStatusState & { status?: 'active' | 'read-only' | 'disabled' }}
238
+ */
239
+ _appStatusState = { isLoading: true, isReadOnly: undefined };
240
+ config;
241
+ mutationDeferredStore = new Map();
242
+ _reconnectTimeoutId = null;
243
+ _reconnectTimeoutMs = 0;
244
+ /** @type {Connection} */
245
+ _transport;
246
+ /** @type {TransportType} */
247
+ _transportType = 'ws';
248
+ /** @type {EventSourceConstructor} */
249
+ _EventSource;
250
+ /** @type {boolean | null} */
251
+ _wsOk = null;
252
+ _localIdPromises = {};
253
+ _errorMessage = null;
254
+ /** @type {Promise<null | {error: {message: string}}> | null}**/
255
+ _oauthCallbackResponse = null;
256
+ /** @type {null | import('./utils/linkIndex.ts').LinkIndex}} */
257
+ _linkIndex = null;
258
+ /** @type BroadcastChannel | undefined */
259
+ _broadcastChannel;
260
+ /** @type {Record<string, {roomType: string; isConnected: boolean; error: any}>} */
261
+ _rooms = {};
262
+ /** @type {Record<string, boolean>} */
263
+ _roomsPendingLeave = {};
264
+ _presence = {};
265
+ _broadcastQueue = [];
266
+ _broadcastSubs = {};
267
+ /** @type {{isLoading: boolean; error: any | undefined, user: any | undefined}} */
268
+ _currentUserCached = { isLoading: true, error: undefined, user: undefined };
269
+ _beforeUnloadCbs = [];
270
+ _dataForQueryCache = {};
271
+ // Memoises dataForQuery between notifies. Separate from _dataForQueryCache,
272
+ // which notifyOne uses as its last-notified value for deduping.
273
+ _dataForQueryMemo = {};
274
+ /** @type {Logger} */
275
+ _log;
276
+ _pendingTxCleanupTimeout;
277
+ _pendingMutationCleanupThreshold;
278
+ _inFlightMutationEventIds = new Set();
279
+ /** @type FrameworkClient | null */
280
+ _frameworkClient = null;
281
+ /**
282
+ * When false, a local write notifies every query rather than only the ones
283
+ * its footprint can affect. Used by tests to compare the two.
284
+ */
285
+ _scopedNotify = true;
286
+ /** @type {Map<string, {q: any, attrs: any, fp: import('./notifyScope.ts').QueryFootprint | null}>} */
287
+ _queryFootprints = new Map();
288
+ constructor(config, Storage = IndexedDBStorage_ts_1.default, NetworkListener = WindowNetworkListener_js_1.default, versions, EventSourceConstructor) {
289
+ this._EventSource = EventSourceConstructor;
290
+ this.config = { ...config };
291
+ this.queryCacheLimit = this.config.queryCacheLimit ?? 10;
292
+ this._pendingTxCleanupTimeout =
293
+ this.config.pendingTxCleanupTimeout ?? PENDING_TX_CLEANUP_TIMEOUT;
294
+ this._pendingMutationCleanupThreshold =
295
+ this.config.pendingMutationCleanupThreshold ??
296
+ PENDING_MUTATION_CLEANUP_THRESHOLD;
297
+ this._log = (0, log_ts_1.default)(config.verbose || flags.devBackend || flags.instantLogs, () => this._reactorStats(), config.logger);
298
+ this.versions = { ...(versions || {}), '@instantdb/core': version_ts_1.default };
299
+ if (this.config.schema) {
300
+ this._linkIndex = (0, linkIndex_ts_1.createLinkIndex)(this.config.schema);
301
+ }
302
+ // This is to protect us against running
303
+ // server-side.
304
+ if (!isClient()) {
305
+ return;
306
+ }
307
+ if (!config.appId) {
308
+ throw new Error('SidekickDB must be initialized with an appId.');
309
+ }
310
+ if (!(0, uuid_1.validate)(config.appId)) {
311
+ throw new Error(`SidekickDB must be initialized with a valid appId. \`${config.appId}\` is not a valid uuid.`);
312
+ }
313
+ if (typeof BroadcastChannel === 'function') {
314
+ this._broadcastChannel = new BroadcastChannel('@instantdb');
315
+ this._broadcastChannel.addEventListener('message', async (e) => {
316
+ try {
317
+ if (e.data?.type === 'auth') {
318
+ const res = await this.getCurrentUser({
319
+ forceReadFromStorage: true,
320
+ });
321
+ await this.updateUser(res.user).catch((error) => {
322
+ this._log.error('[error] update user', error);
323
+ });
324
+ }
325
+ }
326
+ catch (e) {
327
+ this._log.error('[error] handle broadcast channel', e);
328
+ }
329
+ });
330
+ }
331
+ this._initStorage(Storage);
332
+ this._syncTable = new SyncTable_ts_1.SyncTable(this._trySendAuthed.bind(this), new Storage(this.config.appId, 'syncSubs'), {
333
+ useDateObjects: this.config.useDateObjects,
334
+ }, this._log, (triples) => {
335
+ return s.createStore(this.ensureAttrs(), triples, this.config.enableCardinalityInference, this.config.useDateObjects);
336
+ }, () => this.ensureAttrs());
337
+ this._instantStream = new Stream_ts_1.InstantStream({
338
+ WStream: this.config.WritableStream || WritableStream,
339
+ RStream: this.config.ReadableStream || ReadableStream,
340
+ trySend: this._trySendAuthed.bind(this),
341
+ log: this._log,
342
+ });
343
+ this._oauthCallbackResponse = this._oauthLoginInit();
344
+ this.setupUserSyncTimer();
345
+ NetworkListener.getIsOnline().then((isOnline) => {
346
+ this._isOnline = isOnline;
347
+ this._startSocket();
348
+ NetworkListener.listen((isOnline) => {
349
+ // We do this because react native's NetInfo
350
+ // fires multiple online events.
351
+ // We only want to handle one state change
352
+ if (isOnline === this._isOnline) {
353
+ return;
354
+ }
355
+ this._log.info('[network] online =', isOnline);
356
+ this._isOnline = isOnline;
357
+ if (this._isOnline) {
358
+ this._startSocket();
359
+ }
360
+ else {
361
+ this._log.info('Changing status from', this.status, 'to', exports.STATUS.CLOSED);
362
+ this._setStatus(exports.STATUS.CLOSED);
363
+ }
364
+ });
365
+ });
366
+ if (typeof addEventListener !== 'undefined') {
367
+ this._beforeUnload = this._beforeUnload.bind(this);
368
+ addEventListener('beforeunload', this._beforeUnload);
369
+ }
370
+ }
371
+ getFrameworkClient() {
372
+ return this._frameworkClient;
373
+ }
374
+ /** @param {FrameworkClient} client */
375
+ setFrameworkClient(client) {
376
+ this._frameworkClient = client;
377
+ }
378
+ ensureAttrs() {
379
+ if (!this.attrs) {
380
+ throw new Error('attrs have not loaded.');
381
+ }
382
+ return this.attrs;
383
+ }
384
+ updateSchema(schema) {
385
+ this.config = {
386
+ ...this.config,
387
+ schema: schema,
388
+ cardinalityInference: Boolean(schema),
389
+ };
390
+ this._linkIndex = schema ? (0, linkIndex_ts_1.createLinkIndex)(this.config.schema) : null;
391
+ }
392
+ _reactorStats() {
393
+ return {
394
+ inFlightMutationCount: this._inFlightMutationEventIds.size,
395
+ storedMutationCount: this._pendingMutations().size,
396
+ transportType: this._transportType,
397
+ };
398
+ }
399
+ _onQuerySubLoaded(hash) {
400
+ this.kv
401
+ .waitForKeyToLoad('pendingMutations')
402
+ .then(() => this.notifyOne(hash));
403
+ }
404
+ _initStorage(Storage) {
405
+ this.querySubs = new PersistedObject_ts_1.PersistedObject({
406
+ persister: new Storage(this.config.appId, 'querySubs'),
407
+ merge: onMergeQuerySub,
408
+ serialize: querySubToStorage,
409
+ parse: (_key, x) => querySubFromStorage(x, this.config.useDateObjects),
410
+ // objectSize
411
+ objectSize: (x) => x?.result?.store?.triples?.length ?? 0,
412
+ logger: this._log,
413
+ preloadEntryCount: 10,
414
+ gc: {
415
+ maxAgeMs: 1000 * 60 * 60 * 24 * 7 * 52, // 1 year
416
+ maxEntries: 1000,
417
+ // Size of each query is the number of triples
418
+ maxSize: 1_000_000, // 1 million triples
419
+ },
420
+ });
421
+ this.querySubs.onKeyLoaded = (k) => this._onQuerySubLoaded(k);
422
+ this.kv = new PersistedObject_ts_1.PersistedObject({
423
+ persister: new Storage(this.config.appId, 'kv'),
424
+ merge: this._onMergeKv,
425
+ serialize: kvToStorage,
426
+ parse: kvFromStorage,
427
+ objectSize: () => 0,
428
+ logger: this._log,
429
+ saveThrottleMs: 100,
430
+ idleCallbackMaxWaitMs: 100,
431
+ // Don't GC the kv store
432
+ gc: null,
433
+ });
434
+ this.kv.onKeyLoaded = (k) => {
435
+ if (k === 'pendingMutations') {
436
+ this.notifyAll();
437
+ }
438
+ };
439
+ // Trigger immediate load for pendingMutations and currentUser
440
+ this.kv.waitForKeyToLoad('pendingMutations');
441
+ this.kv.waitForKeyToLoad(currentUserKey);
442
+ this._beforeUnloadCbs.push(() => {
443
+ this.kv.flush();
444
+ this.querySubs.flush();
445
+ });
446
+ }
447
+ _beforeUnload() {
448
+ for (const cb of this._beforeUnloadCbs) {
449
+ cb();
450
+ }
451
+ this._syncTable.beforeUnload();
452
+ }
453
+ /**
454
+ * @param {'enqueued' | 'pending' | 'synced' | 'timeout' | 'error' } status
455
+ * @param {string} eventId
456
+ * @param {{message?: string, type?: string, status?: number, hint?: unknown, traceId?: string}} [errorMsg]
457
+ */
458
+ _finishTransaction(status, eventId, errorMsg) {
459
+ const dfd = this.mutationDeferredStore.get(eventId);
460
+ this.mutationDeferredStore.delete(eventId);
461
+ const ok = status !== 'error' && status !== 'timeout';
462
+ if (!dfd && !ok) {
463
+ // console.erroring here, as there are no listeners to let know
464
+ console.error('Mutation failed', { status, eventId, ...errorMsg });
465
+ }
466
+ if (!dfd) {
467
+ return;
468
+ }
469
+ if (ok) {
470
+ dfd.resolve({ status, eventId });
471
+ }
472
+ else {
473
+ // Check if error comes from server or client
474
+ if (errorMsg?.type) {
475
+ const { status, ...body } = errorMsg;
476
+ dfd.reject(new fetch_ts_1.InstantAPIError({
477
+ // @ts-expect-error body.type is not constant typed
478
+ body,
479
+ status: status ?? 0,
480
+ }));
481
+ }
482
+ else {
483
+ dfd.reject(new InstantError_ts_1.InstantError(errorMsg?.message || 'Unknown error', errorMsg?.hint, errorMsg?.traceId));
484
+ }
485
+ }
486
+ }
487
+ _setStatus(status, err) {
488
+ this.status = status;
489
+ this._errorMessage = err;
490
+ this.notifyConnectionStatusSubs(status);
491
+ this._instantStream.onConnectionStatusChange(status);
492
+ }
493
+ _onMergeKv = (key, storageV, inMemoryV) => {
494
+ switch (key) {
495
+ case 'pendingMutations': {
496
+ const storageEntries = storageV?.entries() ?? [];
497
+ const inMemoryEntries = inMemoryV?.entries() ?? [];
498
+ const muts = new Map([...storageEntries, ...inMemoryEntries]);
499
+ const rewrittenStorageMuts = storageV
500
+ ? this._rewriteMutationsSorted(this.attrs, storageV)
501
+ : [];
502
+ rewrittenStorageMuts.forEach(([k, mut]) => {
503
+ if (!inMemoryV?.pendingMutations?.has(k) && !mut['tx-id']) {
504
+ this._sendMutation(k, mut);
505
+ }
506
+ });
507
+ return muts;
508
+ }
509
+ default:
510
+ return inMemoryV || storageV;
511
+ }
512
+ };
513
+ _flushEnqueuedRoomData(roomId) {
514
+ const enqueuedUserPresence = this._presence[roomId]?.result?.user;
515
+ const enqueuedBroadcasts = this._broadcastQueue[roomId];
516
+ this._broadcastQueue[roomId] = [];
517
+ if (enqueuedUserPresence) {
518
+ this._trySetPresence(roomId, enqueuedUserPresence);
519
+ }
520
+ if (enqueuedBroadcasts) {
521
+ for (const item of enqueuedBroadcasts) {
522
+ const { topic, roomType, data } = item;
523
+ this._tryBroadcast(roomId, roomType, topic, data);
524
+ }
525
+ }
526
+ }
527
+ /**
528
+ * Does the same thing as add-query-ok
529
+ * but called as a result of receiving query info from ssr
530
+ * @param {any} q
531
+ * @param {{ triples: any; pageInfo: any; }} result
532
+ * @param {boolean} enableCardinalityInference
533
+ */
534
+ _addQueryData(q, result, enableCardinalityInference) {
535
+ if (!this.attrs) {
536
+ throw new Error('Attrs in reactor have not been set');
537
+ }
538
+ const queryHash = (0, weakHash_ts_1.default)(q);
539
+ const attrsStore = this.ensureAttrs();
540
+ const store = s.createStore(this.attrs, result.triples, enableCardinalityInference, this.config.useDateObjects);
541
+ this.querySubs.updateInPlace((prev) => {
542
+ prev[queryHash] = {
543
+ result: {
544
+ store,
545
+ attrsStore,
546
+ pageInfo: result.pageInfo,
547
+ processedTxId: undefined,
548
+ isExternal: true,
549
+ },
550
+ q,
551
+ };
552
+ });
553
+ this._cleanupPendingMutationsQueries();
554
+ this.notifyOne(queryHash);
555
+ this.notifyOneQueryOnce(queryHash);
556
+ this._cleanupPendingMutationsTimeout();
557
+ }
558
+ _handleReceive(connId, msg) {
559
+ // opt-out, enabled by default if schema
560
+ const enableCardinalityInference = Boolean(this.config.schema) &&
561
+ ('cardinalityInference' in this.config
562
+ ? Boolean(this.config.cardinalityInference)
563
+ : true);
564
+ if (!ignoreLogging[msg.op]) {
565
+ this._log.info('[receive]', connId, msg.op, msg);
566
+ }
567
+ switch (msg.op) {
568
+ case 'init-ok': {
569
+ this._setStatus(exports.STATUS.AUTHENTICATED);
570
+ this._reconnectTimeoutMs = 0;
571
+ this._setAppStatus(msg['app-status']?.status ?? 'active');
572
+ this._setAttrs(msg.attrs);
573
+ this._flushPendingMessages();
574
+ // (EPH): set session-id, so we know
575
+ // which item is us
576
+ this._sessionId = msg['session-id'];
577
+ for (const roomId of Object.keys(this._rooms)) {
578
+ const enqueuedUserPresence = this._presence[roomId]?.result?.user;
579
+ const roomType = this._rooms[roomId]?.roomType;
580
+ this._tryJoinRoom(roomType, roomId, enqueuedUserPresence);
581
+ }
582
+ break;
583
+ }
584
+ case 'add-query-exists': {
585
+ this.notifyOneQueryOnce((0, weakHash_ts_1.default)(msg.q));
586
+ break;
587
+ }
588
+ case 'add-query-ok': {
589
+ const { q, result } = msg;
590
+ const hash = (0, weakHash_ts_1.default)(q);
591
+ if (!this._hasQueryListeners() && !this.querySubs.currentValue[hash]) {
592
+ break;
593
+ }
594
+ const pageInfo = result?.[0]?.data?.['page-info'];
595
+ const aggregate = result?.[0]?.data?.['aggregate'];
596
+ const triples = (0, instaqlResult_js_1.extractTriples)(result);
597
+ const attrsStore = this.ensureAttrs();
598
+ const store = s.createStore(attrsStore, triples, enableCardinalityInference, this.config.useDateObjects);
599
+ this.querySubs.updateInPlace((prev) => {
600
+ if (!prev[hash]) {
601
+ this._log.info('Missing value in querySubs', { hash, q });
602
+ return;
603
+ }
604
+ prev[hash].result = {
605
+ store,
606
+ attrsStore,
607
+ pageInfo,
608
+ aggregate,
609
+ processedTxId: msg['processed-tx-id'],
610
+ };
611
+ });
612
+ this._cleanupPendingMutationsQueries();
613
+ this.notifyOne(hash);
614
+ this.notifyOneQueryOnce(hash);
615
+ this._cleanupPendingMutationsTimeout();
616
+ break;
617
+ }
618
+ case 'start-sync-ok': {
619
+ this._syncTable.onStartSyncOk(msg);
620
+ break;
621
+ }
622
+ case 'sync-load-batch': {
623
+ this._syncTable.onSyncLoadBatch(msg);
624
+ break;
625
+ }
626
+ case 'sync-init-finish': {
627
+ this._syncTable.onSyncInitFinish(msg);
628
+ break;
629
+ }
630
+ case 'sync-update-triples': {
631
+ this._syncTable.onSyncUpdateTriples(msg);
632
+ break;
633
+ }
634
+ case 'start-stream-ok': {
635
+ this._instantStream.onStartStreamOk(msg);
636
+ break;
637
+ }
638
+ case 'stream-flushed': {
639
+ this._instantStream.onStreamFlushed(msg);
640
+ break;
641
+ }
642
+ case 'append-failed': {
643
+ this._instantStream.onAppendFailed(msg);
644
+ break;
645
+ }
646
+ case 'stream-append': {
647
+ this._instantStream.onStreamAppend(msg);
648
+ break;
649
+ }
650
+ case 'refresh-ok': {
651
+ const { computations, attrs } = msg;
652
+ const processedTxId = msg['processed-tx-id'];
653
+ if (attrs) {
654
+ this._setAttrs(attrs);
655
+ }
656
+ this._cleanupPendingMutationsTimeout();
657
+ const rewrittenMutations = this._rewriteMutations(this.ensureAttrs(), this._pendingMutations(), processedTxId);
658
+ if (rewrittenMutations !== this._pendingMutations()) {
659
+ // We know we've changed the mutations to fix the attr ids and removed
660
+ // processed attrs, so we'll persist those changes to prevent optimisticAttrs
661
+ // from using old attr definitions
662
+ this.kv.updateInPlace((prev) => {
663
+ prev.pendingMutations = rewrittenMutations;
664
+ });
665
+ }
666
+ const mutations = sortedMutationEntries(rewrittenMutations.entries());
667
+ const updates = computations.map((x) => {
668
+ const q = x['instaql-query'];
669
+ const result = x['instaql-result'];
670
+ const hash = (0, weakHash_ts_1.default)(q);
671
+ const triples = (0, instaqlResult_js_1.extractTriples)(result);
672
+ const attrsStore = this.ensureAttrs();
673
+ const store = s.createStore(attrsStore, triples, enableCardinalityInference, this.config.useDateObjects);
674
+ const { store: newStore, attrsStore: newAttrsStore } = this._applyOptimisticUpdates(store, attrsStore, mutations, processedTxId);
675
+ const pageInfo = result?.[0]?.data?.['page-info'];
676
+ const aggregate = result?.[0]?.data?.['aggregate'];
677
+ return {
678
+ q,
679
+ hash,
680
+ store: newStore,
681
+ attrsStore: newAttrsStore,
682
+ pageInfo,
683
+ aggregate,
684
+ };
685
+ });
686
+ updates.forEach(({ hash, q, store, attrsStore, pageInfo, aggregate }) => {
687
+ this.querySubs.updateInPlace((prev) => {
688
+ if (!prev[hash]) {
689
+ this._log.error('Missing value in querySubs', { hash, q });
690
+ return;
691
+ }
692
+ prev[hash].result = {
693
+ store,
694
+ attrsStore,
695
+ pageInfo,
696
+ aggregate,
697
+ processedTxId,
698
+ };
699
+ });
700
+ });
701
+ this._cleanupPendingMutationsQueries();
702
+ updates.forEach(({ hash }) => {
703
+ this.notifyOne(hash);
704
+ });
705
+ break;
706
+ }
707
+ case 'transact-ok': {
708
+ const { 'client-event-id': eventId, 'tx-id': txId } = msg;
709
+ this._inFlightMutationEventIds.delete(eventId);
710
+ const muts = this._rewriteMutations(this.ensureAttrs(), this._pendingMutations());
711
+ const prevMutation = muts.get(eventId);
712
+ if (!prevMutation) {
713
+ break;
714
+ }
715
+ // update pendingMutation with server-side tx-id
716
+ this._updatePendingMutations((prev) => {
717
+ prev.set(eventId, {
718
+ ...prev.get(eventId),
719
+ 'tx-id': txId,
720
+ confirmed: Date.now(),
721
+ });
722
+ });
723
+ const newAttrs = [];
724
+ for (const step of prevMutation['tx-steps']) {
725
+ if (step[0] === 'add-attr') {
726
+ const attr = step[1];
727
+ newAttrs.push(attr);
728
+ }
729
+ }
730
+ if (newAttrs.length) {
731
+ const existingAttrs = Object.values(this.ensureAttrs().attrs);
732
+ this._setAttrs([...existingAttrs, ...newAttrs]);
733
+ }
734
+ this._finishTransaction('synced', eventId);
735
+ this._cleanupPendingMutationsTimeout();
736
+ break;
737
+ }
738
+ case 'patch-presence': {
739
+ const roomId = msg['room-id'];
740
+ this._trySetRoomConnected(roomId, true);
741
+ this._patchPresencePeers(roomId, msg['edits']);
742
+ this._notifyPresenceSubs(roomId);
743
+ break;
744
+ }
745
+ case 'refresh-presence': {
746
+ const roomId = msg['room-id'];
747
+ this._trySetRoomConnected(roomId, true);
748
+ this._setPresencePeers(roomId, msg['data']);
749
+ this._notifyPresenceSubs(roomId);
750
+ break;
751
+ }
752
+ case 'server-broadcast': {
753
+ const room = msg['room-id'];
754
+ const topic = msg.topic;
755
+ this._trySetRoomConnected(room, true);
756
+ this._notifyBroadcastSubs(room, topic, msg);
757
+ break;
758
+ }
759
+ case 'join-room-ok': {
760
+ const loadingRoomId = msg['room-id'];
761
+ const joinedRoom = this._rooms[loadingRoomId];
762
+ if (!joinedRoom) {
763
+ if (this._roomsPendingLeave[loadingRoomId]) {
764
+ this._tryLeaveRoom(loadingRoomId);
765
+ delete this._roomsPendingLeave[loadingRoomId];
766
+ }
767
+ break;
768
+ }
769
+ this._trySetRoomConnected(loadingRoomId, true);
770
+ this._flushEnqueuedRoomData(loadingRoomId);
771
+ break;
772
+ }
773
+ case 'leave-room-ok': {
774
+ const roomId = msg['room-id'];
775
+ this._trySetRoomConnected(roomId, false);
776
+ break;
777
+ }
778
+ case 'app-status-changed': {
779
+ const prevStatus = this._appStatusState.status;
780
+ this._setAppStatus(msg.status);
781
+ if (msg.status === 'disabled' && prevStatus !== 'disabled') {
782
+ // The server has stopped serving reads; surface the typed error on
783
+ // every registered query immediately instead of waiting for the
784
+ // next round trip.
785
+ const error = {
786
+ message: 'This app is currently disabled.',
787
+ hint: { status: 'disabled' },
788
+ };
789
+ Object.keys(this.queryCbs).forEach((hash) => this.notifyQueryError(hash, error));
790
+ }
791
+ if (prevStatus === 'disabled' && msg.status !== 'disabled') {
792
+ // Leaving `disabled`: refreshes were paused server-side, so restart
793
+ // the socket to re-add every query and get fresh results.
794
+ this._startSocket();
795
+ }
796
+ break;
797
+ }
798
+ case 'join-room-error':
799
+ const errorRoomId = msg['room-id'];
800
+ const errorRoom = this._rooms[errorRoomId];
801
+ if (errorRoom) {
802
+ errorRoom.error = msg['error'];
803
+ }
804
+ this._notifyPresenceSubs(errorRoomId);
805
+ break;
806
+ case 'error':
807
+ this._handleReceiveError(msg);
808
+ break;
809
+ default:
810
+ this._log.info('Unknown op', msg.op, msg);
811
+ break;
812
+ }
813
+ }
814
+ createWriteStream(opts) {
815
+ return this._instantStream.createWriteStream(opts);
816
+ }
817
+ createReadStream(opts) {
818
+ return this._instantStream.createReadStream(opts);
819
+ }
820
+ _pendingMutations() {
821
+ return this.kv.currentValue.pendingMutations ?? new Map();
822
+ }
823
+ _updatePendingMutations(f) {
824
+ this.kv.updateInPlace((prev) => {
825
+ const muts = prev.pendingMutations ?? new Map();
826
+ prev.pendingMutations = muts;
827
+ f(muts);
828
+ });
829
+ }
830
+ /**
831
+ * @param {'timeout' | 'error'} status
832
+ * @param {string} eventId
833
+ * @param {{message?: string, type?: string, status?: number, hint?: unknown, traceId?: string}} errorMsg
834
+ */
835
+ _handleMutationError(status, eventId, errorMsg) {
836
+ const mut = this._pendingMutations().get(eventId);
837
+ if (mut && (status !== 'timeout' || !mut['tx-id'])) {
838
+ // Read before the delete below.
839
+ const affected = this._mutationsFrom(eventId);
840
+ this._updatePendingMutations((prev) => {
841
+ prev.delete(eventId);
842
+ return prev;
843
+ });
844
+ this._inFlightMutationEventIds.delete(eventId);
845
+ const errDetails = {
846
+ message: errorMsg.message,
847
+ hint: errorMsg.hint,
848
+ traceId: errorMsg.traceId,
849
+ };
850
+ this._notifyForMutations(affected);
851
+ this.notifyAttrsSubs();
852
+ this.notifyMutationErrorSubs(errDetails);
853
+ this._finishTransaction(status, eventId, errorMsg);
854
+ }
855
+ }
856
+ _handleReceiveError(msg) {
857
+ this._log.info('error', msg);
858
+ const eventId = msg['client-event-id'];
859
+ // This might not be a mutation, but it can't hurt to delete it
860
+ this._inFlightMutationEventIds.delete(eventId);
861
+ const prevMutation = this._pendingMutations().get(eventId);
862
+ const errorMessage = {
863
+ message: msg.message || 'Uh-oh, something went wrong. Ping Joe & Stopa.',
864
+ };
865
+ if (msg.hint) {
866
+ errorMessage.hint = msg.hint;
867
+ }
868
+ if (msg['trace-id'] || msg['original-event']?.['trace-id']) {
869
+ const traceIds = [msg['trace-id'], msg['original-event']?.['trace-id']];
870
+ const traceId = traceIds.filter(Boolean).join(',');
871
+ errorMessage.traceId = traceId;
872
+ }
873
+ if (prevMutation) {
874
+ this._handleMutationError('error', eventId, errorMessage);
875
+ return;
876
+ }
877
+ if (msg['original-event']?.hasOwnProperty('q') &&
878
+ msg['original-event']?.op === 'add-query') {
879
+ const q = msg['original-event']?.q;
880
+ const hash = (0, weakHash_ts_1.default)(q);
881
+ this.notifyQueryError((0, weakHash_ts_1.default)(q), errorMessage);
882
+ this.notifyQueryOnceError(q, hash, eventId, errorMessage);
883
+ return;
884
+ }
885
+ const isInitError = msg['original-event']?.op === 'init';
886
+ if (isInitError) {
887
+ if (msg.type === 'record-not-found' &&
888
+ msg.hint?.['record-type'] === 'app-user') {
889
+ // User has been logged out
890
+ this.changeCurrentUser(null);
891
+ return;
892
+ }
893
+ // We failed to init
894
+ this._setStatus(exports.STATUS.ERRORED, errorMessage);
895
+ this.notifyAll();
896
+ return;
897
+ }
898
+ switch (msg['original-event']?.op) {
899
+ case 'resync-table': {
900
+ this._syncTable.onResyncError(msg);
901
+ return;
902
+ }
903
+ case 'start-sync': {
904
+ this._syncTable.onStartSyncError(msg);
905
+ return;
906
+ }
907
+ case 'start-stream':
908
+ case 'append-stream':
909
+ case 'subscribe-stream':
910
+ case 'unsubscribe-stream': {
911
+ this._instantStream.onRecieveError(msg);
912
+ return;
913
+ }
914
+ }
915
+ // We've caught some error which has no corresponding listener.
916
+ // Let's console.error to let the user know.
917
+ const errorObj = { ...msg };
918
+ delete errorObj.message;
919
+ delete errorObj.hint;
920
+ console.error(msg.message, errorObj);
921
+ if (msg.hint) {
922
+ console.error('This error comes with some debugging information. Here it is: \n', msg.hint);
923
+ }
924
+ }
925
+ notifyQueryOnceError(q, hash, eventId, e) {
926
+ const r = this.queryOnceDfds[hash]?.find((r) => r.eventId === eventId);
927
+ if (!r)
928
+ return;
929
+ r.dfd.reject(e);
930
+ this._completeQueryOnce(q, hash, r.dfd);
931
+ }
932
+ _setAttrs(attrs) {
933
+ this.attrs = new s.AttrsStoreClass(attrs.reduce((acc, attr) => {
934
+ acc[attr.id] = attr;
935
+ return acc;
936
+ }, {}), this._linkIndex);
937
+ this.notifyAttrsSubs();
938
+ }
939
+ // ---------------------------
940
+ // Queries
941
+ getPreviousResult = (q) => {
942
+ const hash = (0, weakHash_ts_1.default)(q);
943
+ return this.dataForQuery(hash)?.data;
944
+ };
945
+ _startQuerySub(q, hash) {
946
+ const eventId = (0, id_ts_1.default)();
947
+ this.querySubs.updateInPlace((prev) => {
948
+ if (!prev[hash]) {
949
+ // Legacy hash migration (sync): if a preloaded entry sits under the
950
+ // old hash, move it to the new key so the placeholder line below
951
+ // becomes a no-op and currentValue[hash] keeps its cached result.
952
+ const legacyHash = (0, weakHashLegacy_ts_1.default)(q);
953
+ if (legacyHash !== hash && prev[legacyHash]) {
954
+ prev[hash] = prev[legacyHash];
955
+ delete prev[legacyHash];
956
+ }
957
+ }
958
+ prev[hash] = prev[hash] || { q, result: null, eventId };
959
+ prev[hash].lastAccessed = Date.now();
960
+ });
961
+ this._tryMigrateLegacyQuerySub(q, hash);
962
+ this._trySendAuthed(eventId, { op: 'add-query', q });
963
+ return eventId;
964
+ }
965
+ // Legacy hash migration (async): covers entries that weren't preloaded
966
+ // into currentValue. Actively loads the legacy key from storage, moves
967
+ // its result onto the new key, and notifies subscribers. Safe to remove
968
+ // a few releases after v1.0.39.
969
+ async _tryMigrateLegacyQuerySub(q, newHash) {
970
+ const legacyHash = (0, weakHashLegacy_ts_1.default)(q);
971
+ if (legacyHash === newHash)
972
+ return;
973
+ await this.querySubs.waitForKeyToLoad(legacyHash);
974
+ const legacy = this.querySubs.currentValue[legacyHash];
975
+ if (!legacy)
976
+ return;
977
+ let migratedResult = false;
978
+ this.querySubs.updateInPlace((prev) => {
979
+ const existing = prev[newHash];
980
+ if (existing && !existing.result && legacy.result) {
981
+ existing.result = legacy.result;
982
+ migratedResult = true;
983
+ }
984
+ else if (!existing) {
985
+ prev[newHash] = legacy;
986
+ migratedResult = !!legacy.result;
987
+ }
988
+ delete prev[legacyHash];
989
+ });
990
+ if (migratedResult)
991
+ this.notifyOne(newHash);
992
+ }
993
+ subscribeTable(q, cb) {
994
+ return this._syncTable.subscribe(q, cb);
995
+ }
996
+ /**
997
+ * When a user subscribes to a query the following side effects occur:
998
+ *
999
+ * - We update querySubs to include the new query
1000
+ * - We update queryCbs to include the new cb
1001
+ * - If we already have a result for the query we call cb immediately
1002
+ * - We send the server an `add-query` message
1003
+ *
1004
+ * Returns an unsubscribe function
1005
+ */
1006
+ subscribeQuery(q, cb, opts) {
1007
+ if (!this.config.disableValidation) {
1008
+ (0, queryValidation_ts_1.validateQuery)(q, this.config.schema);
1009
+ }
1010
+ if (opts && 'ruleParams' in opts) {
1011
+ q = { $$ruleParams: opts['ruleParams'], ...q };
1012
+ }
1013
+ const hash = (0, weakHash_ts_1.default)(q);
1014
+ const prevResult = this.getPreviousResult(q);
1015
+ if (prevResult) {
1016
+ cb(prevResult);
1017
+ }
1018
+ this.queryCbs[hash] = this.queryCbs[hash] ?? [];
1019
+ this.queryCbs[hash].push({ q, cb });
1020
+ this._startQuerySub(q, hash);
1021
+ return () => {
1022
+ this._unsubQuery(q, hash, cb);
1023
+ };
1024
+ }
1025
+ queryOnce(q, opts) {
1026
+ if (!this.config.disableValidation) {
1027
+ (0, queryValidation_ts_1.validateQuery)(q, this.config.schema);
1028
+ }
1029
+ if (opts && 'ruleParams' in opts) {
1030
+ q = { $$ruleParams: opts['ruleParams'], ...q };
1031
+ }
1032
+ const dfd = new Deferred_ts_1.Deferred();
1033
+ if (!this._isOnline) {
1034
+ dfd.reject(new Error("We can't run `queryOnce`, because the device is offline."));
1035
+ return dfd.promise;
1036
+ }
1037
+ if (!this.querySubs) {
1038
+ dfd.reject(new Error("We can't run `queryOnce` on the backend. Use adminAPI.query instead: https://sidekickdb.co/docs/backend#query"));
1039
+ return dfd.promise;
1040
+ }
1041
+ const hash = (0, weakHash_ts_1.default)(q);
1042
+ const eventId = this._startQuerySub(q, hash);
1043
+ this.queryOnceDfds[hash] = this.queryOnceDfds[hash] ?? [];
1044
+ this.queryOnceDfds[hash].push({ q, dfd, eventId });
1045
+ setTimeout(() => dfd.reject(new Error('Query timed out')), QUERY_ONCE_TIMEOUT);
1046
+ return dfd.promise;
1047
+ }
1048
+ _completeQueryOnce(q, hash, dfd) {
1049
+ if (!this.queryOnceDfds[hash])
1050
+ return;
1051
+ this.queryOnceDfds[hash] = this.queryOnceDfds[hash].filter((r) => r.dfd !== dfd);
1052
+ this._cleanupQuery(q, hash);
1053
+ }
1054
+ _unsubQuery(q, hash, cb) {
1055
+ if (!this.queryCbs[hash])
1056
+ return;
1057
+ this.queryCbs[hash] = this.queryCbs[hash].filter((r) => r.cb !== cb);
1058
+ this._cleanupQuery(q, hash);
1059
+ }
1060
+ _hasQueryListeners(hash) {
1061
+ return !!(this.queryCbs[hash]?.length || this.queryOnceDfds[hash]?.length);
1062
+ }
1063
+ _cleanupQuery(q, hash) {
1064
+ const hasListeners = this._hasQueryListeners(hash);
1065
+ if (hasListeners)
1066
+ return;
1067
+ delete this.queryCbs[hash];
1068
+ delete this.queryOnceDfds[hash];
1069
+ delete this._dataForQueryCache[hash];
1070
+ delete this._dataForQueryMemo[hash];
1071
+ delete this._dataForQueryMemo['!' + hash];
1072
+ this._queryFootprints.delete(hash);
1073
+ this.querySubs.unloadKey(hash);
1074
+ this._trySendAuthed((0, id_ts_1.default)(), { op: 'remove-query', q });
1075
+ }
1076
+ // When we `pushTx`, it's possible that we don't yet have `this.attrs`
1077
+ // This means that `tx-steps` in `pendingMutations` will include `add-attr`
1078
+ // commands for attrs that already exist.
1079
+ //
1080
+ // This will also affect `add-triple` and `retract-triple` which
1081
+ // reference attr-ids that do not match the server.
1082
+ //
1083
+ // We fix this by rewriting `tx-steps` in each `pendingMutation`.
1084
+ // We remove `add-attr` commands for attrs that already exist.
1085
+ // We update `add-triple` and `retract-triple` commands to use the
1086
+ // server attr-ids.
1087
+ /**
1088
+ *
1089
+ * @param {s.AttrsStore} attrs
1090
+ * @param {any} muts
1091
+ * @param {number} [processedTxId]
1092
+ */
1093
+ _rewriteMutations(attrs, muts, processedTxId) {
1094
+ if (!attrs)
1095
+ return muts;
1096
+ if (!muts)
1097
+ return new Map();
1098
+ const findExistingAttr = (attr) => {
1099
+ const [_, etype, label] = attr['forward-identity'];
1100
+ const existing = s.getAttrByFwdIdentName(attrs, etype, label);
1101
+ return existing;
1102
+ };
1103
+ const findReverseAttr = (attr) => {
1104
+ const [_, etype, label] = attr['forward-identity'];
1105
+ const revAttr = s.getAttrByReverseIdentName(attrs, etype, label);
1106
+ return revAttr;
1107
+ };
1108
+ const mapping = { attrIdMap: {}, refSwapAttrIds: new Set() };
1109
+ let mappingChanged = false;
1110
+ const rewriteTxSteps = (txSteps, txId) => {
1111
+ const retTxSteps = [];
1112
+ for (const txStep of txSteps) {
1113
+ const [action] = txStep;
1114
+ // Handles add-attr
1115
+ // If existing, we drop it, and track it
1116
+ // to update add/retract triples
1117
+ if (action === 'add-attr') {
1118
+ const [_action, attr] = txStep;
1119
+ const existing = findExistingAttr(attr);
1120
+ if (existing && attr.id !== existing.id) {
1121
+ mapping.attrIdMap[attr.id] = existing.id;
1122
+ mappingChanged = true;
1123
+ continue;
1124
+ }
1125
+ if (attr['value-type'] === 'ref') {
1126
+ const revAttr = findReverseAttr(attr);
1127
+ if (revAttr) {
1128
+ mapping.attrIdMap[attr.id] = revAttr.id;
1129
+ mapping.refSwapAttrIds.add(attr.id);
1130
+ mappingChanged = true;
1131
+ continue;
1132
+ }
1133
+ }
1134
+ }
1135
+ if ((processedTxId &&
1136
+ txId &&
1137
+ processedTxId >= txId &&
1138
+ action === 'add-attr') ||
1139
+ action === 'update-attr' ||
1140
+ action === 'delete-attr') {
1141
+ mappingChanged = true;
1142
+ // Don't add this step because we already have the newer attrs
1143
+ continue;
1144
+ }
1145
+ // Handles add-triple|retract-triple
1146
+ // If in mapping, we update the attr-id
1147
+ const newTxStep = mappingChanged
1148
+ ? instaml.rewriteStep(mapping, txStep)
1149
+ : txStep;
1150
+ retTxSteps.push(newTxStep);
1151
+ }
1152
+ return mappingChanged ? retTxSteps : txSteps;
1153
+ };
1154
+ const rewritten = new Map();
1155
+ for (const [k, mut] of muts.entries()) {
1156
+ rewritten.set(k, {
1157
+ ...mut,
1158
+ 'tx-steps': rewriteTxSteps(mut['tx-steps'], mut['tx-id']),
1159
+ });
1160
+ }
1161
+ if (!mappingChanged) {
1162
+ return muts;
1163
+ }
1164
+ return rewritten;
1165
+ }
1166
+ _rewriteMutationsSorted(attrs, muts) {
1167
+ return sortedMutationEntries(this._rewriteMutations(attrs, muts).entries());
1168
+ }
1169
+ // ---------------------------
1170
+ // Transact
1171
+ /**
1172
+ * @returns {s.AttrsStore}
1173
+ */
1174
+ optimisticAttrs() {
1175
+ const pendingMutationSteps = [...this._pendingMutations().values()] // hack due to Map()
1176
+ .flatMap((x) => x['tx-steps']);
1177
+ const deletedAttrIds = new Set(pendingMutationSteps
1178
+ .filter(([action, _attr]) => action === 'delete-attr')
1179
+ .map(([_action, id]) => id));
1180
+ const pendingAttrs = [];
1181
+ for (const [_action, attr] of pendingMutationSteps) {
1182
+ if (_action === 'add-attr') {
1183
+ pendingAttrs.push(attr);
1184
+ }
1185
+ else if (_action === 'update-attr' &&
1186
+ attr.id &&
1187
+ this.attrs?.getAttr(attr.id)) {
1188
+ const fullAttr = { ...this.attrs.getAttr(attr.id), ...attr };
1189
+ pendingAttrs.push(fullAttr);
1190
+ }
1191
+ }
1192
+ if (!deletedAttrIds.size && !pendingAttrs.length) {
1193
+ return this.attrs || new s.AttrsStoreClass({}, this._linkIndex);
1194
+ }
1195
+ const attrs = { ...(this.attrs?.attrs || {}) };
1196
+ for (const attr of pendingAttrs) {
1197
+ attrs[attr.id] = attr;
1198
+ }
1199
+ for (const id of deletedAttrIds) {
1200
+ delete attrs[id];
1201
+ }
1202
+ return new s.AttrsStoreClass(attrs, this._linkIndex);
1203
+ }
1204
+ /** Runs instaql on a query and a store */
1205
+ dataForQuery(hash, applyOptimistic = true) {
1206
+ const errorMessage = this._errorMessage;
1207
+ if (errorMessage) {
1208
+ return { error: errorMessage };
1209
+ }
1210
+ if (!this.querySubs)
1211
+ return;
1212
+ if (!this.kv.currentValue.pendingMutations)
1213
+ return;
1214
+ const querySubVersion = this.querySubs.version();
1215
+ const querySubs = this.querySubs.currentValue;
1216
+ const pendingMutationsVersion = this.kv.version();
1217
+ const pendingMutations = this._pendingMutations();
1218
+ const { q, result } = querySubs[hash] || {};
1219
+ if (!result)
1220
+ return;
1221
+ // getPreviousResult (called on every useQuery render) reaches here between
1222
+ // notifies, so memoise rather than re-apply every pending mutation.
1223
+ const memoKey = applyOptimistic ? hash : '!' + hash;
1224
+ const memo = this._dataForQueryMemo[memoKey];
1225
+ if (memo &&
1226
+ memo.result === result &&
1227
+ memo.resp.querySubVersion === querySubVersion &&
1228
+ memo.resp.pendingMutationsVersion === pendingMutationsVersion) {
1229
+ return memo.resp;
1230
+ }
1231
+ // notifyOne only ever stores optimistic results here.
1232
+ const cached = applyOptimistic && this._dataForQueryCache[hash];
1233
+ if (cached &&
1234
+ querySubVersion === cached.querySubVersion &&
1235
+ pendingMutationsVersion === cached.pendingMutationsVersion) {
1236
+ return cached;
1237
+ }
1238
+ let store = result.store;
1239
+ let attrsStore = result.attrsStore;
1240
+ const { pageInfo, aggregate, processedTxId } = result;
1241
+ const mutations = this._rewriteMutationsSorted(attrsStore, pendingMutations);
1242
+ if (applyOptimistic) {
1243
+ const optimisticResult = this._applyOptimisticUpdates(store, attrsStore, mutations, processedTxId);
1244
+ store = optimisticResult.store;
1245
+ attrsStore = optimisticResult.attrsStore;
1246
+ }
1247
+ const resp = (0, instaql_ts_1.default)({ store: store, attrsStore: attrsStore, pageInfo, aggregate }, q);
1248
+ const out = { data: resp, querySubVersion, pendingMutationsVersion };
1249
+ this._dataForQueryMemo[memoKey] = { result, resp: out };
1250
+ return out;
1251
+ }
1252
+ _applyOptimisticUpdates(store, attrsStore, mutations, processedTxId) {
1253
+ for (const [_, mut] of mutations) {
1254
+ if (!mut['tx-id'] || (processedTxId && mut['tx-id'] > processedTxId)) {
1255
+ const result = s.transact(store, attrsStore, mut['tx-steps']);
1256
+ store = result.store;
1257
+ attrsStore = result.attrsStore;
1258
+ }
1259
+ }
1260
+ return { store, attrsStore };
1261
+ }
1262
+ /** Re-run instaql and call all callbacks with new data */
1263
+ notifyOne = (hash) => {
1264
+ const cbs = this.queryCbs[hash] ?? [];
1265
+ const prevData = this._dataForQueryCache[hash]?.data;
1266
+ const resp = this.dataForQuery(hash);
1267
+ if (!resp?.data)
1268
+ return;
1269
+ this._dataForQueryCache[hash] = resp;
1270
+ if ((0, object_js_1.areObjectsDeepEqual)(resp.data, prevData))
1271
+ return;
1272
+ cbs.forEach((r) => r.cb(resp.data));
1273
+ };
1274
+ notifyOneQueryOnce = (hash) => {
1275
+ const dfds = this.queryOnceDfds[hash] ?? [];
1276
+ const data = this.dataForQuery(hash)?.data;
1277
+ dfds.forEach((r) => {
1278
+ this._completeQueryOnce(r.q, hash, r.dfd);
1279
+ r.dfd.resolve(data);
1280
+ });
1281
+ };
1282
+ notifyQueryError = (hash, error) => {
1283
+ // Clear the dedupe cache so the next successful result re-notifies
1284
+ // subscribers even if the data is unchanged from before the error
1285
+ delete this._dataForQueryCache[hash];
1286
+ const cbs = this.queryCbs[hash] || [];
1287
+ cbs.forEach((r) => r.cb({ error }));
1288
+ };
1289
+ /** Re-compute all subscriptions */
1290
+ notifyAll() {
1291
+ Object.keys(this.queryCbs).forEach((hash) => {
1292
+ this.querySubs
1293
+ .waitForKeyToLoad(hash)
1294
+ .then(() => this.notifyOne(hash))
1295
+ .catch(() => this.notifyOne(hash));
1296
+ });
1297
+ }
1298
+ /**
1299
+ * The pending mutation `eventId` and every pending mutation applied after
1300
+ * it. Removing one can change how a later one applies (a lookup it
1301
+ * resolved, an update of an entity it created), so rolling one back
1302
+ * re-runs the queries any of them could affect.
1303
+ */
1304
+ _mutationsFrom(eventId) {
1305
+ const sorted = sortedMutationEntries(this._pendingMutations().entries());
1306
+ const i = sorted.findIndex(([k]) => k === eventId);
1307
+ return i < 0 ? null : sorted.slice(i).map(([_k, mut]) => mut);
1308
+ }
1309
+ /**
1310
+ * Like `notifyAll`, but only for the queries `muts` can affect. Anything
1311
+ * it can't classify notifies every query.
1312
+ */
1313
+ _notifyForMutations(muts) {
1314
+ let writeFp = null;
1315
+ if (this._scopedNotify && muts) {
1316
+ writeFp = new Map();
1317
+ for (const mut of muts) {
1318
+ writeFp = (0, notifyScope_ts_1.mutationFootprint)(mut['tx-steps'], this.attrs, writeFp);
1319
+ if (!writeFp)
1320
+ break;
1321
+ }
1322
+ }
1323
+ if (!writeFp) {
1324
+ this.notifyAll();
1325
+ return;
1326
+ }
1327
+ Object.keys(this.queryCbs).forEach((hash) => {
1328
+ if (!this._mutationMayAffect(hash, writeFp))
1329
+ return;
1330
+ this.querySubs
1331
+ .waitForKeyToLoad(hash)
1332
+ .then(() => this.notifyOne(hash))
1333
+ .catch(() => this.notifyOne(hash));
1334
+ });
1335
+ }
1336
+ _mutationMayAffect(hash, writeFp) {
1337
+ // Never delivered, or cleared by notifyQueryError: always deliver.
1338
+ if (!this._dataForQueryCache[hash])
1339
+ return true;
1340
+ const q = this.querySubs.currentValue?.[hash]?.q;
1341
+ if (!q)
1342
+ return true;
1343
+ // Cached while the query form and the attrs it was resolved against are
1344
+ // the same objects.
1345
+ let entry = this._queryFootprints.get(hash);
1346
+ if (!entry || entry.q !== q || entry.attrs !== this.attrs) {
1347
+ entry = { q, attrs: this.attrs, fp: (0, notifyScope_ts_1.queryFootprint)(q, this.attrs) };
1348
+ this._queryFootprints.set(hash, entry);
1349
+ }
1350
+ return !entry.fp || (0, notifyScope_ts_1.footprintsIntersect)(writeFp, entry.fp);
1351
+ }
1352
+ loadedNotifyAll() {
1353
+ this.kv
1354
+ .waitForKeyToLoad('pendingMutations')
1355
+ .then(() => this.notifyAll())
1356
+ .catch(() => this.notifyAll());
1357
+ }
1358
+ /** Applies transactions locally and sends transact message to server */
1359
+ pushTx = (chunks) => {
1360
+ // The server rejects every write while read-only or disabled, so reject
1361
+ // locally instead of applying an optimistic update
1362
+ if (this._appStatusState.isReadOnly) {
1363
+ return Promise.reject(this._appStatusState.status === 'disabled'
1364
+ ? new InstantError_ts_1.InstantError('This app is currently disabled.', {
1365
+ status: 'disabled',
1366
+ })
1367
+ : new InstantError_ts_1.InstantError('This app is in read-only mode.', {
1368
+ status: 'read-only',
1369
+ }));
1370
+ }
1371
+ // Throws if transactions are invalid
1372
+ if (!this.config.disableValidation) {
1373
+ (0, transactionValidation_ts_1.validateTransactions)(chunks, this.config.schema);
1374
+ }
1375
+ try {
1376
+ const txSteps = instaml.transform({
1377
+ attrsStore: this.optimisticAttrs(),
1378
+ schema: this.config.schema,
1379
+ stores: Object.values(this.querySubs.currentValue).map((sub) => sub?.result?.store),
1380
+ useDateObjects: this.config.useDateObjects,
1381
+ }, chunks);
1382
+ return this.pushOps(txSteps);
1383
+ }
1384
+ catch (e) {
1385
+ return this.pushOps([], e);
1386
+ }
1387
+ };
1388
+ /**
1389
+ * @param {*} txSteps
1390
+ * @param {*} [error]
1391
+ * @returns
1392
+ */
1393
+ pushOps = (txSteps, error) => {
1394
+ const eventId = (0, id_ts_1.default)();
1395
+ const mutations = [...this._pendingMutations().values()];
1396
+ const order = Math.max(0, ...mutations.map((mut) => mut.order || 0)) + 1;
1397
+ const mutation = {
1398
+ op: 'transact',
1399
+ 'tx-steps': txSteps,
1400
+ created: Date.now(),
1401
+ error,
1402
+ order,
1403
+ };
1404
+ this._updatePendingMutations((prev) => {
1405
+ prev.set(eventId, mutation);
1406
+ });
1407
+ const dfd = new Deferred_ts_1.Deferred();
1408
+ this.mutationDeferredStore.set(eventId, dfd);
1409
+ this._sendMutation(eventId, mutation);
1410
+ this._notifyForMutations([mutation]);
1411
+ return dfd.promise;
1412
+ };
1413
+ shutdown() {
1414
+ this._log.info('[shutdown]', this.config.appId);
1415
+ this._isShutdown = true;
1416
+ this._transport?.close();
1417
+ }
1418
+ /**
1419
+ * Sends mutation to server and schedules a timeout to cancel it if
1420
+ * we don't hear back in time.
1421
+ * Note: If we're offline we don't schedule a timeout, we'll schedule it
1422
+ * later once we're back online and send the mutation again
1423
+ *
1424
+ */
1425
+ _sendMutation(eventId, mutation) {
1426
+ if (mutation.error) {
1427
+ this._handleMutationError('error', eventId, {
1428
+ message: mutation.error.message,
1429
+ });
1430
+ return;
1431
+ }
1432
+ if (this.status !== exports.STATUS.AUTHENTICATED) {
1433
+ this._finishTransaction('enqueued', eventId);
1434
+ return;
1435
+ }
1436
+ const timeoutMs = Math.max(6000, Math.min(this._inFlightMutationEventIds.size + 1,
1437
+ // Defensive code in case we don't clean up in flight mutation event ids
1438
+ this._pendingMutations().size + 1) * 6000);
1439
+ if (!this._isOnline) {
1440
+ this._finishTransaction('enqueued', eventId);
1441
+ }
1442
+ else {
1443
+ this._trySend(eventId, mutation);
1444
+ setTimeout(() => {
1445
+ if (!this._isOnline) {
1446
+ return;
1447
+ }
1448
+ // If we are here, this means that we have sent this mutation, we are online
1449
+ // but we have not received a response. If it's this long, something must be wrong,
1450
+ // so we error with a timeout.
1451
+ this._handleMutationError('timeout', eventId, {
1452
+ message: 'transaction timed out',
1453
+ });
1454
+ }, timeoutMs);
1455
+ }
1456
+ }
1457
+ // ---------------------------
1458
+ // Websocket
1459
+ /** Send messages we accumulated while we were connecting */
1460
+ _flushPendingMessages() {
1461
+ const subs = Object.keys(this.queryCbs).map((hash) => {
1462
+ return this.querySubs.currentValue[hash];
1463
+ });
1464
+ // Note: we should not have any nulls in subs, but we're
1465
+ // doing this defensively just in case.
1466
+ const safeSubs = subs.filter((x) => x);
1467
+ safeSubs.forEach(({ eventId, q }) => {
1468
+ this._trySendAuthed(eventId, { op: 'add-query', q });
1469
+ });
1470
+ Object.values(this.queryOnceDfds)
1471
+ .flat()
1472
+ .forEach(({ eventId, q }) => {
1473
+ this._trySendAuthed(eventId, { op: 'add-query', q });
1474
+ });
1475
+ const rewrittenMutations = this._rewriteMutations(this.ensureAttrs(), this._pendingMutations());
1476
+ if (rewrittenMutations !== this._pendingMutations()) {
1477
+ // Persist rewritten mutations to avoid stale attr ids in future txs.
1478
+ this.kv.updateInPlace((prev) => {
1479
+ prev.pendingMutations = rewrittenMutations;
1480
+ });
1481
+ }
1482
+ const muts = sortedMutationEntries(rewrittenMutations.entries());
1483
+ muts.forEach(([eventId, mut]) => {
1484
+ if (!mut['tx-id']) {
1485
+ this._sendMutation(eventId, mut);
1486
+ }
1487
+ });
1488
+ this._syncTable.flushPending();
1489
+ }
1490
+ /**
1491
+ * Clean up pendingMutations that all queries have seen
1492
+ */
1493
+ _cleanupPendingMutationsQueries() {
1494
+ let minProcessedTxId = Number.MAX_SAFE_INTEGER;
1495
+ for (const { result } of Object.values(this.querySubs.currentValue)) {
1496
+ if (result?.processedTxId) {
1497
+ minProcessedTxId = Math.min(minProcessedTxId, result?.processedTxId);
1498
+ }
1499
+ }
1500
+ this._updatePendingMutations((prev) => {
1501
+ for (const [eventId, mut] of Array.from(prev.entries())) {
1502
+ if (mut['tx-id'] && mut['tx-id'] <= minProcessedTxId) {
1503
+ prev.delete(eventId);
1504
+ }
1505
+ }
1506
+ });
1507
+ }
1508
+ /**
1509
+ * After mutations is confirmed by server, we give each query 30 sec
1510
+ * to update its results. If that doesn't happen, we assume query is
1511
+ * unaffected by this mutation and it’s safe to delete it from local queue
1512
+ */
1513
+ _cleanupPendingMutationsTimeout() {
1514
+ if (this._pendingMutations().size < this._pendingMutationCleanupThreshold) {
1515
+ return;
1516
+ }
1517
+ const now = Date.now();
1518
+ this._updatePendingMutations((prev) => {
1519
+ for (const [eventId, mut] of Array.from(prev.entries())) {
1520
+ if (mut.confirmed &&
1521
+ mut.confirmed + this._pendingTxCleanupTimeout < now) {
1522
+ prev.delete(eventId);
1523
+ }
1524
+ }
1525
+ });
1526
+ }
1527
+ _trySendAuthed(...args) {
1528
+ if (this.status !== exports.STATUS.AUTHENTICATED) {
1529
+ return;
1530
+ }
1531
+ this._trySend(...args);
1532
+ }
1533
+ _trySend(eventId, msg, opts) {
1534
+ if (!this._transport.isOpen()) {
1535
+ return;
1536
+ }
1537
+ if (!ignoreLogging[msg.op]) {
1538
+ this._log.info('[send]', this._transport.id, msg.op, {
1539
+ 'client-event-id': eventId,
1540
+ ...msg,
1541
+ });
1542
+ }
1543
+ switch (msg.op) {
1544
+ case 'transact': {
1545
+ this._inFlightMutationEventIds.add(eventId);
1546
+ break;
1547
+ }
1548
+ case 'init': {
1549
+ // New connection, so we can't have any mutations in flight
1550
+ this._inFlightMutationEventIds.clear();
1551
+ }
1552
+ }
1553
+ this._transport.send({ 'client-event-id': eventId, ...msg });
1554
+ }
1555
+ _transportOnOpen = (e) => {
1556
+ const targetTransport = e.target;
1557
+ if (this._transport !== targetTransport) {
1558
+ this._log.info('[socket][open]', targetTransport.id, 'skip; this is no longer the current transport');
1559
+ return;
1560
+ }
1561
+ this._log.info('[socket][open]', this._transport.id);
1562
+ this._setStatus(exports.STATUS.OPENED);
1563
+ this.getCurrentUser()
1564
+ .then((resp) => {
1565
+ this._trySend((0, id_ts_1.default)(), {
1566
+ op: 'init',
1567
+ 'app-id': this.config.appId,
1568
+ 'refresh-token': resp.user?.['refresh_token'],
1569
+ versions: this.versions,
1570
+ // If an admin token is provided for an app, we will
1571
+ // skip all permission checks. This is an advanced feature,
1572
+ // to let users write internal tools
1573
+ // This option is not exposed in `Config`, as it's
1574
+ // not ready for prime time
1575
+ '__admin-token': this.config.__adminToken,
1576
+ });
1577
+ })
1578
+ .catch((e) => {
1579
+ this._log.error('[socket][error]', targetTransport.id, e);
1580
+ });
1581
+ };
1582
+ _transportOnMessage = (e) => {
1583
+ const targetTransport = e.target;
1584
+ const m = e.message;
1585
+ if (this._transport !== targetTransport) {
1586
+ this._log.info('[socket][message]', targetTransport.id, m, 'skip; this is no longer the current transport');
1587
+ return;
1588
+ }
1589
+ if (!this._wsOk && targetTransport.type === 'ws') {
1590
+ this._wsOk = true;
1591
+ }
1592
+ // Try to reconnect via websocket the next time we connect
1593
+ this._transportType = 'ws';
1594
+ if (Array.isArray(e.message)) {
1595
+ for (const msg of e.message) {
1596
+ this._handleReceive(targetTransport.id, msg);
1597
+ }
1598
+ }
1599
+ else {
1600
+ this._handleReceive(targetTransport.id, e.message);
1601
+ }
1602
+ };
1603
+ _transportOnError = (e) => {
1604
+ const targetTransport = e.target;
1605
+ if (this._transport !== targetTransport) {
1606
+ this._log.info('[socket][error]', targetTransport.id, 'skip; this is no longer the current transport');
1607
+ return;
1608
+ }
1609
+ this._log.error('[socket][error]', targetTransport.id, e);
1610
+ };
1611
+ _scheduleReconnect = () => {
1612
+ // If we couldn't connect with a websocket last time, try sse
1613
+ if (!this._wsOk && this._transportType !== 'sse') {
1614
+ this._transportType = 'sse';
1615
+ this._reconnectTimeoutMs = 0;
1616
+ }
1617
+ setTimeout(() => {
1618
+ this._reconnectTimeoutMs = Math.min(this._reconnectTimeoutMs + 1000, 10000);
1619
+ if (!this._isOnline) {
1620
+ this._log.info('[socket][close]', this._transport.id, 'we are offline, no need to start socket');
1621
+ return;
1622
+ }
1623
+ this._startSocket();
1624
+ }, this._reconnectTimeoutMs);
1625
+ };
1626
+ _transportOnClose = (e) => {
1627
+ const targetTransport = e.target;
1628
+ if (this._transport !== targetTransport) {
1629
+ this._log.info('[socket][close]', targetTransport.id, 'skip; this is no longer the current transport');
1630
+ return;
1631
+ }
1632
+ this._setStatus(exports.STATUS.CLOSED);
1633
+ for (const room of Object.values(this._rooms)) {
1634
+ room.isConnected = false;
1635
+ }
1636
+ if (this._isShutdown) {
1637
+ this._log.info('[socket][close]', targetTransport.id, 'Reactor has been shut down and will not reconnect');
1638
+ return;
1639
+ }
1640
+ this._log.info('[socket][close]', targetTransport.id, 'schedule reconnect, ms =', this._reconnectTimeoutMs);
1641
+ this._scheduleReconnect();
1642
+ };
1643
+ _startSocket() {
1644
+ // Reset whether we support websockets each time we connect
1645
+ // new networks may not support websockets
1646
+ this._wsOk = null;
1647
+ if (this._isShutdown) {
1648
+ this._log.info('[socket][start]', this.config.appId, 'Reactor has been shut down and will not start a new socket');
1649
+ return;
1650
+ }
1651
+ if (this._transport && this._transport.isConnecting()) {
1652
+ // Our current websocket is in a 'connecting' state.
1653
+ // There's no need to start another one, as the socket is
1654
+ // effectively fresh.
1655
+ this._log.info('[socket][start]', this._transport.id, 'maintained as current transport, we were still in a connecting state');
1656
+ return;
1657
+ }
1658
+ const prevTransport = this._transport;
1659
+ this._transport = createTransport({
1660
+ transportType: this._transportType,
1661
+ appId: this.config.appId,
1662
+ apiURI: this.config.apiURI,
1663
+ wsURI: this.config.websocketURI,
1664
+ EventSourceImpl: this._EventSource,
1665
+ });
1666
+ this._transport.onopen = this._transportOnOpen;
1667
+ this._transport.onmessage = this._transportOnMessage;
1668
+ this._transport.onclose = this._transportOnClose;
1669
+ this._transport.onerror = this._transportOnError;
1670
+ this._log.info('[socket][start]', this._transport.id);
1671
+ if (prevTransport?.isOpen()) {
1672
+ // When the network dies, it doesn't always mean that our
1673
+ // socket connection will fire a close event.
1674
+ //
1675
+ // We _could_ re-use the old socket, if the network drop was a
1676
+ // few seconds. But, to be safe right now we always create a new socket.
1677
+ //
1678
+ // This means that we have to make sure to kill the previous one ourselves.
1679
+ // c.f https://issues.chromium.org/issues/41343684
1680
+ this._log.info('[socket][start]', this._transport.id, 'close previous transport id = ', prevTransport.id);
1681
+ prevTransport.close();
1682
+ }
1683
+ }
1684
+ /**
1685
+ * Given a key, returns a stable local id, unique to this device and app.
1686
+ *
1687
+ * This can be useful if you want to create guest ids for example.
1688
+ *
1689
+ * Note: If the user deletes their local storage, this id will change.
1690
+ *
1691
+ */
1692
+ async getLocalId(name) {
1693
+ const k = `localToken_${name}`;
1694
+ if (this.kv.currentValue[k]) {
1695
+ return this.kv.currentValue[k];
1696
+ }
1697
+ const current = await this.kv.waitForKeyToLoad(k);
1698
+ if (current) {
1699
+ return current;
1700
+ }
1701
+ const newId = (0, id_ts_1.default)();
1702
+ this.kv.updateInPlace((prev) => {
1703
+ if (prev[k])
1704
+ return;
1705
+ prev[k] = newId;
1706
+ });
1707
+ return await this.kv.waitForKeyToLoad(k);
1708
+ }
1709
+ // ----
1710
+ // Auth
1711
+ _replaceUrlAfterOAuth() {
1712
+ if (typeof URL === 'undefined') {
1713
+ return;
1714
+ }
1715
+ const url = new URL(window.location.href);
1716
+ if (url.searchParams.get(OAUTH_REDIRECT_PARAM)) {
1717
+ const startUrl = url.toString();
1718
+ url.searchParams.delete(OAUTH_REDIRECT_PARAM);
1719
+ url.searchParams.delete(OAUTH_EXTRA_FIELDS_ID_PARAM);
1720
+ url.searchParams.delete('code');
1721
+ url.searchParams.delete('error');
1722
+ const newPath = url.pathname +
1723
+ (url.searchParams.size ? '?' + url.searchParams : '') +
1724
+ url.hash;
1725
+ // Note: In next.js, this will revert to the old state if user navigates
1726
+ // back. We would need to allow framework specific routing to work
1727
+ // around that problem.
1728
+ history.replaceState(history.state, '', newPath);
1729
+ // navigation is part of the HTML spec, but not supported by Safari
1730
+ // or Firefox yet:
1731
+ // https://developer.mozilla.org/en-US/docs/Web/API/Navigation_API#browser_compatibility
1732
+ if (
1733
+ // @ts-ignore (waiting for ts support)
1734
+ typeof navigation === 'object' &&
1735
+ // @ts-ignore (waiting for ts support)
1736
+ typeof navigation.addEventListener === 'function' &&
1737
+ // @ts-ignore (waiting for ts support)
1738
+ typeof navigation.removeEventListener === 'function') {
1739
+ let ran = false;
1740
+ // The next.js app router will reset the URL when the router loads.
1741
+ // This puts it back after the router loads.
1742
+ const listener = (e) => {
1743
+ if (!ran) {
1744
+ ran = true;
1745
+ // @ts-ignore (waiting for ts support)
1746
+ navigation.removeEventListener('navigate', listener);
1747
+ if (!e.userInitiated &&
1748
+ e.navigationType === 'replace' &&
1749
+ e.destination?.url === startUrl) {
1750
+ history.replaceState(history.state, '', newPath);
1751
+ }
1752
+ }
1753
+ };
1754
+ // @ts-ignore (waiting for ts support)
1755
+ navigation.addEventListener('navigate', listener);
1756
+ }
1757
+ }
1758
+ }
1759
+ /**
1760
+ *
1761
+ * @returns Promise<null | {error: {message: string}}>
1762
+ */
1763
+ async _oauthLoginInit() {
1764
+ if (typeof window === 'undefined' ||
1765
+ typeof window.location === 'undefined' ||
1766
+ typeof URLSearchParams === 'undefined') {
1767
+ return null;
1768
+ }
1769
+ const params = new URLSearchParams(window.location.search);
1770
+ if (!params.get(OAUTH_REDIRECT_PARAM)) {
1771
+ return null;
1772
+ }
1773
+ const error = params.get('error');
1774
+ if (error) {
1775
+ this._replaceUrlAfterOAuth();
1776
+ return { error: { message: error } };
1777
+ }
1778
+ const code = params.get('code');
1779
+ if (!code) {
1780
+ return null;
1781
+ }
1782
+ const extraFieldsId = params.get(OAUTH_EXTRA_FIELDS_ID_PARAM);
1783
+ this._replaceUrlAfterOAuth();
1784
+ try {
1785
+ let extraFields;
1786
+ const stored = await this.kv.waitForKeyToLoad(oauthExtraFieldsKey);
1787
+ if (extraFieldsId && stored) {
1788
+ extraFields = stored[extraFieldsId];
1789
+ }
1790
+ // Clean up all stored extraFields after login
1791
+ if (stored) {
1792
+ this.kv.updateInPlace((prev) => {
1793
+ delete prev[oauthExtraFieldsKey];
1794
+ });
1795
+ }
1796
+ const currentUser = await this._getCurrentUser();
1797
+ const isGuest = currentUser?.type === 'guest';
1798
+ const { user } = await authAPI.exchangeCodeForToken({
1799
+ apiURI: this.config.apiURI,
1800
+ appId: this.config.appId,
1801
+ code,
1802
+ refreshToken: isGuest ? currentUser.refresh_token : undefined,
1803
+ extraFields,
1804
+ });
1805
+ this.setCurrentUser(user);
1806
+ return null;
1807
+ }
1808
+ catch (e) {
1809
+ if (e?.body?.type === 'record-not-found' &&
1810
+ e?.body?.hint?.['record-type'] === 'app-oauth-code' &&
1811
+ (await this._hasCurrentUser())) {
1812
+ // We probably just weren't able to clean up the URL, so
1813
+ // let's just ignore this error
1814
+ return null;
1815
+ }
1816
+ const message = e?.body?.message || 'Error logging in.';
1817
+ return { error: { message } };
1818
+ }
1819
+ }
1820
+ async _waitForOAuthCallbackResponse() {
1821
+ return await this._oauthCallbackResponse;
1822
+ }
1823
+ __subscribeMutationErrors(cb) {
1824
+ this.mutationErrorCbs.push(cb);
1825
+ return () => {
1826
+ this.mutationErrorCbs = this.mutationErrorCbs.filter((x) => x !== cb);
1827
+ };
1828
+ }
1829
+ subscribeAuth(cb) {
1830
+ this.authCbs.push(cb);
1831
+ const currUserCached = this._currentUserCached;
1832
+ if (!currUserCached.isLoading) {
1833
+ cb(this._currentUserCached);
1834
+ }
1835
+ let unsubbed = false;
1836
+ this.getCurrentUser().then((resp) => {
1837
+ if (unsubbed)
1838
+ return;
1839
+ if ((0, object_js_1.areObjectsDeepEqual)(resp, currUserCached))
1840
+ return;
1841
+ cb(resp);
1842
+ });
1843
+ return () => {
1844
+ unsubbed = true;
1845
+ this.authCbs = this.authCbs.filter((x) => x !== cb);
1846
+ };
1847
+ }
1848
+ async getAuth() {
1849
+ const { user, error } = await this.getCurrentUser();
1850
+ if (error) {
1851
+ throw new InstantError_ts_1.InstantError('Could not get current user: ' + error.message);
1852
+ }
1853
+ return user ?? null;
1854
+ }
1855
+ subscribeConnectionStatus(cb) {
1856
+ this.connectionStatusCbs.push(cb);
1857
+ return () => {
1858
+ this.connectionStatusCbs = this.connectionStatusCbs.filter((x) => x !== cb);
1859
+ };
1860
+ }
1861
+ /**
1862
+ * @param {'active' | 'read-only' | 'disabled' | undefined} status
1863
+ */
1864
+ _setAppStatus(status) {
1865
+ if (!status || status === this._appStatusState.status)
1866
+ return;
1867
+ this._appStatusState = {
1868
+ isLoading: false,
1869
+ isReadOnly: status !== 'active',
1870
+ status,
1871
+ };
1872
+ this.notifyAppStatusSubs(this._appStatusState);
1873
+ }
1874
+ subscribeAppStatus(cb) {
1875
+ this.appStatusCbs.push(cb);
1876
+ cb(this._appStatusState);
1877
+ return () => {
1878
+ this.appStatusCbs = this.appStatusCbs.filter((x) => x !== cb);
1879
+ };
1880
+ }
1881
+ subscribeAttrs(cb) {
1882
+ this.attrsCbs.push(cb);
1883
+ if (this.attrs) {
1884
+ cb(this.attrs.attrs);
1885
+ }
1886
+ return () => {
1887
+ this.attrsCbs = this.attrsCbs.filter((x) => x !== cb);
1888
+ };
1889
+ }
1890
+ notifyAuthSubs(user) {
1891
+ this.authCbs.forEach((cb) => cb(user));
1892
+ }
1893
+ notifyMutationErrorSubs(error) {
1894
+ this.mutationErrorCbs.forEach((cb) => cb(error));
1895
+ }
1896
+ notifyAttrsSubs() {
1897
+ if (!this.attrs)
1898
+ return;
1899
+ const oas = this.optimisticAttrs();
1900
+ this.attrsCbs.forEach((cb) => cb(oas.attrs));
1901
+ }
1902
+ notifyConnectionStatusSubs(status) {
1903
+ this.connectionStatusCbs.forEach((cb) => cb(status));
1904
+ }
1905
+ notifyAppStatusSubs(state) {
1906
+ this.appStatusCbs.forEach((cb) => cb(state));
1907
+ }
1908
+ async setCurrentUser(user) {
1909
+ this.kv.updateInPlace((prev) => {
1910
+ prev[currentUserKey] = user;
1911
+ });
1912
+ await this.kv.waitForKeyToLoad(currentUserKey);
1913
+ }
1914
+ getCurrentUserCached() {
1915
+ return this._currentUserCached;
1916
+ }
1917
+ /**
1918
+ * @param {{ forceReadFromStorage?: boolean }} [opts]
1919
+ * @returns {Promise<User | undefined>}
1920
+ */
1921
+ async _getCurrentUser(opts) {
1922
+ if (opts?.forceReadFromStorage) {
1923
+ await this.kv.unloadKey(currentUserKey);
1924
+ }
1925
+ const user = await this.kv.waitForKeyToLoad(currentUserKey);
1926
+ return typeof user === 'string' ? JSON.parse(user) : user;
1927
+ }
1928
+ /**
1929
+ * @param {{ forceReadFromStorage?: boolean }} [opts]
1930
+ * @returns {Promise<AuthState>}
1931
+ */
1932
+ async getCurrentUser(opts) {
1933
+ const oauthResp = await this._waitForOAuthCallbackResponse();
1934
+ if (oauthResp?.error) {
1935
+ const errorV = { error: oauthResp.error, user: undefined };
1936
+ this._currentUserCached = { isLoading: false, ...errorV };
1937
+ return this._currentUserCached;
1938
+ }
1939
+ try {
1940
+ const user = await this._getCurrentUser(opts);
1941
+ const userV = { user: user, error: undefined };
1942
+ this._currentUserCached = {
1943
+ isLoading: false,
1944
+ ...userV,
1945
+ };
1946
+ return this._currentUserCached;
1947
+ }
1948
+ catch (e) {
1949
+ return {
1950
+ user: undefined,
1951
+ isLoading: false,
1952
+ error: { message: e?.message || 'Error loading user' },
1953
+ };
1954
+ }
1955
+ }
1956
+ async _hasCurrentUser() {
1957
+ const user = await this.kv.waitForKeyToLoad(currentUserKey);
1958
+ return typeof user === 'string' ? JSON.parse(user) != null : user != null;
1959
+ }
1960
+ async changeCurrentUser(newUser) {
1961
+ const { user: oldUser } = await this.getCurrentUser();
1962
+ if ((0, object_js_1.areObjectsDeepEqual)(oldUser, newUser)) {
1963
+ // We were already logged in as the newUser, don't
1964
+ // bother updating
1965
+ return;
1966
+ }
1967
+ // Clear any data in the framework client
1968
+ this._frameworkClient = null;
1969
+ await this.setCurrentUser(newUser);
1970
+ // We need to remove all `result` from querySubs,
1971
+ // as they are no longer valid for the new user
1972
+ await this.updateUser(newUser);
1973
+ try {
1974
+ // Make sure everything is written to storage before we tell the
1975
+ // other tab to refetch
1976
+ await this.kv.flush();
1977
+ this._broadcastChannel?.postMessage({ type: 'auth' });
1978
+ }
1979
+ catch (error) {
1980
+ console.error('Error posting message to broadcast channel', error);
1981
+ }
1982
+ }
1983
+ async setupUserSyncTimer() {
1984
+ if (!this.config.firstPartyPath)
1985
+ return;
1986
+ try {
1987
+ const lastSynced = await this.kv.waitForKeyToLoad(exports.COOKIE_SYNC_LAST_UPDATED_KEY);
1988
+ const lastSyncTime = lastSynced ? new Date(lastSynced).getTime() : 0;
1989
+ const shouldSync = !Number.isFinite(lastSyncTime) ||
1990
+ Date.now() - lastSyncTime >= ONE_DAY_MS;
1991
+ if (!shouldSync)
1992
+ return;
1993
+ const { user } = await this.getCurrentUser();
1994
+ await this.syncUserToEndpoint(user ?? null);
1995
+ }
1996
+ catch (error) {
1997
+ this._log.error('Error syncing user cookie on startup', error);
1998
+ }
1999
+ }
2000
+ async syncUserToEndpoint(user) {
2001
+ if (!this.config.firstPartyPath)
2002
+ return;
2003
+ try {
2004
+ const response = await fetch(this.config.firstPartyPath + '/', {
2005
+ method: 'POST',
2006
+ body: JSON.stringify({
2007
+ type: 'sync-user',
2008
+ appId: this.config.appId,
2009
+ user: user,
2010
+ }),
2011
+ headers: {
2012
+ 'Content-Type': 'application/json',
2013
+ },
2014
+ });
2015
+ if (!response.ok) {
2016
+ throw new Error(`HTTP error! status: ${response.status}`);
2017
+ }
2018
+ }
2019
+ catch (error) {
2020
+ this._log.error('Error syncing user with external endpoint', error);
2021
+ }
2022
+ this.kv.updateInPlace((prev) => {
2023
+ prev[exports.COOKIE_SYNC_LAST_UPDATED_KEY] = new Date().toISOString();
2024
+ });
2025
+ }
2026
+ async updateUser(newUser) {
2027
+ const newV = { error: undefined, user: newUser };
2028
+ this._currentUserCached = { isLoading: false, ...newV };
2029
+ this._dataForQueryCache = {};
2030
+ this._dataForQueryMemo = {};
2031
+ this.querySubs.updateInPlace((prev) => {
2032
+ Object.keys(prev).forEach((k) => {
2033
+ delete prev[k].result;
2034
+ });
2035
+ });
2036
+ this.querySubs.clearUnloadedKeys();
2037
+ this._updatePendingMutations((prev) => {
2038
+ // Mark all pending mutations with an error, since we won't be able to
2039
+ // deliver the result
2040
+ for (const [eventId, _v] of prev.entries()) {
2041
+ if (this.mutationDeferredStore.get(eventId)) {
2042
+ this._finishTransaction('error', eventId, {
2043
+ message: 'User changed while transaction was in progress.',
2044
+ type: 'user-changed',
2045
+ });
2046
+ }
2047
+ }
2048
+ prev.clear();
2049
+ });
2050
+ this._reconnectTimeoutMs = 0;
2051
+ this._transport.close();
2052
+ this._oauthCallbackResponse = null;
2053
+ this.notifyAuthSubs(newV);
2054
+ try {
2055
+ await this.syncUserToEndpoint(newUser);
2056
+ }
2057
+ catch (error) {
2058
+ this._log.error('Error syncing user with external endpoint', error);
2059
+ }
2060
+ }
2061
+ sendMagicCode({ email }) {
2062
+ return authAPI.sendMagicCode({
2063
+ apiURI: this.config.apiURI,
2064
+ appId: this.config.appId,
2065
+ email: email,
2066
+ });
2067
+ }
2068
+ async signInWithMagicCode(params) {
2069
+ const currentUser = await this.getCurrentUser();
2070
+ const isGuest = currentUser?.user?.type === 'guest';
2071
+ const res = await authAPI.checkMagicCode({
2072
+ apiURI: this.config.apiURI,
2073
+ appId: this.config.appId,
2074
+ email: params.email,
2075
+ code: params.code,
2076
+ refreshToken: isGuest ? currentUser?.user?.refresh_token : undefined,
2077
+ extraFields: params.extraFields,
2078
+ });
2079
+ await this.changeCurrentUser(res.user);
2080
+ return res;
2081
+ }
2082
+ async signInWithCustomToken(authToken) {
2083
+ const res = await authAPI.verifyRefreshToken({
2084
+ apiURI: this.config.apiURI,
2085
+ appId: this.config.appId,
2086
+ refreshToken: authToken,
2087
+ });
2088
+ await this.changeCurrentUser(res.user);
2089
+ return res;
2090
+ }
2091
+ async signInAsGuest(params) {
2092
+ const res = await authAPI.signInAsGuest({
2093
+ apiURI: this.config.apiURI,
2094
+ appId: this.config.appId,
2095
+ extraFields: params?.extraFields,
2096
+ });
2097
+ await this.changeCurrentUser(res.user);
2098
+ return res;
2099
+ }
2100
+ potentiallyInvalidateToken(currentUser, opts) {
2101
+ const refreshToken = currentUser?.user?.refresh_token;
2102
+ if (!refreshToken) {
2103
+ return;
2104
+ }
2105
+ const wantsToSkip = opts.invalidateToken === false;
2106
+ if (wantsToSkip) {
2107
+ this._log.info('[auth-invalidate] skipped invalidateToken');
2108
+ return;
2109
+ }
2110
+ authAPI
2111
+ .signOut({
2112
+ apiURI: this.config.apiURI,
2113
+ appId: this.config.appId,
2114
+ refreshToken,
2115
+ })
2116
+ .then(() => {
2117
+ this._log.info('[auth-invalidate] completed invalidateToken');
2118
+ })
2119
+ .catch((e) => { });
2120
+ }
2121
+ async signOut(opts) {
2122
+ const currentUser = await this.getCurrentUser();
2123
+ this.potentiallyInvalidateToken(currentUser, opts);
2124
+ await this.changeCurrentUser(null);
2125
+ }
2126
+ /**
2127
+ * Creates an OAuth authorization URL.
2128
+ *
2129
+ * @param {Object} params - The parameters to create the authorization URL.
2130
+ * @param {string} params.clientName - The name of the client requesting authorization.
2131
+ * @param {string} params.redirectURL - The URL to redirect users to after authorization.
2132
+ * @param {Record<string, any>} [params.extraFields] - Extra fields to write to $users on creation
2133
+ * @returns {string} The created authorization URL.
2134
+ */
2135
+ createAuthorizationURL({ clientName, redirectURL, extraFields }) {
2136
+ const { apiURI, appId } = this.config;
2137
+ let finalRedirectURL = redirectURL;
2138
+ if (extraFields) {
2139
+ // Store extraFields under a unique ID so multiple
2140
+ // createAuthorizationURL calls don't overwrite each other.
2141
+ // The ID is passed through the redirect URL and used
2142
+ // by _oauthLoginInit to retrieve the right extraFields.
2143
+ // All entries are cleaned up after login.
2144
+ const extraFieldsId = `${Math.random().toString(36).slice(2)}`;
2145
+ this.kv.updateInPlace((prev) => {
2146
+ const stored = prev[oauthExtraFieldsKey] || {};
2147
+ stored[extraFieldsId] = extraFields;
2148
+ prev[oauthExtraFieldsKey] = stored;
2149
+ });
2150
+ finalRedirectURL = `${redirectURL}${redirectURL.includes('?') ? '&' : '?'}${OAUTH_EXTRA_FIELDS_ID_PARAM}=${extraFieldsId}`;
2151
+ }
2152
+ return `${apiURI}/runtime/oauth/start?app_id=${appId}&client_name=${clientName}&redirect_uri=${encodeURIComponent(finalRedirectURL)}`;
2153
+ }
2154
+ /**
2155
+ * @param {Object} params
2156
+ * @param {string} params.code - The code received from the OAuth service.
2157
+ * @param {string} [params.codeVerifier] - The code verifier used to generate the code challenge.
2158
+ * @param {Record<string, any>} [params.extraFields] - Extra fields to write to $users on creation
2159
+ */
2160
+ async exchangeCodeForToken({ code, codeVerifier, extraFields }) {
2161
+ const currentUser = await this.getCurrentUser();
2162
+ const isGuest = currentUser?.user?.type === 'guest';
2163
+ const res = await authAPI.exchangeCodeForToken({
2164
+ apiURI: this.config.apiURI,
2165
+ appId: this.config.appId,
2166
+ code: code,
2167
+ codeVerifier,
2168
+ refreshToken: isGuest ? currentUser?.user?.refresh_token : undefined,
2169
+ extraFields,
2170
+ });
2171
+ await this.changeCurrentUser(res.user);
2172
+ return res;
2173
+ }
2174
+ issuerURI() {
2175
+ const { apiURI, appId } = this.config;
2176
+ return `${apiURI}/runtime/${appId}`;
2177
+ }
2178
+ /**
2179
+ * @param {Object} params
2180
+ * @param {string} params.clientName - The name of the client requesting authorization.
2181
+ * @param {string} params.idToken - The id_token from the external service
2182
+ * @param {string | null | undefined} [params.nonce] - The nonce used when requesting the id_token from the external service
2183
+ * @param {Record<string, any>} [params.extraFields] - Extra fields to write to $users on creation
2184
+ */
2185
+ async signInWithIdToken(params) {
2186
+ const currentUser = await this.getCurrentUser();
2187
+ const refreshToken = currentUser?.user?.refresh_token;
2188
+ const res = await authAPI.signInWithIdToken({
2189
+ apiURI: this.config.apiURI,
2190
+ appId: this.config.appId,
2191
+ idToken: params.idToken,
2192
+ clientName: params.clientName,
2193
+ nonce: params.nonce,
2194
+ refreshToken,
2195
+ extraFields: params.extraFields,
2196
+ });
2197
+ await this.changeCurrentUser(res.user);
2198
+ return res;
2199
+ }
2200
+ // --------
2201
+ // Rooms
2202
+ /**
2203
+ * @param {string} roomType
2204
+ * @param {string} roomId
2205
+ * @param {any | null | undefined} [initialPresence] -- initial presence data to send when joining the room
2206
+ * @returns () => void
2207
+ */
2208
+ joinRoom(roomType, roomId, initialPresence) {
2209
+ let needsToSendJoin = false;
2210
+ if (!this._rooms[roomId]) {
2211
+ needsToSendJoin = true;
2212
+ this._rooms[roomId] = {
2213
+ roomType,
2214
+ isConnected: false,
2215
+ error: undefined,
2216
+ };
2217
+ }
2218
+ this._presence[roomId] = this._presence[roomId] || {};
2219
+ const previousResult = this._presence[roomId].result;
2220
+ if (initialPresence && !previousResult) {
2221
+ this._presence[roomId].result = this._presence[roomId].result || {};
2222
+ this._presence[roomId].result.user = initialPresence;
2223
+ this._notifyPresenceSubs(roomId);
2224
+ }
2225
+ if (needsToSendJoin) {
2226
+ this._tryJoinRoom(roomType, roomId, initialPresence);
2227
+ }
2228
+ return () => {
2229
+ this._cleanupRoom(roomId);
2230
+ };
2231
+ }
2232
+ _cleanupRoom(roomId) {
2233
+ if (!this._presence[roomId]?.handlers?.length &&
2234
+ !Object.keys(this._broadcastSubs[roomId] ?? {}).length) {
2235
+ const isConnected = this._rooms[roomId]?.isConnected;
2236
+ delete this._rooms[roomId];
2237
+ delete this._presence[roomId];
2238
+ delete this._broadcastSubs[roomId];
2239
+ if (isConnected) {
2240
+ this._tryLeaveRoom(roomId);
2241
+ }
2242
+ else {
2243
+ this._roomsPendingLeave[roomId] = true;
2244
+ }
2245
+ }
2246
+ }
2247
+ // --------
2248
+ // Presence
2249
+ // TODO: look into typing again
2250
+ getPresence(roomType, roomId, opts = {}) {
2251
+ const room = this._rooms[roomId];
2252
+ const presence = this._presence[roomId];
2253
+ if (!room || !presence || !presence.result)
2254
+ return null;
2255
+ return {
2256
+ ...(0, presence_ts_1.buildPresenceSlice)(presence.result, opts, this._sessionId),
2257
+ isLoading: !room.isConnected,
2258
+ error: room.error,
2259
+ };
2260
+ }
2261
+ // TODO: look into typing again
2262
+ publishPresence(roomType, roomId, partialData) {
2263
+ const room = this._rooms[roomId];
2264
+ const presence = this._presence[roomId];
2265
+ if (!room || !presence) {
2266
+ return;
2267
+ }
2268
+ presence.result = presence.result || {};
2269
+ const data = {
2270
+ ...presence.result.user,
2271
+ ...partialData,
2272
+ };
2273
+ presence.result.user = data;
2274
+ if (!room.isConnected) {
2275
+ return;
2276
+ }
2277
+ this._trySetPresence(roomId, data);
2278
+ this._notifyPresenceSubs(roomId);
2279
+ }
2280
+ _trySetPresence(roomId, data) {
2281
+ this._trySendAuthed((0, id_ts_1.default)(), {
2282
+ op: 'set-presence',
2283
+ 'room-id': roomId,
2284
+ data,
2285
+ });
2286
+ }
2287
+ _tryJoinRoom(roomType, roomId, data) {
2288
+ this._trySendAuthed((0, id_ts_1.default)(), {
2289
+ op: 'join-room',
2290
+ 'room-type': roomType,
2291
+ 'room-id': roomId,
2292
+ data,
2293
+ });
2294
+ delete this._roomsPendingLeave[roomId];
2295
+ }
2296
+ _tryLeaveRoom(roomId) {
2297
+ this._trySendAuthed((0, id_ts_1.default)(), { op: 'leave-room', 'room-id': roomId });
2298
+ }
2299
+ _trySetRoomConnected(roomId, isConnected) {
2300
+ const room = this._rooms[roomId];
2301
+ if (room) {
2302
+ room.isConnected = isConnected;
2303
+ }
2304
+ }
2305
+ // TODO: look into typing again
2306
+ subscribePresence(roomType, roomId, opts, cb) {
2307
+ const leaveRoom = this.joinRoom(roomType, roomId,
2308
+ // Oct 28, 2025
2309
+ // Note: initialData is deprecated.
2310
+ // Keeping here for backwards compatibility
2311
+ opts.initialPresence || opts.initialData);
2312
+ const handler = { ...opts, roomId, cb, prev: null };
2313
+ this._presence[roomId] = this._presence[roomId] || {};
2314
+ this._presence[roomId].handlers = this._presence[roomId].handlers || [];
2315
+ this._presence[roomId].handlers.push(handler);
2316
+ this._notifyPresenceSub(roomId, handler);
2317
+ return () => {
2318
+ this._presence[roomId].handlers =
2319
+ this._presence[roomId]?.handlers?.filter((x) => x !== handler) ?? [];
2320
+ leaveRoom();
2321
+ };
2322
+ }
2323
+ _notifyPresenceSubs(roomId) {
2324
+ this._presence[roomId]?.handlers?.forEach((handler) => {
2325
+ this._notifyPresenceSub(roomId, handler);
2326
+ });
2327
+ }
2328
+ _notifyPresenceSub(roomId, handler) {
2329
+ const slice = this.getPresence('', roomId, handler);
2330
+ if (!slice) {
2331
+ return;
2332
+ }
2333
+ if (handler.prev && !(0, presence_ts_1.hasPresenceResponseChanged)(slice, handler.prev)) {
2334
+ return;
2335
+ }
2336
+ handler.prev = slice;
2337
+ handler.cb(slice);
2338
+ }
2339
+ _patchPresencePeers(roomId, edits) {
2340
+ const peers = this._presence[roomId]?.result?.peers || {};
2341
+ let sessions = Object.fromEntries(Object.entries(peers).map(([k, v]) => [k, { data: v }]));
2342
+ const myPresence = this._presence[roomId]?.result;
2343
+ const newSessions = (0, mutative_1.create)(sessions, (draft) => {
2344
+ for (let [path, op, value] of edits) {
2345
+ switch (op) {
2346
+ case '+':
2347
+ (0, object_js_1.insertInMutative)(draft, path, value);
2348
+ break;
2349
+ case 'r':
2350
+ (0, object_js_1.assocInMutative)(draft, path, value);
2351
+ break;
2352
+ case '-':
2353
+ (0, object_js_1.dissocInMutative)(draft, path);
2354
+ break;
2355
+ }
2356
+ }
2357
+ // Ignore our own edits
2358
+ delete draft[this._sessionId];
2359
+ });
2360
+ this._setPresencePeers(roomId, newSessions);
2361
+ }
2362
+ _setPresencePeers(roomId, data) {
2363
+ const sessions = { ...data };
2364
+ // no need to keep track of `user`
2365
+ delete sessions[this._sessionId];
2366
+ const peers = Object.fromEntries(Object.entries(sessions).map(([k, v]) => [k, v.data]));
2367
+ this._presence = (0, mutative_1.create)(this._presence, (draft) => {
2368
+ (0, object_js_1.assocInMutative)(draft, [roomId, 'result', 'peers'], peers);
2369
+ });
2370
+ }
2371
+ // --------
2372
+ // Broadcast
2373
+ publishTopic({ roomType, roomId, topic, data }) {
2374
+ const room = this._rooms[roomId];
2375
+ if (!room) {
2376
+ return;
2377
+ }
2378
+ if (!room.isConnected) {
2379
+ this._broadcastQueue[roomId] = this._broadcastQueue[roomId] ?? [];
2380
+ this._broadcastQueue[roomId].push({ topic, roomType, data });
2381
+ return;
2382
+ }
2383
+ this._tryBroadcast(roomId, roomType, topic, data);
2384
+ }
2385
+ _tryBroadcast(roomId, roomType, topic, data) {
2386
+ this._trySendAuthed((0, id_ts_1.default)(), {
2387
+ op: 'client-broadcast',
2388
+ 'room-id': roomId,
2389
+ roomType,
2390
+ topic,
2391
+ data,
2392
+ });
2393
+ }
2394
+ subscribeTopic(roomType, roomId, topic, cb) {
2395
+ const leaveRoom = this.joinRoom(roomType, roomId);
2396
+ this._broadcastSubs[roomId] = this._broadcastSubs[roomId] || {};
2397
+ this._broadcastSubs[roomId][topic] =
2398
+ this._broadcastSubs[roomId][topic] || [];
2399
+ this._broadcastSubs[roomId][topic].push(cb);
2400
+ this._presence[roomId] = this._presence[roomId] || {};
2401
+ return () => {
2402
+ this._broadcastSubs[roomId][topic] = this._broadcastSubs[roomId][topic].filter((x) => x !== cb);
2403
+ if (!this._broadcastSubs[roomId][topic].length) {
2404
+ delete this._broadcastSubs[roomId][topic];
2405
+ }
2406
+ leaveRoom();
2407
+ };
2408
+ }
2409
+ _notifyBroadcastSubs(room, topic, msg) {
2410
+ this._broadcastSubs?.[room]?.[topic]?.forEach((cb) => {
2411
+ const data = msg.data?.data;
2412
+ const peer = msg.data['peer-id'] === this._sessionId
2413
+ ? this._presence[room]?.result?.user
2414
+ : this._presence[room]?.result?.peers?.[msg.data['peer-id']];
2415
+ return cb(data, peer);
2416
+ });
2417
+ }
2418
+ // --------
2419
+ // Storage
2420
+ async uploadFile(path, file, opts) {
2421
+ const currentUser = await this.getCurrentUser();
2422
+ const refreshToken = currentUser?.user?.refresh_token;
2423
+ return StorageApi.uploadFile({
2424
+ ...opts,
2425
+ apiURI: this.config.apiURI,
2426
+ appId: this.config.appId,
2427
+ path: path,
2428
+ file,
2429
+ refreshToken: refreshToken,
2430
+ });
2431
+ }
2432
+ async deleteFile(path) {
2433
+ const currentUser = await this.getCurrentUser();
2434
+ const refreshToken = currentUser?.user?.refresh_token;
2435
+ const result = await StorageApi.deleteFile({
2436
+ apiURI: this.config.apiURI,
2437
+ appId: this.config.appId,
2438
+ path,
2439
+ refreshToken: refreshToken,
2440
+ });
2441
+ return result;
2442
+ }
2443
+ // Deprecated Storage API (Jan 2025)
2444
+ // ---------------------------------
2445
+ async upload(path, file) {
2446
+ const currentUser = await this.getCurrentUser();
2447
+ const refreshToken = currentUser?.user?.refresh_token;
2448
+ const fileName = path || file.name;
2449
+ const url = await StorageApi.getSignedUploadUrl({
2450
+ apiURI: this.config.apiURI,
2451
+ appId: this.config.appId,
2452
+ fileName: fileName,
2453
+ refreshToken: refreshToken,
2454
+ });
2455
+ const isSuccess = await StorageApi.upload(url, file);
2456
+ return isSuccess;
2457
+ }
2458
+ async getDownloadUrl(path) {
2459
+ const currentUser = await this.getCurrentUser();
2460
+ const refreshToken = currentUser?.user?.refresh_token;
2461
+ const url = await StorageApi.getDownloadUrl({
2462
+ apiURI: this.config.apiURI,
2463
+ appId: this.config.appId,
2464
+ path: path,
2465
+ refreshToken: refreshToken,
2466
+ });
2467
+ return url;
2468
+ }
2469
+ }
2470
+ exports.default = Reactor;
2471
+ //# sourceMappingURL=Reactor.js.map