@sidekickdb/core 0.0.0 → 2.0.1

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