kitcn 0.23.0 → 0.25.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 (85) hide show
  1. package/dist/aggregate/index.d.ts +11 -1
  2. package/dist/aggregate/index.js +1 -1
  3. package/dist/auth/generated/index.d.ts +1 -1
  4. package/dist/auth/generated/index.js +1 -1
  5. package/dist/auth/http/index.d.ts +1 -1
  6. package/dist/auth/index.d.ts +4 -4
  7. package/dist/auth/index.js +10 -9
  8. package/dist/auth/nextjs/index.d.ts +2 -2
  9. package/dist/auth/nextjs/index.js +3 -3
  10. package/dist/auth/start/server/index.d.ts +1 -1
  11. package/dist/auth/start/server/index.js +1 -1
  12. package/dist/{builder-CsxVc5xC.js → builder-1Vx-tEnS.js} +3 -3
  13. package/dist/{caller-factory-CWa0ELLD.js → caller-factory-Dd3H7j3V.js} +3 -3
  14. package/dist/{where-clause-compiler-B_H3oio5.d.ts → capabilities-Bem7xvGK.d.ts} +2958 -4145
  15. package/dist/cli.mjs +155 -60
  16. package/dist/{convex-plugin-D8B0oCFq.js → convex-plugin-DfOhBU9g.js} +1 -1
  17. package/dist/{create-schema-orm-B3f2Kc8O.js → create-schema-orm-Bu2JCiBS.js} +1 -1
  18. package/dist/crpc/index.d.ts +3 -3
  19. package/dist/crpc/index.js +4 -4
  20. package/dist/{customFunctions-DxEEO4Dq.js → customFunctions-BbhgdRGl.js} +2 -2
  21. package/dist/definitions-D9vhJ6OV.js +215 -0
  22. package/dist/extensions-DzjCJXYl.js +55 -0
  23. package/dist/filter-expression-Dydt8wS0.js +402 -0
  24. package/dist/{generated-contract-disabled-B-nmd7Ne.d.ts → generated-contract-disabled-BEc4d98x.d.ts} +2 -2
  25. package/dist/{http-types-BoSDAh4Y.d.ts → http-types-90mapMP9.d.ts} +33 -3
  26. package/dist/id-Bibg34Yb.js +37 -0
  27. package/dist/{local-env-yFKub75x.mjs → local-env-Du24tdbp.mjs} +2243 -2113
  28. package/dist/{middleware-Br5zubu7.d.ts → middleware-CE_MC6Gi.d.ts} +1 -1
  29. package/dist/{middleware-DUd1Sj39.js → middleware-cJDRHTRY.js} +1 -1
  30. package/dist/orm/aggregate-index/index.d.ts +20 -0
  31. package/dist/orm/aggregate-index/index.js +2136 -0
  32. package/dist/orm/index.d.ts +5 -4
  33. package/dist/orm/index.js +126 -4292
  34. package/dist/orm/migrations/index.d.ts +3 -0
  35. package/dist/orm/migrations/index.js +506 -0
  36. package/dist/plugins/index.d.ts +1 -1
  37. package/dist/plugins/index.js +1 -1
  38. package/dist/{procedure-caller-DQxnLBS_.js → procedure-caller-DIzXfX2E.js} +2 -2
  39. package/dist/{procedure-name-C55TynK3.d.ts → procedure-name-B09-cf1-.d.ts} +3 -3
  40. package/dist/{query-context-BzihIpnM.js → query-context-DOm5Xm3H.js} +1 -402
  41. package/dist/{query-options-C_eBSIXG.js → query-options-DUiOj01a.js} +33 -1
  42. package/dist/ratelimit/index.d.ts +47 -11
  43. package/dist/ratelimit/index.js +256 -102
  44. package/dist/react/index.d.ts +9 -6
  45. package/dist/react/index.js +36 -17
  46. package/dist/rsc/index.d.ts +6 -9
  47. package/dist/rsc/index.js +7 -11
  48. package/dist/runtime-DfGsZtx3.js +1074 -0
  49. package/dist/schema-Besl-rpv.js +1411 -0
  50. package/dist/server/index.d.ts +4 -4
  51. package/dist/server/index.js +4 -4
  52. package/dist/solid/index.d.ts +9 -6
  53. package/dist/solid/index.js +36 -17
  54. package/dist/{runtime-6DJxpDfb.js → table-rmJm5Qio.js} +3 -1095
  55. package/dist/{token-xlpENMVn.js → token-DcV_0fkF.js} +1 -1
  56. package/dist/{types-C0Xl7P8K.d.ts → types-In-ZZOsd.d.ts} +1 -1
  57. package/dist/{validators-C7LelqTN.js → validators-Dmbhsd3U.js} +1 -1
  58. package/dist/watcher.mjs +1 -1
  59. package/dist/where-clause-compiler-mohWFiG0.d.ts +2042 -0
  60. package/package.json +3 -2
  61. package/skills/kitcn/SKILL.md +19 -18
  62. package/skills/kitcn/references/features/aggregates.md +21 -0
  63. package/skills/kitcn/references/features/auth-organizations.md +3 -3
  64. package/skills/kitcn/references/features/auth-polar.md +2 -1
  65. package/skills/kitcn/references/features/auth.md +8 -1
  66. package/skills/kitcn/references/features/http.md +26 -1
  67. package/skills/kitcn/references/features/ratelimit.md +11 -0
  68. package/skills/kitcn/references/features/react.md +1 -1
  69. package/skills/kitcn/references/setup/auth.md +52 -42
  70. package/skills/kitcn/references/setup/index.md +1 -1
  71. package/skills/kitcn/references/setup/server.md +37 -6
  72. /package/dist/{api-entry-N3nBOlI2.js → api-entry-CkDpGYVg.js} +0 -0
  73. /package/dist/{context-utils-BBUtBqjN.d.ts → context-utils-DwZ3Cam1.d.ts} +0 -0
  74. /package/dist/{create-schema-BXrKE2YY.js → create-schema-BRFjdgRr.js} +0 -0
  75. /package/dist/{error-Bvo7YEhk.js → error-CMLeCadS.js} +0 -0
  76. /package/dist/{generated-contract-disabled-BXaz7JCE.js → generated-contract-disabled-CZa0iyV0.js} +0 -0
  77. /package/dist/{meta-utils-D9K4fICl.js → meta-utils-D2lqN2Lg.js} +0 -0
  78. /package/dist/{query-context-CNo9ffvI.d.ts → query-context-DJONf8X5.d.ts} +0 -0
  79. /package/dist/{token-B9Bjcqug.d.ts → token-kQaqFby4.d.ts} +0 -0
  80. /package/dist/{transformer-yZuBWo8v.js → transformer-D8wO-kEj.js} +0 -0
  81. /package/dist/{types-BCl8gfGy.d.ts → types-Bf3XQex5.d.ts} +0 -0
  82. /package/dist/{types-DF2cg_w0.d.ts → types-MHYXboyy.d.ts} +0 -0
  83. /package/dist/{types-CnTpHR1F.d.ts → types-eNzQmbqM.d.ts} +0 -0
  84. /package/dist/{upstream-BR6sBLg3.js → upstream-BCgGZX6q.js} +0 -0
  85. /package/dist/{validators-BhsByJeg.d.ts → validators-V4eM2-Jg.d.ts} +0 -0
