@niscorp/vex 0.1.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 (45) hide show
  1. package/DESIGN.md +881 -0
  2. package/DOCS.md +1295 -0
  3. package/LICENSE +202 -0
  4. package/README.md +97 -0
  5. package/dist/adapters/express/index.cjs +1406 -0
  6. package/dist/adapters/express/index.cjs.map +1 -0
  7. package/dist/adapters/express/index.d.cts +25 -0
  8. package/dist/adapters/express/index.d.ts +25 -0
  9. package/dist/adapters/express/index.js +60 -0
  10. package/dist/adapters/express/index.js.map +1 -0
  11. package/dist/adapters/hono/index.cjs +1426 -0
  12. package/dist/adapters/hono/index.cjs.map +1 -0
  13. package/dist/adapters/hono/index.d.cts +25 -0
  14. package/dist/adapters/hono/index.d.ts +25 -0
  15. package/dist/adapters/hono/index.js +78 -0
  16. package/dist/adapters/hono/index.js.map +1 -0
  17. package/dist/adapters/pglite/index.cjs +17 -0
  18. package/dist/adapters/pglite/index.cjs.map +1 -0
  19. package/dist/adapters/pglite/index.d.cts +21 -0
  20. package/dist/adapters/pglite/index.d.ts +21 -0
  21. package/dist/adapters/pglite/index.js +14 -0
  22. package/dist/adapters/pglite/index.js.map +1 -0
  23. package/dist/agent/index.cjs +478 -0
  24. package/dist/agent/index.cjs.map +1 -0
  25. package/dist/agent/index.d.cts +29 -0
  26. package/dist/agent/index.d.ts +29 -0
  27. package/dist/agent/index.js +313 -0
  28. package/dist/agent/index.js.map +1 -0
  29. package/dist/chunk-FPKW4TRX.js +1528 -0
  30. package/dist/chunk-FPKW4TRX.js.map +1 -0
  31. package/dist/chunk-HF25Q53I.js +165 -0
  32. package/dist/chunk-HF25Q53I.js.map +1 -0
  33. package/dist/handler-Cql8SJ3F.d.cts +133 -0
  34. package/dist/handler-mICf9ins.d.ts +133 -0
  35. package/dist/index.cjs +4078 -0
  36. package/dist/index.cjs.map +1 -0
  37. package/dist/index.d.cts +199 -0
  38. package/dist/index.d.ts +199 -0
  39. package/dist/index.js +2340 -0
  40. package/dist/index.js.map +1 -0
  41. package/dist/introspect-D3OaXHBc.d.cts +16 -0
  42. package/dist/introspect-D3OaXHBc.d.ts +16 -0
  43. package/dist/types-BRvMB6IM.d.cts +1491 -0
  44. package/dist/types-BRvMB6IM.d.ts +1491 -0
  45. package/package.json +125 -0
