@niscorp/vex 0.2.2 → 0.3.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 (36) hide show
  1. package/CHANGELOG.md +172 -0
  2. package/DESIGN.md +66 -3
  3. package/DOCS.md +156 -12
  4. package/dist/adapters/express/index.cjs +102 -17
  5. package/dist/adapters/express/index.cjs.map +1 -1
  6. package/dist/adapters/express/index.d.cts +2 -2
  7. package/dist/adapters/express/index.d.ts +2 -2
  8. package/dist/adapters/express/index.js +2 -2
  9. package/dist/adapters/hono/index.cjs +121 -22
  10. package/dist/adapters/hono/index.cjs.map +1 -1
  11. package/dist/adapters/hono/index.d.cts +2 -2
  12. package/dist/adapters/hono/index.d.ts +2 -2
  13. package/dist/adapters/hono/index.js +21 -7
  14. package/dist/adapters/hono/index.js.map +1 -1
  15. package/dist/agent/index.cjs +2 -0
  16. package/dist/agent/index.cjs.map +1 -1
  17. package/dist/agent/index.d.cts +1 -1
  18. package/dist/agent/index.d.ts +1 -1
  19. package/dist/agent/index.js +1 -1
  20. package/dist/{chunk-HF25Q53I.js → chunk-H4BHW76Q.js} +6 -3
  21. package/dist/chunk-H4BHW76Q.js.map +1 -0
  22. package/dist/{chunk-HCEH55PP.js → chunk-IQM4SQE2.js} +123 -21
  23. package/dist/chunk-IQM4SQE2.js.map +1 -0
  24. package/dist/{handler-Cql8SJ3F.d.cts → handler-BGCL6_Si.d.ts} +3 -2
  25. package/dist/{handler-mICf9ins.d.ts → handler-CMrjTXNx.d.cts} +3 -2
  26. package/dist/index.cjs +163 -35
  27. package/dist/index.cjs.map +1 -1
  28. package/dist/index.d.cts +3 -3
  29. package/dist/index.d.ts +3 -3
  30. package/dist/index.js +44 -22
  31. package/dist/index.js.map +1 -1
  32. package/dist/{types-BRvMB6IM.d.cts → types-Bi-Lg86b.d.cts} +48 -2
  33. package/dist/{types-BRvMB6IM.d.ts → types-Bi-Lg86b.d.ts} +48 -2
  34. package/package.json +5 -5
  35. package/dist/chunk-HCEH55PP.js.map +0 -1
  36. package/dist/chunk-HF25Q53I.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import { ak as ScopeValues, S as ScopePolicy, D as DatabaseSchema, f as Row, M as MutationDefinition, N as Mutation, b as Query, u as CoreMutation, a as QueryEngine, a0 as QueryResponse } from './types-BRvMB6IM.cjs';
1
+ import { al as ScopeValues, S as ScopePolicy, D as DatabaseSchema, f as Row, M as MutationDefinition, N as Mutation, b as Query, u as CoreMutation, a as QueryEngine, a0 as QueryResponse } from './types-Bi-Lg86b.js';
2
2
 