@@ -0,0 +1,1074 @@
1
+ import { A as integer, C as index, M as custom, O as text, t as convexTable } from "./table-rmJm5Qio.js";
2
+ import { t as id } from "./id-Bibg34Yb.js";
3
+ import { ConvexError, convexToJson, jsonToConvex, v } from "convex/values";
4
+
5
+ //#region src/aggregate-core/compare.ts
6
+ function compareValues$1(k1, k2) {
7
+ return compareAsTuples(makeComparable(k1), makeComparable(k2));
8
+ }
9
+ function compareAsTuples(a, b) {
10
+ if (a[0] === b[0]) return compareSameTypeValues(a[1], b[1]);
11
+ if (a[0] < b[0]) return -1;
12
+ return 1;
13
+ }
14
+ function compareSameTypeValues(v1, v2) {
15
+ if (v1 === void 0 || v1 === null) return 0;
16
+ if (typeof v1 === "bigint" || typeof v1 === "number" || typeof v1 === "boolean" || typeof v1 === "string") return v1 < v2 ? -1 : v1 === v2 ? 0 : 1;
17
+ if (!Array.isArray(v1) || !Array.isArray(v2)) throw new Error(`Unexpected type ${v1}`);
18
+ for (let i = 0; i < v1.length && i < v2.length; i++) {
19
+ const cmp = compareAsTuples(v1[i], v2[i]);
20
+ if (cmp !== 0) return cmp;
21
+ }
22
+ if (v1.length < v2.length) return -1;
23
+ if (v1.length > v2.length) return 1;
24
+ return 0;
25
+ }
26
+ function makeComparable(v) {
27
+ if (v === void 0) return [0, void 0];
28
+ if (v === null) return [1, null];
29
+ if (typeof v === "bigint") return [2, v];
30
+ if (typeof v === "number") {
31
+ if (Number.isNaN(v)) return [3.5, 0];
32
+ return [3, v];
33
+ }
34
+ if (typeof v === "boolean") return [4, v];
35
+ if (typeof v === "string") return [5, v];
36
+ if (v instanceof ArrayBuffer) return [6, Array.from(new Uint8Array(v)).map(makeComparable)];
37
+ if (Array.isArray(v)) return [7, v.map(makeComparable)];
38
+ return [8, Object.keys(v).sort().map((k) => [k, v[k]]).map(makeComparable)];
39
+ }
40
+
41
+ //#endregion
42
+ //#region src/aggregate-core/schema.ts
43
+ const AGGREGATE_TREE_TABLE = "aggregate_rank_tree";
44
+ const AGGREGATE_NODE_TABLE = "aggregate_rank_node";
45
+ const aggregateCounterValidator = v.object({
46
+ count: v.number(),
47
+ sum: v.number()
48
+ });
49
+ const aggregateItemValidator = v.object({
50
+ k: v.any(),
51
+ v: v.any(),
52
+ s: v.number()
53
+ });
54
+ const aggregateTreeTable = convexTable(AGGREGATE_TREE_TABLE, {
55
+ aggregateName: text().notNull(),
56
+ deletionStack: custom(v.array(v.id(AGGREGATE_NODE_TABLE))),
57
+ maxNodeSize: integer().notNull(),
58
+ namespace: custom(v.any()),
59
+ root: id(AGGREGATE_NODE_TABLE).notNull()
60
+ }, (tree) => [index("by_namespace").on(tree.namespace), index("by_aggregate_name").on(tree.aggregateName)]);
61
+ const aggregateNodeTable = convexTable(AGGREGATE_NODE_TABLE, {
62
+ aggregate: custom(aggregateCounterValidator),
63
+ items: custom(v.array(aggregateItemValidator)).notNull(),
64
+ subtrees: custom(v.array(v.string())).notNull()
65
+ });
66
+ const aggregateStorageTables = {
67
+ [AGGREGATE_NODE_TABLE]: aggregateNodeTable,
68
+ [AGGREGATE_TREE_TABLE]: aggregateTreeTable
69
+ };
70
+
71
+ //#endregion
72
+ //#region src/aggregate-core/btree.ts
73
+ const DEFAULT_MAX_NODE_SIZE = 16;
74
+ const LEGACY_AGGREGATE_NAME = "__legacy__";
75
+ function p(v) {
76
+ try {
77
+ return JSON.stringify(v);
78
+ } catch {
79
+ return String(v);
80
+ }
81
+ }
82
+ function log(s) {}
83
+ function aggregateNameFromNamespace(namespace) {
84
+ if (Array.isArray(namespace) && namespace.length === 3 && typeof namespace[0] === "string" && (namespace[2] === 0 || namespace[2] === 1)) return namespace[0];
85
+ return LEGACY_AGGREGATE_NAME;
86
+ }
87
+ async function insertHandler(ctx, args) {
88
+ const tree = await getOrCreateTree(ctx.db, args.namespace, DEFAULT_MAX_NODE_SIZE, true);
89
+ const summand = args.summand ?? 0;
90
+ const pushUp = await insertIntoNode(ctx, tree.maxNodeSize, tree.root, {
91
+ k: args.key,
92
+ v: args.value,
93
+ s: summand
94
+ });
95
+ if (pushUp) {
96
+ const total = pushUp.leftSubtreeCount && pushUp.rightSubtreeCount && add(add(pushUp.leftSubtreeCount, pushUp.rightSubtreeCount), itemAggregate(pushUp.item));
97
+ const newRoot = await ctx.db.insert(AGGREGATE_NODE_TABLE, {
98
+ items: [pushUp.item],
99
+ subtrees: [pushUp.leftSubtree, pushUp.rightSubtree],
100
+ aggregate: total
101
+ });
102
+ await ctx.db.patch(tree._id, { root: newRoot });
103
+ }
104
+ }
105
+ async function deleteHandler(ctx, args) {
106
+ const tree = await getOrCreateTree(ctx.db, args.namespace, DEFAULT_MAX_NODE_SIZE, true);
107
+ await deleteFromNode(ctx, tree.maxNodeSize, tree.root, args.key);
108
+ const root = await ctx.db.get(tree.root);
109
+ if (root.items.length === 0 && root.subtrees.length === 1) {
110
+ log(`collapsing root ${root._id} because its only child is ${root.subtrees[0]}`);
111
+ await ctx.db.patch(tree._id, { root: root.subtrees[0] });
112
+ if (root.aggregate === void 0) await ctx.db.patch(root.subtrees[0], { aggregate: void 0 });
113
+ await ctx.db.delete(root._id);
114
+ }
115
+ }
116
+ function assertMaxNodeSize(maxNodeSize) {
117
+ if (maxNodeSize % 2 !== 0 || maxNodeSize < 4) throw new Error("MAX_NODE_SIZE must be even and at least 4");
118
+ }
119
+ function minNodeSizeFor(maxNodeSize) {
120
+ assertMaxNodeSize(maxNodeSize);
121
+ return maxNodeSize / 2;
122
+ }
123
+ async function aggregateBetweenHandler(ctx, args) {
124
+ const tree = await getTree(ctx.db, args.namespace);
125
+ if (tree === null) return {
126
+ count: 0,
127
+ sum: 0
128
+ };
129
+ return await aggregateBetweenInNode(ctx.db, tree.root, args.k1, args.k2);
130
+ }
131
+ async function filterBetween(db, node, k1, k2, preloaded) {
132
+ const n = preloaded ?? await db.get(node);
133
+ const included = [];
134
+ function includeSubtree(i, unboundedRight) {
135
+ const unboundedLeft = k1 === void 0 || included.length > 0;
136
+ if (unboundedLeft && unboundedRight) included.push({
137
+ type: "subtree",
138
+ subtree: n.subtrees[i]
139
+ });
140
+ else included.push(filterBetween(db, n.subtrees[i], unboundedLeft ? void 0 : k1, unboundedRight ? void 0 : k2));
141
+ }
142
+ let done = false;
143
+ for (let i = 0; i < n.items.length; i++) {
144
+ const k1IsLeft = k1 === void 0 || compareKeys(k1, n.items[i].k) === -1;
145
+ const k2IsRight = k2 === void 0 || compareKeys(k2, n.items[i].k) === 1;
146
+ if (k1IsLeft && n.subtrees.length > 0) includeSubtree(i, k2IsRight);
147
+ if (!k2IsRight) {
148
+ done = true;
149
+ break;
150
+ }
151
+ if (k1IsLeft) included.push({
152
+ type: "item",
153
+ item: n.items[i]
154
+ });
155
+ }
156
+ if (!done && n.subtrees.length > 0) includeSubtree(n.subtrees.length - 1, k2 === void 0);
157
+ return (await Promise.all(included)).flat(1);
158
+ }
159
+ async function aggregateBetweenInNode(db, node, k1, k2) {
160
+ const filtered = await filterBetween(db, node, k1, k2);
161
+ const counts = await Promise.all(filtered.map(async (included) => {
162
+ if (included.type === "item") return itemAggregate(included.item);
163
+ return await nodeAggregate(db, await db.get(included.subtree));
164
+ }));
165
+ let count = {
166
+ count: 0,
167
+ sum: 0
168
+ };
169
+ for (const c of counts) count = add(count, c);
170
+ return count;
171
+ }
172
+ async function atOffsetHandler(ctx, args) {
173
+ if (args.offset < 0) throw new Error("offset must be non-negative");
174
+ if (!Number.isInteger(args.offset)) throw new Error("offset must be an integer");
175
+ const tree = await getTree(ctx.db, args.namespace);
176
+ if (tree === null) throw new ConvexError("tree is empty");
177
+ return await atOffsetInNode(ctx.db, tree.root, args.offset, args.k1, args.k2);
178
+ }
179
+ async function atNegativeOffsetHandler(ctx, args) {
180
+ if (args.offset < 0) throw new Error("offset must be non-negative");
181
+ if (!Number.isInteger(args.offset)) throw new Error("offset must be an integer");
182
+ const tree = await getTree(ctx.db, args.namespace);
183
+ if (tree === null) throw new ConvexError("tree is empty");
184
+ return await negativeOffsetInNode(ctx.db, tree.root, args.offset, args.k1, args.k2);
185
+ }
186
+ async function offsetHandler(ctx, args) {
187
+ return (await aggregateBetweenHandler(ctx, {
188
+ k1: args.k1,
189
+ k2: args.key,
190
+ namespace: args.namespace
191
+ })).count;
192
+ }
193
+ async function offsetUntilHandler(ctx, args) {
194
+ return (await aggregateBetweenHandler(ctx, {
195
+ k1: args.key,
196
+ k2: args.k2,
197
+ namespace: args.namespace
198
+ })).count;
199
+ }
200
+ async function deleteFromNode(ctx, maxNodeSize, node, key) {
201
+ let n = await ctx.db.get(node);
202
+ let foundItem = null;
203
+ let i = 0;
204
+ for (; i < n.items.length; i++) {
205
+ const compare = compareKeys(key, n.items[i].k);
206
+ if (compare === -1) break;
207
+ if (compare === 0) {
208
+ log(`found key ${p(key)} in node ${n._id}`);
209
+ if (n.subtrees.length === 0) {
210
+ await ctx.db.patch(node, {
211
+ items: [...n.items.slice(0, i), ...n.items.slice(i + 1)],
212
+ aggregate: n.aggregate && sub(n.aggregate, itemAggregate(n.items[i]))
213
+ });
214
+ return n.items[i];
215
+ }
216
+ const predecessor = await negativeOffsetInNode(ctx.db, n.subtrees[i], 0);
217
+ log(`replacing ${p(key)} with predecessor ${p(predecessor.k)}`);
218
+ foundItem = n.items[i];
219
+ await ctx.db.patch(node, {
220
+ items: [
221
+ ...n.items.slice(0, i),
222
+ predecessor,
223
+ ...n.items.slice(i + 1)
224
+ ],
225
+ aggregate: n.aggregate && sub(add(n.aggregate, itemAggregate(predecessor)), itemAggregate(n.items[i]))
226
+ });
227
+ n = await ctx.db.get(node);
228
+ key = predecessor.k;
229
+ break;
230
+ }
231
+ }
232
+ if (n.subtrees.length === 0) throw new ConvexError({
233
+ code: "DELETE_MISSING_KEY",
234
+ message: `key ${p(key)} not found in node ${n._id}`
235
+ });
236
+ const deleted = await deleteFromNode(ctx, maxNodeSize, n.subtrees[i], key);
237
+ if (!deleted) return null;
238
+ if (!foundItem) foundItem = deleted;
239
+ const newAggregate = n.aggregate && sub(n.aggregate, itemAggregate(deleted));
240
+ if (newAggregate) await ctx.db.patch(node, { aggregate: newAggregate });
241
+ const deficientSubtree = await ctx.db.get(n.subtrees[i]);
242
+ const minNodeSize = minNodeSizeFor(maxNodeSize);
243
+ if (deficientSubtree.items.length < minNodeSize) {
244
+ log(`deficient subtree ${deficientSubtree._id}`);
245
+ if (i > 0) {
246
+ const leftSibling = await ctx.db.get(n.subtrees[i - 1]);
247
+ if (leftSibling.items.length > minNodeSize) {
248
+ log(`rotating right with left sibling ${leftSibling._id}`);
249
+ const grandchild = leftSibling.subtrees.length ? await ctx.db.get(leftSibling.subtrees[leftSibling.subtrees.length - 1]) : null;
250
+ const grandchildCount = grandchild ? grandchild.aggregate : {
251
+ count: 0,
252
+ sum: 0
253
+ };
254
+ await ctx.db.patch(deficientSubtree._id, {
255
+ items: [n.items[i - 1], ...deficientSubtree.items],
256
+ subtrees: grandchild ? [grandchild._id, ...deficientSubtree.subtrees] : [],
257
+ aggregate: deficientSubtree.aggregate && grandchildCount && add(add(deficientSubtree.aggregate, grandchildCount), itemAggregate(n.items[i - 1]))
258
+ });
259
+ await ctx.db.patch(leftSibling._id, {
260
+ items: leftSibling.items.slice(0, leftSibling.items.length - 1),
261
+ subtrees: grandchild ? leftSibling.subtrees.slice(0, leftSibling.subtrees.length - 1) : [],
262
+ aggregate: leftSibling.aggregate && grandchildCount && sub(sub(leftSibling.aggregate, grandchildCount), itemAggregate(leftSibling.items[leftSibling.items.length - 1]))
263
+ });
264
+ await ctx.db.patch(node, { items: [
265
+ ...n.items.slice(0, i - 1),
266
+ leftSibling.items[leftSibling.items.length - 1],
267
+ ...n.items.slice(i)
268
+ ] });
269
+ return foundItem;
270
+ }
271
+ }
272
+ if (i < n.subtrees.length - 1) {
273
+ const rightSibling = await ctx.db.get(n.subtrees[i + 1]);
274
+ if (rightSibling.items.length > minNodeSize) {
275
+ log(`rotating left with right sibling ${rightSibling._id}`);
276
+ const grandchild = rightSibling.subtrees.length ? await ctx.db.get(rightSibling.subtrees[0]) : null;
277
+ const grandchildCount = grandchild ? grandchild.aggregate : {
278
+ count: 0,
279
+ sum: 0
280
+ };
281
+ await ctx.db.patch(deficientSubtree._id, {
282
+ items: [...deficientSubtree.items, n.items[i]],
283
+ subtrees: grandchild ? [...deficientSubtree.subtrees, grandchild._id] : [],
284
+ aggregate: deficientSubtree.aggregate && grandchildCount && add(add(deficientSubtree.aggregate, grandchildCount), itemAggregate(n.items[i]))
285
+ });
286
+ await ctx.db.patch(rightSibling._id, {
287
+ items: rightSibling.items.slice(1),
288
+ subtrees: grandchild ? rightSibling.subtrees.slice(1) : [],
289
+ aggregate: rightSibling.aggregate && grandchildCount && sub(sub(rightSibling.aggregate, grandchildCount), itemAggregate(rightSibling.items[0]))
290
+ });
291
+ await ctx.db.patch(node, { items: [
292
+ ...n.items.slice(0, i),
293
+ rightSibling.items[0],
294
+ ...n.items.slice(i + 1)
295
+ ] });
296
+ return foundItem;
297
+ }
298
+ }
299
+ if (i > 0) {
300
+ log("merging with left sibling");
301
+ await mergeNodes(ctx.db, n, i - 1);
302
+ } else {
303
+ log("merging with right sibling");
304
+ await mergeNodes(ctx.db, n, i);
305
+ }
306
+ }
307
+ return foundItem;
308
+ }
309
+ async function mergeNodes(db, parent, leftIndex) {
310
+ const left = await db.get(parent.subtrees[leftIndex]);
311
+ const right = await db.get(parent.subtrees[leftIndex + 1]);
312
+ log(`merging ${right._id} into ${left._id}`);
313
+ await db.patch(left._id, {
314
+ items: [
315
+ ...left.items,
316
+ parent.items[leftIndex],
317
+ ...right.items
318
+ ],
319
+ subtrees: [...left.subtrees, ...right.subtrees],
320
+ aggregate: left.aggregate && right.aggregate && add(add(left.aggregate, right.aggregate), itemAggregate(parent.items[leftIndex]))
321
+ });
322
+ await db.patch(parent._id, {
323
+ items: [...parent.items.slice(0, leftIndex), ...parent.items.slice(leftIndex + 1)],
324
+ subtrees: [...parent.subtrees.slice(0, leftIndex + 1), ...parent.subtrees.slice(leftIndex + 2)]
325
+ });
326
+ await db.delete(right._id);
327
+ }
328
+ async function negativeOffsetInNode(db, node, index, k1, k2, preloaded) {
329
+ const filtered = await filterBetween(db, node, k1, k2, preloaded);
330
+ for (const included of filtered.reverse()) if (included.type === "item") {
331
+ if (index === 0) return included.item;
332
+ index -= 1;
333
+ } else {
334
+ const subtree = await db.get(included.subtree);
335
+ const subtreeCount = (await nodeAggregate(db, subtree)).count;
336
+ if (index < subtreeCount) return await negativeOffsetInNode(db, included.subtree, index, void 0, void 0, subtree);
337
+ index -= subtreeCount;
338
+ }
339
+ throw new ConvexError(`negative offset exceeded count by ${index} (in node ${node})`);
340
+ }
341
+ async function atOffsetInNode(db, node, index, k1, k2, preloaded) {
342
+ const filtered = await filterBetween(db, node, k1, k2, preloaded);
343
+ for (const included of filtered) if (included.type === "item") {
344
+ if (index === 0) return included.item;
345
+ index -= 1;
346
+ } else {
347
+ const subtree = await db.get(included.subtree);
348
+ const subtreeCount = (await nodeAggregate(db, subtree)).count;
349
+ if (index < subtreeCount) return await atOffsetInNode(db, included.subtree, index, void 0, void 0, subtree);
350
+ index -= subtreeCount;
351
+ }
352
+ throw new ConvexError(`offset exceeded count by ${index} (in node ${node})`);
353
+ }
354
+ function itemAggregate(item) {
355
+ return {
356
+ count: 1,
357
+ sum: item.s
358
+ };
359
+ }
360
+ function nodeCounts(node) {
361
+ return node.items.map(itemAggregate);
362
+ }
363
+ async function subtreeCounts(db, node) {
364
+ return await Promise.all(node.subtrees.map(async (subtree) => {
365
+ return nodeAggregate(db, await db.get(subtree));
366
+ }));
367
+ }
368
+ async function nodeAggregate(db, node) {
369
+ if (node.aggregate !== void 0) return node.aggregate;
370
+ const subCounts = await subtreeCounts(db, node);
371
+ return add(accumulate(nodeCounts(node)), accumulate(subCounts));
372
+ }
373
+ function add(a, b) {
374
+ return {
375
+ count: a.count + b.count,
376
+ sum: a.sum + b.sum
377
+ };
378
+ }
379
+ function sub(a, b) {
380
+ return {
381
+ count: a.count - b.count,
382
+ sum: a.sum - b.sum
383
+ };
384
+ }
385
+ function accumulate(nums) {
386
+ return nums.reduce(add, {
387
+ count: 0,
388
+ sum: 0
389
+ });
390
+ }
391
+ async function insertIntoNode(ctx, maxNodeSize, node, item) {
392
+ const n = await ctx.db.get(node);
393
+ let i = 0;
394
+ for (; i < n.items.length; i++) {
395
+ const compare = compareKeys(item.k, n.items[i].k);
396
+ if (compare === -1) break;
397
+ if (compare === 0) throw new ConvexError(`key ${p(item.k)} already exists in node ${n._id}`);
398
+ }
399
+ let nextItems = n.items;
400
+ let nextSubtrees = n.subtrees;
401
+ if (n.subtrees.length > 0) {
402
+ const pushUp = await insertIntoNode(ctx, maxNodeSize, n.subtrees[i], item);
403
+ if (pushUp) {
404
+ nextItems = [
405
+ ...n.items.slice(0, i),
406
+ pushUp.item,
407
+ ...n.items.slice(i)
408
+ ];
409
+ nextSubtrees = [
410
+ ...n.subtrees.slice(0, i),
411
+ pushUp.leftSubtree,
412
+ pushUp.rightSubtree,
413
+ ...n.subtrees.slice(i + 1)
414
+ ];
415
+ }
416
+ } else nextItems = [
417
+ ...n.items.slice(0, i),
418
+ item,
419
+ ...n.items.slice(i)
420
+ ];
421
+ const newAggregate = n.aggregate && add(n.aggregate, itemAggregate(item));
422
+ const nodePatch = {};
423
+ if (nextItems !== n.items) nodePatch.items = nextItems;
424
+ if (nextSubtrees !== n.subtrees) nodePatch.subtrees = nextSubtrees;
425
+ if (newAggregate) nodePatch.aggregate = newAggregate;
426
+ if (Object.keys(nodePatch).length > 0) await ctx.db.patch(node, nodePatch);
427
+ const newN = {
428
+ ...n,
429
+ items: nextItems,
430
+ subtrees: nextSubtrees,
431
+ aggregate: newAggregate ?? n.aggregate
432
+ };
433
+ const minNodeSize = minNodeSizeFor(maxNodeSize);
434
+ if (newN.items.length > maxNodeSize) {
435
+ if (newN.items.length !== maxNodeSize + 1 || newN.items.length !== 2 * minNodeSize + 1) throw new Error(`bad ${newN.items.length}`);
436
+ log(`splitting node ${newN._id} at ${newN.items[minNodeSize].k}`);
437
+ const topLevel = nodeCounts(newN);
438
+ const subCounts = await subtreeCounts(ctx.db, newN);
439
+ const leftCount = add(accumulate(topLevel.slice(0, minNodeSize)), accumulate(subCounts.length ? subCounts.slice(0, minNodeSize + 1) : []));
440
+ const rightCount = add(accumulate(topLevel.slice(minNodeSize + 1)), accumulate(subCounts.length ? subCounts.slice(minNodeSize + 1) : []));
441
+ if (newN.aggregate && leftCount.count + rightCount.count + 1 !== newN.aggregate.count) throw new Error(`bad count split ${leftCount.count} ${rightCount.count} ${newN.aggregate.count}`);
442
+ if (newN.aggregate && Math.abs(leftCount.sum + rightCount.sum + newN.items[minNodeSize].s - newN.aggregate.sum) > 1e-5) throw new Error(`bad sum split ${leftCount.sum} ${rightCount.sum} ${newN.items[minNodeSize].s} ${newN.aggregate.sum}`);
443
+ await ctx.db.patch(node, {
444
+ items: newN.items.slice(0, minNodeSize),
445
+ subtrees: newN.subtrees.length ? newN.subtrees.slice(0, minNodeSize + 1) : [],
446
+ aggregate: leftCount
447
+ });
448
+ const splitN = await ctx.db.insert(AGGREGATE_NODE_TABLE, {
449
+ items: newN.items.slice(minNodeSize + 1),
450
+ subtrees: newN.subtrees.length ? newN.subtrees.slice(minNodeSize + 1) : [],
451
+ aggregate: rightCount
452
+ });
453
+ return {
454
+ item: newN.items[minNodeSize],
455
+ leftSubtree: node,
456
+ rightSubtree: splitN,
457
+ leftSubtreeCount: newN.aggregate && leftCount,
458
+ rightSubtreeCount: newN.aggregate && rightCount
459
+ };
460
+ }
461
+ return null;
462
+ }
463
+ function compareKeys(k1, k2) {
464
+ return compareValues$1(k1, k2);
465
+ }
466
+ async function getTree(db, namespace) {
467
+ return await db.query(AGGREGATE_TREE_TABLE).withIndex("by_namespace", (q) => q.eq("namespace", namespace)).unique();
468
+ }
469
+ async function mustGetTree(db, namespace) {
470
+ const tree = await getTree(db, namespace);
471
+ if (!tree) throw new Error("btree not initialized");
472
+ return tree;
473
+ }
474
+ async function getOrCreateTree(db, namespace, maxNodeSize, rootLazy) {
475
+ const originalTree = await getTree(db, namespace);
476
+ const aggregateName = aggregateNameFromNamespace(namespace);
477
+ if (originalTree) {
478
+ assertMaxNodeSize(originalTree.maxNodeSize);
479
+ if (originalTree.aggregateName !== aggregateName) {
480
+ await db.patch(originalTree._id, { aggregateName });
481
+ return {
482
+ ...originalTree,
483
+ aggregateName
484
+ };
485
+ }
486
+ return originalTree;
487
+ }
488
+ const root = await db.insert(AGGREGATE_NODE_TABLE, {
489
+ items: [],
490
+ subtrees: [],
491
+ aggregate: {
492
+ count: 0,
493
+ sum: 0
494
+ }
495
+ });
496
+ const effectiveMaxNodeSize = maxNodeSize ?? (await mustGetTree(db, void 0)).maxNodeSize;
497
+ const effectiveRootLazy = rootLazy ?? await isRootLazy(db, void 0) ?? true;
498
+ const id = await db.insert(AGGREGATE_TREE_TABLE, {
499
+ aggregateName,
500
+ root,
501
+ maxNodeSize: effectiveMaxNodeSize,
502
+ namespace
503
+ });
504
+ const newTree = await db.get(id);
505
+ assertMaxNodeSize(effectiveMaxNodeSize);
506
+ if (effectiveRootLazy) await db.patch(root, { aggregate: void 0 });
507
+ return newTree;
508
+ }
509
+ async function isRootLazy(db, namespace) {
510
+ const tree = await getTree(db, namespace);
511
+ if (!tree) return true;
512
+ return (await db.get(tree.root))?.aggregate === void 0;
513
+ }
514
+ async function deleteTreeNodes(db, node) {
515
+ const current = await db.get(node);
516
+ if (!current) return;
517
+ for (const subtree of current.subtrees) await deleteTreeNodes(db, subtree);
518
+ await db.delete(node);
519
+ }
520
+ /**
521
+ * Deletes up to `limit` nodes from one namespace tree belonging to an
522
+ * aggregate, returning true once none are left. The traversal stack lives on
523
+ * the tree document so a large tree resumes across transactions.
524
+ */
525
+ async function deleteTreesHandler(ctx, args) {
526
+ const tree = (await ctx.db.query(AGGREGATE_TREE_TABLE).withIndex("by_aggregate_name", (q) => q.eq("aggregateName", args.aggregateName)).take(1))[0];
527
+ if (!tree) return true;
528
+ const stack = [...tree.deletionStack ?? [tree.root]];
529
+ let remaining = Math.max(1, Math.floor(args.limit));
530
+ while (stack.length > 0 && remaining > 0) {
531
+ const nodeId = stack.pop();
532
+ const node = await ctx.db.get(nodeId);
533
+ remaining -= 1;
534
+ if (!node) continue;
535
+ stack.push(...node.subtrees);
536
+ await ctx.db.delete(nodeId);
537
+ }
538
+ if (stack.length > 0) await ctx.db.patch(tree._id, { deletionStack: stack });
539
+ else await ctx.db.delete(tree._id);
540
+ return false;
541
+ }
542
+ async function clearTree(db, args) {
543
+ const tree = await getTree(db, args.namespace);
544
+ let existingRootLazy = true;
545
+ let existingMaxNodeSize = DEFAULT_MAX_NODE_SIZE;
546
+ if (tree) {
547
+ await db.delete(tree._id);
548
+ const root = await db.get(tree.root);
549
+ if (root) {
550
+ existingRootLazy = root.aggregate === void 0;
551
+ await deleteTreeNodes(db, tree.root);
552
+ }
553
+ existingMaxNodeSize = tree.maxNodeSize;
554
+ }
555
+ await getOrCreateTree(db, args.namespace, args.maxNodeSize ?? existingMaxNodeSize, args.rootLazy ?? existingRootLazy);
556
+ }
557
+ async function paginateHandler(ctx, args) {
558
+ const tree = await getTree(ctx.db, args.namespace);
559
+ if (tree === null) return {
560
+ page: [],
561
+ cursor: "",
562
+ isDone: true
563
+ };
564
+ return await paginateInNode(ctx.db, tree.root, args.limit, args.order, args.cursor, args.k1, args.k2);
565
+ }
566
+ async function paginateInNode(db, node, limit, order, cursor, k1, k2) {
567
+ if (limit <= 0) throw new ConvexError("limit must be positive");
568
+ if (cursor !== void 0 && cursor.length === 0) return {
569
+ page: [],
570
+ cursor: "",
571
+ isDone: true
572
+ };
573
+ const items = [];
574
+ const filtered = await filterBetween(db, node, cursor === void 0 || order === "desc" ? k1 : jsonToConvex(JSON.parse(cursor)), cursor === void 0 || order === "asc" ? k2 : jsonToConvex(JSON.parse(cursor)));
575
+ if (order === "desc") filtered.reverse();
576
+ for (const included of filtered) {
577
+ if (items.length >= limit) return {
578
+ page: items,
579
+ cursor: JSON.stringify(convexToJson(items[items.length - 1].k)),
580
+ isDone: false
581
+ };
582
+ if (included.type === "item") items.push(included.item);
583
+ else {
584
+ const { page, cursor: newCursor, isDone } = await paginateInNode(db, included.subtree, limit - items.length, order);
585
+ items.push(...page);
586
+ if (!isDone) return {
587
+ page: items,
588
+ cursor: newCursor,
589
+ isDone: false
590
+ };
591
+ }
592
+ }
593
+ return {
594
+ page: items,
595
+ cursor: "",
596
+ isDone: true
597
+ };
598
+ }
599
+ async function paginateNamespacesHandler(ctx, args) {
600
+ if (args.cursor === "endcursor") return {
601
+ page: [],
602
+ cursor: "endcursor",
603
+ isDone: true
604
+ };
605
+ const { page: trees, continueCursor, isDone } = await (args.aggregateName === void 0 ? ctx.db.query(AGGREGATE_TREE_TABLE) : ctx.db.query(AGGREGATE_TREE_TABLE).withIndex("by_aggregate_name", (q) => q.eq("aggregateName", args.aggregateName))).paginate({
606
+ cursor: args.cursor ?? null,
607
+ numItems: args.limit
608
+ });
609
+ return {
610
+ page: trees.map((t) => t.namespace ?? null),
611
+ cursor: isDone ? "endcursor" : continueCursor ?? "endcursor",
612
+ isDone
613
+ };
614
+ }
615
+ async function aggregateBetweenBatchHandler(ctx, args) {
616
+ return await Promise.all(args.queries.map((query) => aggregateBetweenHandler(ctx, query)));
617
+ }
618
+ async function atOffsetBatchHandler(ctx, args) {
619
+ return await Promise.all(args.queries.map((query) => query.offset >= 0 ? atOffsetHandler(ctx, query) : atNegativeOffsetHandler(ctx, {
620
+ ...query,
621
+ offset: -query.offset - 1
622
+ })));
623
+ }
624
+
625
+ //#endregion
626
+ //#region src/aggregate-core/positions.ts
627
+ const BEFORE_ALL_IDS = null;
628
+ const AFTER_ALL_IDS = [];
629
+ function explodeKey(key) {
630
+ if (Array.isArray(key)) {
631
+ const exploded = [""];
632
+ for (const item of key) {
633
+ exploded.push(item);
634
+ exploded.push("");
635
+ }
636
+ return exploded;
637
+ }
638
+ return key;
639
+ }
640
+ function implodeKey(k) {
641
+ if (Array.isArray(k)) {
642
+ const imploded = [];
643
+ for (let i = 1; i < k.length; i += 2) imploded.push(k[i]);
644
+ return imploded;
645
+ }
646
+ return k;
647
+ }
648
+ function keyToPosition(key, id) {
649
+ return [
650
+ explodeKey(key),
651
+ id,
652
+ ""
653
+ ];
654
+ }
655
+ function positionToKey(position) {
656
+ return {
657
+ key: implodeKey(position[0]),
658
+ id: position[1]
659
+ };
660
+ }
661
+ function boundsToPositions(bounds) {
662
+ if (bounds === void 0) return {};
663
+ if ("eq" in bounds) return {
664
+ k1: boundToPosition("lower", {
665
+ key: bounds.eq,
666
+ inclusive: true
667
+ }),
668
+ k2: boundToPosition("upper", {
669
+ key: bounds.eq,
670
+ inclusive: true
671
+ })
672
+ };
673
+ if ("prefix" in bounds) {
674
+ const prefix = bounds.prefix;
675
+ const exploded = [];
676
+ for (const item of prefix) {
677
+ exploded.push("");
678
+ exploded.push(item);
679
+ }
680
+ return {
681
+ k1: [
682
+ exploded.concat([BEFORE_ALL_IDS]),
683
+ BEFORE_ALL_IDS,
684
+ BEFORE_ALL_IDS
685
+ ],
686
+ k2: [
687
+ exploded.concat([AFTER_ALL_IDS]),
688
+ AFTER_ALL_IDS,
689
+ AFTER_ALL_IDS
690
+ ]
691
+ };
692
+ }
693
+ return {
694
+ k1: boundToPosition("lower", bounds.lower),
695
+ k2: boundToPosition("upper", bounds.upper)
696
+ };
697
+ }
698
+ function boundToPosition(direction, bound) {
699
+ if (bound === void 0) return;
700
+ if (direction === "lower") return [
701
+ explodeKey(bound.key),
702
+ bound.id ?? (bound.inclusive ? BEFORE_ALL_IDS : AFTER_ALL_IDS),
703
+ bound.inclusive ? BEFORE_ALL_IDS : AFTER_ALL_IDS
704
+ ];
705
+ return [
706
+ explodeKey(bound.key),
707
+ bound.id ?? (bound.inclusive ? AFTER_ALL_IDS : BEFORE_ALL_IDS),
708
+ bound.inclusive ? AFTER_ALL_IDS : BEFORE_ALL_IDS
709
+ ];
710
+ }
711
+
712
+ //#endregion
713
+ //#region src/aggregate-core/runtime.ts
714
+ const INTERNAL_NAMESPACE_MARKER_MISSING = 0;
715
+ const INTERNAL_NAMESPACE_MARKER_PRESENT = 1;
716
+ const encodeNamespace = (aggregateName, namespace) => [
717
+ aggregateName,
718
+ namespace === void 0 ? null : namespace,
719
+ namespace === void 0 ? INTERNAL_NAMESPACE_MARKER_MISSING : INTERNAL_NAMESPACE_MARKER_PRESENT
720
+ ];
721
+ const isInternalNamespace = (value) => Array.isArray(value) && value.length === 3 && typeof value[0] === "string" && (value[2] === INTERNAL_NAMESPACE_MARKER_MISSING || value[2] === INTERNAL_NAMESPACE_MARKER_PRESENT);
722
+ const decodeNamespace = (namespace) => {
723
+ if (namespace[2] === INTERNAL_NAMESPACE_MARKER_MISSING) return;
724
+ return namespace[1];
725
+ };
726
+ const namespaceForOpts = (aggregateName, opts) => encodeNamespace(aggregateName, namespaceFromOpts(opts));
727
+ const namespaceForArg = (aggregateName, args) => encodeNamespace(aggregateName, namespaceFromArg(args));
728
+ /**
729
+ * Write data to be aggregated, and read aggregated data.
730
+ */
731
+ var Aggregate = class {
732
+ constructor(aggregateName) {
733
+ this.aggregateName = aggregateName;
734
+ }
735
+ async count(ctx, ...opts) {
736
+ return (await aggregateBetweenHandler({ db: ctx.db }, {
737
+ ...boundsToPositions(opts[0]?.bounds),
738
+ namespace: namespaceForOpts(this.aggregateName, opts)
739
+ })).count;
740
+ }
741
+ async countBatch(ctx, queries) {
742
+ return (await aggregateBetweenBatchHandler({ db: ctx.db }, { queries: queries.map((query) => {
743
+ if (!query) throw new Error("You must pass bounds and/or namespace");
744
+ return {
745
+ ...boundsToPositions(query.bounds),
746
+ namespace: namespaceForArg(this.aggregateName, query)
747
+ };
748
+ }) })).map((result) => result.count);
749
+ }
750
+ async sum(ctx, ...opts) {
751
+ return (await aggregateBetweenHandler({ db: ctx.db }, {
752
+ ...boundsToPositions(opts[0]?.bounds),
753
+ namespace: namespaceForOpts(this.aggregateName, opts)
754
+ })).sum;
755
+ }
756
+ async sumBatch(ctx, queries) {
757
+ return (await aggregateBetweenBatchHandler({ db: ctx.db }, { queries: queries.map((query) => {
758
+ if (!query) throw new Error("You must pass bounds and/or namespace");
759
+ return {
760
+ ...boundsToPositions(query.bounds),
761
+ namespace: namespaceForArg(this.aggregateName, query)
762
+ };
763
+ }) })).map((result) => result.sum);
764
+ }
765
+ async at(ctx, offset, ...opts) {
766
+ const encodedNamespace = namespaceForOpts(this.aggregateName, opts);
767
+ return btreeItemToAggregateItem(offset < 0 ? await atNegativeOffsetHandler({ db: ctx.db }, {
768
+ ...boundsToPositions(opts[0]?.bounds),
769
+ namespace: encodedNamespace,
770
+ offset: -offset - 1
771
+ }) : await atOffsetHandler({ db: ctx.db }, {
772
+ ...boundsToPositions(opts[0]?.bounds),
773
+ namespace: encodedNamespace,
774
+ offset
775
+ }));
776
+ }
777
+ async atBatch(ctx, queries) {
778
+ return (await atOffsetBatchHandler({ db: ctx.db }, { queries: queries.map((query) => ({
779
+ ...boundsToPositions(query.bounds),
780
+ namespace: namespaceForArg(this.aggregateName, query),
781
+ offset: query.offset
782
+ })) })).map(btreeItemToAggregateItem);
783
+ }
784
+ async indexOf(ctx, key, ...opts) {
785
+ const { k1, k2 } = boundsToPositions(opts[0]?.bounds);
786
+ const namespace = namespaceForOpts(this.aggregateName, opts);
787
+ if (opts[0]?.order === "desc") return offsetUntilHandler({ db: ctx.db }, {
788
+ k2,
789
+ key: boundToPosition("upper", {
790
+ id: opts[0]?.id,
791
+ inclusive: true,
792
+ key
793
+ }),
794
+ namespace
795
+ });
796
+ return offsetHandler({ db: ctx.db }, {
797
+ k1,
798
+ key: boundToPosition("lower", {
799
+ id: opts[0]?.id,
800
+ inclusive: true,
801
+ key
802
+ }),
803
+ namespace
804
+ });
805
+ }
806
+ async offsetOf(ctx, key, namespace, id, bounds) {
807
+ return this.indexOf(ctx, key, {
808
+ bounds,
809
+ id,
810
+ namespace,
811
+ order: "asc"
812
+ });
813
+ }
814
+ async offsetUntil(ctx, key, namespace, id, bounds) {
815
+ return this.indexOf(ctx, key, {
816
+ bounds,
817
+ id,
818
+ namespace,
819
+ order: "desc"
820
+ });
821
+ }
822
+ async min(ctx, ...opts) {
823
+ const { page } = await this.paginate(ctx, {
824
+ bounds: opts[0]?.bounds,
825
+ namespace: namespaceFromOpts(opts),
826
+ order: "asc",
827
+ pageSize: 1
828
+ });
829
+ return page[0] ?? null;
830
+ }
831
+ async max(ctx, ...opts) {
832
+ const { page } = await this.paginate(ctx, {
833
+ bounds: opts[0]?.bounds,
834
+ namespace: namespaceFromOpts(opts),
835
+ order: "desc",
836
+ pageSize: 1
837
+ });
838
+ return page[0] ?? null;
839
+ }
840
+ async random(ctx, ...opts) {
841
+ const count = await this.count(ctx, ...opts);
842
+ if (count === 0) return null;
843
+ return this.at(ctx, Math.floor(Math.random() * count), ...opts);
844
+ }
845
+ async paginate(ctx, ...opts) {
846
+ const result = await paginateHandler({ db: ctx.db }, {
847
+ ...boundsToPositions(opts[0]?.bounds),
848
+ cursor: opts[0]?.cursor,
849
+ limit: opts[0]?.pageSize ?? 100,
850
+ namespace: namespaceForOpts(this.aggregateName, opts),
851
+ order: opts[0]?.order ?? "asc"
852
+ });
853
+ return {
854
+ cursor: result.cursor,
855
+ isDone: result.isDone,
856
+ page: result.page.map(btreeItemToAggregateItem)
857
+ };
858
+ }
859
+ async *iter(ctx, ...opts) {
860
+ const bounds = opts[0]?.bounds;
861
+ const namespace = namespaceFromOpts(opts);
862
+ const order = opts[0]?.order ?? "asc";
863
+ const pageSize = opts[0]?.pageSize ?? 100;
864
+ let cursor;
865
+ let isDone = false;
866
+ while (!isDone) {
867
+ const page = await this.paginate(ctx, {
868
+ bounds,
869
+ cursor,
870
+ namespace,
871
+ order,
872
+ pageSize
873
+ });
874
+ for (const item of page.page) yield item;
875
+ cursor = page.cursor;
876
+ isDone = page.isDone;
877
+ }
878
+ }
879
+ async _insert(ctx, namespace, key, id, summand) {
880
+ await insertHandler({ db: ctx.db }, {
881
+ key: keyToPosition(key, id),
882
+ namespace: namespaceForArg(this.aggregateName, { namespace }),
883
+ summand,
884
+ value: id
885
+ });
886
+ }
887
+ async _delete(ctx, namespace, key, id) {
888
+ await deleteHandler({ db: ctx.db }, {
889
+ key: keyToPosition(key, id),
890
+ namespace: namespaceForArg(this.aggregateName, { namespace })
891
+ });
892
+ }
893
+ async _replace(ctx, currentNamespace, currentKey, newNamespace, newKey, id, summand) {
894
+ await deleteHandler({ db: ctx.db }, {
895
+ key: keyToPosition(currentKey, id),
896
+ namespace: namespaceForArg(this.aggregateName, { namespace: currentNamespace })
897
+ });
898
+ await insertHandler({ db: ctx.db }, {
899
+ key: keyToPosition(newKey, id),
900
+ namespace: namespaceForArg(this.aggregateName, { namespace: newNamespace }),
901
+ summand,
902
+ value: id
903
+ });
904
+ }
905
+ async _insertIfDoesNotExist(ctx, namespace, key, id, summand) {
906
+ await this._replaceOrInsert(ctx, namespace, key, namespace, key, id, summand);
907
+ }
908
+ async _deleteIfExists(ctx, namespace, key, id) {
909
+ try {
910
+ await this._delete(ctx, namespace, key, id);
911
+ } catch (error) {
912
+ if (error instanceof ConvexError && error.data?.code === "DELETE_MISSING_KEY") return;
913
+ throw error;
914
+ }
915
+ }
916
+ async _replaceOrInsert(ctx, currentNamespace, currentKey, newNamespace, newKey, id, summand) {
917
+ try {
918
+ await this._delete(ctx, currentNamespace, currentKey, id);
919
+ } catch (error) {
920
+ if (!(error instanceof ConvexError && error.data?.code === "DELETE_MISSING_KEY")) throw error;
921
+ }
922
+ await this._insert(ctx, newNamespace, newKey, id, summand);
923
+ }
924
+ async clear(ctx, ...opts) {
925
+ await clearTree(ctx.db, {
926
+ maxNodeSize: opts[0]?.maxNodeSize,
927
+ namespace: namespaceForOpts(this.aggregateName, opts),
928
+ rootLazy: opts[0]?.rootLazy
929
+ });
930
+ }
931
+ /**
932
+ * Deletes up to `limit` namespace trees without recreating them. Returns true
933
+ * once this aggregate owns no trees, so callers can drain every namespace
934
+ * across several mutations instead of walking them all in one.
935
+ */
936
+ async deleteTrees(ctx, limit) {
937
+ return deleteTreesHandler({ db: ctx.db }, {
938
+ aggregateName: this.aggregateName,
939
+ limit
940
+ });
941
+ }
942
+ async makeRootLazy(ctx, namespace) {
943
+ const tree = await getOrCreateTree(ctx.db, namespaceForArg(this.aggregateName, { namespace }));
944
+ await ctx.db.patch(tree.root, { aggregate: void 0 });
945
+ }
946
+ async paginateNamespaces(ctx, cursor, pageSize = 100) {
947
+ const result = await paginateNamespacesHandler({ db: ctx.db }, {
948
+ aggregateName: this.aggregateName,
949
+ cursor,
950
+ limit: pageSize
951
+ });
952
+ const page = [];
953
+ for (const namespace of result.page) {
954
+ if (!isInternalNamespace(namespace)) continue;
955
+ if (namespace[0] !== this.aggregateName) continue;
956
+ page.push(decodeNamespace(namespace));
957
+ }
958
+ return {
959
+ cursor: result.cursor,
960
+ isDone: result.isDone,
961
+ page
962
+ };
963
+ }
964
+ async *iterNamespaces(ctx, pageSize = 100) {
965
+ let cursor;
966
+ let isDone = false;
967
+ while (!isDone) {
968
+ const page = await this.paginateNamespaces(ctx, cursor, pageSize);
969
+ for (const namespace of page.page) yield namespace;
970
+ cursor = page.cursor;
971
+ isDone = page.isDone;
972
+ }
973
+ }
974
+ async clearAll(ctx, opts) {
975
+ for await (const namespace of this.iterNamespaces(ctx)) await this.clear(ctx, {
976
+ ...opts,
977
+ namespace
978
+ });
979
+ await this.clear(ctx, {
980
+ ...opts,
981
+ namespace: void 0
982
+ });
983
+ }
984
+ async makeAllRootsLazy(ctx) {
985
+ for await (const namespace of this.iterNamespaces(ctx)) await this.makeRootLazy(ctx, namespace);
986
+ }
987
+ };
988
+ var DirectAggregate = class extends Aggregate {
989
+ constructor(config) {
990
+ super(config.name);
991
+ }
992
+ async insert(ctx, args) {
993
+ await this._insert(ctx, namespaceFromArg(args), args.key, args.id, args.sumValue);
994
+ }
995
+ async delete(ctx, args) {
996
+ await this._delete(ctx, namespaceFromArg(args), args.key, args.id);
997
+ }
998
+ async replace(ctx, currentItem, newItem) {
999
+ await this._replace(ctx, namespaceFromArg(currentItem), currentItem.key, namespaceFromArg(newItem), newItem.key, currentItem.id, newItem.sumValue);
1000
+ }
1001
+ async insertIfDoesNotExist(ctx, args) {
1002
+ await this._insertIfDoesNotExist(ctx, namespaceFromArg(args), args.key, args.id, args.sumValue);
1003
+ }
1004
+ async deleteIfExists(ctx, args) {
1005
+ await this._deleteIfExists(ctx, namespaceFromArg(args), args.key, args.id);
1006
+ }
1007
+ async replaceOrInsert(ctx, currentItem, newItem) {
1008
+ await this._replaceOrInsert(ctx, namespaceFromArg(currentItem), currentItem.key, namespaceFromArg(newItem), newItem.key, currentItem.id, newItem.sumValue);
1009
+ }
1010
+ };
1011
+ var TableAggregate = class extends Aggregate {
1012
+ constructor(options) {
1013
+ super(options.name);
1014
+ this.options = options;
1015
+ }
1016
+ options;
1017
+ async insert(ctx, doc) {
1018
+ await this._insert(ctx, this.options.namespace?.(doc), this.options.sortKey(doc), doc._id, this.options.sumValue?.(doc));
1019
+ }
1020
+ async delete(ctx, doc) {
1021
+ await this._delete(ctx, this.options.namespace?.(doc), this.options.sortKey(doc), doc._id);
1022
+ }
1023
+ async replace(ctx, oldDoc, newDoc) {
1024
+ await this._replace(ctx, this.options.namespace?.(oldDoc), this.options.sortKey(oldDoc), this.options.namespace?.(newDoc), this.options.sortKey(newDoc), newDoc._id, this.options.sumValue?.(newDoc));
1025
+ }
1026
+ async insertIfDoesNotExist(ctx, doc) {
1027
+ await this._insertIfDoesNotExist(ctx, this.options.namespace?.(doc), this.options.sortKey(doc), doc._id, this.options.sumValue?.(doc));
1028
+ }
1029
+ async deleteIfExists(ctx, doc) {
1030
+ await this._deleteIfExists(ctx, this.options.namespace?.(doc), this.options.sortKey(doc), doc._id);
1031
+ }
1032
+ async replaceOrInsert(ctx, oldDoc, newDoc) {
1033
+ await this._replaceOrInsert(ctx, this.options.namespace?.(oldDoc), this.options.sortKey(oldDoc), this.options.namespace?.(newDoc), this.options.sortKey(newDoc), newDoc._id, this.options.sumValue?.(newDoc));
1034
+ }
1035
+ async indexOfDoc(ctx, doc, opts) {
1036
+ return this.indexOf(ctx, this.options.sortKey(doc), {
1037
+ namespace: this.options.namespace?.(doc),
1038
+ ...opts
1039
+ });
1040
+ }
1041
+ trigger() {
1042
+ return async (ctx, change) => {
1043
+ if (change.operation === "insert") await this.insert(ctx, change.newDoc);
1044
+ else if (change.operation === "update") await this.replace(ctx, change.oldDoc, change.newDoc);
1045
+ else if (change.operation === "delete") await this.delete(ctx, change.oldDoc);
1046
+ };
1047
+ }
1048
+ idempotentTrigger() {
1049
+ return async (ctx, change) => {
1050
+ if (change.operation === "insert") await this.insertIfDoesNotExist(ctx, change.newDoc);
1051
+ else if (change.operation === "update") await this.replaceOrInsert(ctx, change.oldDoc, change.newDoc);
1052
+ else if (change.operation === "delete") await this.deleteIfExists(ctx, change.oldDoc);
1053
+ };
1054
+ }
1055
+ };
1056
+ function btreeItemToAggregateItem({ k, s }) {
1057
+ const { key, id } = positionToKey(k);
1058
+ return {
1059
+ id,
1060
+ key,
1061
+ sumValue: s
1062
+ };
1063
+ }
1064
+ function namespaceFromArg(args) {
1065
+ if ("namespace" in args) return args.namespace;
1066
+ }
1067
+ function namespaceFromOpts(opts) {
1068
+ if (opts.length === 0) return;
1069
+ const [{ namespace }] = opts;
1070
+ return namespace;
1071
+ }
1072
+
1073
+ //#endregion
1074
+ export { TableAggregate as n, aggregateStorageTables as r, DirectAggregate as t };