@@ -0,0 +1,1528 @@
1
+ import { FilterSchema, VexError, QuerySchema, isFieldPathShape } from './chunk-HF25Q53I.js';
2
+ import { z } from 'zod';
3
+ import { createHash } from 'crypto';
4
+ import { exceedsDepth, depthRefusal } from '@niscorp/strata';
5
+
6
+ var RESERVED_CONTEXT_KEYS = /* @__PURE__ */ new Set(["sortBy", "sortDir"]);
7
+ var ContextSchema = z.object({
8
+ sortBy: z.string().optional(),
9
+ sortDir: z.enum(["asc", "desc"]).optional()
10
+ }).catchall(z.unknown()).describe(
11
+ 'Caller runtime values. Keys referenced from the DSL via { $context: "key" } are bound as SQL parameters. `sortBy` (an entity.field, schema-validated) and `sortDir` ("asc"|"desc") are reserved keys that drive ORDER BY directly and are never bound as parameters.'
12
+ );
13
+ var QueryRequestSchema = z.object({
14
+ // The ONE cache identity. Server-minted (`fp_…`) when absent — returned in
15
+ // meta.cache.fingerprint, an immutable pin. Caller-chosen strings are
16
+ // mutable named slots: the name is yours, its content follows your request.
17
+ // Alone → replay-or-error. With intent/shape → hit when the stored request
18
+ // matches, regenerate-and-replace when it differs (409 when protected).
19
+ fingerprint: z.string().min(1).optional(),
20
+ intent: z.string().optional(),
21
+ shape: z.unknown().optional(),
22
+ context: ContextSchema.default({})
23
+ });
24
+
25
+ // src/engine/optional.ts
26
+ var gateKeys = (key) => Array.isArray(key) ? key : [key];
27
+ var optionalKeysOf = (dsl) => {
28
+ const keys = [];
29
+ const walk = (filter) => {
30
+ if ("optional" in filter) {
31
+ for (const key of gateKeys(filter.optional.key)) {
32
+ if (!keys.includes(key)) keys.push(key);
33
+ }
34
+ walk(filter.optional.then);
35
+ return;
36
+ }
37
+ if ("and" in filter) {
38
+ for (const sub of filter.and) walk(sub);
39
+ return;
40
+ }
41
+ if ("or" in filter) {
42
+ for (const sub of filter.or) walk(sub);
43
+ return;
44
+ }
45
+ if ("not" in filter) {
46
+ walk(filter.not);
47
+ return;
48
+ }
49
+ };
50
+ if (dsl.filter !== void 0) walk(dsl.filter);
51
+ for (const source of dsl.from) {
52
+ if (typeof source !== "string") keys.push(...optionalKeysOf(source.query).filter((k) => !keys.includes(k)));
53
+ }
54
+ return keys;
55
+ };
56
+ var presenceOf = (context) => {
57
+ const present = /* @__PURE__ */ new Set();
58
+ for (const [key, value] of Object.entries(context)) {
59
+ if (value !== void 0 && value !== null) present.add(key);
60
+ }
61
+ return present;
62
+ };
63
+ var presenceSignature = (dsl, present) => {
64
+ const keys = optionalKeysOf(dsl);
65
+ if (keys.length === 0) return "";
66
+ if (present === "all") return keys.join(",");
67
+ return keys.filter((k) => present.has(k)).join(",");
68
+ };
69
+ var prune = (filter, present, insideExists) => {
70
+ if ("optional" in filter) {
71
+ const keys = gateKeys(filter.optional.key);
72
+ if (insideExists) {
73
+ throw new VexError("invalid_dsl", `An optional condition ("${keys.join(", ")}") cannot live inside an exists \u2014 its correlation must hold on every run.`);
74
+ }
75
+ if (present !== "all" && !keys.every((key) => present.has(key))) return void 0;
76
+ return prune(filter.optional.then, present, insideExists);
77
+ }
78
+ if ("exists" in filter) {
79
+ const inner = filter.exists.filter === void 0 ? void 0 : prune(filter.exists.filter, present, true);
80
+ return inner === void 0 ? { exists: { from: filter.exists.from } } : { exists: { from: filter.exists.from, filter: inner } };
81
+ }
82
+ if ("and" in filter || "or" in filter) {
83
+ const isAnd = "and" in filter;
84
+ const kept = (isAnd ? filter.and : filter.or).map((sub) => prune(sub, present, insideExists)).filter((sub) => sub !== void 0);
85
+ if (kept.length === 0) return void 0;
86
+ if (kept.length === 1) return kept[0];
87
+ return isAnd ? { and: kept } : { or: kept };
88
+ }
89
+ if ("not" in filter) {
90
+ const inner = prune(filter.not, present, insideExists);
91
+ if (inner === void 0) {
92
+ throw new VexError("invalid_dsl", "An optional condition cannot be the whole body of a `not` \u2014 wrap the `not` in the optional instead.");
93
+ }
94
+ return { not: inner };
95
+ }
96
+ return filter;
97
+ };
98
+ var pruneOptional = (dsl, present) => {
99
+ const from = dsl.from.map(
100
+ (source) => typeof source === "string" ? source : { as: source.as, query: pruneOptional(source.query, present) }
101
+ );
102
+ if (dsl.filter === void 0) return { ...dsl, from };
103
+ const filter = prune(dsl.filter, present, false);
104
+ if (filter === void 0) {
105
+ const { filter: _dropped, ...rest } = dsl;
106
+ return { ...rest, from };
107
+ }
108
+ return { ...dsl, from, filter };
109
+ };
110
+ var refuseOptional = (where) => {
111
+ throw new VexError(
112
+ "invalid_dsl",
113
+ `An optional condition reached ${where}. It should have been resolved by pruneOptional before the pipeline ran \u2014 reaching this point means a query was compiled without knowing which context keys the caller supplied.`
114
+ );
115
+ };
116
+
117
+ // src/scope/scope.types.ts
118
+ var isSetMatch = (m) => "in" in m;
119
+
120
+ // src/scope/apply.ts
121
+ var VexScopeError = class extends VexError {
122
+ entity;
123
+ constructor(entity, message) {
124
+ super("scope_denied", message);
125
+ this.name = "VexScopeError";
126
+ this.entity = entity;
127
+ }
128
+ };
129
+ var matchesFor = (entity, rule, def) => {
130
+ if (rule === void 0) {
131
+ if (def === "deny") throw new VexScopeError(entity, `Entity "${entity}" is not allowed by scope policy (default: deny)`);
132
+ return [];
133
+ }
134
+ if ("public" in rule) return [];
135
+ if ("deny" in rule) throw new VexScopeError(entity, `Entity "${entity}" is denied by scope policy`);
136
+ if (rule.read === void 0) {
137
+ if (def === "deny") throw new VexScopeError(entity, `Reads of "${entity}" are not allowed by scope policy (default: deny)`);
138
+ return [];
139
+ }
140
+ return rule.read;
141
+ };
142
+ var canReadTable = (policy, table) => {
143
+ const rule = policy.entities[table];
144
+ if (rule === void 0) return policy.default === "allow";
145
+ if ("public" in rule) return true;
146
+ if ("deny" in rule) return false;
147
+ return rule.read !== void 0 || policy.default === "allow";
148
+ };
149
+ var checkScope = (entities, policy) => {
150
+ for (const entity of entities) matchesFor(entity, policy.entities[entity], policy.default);
151
+ };
152
+ var andMerge = (existing, additions) => {
153
+ if (additions.length === 0) return existing;
154
+ const all = existing === void 0 ? additions : [existing, ...additions];
155
+ if (all.length === 1) return all[0];
156
+ const paths = /* @__PURE__ */ new Map();
157
+ for (const part of all) for (const [key, value] of part.resolvedPaths) paths.set(key, value);
158
+ return { original: { and: all.map((f) => f.original) }, resolvedPaths: paths };
159
+ };
160
+ var predicateFor = (entityName, alias, match, fields) => {
161
+ const field = fields.find((f) => f.name === match.match);
162
+ if (field === void 0) throw new VexScopeError(entityName, `Scope rule for "${entityName}" names column "${match.match}", which the table does not have`);
163
+ const path = `${entityName}.${match.match}`;
164
+ const original = isSetMatch(match) ? { in: [path, { $scope: match.in }] } : { eq: [path, { $scope: match.to }] };
165
+ return { original, resolvedPaths: /* @__PURE__ */ new Map([[path, { alias, column: match.match, schema: field }]]) };
166
+ };
167
+ var placeInto = (level, policy) => {
168
+ const whereAdditions = [];
169
+ for (const source of level.sources) {
170
+ const entity = source.entity;
171
+ if (entity === void 0) continue;
172
+ const join = level.joins.find((j) => j.toAlias === source.alias);
173
+ for (const match of matchesFor(entity.name, policy.entities[entity.name], policy.default)) {
174
+ const predicate = predicateFor(entity.name, source.alias, match, entity.fields);
175
+ if (predicate === void 0) continue;
176
+ level.aliasMap.set(`${entity.name}.${match.match}`, `${source.alias}.${match.match}`);
177
+ if (join !== void 0 && join.kind === "left") join.on = [...join.on ?? [], predicate];
178
+ else whereAdditions.push(predicate);
179
+ }
180
+ }
181
+ const merged = andMerge(level.filter, whereAdditions);
182
+ if (merged !== void 0) level.filter = merged;
183
+ };
184
+ var scopeResolved = (resolved, policy) => {
185
+ for (const source of resolved.sources) {
186
+ if (source.subquery !== void 0) scopeResolved(source.subquery, policy);
187
+ }
188
+ for (const node of resolved.existsMap?.values() ?? []) {
189
+ placeInto(node, policy);
190
+ }
191
+ placeInto(resolved, policy);
192
+ return resolved;
193
+ };
194
+ var applyScope = (dsl, entities, policy) => {
195
+ checkScope(entities, policy);
196
+ return dsl;
197
+ };
198
+
199
+ // src/utils/context.ts
200
+ var defaultForType = (type) => {
201
+ if (type === "string") return "";
202
+ if (type === "number") return 0;
203
+ if (type === "boolean") return false;
204
+ if (type === "string[]") return [""];
205
+ if (type === "number[]") return [0];
206
+ if (type === "json") return [];
207
+ return "";
208
+ };
209
+ var buildValidationContext = (contract) => {
210
+ const ctx = {};
211
+ for (const key of Object.keys(contract)) {
212
+ const slot = contract[key];
213
+ if (slot === void 0) continue;
214
+ if (slot.kind === "semantic") continue;
215
+ ctx[key] = defaultForType(slot.type);
216
+ }
217
+ return ctx;
218
+ };
219
+ var resolveParams = async (slots, context, scope, embed) => {
220
+ const results = [];
221
+ for (const slot of slots) {
222
+ if (slot.kind === "context") {
223
+ results.push(context[slot.key]);
224
+ continue;
225
+ }
226
+ if (slot.kind === "scope") {
227
+ results.push(scope[slot.key]);
228
+ continue;
229
+ }
230
+ if (embed === void 0) {
231
+ throw new Error(`Semantic parameter "${slot.key}" requires an embed function`);
232
+ }
233
+ const text = context[slot.key];
234
+ if (typeof text !== "string") {
235
+ throw new Error(`Semantic parameter "${slot.key}" requires a string value in context`);
236
+ }
237
+ const vector = await embed(text, slot.dimensions);
238
+ results.push(`[${vector.join(",")}]`);
239
+ }
240
+ return results;
241
+ };
242
+
243
+ // src/engine/executor.ts
244
+ var executeQuery = async (compiled, context, scope, adapter, embed) => {
245
+ const boundParams = await resolveParams(
246
+ compiled.paramSlots,
247
+ context,
248
+ scope,
249
+ embed
250
+ );
251
+ return adapter.execute(compiled, boundParams);
252
+ };
253
+ var buildContextContract = (compiled, optionalKeys = []) => {
254
+ const contract = {};
255
+ for (const slot of compiled.paramSlots) {
256
+ contract[slot.key] = {
257
+ type: slot.type,
258
+ kind: slot.kind,
259
+ ...optionalKeys.includes(slot.key) ? { optional: true } : {}
260
+ };
261
+ }
262
+ for (const key of optionalKeys) {
263
+ if (contract[key] !== void 0) continue;
264
+ contract[key] = { kind: "context", optional: true, absent: true };
265
+ }
266
+ return contract;
267
+ };
268
+ var findMissingContext = (compiled, context) => {
269
+ const missing = [];
270
+ for (const slot of compiled.paramSlots) {
271
+ if ((slot.kind === "context" || slot.kind === "semantic") && context[slot.key] === void 0) {
272
+ missing.push(slot.key);
273
+ }
274
+ }
275
+ return missing;
276
+ };
277
+ var requireScope = (compiled, scope) => {
278
+ const missing = [...new Set(compiled.paramSlots.filter((slot) => slot.kind === "scope" && scope[slot.key] === void 0).map((slot) => slot.key))];
279
+ if (missing.length > 0) {
280
+ throw new VexError("missing_scope", `This statement is scoped by ${missing.join(", ")}, which the host did not supply.`, { keys: missing });
281
+ }
282
+ };
283
+ var isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
284
+ var normalizeShape = (shape) => {
285
+ if (shape === null) return "null";
286
+ if (shape === void 0) return "unknown";
287
+ if (Array.isArray(shape)) {
288
+ const first = shape[0];
289
+ return first !== void 0 ? [normalizeShape(first)] : [];
290
+ }
291
+ if (isRecord(shape)) {
292
+ const sortedKeys = Object.keys(shape).sort();
293
+ const normalized = {};
294
+ for (const key of sortedKeys) {
295
+ normalized[key] = normalizeShape(shape[key]);
296
+ }
297
+ return normalized;
298
+ }
299
+ if (typeof shape === "string") return "string";
300
+ if (typeof shape === "number") return "number";
301
+ if (typeof shape === "boolean") return "boolean";
302
+ return "unknown";
303
+ };
304
+ var mintFingerprint = () => `fp_${createHash("sha256").update(`${Date.now()}:${Math.random()}`).digest("hex").slice(0, 16)}`;
305
+ var computeRequestHash = (request) => {
306
+ const identity = {
307
+ intent: request.intent ?? null,
308
+ shape: normalizeShape(request.shape),
309
+ contextKeys: Object.keys(request.context ?? {}).sort()
310
+ };
311
+ return createHash("sha256").update(JSON.stringify(identity)).digest("hex");
312
+ };
313
+ var canonical = (value) => {
314
+ if (Array.isArray(value)) return value.map(canonical);
315
+ if (isRecord(value)) {
316
+ const out = {};
317
+ for (const key of Object.keys(value).sort()) out[key] = canonical(value[key]);
318
+ return out;
319
+ }
320
+ return value;
321
+ };
322
+ var computePolicyKey = (policy) => policy === void 0 ? "none" : createHash("sha256").update(JSON.stringify(canonical(policy))).digest("hex").slice(0, 16);
323
+ var computeSchemaFingerprint = (schema) => {
324
+ const byName = (a, b) => a.name.localeCompare(b.name);
325
+ const stable = {
326
+ entities: [...schema.entities].sort(byName).map((e) => ({
327
+ name: e.name,
328
+ table: e.table,
329
+ fields: [...e.fields].sort(byName).map((f) => ({
330
+ name: f.name,
331
+ type: f.type,
332
+ normalizedType: f.normalizedType,
333
+ nullable: f.nullable,
334
+ primaryKey: f.primaryKey,
335
+ ...f.vectorDimensions !== void 0 ? { vectorDimensions: f.vectorDimensions } : {}
336
+ })),
337
+ // Column order within a relation is the key's own order, so it is
338
+ // preserved; relations are sorted by target and columns. This shape
339
+ // changed when keys became composite, so every entry cached before
340
+ // revalidates once on the next boot — the drift eviction, by design.
341
+ relations: [...e.relations].sort((a, b) => `${a.entity}.${a.localFields.join(",")}`.localeCompare(`${b.entity}.${b.localFields.join(",")}`)).map((r) => ({ type: r.type, entity: r.entity, localFields: r.localFields, foreignFields: r.foreignFields })),
342
+ // Index field order is significant (composite indexes) and stable
343
+ // from introspection, so it is preserved; indexes are sorted by name.
344
+ indexes: [...e.indexes].sort(byName).map((i) => ({
345
+ name: i.name,
346
+ fields: i.fields,
347
+ unique: i.unique,
348
+ type: i.type
349
+ }))
350
+ }))
351
+ };
352
+ return createHash("sha256").update(JSON.stringify(stable)).digest("hex");
353
+ };
354
+
355
+ // src/cache/util.ts
356
+ var fireAndForget = (p, onError) => {
357
+ void p.catch((err) => {
358
+ if (onError) onError(err);
359
+ else console.error("[vex:cache]", err);
360
+ });
361
+ };
362
+ var TOUCH_EVERY_MS = 6e4;
363
+ var isTouchDue = (entry, now) => entry.lastUsedAt === void 0 || now - entry.lastUsedAt >= TOUCH_EVERY_MS;
364
+ var isEntryFresh = (entry, currentFingerprint) => {
365
+ const expired = entry.expiresAt !== void 0 && entry.expiresAt <= Date.now();
366
+ const stale = entry.schemaFingerprint !== void 0 && currentFingerprint !== void 0 && entry.schemaFingerprint !== currentFingerprint;
367
+ return !expired && !stale;
368
+ };
369
+ var sweepCache = async (cache, options) => {
370
+ const cutoff = Date.now() - options.maxIdleMs;
371
+ const rows = cache.entries !== void 0 ? await cache.entries() : await Promise.all((await cache.keys()).map(async (key) => ({ key, entry: await cache.get(key) })));
372
+ let evicted = 0;
373
+ for (const { key, entry } of rows) {
374
+ if (entry === void 0) continue;
375
+ if (entry.protected === true) continue;
376
+ const lastAlive = entry.lastUsedAt ?? entry.createdAt;
377
+ if (lastAlive < cutoff) {
378
+ await cache.delete(key);
379
+ evicted += 1;
380
+ }
381
+ }
382
+ return evicted;
383
+ };
384
+
385
+ // src/adapters/postgres/operators.ts
386
+ var assertNotReserved = (key) => {
387
+ if (RESERVED_CONTEXT_KEYS.has(key))
388
+ throw new VexError(
389
+ "invalid_dsl",
390
+ `"${key}" is a reserved sort key (applied to ORDER BY); it cannot be bound as a parameter.`
391
+ );
392
+ };
393
+ var quoteLiteral = (s) => {
394
+ const doubled = s.replace(/'/g, "''");
395
+ return s.includes("\\") ? `E'${doubled.replace(/\\/g, "\\\\")}'` : `'${doubled}'`;
396
+ };
397
+ var quoteIdent = (name) => `"${name.replace(/"/g, '""')}"`;
398
+ var numberLiteral = (n) => {
399
+ if (!Number.isFinite(n)) throw new VexError("invalid_dsl", `${String(n)} is not a number SQL can hold.`);
400
+ return String(n);
401
+ };
402
+ var columnOf = (path, ctx) => {
403
+ const mapped = ctx.aliasMap.get(path);
404
+ if (mapped !== void 0) return mapped;
405
+ const res = ctx.resolvedPaths.get(path);
406
+ if (res !== void 0) return `${res.alias}.${res.column}`;
407
+ throw new VexError("invalid_dsl", `"${path}" is not a column this query reads.`);
408
+ };
409
+ var isFieldPath = isFieldPathShape;
410
+ var inferParamType = (path, resolvedPaths) => {
411
+ const res = resolvedPaths.get(path);
412
+ if (res === void 0) return "string";
413
+ const nt = res.schema.normalizedType;
414
+ if (nt === "number") return "number";
415
+ if (nt === "boolean") return "boolean";
416
+ return "string";
417
+ };
418
+ var compileFieldOrValue = (fov, ctx) => {
419
+ if (fov === null) return "NULL";
420
+ if (typeof fov === "boolean") return fov ? "TRUE" : "FALSE";
421
+ if (typeof fov === "number") return numberLiteral(fov);
422
+ if (typeof fov === "string") {
423
+ return isFieldPath(fov) ? columnOf(fov, ctx) : quoteLiteral(fov);
424
+ }
425
+ if (typeof fov === "object" && fov !== null && "$context" in fov) {
426
+ const key = fov.$context;
427
+ assertNotReserved(key);
428
+ ctx.paramCounter.value += 1;
429
+ ctx.paramSlots.push({
430
+ key,
431
+ kind: "context",
432
+ type: inferParamType(key, ctx.resolvedPaths)
433
+ });
434
+ return `$${ctx.paramCounter.value}`;
435
+ }
436
+ if (typeof fov === "object" && fov !== null && "$scope" in fov) {
437
+ const key = fov.$scope;
438
+ ctx.paramCounter.value += 1;
439
+ ctx.paramSlots.push({
440
+ key,
441
+ kind: "scope",
442
+ type: inferParamType(key, ctx.resolvedPaths)
443
+ });
444
+ return `$${ctx.paramCounter.value}`;
445
+ }
446
+ return "NULL";
447
+ };
448
+ var compileJoinPairs = (join) => join.fromColumns.map((column, i) => {
449
+ const to = join.toColumns[i];
450
+ if (to === void 0) {
451
+ throw new VexError(
452
+ "invalid_dsl",
453
+ `The join from "${join.fromAlias}" to "${join.toAlias}" pairs "${column}" with no column.`
454
+ );
455
+ }
456
+ return `${join.fromAlias}.${column} = ${join.toAlias}.${to}`;
457
+ });
458
+ var compileComparisonFilter = (op, pair, ctx) => {
459
+ const left = compileFieldOrValue(pair[0], ctx);
460
+ const right = compileFieldOrValue(pair[1], ctx);
461
+ return `${left} ${op} ${right}`;
462
+ };
463
+ var compileFilter = (filter, ctx) => {
464
+ if ("exists" in filter) {
465
+ const resolved = ctx.existsMap?.get(filter.exists);
466
+ if (resolved === void 0) throw new VexError("invalid_dsl", `An "exists" filter was not resolved. It must appear in a query's own filter.`);
467
+ const inner = {
468
+ ...ctx,
469
+ resolvedPaths: resolved.filter?.resolvedPaths ?? ctx.resolvedPaths,
470
+ // The inner map LAYERS OVER the outer one, so an inner path resolves to
471
+ // the inner alias and an outer path — the correlation — still resolves.
472
+ aliasMap: new Map([...ctx.aliasMap, ...resolved.aliasMap])
473
+ };
474
+ const parts = ["SELECT 1"];
475
+ const first = resolved.sources[0];
476
+ if (first?.table !== void 0) parts.push(`FROM ${first.table} AS ${first.alias}`);
477
+ for (const join of resolved.joins) {
478
+ const source = resolved.sources.find((s) => s.alias === join.toAlias);
479
+ if (source?.table === void 0) continue;
480
+ const keyword = join.kind === "left" ? "LEFT JOIN" : "JOIN";
481
+ const conditions = [
482
+ ...compileJoinPairs(join),
483
+ ...(join.on ?? []).map((extra) => compileFilter(extra.original, inner))
484
+ ];
485
+ parts.push(`${keyword} ${source.table} AS ${join.toAlias} ON ${conditions.join(" AND ")}`);
486
+ }
487
+ if (resolved.filter !== void 0) parts.push(`WHERE ${compileFilter(resolved.filter.original, inner)}`);
488
+ return `EXISTS (${parts.join(" ")})`;
489
+ }
490
+ if ("eq" in filter) return compileComparisonFilter("=", filter.eq, ctx);
491
+ if ("neq" in filter) return compileComparisonFilter("<>", filter.neq, ctx);
492
+ if ("gt" in filter) return compileComparisonFilter(">", filter.gt, ctx);
493
+ if ("gte" in filter) return compileComparisonFilter(">=", filter.gte, ctx);
494
+ if ("lt" in filter) return compileComparisonFilter("<", filter.lt, ctx);
495
+ if ("lte" in filter) return compileComparisonFilter("<=", filter.lte, ctx);
496
+ if ("in" in filter) {
497
+ const col = columnOf(filter.in[0], ctx);
498
+ const target = filter.in[1];
499
+ if (Array.isArray(target)) {
500
+ const values = target.map((v) => compileFieldOrValue(v, ctx));
501
+ return `${col} IN (${values.join(", ")})`;
502
+ }
503
+ if ("$context" in target) {
504
+ assertNotReserved(target.$context);
505
+ ctx.paramCounter.value += 1;
506
+ ctx.paramSlots.push({ key: target.$context, kind: "context", type: "string[]" });
507
+ return `${col} = ANY($${ctx.paramCounter.value})`;
508
+ }
509
+ if ("$scope" in target) {
510
+ ctx.paramCounter.value += 1;
511
+ ctx.paramSlots.push({ key: target.$scope, kind: "scope", type: "string[]" });
512
+ return `${col} = ANY($${ctx.paramCounter.value})`;
513
+ }
514
+ return `${col} IN ()`;
515
+ }
516
+ if ("notIn" in filter) {
517
+ const col = columnOf(filter.notIn[0], ctx);
518
+ const target = filter.notIn[1];
519
+ if (Array.isArray(target)) {
520
+ const values = target.map((v) => compileFieldOrValue(v, ctx));
521
+ return `${col} NOT IN (${values.join(", ")})`;
522
+ }
523
+ if ("$context" in target) {
524
+ assertNotReserved(target.$context);
525
+ ctx.paramCounter.value += 1;
526
+ ctx.paramSlots.push({ key: target.$context, kind: "context", type: "string[]" });
527
+ return `${col} <> ALL($${ctx.paramCounter.value})`;
528
+ }
529
+ if ("$scope" in target) {
530
+ ctx.paramCounter.value += 1;
531
+ ctx.paramSlots.push({ key: target.$scope, kind: "scope", type: "string[]" });
532
+ return `${col} <> ALL($${ctx.paramCounter.value})`;
533
+ }
534
+ return `${col} NOT IN ()`;
535
+ }
536
+ if ("like" in filter) {
537
+ const col = columnOf(filter.like[0], ctx);
538
+ const pattern = compileFieldOrValue(filter.like[1], ctx);
539
+ return `${col} LIKE ${pattern}`;
540
+ }
541
+ if ("ilike" in filter) {
542
+ const col = columnOf(filter.ilike[0], ctx);
543
+ const pattern = compileFieldOrValue(filter.ilike[1], ctx);
544
+ return `${col} ILIKE ${pattern}`;
545
+ }
546
+ if ("isNull" in filter) {
547
+ return `${columnOf(filter.isNull, ctx)} IS NULL`;
548
+ }
549
+ if ("isNotNull" in filter) {
550
+ return `${columnOf(filter.isNotNull, ctx)} IS NOT NULL`;
551
+ }
552
+ if ("and" in filter) {
553
+ const parts = filter.and.map((sub) => compileFilter(sub, ctx));
554
+ return `(${parts.join(" AND ")})`;
555
+ }
556
+ if ("or" in filter) {
557
+ const parts = filter.or.map((sub) => compileFilter(sub, ctx));
558
+ return `(${parts.join(" OR ")})`;
559
+ }
560
+ if ("not" in filter) {
561
+ const inner = compileFilter(filter.not, ctx);
562
+ return `NOT (${inner})`;
563
+ }
564
+ if ("semantic" in filter) {
565
+ const fieldPath = filter.semantic.field;
566
+ const col = columnOf(fieldPath, ctx);
567
+ const queryRef = filter.semantic.query;
568
+ const key = "$context" in queryRef ? queryRef.$context : queryRef.$scope;
569
+ if ("$context" in queryRef) assertNotReserved(queryRef.$context);
570
+ const res = ctx.resolvedPaths.get(fieldPath);
571
+ const dimensions = res?.schema.vectorDimensions;
572
+ ctx.paramCounter.value += 1;
573
+ ctx.paramSlots.push({
574
+ key,
575
+ kind: "semantic",
576
+ type: "string",
577
+ dimensions
578
+ });
579
+ const paramRef = `$${ctx.paramCounter.value}`;
580
+ const minScore = numberLiteral(filter.semantic.minScore ?? 0);
581
+ return `1 - (${col} <=> ${paramRef}) >= ${minScore}`;
582
+ }
583
+ if ("fuzzy" in filter) {
584
+ const col = columnOf(filter.fuzzy.field, ctx);
585
+ const queryRef = filter.fuzzy.query;
586
+ const key = "$context" in queryRef ? queryRef.$context : queryRef.$scope;
587
+ const kind = "$context" in queryRef ? "context" : "scope";
588
+ if ("$context" in queryRef) assertNotReserved(queryRef.$context);
589
+ ctx.paramCounter.value += 1;
590
+ ctx.paramSlots.push({ key, kind, type: "string" });
591
+ const paramRef = `$${ctx.paramCounter.value}`;
592
+ const maxDistance = filter.fuzzy.maxDistance;
593
+ if (maxDistance !== void 0) {
594
+ return `levenshtein(${col}, ${paramRef}) <= ${numberLiteral(maxDistance)}`;
595
+ }
596
+ return `${col} % ${paramRef}`;
597
+ }
598
+ if ("optional" in filter) refuseOptional("SQL compilation");
599
+ return "TRUE";
600
+ };
601
+ var compileCompute = (expr, ctx) => {
602
+ if ("add" in expr) {
603
+ const a = compileFieldOrValue(expr.add[0], ctx);
604
+ const b = compileFieldOrValue(expr.add[1], ctx);
605
+ return `(${a} + ${b})`;
606
+ }
607
+ if ("subtract" in expr) {
608
+ const a = compileFieldOrValue(expr.subtract[0], ctx);
609
+ const b = compileFieldOrValue(expr.subtract[1], ctx);
610
+ return `(${a} - ${b})`;
611
+ }
612
+ if ("multiply" in expr) {
613
+ const a = compileFieldOrValue(expr.multiply[0], ctx);
614
+ const b = compileFieldOrValue(expr.multiply[1], ctx);
615
+ return `(${a} * ${b})`;
616
+ }
617
+ if ("divide" in expr) {
618
+ const a = compileFieldOrValue(expr.divide[0], ctx);
619
+ const b = compileFieldOrValue(expr.divide[1], ctx);
620
+ return `(${a} / ${b})`;
621
+ }
622
+ if ("concat" in expr) {
623
+ const parts = expr.concat.map((v) => compileFieldOrValue(v, ctx));
624
+ return `(${parts.join(" || ")})`;
625
+ }
626
+ if ("coalesce" in expr) {
627
+ const parts = expr.coalesce.map((v) => compileFieldOrValue(v, ctx));
628
+ return `COALESCE(${parts.join(", ")})`;
629
+ }
630
+ if ("case" in expr) {
631
+ const whenClauses = expr.case.when.map((w) => {
632
+ const cond = compileFilter(w.condition, ctx);
633
+ const val = compileFieldOrValue(w.then, ctx);
634
+ return `WHEN ${cond} THEN ${val}`;
635
+ });
636
+ const elseVal = compileFieldOrValue(expr.case.else, ctx);
637
+ return `CASE ${whenClauses.join(" ")} ELSE ${elseVal} END`;
638
+ }
639
+ return "NULL";
640
+ };
641
+ var aggArg = (arg, ctx) => typeof arg === "string" ? columnOf(arg, ctx) : compileCompute(arg, ctx);
642
+ var compileAggregate = (expr, ctx) => {
643
+ if ("count" in expr) {
644
+ if (expr.count === "*") return "COUNT(*)";
645
+ return `COUNT(${columnOf(expr.count, ctx)})`;
646
+ }
647
+ if ("countDistinct" in expr) return `COUNT(DISTINCT ${columnOf(expr.countDistinct, ctx)})`;
648
+ if ("sum" in expr) return `SUM(${aggArg(expr.sum, ctx)})`;
649
+ if ("avg" in expr) return `AVG(${aggArg(expr.avg, ctx)})`;
650
+ if ("min" in expr) return `MIN(${aggArg(expr.min, ctx)})`;
651
+ if ("max" in expr) return `MAX(${aggArg(expr.max, ctx)})`;
652
+ return "NULL";
653
+ };
654
+ var LookupSchema = z.object({
655
+ $lookup: z.object({
656
+ from: z.string().describe("Table the value is read from"),
657
+ field: z.string().describe("Column the subquery returns"),
658
+ where: FilterSchema.describe("Bounds the lookup \u2014 should match at most one row")
659
+ }).strict()
660
+ }).strict().describe("Scalar subquery: reads one value from another table at write time; read scope rules apply");
661
+ var ValueSchema = z.union([
662
+ z.string(),
663
+ z.number(),
664
+ z.boolean(),
665
+ z.null(),
666
+ z.object({ $context: z.string() }).strict(),
667
+ LookupSchema
668
+ ]);
669
+ var Columns = z.record(z.string(), ValueSchema).refine((r) => Object.keys(r).length > 0, { message: "a write must set at least one column" });
670
+ var OnConflictSchema = z.object({
671
+ target: z.array(z.string()).min(1).describe("Conflict columns \u2014 must match a unique index or the primary key"),
672
+ set: Columns.optional().describe("DO UPDATE SET when the row already exists; omitted \u2192 DO NOTHING (no row returned on conflict)")
673
+ }).strict();
674
+ var InsertSchema = z.object({ op: z.literal("insert"), table: z.string(), values: Columns, onConflict: OnConflictSchema.optional() }).strict();
675
+ var UpdateSchema = z.object({ op: z.literal("update"), table: z.string(), set: Columns, where: FilterSchema }).strict();
676
+ var DeleteSchema = z.object({ op: z.literal("delete"), table: z.string(), where: FilterSchema }).strict();
677
+ var ItemRefSchema = z.object({ $item: z.string() }).strict().describe("insertEach only: a key read from the current element of `items`");
678
+ var EachColumns = z.record(z.string(), z.union([ValueSchema, ItemRefSchema])).refine((r) => Object.keys(r).length > 0, { message: "a write must set at least one column" });
679
+ var InsertEachSchema = z.object({
680
+ op: z.literal("insertEach"),
681
+ table: z.string(),
682
+ items: z.object({ $context: z.string() }).strict().describe("Context key holding an array of objects \u2014 one inserted row per element"),
683
+ values: EachColumns,
684
+ onConflict: OnConflictSchema.optional()
685
+ }).strict();
686
+ var UpsertSchema = z.object({
687
+ op: z.literal("upsert"),
688
+ table: z.string(),
689
+ columns: Columns,
690
+ // set on BOTH branches (update SET, and part of the insert)
691
+ insert: Columns.optional(),
692
+ // extra columns set ONLY on insert — immutable-on-create (e.g. a FK)
693
+ key: z.string()
694
+ }).strict().describe('Sugar: insert-or-update by `key` (e.g. "id"). Desugars to update (SET columns WHERE key) when the key is present, else insert (columns + `insert`-only).');
695
+ var MutationSchema = z.discriminatedUnion("op", [InsertSchema, InsertEachSchema, UpdateSchema, DeleteSchema, UpsertSchema]);
696
+ var MutationDefinitionSchema = z.union([MutationSchema, MutationSchema.array().min(1)]);
697
+
698
+ // src/mutations/signature.ts
699
+ var isContextRef = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && typeof v["$context"] === "string";
700
+ var columnInfo = (path, schema) => {
701
+ const [table, field] = path.split(".");
702
+ const entity = schema?.entities.find((e) => e.table === table || e.name === table);
703
+ const f = entity?.fields.find((x) => x.name === field);
704
+ return { type: f?.normalizedType ?? "unknown", column: path };
705
+ };
706
+ var addField = (sig, key, field) => {
707
+ const existing = sig[key];
708
+ if (existing === void 0) {
709
+ sig[key] = field;
710
+ return;
711
+ }
712
+ if (existing.type === "unknown" && field.type !== "unknown") {
713
+ sig[key] = { ...field, ...existing.note !== void 0 ? { note: existing.note } : {} };
714
+ }
715
+ };
716
+ var deepScan = (value, sig) => {
717
+ if (isContextRef(value)) {
718
+ addField(sig, value.$context, { type: "unknown" });
719
+ return;
720
+ }
721
+ if (Array.isArray(value)) {
722
+ for (const v of value) deepScan(v, sig);
723
+ return;
724
+ }
725
+ if (value !== null && typeof value === "object") {
726
+ for (const v of Object.values(value)) deepScan(v, sig);
727
+ }
728
+ };
729
+ var COMPARISONS = ["eq", "neq", "gt", "gte", "lt", "lte"];
730
+ var walkFilter = (filter, schema, sig) => {
731
+ const f = filter;
732
+ for (const op of COMPARISONS) {
733
+ const pair = f[op];
734
+ if (Array.isArray(pair) && pair.length === 2) {
735
+ const [a, b] = pair;
736
+ if (typeof a === "string" && isContextRef(b)) addField(sig, b.$context, columnInfo(a, schema));
737
+ else if (typeof b === "string" && isContextRef(a)) addField(sig, a.$context, columnInfo(b, schema));
738
+ else deepScan(pair, sig);
739
+ return;
740
+ }
741
+ }
742
+ if ("in" in f || "notIn" in f) {
743
+ const [path, target] = f["in"] ?? f["notIn"];
744
+ if (isContextRef(target)) addField(sig, target.$context, { ...columnInfo(path, schema), type: `${columnInfo(path, schema).type}[]` });
745
+ else deepScan(target, sig);
746
+ return;
747
+ }
748
+ if ("like" in f || "ilike" in f) {
749
+ const [path, v] = f["like"] ?? f["ilike"];
750
+ if (isContextRef(v)) addField(sig, v.$context, { type: "string", column: path, note: "pattern" });
751
+ return;
752
+ }
753
+ if ("and" in f || "or" in f) {
754
+ for (const sub of f["and"] ?? f["or"]) walkFilter(sub, schema, sig);
755
+ return;
756
+ }
757
+ if ("not" in f) {
758
+ walkFilter(f["not"], schema, sig);
759
+ return;
760
+ }
761
+ deepScan(f, sig);
762
+ };
763
+ var isLookupRef = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && "$lookup" in v;
764
+ 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 ?? {} } : {};
765
+ var collectMutationContext = (def, schema) => {
766
+ const sig = {};
767
+ const list = Array.isArray(def) ? def : [def];
768
+ for (const m of list) {
769
+ for (const [col, v] of Object.entries(columnsOf(m))) {
770
+ if (isLookupRef(v)) {
771
+ walkFilter(v.$lookup.where, schema, sig);
772
+ continue;
773
+ }
774
+ if (!isContextRef(v)) continue;
775
+ const insertOnly = m.op === "upsert" && m.insert !== void 0 && col in m.insert;
776
+ addField(sig, v.$context, { ...columnInfo(`${m.table}.${col}`, schema), ...insertOnly ? { note: "insert only" } : {} });
777
+ }
778
+ if (m.op === "update" || m.op === "delete") walkFilter(m.where, schema, sig);
779
+ if (m.op === "insertEach") {
780
+ const itemKeys = Object.values(m.values).filter((v) => v !== null && typeof v === "object" && "$item" in v).map((v) => v.$item);
781
+ sig[m.items.$context] = { type: "json", note: `array of objects \u2014 one inserted row per element${itemKeys.length > 0 ? ` (keys: ${itemKeys.join(", ")})` : ""}` };
782
+ }
783
+ if (m.op === "upsert") {
784
+ sig[m.key] = { ...columnInfo(`${m.table}.${m.key}`, schema), note: "upsert key \u2014 present updates that row, absent/empty inserts" };
785
+ }
786
+ }
787
+ return sig;
788
+ };
789
+ var collectQueryContext = (dsl, schema) => {
790
+ const sig = {};
791
+ const walkQuery = (q) => {
792
+ for (const source of q.from) {
793
+ if (typeof source !== "string") walkQuery(source.query);
794
+ }
795
+ if (q.filter !== void 0) walkFilter(q.filter, schema, sig);
796
+ if (q.compute !== void 0) deepScan(q.compute, sig);
797
+ if (q.aggregate !== void 0) deepScan(q.aggregate, sig);
798
+ };
799
+ walkQuery(dsl);
800
+ return sig;
801
+ };
802
+ var mutationEffect = (def) => {
803
+ const list = Array.isArray(def) ? def : [def];
804
+ return list.flatMap((m) => {
805
+ const base = { op: m.op, table: m.table, columns: Object.keys(columnsOf(m)).sort() };
806
+ const conflictSet = (m.op === "insert" || m.op === "insertEach") && m.onConflict?.set !== void 0 ? m.onConflict.set : void 0;
807
+ if (conflictSet === void 0) return [base];
808
+ return [base, { op: "update", table: m.table, columns: Object.keys(conflictSet).sort() }];
809
+ });
810
+ };
811
+ var requiredContextKeys = (m) => {
812
+ const keys = /* @__PURE__ */ new Set();
813
+ const cols = m.op === "insert" || m.op === "insertEach" ? { ...m.values, ...m.onConflict?.set ?? {} } : m.op === "update" ? m.set : {};
814
+ for (const v of Object.values(cols)) {
815
+ if (isContextRef(v)) keys.add(v.$context);
816
+ else if (isLookupRef(v)) {
817
+ const sub = {};
818
+ deepScan(v.$lookup.where, sub);
819
+ for (const k of Object.keys(sub)) keys.add(k);
820
+ }
821
+ }
822
+ if (m.op === "insertEach") keys.add(m.items.$context);
823
+ if (m.op === "update" || m.op === "delete") {
824
+ const sub = {};
825
+ deepScan(m.where, sub);
826
+ for (const k of Object.keys(sub)) keys.add(k);
827
+ }
828
+ return [...keys].sort();
829
+ };
830
+ var findOptional = (value) => {
831
+ if (Array.isArray(value)) return value.some(findOptional);
832
+ if (value === null || typeof value !== "object") return false;
833
+ if ("optional" in value) return true;
834
+ return Object.values(value).some(findOptional);
835
+ };
836
+ var lintMutation = (def) => {
837
+ const issues = [];
838
+ const list = Array.isArray(def) ? def : [def];
839
+ for (const m of list) {
840
+ if (findOptional(m)) {
841
+ 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`);
842
+ }
843
+ if (m.op !== "update" && m.op !== "delete") continue;
844
+ const sub = {};
845
+ deepScan(m.where, sub);
846
+ if (Object.keys(sub).length === 0) {
847
+ issues.push(`${m.op} on "${m.table}" has no $context-keyed WHERE \u2014 the write is not caller-bounded`);
848
+ }
849
+ }
850
+ return issues;
851
+ };
852
+
853
+ // src/mutations/engine.ts
854
+ var isLookup = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && "$lookup" in v;
855
+ var isItemRef = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && "$item" in v;
856
+ var collectLookups = (m) => {
857
+ const out = [];
858
+ const scan = (cols) => {
859
+ for (const v of Object.values(cols ?? {})) if (isLookup(v)) out.push(v.$lookup);
860
+ };
861
+ if (m.op === "insert" || m.op === "insertEach") {
862
+ scan(m.values);
863
+ scan(m.onConflict?.set);
864
+ }
865
+ if (m.op === "update") scan(m.set);
866
+ return out;
867
+ };
868
+ var findEntity = (table, schema) => schema.entities.find((e) => e.table === table || e.name === table);
869
+ var assertConflictTarget = (table, target, entity) => {
870
+ const uniqueSets = [
871
+ entity.fields.filter((f) => f.primaryKey).map((f) => f.name),
872
+ ...entity.indexes.filter((i) => i.unique).map((i) => [...i.fields])
873
+ ].filter((s) => s.length > 0);
874
+ if (uniqueSets.length === 0) return;
875
+ const want = new Set(target);
876
+ const ok = uniqueSets.some((s) => s.length === want.size && s.every((c) => want.has(c)));
877
+ if (!ok) {
878
+ throw new VexError(
879
+ "invalid_dsl",
880
+ `onConflict target (${target.join(", ")}) does not match a unique constraint on "${table}". Unique column sets: ${uniqueSets.map((s) => `(${s.join(", ")})`).join(" ")}.`
881
+ );
882
+ }
883
+ };
884
+ var filterColumns = (filter) => {
885
+ const out = [];
886
+ const value = (v) => {
887
+ if (isFieldPathShape(v)) out.push(v);
888
+ };
889
+ const walk = (f) => {
890
+ if ("and" in f) return f.and.forEach(walk);
891
+ if ("or" in f) return f.or.forEach(walk);
892
+ if ("not" in f) return walk(f.not);
893
+ if ("eq" in f) return f.eq.forEach(value);
894
+ if ("neq" in f) return f.neq.forEach(value);
895
+ if ("gt" in f) return f.gt.forEach(value);
896
+ if ("gte" in f) return f.gte.forEach(value);
897
+ if ("lt" in f) return f.lt.forEach(value);
898
+ if ("lte" in f) return f.lte.forEach(value);
899
+ if ("in" in f || "notIn" in f) {
900
+ const [field, target] = "in" in f ? f.in : f.notIn;
901
+ out.push(field);
902
+ if (Array.isArray(target)) target.forEach(value);
903
+ return;
904
+ }
905
+ if ("like" in f || "ilike" in f) {
906
+ const [field, pattern] = "like" in f ? f.like : f.ilike;
907
+ out.push(field);
908
+ return value(pattern);
909
+ }
910
+ if ("isNull" in f) return void out.push(f.isNull);
911
+ if ("isNotNull" in f) return void out.push(f.isNotNull);
912
+ if ("semantic" in f) return void out.push(f.semantic.field);
913
+ if ("fuzzy" in f) return void out.push(f.fuzzy.field);
914
+ };
915
+ walk(filter);
916
+ return out;
917
+ };
918
+ var assertFilterColumns = (filter, table, schema, where) => {
919
+ const entity = findEntity(table, schema);
920
+ if (entity === void 0) throw new VexError("invalid_dsl", `Unknown table "${table}" in ${where}.`);
921
+ for (const path of filterColumns(filter)) {
922
+ const dot = path.indexOf(".");
923
+ const owner = path.slice(0, dot);
924
+ const column = path.slice(dot + 1);
925
+ if (!isFieldPathShape(path) || owner !== table || !entity.fields.some((f) => f.name === column)) {
926
+ throw new VexError("invalid_dsl", `"${path}" in ${where} is not a column of "${table}".`);
927
+ }
928
+ }
929
+ };
930
+ var assertWritableColumns = (m, schema) => {
931
+ const entity = findEntity(m.table, schema);
932
+ if (entity === void 0) throw new VexError("invalid_dsl", `Unknown table "${m.table}".`);
933
+ if (m.op === "update" || m.op === "delete") assertFilterColumns(m.where, m.table, schema, "the WHERE");
934
+ const known = new Set(entity.fields.map((f) => f.name));
935
+ const cols = m.op === "insert" || m.op === "insertEach" ? Object.keys(m.values) : m.op === "update" ? Object.keys(m.set) : [];
936
+ for (const c of cols) {
937
+ if (!known.has(c)) throw new VexError("invalid_dsl", `Unknown column "${m.table}.${c}".`);
938
+ }
939
+ for (const l of collectLookups(m)) {
940
+ const le = findEntity(l.from, schema);
941
+ if (le === void 0) throw new VexError("invalid_dsl", `Unknown table "${l.from}" in $lookup.`);
942
+ if (!le.fields.some((f) => f.name === l.field)) throw new VexError("invalid_dsl", `Unknown column "${l.from}.${l.field}" in $lookup.`);
943
+ assertFilterColumns(l.where, l.from, schema, "a $lookup");
944
+ }
945
+ if ((m.op === "insert" || m.op === "insertEach") && m.onConflict !== void 0) {
946
+ for (const c of [...m.onConflict.target, ...Object.keys(m.onConflict.set ?? {})]) {
947
+ if (!known.has(c)) throw new VexError("invalid_dsl", `Unknown column "${m.table}.${c}" in onConflict.`);
948
+ }
949
+ assertConflictTarget(m.table, m.onConflict.target, entity);
950
+ if (m.onConflict.where !== void 0) assertFilterColumns(m.onConflict.where, m.table, schema, "onConflict");
951
+ }
952
+ };
953
+ var readMatchesFor = (table, policy) => {
954
+ const rule = policy.entities[table];
955
+ if (rule === void 0) {
956
+ if (policy.default === "deny") throw new VexScopeError(table, `A $lookup reads "${table}", which is not allowed by scope policy (default: deny).`);
957
+ return [];
958
+ }
959
+ if ("public" in rule) return [];
960
+ if ("deny" in rule) throw new VexScopeError(table, `A $lookup reads "${table}", which is denied by scope policy.`);
961
+ if (rule.read === void 0) {
962
+ if (policy.default === "deny") throw new VexScopeError(table, `A $lookup reads "${table}", which this principal has no read grant for.`);
963
+ return [];
964
+ }
965
+ return rule.read;
966
+ };
967
+ var boundaryOf = (table, r) => isSetMatch(r) ? { in: [`${table}.${r.match}`, { $scope: r.in }] } : { eq: [`${table}.${r.match}`, { $scope: r.to }] };
968
+ var scopeLookups = (cols, policy) => {
969
+ const out = {};
970
+ for (const [k, v] of Object.entries(cols)) {
971
+ if (!isLookup(v)) {
972
+ out[k] = v;
973
+ continue;
974
+ }
975
+ let where = v.$lookup.where;
976
+ for (const r of readMatchesFor(v.$lookup.from, policy)) {
977
+ where = { and: [where, boundaryOf(v.$lookup.from, r)] };
978
+ }
979
+ out[k] = { $lookup: { ...v.$lookup, where } };
980
+ }
981
+ return out;
982
+ };
983
+ var writeGate = (table, op, policy) => {
984
+ const rule = policy.entities[table];
985
+ if (rule === void 0) {
986
+ if (policy.default === "deny") throw new VexScopeError(table, `Writes to "${table}" are not allowed by scope policy (default: deny).`);
987
+ return void 0;
988
+ }
989
+ if ("public" in rule) return void 0;
990
+ if ("deny" in rule) throw new VexScopeError(table, `Writes to "${table}" are denied by scope policy.`);
991
+ const specific = op === "insert" ? rule.insert : op === "update" ? rule.update : rule.delete;
992
+ if (rule.write === void 0 && specific === void 0) {
993
+ if (policy.default === "deny") throw new VexScopeError(table, `"${op}" on "${table}" is not allowed by scope policy (default: deny).`);
994
+ return void 0;
995
+ }
996
+ return { rule, rules: [...rule.write ?? [], ...specific ?? []] };
997
+ };
998
+ var scopeInsertParts = (table, rawValues, rawConflict, policy) => {
999
+ let values = scopeLookups(rawValues, policy);
1000
+ let conflict = rawConflict === void 0 || rawConflict.set === void 0 ? rawConflict : { ...rawConflict, set: scopeLookups(rawConflict.set, policy) };
1001
+ const gate = writeGate(table, "insert", policy);
1002
+ if (gate === void 0) return { values, conflict };
1003
+ for (const r of gate.rules) {
1004
+ if ("match" in r && isSetMatch(r)) {
1005
+ throw new VexScopeError(
1006
+ table,
1007
+ `Scope rule for "${table}" is set-valued ("${r.match}" in "${r.in}") and cannot pin an INSERT \u2014 a write's subject must be a single value. Use a scalar match, or carry the subject in a $lookup whose own read rules bound it.`
1008
+ );
1009
+ }
1010
+ values = { ...values, ["set" in r ? r.set : r.match]: { $scope: r.to } };
1011
+ }
1012
+ if (conflict?.set !== void 0) {
1013
+ if (gate.rule.write === void 0 && gate.rule.update === void 0) {
1014
+ throw new VexScopeError(table, `onConflict on "${table}" declares DO UPDATE, but this principal has no update grant.`);
1015
+ }
1016
+ for (const r of [...gate.rule.write ?? [], ...gate.rule.update ?? []]) {
1017
+ if ("set" in r) {
1018
+ conflict = { ...conflict, set: { ...conflict.set ?? {}, [r.set]: { $scope: r.to } } };
1019
+ } else if (!conflict.target.includes(r.match)) {
1020
+ const boundary = boundaryOf(table, r);
1021
+ conflict = { ...conflict, where: conflict.where === void 0 ? boundary : { and: [conflict.where, boundary] } };
1022
+ }
1023
+ }
1024
+ }
1025
+ return { values, conflict };
1026
+ };
1027
+ var scopeMutation = (m, policy) => {
1028
+ if (m.op === "insert") {
1029
+ const { values, conflict } = scopeInsertParts(m.table, m.values, m.onConflict, policy);
1030
+ return { op: "insert", table: m.table, values, ...conflict === void 0 ? {} : { onConflict: conflict } };
1031
+ }
1032
+ if (m.op === "insertEach") {
1033
+ const { values, conflict } = scopeInsertParts(m.table, m.values, m.onConflict, policy);
1034
+ return { op: "insertEach", table: m.table, items: m.items, values, ...conflict === void 0 ? {} : { onConflict: conflict } };
1035
+ }
1036
+ if (m.op === "update") {
1037
+ let set = scopeLookups(m.set, policy);
1038
+ let where2 = m.where;
1039
+ const gate2 = writeGate(m.table, "update", policy);
1040
+ if (gate2 !== void 0) {
1041
+ for (const r of gate2.rules) {
1042
+ if ("set" in r) set = { ...set, [r.set]: { $scope: r.to } };
1043
+ else where2 = { and: [where2, boundaryOf(m.table, r)] };
1044
+ }
1045
+ }
1046
+ return { op: "update", table: m.table, set, where: where2 };
1047
+ }
1048
+ let where = m.where;
1049
+ const gate = writeGate(m.table, "delete", policy);
1050
+ if (gate !== void 0) {
1051
+ for (const r of gate.rules) {
1052
+ if ("match" in r) where = { and: [where, boundaryOf(m.table, r)] };
1053
+ }
1054
+ }
1055
+ return { op: "delete", table: m.table, where };
1056
+ };
1057
+ var newCtx = () => ({
1058
+ resolvedPaths: /* @__PURE__ */ new Map(),
1059
+ aliasMap: /* @__PURE__ */ new Map(),
1060
+ paramSlots: [],
1061
+ paramCounter: { value: 0 }
1062
+ });
1063
+ var indexFilterFields = (filter, aliasMap) => {
1064
+ for (const path of filterColumns(filter)) aliasMap.set(path, path);
1065
+ };
1066
+ var compileValue = (v, ctx) => {
1067
+ if (isLookup(v)) {
1068
+ indexFilterFields(v.$lookup.where, ctx.aliasMap);
1069
+ const where = compileFilter(v.$lookup.where, ctx);
1070
+ return `(SELECT ${v.$lookup.field} FROM ${v.$lookup.from} WHERE ${where})`;
1071
+ }
1072
+ return compileFieldOrValue(v, ctx);
1073
+ };
1074
+ var compileColumnValue = (table, column, v, ctx, schema) => {
1075
+ const before = ctx.paramSlots.length;
1076
+ const sql = compileValue(v, ctx);
1077
+ const json = findEntity(table, schema)?.fields.find((f) => f.name === column)?.normalizedType === "json";
1078
+ if (json && typeof v === "object" && v !== null && "$context" in v) {
1079
+ const slot = ctx.paramSlots[before];
1080
+ if (slot !== void 0) ctx.paramSlots[before] = { ...slot, encode: "json" };
1081
+ }
1082
+ return sql;
1083
+ };
1084
+ var compileConflict = (m, ctx, schema) => {
1085
+ const c = m.onConflict;
1086
+ if (c === void 0) return "";
1087
+ if (c.set === void 0) return ` ON CONFLICT (${c.target.join(", ")}) DO NOTHING`;
1088
+ const sets = Object.entries(c.set).map(([col, v]) => `${col} = ${compileColumnValue(m.table, col, v, ctx, schema)}`);
1089
+ let where = "";
1090
+ if (c.where !== void 0) {
1091
+ indexFilterFields(c.where, ctx.aliasMap);
1092
+ where = ` WHERE ${compileFilter(c.where, ctx)}`;
1093
+ }
1094
+ return ` ON CONFLICT (${c.target.join(", ")}) DO UPDATE SET ${sets.join(", ")}${where}`;
1095
+ };
1096
+ var ITEM_CAST = {
1097
+ number: "numeric",
1098
+ boolean: "boolean",
1099
+ date: "date",
1100
+ timestamp: "timestamptz",
1101
+ uuid: "uuid"
1102
+ };
1103
+ var compileMutation = (m, schema) => {
1104
+ const ctx = newCtx();
1105
+ if (m.op === "insert") {
1106
+ const entries = Object.entries(m.values);
1107
+ const cols = entries.map(([c]) => c);
1108
+ const vals = entries.map(([c, v]) => compileColumnValue(m.table, c, v, ctx, schema));
1109
+ return { sql: `INSERT INTO ${m.table} (${cols.join(", ")}) VALUES (${vals.join(", ")})${compileConflict(m, ctx, schema)} RETURNING *`, slots: ctx.paramSlots };
1110
+ }
1111
+ if (m.op === "insertEach") {
1112
+ const entity = findEntity(m.table, schema);
1113
+ const entries = Object.entries(m.values);
1114
+ const cols = entries.map(([c]) => c);
1115
+ const exprs = entries.map(([col, v]) => {
1116
+ if (isItemRef(v)) {
1117
+ const nt = entity?.fields.find((f) => f.name === col)?.normalizedType ?? "string";
1118
+ if (nt === "json") return `(item.value->${quoteLiteral(v.$item)})`;
1119
+ const cast = ITEM_CAST[nt];
1120
+ const raw = `(item.value->>${quoteLiteral(v.$item)})`;
1121
+ return cast === void 0 ? raw : `${raw}::${cast}`;
1122
+ }
1123
+ return compileValue(v, ctx);
1124
+ });
1125
+ ctx.paramCounter.value += 1;
1126
+ ctx.paramSlots.push({ key: m.items.$context, kind: "context", type: "json" });
1127
+ const source = `jsonb_array_elements($${ctx.paramCounter.value}::jsonb) AS item`;
1128
+ return {
1129
+ sql: `INSERT INTO ${m.table} (${cols.join(", ")}) SELECT ${exprs.join(", ")} FROM ${source}${compileConflict(m, ctx, schema)} RETURNING *`,
1130
+ slots: ctx.paramSlots
1131
+ };
1132
+ }
1133
+ if (m.op === "update") {
1134
+ const sets = Object.entries(m.set).map(([c, v]) => `${c} = ${compileColumnValue(m.table, c, v, ctx, schema)}`);
1135
+ indexFilterFields(m.where, ctx.aliasMap);
1136
+ const where2 = compileFilter(m.where, ctx);
1137
+ return { sql: `UPDATE ${m.table} SET ${sets.join(", ")} WHERE ${where2} RETURNING *`, slots: ctx.paramSlots };
1138
+ }
1139
+ indexFilterFields(m.where, ctx.aliasMap);
1140
+ const where = compileFilter(m.where, ctx);
1141
+ return { sql: `DELETE FROM ${m.table} WHERE ${where} RETURNING *`, slots: ctx.paramSlots };
1142
+ };
1143
+ var SUGAR = {
1144
+ upsert: (m, context) => {
1145
+ const keyed = context[m.key] !== void 0 && context[m.key] !== "";
1146
+ return keyed ? { op: "update", table: m.table, set: m.columns, where: { eq: [`${m.table}.${m.key}`, { $context: m.key }] } } : { op: "insert", table: m.table, values: { ...m.columns, ...m.insert } };
1147
+ }
1148
+ };
1149
+ var desugarMutation = (m, context) => {
1150
+ const rewrite = SUGAR[m.op];
1151
+ return rewrite === void 0 ? m : rewrite(m, context);
1152
+ };
1153
+ var executeWrites = async (client, def, mctx) => {
1154
+ const parsed = MutationDefinitionSchema.parse(def);
1155
+ const entries = Array.isArray(parsed) ? parsed : [parsed];
1156
+ const compiled = entries.map((entry) => {
1157
+ const core = desugarMutation(entry, mctx.context);
1158
+ const missing = requiredContextKeys(core).filter((k) => mctx.context[k] === void 0);
1159
+ if (missing.length > 0) {
1160
+ throw new VexError("missing_context", `Mutation is missing context: ${missing.join(", ")}.`, {
1161
+ expected: collectMutationContext(parsed, mctx.schema)
1162
+ });
1163
+ }
1164
+ const m = scopeMutation(core, mctx.policy);
1165
+ assertWritableColumns(m, mctx.schema);
1166
+ const statement = compileMutation(m, mctx.schema);
1167
+ requireScope({ paramSlots: statement.slots }, mctx.scope);
1168
+ return { ...statement, table: m.table, op: m.op === "insertEach" ? "insert" : m.op };
1169
+ });
1170
+ const runAll = async (q) => {
1171
+ const results = [];
1172
+ for (const c of compiled) {
1173
+ const params = await resolveParams(c.slots, mctx.context, mctx.scope);
1174
+ const bound = params.map((value, i) => {
1175
+ if (c.slots[i]?.encode === "json") return value !== null && typeof value === "object" ? JSON.stringify(value) : value;
1176
+ if (c.slots[i]?.type !== "json") return value;
1177
+ if (!Array.isArray(value)) {
1178
+ throw new VexError("invalid_request", `"${c.slots[i]?.key ?? ""}" must be an array of objects (one inserted row per element).`);
1179
+ }
1180
+ return JSON.stringify(value);
1181
+ });
1182
+ const res = await q.query(c.sql, bound);
1183
+ results.push({ table: c.table, op: c.op, rows: res.rows });
1184
+ }
1185
+ return results;
1186
+ };
1187
+ if (compiled.length === 1) return runAll(client);
1188
+ if (client.transaction === void 0) {
1189
+ throw new VexError("execution_error", "Batch mutations require a transactional client.");
1190
+ }
1191
+ return client.transaction((tx) => runAll(tx));
1192
+ };
1193
+ var executeMutation = async (client, def, mctx) => (await executeWrites(client, def, mctx)).flatMap((w) => w.rows);
1194
+ var tablesChangedBy = (writes, schema) => {
1195
+ const changed = /* @__PURE__ */ new Set();
1196
+ const referencing = (table) => (schema?.entities.find((entity) => entity.name === table)?.relations ?? []).filter((relation) => relation.type !== "belongsTo").map((relation) => relation.entity);
1197
+ for (const write of writes) {
1198
+ if (write.rows.length === 0) continue;
1199
+ changed.add(write.table);
1200
+ if (write.op !== "delete") continue;
1201
+ const pending = [write.table];
1202
+ for (let next = pending.pop(); next !== void 0; next = pending.pop()) {
1203
+ for (const table of referencing(next)) {
1204
+ if (changed.has(table)) continue;
1205
+ changed.add(table);
1206
+ pending.push(table);
1207
+ }
1208
+ }
1209
+ }
1210
+ return [...changed];
1211
+ };
1212
+ var filterSchema = (schema, entities) => {
1213
+ if (schema === void 0) return [];
1214
+ if (entities === void 0 || entities.length === 0) return schema.entities;
1215
+ return schema.entities.filter((e) => entities.includes(e.name));
1216
+ };
1217
+ var canWriteTable = (policy, table, op) => {
1218
+ const rule = policy.entities[table];
1219
+ if (rule === void 0) return policy.default === "allow";
1220
+ if ("public" in rule) return true;
1221
+ if ("deny" in rule) return false;
1222
+ if (rule.write !== void 0 || policy.default === "allow") return true;
1223
+ if (op === "insert" || op === "insertEach") return rule.insert !== void 0;
1224
+ if (op === "update") return rule.update !== void 0;
1225
+ if (op === "delete") return rule.delete !== void 0;
1226
+ if (op === "upsert") return rule.insert !== void 0 || rule.update !== void 0;
1227
+ return false;
1228
+ };
1229
+ var collectTables = (dsl) => {
1230
+ const out = [];
1231
+ const walk = (q) => {
1232
+ for (const src of q.from) {
1233
+ if (typeof src === "string") out.push(src);
1234
+ else walk(src.query);
1235
+ }
1236
+ };
1237
+ walk(dsl);
1238
+ return out;
1239
+ };
1240
+ var entryVisible = (policy, entry) => {
1241
+ if (entry.kind === "ok") return collectTables(entry.dsl).every((t) => canReadTable(policy, t));
1242
+ if (entry.kind === "mutation") return mutationEffect(entry.mutation).every((e) => canWriteTable(policy, e.table, e.op));
1243
+ return false;
1244
+ };
1245
+ var listFingerprints = async (engine, policy) => {
1246
+ if (engine.cache.entries === void 0) return [];
1247
+ const schema = engine.getSchema();
1248
+ const current = schema !== void 0 ? computeSchemaFingerprint(schema) : void 0;
1249
+ const rows = await engine.cache.entries();
1250
+ return rows.filter(({ key, entry }) => (entry.kind === "ok" || entry.kind === "mutation") && !key.startsWith("neg:")).filter(({ entry }) => policy === void 0 || entryVisible(policy, entry)).map(({ key, entry }) => ({
1251
+ fingerprint: key,
1252
+ kind: entry.kind === "mutation" ? "mutation" : "query",
1253
+ protected: entry.protected === true,
1254
+ schemaFresh: isEntryFresh(entry, current),
1255
+ ...entry.intent !== void 0 ? { intent: entry.intent } : {},
1256
+ createdAt: entry.createdAt,
1257
+ ...entry.lastUsedAt !== void 0 ? { lastUsedAt: entry.lastUsedAt } : {},
1258
+ // The derived contract — what to pass, straight from the stored def.
1259
+ ...entry.kind === "ok" ? {
1260
+ context: collectQueryContext(entry.dsl, schema),
1261
+ ...entry.shape !== void 0 ? { shape: entry.shape } : {}
1262
+ } : entry.kind === "mutation" ? {
1263
+ context: collectMutationContext(entry.mutation, schema),
1264
+ effect: mutationEffect(entry.mutation)
1265
+ } : {}
1266
+ }));
1267
+ };
1268
+ var handleDiscovery = async (config) => {
1269
+ const { engine, entities: entityFilter, scopePolicy } = config;
1270
+ const filtered = filterSchema(engine.getSchema(), entityFilter).filter(
1271
+ (e) => scopePolicy === void 0 || canReadTable(scopePolicy, e.name)
1272
+ );
1273
+ const fingerprints = await listFingerprints(engine, scopePolicy);
1274
+ const protectedCount = fingerprints.filter((f) => f.protected).length;
1275
+ return {
1276
+ protection: protectedCount === 0 ? "none" : protectedCount === fingerprints.length ? "all" : "some",
1277
+ locked: config.locked === true,
1278
+ fingerprints,
1279
+ vex: "1.0",
1280
+ description: "Query this resource using natural language or structured DSL",
1281
+ entities: filtered.map((e) => ({
1282
+ name: e.name,
1283
+ fields: e.fields.map((f) => ({
1284
+ name: f.name,
1285
+ type: f.normalizedType,
1286
+ nullable: f.nullable,
1287
+ primaryKey: f.primaryKey
1288
+ })),
1289
+ relations: e.relations.map((r) => ({
1290
+ entity: r.entity,
1291
+ type: r.type,
1292
+ via: r.localFields
1293
+ })),
1294
+ rowCount: e.rowCount
1295
+ })),
1296
+ query: {
1297
+ method: "POST",
1298
+ accepts: "application/json",
1299
+ body: {
1300
+ fingerprint: {
1301
+ type: "string",
1302
+ required: false,
1303
+ description: "Cache identity. Alone \u2192 replay a known query (no generation). With intent+shape \u2192 a named slot: matching request hits, differing request regenerates and replaces (409 when protected). Omitted \u2192 generate fresh; the minted fingerprint returns in meta.cache.fingerprint."
1304
+ },
1305
+ intent: {
1306
+ type: "string",
1307
+ required: false,
1308
+ description: "Natural language description of what data you need"
1309
+ },
1310
+ shape: {
1311
+ type: "any",
1312
+ required: false,
1313
+ description: "Example of the response structure \u2014 use empty strings, zeros, booleans as type indicators. Required unless replaying by fingerprint."
1314
+ },
1315
+ context: {
1316
+ type: "Record<string, unknown>",
1317
+ required: false,
1318
+ description: 'Runtime parameters referenced in filters as { $context: "key" }'
1319
+ }
1320
+ }
1321
+ },
1322
+ dsl: z.toJSONSchema(QuerySchema, { target: "draft-7", reused: "ref" })
1323
+ };
1324
+ };
1325
+ var rowsOf = (result) => Array.isArray(result) ? result.length : result === null || result === void 0 ? 0 : 1;
1326
+ var handleQuery = async (config, body, scope, live) => {
1327
+ if (config.onExecute === void 0) return runQuery(config, body, scope, void 0, live);
1328
+ const startUnixNano = Date.now() * 1e6;
1329
+ const t0 = elapsedClock();
1330
+ const probe = { kind: "query" };
1331
+ const result = await runQuery(config, body, scope, probe, live);
1332
+ const record = {
1333
+ kind: probe.kind,
1334
+ // 200 succeeded; 403 is a policy/reach refusal (a normal outcome, not a
1335
+ // fault); everything else is an error.
1336
+ status: result.status === 200 ? "ok" : result.status === 403 ? "refused" : "error",
1337
+ startUnixNano,
1338
+ endUnixNano: startUnixNano + (elapsedClock() - t0) * 1e6,
1339
+ scope,
1340
+ ...probe.fingerprint !== void 0 ? { fingerprint: probe.fingerprint } : {},
1341
+ ...probe.reach !== void 0 ? { reach: probe.reach } : {},
1342
+ ...probe.cacheHit !== void 0 ? { cacheHit: probe.cacheHit } : {},
1343
+ ...probe.rows !== void 0 ? { rows: probe.rows } : {}
1344
+ };
1345
+ try {
1346
+ config.onExecute(record);
1347
+ } catch (err) {
1348
+ console.error("[vex:onExecute]", err);
1349
+ }
1350
+ return result;
1351
+ };
1352
+ var elapsedClock = () => typeof performance !== "undefined" ? performance.now() : Date.now();
1353
+ var runQuery = async (config, body, scope, probe, live) => {
1354
+ const { engine } = config;
1355
+ if (exceedsDepth(body)) return { status: 400, body: { error: "invalid_request", message: depthRefusal() } };
1356
+ const parsed = QueryRequestSchema.safeParse(body);
1357
+ if (!parsed.success) {
1358
+ return {
1359
+ status: 400,
1360
+ body: {
1361
+ error: "invalid_request",
1362
+ message: parsed.error.message
1363
+ }
1364
+ };
1365
+ }
1366
+ const hasShape = parsed.data.shape !== void 0 && parsed.data.shape !== null;
1367
+ if (!hasShape && parsed.data.fingerprint === void 0) {
1368
+ return {
1369
+ status: 400,
1370
+ body: {
1371
+ error: "invalid_request",
1372
+ message: "Pass a fingerprint (replay) or intent + shape (generate) \u2014 or both (named slot)."
1373
+ }
1374
+ };
1375
+ }
1376
+ if (probe !== void 0 && parsed.data.fingerprint !== void 0) probe.fingerprint = parsed.data.fingerprint;
1377
+ try {
1378
+ let entryReach;
1379
+ if (parsed.data.fingerprint !== void 0) {
1380
+ const entry = await engine.cache.get(parsed.data.fingerprint);
1381
+ if (entry !== void 0 && entry.kind === "ok") entryReach = entry.reach;
1382
+ if (probe !== void 0 && entryReach !== void 0) probe.reach = entryReach;
1383
+ if (entry !== void 0 && entry.kind === "mutation") {
1384
+ if (probe !== void 0) {
1385
+ probe.kind = "mutation";
1386
+ if (entry.reach !== void 0) probe.reach = entry.reach;
1387
+ }
1388
+ if (config.mutations === void 0) {
1389
+ return {
1390
+ status: 500,
1391
+ body: { error: "execution_error", message: "This endpoint serves no mutations \u2014 handler has no mutation client configured." }
1392
+ };
1393
+ }
1394
+ const schema = engine.getSchema();
1395
+ if (schema === void 0) {
1396
+ return { status: 500, body: { error: "execution_error", message: "Vex schema not introspected." } };
1397
+ }
1398
+ let writePolicy = config.mutations.policy;
1399
+ if (entry.reach !== void 0) {
1400
+ if (config.policyForReach === void 0) {
1401
+ return {
1402
+ status: 500,
1403
+ body: {
1404
+ error: "execution_error",
1405
+ message: `Entry "${parsed.data.fingerprint ?? ""}" requires reach "${entry.reach}" and this handler has no policyForReach.`
1406
+ }
1407
+ };
1408
+ }
1409
+ const narrowed = await config.policyForReach(entry.reach);
1410
+ if (narrowed === void 0) {
1411
+ return {
1412
+ status: 403,
1413
+ body: { error: "scope_denied", message: `Reach "${entry.reach}" is not available to this principal.` }
1414
+ };
1415
+ }
1416
+ writePolicy = narrowed;
1417
+ }
1418
+ const writes = await executeWrites(config.mutations.client, entry.mutation, {
1419
+ context: parsed.data.context,
1420
+ scope,
1421
+ policy: writePolicy,
1422
+ schema
1423
+ });
1424
+ const rows = writes.flatMap((w) => w.rows);
1425
+ engine.invalidate(tablesChangedBy(writes, schema));
1426
+ if (config.mutations.onWrite !== void 0) {
1427
+ try {
1428
+ config.mutations.onWrite({ fingerprint: parsed.data.fingerprint, writes, scope });
1429
+ } catch (err) {
1430
+ console.error("[vex:onWrite]", err);
1431
+ }
1432
+ }
1433
+ const now = Date.now();
1434
+ if (isTouchDue(entry, now)) fireAndForget(engine.cache.set(parsed.data.fingerprint, { ...entry, lastUsedAt: now }));
1435
+ if (probe !== void 0) probe.rows = rows.length;
1436
+ return { status: 200, body: { result: rows.length === 1 ? rows[0] : rows } };
1437
+ }
1438
+ }
1439
+ let readPolicy = config.scopePolicy;
1440
+ if (entryReach !== void 0) {
1441
+ if (config.policyForReach === void 0) {
1442
+ return {
1443
+ status: 500,
1444
+ body: {
1445
+ error: "execution_error",
1446
+ message: `Entry "${parsed.data.fingerprint ?? ""}" requires reach "${entryReach}" and this handler has no policyForReach.`
1447
+ }
1448
+ };
1449
+ }
1450
+ readPolicy = await config.policyForReach(entryReach);
1451
+ if (readPolicy === void 0) {
1452
+ return {
1453
+ status: 403,
1454
+ body: { error: "scope_denied", message: `Reach "${entryReach}" is not available to this principal.` }
1455
+ };
1456
+ }
1457
+ }
1458
+ const response = await engine.execute(parsed.data, {
1459
+ scope,
1460
+ entities: config.entities,
1461
+ ...config.locked === true ? { locked: true } : {},
1462
+ ...readPolicy !== void 0 ? { scopePolicy: readPolicy } : {},
1463
+ ...live !== void 0 ? { signal: live.signal, onChange: live.onChange } : {}
1464
+ });
1465
+ if (probe !== void 0) {
1466
+ probe.cacheHit = response.meta.cache.hit;
1467
+ if (response.meta.cache.fingerprint !== void 0) probe.fingerprint = response.meta.cache.fingerprint;
1468
+ probe.rows = rowsOf(response.result);
1469
+ }
1470
+ return { status: 200, body: response };
1471
+ } catch (err) {
1472
+ if (err instanceof VexError && err.code === "missing_scope") {
1473
+ console.error("[vex] refused a statement the host did not scope:", err.message);
1474
+ return { status: 500, body: { error: "missing_scope", message: "The server did not supply the scope this request needs." } };
1475
+ }
1476
+ if (err instanceof VexError) {
1477
+ const status = err.code === "fingerprint_protected" ? 409 : err.code === "cache_miss" ? 404 : 400;
1478
+ return {
1479
+ status,
1480
+ body: {
1481
+ error: err.code,
1482
+ message: err.message,
1483
+ details: err.details
1484
+ }
1485
+ };
1486
+ }
1487
+ console.error("[vex] unhandled error:", err);
1488
+ const errObj = err;
1489
+ const message = err instanceof Error ? err.message : typeof errObj?.message === "string" ? errObj.message : "Unknown error";
1490
+ const code = typeof errObj?.code === "string" ? errObj.code : "execution_error";
1491
+ return {
1492
+ status: 500,
1493
+ body: { error: code, message }
1494
+ };
1495
+ }
1496
+ };
1497
+ var handleFingerprintPatch = async (config, fingerprint, patch) => {
1498
+ if (config.locked === true) {
1499
+ return { status: 403, body: { error: "locked", message: "This endpoint is locked \u2014 fingerprints cannot be managed here." } };
1500
+ }
1501
+ const entry = await config.engine.cache.get(fingerprint);
1502
+ if (entry === void 0 || entry.kind !== "ok" && entry.kind !== "mutation") {
1503
+ return { status: 404, body: { error: "cache_miss", message: `Unknown fingerprint "${fingerprint}"` } };
1504
+ }
1505
+ if (typeof patch.protected !== "boolean") {
1506
+ return { status: 400, body: { error: "invalid_request", message: "Body must be { protected: boolean }" } };
1507
+ }
1508
+ await config.engine.cache.set(fingerprint, { ...entry, protected: patch.protected });
1509
+ return { status: 200, body: { fingerprint, protected: patch.protected } };
1510
+ };
1511
+ var handleFingerprintDelete = async (config, fingerprint) => {
1512
+ if (config.locked === true) {
1513
+ return { status: 403, body: { error: "locked", message: "This endpoint is locked \u2014 fingerprints cannot be managed here." } };
1514
+ }
1515
+ const entry = await config.engine.cache.get(fingerprint);
1516
+ if (entry === void 0) {
1517
+ return { status: 404, body: { error: "cache_miss", message: `Unknown fingerprint "${fingerprint}"` } };
1518
+ }
1519
+ if (entry.kind === "ok" && entry.protected === true) {
1520
+ return { status: 409, body: { error: "fingerprint_protected", message: `"${fingerprint}" is protected \u2014 unprotect it first.` } };
1521
+ }
1522
+ await config.engine.cache.delete(fingerprint);
1523
+ return { status: 200, body: { fingerprint, deleted: true } };
1524
+ };
1525
+
1526
+ export { MutationDefinitionSchema, MutationSchema, QueryRequestSchema, VexScopeError, applyScope, buildContextContract, buildValidationContext, canReadTable, checkScope, collectMutationContext, collectQueryContext, compileAggregate, compileCompute, compileFieldOrValue, compileFilter, compileJoinPairs, computePolicyKey, computeRequestHash, computeSchemaFingerprint, executeMutation, executeQuery, executeWrites, findMissingContext, fireAndForget, handleDiscovery, handleFingerprintDelete, handleFingerprintPatch, handleQuery, isEntryFresh, isSetMatch, isTouchDue, lintMutation, mintFingerprint, mutationEffect, normalizeShape, optionalKeysOf, presenceOf, presenceSignature, pruneOptional, quoteIdent, refuseOptional, requireScope, requiredContextKeys, resolveParams, scopeResolved, sweepCache, tablesChangedBy };
1527
+ //# sourceMappingURL=chunk-FPKW4TRX.js.map
1528
+ //# sourceMappingURL=chunk-FPKW4TRX.js.map