@sidekickdb/core 2.0.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (321) hide show
  1. package/README.md +1 -1
  2. package/__example__/standalone.esm.html +1 -1
  3. package/__example__/standalone.umd.html +2 -2
  4. package/__tests__/src/Reactor.test.ts +70 -25
  5. package/__tests__/src/batchedFrames.test.ts +110 -0
  6. package/__tests__/src/createRouteHandler.test.ts +30 -0
  7. package/__tests__/src/data/zeneca/triples.json +6 -6
  8. package/__tests__/src/dataForQueryMemo.test.ts +4 -4
  9. package/__tests__/src/datalog.test.ts +2 -2
  10. package/__tests__/src/devtool.test.ts +2 -2
  11. package/__tests__/src/endpoints.test.ts +2 -2
  12. package/__tests__/src/infiniteQuery.test.ts +142 -0
  13. package/__tests__/src/notifyScope.test.ts +6 -6
  14. package/__tests__/src/queryValidation.test.ts +3 -3
  15. package/__tests__/src/schema.test.ts +6 -6
  16. package/__tests__/src/serializeSchema.test.ts +2 -2
  17. package/__tests__/src/{instaml.test.ts → sideml.test.ts} +106 -112
  18. package/__tests__/src/{instaql.bench.ts → sideql.bench.ts} +1 -1
  19. package/__tests__/src/{instaql.test.ts → sideql.test.ts} +25 -34
  20. package/__tests__/src/{instaqlInference.test.ts → sideqlInference.test.ts} +1 -1
  21. package/__tests__/src/store.test.ts +32 -32
  22. package/__tests__/src/transactionValidation.test.ts +4 -4
  23. package/__tests__/src/utils/e2e.ts +8 -8
  24. package/dist/commonjs/Connection.d.ts +1 -0
  25. package/dist/commonjs/Connection.d.ts.map +1 -1
  26. package/dist/commonjs/Connection.js +19 -3
  27. package/dist/commonjs/Connection.js.map +1 -1
  28. package/dist/commonjs/IndexedDBStorage.d.ts.map +1 -1
  29. package/dist/commonjs/IndexedDBStorage.js +3 -160
  30. package/dist/commonjs/IndexedDBStorage.js.map +1 -1
  31. package/dist/commonjs/Reactor.d.ts +7 -7
  32. package/dist/commonjs/Reactor.d.ts.map +1 -1
  33. package/dist/commonjs/Reactor.js +37 -38
  34. package/dist/commonjs/Reactor.js.map +1 -1
  35. package/dist/commonjs/{InstantError.d.ts → SidekickError.d.ts} +2 -2
  36. package/dist/commonjs/SidekickError.d.ts.map +1 -0
  37. package/dist/commonjs/{InstantError.js → SidekickError.js} +7 -7
  38. package/dist/commonjs/SidekickError.js.map +1 -0
  39. package/dist/commonjs/Stream.d.ts +5 -5
  40. package/dist/commonjs/Stream.d.ts.map +1 -1
  41. package/dist/commonjs/Stream.js +14 -14
  42. package/dist/commonjs/Stream.js.map +1 -1
  43. package/dist/commonjs/SyncTable.d.ts +3 -3
  44. package/dist/commonjs/SyncTable.d.ts.map +1 -1
  45. package/dist/commonjs/SyncTable.js +7 -7
  46. package/dist/commonjs/SyncTable.js.map +1 -1
  47. package/dist/commonjs/attrTypes.d.ts +11 -11
  48. package/dist/commonjs/attrTypes.d.ts.map +1 -1
  49. package/dist/commonjs/attrTypes.js.map +1 -1
  50. package/dist/commonjs/coreTypes.d.ts +4 -4
  51. package/dist/commonjs/coreTypes.d.ts.map +1 -1
  52. package/dist/commonjs/coreTypes.js.map +1 -1
  53. package/dist/commonjs/createRouteHandler.d.ts +1 -1
  54. package/dist/commonjs/createRouteHandler.d.ts.map +1 -1
  55. package/dist/commonjs/createRouteHandler.js +5 -5
  56. package/dist/commonjs/createRouteHandler.js.map +1 -1
  57. package/dist/commonjs/devtool.js +13 -6
  58. package/dist/commonjs/devtool.js.map +1 -1
  59. package/dist/commonjs/endpoints.d.ts +2 -2
  60. package/dist/commonjs/endpoints.d.ts.map +1 -1
  61. package/dist/commonjs/endpoints.js +3 -3
  62. package/dist/commonjs/endpoints.js.map +1 -1
  63. package/dist/commonjs/framework.d.ts +4 -4
  64. package/dist/commonjs/framework.d.ts.map +1 -1
  65. package/dist/commonjs/framework.js +5 -5
  66. package/dist/commonjs/framework.js.map +1 -1
  67. package/dist/commonjs/helperTypes.d.ts +24 -24
  68. package/dist/commonjs/helperTypes.d.ts.map +1 -1
  69. package/dist/commonjs/helperTypes.js.map +1 -1
  70. package/dist/commonjs/index.d.ts +36 -36
  71. package/dist/commonjs/index.d.ts.map +1 -1
  72. package/dist/commonjs/index.js +36 -36
  73. package/dist/commonjs/index.js.map +1 -1
  74. package/dist/commonjs/infiniteQuery.d.ts +7 -7
  75. package/dist/commonjs/infiniteQuery.d.ts.map +1 -1
  76. package/dist/commonjs/infiniteQuery.js +16 -3
  77. package/dist/commonjs/infiniteQuery.js.map +1 -1
  78. package/dist/commonjs/model/{instaqlResult.d.ts → sideqlResult.d.ts} +2 -2
  79. package/dist/commonjs/model/sideqlResult.d.ts.map +1 -0
  80. package/dist/commonjs/model/{instaqlResult.js → sideqlResult.js} +2 -2
  81. package/dist/commonjs/model/sideqlResult.js.map +1 -0
  82. package/dist/commonjs/notifyScope.js +3 -3
  83. package/dist/commonjs/notifyScope.js.map +1 -1
  84. package/dist/commonjs/parseSchemaFromJSON.d.ts +2 -2
  85. package/dist/commonjs/parseSchemaFromJSON.d.ts.map +1 -1
  86. package/dist/commonjs/parseSchemaFromJSON.js.map +1 -1
  87. package/dist/commonjs/queryTypes.d.ts +32 -32
  88. package/dist/commonjs/queryTypes.d.ts.map +1 -1
  89. package/dist/commonjs/queryTypes.js.map +1 -1
  90. package/dist/commonjs/routeHandlerProtocol.d.ts +7 -7
  91. package/dist/commonjs/routeHandlerProtocol.d.ts.map +1 -1
  92. package/dist/commonjs/routeHandlerProtocol.js.map +1 -1
  93. package/dist/commonjs/rulesTypes.d.ts +20 -20
  94. package/dist/commonjs/rulesTypes.d.ts.map +1 -1
  95. package/dist/commonjs/rulesTypes.js.map +1 -1
  96. package/dist/commonjs/sanityCheckQueries.d.ts +3 -3
  97. package/dist/commonjs/sanityCheckQueries.d.ts.map +1 -1
  98. package/dist/commonjs/sanityCheckQueries.js.map +1 -1
  99. package/dist/commonjs/schema.d.ts +3 -3
  100. package/dist/commonjs/schema.d.ts.map +1 -1
  101. package/dist/commonjs/schema.js +2 -2
  102. package/dist/commonjs/schema.js.map +1 -1
  103. package/dist/commonjs/schemaTypes.d.ts +8 -8
  104. package/dist/commonjs/schemaTypes.d.ts.map +1 -1
  105. package/dist/commonjs/schemaTypes.js +9 -9
  106. package/dist/commonjs/schemaTypes.js.map +1 -1
  107. package/dist/commonjs/{instaml.d.ts → sideml.d.ts} +1 -1
  108. package/dist/commonjs/sideml.d.ts.map +1 -0
  109. package/dist/commonjs/{instaml.js → sideml.js} +10 -7
  110. package/dist/commonjs/sideml.js.map +1 -0
  111. package/dist/commonjs/{instaql.d.ts → sideql.d.ts} +1 -1
  112. package/dist/commonjs/sideql.d.ts.map +1 -0
  113. package/dist/commonjs/{instaql.js → sideql.js} +1 -1
  114. package/dist/commonjs/sideql.js.map +1 -0
  115. package/dist/commonjs/{instatx.d.ts → sidetx.d.ts} +1 -1
  116. package/dist/commonjs/sidetx.d.ts.map +1 -0
  117. package/dist/commonjs/{instatx.js → sidetx.js} +1 -1
  118. package/dist/commonjs/sidetx.js.map +1 -0
  119. package/dist/commonjs/store.d.ts +22 -22
  120. package/dist/commonjs/store.d.ts.map +1 -1
  121. package/dist/commonjs/store.js +0 -2
  122. package/dist/commonjs/store.js.map +1 -1
  123. package/dist/commonjs/transactionValidation.d.ts +1 -1
  124. package/dist/commonjs/transactionValidation.d.ts.map +1 -1
  125. package/dist/commonjs/transactionValidation.js +2 -2
  126. package/dist/commonjs/transactionValidation.js.map +1 -1
  127. package/dist/commonjs/utils/dates.js +31 -31
  128. package/dist/commonjs/utils/dates.js.map +1 -1
  129. package/dist/commonjs/utils/fetch.d.ts +7 -7
  130. package/dist/commonjs/utils/fetch.d.ts.map +1 -1
  131. package/dist/commonjs/utils/fetch.js +8 -8
  132. package/dist/commonjs/utils/fetch.js.map +1 -1
  133. package/dist/commonjs/utils/flags.d.ts +2 -2
  134. package/dist/commonjs/utils/flags.d.ts.map +1 -1
  135. package/dist/commonjs/utils/flags.js +4 -4
  136. package/dist/commonjs/utils/flags.js.map +1 -1
  137. package/dist/commonjs/utils/linkIndex.d.ts +2 -2
  138. package/dist/commonjs/utils/linkIndex.d.ts.map +1 -1
  139. package/dist/commonjs/utils/linkIndex.js.map +1 -1
  140. package/dist/commonjs/warningToggle.d.ts +1 -1
  141. package/dist/commonjs/warningToggle.d.ts.map +1 -1
  142. package/dist/commonjs/warningToggle.js +3 -3
  143. package/dist/commonjs/warningToggle.js.map +1 -1
  144. package/dist/esm/Connection.d.ts +1 -0
  145. package/dist/esm/Connection.d.ts.map +1 -1
  146. package/dist/esm/Connection.js +18 -3
  147. package/dist/esm/Connection.js.map +1 -1
  148. package/dist/esm/IndexedDBStorage.d.ts.map +1 -1
  149. package/dist/esm/IndexedDBStorage.js +4 -161
  150. package/dist/esm/IndexedDBStorage.js.map +1 -1
  151. package/dist/esm/Reactor.d.ts +7 -7
  152. package/dist/esm/Reactor.d.ts.map +1 -1
  153. package/dist/esm/Reactor.js +38 -39
  154. package/dist/esm/Reactor.js.map +1 -1
  155. package/dist/esm/{InstantError.d.ts → SidekickError.d.ts} +2 -2
  156. package/dist/esm/SidekickError.d.ts.map +1 -0
  157. package/dist/esm/{InstantError.js → SidekickError.js} +5 -5
  158. package/dist/esm/SidekickError.js.map +1 -0
  159. package/dist/esm/Stream.d.ts +5 -5
  160. package/dist/esm/Stream.d.ts.map +1 -1
  161. package/dist/esm/Stream.js +12 -12
  162. package/dist/esm/Stream.js.map +1 -1
  163. package/dist/esm/SyncTable.d.ts +3 -3
  164. package/dist/esm/SyncTable.d.ts.map +1 -1
  165. package/dist/esm/SyncTable.js +3 -3
  166. package/dist/esm/SyncTable.js.map +1 -1
  167. package/dist/esm/attrTypes.d.ts +11 -11
  168. package/dist/esm/attrTypes.d.ts.map +1 -1
  169. package/dist/esm/attrTypes.js.map +1 -1
  170. package/dist/esm/coreTypes.d.ts +4 -4
  171. package/dist/esm/coreTypes.d.ts.map +1 -1
  172. package/dist/esm/coreTypes.js.map +1 -1
  173. package/dist/esm/createRouteHandler.d.ts +1 -1
  174. package/dist/esm/createRouteHandler.d.ts.map +1 -1
  175. package/dist/esm/createRouteHandler.js +3 -3
  176. package/dist/esm/createRouteHandler.js.map +1 -1
  177. package/dist/esm/devtool.js +13 -6
  178. package/dist/esm/devtool.js.map +1 -1
  179. package/dist/esm/endpoints.d.ts +2 -2
  180. package/dist/esm/endpoints.d.ts.map +1 -1
  181. package/dist/esm/endpoints.js +3 -3
  182. package/dist/esm/endpoints.js.map +1 -1
  183. package/dist/esm/framework.d.ts +4 -4
  184. package/dist/esm/framework.d.ts.map +1 -1
  185. package/dist/esm/framework.js +6 -6
  186. package/dist/esm/framework.js.map +1 -1
  187. package/dist/esm/helperTypes.d.ts +24 -24
  188. package/dist/esm/helperTypes.d.ts.map +1 -1
  189. package/dist/esm/helperTypes.js.map +1 -1
  190. package/dist/esm/index.d.ts +36 -36
  191. package/dist/esm/index.d.ts.map +1 -1
  192. package/dist/esm/index.js +33 -33
  193. package/dist/esm/index.js.map +1 -1
  194. package/dist/esm/infiniteQuery.d.ts +7 -7
  195. package/dist/esm/infiniteQuery.d.ts.map +1 -1
  196. package/dist/esm/infiniteQuery.js +16 -3
  197. package/dist/esm/infiniteQuery.js.map +1 -1
  198. package/dist/esm/model/{instaqlResult.d.ts → sideqlResult.d.ts} +2 -2
  199. package/dist/esm/model/sideqlResult.d.ts.map +1 -0
  200. package/dist/esm/model/{instaqlResult.js → sideqlResult.js} +2 -2
  201. package/dist/esm/model/sideqlResult.js.map +1 -0
  202. package/dist/esm/notifyScope.js +3 -3
  203. package/dist/esm/notifyScope.js.map +1 -1
  204. package/dist/esm/parseSchemaFromJSON.d.ts +2 -2
  205. package/dist/esm/parseSchemaFromJSON.d.ts.map +1 -1
  206. package/dist/esm/parseSchemaFromJSON.js.map +1 -1
  207. package/dist/esm/queryTypes.d.ts +32 -32
  208. package/dist/esm/queryTypes.d.ts.map +1 -1
  209. package/dist/esm/queryTypes.js.map +1 -1
  210. package/dist/esm/routeHandlerProtocol.d.ts +7 -7
  211. package/dist/esm/routeHandlerProtocol.d.ts.map +1 -1
  212. package/dist/esm/routeHandlerProtocol.js.map +1 -1
  213. package/dist/esm/rulesTypes.d.ts +20 -20
  214. package/dist/esm/rulesTypes.d.ts.map +1 -1
  215. package/dist/esm/rulesTypes.js.map +1 -1
  216. package/dist/esm/sanityCheckQueries.d.ts +3 -3
  217. package/dist/esm/sanityCheckQueries.d.ts.map +1 -1
  218. package/dist/esm/sanityCheckQueries.js.map +1 -1
  219. package/dist/esm/schema.d.ts +3 -3
  220. package/dist/esm/schema.d.ts.map +1 -1
  221. package/dist/esm/schema.js +3 -3
  222. package/dist/esm/schema.js.map +1 -1
  223. package/dist/esm/schemaTypes.d.ts +8 -8
  224. package/dist/esm/schemaTypes.d.ts.map +1 -1
  225. package/dist/esm/schemaTypes.js +5 -5
  226. package/dist/esm/schemaTypes.js.map +1 -1
  227. package/dist/esm/{instaml.d.ts → sideml.d.ts} +1 -1
  228. package/dist/esm/sideml.d.ts.map +1 -0
  229. package/dist/esm/{instaml.js → sideml.js} +6 -3
  230. package/dist/esm/sideml.js.map +1 -0
  231. package/dist/esm/{instaql.d.ts → sideql.d.ts} +1 -1
  232. package/dist/esm/sideql.d.ts.map +1 -0
  233. package/dist/esm/{instaql.js → sideql.js} +1 -1
  234. package/dist/esm/sideql.js.map +1 -0
  235. package/dist/esm/{instatx.d.ts → sidetx.d.ts} +1 -1
  236. package/dist/esm/sidetx.d.ts.map +1 -0
  237. package/dist/esm/{instatx.js → sidetx.js} +1 -1
  238. package/dist/esm/sidetx.js.map +1 -0
  239. package/dist/esm/store.d.ts +22 -22
  240. package/dist/esm/store.d.ts.map +1 -1
  241. package/dist/esm/store.js +0 -2
  242. package/dist/esm/store.js.map +1 -1
  243. package/dist/esm/transactionValidation.d.ts +1 -1
  244. package/dist/esm/transactionValidation.d.ts.map +1 -1
  245. package/dist/esm/transactionValidation.js +1 -1
  246. package/dist/esm/transactionValidation.js.map +1 -1
  247. package/dist/esm/utils/dates.js +31 -31
  248. package/dist/esm/utils/dates.js.map +1 -1
  249. package/dist/esm/utils/fetch.d.ts +7 -7
  250. package/dist/esm/utils/fetch.d.ts.map +1 -1
  251. package/dist/esm/utils/fetch.js +6 -6
  252. package/dist/esm/utils/fetch.js.map +1 -1
  253. package/dist/esm/utils/flags.d.ts +2 -2
  254. package/dist/esm/utils/flags.d.ts.map +1 -1
  255. package/dist/esm/utils/flags.js +3 -3
  256. package/dist/esm/utils/flags.js.map +1 -1
  257. package/dist/esm/utils/linkIndex.d.ts +2 -2
  258. package/dist/esm/utils/linkIndex.d.ts.map +1 -1
  259. package/dist/esm/utils/linkIndex.js.map +1 -1
  260. package/dist/esm/warningToggle.d.ts +1 -1
  261. package/dist/esm/warningToggle.d.ts.map +1 -1
  262. package/dist/esm/warningToggle.js +1 -1
  263. package/dist/esm/warningToggle.js.map +1 -1
  264. package/dist/standalone/index.js +2705 -2791
  265. package/dist/standalone/index.umd.cjs +9 -6
  266. package/package.json +3 -3
  267. package/src/Connection.ts +18 -3
  268. package/src/IndexedDBStorage.ts +3 -181
  269. package/src/Reactor.js +40 -39
  270. package/src/{InstantError.ts → SidekickError.ts} +4 -4
  271. package/src/Stream.ts +35 -32
  272. package/src/SyncTable.ts +6 -6
  273. package/src/attrTypes.ts +15 -11
  274. package/src/coreTypes.ts +5 -5
  275. package/src/createRouteHandler.ts +9 -7
  276. package/src/devtool.ts +13 -6
  277. package/src/endpoints.ts +4 -4
  278. package/src/framework.ts +13 -13
  279. package/src/helperTypes.ts +37 -37
  280. package/src/index.ts +123 -123
  281. package/src/infiniteQuery.ts +39 -22
  282. package/src/model/{instaqlResult.js → sideqlResult.js} +1 -1
  283. package/src/notifyScope.ts +3 -3
  284. package/src/parseSchemaFromJSON.ts +2 -2
  285. package/src/queryTypes.ts +55 -55
  286. package/src/routeHandlerProtocol.ts +8 -8
  287. package/src/rulesTypes.ts +23 -23
  288. package/src/sanityCheckQueries.ts +9 -9
  289. package/src/schema.ts +3 -3
  290. package/src/schemaTypes.ts +11 -9
  291. package/src/{instaml.ts → sideml.ts} +17 -14
  292. package/src/{instaql.ts → sideql.ts} +5 -5
  293. package/src/store.ts +35 -36
  294. package/src/transactionValidation.ts +1 -1
  295. package/src/utils/dates.ts +31 -31
  296. package/src/utils/fetch.ts +13 -13
  297. package/src/utils/flags.ts +3 -3
  298. package/src/utils/linkIndex.ts +2 -2
  299. package/src/warningToggle.ts +1 -1
  300. package/vite.config.ts +1 -1
  301. package/dist/commonjs/InstantError.d.ts.map +0 -1
  302. package/dist/commonjs/InstantError.js.map +0 -1
  303. package/dist/commonjs/instaml.d.ts.map +0 -1
  304. package/dist/commonjs/instaml.js.map +0 -1
  305. package/dist/commonjs/instaql.d.ts.map +0 -1
  306. package/dist/commonjs/instaql.js.map +0 -1
  307. package/dist/commonjs/instatx.d.ts.map +0 -1
  308. package/dist/commonjs/instatx.js.map +0 -1
  309. package/dist/commonjs/model/instaqlResult.d.ts.map +0 -1
  310. package/dist/commonjs/model/instaqlResult.js.map +0 -1
  311. package/dist/esm/InstantError.d.ts.map +0 -1
  312. package/dist/esm/InstantError.js.map +0 -1
  313. package/dist/esm/instaml.d.ts.map +0 -1
  314. package/dist/esm/instaml.js.map +0 -1
  315. package/dist/esm/instaql.d.ts.map +0 -1
  316. package/dist/esm/instaql.js.map +0 -1
  317. package/dist/esm/instatx.d.ts.map +0 -1
  318. package/dist/esm/instatx.js.map +0 -1
  319. package/dist/esm/model/instaqlResult.d.ts.map +0 -1
  320. package/dist/esm/model/instaqlResult.js.map +0 -1
  321. /package/src/{instatx.ts → sidetx.ts} +0 -0
