@gaganref/confect-test 10.3.1-fork.87 → 10.3.1-fork.89

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 (51) hide show
  1. package/dist/internal/Attempt.d.ts +77 -0
  2. package/dist/internal/Attempt.d.ts.map +1 -0
  3. package/dist/internal/Attempt.js +154 -0
  4. package/dist/internal/Attempt.js.map +1 -0
  5. package/dist/internal/ConvexTest.d.ts +34 -0
  6. package/dist/internal/ConvexTest.d.ts.map +1 -0
  7. package/dist/internal/ConvexTest.js +59 -0
  8. package/dist/internal/ConvexTest.js.map +1 -0
  9. package/dist/internal/Execution.d.ts +167 -0
  10. package/dist/internal/Execution.d.ts.map +1 -0
  11. package/dist/internal/Execution.js +790 -0
  12. package/dist/internal/Execution.js.map +1 -0
  13. package/dist/internal/Globals.d.ts +11 -0
  14. package/dist/internal/Globals.d.ts.map +1 -0
  15. package/dist/internal/Globals.js +76 -0
  16. package/dist/internal/Globals.js.map +1 -0
  17. package/dist/internal/Invocation.d.ts +57 -0
  18. package/dist/internal/Invocation.d.ts.map +1 -0
  19. package/dist/internal/Invocation.js +145 -0
  20. package/dist/internal/Invocation.js.map +1 -0
  21. package/dist/internal/Kernel.d.ts +93 -0
  22. package/dist/internal/Kernel.d.ts.map +1 -0
  23. package/dist/internal/Kernel.js +91 -0
  24. package/dist/internal/Kernel.js.map +1 -0
  25. package/dist/internal/KernelQuery.d.ts +55 -0
  26. package/dist/internal/KernelQuery.d.ts.map +1 -0
  27. package/dist/internal/KernelQuery.js +205 -0
  28. package/dist/internal/KernelQuery.js.map +1 -0
  29. package/dist/internal/KernelRefusal.d.ts +77 -0
  30. package/dist/internal/KernelRefusal.d.ts.map +1 -0
  31. package/dist/internal/KernelRefusal.js +73 -0
  32. package/dist/internal/KernelRefusal.js.map +1 -0
  33. package/dist/internal/KernelValues.d.ts +136 -0
  34. package/dist/internal/KernelValues.d.ts.map +1 -0
  35. package/dist/internal/KernelValues.js +266 -0
  36. package/dist/internal/KernelValues.js.map +1 -0
  37. package/dist/internal/ReadSet.d.ts +55 -0
  38. package/dist/internal/ReadSet.d.ts.map +1 -0
  39. package/dist/internal/ReadSet.js +29 -0
  40. package/dist/internal/ReadSet.js.map +1 -0
  41. package/package.json +3 -3
  42. package/src/internal/Attempt.ts +185 -0
  43. package/src/internal/ConvexTest.ts +118 -0
  44. package/src/internal/Execution.ts +1430 -0
  45. package/src/internal/Globals.ts +93 -0
  46. package/src/internal/Invocation.ts +291 -0
  47. package/src/internal/Kernel.ts +190 -0
  48. package/src/internal/KernelQuery.ts +405 -0
  49. package/src/internal/KernelRefusal.ts +88 -0
  50. package/src/internal/KernelValues.ts +725 -0
  51. package/src/internal/ReadSet.ts +108 -0