3
3
  type MutationTx = {
4
4
  query: (sql: string, params?: unknown[]) => Promise<{
@@ -8,6 +8,7 @@ type MutationTx = {
8
8
  type MutationClient = MutationTx & {
9
9
  transaction?: <T>(fn: (tx: MutationTx) => Promise<T>) => Promise<T>;
10
10
  };
11
+ declare const mutationMisfits: (def: MutationDefinition, schema: DatabaseSchema) => string[];
11
12
  type MutationContext = {
12
13
  context: Record<string, unknown>;
13
14
  scope: ScopeValues;
@@ -130,4 +131,4 @@ declare const handleFingerprintPatch: (config: VexHandlerConfig, fingerprint: st
130
131
  }) => Promise<QueryResult>;
131
132
  declare const handleFingerprintDelete: (config: VexHandlerConfig, fingerprint: string) => Promise<QueryResult>;
132
133
 
133
- export { type ContextField as C, type DiscoveryFingerprint as D, type ExecuteRecord as E, type MutationClient as M, type QueryResult as Q, type VexHandlerConfig as V, type WriteEvent as W, type ContextSignature as a, type DiscoveryResponse as b, type MutationContext as c, type MutationEffect as d, type MutationTx as e, type VexLive as f, type WriteResult as g, collectMutationContext as h, collectQueryContext as i, executeMutation as j, executeWrites as k, handleDiscovery as l, handleFingerprintDelete as m, handleFingerprintPatch as n, handleQuery as o, lintMutation as p, mutationEffect as q, requiredContextKeys as r, tablesChangedBy as t };
134
+ export { type ContextField as C, type DiscoveryFingerprint as D, type ExecuteRecord as E, type MutationClient as M, type QueryResult as Q, type VexHandlerConfig as V, type WriteEvent as W, type ContextSignature as a, type DiscoveryResponse as b, type MutationContext as c, type MutationEffect as d, type MutationTx as e, type VexLive as f, type WriteResult as g, collectMutationContext as h, collectQueryContext as i, executeMutation as j, executeWrites as k, handleDiscovery as l, handleFingerprintDelete as m, handleFingerprintPatch as n, handleQuery as o, lintMutation as p, mutationEffect as q, mutationMisfits as r, requiredContextKeys as s, tablesChangedBy as t };
@@ -1,4 +1,4 @@
1
- import { ak as ScopeValues, S as ScopePolicy, D as DatabaseSchema, f as Row, M as MutationDefinition, N as Mutation, b as Query, u as CoreMutation, a as QueryEngine, a0 as QueryResponse } from './types-BRvMB6IM.js';
1
+ import { al as ScopeValues, S as ScopePolicy, D as DatabaseSchema, f as Row, M as MutationDefinition, N as Mutation, b as Query, u as CoreMutation, a as QueryEngine, a0 as QueryResponse } from './types-Bi-Lg86b.cjs';
2
2
 
3
3
  type MutationTx = {
4
4
  query: (sql: string, params?: unknown[]) => Promise<{
@@ -8,6 +8,7 @@ type MutationTx = {
8
8
  type MutationClient = MutationTx & {
9
9
  transaction?: <T>(fn: (tx: MutationTx) => Promise<T>) => Promise<T>;
10
10
  };
11
+ declare const mutationMisfits: (def: MutationDefinition, schema: DatabaseSchema) => string[];
11
12
  type MutationContext = {
12
13
  context: Record<string, unknown>;
13
14
  scope: ScopeValues;
@@ -130,4 +131,4 @@ declare const handleFingerprintPatch: (config: VexHandlerConfig, fingerprint: st
130
131
  }) => Promise<QueryResult>;
131
132
  declare const handleFingerprintDelete: (config: VexHandlerConfig, fingerprint: string) => Promise<QueryResult>;
132
133
 
133
- export { type ContextField as C, type DiscoveryFingerprint as D, type ExecuteRecord as E, type MutationClient as M, type QueryResult as Q, type VexHandlerConfig as V, type WriteEvent as W, type ContextSignature as a, type DiscoveryResponse as b, type MutationContext as c, type MutationEffect as d, type MutationTx as e, type VexLive as f, type WriteResult as g, collectMutationContext as h, collectQueryContext as i, executeMutation as j, executeWrites as k, handleDiscovery as l, handleFingerprintDelete as m, handleFingerprintPatch as n, handleQuery as o, lintMutation as p, mutationEffect as q, requiredContextKeys as r, tablesChangedBy as t };
134
+ export { type ContextField as C, type DiscoveryFingerprint as D, type ExecuteRecord as E, type MutationClient as M, type QueryResult as Q, type VexHandlerConfig as V, type WriteEvent as W, type ContextSignature as a, type DiscoveryResponse as b, type MutationContext as c, type MutationEffect as d, type MutationTx as e, type VexLive as f, type WriteResult as g, collectMutationContext as h, collectQueryContext as i, executeMutation as j, executeWrites as k, handleDiscovery as l, handleFingerprintDelete as m, handleFingerprintPatch as n, handleQuery as o, lintMutation as p, mutationEffect as q, mutationMisfits as r, requiredContextKeys as s, tablesChangedBy as t };
package/dist/index.cjs CHANGED
@@ -174,6 +174,7 @@ var QuerySchema = zod.z.lazy(
174
174
  );
175
175
 
176
176
  // src/errors.ts
177
+ var VEX_ERROR = /* @__PURE__ */ Symbol.for("@niscorp/vex:VexError");
177
178
  var VexError = class extends Error {
178
179
  code;
179
180
  details;
@@ -184,6 +185,8 @@ var VexError = class extends Error {
184
185
  this.details = details;
185
186
  }
186
187
  };
188
+ Object.defineProperty(VexError.prototype, VEX_ERROR, { value: true });
189
+ var isVexError = (err) => err instanceof VexError || err instanceof Error && Reflect.get(err, VEX_ERROR) === true;
187
190
 
188
191
  // src/engine/optional.ts
189
192
  var gateKeys = (key) => Array.isArray(key) ? key : [key];
@@ -1768,6 +1771,7 @@ var createQueryEngine = (engineConfig) => {
1768
1771
  const maxNestingDepth = engineConfig.config?.maxNestingDepth ?? DEFAULT_MAX_NESTING_DEPTH;
1769
1772
  const defaultLimit = engineConfig.config?.defaultLimit ?? DEFAULT_LIMIT;
1770
1773
  const maxLimit = engineConfig.config?.maxLimit ?? DEFAULT_MAX_LIMIT;
1774
+ const capAuthored = engineConfig.config?.capAuthored ?? false;
1771
1775
  const rejectCartesianProducts = engineConfig.config?.rejectCartesianProducts ?? true;
1772
1776
  const warnUnindexedFilters = engineConfig.config?.warnUnindexedFilters ?? true;
1773
1777
  const rejectUnindexedFilters = engineConfig.config?.rejectUnindexedFilters ?? false;
@@ -1826,13 +1830,16 @@ var createQueryEngine = (engineConfig) => {
1826
1830
  }
1827
1831
  return cachedSchema;
1828
1832
  };
1829
- const runPipeline = (dsl, policyOverride) => {
1833
+ const runPipeline = (dsl, policyOverride, seeded = false) => {
1830
1834
  const schema = ensureSchema();
1831
1835
  let processedDsl = dsl;
1836
+ let engineLimit;
1832
1837
  if (processedDsl.limit === void 0) {
1833
1838
  processedDsl = { ...processedDsl, limit: defaultLimit };
1834
- } else if (processedDsl.limit > maxLimit) {
1839
+ engineLimit = defaultLimit;
1840
+ } else if (processedDsl.limit > maxLimit && (capAuthored || !seeded)) {
1835
1841
  processedDsl = { ...processedDsl, limit: maxLimit };
1842
+ engineLimit = maxLimit;
1836
1843
  }
1837
1844
  const entities = discoverEntities(processedDsl);
1838
1845
  const activePolicy = policyOverride ?? scopePolicy;
@@ -1848,7 +1855,18 @@ var createQueryEngine = (engineConfig) => {
1848
1855
  );
1849
1856
  }
1850
1857
  const compiled = adapter.compile(resolved);
1851
- return { compiled, warnings: analysis.warnings };
1858
+ return { compiled, warnings: analysis.warnings, ...engineLimit !== void 0 ? { engineLimit } : {} };
1859
+ };
1860
+ const cutSaid = /* @__PURE__ */ new Set();
1861
+ const cutNote = (engineLimit, stated, rowCount, shape, fingerprint) => {
1862
+ if (engineLimit === void 0 || rowCount !== engineLimit) return void 0;
1863
+ if (shape !== void 0 && !Array.isArray(shape)) return void 0;
1864
+ const note = stated === void 0 ? `This list states no limit, so it ran with the engine's defaultLimit of ${engineLimit}, and exactly ${engineLimit} rows came back \u2014 it may have been cut. State a \`limit\`.` : `This query asks for ${stated} rows, the engine's maxLimit is ${engineLimit}, and exactly ${engineLimit} came back \u2014 the list may have been cut. Raise \`maxLimit\` to read more.`;
1865
+ if (fingerprint !== void 0 && !cutSaid.has(fingerprint)) {
1866
+ cutSaid.add(fingerprint);
1867
+ console.warn(`[vex] "${fingerprint}": ${note}`);
1868
+ }
1869
+ return note;
1852
1870
  };
1853
1871
  const compile2 = (dsl) => runPipeline(pruneOptional(dsl, "all")).compiled;
1854
1872
  const test = async (dsl, scopeValues) => {
@@ -1896,6 +1914,7 @@ var createQueryEngine = (engineConfig) => {
1896
1914
  ...entry.intent !== void 0 ? { intent: entry.intent } : {},
1897
1915
  ...entry.shape !== void 0 ? { shape: entry.shape } : {},
1898
1916
  ...entry.refresh !== void 0 ? { refresh: entry.refresh } : {},
1917
+ seeded: entry.protected === true && entry.requestHash === void 0,
1899
1918
  hit: true,
1900
1919
  replaced: false
1901
1920
  };
@@ -1940,7 +1959,7 @@ var createQueryEngine = (engineConfig) => {
1940
1959
  try {
1941
1960
  return await generateDsl(validRequest, agentSchema, callerOf(policy, scope, agentSchema.entities.map((e) => e.name)));
1942
1961
  } catch (err) {
1943
- if (err instanceof VexError && err.code === "unsatisfiable") {
1962
+ if (isVexError(err) && err.code === "unsatisfiable") {
1944
1963
  const now = Date.now();
1945
1964
  await cache.set(negKey, {
1946
1965
  kind: "unsatisfiable",
@@ -1996,7 +2015,7 @@ var createQueryEngine = (engineConfig) => {
1996
2015
  }
1997
2016
  if (mappingMs !== void 0) emit({ type: "query.mapped", mappingMs });
1998
2017
  }
1999
- return { result, executionMs, mappingMs, mappedIr };
2018
+ return { result, rowCount: rows.length, executionMs, mappingMs, mappedIr };
2000
2019
  };
2001
2020
  const execute = async (request, options) => {
2002
2021
  if (strata.exceedsDepth(request)) throw new VexError("invalid_request", `Invalid request: ${strata.depthRefusal()}`);
@@ -2045,7 +2064,7 @@ var createQueryEngine = (engineConfig) => {
2045
2064
  }
2046
2065
  const presence = presenceOf(validRequest.context);
2047
2066
  const shaped = pruneOptional(applySortContext(dsl, validRequest.context), presence);
2048
- const { compiled, warnings } = runPipeline(shaped, activePolicy);
2067
+ const { compiled, warnings, engineLimit } = runPipeline(shaped, activePolicy, cached.seeded === true);
2049
2068
  noteVariant(cached.fingerprint, presenceSignature(dsl, presence), warnings);
2050
2069
  emit({ type: "query.sql", sql: compiled.sql, warnings });
2051
2070
  requireScope(compiled, scope);
@@ -2080,14 +2099,18 @@ var createQueryEngine = (engineConfig) => {
2080
2099
  const executionMs2 = Date.now() - execStart;
2081
2100
  emit({ type: "query.rows", count: rows.length, executionMs: executionMs2 });
2082
2101
  const result2 = shapeRows(rows);
2083
- const meta = {
2084
- cache: {
2085
- hit: cached.hit,
2086
- fingerprint: cached.fingerprint,
2087
- intent: cached.intent ?? validRequest.intent
2088
- },
2089
- context: buildContextContract(compiled, optionalKeysOf(dsl)),
2090
- warnings: warnings.length > 0 ? warnings : void 0
2102
+ const metaOf = (rowCount2) => {
2103
+ const cut2 = cutNote(engineLimit, shaped.limit, rowCount2, shape, validRequest.fingerprint);
2104
+ const said2 = cut2 === void 0 ? warnings : [...warnings, cut2];
2105
+ return {
2106
+ cache: {
2107
+ hit: cached.hit,
2108
+ fingerprint: cached.fingerprint,
2109
+ intent: cached.intent ?? validRequest.intent
2110
+ },
2111
+ context: buildContextContract(compiled, optionalKeysOf(dsl)),
2112
+ warnings: said2.length > 0 ? said2 : void 0
2113
+ };
2091
2114
  };
2092
2115
  const { signal, onChange } = options ?? {};
2093
2116
  if (signal !== void 0 && onChange !== void 0) {
@@ -2098,20 +2121,22 @@ var createQueryEngine = (engineConfig) => {
2098
2121
  const nextHash = canonicalHash(nextResult);
2099
2122
  if (nextHash === lastHash) return;
2100
2123
  lastHash = nextHash;
2101
- onChange({ result: nextResult, meta });
2124
+ onChange({ result: nextResult, meta: metaOf(next.length) });
2102
2125
  }
2103
2126
  }, signal);
2104
2127
  }
2105
2128
  emit({ type: "query.done", totalMs: Date.now() - t0 });
2106
- return { result: result2, meta: { ...meta, timing: { executionMs: executionMs2 } } };
2129
+ return { result: result2, meta: { ...metaOf(rows.length), timing: { executionMs: executionMs2 } } };
2107
2130
  }
2108
- const { result, executionMs, mappingMs, mappedIr } = await executeAndMap(
2131
+ const { result, rowCount, executionMs, mappingMs, mappedIr } = await executeAndMap(
2109
2132
  compiled,
2110
2133
  effectiveRequest,
2111
2134
  cached.cachedIr,
2112
2135
  context,
2113
2136
  scope
2114
2137
  );
2138
+ const cut = cutNote(engineLimit, shaped.limit, rowCount, effectiveRequest.shape, validRequest.fingerprint);
2139
+ const said = cut === void 0 ? warnings : [...warnings, cut];
2115
2140
  if (!cached.hit) {
2116
2141
  const now = Date.now();
2117
2142
  const entry = {
@@ -2143,7 +2168,7 @@ var createQueryEngine = (engineConfig) => {
2143
2168
  executionMs,
2144
2169
  ...mappingMs !== void 0 ? { mappingMs } : {}
2145
2170
  },
2146
- warnings: warnings.length > 0 ? warnings : void 0
2171
+ warnings: said.length > 0 ? said : void 0
2147
2172
  }
2148
2173
  };
2149
2174
  };
@@ -2951,13 +2976,21 @@ var LookupSchema = zod.z.object({
2951
2976
  where: FilterSchema.describe("Bounds the lookup \u2014 should match at most one row")
2952
2977
  }).strict()
2953
2978
  }).strict().describe("Scalar subquery: reads one value from another table at write time; read scope rules apply");
2979
+ var ReturnedSchema = zod.z.object({
2980
+ $returned: FieldPathSchema.describe(
2981
+ "`table.column`: `table` is written by exactly one earlier statement of this batch; `column` is a column of that table, including one the database generated."
2982
+ )
2983
+ }).strict().describe(
2984
+ "A column of the one row an earlier statement of this batch (an insert, update, upsert or delete) returned \u2014 how a later row gets an id the database generated. That statement must return exactly one row; none (its `where` matched no row, or scope kept the row back) or several fails the whole batch and nothing is written. Allowed only as the value of a column a statement sets; never inside a `where`, a `$lookup` or `items`, and never naming an `insertEach` or an `insert` whose `onConflict` has no `set`."
2985
+ );
2954
2986
  var ValueSchema = zod.z.union([
2955
2987
  zod.z.string(),
2956
2988
  zod.z.number(),
2957
2989
  zod.z.boolean(),
2958
2990
  zod.z.null(),
2959
2991
  zod.z.object({ $context: zod.z.string() }).strict(),
2960
- LookupSchema
2992
+ LookupSchema,
2993
+ ReturnedSchema
2961
2994
  ]);
2962
2995
  var Columns = zod.z.record(zod.z.string(), ValueSchema).refine((r) => Object.keys(r).length > 0, { message: "a write must set at least one column" });
2963
2996
  var OnConflictSchema = zod.z.object({
@@ -3350,17 +3383,23 @@ var walkFilter = (filter, schema, sig) => {
3350
3383
  };
3351
3384
  var isLookupRef = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && "$lookup" in v;
3352
3385
  var columnsOf = (m) => m.op === "insert" || m.op === "insertEach" ? { ...m.values, ...m.onConflict?.set ?? {} } : m.op === "update" ? m.set : m.op === "upsert" ? { ...m.columns, ...m.insert ?? {} } : {};
3386
+ var positionsSetBy = (m) => {
3387
+ const positions = (cols, insertOnly = false) => Object.entries(cols ?? {}).map(([column, value]) => ({ column, value, insertOnly }));
3388
+ if (m.op === "insert" || m.op === "insertEach") return [...positions(m.values), ...positions(m.onConflict?.set)];
3389
+ if (m.op === "update") return positions(m.set);
3390
+ if (m.op === "upsert") return [...positions(m.columns), ...positions(m.insert, true)];
3391
+ return [];
3392
+ };
3353
3393
  var collectMutationContext = (def, schema) => {
3354
3394
  const sig = {};
3355
3395
  const list = Array.isArray(def) ? def : [def];
3356
3396
  for (const m of list) {
3357
- for (const [col, v] of Object.entries(columnsOf(m))) {
3397
+ for (const { column: col, value: v, insertOnly } of positionsSetBy(m)) {
3358
3398
  if (isLookupRef(v)) {
3359
3399
  walkFilter(v.$lookup.where, schema, sig);
3360
3400
  continue;
3361
3401
  }
3362
3402
  if (!isContextRef(v)) continue;
3363
- const insertOnly = m.op === "upsert" && m.insert !== void 0 && col in m.insert;
3364
3403
  addField(sig, v.$context, { ...columnInfo(`${m.table}.${col}`, schema), ...insertOnly ? { note: "insert only" } : {} });
3365
3404
  }
3366
3405
  if (m.op === "update" || m.op === "delete") walkFilter(m.where, schema, sig);
@@ -3398,8 +3437,7 @@ var mutationEffect = (def) => {
3398
3437
  };
3399
3438
  var requiredContextKeys = (m) => {
3400
3439
  const keys = /* @__PURE__ */ new Set();
3401
- const cols = m.op === "insert" || m.op === "insertEach" ? { ...m.values, ...m.onConflict?.set ?? {} } : m.op === "update" ? m.set : {};
3402
- for (const v of Object.values(cols)) {
3440
+ for (const { value: v } of positionsSetBy(m)) {
3403
3441
  if (isContextRef(v)) keys.add(v.$context);
3404
3442
  else if (isLookupRef(v)) {
3405
3443
  const sub = {};
@@ -3421,9 +3459,40 @@ var findOptional = (value) => {
3421
3459
  if ("optional" in value) return true;
3422
3460
  return Object.values(value).some(findOptional);
3423
3461
  };
3462
+ var isReturnedRef = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && "$returned" in v && typeof v.$returned === "string";
3463
+ var returnedIn = (list, at) => {
3464
+ const refs = /* @__PURE__ */ new Map();
3465
+ const issues = [];
3466
+ const m = list[at];
3467
+ if (m === void 0) return { refs, issues };
3468
+ const judged = /* @__PURE__ */ new Set();
3469
+ for (const { value: v } of positionsSetBy(m)) {
3470
+ if (!isReturnedRef(v) || judged.has(v.$returned)) continue;
3471
+ judged.add(v.$returned);
3472
+ const dot = v.$returned.indexOf(".");
3473
+ const table = v.$returned.slice(0, dot);
3474
+ const column = v.$returned.slice(dot + 1);
3475
+ const reads = `${m.op} on "${m.table}" reads "${v.$returned}"`;
3476
+ const earlier = list.flatMap((s, i) => i < at && s.table === table ? [{ s, i }] : []);
3477
+ const source = earlier[0];
3478
+ if (source === void 0) {
3479
+ issues.push(`${reads}, and no earlier statement writes "${table}" \u2014 put the statement that writes it before this one, in the same batch`);
3480
+ } else if (earlier.length > 1) {
3481
+ issues.push(`${reads}, and ${earlier.length} earlier statements write "${table}" \u2014 a reference cannot tell them apart`);
3482
+ } else if (source.s.op === "insertEach") {
3483
+ issues.push(`${reads} from an insertEach, which writes a row per element \u2014 there is no one row to read`);
3484
+ } else if (source.s.op === "insert" && source.s.onConflict !== void 0 && source.s.onConflict.set === void 0) {
3485
+ issues.push(`${reads} from an insert that does nothing on conflict, which then returns no row \u2014 give its onConflict a \`set\``);
3486
+ } else {
3487
+ refs.set(v.$returned, { statement: source.i, table, column });
3488
+ }
3489
+ }
3490
+ return { refs, issues };
3491
+ };
3424
3492
  var lintMutation = (def) => {
3425
3493
  const issues = [];
3426
3494
  const list = Array.isArray(def) ? def : [def];
3495
+ list.forEach((_m, at) => issues.push(...returnedIn(list, at).issues));
3427
3496
  for (const m of list) {
3428
3497
  if (findOptional(m)) {
3429
3498
  issues.push(`${m.op} on "${m.table}" contains an optional condition \u2014 a write's bounds cannot depend on what the caller chose to send`);
@@ -3481,6 +3550,7 @@ var seedCache = async (cache, entries) => {
3481
3550
  // src/mutations/engine.ts
3482
3551
  var isLookup = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && "$lookup" in v;
3483
3552
  var isItemRef = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && "$item" in v;
3553
+ var isReturned = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && "$returned" in v;
3484
3554
  var collectLookups = (m) => {
3485
3555
  const out = [];
3486
3556
  const scan = (cols) => {
@@ -3578,6 +3648,13 @@ var assertWritableColumns = (m, schema) => {
3578
3648
  if (m.onConflict.where !== void 0) assertFilterColumns(m.onConflict.where, m.table, schema, "onConflict");
3579
3649
  }
3580
3650
  };
3651
+ var assertReturnedColumns = (refs, schema) => {
3652
+ for (const [ref, source] of refs) {
3653
+ if (findEntity2(source.table, schema)?.fields.some((f) => f.name === source.column) !== true) {
3654
+ throw new VexError("invalid_dsl", `Unknown column "${ref}" in $returned.`);
3655
+ }
3656
+ }
3657
+ };
3581
3658
  var readMatchesFor = (table, policy) => {
3582
3659
  const rule = policy.entities[table];
3583
3660
  if (rule === void 0) {
@@ -3686,7 +3763,8 @@ var newCtx = () => ({
3686
3763
  resolvedPaths: /* @__PURE__ */ new Map(),
3687
3764
  aliasMap: /* @__PURE__ */ new Map(),
3688
3765
  paramSlots: [],
3689
- paramCounter: { value: 0 }
3766
+ paramCounter: { value: 0 },
3767
+ returned: /* @__PURE__ */ new Map()
3690
3768
  });
3691
3769
  var indexFilterFields = (filter, aliasMap) => {
3692
3770
  for (const path of filterColumns(filter)) aliasMap.set(path, path);
@@ -3697,13 +3775,19 @@ var compileValue = (v, ctx) => {
3697
3775
  const where = compileFilter(v.$lookup.where, ctx);
3698
3776
  return `(SELECT ${v.$lookup.field} FROM ${v.$lookup.from} WHERE ${where})`;
3699
3777
  }
3778
+ if (isReturned(v)) {
3779
+ ctx.paramCounter.value += 1;
3780
+ ctx.returned.set(ctx.paramSlots.length, v.$returned);
3781
+ ctx.paramSlots.push({ key: v.$returned, kind: "context", type: "string" });
3782
+ return `$${ctx.paramCounter.value}`;
3783
+ }
3700
3784
  return compileFieldOrValue(v, ctx);
3701
3785
  };
3702
3786
  var compileColumnValue = (table, column, v, ctx, schema) => {
3703
3787
  const before = ctx.paramSlots.length;
3704
3788
  const sql = compileValue(v, ctx);
3705
3789
  const json = findEntity2(table, schema)?.fields.find((f) => f.name === column)?.normalizedType === "json";
3706
- if (json && typeof v === "object" && v !== null && "$context" in v) {
3790
+ if (json && typeof v === "object" && v !== null && ("$context" in v || "$returned" in v)) {
3707
3791
  const slot = ctx.paramSlots[before];
3708
3792
  if (slot !== void 0) ctx.paramSlots[before] = { ...slot, encode: "json" };
3709
3793
  }
@@ -3734,7 +3818,7 @@ var compileMutation = (m, schema) => {
3734
3818
  const entries = Object.entries(m.values);
3735
3819
  const cols = entries.map(([c]) => c);
3736
3820
  const vals = entries.map(([c, v]) => compileColumnValue(m.table, c, v, ctx, schema));
3737
- return { sql: `INSERT INTO ${m.table} (${cols.join(", ")}) VALUES (${vals.join(", ")})${compileConflict(m, ctx, schema)} RETURNING *`, slots: ctx.paramSlots };
3821
+ return { sql: `INSERT INTO ${m.table} (${cols.join(", ")}) VALUES (${vals.join(", ")})${compileConflict(m, ctx, schema)} RETURNING *`, slots: ctx.paramSlots, returned: ctx.returned };
3738
3822
  }
3739
3823
  if (m.op === "insertEach") {
3740
3824
  const entity = findEntity2(m.table, schema);
@@ -3748,25 +3832,26 @@ var compileMutation = (m, schema) => {
3748
3832
  const raw = `(item.value->>${quoteLiteral(v.$item)})`;
3749
3833
  return cast === void 0 ? raw : `${raw}::${cast}`;
3750
3834
  }
3751
- return compileValue(v, ctx);
3835
+ return isReturned(v) ? compileColumnValue(m.table, col, v, ctx, schema) : compileValue(v, ctx);
3752
3836
  });
3753
3837
  ctx.paramCounter.value += 1;
3754
3838
  ctx.paramSlots.push({ key: m.items.$context, kind: "context", type: "json" });
3755
3839
  const source = `jsonb_array_elements($${ctx.paramCounter.value}::jsonb) AS item`;
3756
3840
  return {
3757
3841
  sql: `INSERT INTO ${m.table} (${cols.join(", ")}) SELECT ${exprs.join(", ")} FROM ${source}${compileConflict(m, ctx, schema)} RETURNING *`,
3758
- slots: ctx.paramSlots
3842
+ slots: ctx.paramSlots,
3843
+ returned: ctx.returned
3759
3844
  };
3760
3845
  }
3761
3846
  if (m.op === "update") {
3762
3847
  const sets = Object.entries(m.set).map(([c, v]) => `${c} = ${compileColumnValue(m.table, c, v, ctx, schema)}`);
3763
3848
  indexFilterFields(m.where, ctx.aliasMap);
3764
3849
  const where2 = compileFilter(m.where, ctx);
3765
- return { sql: `UPDATE ${m.table} SET ${sets.join(", ")} WHERE ${where2} RETURNING *`, slots: ctx.paramSlots };
3850
+ return { sql: `UPDATE ${m.table} SET ${sets.join(", ")} WHERE ${where2} RETURNING *`, slots: ctx.paramSlots, returned: ctx.returned };
3766
3851
  }
3767
3852
  indexFilterFields(m.where, ctx.aliasMap);
3768
3853
  const where = compileFilter(m.where, ctx);
3769
- return { sql: `DELETE FROM ${m.table} WHERE ${where} RETURNING *`, slots: ctx.paramSlots };
3854
+ return { sql: `DELETE FROM ${m.table} WHERE ${where} RETURNING *`, slots: ctx.paramSlots, returned: ctx.returned };
3770
3855
  };
3771
3856
  var SUGAR = {
3772
3857
  upsert: (m, context) => {
@@ -3778,27 +3863,69 @@ var desugarMutation = (m, context) => {
3778
3863
  const rewrite = SUGAR[m.op];
3779
3864
  return rewrite === void 0 ? m : rewrite(m, context);
3780
3865
  };
3866
+ var mutationMisfits = (def, schema) => {
3867
+ const reasons = [];
3868
+ const list = Array.isArray(def) ? def : [def];
3869
+ for (const [at, entry] of list.entries()) {
3870
+ const asked = [
3871
+ // keyed, an upsert is an update; unkeyed, an insert
3872
+ ...(entry.op === "upsert" ? [{ [entry.key]: 0 }, {}] : [{}]).map((context) => () => assertWritableColumns(desugarMutation(entry, context), schema)),
3873
+ () => assertReturnedColumns(returnedIn(list, at).refs, schema)
3874
+ ];
3875
+ for (const ask of asked) {
3876
+ try {
3877
+ ask();
3878
+ } catch (error) {
3879
+ reasons.push(error instanceof Error ? error.message : String(error));
3880
+ }
3881
+ }
3882
+ }
3883
+ return reasons;
3884
+ };
3781
3885
  var executeWrites = async (client, def, mctx) => {
3782
3886
  const parsed = MutationDefinitionSchema.parse(def);
3783
3887
  const entries = Array.isArray(parsed) ? parsed : [parsed];
3784
- const compiled = entries.map((entry) => {
3785
- const core = desugarMutation(entry, mctx.context);
3888
+ const cores = entries.map((entry) => desugarMutation(entry, mctx.context));
3889
+ const compiled = cores.map((core, at) => {
3786
3890
  const missing = requiredContextKeys(core).filter((k) => mctx.context[k] === void 0);
3787
3891
  if (missing.length > 0) {
3788
3892
  throw new VexError("missing_context", `Mutation is missing context: ${missing.join(", ")}.`, {
3789
3893
  expected: collectMutationContext(parsed, mctx.schema)
3790
3894
  });
3791
3895
  }
3896
+ const returned = returnedIn(cores, at);
3897
+ if (returned.issues.length > 0) throw new VexError("invalid_dsl", `${returned.issues.join("; ")}.`);
3792
3898
  const m = scopeMutation(core, mctx.policy);
3793
3899
  assertWritableColumns(m, mctx.schema);
3900
+ assertReturnedColumns(returned.refs, mctx.schema);
3794
3901
  const statement = compileMutation(m, mctx.schema);
3795
3902
  requireScope({ paramSlots: statement.slots }, mctx.scope);
3796
- return { ...statement, table: m.table, op: m.op === "insertEach" ? "insert" : m.op };
3903
+ const reads = [...statement.returned].map(([slot, ref]) => {
3904
+ const source = returned.refs.get(ref);
3905
+ if (source === void 0) throw new VexError("invalid_dsl", `"${ref}" names no earlier statement of the batch.`);
3906
+ return { slot, ref, source };
3907
+ });
3908
+ return { ...statement, reads, table: m.table, op: m.op === "insertEach" ? "insert" : m.op };
3797
3909
  });
3798
3910
  const runAll = async (q) => {
3799
3911
  const results = [];
3800
3912
  for (const c of compiled) {
3801
3913
  const params = await resolveParams(c.slots, mctx.context, mctx.scope);
3914
+ for (const read of c.reads) {
3915
+ const rows = results[read.source.statement]?.rows ?? [];
3916
+ const row = rows[0];
3917
+ if (rows.length !== 1 || row === void 0) {
3918
+ throw new VexError(
3919
+ "execution_error",
3920
+ `"${read.ref}" needs exactly one row from statement ${read.source.statement + 1} of the batch, which wrote ${rows.length}. Nothing was written.`,
3921
+ { returned: read.ref, rows: rows.length }
3922
+ );
3923
+ }
3924
+ if (!(read.source.column in row)) {
3925
+ throw new VexError("execution_error", `"${read.ref}": the row statement ${read.source.statement + 1} returned has no "${read.source.column}" key. Nothing was written.`, { returned: read.ref });
3926
+ }
3927
+ params[read.slot] = row[read.source.column];
3928
+ }
3802
3929
  const bound = params.map((value, i) => {
3803
3930
  if (c.slots[i]?.encode === "json") return value !== null && typeof value === "object" ? JSON.stringify(value) : value;
3804
3931
  if (c.slots[i]?.type !== "json") return value;
@@ -4097,11 +4224,11 @@ var runQuery = async (config, body, scope, probe, live) => {
4097
4224
  }
4098
4225
  return { status: 200, body: response };
4099
4226
  } catch (err) {
4100
- if (err instanceof VexError && err.code === "missing_scope") {
4227
+ if (isVexError(err) && err.code === "missing_scope") {
4101
4228
  console.error("[vex] refused a statement the host did not scope:", err.message);
4102
4229
  return { status: 500, body: { error: "missing_scope", message: "The server did not supply the scope this request needs." } };
4103
4230
  }
4104
- if (err instanceof VexError) {
4231
+ if (isVexError(err)) {
4105
4232
  const status = err.code === "fingerprint_protected" ? 409 : err.code === "cache_miss" ? 404 : 400;
4106
4233
  return {
4107
4234
  status,
@@ -4193,6 +4320,7 @@ exports.lintMutation = lintMutation;
4193
4320
  exports.mergeScopePolicies = mergeScopePolicies;
4194
4321
  exports.mintFingerprint = mintFingerprint;
4195
4322
  exports.mutationEffect = mutationEffect;
4323
+ exports.mutationMisfits = mutationMisfits;
4196
4324
  exports.normalizeShape = normalizeShape;
4197
4325
  exports.optionalKeysOf = optionalKeysOf;
4198
4326
  exports.presenceOf = presenceOf;