package/README.md CHANGED
@@ -20,7 +20,7 @@ db.subscribeQuery({ todos: {} }, (resp) => {
20
20
 
21
21
  # Get Started
22
22
 
23
- Follow the [getting started in vanilla Javascript](https://github.com/SidekickDB/sidekick/blob/main/client/www/app/docs/start-vanilla/page.md) tutorial to set up a live app in under 5 minutes!
23
+ Follow the [getting started in vanilla Javascript](https://sidekickdb.co/docs/start-vanilla) tutorial to set up a live app in under 5 minutes!
24
24
 
25
25
  # Questions?
26
26
 
@@ -3,7 +3,7 @@
3
3
  <head>
4
4
  <meta charset="UTF-8" />
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
- <title>Instant Core ESM standalone example/test</title>
6
+ <title>SidekickDB Core ESM standalone example/test</title>
7
7
  </head>
8
8
  <body>
9
9
  <!-- make sure to run `build:standalone` first! -->
@@ -3,7 +3,7 @@
3
3
  <head>
4
4
  <meta charset="UTF-8" />
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
- <title>Instant Core UMD standalone example/test</title>
6
+ <title>SidekickDB Core UMD standalone example/test</title>
7
7
  </head>
8
8
  <body>
9
9
  <!-- make sure to run `build:standalone` first! -->
@@ -11,7 +11,7 @@
11
11
  <script>
12
12
  const query = {};
13
13
 
14
- const db = instant.init({
14
+ const db = sidekick.init({
15
15
  appId: new URL(location.href).searchParams.get("app_id"),
16
16
  });
17
17
 
@@ -1,14 +1,14 @@
1
1
  // https://www.npmjs.com/package/fake-indexeddb
2
2
  import 'fake-indexeddb/auto';
3
- import { test, expect } from 'vitest';
3
+ import { test, expect, vi } from 'vitest';
4
4
  import { setTimeout as sleep } from 'timers/promises';
5
5
 
6
6
  import IndexedDBStorage from '../../src/IndexedDBStorage';
7
7
 
8
8
  import Reactor from '../../src/Reactor';
9
9
  import InMemoryStorage from '../../src/InMemoryStorage';
10
- import * as instaml from '../../src/instaml';
11
- import * as instatx from '../../src/instatx';
10
+ import * as sideml from '../../src/sideml';
11
+ import * as sidetx from '../../src/sidetx';
12
12
  import zenecaAttrs from './data/zeneca/attrs.json';
13
13
  import zenecaTriples from './data/zeneca/triples.json';
14
14
  import uuid from '../../src/utils/id';
@@ -111,23 +111,23 @@ test('rewrite mutations', () => {
111
111
  const bookId = 'bookId';
112
112
  const bookshelfId = 'bookshelfId';
113
113
  const ops = [
114
- instatx.tx.books[bookId].update({ title: 'title' }),
115
- instatx.tx.users[instatx.lookup('handle', 'stopa')].update({
114
+ sidetx.tx.books[bookId].update({ title: 'title' }),
115
+ sidetx.tx.users[sidetx.lookup('handle', 'stopa')].update({
116
116
  email: 's@example.com',
117
117
  }),
118
- instatx.tx.bookshelves[bookshelfId].link({
118
+ sidetx.tx.bookshelves[bookshelfId].link({
119
119
  users: { handle: 'stopa' },
120
120
  }),
121
- instatx.tx.bookshelves[bookshelfId].unlink({
121
+ sidetx.tx.bookshelves[bookshelfId].unlink({
122
122
  users: ['handle', 'joe'],
123
123
  }),
124
- instatx.tx.bookshelves[bookshelfId].unlink({
125
- users: instatx.lookup('handle', 'joe'),
124
+ sidetx.tx.bookshelves[bookshelfId].unlink({
125
+ users: sidetx.lookup('handle', 'joe'),
126
126
  }),
127
127
  ];
128
128
 
129
129
  // create transactions without any attributes
130
- const optimisticSteps = instaml.transform(
130
+ const optimisticSteps = sideml.transform(
131
131
  { attrsStore: new AttrsStoreClass({}, null) },
132
132
  ops,
133
133
  );
@@ -146,7 +146,7 @@ test('rewrite mutations', () => {
146
146
  ._rewriteMutations(zenecaAttrsStore, mutations)
147
147
  .get('k')['tx-steps'];
148
148
 
149
- const serverSteps = instaml.transform({ attrsStore: zenecaAttrsStore }, ops);
149
+ const serverSteps = sideml.transform({ attrsStore: zenecaAttrsStore }, ops);
150
150
  expect(rewrittenSteps).toEqual(serverSteps);
151
151
  });
152
152
 
@@ -158,18 +158,18 @@ test('rewrite mutations works with multiple transactions', () => {
158
158
  const bookId = 'bookId';
159
159
  const bookshelfId = 'bookshelfId';
160
160
  const ops = [
161
- instatx.tx.books[bookId].update({ title: 'title' }),
162
- instatx.tx.users[instatx.lookup('handle', 'stopa')].update({
161
+ sidetx.tx.books[bookId].update({ title: 'title' }),
162
+ sidetx.tx.users[sidetx.lookup('handle', 'stopa')].update({
163
163
  email: 's@example.com',
164
164
  }),
165
- instatx.tx.bookshelves[bookshelfId].link({
165
+ sidetx.tx.bookshelves[bookshelfId].link({
166
166
  users: { handle: 'stopa' },
167
167
  }),
168
- instatx.tx.bookshelves[bookshelfId].unlink({
168
+ sidetx.tx.bookshelves[bookshelfId].unlink({
169
169
  users: ['handle', 'joe'],
170
170
  }),
171
- instatx.tx.bookshelves[bookshelfId].unlink({
172
- users: instatx.lookup('handle', 'joe'),
171
+ sidetx.tx.bookshelves[bookshelfId].unlink({
172
+ users: sidetx.lookup('handle', 'joe'),
173
173
  }),
174
174
  ];
175
175
 
@@ -177,7 +177,7 @@ test('rewrite mutations works with multiple transactions', () => {
177
177
 
178
178
  for (const k of keys) {
179
179
  const attrs = reactor.optimisticAttrs();
180
- const steps = instaml.transform({ attrsStore: attrs }, ops);
180
+ const steps = sideml.transform({ attrsStore: attrs }, ops);
181
181
  const mut = {
182
182
  op: 'transact',
183
183
  'tx-steps': steps,
@@ -194,7 +194,7 @@ test('rewrite mutations works with multiple transactions', () => {
194
194
  reactor._pendingMutations(),
195
195
  );
196
196
 
197
- const serverSteps = instaml.transform({ attrsStore: zenecaAttrsStore }, ops);
197
+ const serverSteps = sideml.transform({ attrsStore: zenecaAttrsStore }, ops);
198
198
  for (const k of keys) {
199
199
  expect(rewrittenMutations.get(k)['tx-steps']).toEqual(serverSteps);
200
200
  }
@@ -244,7 +244,7 @@ test('optimisticTx is not overwritten by refresh-ok', async () => {
244
244
 
245
245
  // first optimistic
246
246
  const ops2 = [
247
- instatx.tx.users[joe_id].update({
247
+ sidetx.tx.users[joe_id].update({
248
248
  handle: 'joe2',
249
249
  }),
250
250
  ];
@@ -264,7 +264,7 @@ test('optimisticTx is not overwritten by refresh-ok', async () => {
264
264
 
265
265
  // second optimistic
266
266
  const ops3 = [
267
- instatx.tx.users[joe_id].update({
267
+ sidetx.tx.users[joe_id].update({
268
268
  handle: 'joe3',
269
269
  }),
270
270
  ];
@@ -305,8 +305,8 @@ test('optimisticTx is not overwritten by refresh-ok', async () => {
305
305
  attrs: zenecaAttrs,
306
306
  computations: [
307
307
  {
308
- 'instaql-query': q,
309
- 'instaql-result': [
308
+ 'sideql-query': q,
309
+ 'sideql-result': [
310
310
  {
311
311
  data: {
312
312
  'datalog-result': {
@@ -374,7 +374,7 @@ test("we don't cleanup mutations we're still waiting on", async () => {
374
374
 
375
375
  // Add two transactions
376
376
  const ops1 = [
377
- instatx.tx.users[joe_id].update({
377
+ sidetx.tx.users[joe_id].update({
378
378
  handle: 'joe2',
379
379
  }),
380
380
  ];
@@ -382,7 +382,7 @@ test("we don't cleanup mutations we're still waiting on", async () => {
382
382
  reactor.pushTx(ops1);
383
383
 
384
384
  const ops2 = [
385
- instatx.tx.users[joe_id].update({
385
+ sidetx.tx.users[joe_id].update({
386
386
  handle: 'joe2',
387
387
  }),
388
388
  ];
@@ -478,3 +478,48 @@ test('getLocalId always returns the same id', async () => {
478
478
 
479
479
  expect(id).toStrictEqual([...ids][0]);
480
480
  });
481
+
482
+ test('OAuth redirect: the URL parameters are _sidekick_*', async () => {
483
+ const reactor = new Reactor({ appId: uuid(), apiURI: 'https://api.example' });
484
+ reactor._initStorage(InMemoryStorage);
485
+ await waitForLoaded(reactor);
486
+
487
+ const url = new URL(
488
+ reactor.createAuthorizationURL({
489
+ clientName: 'google',
490
+ redirectURL: 'https://app.example/cb',
491
+ extraFields: { plan: 'free' },
492
+ }),
493
+ );
494
+ const redirect = new URL(url.searchParams.get('redirect_uri')!);
495
+ expect(redirect.searchParams.get('_sidekick_extra_fields_id')).toBeTruthy();
496
+
497
+ const replaced: string[] = [];
498
+ const withLocation = async (search: string) => {
499
+ vi.stubGlobal('window', {
500
+ location: { href: `https://app.example/cb${search}`, search },
501
+ });
502
+ vi.stubGlobal('history', {
503
+ state: null,
504
+ replaceState: (_s, _t, path) => replaced.push(path),
505
+ });
506
+ try {
507
+ return await reactor._oauthLoginInit();
508
+ } finally {
509
+ vi.unstubAllGlobals();
510
+ }
511
+ };
512
+
513
+ // The old parameter name is not read (spelled in two parts, as in
514
+ // scripts/brand/check-old-name.mjs).
515
+ const old = 'ins' + 'tant';
516
+ expect(
517
+ await withLocation(`?_${old}_oauth_redirect=true&error=denied`),
518
+ ).toBeNull();
519
+ expect(replaced).toEqual([]);
520
+
521
+ expect(
522
+ await withLocation('?_sidekick_oauth_redirect=true&error=denied&x=1'),
523
+ ).toEqual({ error: { message: 'denied' } });
524
+ expect(replaced).toEqual(['/cb?x=1']);
525
+ });
@@ -0,0 +1,110 @@
1
+ import { afterEach, beforeEach, expect, test, vi } from 'vitest';
2
+
3
+ import Reactor from '../../src/Reactor';
4
+ import { SSEConnection } from '../../src/Connection';
5
+ import uuid from '../../src/utils/id';
6
+
7
+ const broadcast = (i: number) => ({
8
+ op: 'server-broadcast',
9
+ 'room-id': 'r',
10
+ topic: 't',
11
+ data: { data: { i } },
12
+ });
13
+ const batch = [broadcast(0), broadcast(1), broadcast(2)];
14
+
15
+ beforeEach(() => {
16
+ vi.useFakeTimers();
17
+ });
18
+
19
+ afterEach(() => {
20
+ vi.useRealTimers();
21
+ });
22
+
23
+ // Handles every message, and throws on the one with i = 1.
24
+ function throwingHandler(seen: number[]) {
25
+ return (msg: any) => {
26
+ seen.push(msg.data.data.i);
27
+ if (msg.data.data.i === 1) throw new Error('callback failed');
28
+ };
29
+ }
30
+
31
+ // A reactor whose current transport is `transport`, with one topic callback
32
+ // in room r that throws on the message with i = 1.
33
+ function reactorWithTopicCallback(seen: number[]) {
34
+ const reactor = new Reactor({ appId: uuid() }) as any;
35
+ const transport = { id: 'ws_test', type: 'ws' };
36
+ reactor._transport = transport;
37
+ reactor._broadcastSubs = {
38
+ r: {
39
+ t: [(data: { i: number }) => throwingHandler(seen)({ data: { data } })],
40
+ },
41
+ };
42
+ return { reactor, transport };
43
+ }
44
+
45
+ test('a WebSocket array frame: a throwing callback does not drop the rest', () => {
46
+ const seen: number[] = [];
47
+ const { reactor, transport } = reactorWithTopicCallback(seen);
48
+
49
+ reactor._transportOnMessage({ target: transport, message: batch });
50
+
51
+ expect(seen).toEqual([0, 1, 2]);
52
+ expect(() => vi.runAllTimers()).toThrow('callback failed');
53
+ });
54
+
55
+ test('a WebSocket single frame still throws synchronously', () => {
56
+ const seen: number[] = [];
57
+ const { reactor, transport } = reactorWithTopicCallback(seen);
58
+
59
+ expect(() =>
60
+ reactor._transportOnMessage({ target: transport, message: broadcast(1) }),
61
+ ).toThrow('callback failed');
62
+ expect(seen).toEqual([1]);
63
+ expect(vi.getTimerCount()).toBe(0);
64
+ });
65
+
66
+ class FakeEventSource {
67
+ static OPEN = 1;
68
+ static CONNECTING = 0;
69
+ static CLOSED = 2;
70
+ static last: FakeEventSource;
71
+ url: string;
72
+ readyState = 1;
73
+ onopen: any = null;
74
+ onmessage: any = null;
75
+ onerror: any = null;
76
+ constructor(url: string) {
77
+ this.url = url;
78
+ FakeEventSource.last = this;
79
+ }
80
+ close() {}
81
+ }
82
+
83
+ function sseConnection(seen: number[]) {
84
+ const conn = new SSEConnection(FakeEventSource as any, 'http://sse.test');
85
+ const handle = throwingHandler(seen);
86
+ conn.onmessage = (e) => handle(e.message);
87
+ return conn;
88
+ }
89
+
90
+ test('an SSE array frame: a throwing message does not drop the rest', () => {
91
+ const seen: number[] = [];
92
+ const conn = sseConnection(seen);
93
+
94
+ FakeEventSource.last.onmessage({ data: JSON.stringify(batch) });
95
+
96
+ expect(seen).toEqual([0, 1, 2]);
97
+ expect(() => vi.runOnlyPendingTimers()).toThrow('callback failed');
98
+ conn.close();
99
+ });
100
+
101
+ test('an SSE single frame still throws synchronously', () => {
102
+ const seen: number[] = [];
103
+ const conn = sseConnection(seen);
104
+
105
+ expect(() =>
106
+ FakeEventSource.last.onmessage({ data: JSON.stringify(broadcast(1)) }),
107
+ ).toThrow('callback failed');
108
+ expect(seen).toEqual([1]);
109
+ conn.close();
110
+ });
@@ -0,0 +1,30 @@
1
+ // SidekickDB: the route handler sets the auth cookie under its new name.
2
+ import { expect, test } from 'vitest';
3
+ import { createSidekickRouteHandler } from '../../src';
4
+
5
+ const handler = createSidekickRouteHandler({ appId: 'a' });
6
+ const user = { id: 'u1', refresh_token: 't1' };
7
+
8
+ const post = (body: object) =>
9
+ handler.POST(
10
+ new Request('http://localhost/api/sidekick', {
11
+ method: 'POST',
12
+ body: JSON.stringify({ type: 'sync-user', appId: 'a', ...body }),
13
+ }),
14
+ );
15
+
16
+ const attributes = 'Path=/; HttpOnly; Secure; SameSite=Strict';
17
+
18
+ test('sets the cookie under the new name', async () => {
19
+ const res = await post({ user });
20
+ expect(res.headers.getSetCookie()).toEqual([
21
+ `sidekick_user_a=${encodeURIComponent(JSON.stringify(user))}; ${attributes}; Max-Age=604800`,
22
+ ]);
23
+ });
24
+
25
+ test('signing out clears it', async () => {
26
+ const res = await post({ user: null });
27
+ expect(res.headers.getSetCookie()).toEqual([
28
+ `sidekick_user_a=; ${attributes}; Max-Age=-1`,
29
+ ]);
30
+ });
@@ -2912,7 +2912,7 @@
2912
2912
  [
2913
2913
  "ce942051-2d74-404a-9c7d-4aa3f2d54ae4",
2914
2914
  "20b65ea3-faad-4e80-863e-87468ff7792f",
2915
- "joe@instantdb.com",
2915
+ "joe@example.com",
2916
2916
  1718117800976
2917
2917
  ],
2918
2918
  [
@@ -4700,7 +4700,7 @@
4700
4700
  [
4701
4701
  "b4e6479f-d0fb-486e-bee0-27cd98de59fa",
4702
4702
  "275e5c3c-d565-4f5a-b832-4290cc6de915",
4703
- "The instant Wall Street Journal, USA Today, and international bestseller \"While the history books are filled with tales of obsessive visionary geniuses who remade the world in their image with sheer, almost irrational force, I've found that history is also made by individuals who fought their egos at every turn, who eschewed the spotlight, and who put their higher goals above their desire for recognition.\" --from the prologue Many of us insist the main impediment to a full, successful life is the outside world. In fact, the most common enemy lies within: our ego. Early in our careers, it impedes learning and the cultivation of talent. With success, it can blind us to our faults and sow future problems. In failure, it magnifies each blow and makes recovery more difficult. At every stage, ego holds us back. Ego Is the Enemy draws on a vast array of stories and examples, from literature to philosophy to history. We meet fascinating figures such as George Marshall, Jackie Robinson, Katharine Graham, Bill Belichick, and Eleanor Roosevelt, who all reached the highest levels of power and success by conquering their own egos. Their strategies and tactics can be ours as well. In an era that glorifies social media, reality TV, and other forms of shameless self-promotion, the battle against ego must be fought on many fronts. Armed with the lessons in this book, as Holiday writes, \"you will be less invested in the story you tell about your own specialness, and as a result, you will be liberated to accomplish the world-changing work you've set out to achieve.\"",
4703
+ "The immediate Wall Street Journal, USA Today, and international bestseller \"While the history books are filled with tales of obsessive visionary geniuses who remade the world in their image with sheer, almost irrational force, I've found that history is also made by individuals who fought their egos at every turn, who eschewed the spotlight, and who put their higher goals above their desire for recognition.\" --from the prologue Many of us insist the main impediment to a full, successful life is the outside world. In fact, the most common enemy lies within: our ego. Early in our careers, it impedes learning and the cultivation of talent. With success, it can blind us to our faults and sow future problems. In failure, it magnifies each blow and makes recovery more difficult. At every stage, ego holds us back. Ego Is the Enemy draws on a vast array of stories and examples, from literature to philosophy to history. We meet fascinating figures such as George Marshall, Jackie Robinson, Katharine Graham, Bill Belichick, and Eleanor Roosevelt, who all reached the highest levels of power and success by conquering their own egos. Their strategies and tactics can be ours as well. In an era that glorifies social media, reality TV, and other forms of shameless self-promotion, the battle against ego must be fought on many fronts. Armed with the lessons in this book, as Holiday writes, \"you will be less invested in the story you tell about your own specialness, and as a result, you will be liberated to accomplish the world-changing work you've set out to achieve.\"",
4704
4704
  1718117842976
4705
4705
  ],
4706
4706
  [
@@ -5240,7 +5240,7 @@
5240
5240
  [
5241
5241
  "ad45e100-777a-4de8-8978-aa13200a4824",
5242
5242
  "20b65ea3-faad-4e80-863e-87468ff7792f",
5243
- "alex@instantdb.com",
5243
+ "alex@example.com",
5244
5244
  1718117855976
5245
5245
  ],
5246
5246
  [
@@ -5642,7 +5642,7 @@
5642
5642
  [
5643
5643
  "a55a5231-5c4d-4033-b859-7790c45c22d5",
5644
5644
  "20b65ea3-faad-4e80-863e-87468ff7792f",
5645
- "stopa@instantdb.com",
5645
+ "stopa@example.com",
5646
5646
  1718117867976
5647
5647
  ],
5648
5648
  [
@@ -12896,7 +12896,7 @@
12896
12896
  [
12897
12897
  "23623419-3dae-49fd-92ce-07ab069e7f93",
12898
12898
  "275e5c3c-d565-4f5a-b832-4290cc6de915",
12899
- "\"It took me a long time and most of the world to learn what I know about love and fate and the choices we make, but the heart of it came to me in an instant, while I was chained to a wall and being tortured.\" So begins this epic, mesmerizing first novel by Gregory David Roberts, set in the underworld of contemporary Bombay. Shantaram is narrated by Lin, an escaped convict with a false passport who flees maximum security prison in Australia for the teeming streets of a city where he can disappear. Accompanied by his guide and faithful friend, Prabaker, the two enter Bombay's hidden society of beggars and gangsters, prostitutes and holy men, soldiers and actors, and Indians and exiles from other countries, who seek in this remarkable place what they cannot find elsewhere. As a hunted man without a home, family, or identity, Lin searches for love and meaning while running a clinic in one of the city's poorest slums, and serving his apprenticeship in the dark arts of the Bombay mafia. The search leads him to war, prison torture, murder, and a series of enigmatic and bloody betrayals. The keys to unlock the mysteries and intrigues that bind Lin are held by two people. The first is Khader Khan: mafia godfather, criminal-philosopher-saint, and mentor to Lin in the underworld of the Golden City. The second is Karla: elusive, dangerous, and beautiful, whose passions are driven by secrets that torment her and yet give her a terrible power. Burning slums and five-star hotels, romantic love and prison agonies, criminal wars and Bollywood films, spiritual gurus and mujaheddin guerrillas---this huge novel has the world of human experience in its reach, and a passionate love for India at its heart. Based on the life of the author, it is by any measure the debut of an extraordinary voice in literature.",
12899
+ "\"It took me a long time and most of the world to learn what I know about love and fate and the choices we make, but the heart of it came to me in a moment, while I was chained to a wall and being tortured.\" So begins this epic, mesmerizing first novel by Gregory David Roberts, set in the underworld of contemporary Bombay. Shantaram is narrated by Lin, an escaped convict with a false passport who flees maximum security prison in Australia for the teeming streets of a city where he can disappear. Accompanied by his guide and faithful friend, Prabaker, the two enter Bombay's hidden society of beggars and gangsters, prostitutes and holy men, soldiers and actors, and Indians and exiles from other countries, who seek in this remarkable place what they cannot find elsewhere. As a hunted man without a home, family, or identity, Lin searches for love and meaning while running a clinic in one of the city's poorest slums, and serving his apprenticeship in the dark arts of the Bombay mafia. The search leads him to war, prison torture, murder, and a series of enigmatic and bloody betrayals. The keys to unlock the mysteries and intrigues that bind Lin are held by two people. The first is Khader Khan: mafia godfather, criminal-philosopher-saint, and mentor to Lin in the underworld of the Golden City. The second is Karla: elusive, dangerous, and beautiful, whose passions are driven by secrets that torment her and yet give her a terrible power. Burning slums and five-star hotels, romantic love and prison agonies, criminal wars and Bollywood films, spiritual gurus and mujaheddin guerrillas---this huge novel has the world of human experience in its reach, and a passionate love for India at its heart. Based on the life of the author, it is by any measure the debut of an extraordinary voice in literature.",
12900
12900
  1718118074976
12901
12901
  ],
12902
12902
  [
@@ -14894,7 +14894,7 @@
14894
14894
  [
14895
14895
  "0f3d67fc-8b37-4b03-ac47-29fec4edc4f7",
14896
14896
  "20b65ea3-faad-4e80-863e-87468ff7792f",
14897
- "nicole@instantdb.com",
14897
+ "nicole@example.com",
14898
14898
  1718118127976
14899
14899
  ],
14900
14900
  [
@@ -5,7 +5,7 @@ import { test, expect, vi } from 'vitest';
5
5
  import IndexedDBStorage from '../../src/IndexedDBStorage';
6
6
 
7
7
  import Reactor from '../../src/Reactor';
8
- import * as instatx from '../../src/instatx';
8
+ import * as sidetx from '../../src/sidetx';
9
9
  import zenecaAttrs from './data/zeneca/attrs.json';
10
10
  import zenecaTriples from './data/zeneca/triples.json';
11
11
  import uuid from '../../src/utils/id';
@@ -54,7 +54,7 @@ async function setup() {
54
54
  reactor.subscribeQuery(q, cb);
55
55
  addQueryOk(reactor, q, [zenecaTriples]);
56
56
 
57
- reactor.pushTx([instatx.tx.users[joe_id].update({ handle: 'joe2' })]);
57
+ reactor.pushTx([sidetx.tx.users[joe_id].update({ handle: 'joe2' })]);
58
58
  await waitForLoaded(reactor);
59
59
 
60
60
  reactor.subscribeQuery(otherQ, () => {});
@@ -85,7 +85,7 @@ test('dataForQuery recomputes after a new pending mutation', async () => {
85
85
  const { reactor, hash, applyOptimisticUpdates } = await setup();
86
86
 
87
87
  const first = reactor.dataForQuery(hash);
88
- reactor.pushTx([instatx.tx.users[joe_id].update({ handle: 'joe3' })]);
88
+ reactor.pushTx([sidetx.tx.users[joe_id].update({ handle: 'joe3' })]);
89
89
  await waitForLoaded(reactor);
90
90
 
91
91
  const second = reactor.dataForQuery(hash);
@@ -123,7 +123,7 @@ test('a read between notifies does not affect notifyOne deduping', async () => {
123
123
  expect(cb).toHaveBeenCalledTimes(callsBefore);
124
124
 
125
125
  // Changed data: the callback still fires.
126
- reactor.pushTx([instatx.tx.users[joe_id].update({ handle: 'joe3' })]);
126
+ reactor.pushTx([sidetx.tx.users[joe_id].update({ handle: 'joe3' })]);
127
127
  await waitForLoaded(reactor);
128
128
  reactor.dataForQuery(hash);
129
129
  reactor.notifyOne(hash);
@@ -12,10 +12,10 @@ import {
12
12
  createStore,
13
13
  getAttrByFwdIdentName,
14
14
  } from '../../src/store';
15
- import { InstantDBAttr } from '../../src';
15
+ import { SidekickDBAttr } from '../../src';
16
16
 
17
17
  const movieAttrsStore = new AttrsStoreClass(
18
- movieAttrs as unknown as Record<string, InstantDBAttr>,
18
+ movieAttrs as unknown as Record<string, SidekickDBAttr>,
19
19
  null,
20
20
  );
21
21
 
@@ -16,9 +16,9 @@ describe('getDevtoolSrc', () => {
16
16
  expect(
17
17
  getDevtoolSrc('app-id', {
18
18
  ...defaultConfig,
19
- dashURI: 'https://dash.instant.example/',
19
+ dashURI: 'https://dash.sidekick.example/',
20
20
  }),
21
- ).toBe('https://dash.instant.example/_devtool?appId=app-id');
21
+ ).toBe('https://dash.sidekick.example/_devtool?appId=app-id');
22
22
  });
23
23
  });
24
24
 
@@ -94,10 +94,10 @@ describe('requireApiURI', () => {
94
94
  expect(() =>
95
95
  requireApiURI(undefined, {
96
96
  target: 'createResumableStreamContext()',
97
- envVar: 'INSTANT_API_URI',
97
+ envVar: 'SIDEKICK_API_URI',
98
98
  }),
99
99
  ).toThrow(
100
- 'Pass `apiURI` to createResumableStreamContext() or set the INSTANT_API_URI environment variable',
100
+ 'Pass `apiURI` to createResumableStreamContext() or set the SIDEKICK_API_URI environment variable',
101
101
  );
102
102
  });
103
103
  });
@@ -0,0 +1,142 @@
1
+ import { describe, expect, test } from 'vitest';
2
+ import { subscribeInfiniteQuery } from '../../src/infiniteQuery';
3
+
4
+ // A fake `db` whose subscribeQuery answers windowed queries (after, before,
5
+ // limit, order on `value`) from an in-memory list, the way the server does.
6
+ // The starter subscription (the one without a cursor) is driven by hand, so a
7
+ // test controls when it reports rows and when it first gets a start cursor.
8
+
9
+ type Item = { id: string; value: number };
10
+ type Cursor = [string, string, number, number];
11
+ type Sub = { q: any; cb: (resp: any) => void; active: boolean };
12
+
13
+ const cursorOf = (item: Item): Cursor => [item.id, 'value-attr', item.value, 0];
14
+
15
+ const compare = (a: Item, b: Item) =>
16
+ a.value === b.value ? a.id.localeCompare(b.id) : a.value - b.value;
17
+
18
+ const compareToCursor = (item: Item, cursor: Cursor) =>
19
+ compare(item, { id: cursor[0], value: cursor[2] });
20
+
21
+ function runWindow(items: Item[], $: any) {
22
+ const desc = $.order.value === 'desc';
23
+ const sign = desc ? -1 : 1;
24
+ let rows = items.slice().sort((a, b) => sign * compare(a, b));
25
+ if ($.after) {
26
+ rows = rows.filter((item) => {
27
+ const c = sign * compareToCursor(item, $.after);
28
+ return $.afterInclusive ? c >= 0 : c > 0;
29
+ });
30
+ }
31
+ if ($.before) {
32
+ rows = rows.filter((item) => {
33
+ const c = sign * compareToCursor(item, $.before);
34
+ return $.beforeInclusive ? c <= 0 : c < 0;
35
+ });
36
+ }
37
+ const hasNextPage = $.limit != null && rows.length > $.limit;
38
+ if ($.limit != null) rows = rows.slice(0, $.limit);
39
+ return {
40
+ data: { items: rows },
41
+ pageInfo: {
42
+ items: {
43
+ startCursor: rows[0] && cursorOf(rows[0]),
44
+ endCursor: rows[rows.length - 1] && cursorOf(rows[rows.length - 1]),
45
+ hasNextPage,
46
+ hasPreviousPage: false,
47
+ },
48
+ },
49
+ };
50
+ }
51
+
52
+ function makeFakeDb() {
53
+ const subs: Sub[] = [];
54
+ const db = {
55
+ subscribeQuery(q: any, cb: (resp: any) => void) {
56
+ const sub = { q, cb, active: true };
57
+ subs.push(sub);
58
+ return () => {
59
+ sub.active = false;
60
+ };
61
+ },
62
+ };
63
+ const isStarter = (sub: Sub) => !sub.q.items.$.after;
64
+ return {
65
+ db: db as any,
66
+ emitStarter(rows: Item[], startCursor?: Cursor) {
67
+ const starter = subs.find(isStarter)!;
68
+ starter.cb({
69
+ data: { items: rows },
70
+ pageInfo: {
71
+ items: {
72
+ startCursor,
73
+ endCursor: undefined,
74
+ hasNextPage: false,
75
+ hasPreviousPage: false,
76
+ },
77
+ },
78
+ });
79
+ },
80
+ emitWindows(items: Item[]) {
81
+ for (const sub of subs.filter((s) => s.active && !isStarter(s))) {
82
+ sub.cb(runWindow(items, sub.q.items.$));
83
+ }
84
+ },
85
+ };
86
+ }
87
+
88
+ const item = (value: number): Item => ({
89
+ id: `id-${String(value + 100).padStart(3, '0')}`,
90
+ value,
91
+ });
92
+
93
+ describe('subscribeInfiniteQuery', () => {
94
+ test('an item inserted before a full optimistic first page does not push its last item out', () => {
95
+ const { db, emitStarter, emitWindows } = makeFakeDb();
96
+ let values: number[] = [];
97
+ subscribeInfiniteQuery(
98
+ db,
99
+ { items: { $: { limit: 4, order: { value: 'asc' } } } },
100
+ (resp) => {
101
+ values = (resp.data?.items ?? []).map((i: Item) => i.value);
102
+ },
103
+ );
104
+
105
+ const page = [0, 1, 2, 3].map(item);
106
+ const minusOne = item(-1);
107
+
108
+ // The server answered the empty query; then 0..3 are added. The client
109
+ // shows them from its optimistic store, without a start cursor yet.
110
+ emitStarter([]);
111
+ emitStarter(page);
112
+ expect(values).toEqual([0, 1, 2, 3]);
113
+
114
+ // -1 is added before the server refreshes the query. The refresh it then
115
+ // sends is the first with a start cursor, and it already contains -1.
116
+ emitStarter([minusOne, ...page.slice(0, 3)]);
117
+ emitStarter([minusOne, ...page.slice(0, 3)], cursorOf(minusOne));
118
+ emitWindows([minusOne, ...page]);
119
+
120
+ expect(values).toEqual([-1, 0, 1, 2, 3]);
121
+ });
122
+
123
+ test('without an optimistic first page, the first page starts at the server start cursor', () => {
124
+ const { db, emitStarter, emitWindows } = makeFakeDb();
125
+ let resp: any;
126
+ subscribeInfiniteQuery(
127
+ db,
128
+ { items: { $: { limit: 4, order: { value: 'asc' } } } },
129
+ (r) => {
130
+ resp = r;
131
+ },
132
+ );
133
+
134
+ const items = [-1, 0, 1, 2, 3].map(item);
135
+ emitStarter([]);
136
+ emitStarter(items.slice(0, 4), cursorOf(items[0]));
137
+ emitWindows(items);
138
+
139
+ expect(resp.data.items.map((i: Item) => i.value)).toEqual([-1, 0, 1, 2]);
140
+ expect(resp.canLoadNextPage).toBe(true);
141
+ });
142
+ });