@@ -0,0 +1,790 @@
1
+ import { own } from "./Globals.js";
2
+ import { createFunctionHandle, createTestJwt, deserializeConvexErrorData, evaluateValue, hasPendingValues, parseArgs, parseFunctionHandle, resolveCommittedValues, simpleHash, tableNameFromId, validateFunctionArgs, validateReturnValue } from "./KernelValues.js";
3
+ import { apply, conflict, empty, wallClock } from "./Kernel.js";
4
+ import { KernelAttempt } from "./Attempt.js";
5
+ import { bind, current as current$1 } from "./Invocation.js";
6
+ import { ClosedAttempt, CommitTsNotIncreasing, OptimisticConcurrencyControlFailure, RegisteredAfterOpen, StaleAttempt, requiresBinary, rowPending } from "./KernelRefusal.js";
7
+ import { exportSchema, paginate, stream, validateDocument } from "./KernelQuery.js";
8
+ import { actionGeneric, getFunctionAddress, mutationGeneric, queryGeneric } from "convex/server";
9
+ import { AsyncLocalStorage } from "node:async_hooks";
10
+ import { convexToJson, jsonToConvex } from "convex/values";
11
+ //#region src/internal/Execution.ts
12
+ const ROOT = "";
13
+ const TYPICAL_CONVEX_ID_LENGTH = 32;
14
+ const anonymous = {
15
+ identity: null,
16
+ token: null,
17
+ ip: null,
18
+ userAgent: null
19
+ };
20
+ const withIdentity = (caller, identity) => {
21
+ const subject = identity.subject ?? "" + simpleHash(JSON.stringify(identity));
22
+ const issuer = identity.issuer ?? "https://convex.test";
23
+ const tokenIdentifier = identity.tokenIdentifier ?? `${issuer}|${subject}`;
24
+ const full = {
25
+ ...identity,
26
+ subject,
27
+ issuer,
28
+ tokenIdentifier
29
+ };
30
+ return {
31
+ ...caller,
32
+ identity: full,
33
+ token: createTestJwt(full)
34
+ };
35
+ };
36
+ const lastAttempt = 5;
37
+ const tagOf = (error) => {
38
+ const tagged = (value) => typeof value === "object" && value !== null && typeof value._tag === "string";
39
+ const data = error?.data;
40
+ if (tagged(data)) return data._tag;
41
+ if (tagged(error)) return error._tag;
42
+ return error instanceof Error ? error.name : "Error";
43
+ };
44
+ /**
45
+ * A queue that runs one task at a time, in the order they were taken.
46
+ */
47
+ var Turn = class {
48
+ tail = Promise.resolve();
49
+ take(task) {
50
+ const result = this.tail.then(task);
51
+ this.tail = result.then(() => void 0, () => void 0);
52
+ return result;
53
+ }
54
+ /**
55
+ * Resolves once every task taken so far has settled, including the tasks
56
+ * taken while waiting.
57
+ */
58
+ idle() {
59
+ const tail = this.tail;
60
+ return tail.then(() => this.tail === tail ? void 0 : this.idle());
61
+ }
62
+ };
63
+ /**
64
+ * A function's invocation finishes once its handler returned and every syscall
65
+ * it started has run. On the binary a query or mutation keeps running the
66
+ * syscalls in its queue after its promise resolves, then returns (`run_inner`
67
+ * in `crates/isolate/src/environment/udf/mod.rs`, 1.49), so an unawaited write
68
+ * still lands in its own transaction.
69
+ */
70
+ const settled = (execution, result) => execution.turn.idle().then(() => result);
71
+ const executions = new AsyncLocalStorage();
72
+ /**
73
+ * Run a function's code as `execution`, with its own copy of the globals a test
74
+ * invocation pins.
75
+ */
76
+ const enter = (execution, run) => own(() => executions.run(execution, run));
77
+ const kernelBrand = Symbol.for("@confect/test/Kernel");
78
+ const current = () => {
79
+ const execution = executions.getStore();
80
+ if (execution === void 0) throw new Error("A Convex syscall ran outside any function the test kernel started.");
81
+ return execution;
82
+ };
83
+ let nextRequestId = 0;
84
+ const newRequest = (caller) => ({
85
+ ip: caller.ip,
86
+ userAgent: caller.userAgent,
87
+ requestId: `kernel-request-${nextRequestId++}`,
88
+ scheduledFunctionId: null,
89
+ authToken: caller.token
90
+ });
91
+ const findModulesRoot = (paths) => {
92
+ const generated = paths.find((path) => path.includes("_generated"));
93
+ if (generated === void 0) throw new Error("Could not find the \"_generated\" directory, make sure to run `npx convex dev` or `npx convex codegen`. Make sure your `import.meta.glob` includes the files in the \"_generated\" directory");
94
+ return generated.split("_generated", 2)[0];
95
+ };
96
+ const makeComponent = (path, schema, modules) => {
97
+ const root = findModulesRoot(Object.keys(modules));
98
+ const relative = Object.entries(modules).filter(([key]) => key.startsWith(root)).map(([key, load]) => [key.slice(root.length), load]);
99
+ const nested = relative.map(([file]) => file).filter((file) => file.endsWith("/convex.config.ts")).map((file) => file.slice(0, -16));
100
+ return {
101
+ path,
102
+ schema: exportSchema(schema),
103
+ loaders: new Map(relative.filter(([file]) => isFunctionModule(file) && !nested.some((dir) => file.startsWith(dir))).map(([file, load]) => [file.replace(/\.[^.]+$/, ""), load])),
104
+ loaded: /* @__PURE__ */ new Map()
105
+ };
106
+ };
107
+ const entryExtensions = [
108
+ ".js",
109
+ ".mjs",
110
+ ".cjs",
111
+ ".ts",
112
+ ".tsx",
113
+ ".mts",
114
+ ".cts",
115
+ ".jsx"
116
+ ];
117
+ /**
118
+ * Whether Convex's bundler deploys this file as a function module, by the rule
119
+ * `entryPoints` applies in `convex/src/bundler/index.ts` (1.49). A test file, a
120
+ * schema, a config and `_generated` never reach the binary, so the kernel
121
+ * neither loads them nor resolves a function in them.
122
+ */
123
+ const isFunctionModule = (file) => {
124
+ const base = file.split("/").pop();
125
+ return entryExtensions.some((extension) => file.endsWith(extension)) && !file.startsWith("_generated/") && !base.startsWith(".") && !base.startsWith("#") && base !== "schema.ts" && base !== "schema.js" && (base.match(/\./g) ?? []).length <= 1 && !file.includes(" ");
126
+ };
127
+ const unregistered = (world, componentPath) => {
128
+ const registered = [...world.components.keys()].filter((p) => p !== ROOT);
129
+ return /* @__PURE__ */ new Error(`Component "${componentPath}" is not registered on this test backend. ` + (registered.length === 0 ? "No components have been registered." : `Registered components: ${registered.map((p) => `"${p}"`).join(", ")}.`));
130
+ };
131
+ /**
132
+ * Where an address points, read from the calling component.
133
+ */
134
+ const functionPathOf = (address, from) => {
135
+ if (address.functionHandle !== void 0) return parseFunctionHandle(address.functionHandle);
136
+ if (address.name !== void 0) return {
137
+ udfPath: address.name,
138
+ componentPath: from
139
+ };
140
+ if (address.reference !== void 0) {
141
+ const parts = address.reference.split("/");
142
+ const child = parts[2];
143
+ const rest = parts.slice(3);
144
+ return {
145
+ componentPath: from.length > 0 ? `${from}/${child}` : child,
146
+ udfPath: `${rest.slice(0, -1).join("/")}:${rest[rest.length - 1]}`
147
+ };
148
+ }
149
+ throw new Error("Function address not supported");
150
+ };
151
+ const pathOfReference = (reference, from) => functionPathOf(getFunctionAddress(reference), from);
152
+ const kindCheck = {
153
+ query: "isQuery",
154
+ mutation: "isMutation",
155
+ action: "isAction"
156
+ };
157
+ /**
158
+ * A test backend: its registered components and the kernel state they share.
159
+ */
160
+ var World = class {
161
+ runtime;
162
+ components = /* @__PURE__ */ new Map();
163
+ state = empty;
164
+ opened;
165
+ nextDocId = 1e4;
166
+ lastCreationTime = 0;
167
+ nextQueryId = 1;
168
+ queries = /* @__PURE__ */ new Map();
169
+ holding = /* @__PURE__ */ new Map();
170
+ nextAttemptId = 1;
171
+ constructor(schema, modules, runtime = wallClock()) {
172
+ this.runtime = runtime;
173
+ installConvexGlobal();
174
+ this.components.set(ROOT, makeComponent(ROOT, schema, modules));
175
+ }
176
+ register(componentPath, schema, modules) {
177
+ if (this.opened !== void 0) throw new RegisteredAfterOpen({
178
+ componentPath,
179
+ message: `Component "${componentPath}" was registered after the test backend opened. Register every component before the first call.`
180
+ });
181
+ this.components.set(componentPath, makeComponent(componentPath, schema, modules));
182
+ }
183
+ /**
184
+ * Load every registered module of every component, once, before any function
185
+ * runs.
186
+ */
187
+ open() {
188
+ this.opened ??= Promise.all(Array.from(this.components.values(), (component) => Promise.all(Array.from(component.loaders, ([path, load]) => load().then((module) => component.loaded.set(path, module)))))).then(() => void 0);
189
+ return this.opened;
190
+ }
191
+ component(componentPath) {
192
+ const component = this.components.get(componentPath);
193
+ if (component === void 0) throw unregistered(this, componentPath);
194
+ return component;
195
+ }
196
+ resolve(functionPath, kind) {
197
+ const [modulePath, maybeExport] = functionPath.udfPath.split(":");
198
+ const exportName = maybeExport ?? "default";
199
+ const module = this.component(functionPath.componentPath).loaded.get(modulePath);
200
+ if (module === void 0) throw new Error(`Could not find module for: "${modulePath}"`);
201
+ const func = module[exportName];
202
+ if (func === void 0) throw new Error(`Expected a Convex function exported from module "${modulePath}" as \`${exportName}\`, but there is no such export.`);
203
+ const handler = "_handler" in func ? func._handler : func;
204
+ if (typeof handler !== "function") throw new Error(`Expected a Convex function exported from module "${modulePath}" as \`${exportName}\`, but got: ${func}`);
205
+ if (kind !== "any" && !func[kindCheck[kind]]) throw new Error(`Expected a ${kind} function, but the function exported from module "${modulePath}" as \`${exportName}\` is not a ${kind}.`);
206
+ const args = JSON.parse(func.exportArgs());
207
+ if (args.type !== "object" && args.type !== "any") throw new Error(`Invalid JSON returned from ${modulePath}.js:${exportName}.exportArgs(): Args validator must be an object or any`);
208
+ return {
209
+ func,
210
+ handler,
211
+ args,
212
+ returns: JSON.parse(func.exportReturns())
213
+ };
214
+ }
215
+ query(caller, reference, args) {
216
+ return this.open().then(() => {
217
+ const from = {
218
+ caller,
219
+ request: newRequest(caller)
220
+ };
221
+ return typeof reference === "function" ? this.runQuery({
222
+ componentPath: ROOT,
223
+ udfPath: "inline"
224
+ }, {
225
+ handler: reference,
226
+ args: { type: "any" },
227
+ returns: null
228
+ }, args ?? {}, from) : this.queryAt(pathOfReference(reference, ROOT), args, from);
229
+ });
230
+ }
231
+ mutation(caller, reference, args) {
232
+ return this.open().then(() => {
233
+ const from = {
234
+ caller,
235
+ request: newRequest(caller)
236
+ };
237
+ return typeof reference === "function" ? this.runMutation({
238
+ componentPath: ROOT,
239
+ udfPath: "inline"
240
+ }, {
241
+ handler: reference,
242
+ args: { type: "any" },
243
+ returns: null
244
+ }, args ?? {}, from) : this.mutationAt(pathOfReference(reference, ROOT), args, from);
245
+ });
246
+ }
247
+ action(caller, reference, args) {
248
+ return this.open().then(() => {
249
+ const from = {
250
+ caller,
251
+ request: newRequest(caller)
252
+ };
253
+ return typeof reference === "function" ? this.runAction({
254
+ componentPath: ROOT,
255
+ udfPath: "inline"
256
+ }, {
257
+ handler: reference,
258
+ args: { type: "any" },
259
+ returns: null
260
+ }, args ?? {}, from) : this.actionAt(pathOfReference(reference, ROOT), args, from);
261
+ });
262
+ }
263
+ run(caller, componentPath, handler) {
264
+ return this.open().then(() => {
265
+ this.component(componentPath);
266
+ return this.runMutation({
267
+ componentPath,
268
+ udfPath: "custom"
269
+ }, {
270
+ handler,
271
+ args: { type: "any" },
272
+ returns: null
273
+ }, {}, {
274
+ caller,
275
+ request: newRequest(caller)
276
+ });
277
+ });
278
+ }
279
+ /**
280
+ * Run a mutation to its commit point and hold it as attempt 1.
281
+ */
282
+ prepare(caller, reference, args) {
283
+ return this.open().then(() => {
284
+ const functionPath = pathOfReference(reference, ROOT);
285
+ const resolved = this.resolve(functionPath, "mutation");
286
+ validateFunctionArgs(resolved.args, args ?? {}, functionPath, false);
287
+ return this.prepareMutation(functionPath, resolved, args, {
288
+ caller,
289
+ request: newRequest(caller)
290
+ }, 1, current$1()).then((held) => held.view);
291
+ });
292
+ }
293
+ apply(id) {
294
+ const held = this.holding.get(id);
295
+ return held === void 0 ? Promise.reject(new StaleAttempt({
296
+ id,
297
+ message: `The test kernel holds no attempt "${id}". It was already applied, or never prepared.`
298
+ })) : this.applyHeld(held);
299
+ }
300
+ /**
301
+ * The held attempts, oldest first.
302
+ */
303
+ held() {
304
+ return Array.from(this.holding.values(), (held) => held.view);
305
+ }
306
+ queryAt(functionPath, args, from, snapshotOnly = false) {
307
+ const resolved = this.resolve(functionPath, "query");
308
+ validateFunctionArgs(resolved.args, args ?? {}, functionPath, from.parent?.attempt !== void 0);
309
+ return this.runQuery(functionPath, resolved, args, from, snapshotOnly);
310
+ }
311
+ mutationAt(functionPath, args, from) {
312
+ const resolved = this.resolve(functionPath, "mutation");
313
+ validateFunctionArgs(resolved.args, args ?? {}, functionPath, from.parent?.attempt !== void 0);
314
+ return this.runMutation(functionPath, resolved, args, from);
315
+ }
316
+ actionAt(functionPath, args, from) {
317
+ const resolved = this.resolve(functionPath, "action");
318
+ validateFunctionArgs(resolved.args, args ?? {}, functionPath, false);
319
+ return this.runAction(functionPath, resolved, args, from);
320
+ }
321
+ execution(functionPath, udfType, attempt, from, pagination) {
322
+ const identity = functionPath.componentPath !== ROOT ? null : from.parent !== void 0 ? from.parent.identity : from.caller.identity;
323
+ return {
324
+ world: this,
325
+ componentPath: functionPath.componentPath,
326
+ udfPath: functionPath.udfPath,
327
+ udfType,
328
+ attempt,
329
+ identity,
330
+ request: from.request,
331
+ pagination,
332
+ turn: new Turn()
333
+ };
334
+ }
335
+ runQuery(functionPath, resolved, args, from, snapshotOnly = false) {
336
+ const parentAttempt = from.parent?.attempt;
337
+ const isNested = parentAttempt !== void 0;
338
+ const attempt = parentAttempt === void 0 ? new KernelAttempt(this.state) : snapshotOnly ? new KernelAttempt(parentAttempt.snapshot) : parentAttempt;
339
+ const execution = this.execution(functionPath, "query", attempt, from, isNested && from.parent?.pagination || { calls: 0 });
340
+ const q = queryGeneric({ handler: (ctx, a) => resolved.handler({
341
+ ...ctx,
342
+ auth: queryAuth(execution)
343
+ }, a) });
344
+ return enter(execution, () => q.invokeQuery(JSON.stringify(convexToJson([parseArgs(args)])))).then((raw) => settled(execution, raw)).then((raw) => {
345
+ const result = jsonToConvex(JSON.parse(raw));
346
+ if (!isNested && hasPendingValues(result)) throw new Error(`Function ${functionPath.udfPath} return value invalid: queries cannot return an unresolved placeholder value.`);
347
+ validateReturnValue(resolved.returns, result, "query", functionPath);
348
+ return result;
349
+ }).catch((error) => {
350
+ throw deserializeConvexErrorData(error);
351
+ });
352
+ }
353
+ invokeMutation(execution, resolved, args) {
354
+ const m = mutationGeneric({ handler: (ctx, a) => resolved.handler({
355
+ ...ctx,
356
+ auth: mutationAuth(execution)
357
+ }, a) });
358
+ return enter(execution, () => m.invokeMutation(JSON.stringify(convexToJson([parseArgs(args)])))).then((raw) => settled(execution, raw)).then((raw) => {
359
+ const result = jsonToConvex(JSON.parse(raw));
360
+ validateReturnValue(resolved.returns, result, "mutation", {
361
+ componentPath: execution.componentPath,
362
+ udfPath: execution.udfPath
363
+ });
364
+ return result;
365
+ });
366
+ }
367
+ runMutation(functionPath, resolved, args, from) {
368
+ const parentAttempt = from.parent?.attempt;
369
+ if (parentAttempt !== void 0) {
370
+ const frame = parentAttempt.child();
371
+ const execution = this.execution(functionPath, "mutation", frame, from, void 0);
372
+ return this.invokeMutation(execution, resolved, args).then((result) => frame.drained().then(() => {
373
+ frame.close();
374
+ frame.merge();
375
+ return result;
376
+ }), (error) => {
377
+ frame.close();
378
+ throw deserializeConvexErrorData(error);
379
+ });
380
+ }
381
+ return this.prepareMutation(functionPath, resolved, args, from, 1, current$1()).then((held) => this.publish(held));
382
+ }
383
+ /**
384
+ * Run one attempt of a top-level mutation against the latest commit, then
385
+ * hold it. The commit point is once the function has returned and every
386
+ * syscall it started has settled. A test invocation bound when the mutation
387
+ * was first called reaches each attempt's handler with that attempt's
388
+ * number.
389
+ */
390
+ prepareMutation(functionPath, resolved, args, from, number, bound) {
391
+ const attempt = new KernelAttempt(this.state, number);
392
+ const execution = this.execution(functionPath, "mutation", attempt, from, void 0);
393
+ const run = () => this.invokeMutation(execution, resolved, args);
394
+ return (bound === void 0 ? run() : bind({
395
+ ...bound,
396
+ attempt: number
397
+ }, run)).then((value) => attempt.drained().then(() => ({
398
+ _tag: "returned",
399
+ value
400
+ })), (error) => ({
401
+ _tag: "failed",
402
+ error: deserializeConvexErrorData(error)
403
+ })).then((outcome) => {
404
+ attempt.close();
405
+ const held = {
406
+ view: {
407
+ id: `attempt-${this.nextAttemptId++}`,
408
+ request: from.request.requestId,
409
+ number,
410
+ snapshot: attempt.snapshot.version,
411
+ reads: attempt.reads,
412
+ outcome
413
+ },
414
+ attempt,
415
+ again: (next) => this.prepareMutation(functionPath, resolved, args, from, next, bound)
416
+ };
417
+ this.holding.set(held.view.id, held);
418
+ return held;
419
+ });
420
+ }
421
+ /**
422
+ * Validate a held attempt's reads against every commit since its snapshot,
423
+ * then publish its writes or prepare its next attempt. An attempt that wrote
424
+ * nothing publishes nothing and has nothing to validate. It answers its
425
+ * snapshot's version and commit timestamp.
426
+ */
427
+ applyHeld({ view, attempt, again }) {
428
+ this.holding.delete(view.id);
429
+ const { outcome } = view;
430
+ if (outcome._tag === "failed") return Promise.resolve({
431
+ kind: "refused",
432
+ tag: tagOf(outcome.error),
433
+ error: outcome.error
434
+ });
435
+ const writes = attempt.writes();
436
+ if (writes.length === 0) {
437
+ const { version, commitTs } = attempt.snapshot;
438
+ return Promise.resolve({
439
+ kind: "applied",
440
+ version,
441
+ commitTs,
442
+ result: resolveCommittedValues(outcome.value, commitTs)
443
+ });
444
+ }
445
+ if (conflict(this.state, view.snapshot, attempt.reads) !== void 0) {
446
+ if (view.number === lastAttempt) return Promise.resolve({
447
+ kind: "exhausted",
448
+ error: new OptimisticConcurrencyControlFailure({
449
+ attempts: lastAttempt,
450
+ message: `Documents read by the mutation changed before each of its ${lastAttempt} attempts could commit.`
451
+ })
452
+ });
453
+ return again(view.number + 1).then((next) => ({
454
+ kind: "conflict",
455
+ next: next.view
456
+ }));
457
+ }
458
+ const commitTs = this.runtime.commitTs(this.state.version + 1);
459
+ if (commitTs <= this.state.commitTs) return Promise.reject(new CommitTsNotIncreasing({
460
+ version: this.state.version + 1,
461
+ previous: this.state.commitTs,
462
+ commitTs,
463
+ message: `The runtime answered commit timestamp ${commitTs} for version ${this.state.version + 1}, which is not greater than the previous commit's ${this.state.commitTs}.`
464
+ }));
465
+ this.state = apply(this.state, writes, commitTs);
466
+ return Promise.resolve({
467
+ kind: "applied",
468
+ version: this.state.version,
469
+ commitTs,
470
+ result: resolveCommittedValues(outcome.value, commitTs)
471
+ });
472
+ }
473
+ /**
474
+ * Apply until the mutation publishes, is refused or is exhausted, as the
475
+ * binary retries a mutation that conflicts.
476
+ */
477
+ publish(held) {
478
+ return this.applyHeld(held).then((applied) => {
479
+ if (applied.kind === "applied") return applied.result;
480
+ if (applied.kind === "conflict") return this.publish(this.holding.get(applied.next.id));
481
+ throw applied.error;
482
+ });
483
+ }
484
+ runAction(functionPath, resolved, args, from) {
485
+ const execution = this.execution(functionPath, "action", void 0, from, void 0);
486
+ const inner = {
487
+ request: from.request,
488
+ parent: execution
489
+ };
490
+ const a = actionGeneric({ handler: (ctx, innerArgs) => resolved.handler({
491
+ ...ctx,
492
+ runQuery: (reference, queryArgs) => this.queryAt(pathOfReference(reference, functionPath.componentPath), queryArgs, inner),
493
+ runMutation: (reference, mutationArgs) => this.mutationAt(pathOfReference(reference, functionPath.componentPath), mutationArgs, inner),
494
+ runAction: (reference, actionArgs) => this.actionAt(pathOfReference(reference, functionPath.componentPath), actionArgs, inner),
495
+ auth: queryAuth(execution)
496
+ }, innerArgs) });
497
+ const run = () => enter(execution, () => a.invokeAction(from.request.requestId, JSON.stringify(convexToJson([parseArgs(args)]))));
498
+ const bound = from.parent === void 0 ? void 0 : current$1();
499
+ const { ip, userAgent, requestId, scheduledFunctionId } = from.request;
500
+ return (bound === void 0 ? run() : bind({
501
+ world: bound.world,
502
+ componentPath: functionPath.componentPath,
503
+ attempt: 1,
504
+ request: {
505
+ ip,
506
+ userAgent,
507
+ requestId,
508
+ scheduledFunctionId
509
+ },
510
+ services: bound.world.services,
511
+ startedAt: bound.world.clock(),
512
+ random: bound.world.random
513
+ }, run)).then((raw) => {
514
+ const result = jsonToConvex(JSON.parse(raw));
515
+ validateReturnValue(resolved.returns, result, "action", functionPath);
516
+ return result;
517
+ }).catch((error) => {
518
+ throw deserializeConvexErrorData(error);
519
+ });
520
+ }
521
+ schema(componentPath) {
522
+ return this.component(componentPath).schema;
523
+ }
524
+ view(execution) {
525
+ const attempt = transaction(execution);
526
+ return {
527
+ schema: this.schema(execution.componentPath),
528
+ scan: (tableName) => attempt.scan(execution.componentPath, tableName),
529
+ read: (interval, after) => attempt.readInterval({
530
+ ...interval,
531
+ componentPath: execution.componentPath,
532
+ after
533
+ })
534
+ };
535
+ }
536
+ generateId(table) {
537
+ return String(this.nextDocId++).padStart(TYPICAL_CONVEX_ID_LENGTH - table.length, "0") + table;
538
+ }
539
+ syscall(op, jsonArgs) {
540
+ const args = JSON.parse(jsonArgs);
541
+ const execution = current();
542
+ if (execution.attempt?.closed === true) throw closed(execution, op);
543
+ switch (op) {
544
+ case "1.0/getSnapshotTs": return JSON.stringify(convexToJson(transaction(execution).snapshot.commitTs));
545
+ case "1.0/queryStream": {
546
+ const queryId = this.nextQueryId++;
547
+ const view = this.view(execution);
548
+ let results;
549
+ this.queries.set(queryId, { next: () => (results ??= stream(view, args.query)).next() });
550
+ return JSON.stringify({ queryId });
551
+ }
552
+ case "1.0/queryCleanup":
553
+ this.queries.delete(args.queryId);
554
+ return JSON.stringify({});
555
+ case "1.0/db/normalizeId": {
556
+ const tableName = tableNameFromId(args.idString);
557
+ return JSON.stringify({ id: tableName === args.table ? args.idString : null });
558
+ }
559
+ default: throw new Error(`The test kernel does not support syscall: "${op}"`);
560
+ }
561
+ }
562
+ /**
563
+ * The binary queues a query's or mutation's async syscalls and runs them one
564
+ * at a time, oldest first (`start_async_syscall` and `run_inner` in
565
+ * `crates/isolate/src/environment/udf/mod.rs`, 1.49). A write and a nested
566
+ * call never share a batch (`AsyncSyscallBatch::can_push` in
567
+ * `async_syscall.rs`), and a nested call holds the queue until it has
568
+ * committed or rolled back its subtransaction (`run_udf` in
569
+ * `async_syscall.rs`). So a caller's write made after its nested call runs
570
+ * after that call, and a nested mutation sees every write made before it. An
571
+ * action's calls run side by side.
572
+ */
573
+ asyncSyscall(op, jsonArgs) {
574
+ const execution = current();
575
+ const attempt = execution.attempt;
576
+ if (attempt === void 0) return Promise.resolve().then(() => this.dispatchAsync(op, JSON.parse(jsonArgs), execution));
577
+ if (attempt.closed) return Promise.reject(closed(execution, op));
578
+ const end = attempt.begin();
579
+ return execution.turn.take(() => this.dispatchAsync(op, JSON.parse(jsonArgs), execution)).finally(end);
580
+ }
581
+ dispatchAsync(op, args, execution) {
582
+ switch (op) {
583
+ case "1.0/get": {
584
+ const { table, id } = args;
585
+ return JSON.stringify(convexToJson(this.get(execution, table, id)));
586
+ }
587
+ case "1.0/queryStreamNext": {
588
+ const results = this.queries.get(args.queryId);
589
+ if (results === void 0) throw new Error("Bad queryId");
590
+ const { value, done } = results.next();
591
+ return JSON.stringify(convexToJson(done ? {
592
+ value: null,
593
+ done: true
594
+ } : {
595
+ value,
596
+ done: false
597
+ }));
598
+ }
599
+ case "1.0/queryPage": {
600
+ const pagination = execution.pagination;
601
+ if (pagination) {
602
+ pagination.calls += 1;
603
+ if (pagination.calls > 1) throw new Error("Only a single paginated query (`.paginate()`) is allowed per query, including nested query calls and component calls. This is a Convex limit: https://docs.convex.dev/database/pagination");
604
+ }
605
+ return JSON.stringify(convexToJson(paginate(this.view(execution), args)));
606
+ }
607
+ case "1.0/insert": return JSON.stringify({ _id: this.insert(execution, args.table, jsonToConvex(args.value)) });
608
+ case "1.0/shallowMerge":
609
+ this.patch(execution, args.table, args.id, args.value);
610
+ return JSON.stringify({});
611
+ case "1.0/replace":
612
+ this.replace(execution, args.table, args.id, args.value);
613
+ return JSON.stringify({});
614
+ case "1.0/remove":
615
+ this.remove(execution, args.table, args.id);
616
+ return JSON.stringify({});
617
+ case "1.0/count": {
618
+ const attempt = transaction(execution);
619
+ attempt.readInterval({
620
+ kind: "interval",
621
+ componentPath: execution.componentPath,
622
+ table: args.table,
623
+ fields: ["_creationTime", "_id"],
624
+ order: "asc",
625
+ range: [],
626
+ after: null
627
+ })("end");
628
+ return JSON.stringify(attempt.scan(execution.componentPath, args.table).length);
629
+ }
630
+ case "1.0/getFunctionMetadata": return JSON.stringify(convexToJson({
631
+ name: execution.udfPath,
632
+ componentPath: execution.componentPath
633
+ }));
634
+ case "1.0/getRequestMetadata":
635
+ if (execution.udfType === "query") throw new Error("getRequestMetadata() can only be called from a mutation, action or HTTP action. It is not available in queries.");
636
+ return JSON.stringify(convexToJson(execution.request));
637
+ case "1.0/getDeploymentMetadata": return JSON.stringify(convexToJson({
638
+ name: "test",
639
+ region: null,
640
+ class: "s16"
641
+ }));
642
+ case "1.0/actions/query":
643
+ case "1.0/actions/mutation":
644
+ case "1.0/actions/action": {
645
+ const from = {
646
+ request: execution.request,
647
+ parent: execution
648
+ };
649
+ const functionPath = functionPathOf(args, execution.componentPath);
650
+ return (op === "1.0/actions/query" ? this.queryAt(functionPath, args.args, from) : op === "1.0/actions/mutation" ? this.mutationAt(functionPath, args.args, from) : this.actionAt(functionPath, args.args, from)).then((value) => JSON.stringify(convexToJson(value)));
651
+ }
652
+ case "1.0/runUdf": {
653
+ const { udfType, args: udfArgs } = args;
654
+ const from = {
655
+ request: execution.request,
656
+ parent: execution
657
+ };
658
+ const functionPath = functionPathOf(args, execution.componentPath);
659
+ const value = jsonToConvex(udfArgs);
660
+ return (udfType === "query" ? this.queryAt(functionPath, value, from) : udfType === "snapshotQuery" ? this.queryAt(functionPath, value, from, true) : udfType === "mutation" ? this.mutationAt(functionPath, value, from) : Promise.reject(/* @__PURE__ */ new Error(`The test kernel does not support udf type: "${udfType}"`))).then((result) => JSON.stringify(convexToJson(result)));
661
+ }
662
+ case "1.0/createFunctionHandle": {
663
+ const functionPath = functionPathOf(args, execution.componentPath);
664
+ this.component(functionPath.componentPath);
665
+ return JSON.stringify(createFunctionHandle(functionPath));
666
+ }
667
+ case "1.0/auditLog": return JSON.stringify(null);
668
+ case "1.0/schedule":
669
+ case "1.0/actions/schedule":
670
+ case "1.0/cancel_job":
671
+ case "1.0/actions/cancel_job": throw rowPending("the scheduler", 5);
672
+ case "1.0/storageDelete":
673
+ case "1.0/storageGetUrl":
674
+ case "1.0/storageGenerateUploadUrl": throw rowPending("storage", 6);
675
+ case "1.0/getTransactionMetrics": throw rowPending("transaction limits", 6);
676
+ case "1.0/actions/vectorSearch": throw requiresBinary("vectorSearch");
677
+ default: throw new Error(`The test kernel does not support async syscall: "${op}"`);
678
+ }
679
+ }
680
+ jsSyscall(op) {
681
+ return Promise.reject(op.startsWith("storage/") ? rowPending("storage", 6) : /* @__PURE__ */ new Error(`The test kernel does not support js syscall: "${op}"`));
682
+ }
683
+ get(execution, tableName, id) {
684
+ validateId(tableName, id);
685
+ const attempt = transaction(execution);
686
+ attempt.readDocument(execution.componentPath, id);
687
+ return attempt.get(execution.componentPath, id);
688
+ }
689
+ insert(execution, table, value) {
690
+ const attempt = transaction(execution);
691
+ validateDocument(this.schema(execution.componentPath), table, value);
692
+ const _id = this.generateId(table);
693
+ const now = this.runtime.now();
694
+ const _creationTime = now <= this.lastCreationTime ? this.lastCreationTime + .001 : now;
695
+ this.lastCreationTime = _creationTime;
696
+ attempt.write(execution.componentPath, _id, {
697
+ ...value,
698
+ _id,
699
+ _creationTime
700
+ });
701
+ return _id;
702
+ }
703
+ existing(execution, tableName, id, write, value) {
704
+ validateId(tableName, id);
705
+ if (value !== void 0 && typeof value !== "object") throw new Error(`Invalid argument \`value\` in \`db.${write}\`, expected object but got '${typeof value}': ${value}`);
706
+ const attempt = transaction(execution);
707
+ attempt.readDocument(execution.componentPath, id);
708
+ const document = attempt.get(execution.componentPath, id);
709
+ if (document === null) throw new Error(write === "delete" ? "Delete on non-existent doc" : `${write === "patch" ? "Patch" : "Replace"} on non-existent document with ID "${id}"`);
710
+ return document;
711
+ }
712
+ fields(document, value) {
713
+ if (value._id !== void 0 && value._id !== document._id) throw new Error(`Provided \`_id\` field value "${value._id}" does not match the document ID "${document._id}"`);
714
+ if (value._creationTime !== void 0 && value._creationTime !== document._creationTime) throw new Error(`Provided \`_creationTime\` field value ${value._creationTime} does not match the document's creation time ${document._creationTime}`);
715
+ const convexValue = {};
716
+ for (const [key, v] of Object.entries(value)) if (key !== "_id" && key !== "_creationTime") convexValue[key] = evaluateValue(v);
717
+ return convexValue;
718
+ }
719
+ patch(execution, tableName, id, value) {
720
+ const document = this.existing(execution, tableName, id, "patch", value);
721
+ const { _id, _creationTime, ...fields } = document;
722
+ const merged = {
723
+ ...fields,
724
+ ...this.fields(document, value)
725
+ };
726
+ validateDocument(this.schema(execution.componentPath), tableNameFromId(_id), merged);
727
+ transaction(execution).write(execution.componentPath, _id, {
728
+ _id,
729
+ _creationTime,
730
+ ...merged
731
+ });
732
+ }
733
+ replace(execution, tableName, id, value) {
734
+ const document = this.existing(execution, tableName, id, "replace", value);
735
+ const fields = this.fields(document, value);
736
+ validateDocument(this.schema(execution.componentPath), tableNameFromId(document._id), fields);
737
+ transaction(execution).write(execution.componentPath, document._id, {
738
+ ...fields,
739
+ _id: document._id,
740
+ _creationTime: document._creationTime
741
+ });
742
+ }
743
+ remove(execution, tableName, id) {
744
+ const document = this.existing(execution, tableName, id, "delete", void 0);
745
+ transaction(execution).write(execution.componentPath, document._id, null);
746
+ }
747
+ };
748
+ const closed = (execution, operation) => new ClosedAttempt({
749
+ operation,
750
+ message: `"${operation}" reached mutation ${execution.udfPath} after it returned and its syscalls settled. Await every read and write inside the handler.`
751
+ });
752
+ const transaction = (execution) => {
753
+ if (execution.attempt === void 0) throw new Error("The database is only available in queries and mutations. An action reads and writes through `ctx.runQuery` and `ctx.runMutation`.");
754
+ return execution.attempt;
755
+ };
756
+ const queryAuth = (execution) => ({ getUserIdentity: () => Promise.resolve(execution.identity) });
757
+ const mutationAuth = (execution) => ({
758
+ ...queryAuth(execution),
759
+ signJwt: () => Promise.reject(rowPending("JWT signing", 6))
760
+ });
761
+ function validateId(expectedTableName, id) {
762
+ if (typeof id !== "string") throw new Error(`Invalid argument \`id\`, expected string but got '${typeof id}': ${id}`);
763
+ if (expectedTableName === void 0) return;
764
+ if (typeof expectedTableName !== "string") throw new Error(`Invalid argument \`tableName\`, expected string but got '${typeof expectedTableName}': ${expectedTableName}`);
765
+ const actualTableName = tableNameFromId(id);
766
+ if (actualTableName === null) throw new Error(`Invalid argument \`id\`, expected ID value but got '${id}'`);
767
+ if (actualTableName !== expectedTableName) throw new Error(`Invalid argument \`id\`, expected ID in table '${expectedTableName}' but got ID in table '${actualTableName}'`);
768
+ }
769
+ /**
770
+ * Convex's server library reaches the backend through `globalThis.Convex`. The
771
+ * kernel answers each syscall for the function that made it.
772
+ */
773
+ const installConvexGlobal = () => {
774
+ const global = globalThis;
775
+ if (global.Convex?.[kernelBrand] === true) return;
776
+ global.Convex = {
777
+ [kernelBrand]: true,
778
+ syscall: (op, args) => current().world.syscall(op, args),
779
+ asyncSyscall: (op, args) => current().world.asyncSyscall(op, args),
780
+ jsSyscall: (op) => current().world.jsSyscall(op)
781
+ };
782
+ };
783
+ /**
784
+ * Whether `globalThis.Convex` is the kernel's, so no other backend answered.
785
+ */
786
+ const ownsConvexGlobal = () => globalThis.Convex?.[kernelBrand] === true;
787
+ //#endregion
788
+ export { World, anonymous, ownsConvexGlobal, withIdentity };
789
+
790
+ //# sourceMappingURL=Execution.js.map