@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
package/dist/index.js ADDED
@@ -0,0 +1,2340 @@
1
+ import { MutationDefinitionSchema, lintMutation, computeSchemaFingerprint, pruneOptional, buildValidationContext, requireScope, executeQuery, QueryRequestSchema, computeRequestHash, computePolicyKey, presenceOf, presenceSignature, findMissingContext, buildContextContract, optionalKeysOf, resolveParams, fireAndForget, isSetMatch, refuseOptional, quoteIdent, compileCompute, compileAggregate, compileJoinPairs, compileFilter, checkScope, scopeResolved, mintFingerprint, isEntryFresh, canReadTable, isTouchDue } from './chunk-FPKW4TRX.js';
2
+ export { MutationDefinitionSchema, MutationSchema, QueryRequestSchema, VexScopeError, applyScope, buildContextContract, buildValidationContext, checkScope, collectMutationContext, collectQueryContext, compileFieldOrValue, compileFilter, computeRequestHash, computeSchemaFingerprint, executeMutation, executeQuery, executeWrites, findMissingContext, handleDiscovery, handleFingerprintDelete, handleFingerprintPatch, handleQuery, lintMutation, mintFingerprint, mutationEffect, normalizeShape, optionalKeysOf, presenceOf, pruneOptional, requiredContextKeys, resolveParams, scopeResolved, sweepCache, tablesChangedBy } from './chunk-FPKW4TRX.js';
3
+ import { VexError, QuerySchema, isIdentifier, isFieldPathShape } from './chunk-HF25Q53I.js';
4
+ export { AggregateExpressionSchema, ComputeExpressionSchema, FilterSchema, QuerySchema, VexError } from './chunk-HF25Q53I.js';
5
+ import { z } from 'zod';
6
+ import { createHash } from 'crypto';
7
+ import { exceedsDepth, depthRefusal } from '@niscorp/strata';
8
+ import { compile, execute } from '@niscorp/prism';
9
+ import { migrate } from '@niscorp/strata/postgres';
10
+
11
+ // src/scope/discover.ts
12
+ var extractEntityFromPath = (path) => {
13
+ const parts = path.split(".");
14
+ return parts.length === 2 ? parts[0] : void 0;
15
+ };
16
+ var collectFromFieldOrValue = (fov, out) => {
17
+ if (isFieldPathShape(fov)) {
18
+ const entity = extractEntityFromPath(fov);
19
+ if (entity !== void 0) out.add(entity);
20
+ }
21
+ };
22
+ var collectFromFilter = (filter, out) => {
23
+ if ("exists" in filter) {
24
+ for (const entity of filter.exists.from) out.add(entity);
25
+ if (filter.exists.filter !== void 0) collectFromFilter(filter.exists.filter, out);
26
+ return;
27
+ }
28
+ if ("eq" in filter || "neq" in filter || "gt" in filter || "gte" in filter || "lt" in filter || "lte" in filter) {
29
+ const pair = "eq" in filter ? filter.eq : "neq" in filter ? filter.neq : "gt" in filter ? filter.gt : "gte" in filter ? filter.gte : "lt" in filter ? filter.lt : filter.lte;
30
+ collectFromFieldOrValue(pair[0], out);
31
+ collectFromFieldOrValue(pair[1], out);
32
+ return;
33
+ }
34
+ if ("in" in filter || "notIn" in filter) {
35
+ const tuple = "in" in filter ? filter.in : filter.notIn;
36
+ const entity = extractEntityFromPath(tuple[0]);
37
+ if (entity !== void 0) out.add(entity);
38
+ const target = tuple[1];
39
+ if (Array.isArray(target)) {
40
+ for (const v of target) {
41
+ collectFromFieldOrValue(v, out);
42
+ }
43
+ }
44
+ return;
45
+ }
46
+ if ("like" in filter || "ilike" in filter) {
47
+ const tuple = "like" in filter ? filter.like : filter.ilike;
48
+ const entity = extractEntityFromPath(tuple[0]);
49
+ if (entity !== void 0) out.add(entity);
50
+ collectFromFieldOrValue(tuple[1], out);
51
+ return;
52
+ }
53
+ if ("isNull" in filter) {
54
+ const entity = extractEntityFromPath(filter.isNull);
55
+ if (entity !== void 0) out.add(entity);
56
+ return;
57
+ }
58
+ if ("isNotNull" in filter) {
59
+ const entity = extractEntityFromPath(filter.isNotNull);
60
+ if (entity !== void 0) out.add(entity);
61
+ return;
62
+ }
63
+ if ("and" in filter) {
64
+ for (const sub of filter.and) {
65
+ collectFromFilter(sub, out);
66
+ }
67
+ return;
68
+ }
69
+ if ("or" in filter) {
70
+ for (const sub of filter.or) {
71
+ collectFromFilter(sub, out);
72
+ }
73
+ return;
74
+ }
75
+ if ("not" in filter) {
76
+ collectFromFilter(filter.not, out);
77
+ return;
78
+ }
79
+ if ("semantic" in filter) {
80
+ const entity = extractEntityFromPath(filter.semantic.field);
81
+ if (entity !== void 0) out.add(entity);
82
+ return;
83
+ }
84
+ if ("fuzzy" in filter) {
85
+ const entity = extractEntityFromPath(filter.fuzzy.field);
86
+ if (entity !== void 0) out.add(entity);
87
+ return;
88
+ }
89
+ if ("optional" in filter) refuseOptional("scope discovery");
90
+ };
91
+ var collectFromCompute = (expr, out) => {
92
+ if ("add" in expr || "subtract" in expr || "multiply" in expr || "divide" in expr) {
93
+ const pair = "add" in expr ? expr.add : "subtract" in expr ? expr.subtract : "multiply" in expr ? expr.multiply : expr.divide;
94
+ collectFromFieldOrValue(pair[0], out);
95
+ collectFromFieldOrValue(pair[1], out);
96
+ return;
97
+ }
98
+ if ("concat" in expr) {
99
+ for (const v of expr.concat) {
100
+ collectFromFieldOrValue(v, out);
101
+ }
102
+ return;
103
+ }
104
+ if ("coalesce" in expr) {
105
+ for (const v of expr.coalesce) {
106
+ collectFromFieldOrValue(v, out);
107
+ }
108
+ return;
109
+ }
110
+ if ("case" in expr) {
111
+ for (const when of expr.case.when) {
112
+ collectFromFilter(when.condition, out);
113
+ collectFromFieldOrValue(when.then, out);
114
+ }
115
+ collectFromFieldOrValue(expr.case.else, out);
116
+ return;
117
+ }
118
+ };
119
+ var collectFromAggregate = (expr, out) => {
120
+ const arg = "count" in expr ? expr.count : "countDistinct" in expr ? expr.countDistinct : "sum" in expr ? expr.sum : "avg" in expr ? expr.avg : "min" in expr ? expr.min : expr.max;
121
+ if (typeof arg !== "string") {
122
+ collectFromCompute(arg, out);
123
+ return;
124
+ }
125
+ const entity = extractEntityFromPath(arg);
126
+ if (entity !== void 0) out.add(entity);
127
+ };
128
+ var collectFromQuery = (dsl, out) => {
129
+ const aliases = /* @__PURE__ */ new Set();
130
+ const local = /* @__PURE__ */ new Set();
131
+ for (const source of dsl.from) {
132
+ if (typeof source === "string") {
133
+ out.add(source);
134
+ } else {
135
+ aliases.add(source.as);
136
+ collectFromQuery(source.query, out);
137
+ }
138
+ }
139
+ for (const ref of dsl.fields ?? []) {
140
+ const entity = extractEntityFromPath(typeof ref === "string" ? ref : ref.field);
141
+ if (entity !== void 0) local.add(entity);
142
+ }
143
+ if (dsl.filter !== void 0) {
144
+ collectFromFilter(dsl.filter, local);
145
+ }
146
+ if (dsl.compute !== void 0) {
147
+ for (const key of Object.keys(dsl.compute)) {
148
+ const expr = dsl.compute[key];
149
+ if (expr !== void 0) {
150
+ collectFromCompute(expr, local);
151
+ }
152
+ }
153
+ }
154
+ if (dsl.aggregate !== void 0) {
155
+ for (const key of Object.keys(dsl.aggregate)) {
156
+ const expr = dsl.aggregate[key];
157
+ if (expr !== void 0) {
158
+ collectFromAggregate(expr, local);
159
+ }
160
+ }
161
+ }
162
+ if (dsl.groupBy !== void 0) {
163
+ for (const path of dsl.groupBy) {
164
+ const entity = extractEntityFromPath(path);
165
+ if (entity !== void 0) local.add(entity);
166
+ }
167
+ }
168
+ if (dsl.sort !== void 0) {
169
+ for (const entry of dsl.sort) {
170
+ const entity = extractEntityFromPath(entry.field);
171
+ if (entity !== void 0) local.add(entity);
172
+ }
173
+ }
174
+ for (const entity of local) {
175
+ if (!aliases.has(entity)) out.add(entity);
176
+ }
177
+ };
178
+ var discoverEntities = (dsl) => {
179
+ const entities = /* @__PURE__ */ new Set();
180
+ collectFromQuery(dsl, entities);
181
+ return entities;
182
+ };
183
+
184
+ // src/scope/grants.ts
185
+ var SCOPE_VERBS = ["read", "write.insert", "write.update", "write.delete"];
186
+ var scopeGrants = (tables) => tables.flatMap((t) => SCOPE_VERBS.map((v) => `${t}.${v}`));
187
+ var RULE_KEYS = ["read", "write", "insert", "update", "delete"];
188
+ var isRuleSet = (value) => RULE_KEYS.some((k) => k in value);
189
+ var behaviorFor = (behaviors, table, profile) => {
190
+ const entry = behaviors[table];
191
+ if (entry === void 0) return {};
192
+ if (isRuleSet(entry)) return entry;
193
+ return (profile === void 0 ? void 0 : entry[profile]) ?? entry["default"];
194
+ };
195
+ var onlyMatches = (rules) => rules.filter((r) => "match" in r);
196
+ var VERBS = new Set(SCOPE_VERBS);
197
+ var bindingsOf = (entry) => (isRuleSet(entry) ? [entry] : Object.values(entry)).flatMap(
198
+ (rules) => RULE_KEYS.flatMap(
199
+ (phase) => (rules[phase] ?? []).map(
200
+ (rule) => "set" in rule ? { field: rule.set, key: rule.to } : isSetMatch(rule) ? { field: rule.match, key: rule.in } : { field: rule.match, key: rule.to }
201
+ )
202
+ )
203
+ );
204
+ var scopeBindings = (behaviors, tables, scope) => {
205
+ const seen = /* @__PURE__ */ new Map();
206
+ for (const table of tables) {
207
+ const entry = behaviors[table];
208
+ if (entry === void 0) continue;
209
+ for (const { field, key } of bindingsOf(entry)) {
210
+ if (scope[key] === void 0 || scope[key] === null) continue;
211
+ seen.set(`${table}.${field}:${key}`, { entity: table, field, key });
212
+ }
213
+ }
214
+ return [...seen.values()].sort((a, b) => `${a.entity}.${a.field}:${a.key}`.localeCompare(`${b.entity}.${b.field}:${b.key}`));
215
+ };
216
+ var behaviorColumns = (behaviors) => Object.entries(behaviors).flatMap(([table, entry]) => bindingsOf(entry).map(({ field }) => ({ entity: table, field })));
217
+ var scopeProfiles = (behaviors) => {
218
+ const names = /* @__PURE__ */ new Set();
219
+ for (const entry of Object.values(behaviors)) {
220
+ if (isRuleSet(entry)) continue;
221
+ for (const name of Object.keys(entry)) if (name !== "default") names.add(name);
222
+ }
223
+ return names;
224
+ };
225
+ var createScopePolicy = (grants, behaviors = {}, scoping) => {
226
+ if (scoping !== void 0 && !scopeProfiles(behaviors).has(scoping)) return { default: "deny", entities: {} };
227
+ const entities = {};
228
+ for (const grant of grants) {
229
+ const dot = grant.indexOf(".");
230
+ if (dot < 0) continue;
231
+ const table = grant.slice(0, dot);
232
+ const verb = grant.slice(dot + 1);
233
+ if (!VERBS.has(verb)) continue;
234
+ const b = behaviorFor(behaviors, table, scoping);
235
+ if (b === void 0) continue;
236
+ const rule = entities[table] ??= {};
237
+ if (verb === "read") rule.read = b?.read ?? [];
238
+ else if (verb === "write.insert") rule.insert = [...b?.write ?? [], ...b?.insert ?? []];
239
+ else if (verb === "write.update") rule.update = [...b?.write ?? [], ...b?.update ?? []];
240
+ else if (verb === "write.delete") rule.delete = [...onlyMatches(b?.write ?? []), ...b?.delete ?? []];
241
+ }
242
+ return { default: "deny", entities };
243
+ };
244
+ var matchCount = (rules) => (rules ?? []).filter((r) => "match" in r).length;
245
+ var mergeScopePolicies = (policies) => {
246
+ const entities = {};
247
+ for (const policy of policies) {
248
+ for (const [table, rule] of Object.entries(policy.entities)) {
249
+ if (rule === void 0 || "public" in rule || "deny" in rule) continue;
250
+ const into = entities[table] ??= {};
251
+ for (const phase of ["read", "insert", "update", "delete"]) {
252
+ const incoming = rule[phase];
253
+ if (incoming === void 0) continue;
254
+ const held = into[phase];
255
+ if (held === void 0 || matchCount(incoming) < matchCount(held)) {
256
+ into[phase] = incoming;
257
+ }
258
+ }
259
+ }
260
+ }
261
+ return { default: "deny", entities };
262
+ };
263
+
264
+ // src/engine/resolver.ts
265
+ var levenshtein = (a, b) => {
266
+ const la = a.length;
267
+ const lb = b.length;
268
+ if (la === 0) return lb;
269
+ if (lb === 0) return la;
270
+ let prev = Array.from({ length: lb + 1 }, (_, i) => i);
271
+ let curr = new Array(lb + 1);
272
+ for (let i = 1; i <= la; i++) {
273
+ curr[0] = i;
274
+ for (let j = 1; j <= lb; j++) {
275
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
276
+ const prevJ = prev[j] ?? 0;
277
+ const currJ1 = curr[j - 1] ?? 0;
278
+ const prevJ1 = prev[j - 1] ?? 0;
279
+ curr[j] = Math.min(prevJ + 1, currJ1 + 1, prevJ1 + cost);
280
+ }
281
+ [prev, curr] = [curr, prev];
282
+ }
283
+ return prev[lb] ?? 0;
284
+ };
285
+ var findClosest = (target, candidates) => {
286
+ let best;
287
+ let bestDist = Infinity;
288
+ for (const c of candidates) {
289
+ const dist = levenshtein(target.toLowerCase(), c.toLowerCase());
290
+ if (dist < bestDist) {
291
+ bestDist = dist;
292
+ best = c;
293
+ }
294
+ }
295
+ if (bestDist <= Math.max(3, Math.ceil(target.length / 2))) {
296
+ return best;
297
+ }
298
+ return void 0;
299
+ };
300
+ var generateAlias = (name, counter) => {
301
+ const prefix = name.charAt(0).toLowerCase();
302
+ const current = counter.get(prefix) ?? 0;
303
+ const next = current + 1;
304
+ counter.set(prefix, next);
305
+ return `${prefix}${next}`;
306
+ };
307
+ var findEntity = (name, schema) => {
308
+ const found = schema.entities.find((e) => e.name === name);
309
+ if (found !== void 0) return found;
310
+ const allNames = schema.entities.map((e) => e.name);
311
+ const suggestion = findClosest(name, allNames);
312
+ const hint = suggestion !== void 0 ? ` Did you mean "${suggestion}"?` : "";
313
+ throw new VexError(
314
+ "invalid_dsl",
315
+ `Entity "${name}" not found in schema.${hint}`,
316
+ { suggestion, options: allNames }
317
+ );
318
+ };
319
+ var findField = (fieldName, entity) => {
320
+ const found = entity.fields.find((f) => f.name === fieldName);
321
+ if (found !== void 0) return found;
322
+ const allFields = entity.fields.map((f) => f.name);
323
+ const suggestion = findClosest(fieldName, allFields);
324
+ const hint = suggestion !== void 0 ? ` Did you mean "${suggestion}"?` : "";
325
+ throw new VexError(
326
+ "invalid_dsl",
327
+ `Field "${fieldName}" not found on entity "${entity.name}".${hint} Available fields: ${allFields.join(", ")}`,
328
+ { suggestion, options: allFields }
329
+ );
330
+ };
331
+ var parsePath = (path) => {
332
+ if (!isFieldPathShape(path)) {
333
+ throw new VexError(
334
+ "invalid_dsl",
335
+ `Invalid field path "${path}". Expected format: entity.field`
336
+ );
337
+ }
338
+ const dotIndex = path.indexOf(".");
339
+ return {
340
+ entity: path.substring(0, dotIndex),
341
+ field: path.substring(dotIndex + 1)
342
+ };
343
+ };
344
+ var assertName = (name, what) => {
345
+ if (!isIdentifier(name)) {
346
+ throw new VexError("invalid_dsl", `Invalid ${what} "${name}": letters, digits and underscores, not starting with a digit.`);
347
+ }
348
+ };
349
+ var findJoinBetween = (fromEntity, toEntity, fromAlias, toAlias) => {
350
+ for (const rel of fromEntity.relations) {
351
+ if (rel.entity === toEntity.name) {
352
+ const fkNullable = rel.localFields.some(
353
+ (column) => fromEntity.fields.find((f) => f.name === column)?.nullable === true
354
+ );
355
+ return {
356
+ fromAlias,
357
+ fromColumns: rel.localFields,
358
+ toAlias,
359
+ toColumns: rel.foreignFields,
360
+ toTable: toEntity.table,
361
+ kind: fkNullable ? "left" : "inner"
362
+ };
363
+ }
364
+ }
365
+ for (const rel of toEntity.relations) {
366
+ if (rel.entity === fromEntity.name) {
367
+ return {
368
+ fromAlias,
369
+ fromColumns: rel.foreignFields,
370
+ toAlias,
371
+ toColumns: rel.localFields,
372
+ toTable: toEntity.table,
373
+ kind: "inner"
374
+ };
375
+ }
376
+ }
377
+ return void 0;
378
+ };
379
+ var resolveFieldPath = (path, entityLookup, schema) => {
380
+ const parsed = parsePath(path);
381
+ const lookup = entityLookup.get(parsed.entity);
382
+ if (lookup === void 0) {
383
+ const entityExists = schema.entities.some((e) => e.name === parsed.entity);
384
+ if (entityExists) {
385
+ throw new VexError(
386
+ "invalid_dsl",
387
+ `Entity "${parsed.entity}" is referenced in field path "${path}" but not listed in "from"`
388
+ );
389
+ }
390
+ const allNames = schema.entities.map((e) => e.name);
391
+ const suggestion = findClosest(parsed.entity, allNames);
392
+ const hint = suggestion !== void 0 ? ` Did you mean "${suggestion}"?` : "";
393
+ throw new VexError(
394
+ "invalid_dsl",
395
+ `Entity "${parsed.entity}" not found in schema.${hint}`,
396
+ { suggestion, options: allNames }
397
+ );
398
+ }
399
+ const fieldSchema = findField(parsed.field, lookup.entity);
400
+ return {
401
+ resolved: {
402
+ path,
403
+ alias: lookup.alias,
404
+ column: fieldSchema.name,
405
+ outputName: parsed.field,
406
+ schema: fieldSchema
407
+ },
408
+ entityName: parsed.entity
409
+ };
410
+ };
411
+ var isFieldPath = isFieldPathShape;
412
+ var collectFilterPaths = (filter, entityLookup, schema, resolvedPaths, existsOut, aliasCounter) => {
413
+ if ("eq" in filter || "neq" in filter || "gt" in filter || "gte" in filter || "lt" in filter || "lte" in filter) {
414
+ const pair = "eq" in filter ? filter.eq : "neq" in filter ? filter.neq : "gt" in filter ? filter.gt : "gte" in filter ? filter.gte : "lt" in filter ? filter.lt : filter.lte;
415
+ resolveFilterFieldOrValue(pair[0], entityLookup, schema, resolvedPaths);
416
+ resolveFilterFieldOrValue(pair[1], entityLookup, schema, resolvedPaths);
417
+ return;
418
+ }
419
+ if ("in" in filter || "notIn" in filter) {
420
+ const tuple = "in" in filter ? filter.in : filter.notIn;
421
+ resolveFilterFieldPath(tuple[0], entityLookup, schema, resolvedPaths);
422
+ const target = tuple[1];
423
+ if (Array.isArray(target)) {
424
+ for (const v of target) {
425
+ resolveFilterFieldOrValue(v, entityLookup, schema, resolvedPaths);
426
+ }
427
+ }
428
+ return;
429
+ }
430
+ if ("like" in filter || "ilike" in filter) {
431
+ const tuple = "like" in filter ? filter.like : filter.ilike;
432
+ resolveFilterFieldPath(tuple[0], entityLookup, schema, resolvedPaths);
433
+ resolveFilterFieldOrValue(tuple[1], entityLookup, schema, resolvedPaths);
434
+ return;
435
+ }
436
+ if ("isNull" in filter) {
437
+ resolveFilterFieldPath(filter.isNull, entityLookup, schema, resolvedPaths);
438
+ return;
439
+ }
440
+ if ("isNotNull" in filter) {
441
+ resolveFilterFieldPath(filter.isNotNull, entityLookup, schema, resolvedPaths);
442
+ return;
443
+ }
444
+ if ("exists" in filter) {
445
+ if (existsOut === void 0 || aliasCounter === void 0) return;
446
+ const inner = new Map(entityLookup);
447
+ const innerSources = [];
448
+ const innerEntities = [];
449
+ const innerJoins = [];
450
+ const innerAliasMap = /* @__PURE__ */ new Map();
451
+ for (const name of filter.exists.from) {
452
+ const entity = findEntity(name, schema);
453
+ const alias = generateAlias(name, aliasCounter);
454
+ inner.set(name, { entity, alias });
455
+ innerSources.push({ alias, entity, table: entity.table });
456
+ innerEntities.push({ entity, alias });
457
+ }
458
+ for (let i = 1; i < innerEntities.length; i += 1) {
459
+ const curr = innerEntities[i];
460
+ if (curr === void 0) continue;
461
+ let found = false;
462
+ for (let j = 0; j < i; j += 1) {
463
+ const earlier = innerEntities[j];
464
+ if (earlier === void 0) continue;
465
+ const join = findJoinBetween(earlier.entity, curr.entity, earlier.alias, curr.alias);
466
+ if (join !== void 0) {
467
+ innerJoins.push(join);
468
+ found = true;
469
+ break;
470
+ }
471
+ }
472
+ if (!found) throw new VexError("invalid_dsl", `No foreign key relationship found between the entities of an "exists" and "${curr.entity.name}".`);
473
+ }
474
+ let innerFilter;
475
+ if (filter.exists.filter !== void 0) {
476
+ const innerPaths = /* @__PURE__ */ new Map();
477
+ collectFilterPaths(filter.exists.filter, inner, schema, innerPaths, existsOut, aliasCounter);
478
+ innerFilter = { original: filter.exists.filter, resolvedPaths: innerPaths };
479
+ for (const [path, res] of innerPaths) {
480
+ const owner = path.slice(0, path.indexOf("."));
481
+ if (filter.exists.from.includes(owner)) innerAliasMap.set(path, `${res.alias}.${res.column}`);
482
+ else resolvedPaths.set(path, res);
483
+ }
484
+ }
485
+ existsOut.set(filter.exists, { sources: innerSources, joins: innerJoins, filter: innerFilter, aliasMap: innerAliasMap });
486
+ return;
487
+ }
488
+ if ("and" in filter) {
489
+ for (const sub of filter.and) {
490
+ collectFilterPaths(sub, entityLookup, schema, resolvedPaths, existsOut, aliasCounter);
491
+ }
492
+ return;
493
+ }
494
+ if ("or" in filter) {
495
+ for (const sub of filter.or) {
496
+ collectFilterPaths(sub, entityLookup, schema, resolvedPaths, existsOut, aliasCounter);
497
+ }
498
+ return;
499
+ }
500
+ if ("not" in filter) {
501
+ collectFilterPaths(filter.not, entityLookup, schema, resolvedPaths, existsOut, aliasCounter);
502
+ return;
503
+ }
504
+ if ("semantic" in filter) {
505
+ resolveFilterFieldPath(filter.semantic.field, entityLookup, schema, resolvedPaths);
506
+ return;
507
+ }
508
+ if ("fuzzy" in filter) {
509
+ resolveFilterFieldPath(filter.fuzzy.field, entityLookup, schema, resolvedPaths);
510
+ return;
511
+ }
512
+ if ("optional" in filter) refuseOptional("field resolution");
513
+ };
514
+ var resolveFilterFieldPath = (path, entityLookup, schema, resolvedPaths) => {
515
+ if (resolvedPaths.has(path)) return;
516
+ const { resolved } = resolveFieldPath(path, entityLookup, schema);
517
+ resolvedPaths.set(path, { alias: resolved.alias, column: resolved.column, schema: resolved.schema });
518
+ };
519
+ var resolveFilterFieldOrValue = (fov, entityLookup, schema, resolvedPaths) => {
520
+ if (typeof fov === "string" && isFieldPath(fov)) {
521
+ resolveFilterFieldPath(fov, entityLookup, schema, resolvedPaths);
522
+ }
523
+ };
524
+ var extractSemantic = (filter, entityLookup, schema) => {
525
+ if ("semantic" in filter) {
526
+ const { resolved } = resolveFieldPath(filter.semantic.field, entityLookup, schema);
527
+ const queryRef = filter.semantic.query;
528
+ const contextPath = "$context" in queryRef ? queryRef.$context : queryRef.$scope;
529
+ return {
530
+ field: resolved,
531
+ contextPath,
532
+ minScore: filter.semantic.minScore
533
+ };
534
+ }
535
+ if ("and" in filter) {
536
+ for (const sub of filter.and) {
537
+ const result = extractSemantic(sub, entityLookup, schema);
538
+ if (result !== void 0) return result;
539
+ }
540
+ }
541
+ if ("or" in filter) {
542
+ for (const sub of filter.or) {
543
+ const result = extractSemantic(sub, entityLookup, schema);
544
+ if (result !== void 0) return result;
545
+ }
546
+ }
547
+ if ("not" in filter) {
548
+ return extractSemantic(filter.not, entityLookup, schema);
549
+ }
550
+ return void 0;
551
+ };
552
+ var resolve = (dsl, schema) => {
553
+ const aliasCounter = /* @__PURE__ */ new Map();
554
+ const entityLookup = /* @__PURE__ */ new Map();
555
+ const aliasMap = /* @__PURE__ */ new Map();
556
+ const sources = [];
557
+ const joins = [];
558
+ const entitySources = [];
559
+ for (const source of dsl.from) {
560
+ if (typeof source === "string") {
561
+ const entity = findEntity(source, schema);
562
+ const alias = generateAlias(source, aliasCounter);
563
+ entityLookup.set(source, { entity, alias });
564
+ sources.push({ alias, entity, table: entity.table });
565
+ entitySources.push({ entity, alias });
566
+ } else {
567
+ assertName(source.as, "subquery alias");
568
+ const subResolved = resolve(source.query, schema);
569
+ const alias = source.as;
570
+ const synthField = (name, normalizedType) => ({
571
+ name,
572
+ type: normalizedType,
573
+ normalizedType,
574
+ nullable: true,
575
+ primaryKey: false
576
+ });
577
+ const syntheticFields = [
578
+ ...subResolved.fields.map((f) => ({ ...f.schema, name: f.outputName })),
579
+ ...subResolved.computes.map((c) => synthField(c.name, "unknown")),
580
+ ...subResolved.aggregates.map((a) => synthField(a.name, "number"))
581
+ ];
582
+ const syntheticEntity = {
583
+ name: alias,
584
+ table: alias,
585
+ fields: syntheticFields,
586
+ relations: [],
587
+ indexes: []
588
+ };
589
+ entityLookup.set(alias, { entity: syntheticEntity, alias });
590
+ sources.push({ alias, subquery: subResolved });
591
+ }
592
+ }
593
+ for (let i = 1; i < entitySources.length; i++) {
594
+ const prev = entitySources[i - 1];
595
+ const curr = entitySources[i];
596
+ if (prev === void 0 || curr === void 0) continue;
597
+ let joinFound = false;
598
+ for (let j = 0; j < i; j++) {
599
+ const earlier = entitySources[j];
600
+ if (earlier === void 0) continue;
601
+ const join = findJoinBetween(earlier.entity, curr.entity, earlier.alias, curr.alias);
602
+ if (join !== void 0) {
603
+ joins.push(join);
604
+ joinFound = true;
605
+ break;
606
+ }
607
+ }
608
+ if (!joinFound) {
609
+ throw new VexError(
610
+ "invalid_dsl",
611
+ `No foreign key relationship found between any previous entity and "${curr.entity.name}". Cannot determine join condition.`
612
+ );
613
+ }
614
+ }
615
+ const fields = [];
616
+ for (const ref of dsl.fields ?? []) {
617
+ const path = typeof ref === "string" ? ref : ref.field;
618
+ if (typeof ref !== "string") assertName(ref.as, "field alias");
619
+ const { resolved } = resolveFieldPath(path, entityLookup, schema);
620
+ fields.push(typeof ref === "string" ? resolved : { ...resolved, outputName: ref.as });
621
+ aliasMap.set(path, `${resolved.alias}.${resolved.column}`);
622
+ }
623
+ let resolvedFilter;
624
+ let semantic;
625
+ const existsMap = /* @__PURE__ */ new Map();
626
+ if (dsl.filter !== void 0) {
627
+ const resolvedPaths = /* @__PURE__ */ new Map();
628
+ collectFilterPaths(dsl.filter, entityLookup, schema, resolvedPaths, existsMap, aliasCounter);
629
+ resolvedFilter = { original: dsl.filter, resolvedPaths };
630
+ for (const [path, res] of resolvedPaths) {
631
+ aliasMap.set(path, `${res.alias}.${res.column}`);
632
+ }
633
+ semantic = extractSemantic(dsl.filter, entityLookup, schema);
634
+ }
635
+ const computes = [];
636
+ if (dsl.compute !== void 0) {
637
+ for (const [name, expr] of Object.entries(dsl.compute)) {
638
+ if (expr !== void 0) {
639
+ assertName(name, "compute name");
640
+ resolveComputePaths(expr, entityLookup, schema, aliasMap, existsMap, aliasCounter);
641
+ computes.push({ name, expression: expr });
642
+ }
643
+ }
644
+ }
645
+ const aggregates = [];
646
+ if (dsl.aggregate !== void 0) {
647
+ for (const [name, expr] of Object.entries(dsl.aggregate)) {
648
+ if (expr !== void 0) {
649
+ assertName(name, "aggregate name");
650
+ resolveAggregatePaths(expr, entityLookup, schema, aliasMap);
651
+ aggregates.push({ name, expression: expr });
652
+ }
653
+ }
654
+ }
655
+ const groupBy = [];
656
+ if (dsl.groupBy !== void 0) {
657
+ for (const path of dsl.groupBy) {
658
+ const { resolved } = resolveFieldPath(path, entityLookup, schema);
659
+ groupBy.push(resolved);
660
+ aliasMap.set(path, `${resolved.alias}.${resolved.column}`);
661
+ }
662
+ }
663
+ const sort = [];
664
+ if (dsl.sort !== void 0) {
665
+ const computeNames = new Set(computes.map((c) => c.name));
666
+ const aggregateNames = new Set(aggregates.map((a) => a.name));
667
+ for (const entry of dsl.sort) {
668
+ const dir = entry.dir ?? "asc";
669
+ if (computeNames.has(entry.field) || aggregateNames.has(entry.field)) {
670
+ sort.push({ field: entry.field, dir });
671
+ } else {
672
+ const { resolved } = resolveFieldPath(entry.field, entityLookup, schema);
673
+ aliasMap.set(entry.field, `${resolved.alias}.${resolved.column}`);
674
+ sort.push({ field: resolved, dir });
675
+ }
676
+ }
677
+ }
678
+ return {
679
+ sources,
680
+ joins,
681
+ fields,
682
+ filter: resolvedFilter,
683
+ semantic,
684
+ computes,
685
+ aggregates,
686
+ groupBy,
687
+ sort,
688
+ limit: dsl.limit,
689
+ distinct: dsl.distinct ?? false,
690
+ aliasMap,
691
+ ...existsMap.size > 0 ? { existsMap } : {}
692
+ };
693
+ };
694
+ var resolveComputePaths = (expr, entityLookup, schema, aliasMap, existsOut, aliasCounter) => {
695
+ const resolveFieldOrValue = (fov) => {
696
+ if (typeof fov === "string" && isFieldPath(fov)) {
697
+ if (!aliasMap.has(fov)) {
698
+ const { resolved } = resolveFieldPath(fov, entityLookup, schema);
699
+ aliasMap.set(fov, `${resolved.alias}.${resolved.column}`);
700
+ }
701
+ }
702
+ };
703
+ if ("add" in expr || "subtract" in expr || "multiply" in expr || "divide" in expr) {
704
+ const pair = "add" in expr ? expr.add : "subtract" in expr ? expr.subtract : "multiply" in expr ? expr.multiply : expr.divide;
705
+ resolveFieldOrValue(pair[0]);
706
+ resolveFieldOrValue(pair[1]);
707
+ return;
708
+ }
709
+ if ("concat" in expr) {
710
+ for (const v of expr.concat) resolveFieldOrValue(v);
711
+ return;
712
+ }
713
+ if ("coalesce" in expr) {
714
+ for (const v of expr.coalesce) resolveFieldOrValue(v);
715
+ return;
716
+ }
717
+ if ("case" in expr) {
718
+ for (const when of expr.case.when) {
719
+ const resolvedPaths = /* @__PURE__ */ new Map();
720
+ collectFilterPaths(when.condition, entityLookup, schema, resolvedPaths, existsOut, aliasCounter);
721
+ for (const [path, res] of resolvedPaths) {
722
+ aliasMap.set(path, `${res.alias}.${res.column}`);
723
+ }
724
+ resolveFieldOrValue(when.then);
725
+ }
726
+ resolveFieldOrValue(expr.case.else);
727
+ }
728
+ };
729
+ var resolveAggregatePaths = (expr, entityLookup, schema, aliasMap) => {
730
+ const arg = "count" in expr ? expr.count : "countDistinct" in expr ? expr.countDistinct : "sum" in expr ? expr.sum : "avg" in expr ? expr.avg : "min" in expr ? expr.min : expr.max;
731
+ if (arg === "*") return;
732
+ if (typeof arg !== "string") {
733
+ resolveComputePaths(arg, entityLookup, schema, aliasMap);
734
+ return;
735
+ }
736
+ if (!aliasMap.has(arg)) {
737
+ const { resolved } = resolveFieldPath(arg, entityLookup, schema);
738
+ aliasMap.set(arg, `${resolved.alias}.${resolved.column}`);
739
+ }
740
+ };
741
+
742
+ // src/engine/analyzer.ts
743
+ var measureNestingDepth = (source) => {
744
+ if (source.subquery === void 0) return 0;
745
+ let maxChild = 0;
746
+ for (const childSource of source.subquery.sources) {
747
+ const childDepth = measureNestingDepth(childSource);
748
+ if (childDepth > maxChild) maxChild = childDepth;
749
+ }
750
+ return 1 + maxChild;
751
+ };
752
+ var getMaxNestingDepth = (resolved) => {
753
+ let max = 0;
754
+ for (const source of resolved.sources) {
755
+ const depth = measureNestingDepth(source);
756
+ if (depth > max) max = depth;
757
+ }
758
+ return max;
759
+ };
760
+ var hasCartesianProduct = (resolved) => {
761
+ const entitySources = resolved.sources.filter((s) => s.entity !== void 0);
762
+ if (entitySources.length <= 1) return false;
763
+ const seenAliases = /* @__PURE__ */ new Set();
764
+ const firstSource = entitySources[0];
765
+ if (firstSource !== void 0) {
766
+ seenAliases.add(firstSource.alias);
767
+ }
768
+ for (let i = 1; i < entitySources.length; i++) {
769
+ const source = entitySources[i];
770
+ if (source === void 0) continue;
771
+ const hasJoin = resolved.joins.some(
772
+ (j) => j.toAlias === source.alias && seenAliases.has(j.fromAlias) || j.fromAlias === source.alias && seenAliases.has(j.toAlias)
773
+ );
774
+ if (!hasJoin) return true;
775
+ seenAliases.add(source.alias);
776
+ }
777
+ return false;
778
+ };
779
+ var findUnindexedFilterColumns = (resolved) => {
780
+ if (resolved.filter === void 0) return [];
781
+ const unindexed = [];
782
+ for (const [path, res] of resolved.filter.resolvedPaths) {
783
+ const source = resolved.sources.find((s) => s.alias === res.alias);
784
+ if (source === void 0 || source.entity === void 0) continue;
785
+ const isIndexed = source.entity.indexes.some(
786
+ (idx) => idx.fields.includes(res.column)
787
+ );
788
+ const isPrimaryKey = source.entity.fields.some(
789
+ (f) => f.name === res.column && f.primaryKey
790
+ );
791
+ if (!isIndexed && !isPrimaryKey) {
792
+ unindexed.push(path);
793
+ }
794
+ }
795
+ return unindexed;
796
+ };
797
+ var hasAggregatesWithoutGroupBy = (resolved) => resolved.aggregates.length > 0 && resolved.groupBy.length === 0;
798
+ var analyze = (resolved, config) => {
799
+ const warnings = [];
800
+ const errors = [];
801
+ const depth = getMaxNestingDepth(resolved);
802
+ if (depth > config.maxNestingDepth) {
803
+ errors.push(
804
+ `Subquery nesting depth ${depth} exceeds maximum allowed depth of ${config.maxNestingDepth}`
805
+ );
806
+ }
807
+ if (config.rejectCartesianProducts && hasCartesianProduct(resolved)) {
808
+ errors.push(
809
+ "Cartesian product detected: multiple sources with no join between them. Add a join or reduce sources."
810
+ );
811
+ }
812
+ const unindexed = findUnindexedFilterColumns(resolved);
813
+ if (unindexed.length > 0) {
814
+ const message = `Unindexed filter columns: ${unindexed.join(", ")}. Consider adding indexes for better performance.`;
815
+ if (config.rejectUnindexedFilters) {
816
+ errors.push(message);
817
+ } else if (config.warnUnindexedFilters) {
818
+ warnings.push(message);
819
+ }
820
+ }
821
+ if (hasAggregatesWithoutGroupBy(resolved)) {
822
+ warnings.push(
823
+ "Aggregate functions used without groupBy. The result will be a single aggregated row."
824
+ );
825
+ }
826
+ if (resolved.semantic !== void 0) {
827
+ const semanticField = resolved.semantic.field;
828
+ const vectorSource = resolved.sources.find(
829
+ (s) => s.alias === semanticField.alias
830
+ );
831
+ if (vectorSource !== void 0 && vectorSource.entity !== void 0) {
832
+ const hasVectorIndex = vectorSource.entity.indexes.some(
833
+ (idx) => idx.fields.includes(semanticField.column) && (idx.type === "hnsw" || idx.type === "ivfflat")
834
+ );
835
+ if (!hasVectorIndex) {
836
+ warnings.push(
837
+ `Vector field "${semanticField.path}" has no HNSW or IVFFlat index. Semantic search may be slow.`
838
+ );
839
+ }
840
+ }
841
+ }
842
+ return { warnings, errors };
843
+ };
844
+
845
+ // src/cache/memory.ts
846
+ var createMemoryCache = () => {
847
+ const store = /* @__PURE__ */ new Map();
848
+ const get = async (key) => {
849
+ return store.get(key);
850
+ };
851
+ const set = async (key, entry) => {
852
+ store.set(key, entry);
853
+ };
854
+ const del = async (key) => {
855
+ store.delete(key);
856
+ };
857
+ const clear = async () => {
858
+ store.clear();
859
+ };
860
+ const keys = async () => {
861
+ return [...store.keys()];
862
+ };
863
+ const entries = async () => {
864
+ return [...store.entries()].map(([key, entry]) => ({ key, entry }));
865
+ };
866
+ return { get, set, delete: del, clear, keys, entries };
867
+ };
868
+ var canonical = (value) => {
869
+ if (Array.isArray(value)) return value.map(canonical);
870
+ if (value !== null && typeof value === "object" && !(value instanceof Date)) {
871
+ const sorted = {};
872
+ for (const [key, inner] of Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) sorted[key] = canonical(inner);
873
+ return sorted;
874
+ }
875
+ return value;
876
+ };
877
+ var canonicalText = (value) => JSON.stringify(canonical(value)) ?? "undefined";
878
+ var hashText = (text) => createHash("sha256").update(text).digest("hex");
879
+ var canonicalHash = (value) => hashText(canonicalText(value));
880
+
881
+ // src/engine/live.ts
882
+ var DEFAULT_TTL_MS = 6e4;
883
+ var DEFAULT_MAX_ENTRIES = 5e3;
884
+ var DEFAULT_MAX_BYTES = 64 * 1024 * 1024;
885
+ var DEFAULT_DEBOUNCE_MS = 10;
886
+ var THRASH_WINDOW_MS = 6e4;
887
+ var THRASH_FLOOR = 100;
888
+ var unref = (timer) => {
889
+ if (typeof timer === "object" && timer !== null && "unref" in timer && typeof timer.unref === "function") timer.unref();
890
+ };
891
+ var createLiveRows = (config = {}, emit = () => {
892
+ }, now = Date.now) => {
893
+ const ttlMs = config.ttlMs ?? DEFAULT_TTL_MS;
894
+ const maxEntries = config.maxEntries ?? DEFAULT_MAX_ENTRIES;
895
+ const maxBytes = config.maxBytes ?? DEFAULT_MAX_BYTES;
896
+ const maxEntryBytes = config.maxEntryBytes ?? Math.floor(maxBytes / 10);
897
+ const debounceMs = config.debounceMs ?? DEFAULT_DEBOUNCE_MS;
898
+ const versions = /* @__PURE__ */ new Map();
899
+ const versionOf = (table) => versions.get(table) ?? 0;
900
+ const snapshot = (tables) => tables.map(versionOf);
901
+ const unchanged = (tables, seen) => tables.every((table, i) => versionOf(table) === seen[i]);
902
+ const stored = /* @__PURE__ */ new Map();
903
+ let bytes = 0;
904
+ const flights = /* @__PURE__ */ new Map();
905
+ const follows = /* @__PURE__ */ new Map();
906
+ const followsByTable = /* @__PURE__ */ new Map();
907
+ const counts = { hits: 0, misses: 0, evictions: 0, oversized: 0, refreshes: 0 };
908
+ const thrash = { start: now(), hits: 0, evictions: 0, warned: 0 };
909
+ const drop = (key) => {
910
+ const entry = stored.get(key);
911
+ if (entry === void 0) return;
912
+ stored.delete(key);
913
+ bytes -= entry.bytes;
914
+ };
915
+ const noteEviction = () => {
916
+ const at = now();
917
+ if (at - thrash.start > THRASH_WINDOW_MS) {
918
+ thrash.start = at;
919
+ thrash.hits = 0;
920
+ thrash.evictions = 0;
921
+ }
922
+ thrash.evictions += 1;
923
+ if (thrash.evictions >= THRASH_FLOOR && thrash.evictions > thrash.hits && at - thrash.warned > THRASH_WINDOW_MS) {
924
+ thrash.warned = at;
925
+ console.warn(
926
+ `[vex:rows] evicting faster than answering (${thrash.evictions} evictions, ${thrash.hits} hits this minute) \u2014 raise the engine's rows.maxBytes / rows.maxEntries.`
927
+ );
928
+ }
929
+ };
930
+ const store = (key, rows, tables, seen) => {
931
+ drop(key);
932
+ const size = (JSON.stringify(rows) ?? "").length;
933
+ if (size > maxEntryBytes) {
934
+ counts.oversized += 1;
935
+ emit({ type: "rows.evict", reason: "oversized", bytes: size });
936
+ return;
937
+ }
938
+ stored.set(key, { rows, bytes: size, tables, seen, at: now() });
939
+ bytes += size;
940
+ while (stored.size > maxEntries || bytes > maxBytes) {
941
+ const oldest = stored.keys().next();
942
+ if (oldest.done === true) break;
943
+ const evicted = stored.get(oldest.value);
944
+ drop(oldest.value);
945
+ counts.evictions += 1;
946
+ emit({ type: "rows.evict", reason: "capacity", bytes: evicted?.bytes ?? 0 });
947
+ noteEviction();
948
+ }
949
+ };
950
+ const read = (key, source) => {
951
+ const hit = stored.get(key);
952
+ if (hit !== void 0) {
953
+ if (now() - hit.at < ttlMs && unchanged(hit.tables, hit.seen)) {
954
+ stored.delete(key);
955
+ stored.set(key, hit);
956
+ counts.hits += 1;
957
+ thrash.hits += 1;
958
+ return Promise.resolve(hit.rows);
959
+ }
960
+ drop(key);
961
+ }
962
+ counts.misses += 1;
963
+ const flight = flights.get(key);
964
+ if (flight !== void 0 && unchanged(flight.tables, flight.seen)) return flight.promise;
965
+ const seen = snapshot(source.tables);
966
+ const promise = source.fetch().then((rows) => {
967
+ store(key, rows, source.tables, seen);
968
+ return rows;
969
+ });
970
+ const entry = { promise, tables: source.tables, seen };
971
+ flights.set(key, entry);
972
+ const settle = () => {
973
+ if (flights.get(key) === entry) flights.delete(key);
974
+ };
975
+ promise.then(settle, settle);
976
+ return promise;
977
+ };
978
+ const dirty = /* @__PURE__ */ new Set();
979
+ let flushTimer;
980
+ const schedule = (key) => {
981
+ dirty.add(key);
982
+ if (flushTimer !== void 0) return;
983
+ flushTimer = setTimeout(() => {
984
+ flushTimer = void 0;
985
+ const keys = [...dirty];
986
+ dirty.clear();
987
+ for (const next of keys) void refresh(next, false);
988
+ }, debounceMs);
989
+ unref(flushTimer);
990
+ };
991
+ const arm = (key, follow2) => {
992
+ if (follow2.timer !== void 0) clearTimeout(follow2.timer);
993
+ if (!Number.isFinite(ttlMs)) return;
994
+ follow2.timer = setTimeout(() => void refresh(key, true), ttlMs);
995
+ unref(follow2.timer);
996
+ };
997
+ const refresh = async (key, bypass) => {
998
+ const follow2 = follows.get(key);
999
+ if (follow2 === void 0) return;
1000
+ follow2.issued += 1;
1001
+ const ticket = follow2.issued;
1002
+ if (bypass) drop(key);
1003
+ let rows;
1004
+ try {
1005
+ rows = await read(key, follow2.source);
1006
+ } catch (err) {
1007
+ emit({ type: "rows.error", message: err instanceof Error ? err.message : String(err) });
1008
+ if (follows.get(key) === follow2) arm(key, follow2);
1009
+ return;
1010
+ }
1011
+ if (follows.get(key) !== follow2 || ticket < follow2.landed) return;
1012
+ follow2.landed = ticket;
1013
+ counts.refreshes += 1;
1014
+ arm(key, follow2);
1015
+ const rowsHash = hashText(JSON.stringify(rows) ?? "");
1016
+ if (rowsHash === follow2.rowsHash) return;
1017
+ follow2.rowsHash = rowsHash;
1018
+ for (const follower of [...follow2.followers]) {
1019
+ try {
1020
+ follower.deliver(rows);
1021
+ } catch (err) {
1022
+ emit({ type: "rows.error", message: err instanceof Error ? err.message : String(err) });
1023
+ }
1024
+ }
1025
+ };
1026
+ const unfollow = (key, follower) => {
1027
+ const follow2 = follows.get(key);
1028
+ if (follow2 === void 0) return;
1029
+ follow2.followers.delete(follower);
1030
+ if (follow2.followers.size > 0) return;
1031
+ follows.delete(key);
1032
+ dirty.delete(key);
1033
+ if (follow2.timer !== void 0) clearTimeout(follow2.timer);
1034
+ for (const table of follow2.source.tables) {
1035
+ const keys = followsByTable.get(table);
1036
+ keys?.delete(key);
1037
+ if (keys !== void 0 && keys.size === 0) followsByTable.delete(table);
1038
+ }
1039
+ };
1040
+ const follow = (key, source, rows, follower, signal) => {
1041
+ if (signal.aborted) return;
1042
+ let existing = follows.get(key);
1043
+ if (existing === void 0) {
1044
+ existing = { source, followers: /* @__PURE__ */ new Set(), rowsHash: hashText(JSON.stringify(rows) ?? ""), issued: 0, landed: 0 };
1045
+ follows.set(key, existing);
1046
+ for (const table of source.tables) {
1047
+ let keys = followsByTable.get(table);
1048
+ if (keys === void 0) {
1049
+ keys = /* @__PURE__ */ new Set();
1050
+ followsByTable.set(table, keys);
1051
+ }
1052
+ keys.add(key);
1053
+ }
1054
+ arm(key, existing);
1055
+ }
1056
+ existing.followers.add(follower);
1057
+ signal.addEventListener("abort", () => unfollow(key, follower), { once: true });
1058
+ };
1059
+ const invalidate = (tables) => {
1060
+ for (const table of tables) versions.set(table, versionOf(table) + 1);
1061
+ for (const table of tables) {
1062
+ for (const key of followsByTable.get(table) ?? []) schedule(key);
1063
+ }
1064
+ };
1065
+ const stats = () => {
1066
+ let followers = 0;
1067
+ for (const entry of follows.values()) followers += entry.followers.size;
1068
+ return { entries: stored.size, bytes, follows: follows.size, followers, ...counts };
1069
+ };
1070
+ const stop = () => {
1071
+ if (flushTimer !== void 0) clearTimeout(flushTimer);
1072
+ flushTimer = void 0;
1073
+ for (const entry of follows.values()) if (entry.timer !== void 0) clearTimeout(entry.timer);
1074
+ };
1075
+ return { read, follow, invalidate, stats, stop };
1076
+ };
1077
+ var applySortContext = (dsl, context) => {
1078
+ const sortBy = context["sortBy"];
1079
+ if (typeof sortBy !== "string" || sortBy === "") return dsl;
1080
+ const dir = context["sortDir"] === "desc" ? "desc" : "asc";
1081
+ const tiebreakers = (dsl.sort ?? []).filter((entry) => entry.field !== sortBy);
1082
+ return { ...dsl, sort: [{ field: sortBy, dir }, ...tiebreakers] };
1083
+ };
1084
+ var DEFAULT_MAX_NESTING_DEPTH = 2;
1085
+ var DEFAULT_LIMIT = 100;
1086
+ var DEFAULT_MAX_LIMIT = 1e3;
1087
+ var DEFAULT_STATEMENT_TIMEOUT_MS = 1e4;
1088
+ var DEFAULT_UNSATISFIABLE_TTL_MS = 3e5;
1089
+ var DEFAULT_MAX_PRESENCE_VARIANTS = 32;
1090
+ var createQueryEngine = (engineConfig) => {
1091
+ const { adapter, scope: scopePolicy, generateDsl, mapToShape, embed, behaviors } = engineConfig;
1092
+ const emit = engineConfig.onEvent ?? (() => {
1093
+ });
1094
+ const maxNestingDepth = engineConfig.config?.maxNestingDepth ?? DEFAULT_MAX_NESTING_DEPTH;
1095
+ const defaultLimit = engineConfig.config?.defaultLimit ?? DEFAULT_LIMIT;
1096
+ const maxLimit = engineConfig.config?.maxLimit ?? DEFAULT_MAX_LIMIT;
1097
+ const rejectCartesianProducts = engineConfig.config?.rejectCartesianProducts ?? true;
1098
+ const warnUnindexedFilters = engineConfig.config?.warnUnindexedFilters ?? true;
1099
+ const rejectUnindexedFilters = engineConfig.config?.rejectUnindexedFilters ?? false;
1100
+ const unsatisfiableTtlMs = engineConfig.config?.unsatisfiableTtlMs ?? DEFAULT_UNSATISFIABLE_TTL_MS;
1101
+ const analysisConfig = {
1102
+ maxNestingDepth,
1103
+ rejectCartesianProducts,
1104
+ warnUnindexedFilters,
1105
+ rejectUnindexedFilters
1106
+ };
1107
+ const live = createLiveRows(engineConfig.rows, emit);
1108
+ let cachedSchema;
1109
+ let cachedFingerprint;
1110
+ const cache = engineConfig.cache ?? createMemoryCache();
1111
+ const variantsSeen = /* @__PURE__ */ new Map();
1112
+ const maxPresenceVariants = engineConfig.config?.maxPresenceVariants ?? DEFAULT_MAX_PRESENCE_VARIANTS;
1113
+ const noteVariant = (fingerprint, signature, warnings) => {
1114
+ if (fingerprint === void 0 || signature === "") return;
1115
+ let seen = variantsSeen.get(fingerprint);
1116
+ if (seen === void 0) {
1117
+ seen = /* @__PURE__ */ new Set();
1118
+ variantsSeen.set(fingerprint, seen);
1119
+ }
1120
+ if (seen.has(signature)) return;
1121
+ seen.add(signature);
1122
+ if (seen.size > maxPresenceVariants) {
1123
+ warnings.push(
1124
+ `"${fingerprint}" has now compiled ${seen.size} distinct optional-key combinations (limit ${maxPresenceVariants}). An entry answering this many shapes is closer to a query builder than to a question \u2014 consider splitting it.`
1125
+ );
1126
+ }
1127
+ };
1128
+ const inFlight = /* @__PURE__ */ new Map();
1129
+ const introspect = async () => {
1130
+ const options = engineConfig.config?.entities !== void 0 ? { entities: engineConfig.config.entities } : void 0;
1131
+ const schema = await adapter.introspect(options);
1132
+ const readLimit = engineConfig.config?.statementTimeoutMs ?? DEFAULT_STATEMENT_TIMEOUT_MS;
1133
+ if (adapter.limitReads !== void 0 && await adapter.limitReads(readLimit) === "unenforced" && readLimit > 0) {
1134
+ console.warn(`[vex] reads are not bounded: this database cannot enforce statement_timeout (${readLimit}ms asked). Fine for development; production wants Postgres.`);
1135
+ }
1136
+ if (behaviors !== void 0) {
1137
+ const missing = behaviorColumns(behaviors).filter(({ entity, field }) => !schema.entities.some((e) => e.name === entity && e.fields.some((f) => f.name === field)));
1138
+ if (missing.length > 0) {
1139
+ throw new VexError("execution_error", `The behaviors name columns the database does not have: ${missing.map((m) => `${m.entity}.${m.field}`).join(", ")}.`);
1140
+ }
1141
+ }
1142
+ cachedSchema = schema;
1143
+ cachedFingerprint = computeSchemaFingerprint(schema);
1144
+ return schema;
1145
+ };
1146
+ const ensureSchema = () => {
1147
+ if (cachedSchema === void 0) {
1148
+ throw new VexError(
1149
+ "execution_error",
1150
+ "Database schema not loaded. Call introspect() first."
1151
+ );
1152
+ }
1153
+ return cachedSchema;
1154
+ };
1155
+ const runPipeline = (dsl, policyOverride) => {
1156
+ const schema = ensureSchema();
1157
+ let processedDsl = dsl;
1158
+ if (processedDsl.limit === void 0) {
1159
+ processedDsl = { ...processedDsl, limit: defaultLimit };
1160
+ } else if (processedDsl.limit > maxLimit) {
1161
+ processedDsl = { ...processedDsl, limit: maxLimit };
1162
+ }
1163
+ const entities = discoverEntities(processedDsl);
1164
+ const activePolicy = policyOverride ?? scopePolicy;
1165
+ if (activePolicy !== void 0) checkScope(entities, activePolicy);
1166
+ const resolved = resolve(processedDsl, schema);
1167
+ if (activePolicy !== void 0) scopeResolved(resolved, activePolicy);
1168
+ const analysis = analyze(resolved, analysisConfig);
1169
+ if (analysis.errors.length > 0) {
1170
+ throw new VexError(
1171
+ "invalid_dsl",
1172
+ `Analysis failed: ${analysis.errors.join("; ")}`,
1173
+ { errors: analysis.errors, warnings: analysis.warnings }
1174
+ );
1175
+ }
1176
+ const compiled = adapter.compile(resolved);
1177
+ return { compiled, warnings: analysis.warnings };
1178
+ };
1179
+ const compile2 = (dsl) => runPipeline(pruneOptional(dsl, "all")).compiled;
1180
+ const test = async (dsl, scopeValues) => {
1181
+ try {
1182
+ const testDsl = { ...pruneOptional(dsl, "all"), limit: 5 };
1183
+ const { compiled, warnings } = runPipeline(testDsl);
1184
+ const syntheticContext = buildValidationContext(compiled.contextContract);
1185
+ const scope = scopeValues ?? {};
1186
+ requireScope(compiled, scope);
1187
+ const rows = await executeQuery(compiled, syntheticContext, scope, adapter, embed);
1188
+ return { rows, warnings, errors: [] };
1189
+ } catch (err) {
1190
+ const message = err instanceof Error ? err.message : String(err);
1191
+ return { rows: [], warnings: [], errors: [message] };
1192
+ }
1193
+ };
1194
+ const freshOrEvict = (entry, key) => {
1195
+ if (isEntryFresh(entry, cachedFingerprint)) return true;
1196
+ void cache.delete(key);
1197
+ return false;
1198
+ };
1199
+ const touch = (key, entry) => {
1200
+ const now = Date.now();
1201
+ if (isTouchDue(entry, now)) fireAndForget(cache.set(key, { ...entry, lastUsedAt: now }));
1202
+ };
1203
+ const resolveFingerprint = async (validRequest, hasRequest, requestHash) => {
1204
+ const fp = validRequest.fingerprint;
1205
+ if (fp === void 0) {
1206
+ return { fingerprint: mintFingerprint(), hit: false, replaced: false };
1207
+ }
1208
+ const entry = await cache.get(fp);
1209
+ if (entry?.kind === "mutation") {
1210
+ throw new VexError(
1211
+ "invalid_request",
1212
+ `Fingerprint "${fp}" names a mutation \u2014 the query engine cannot execute writes. Replay it through the vex endpoint.`
1213
+ );
1214
+ }
1215
+ if (entry?.kind === "ok" && freshOrEvict(entry, fp)) {
1216
+ if (!hasRequest || entry.requestHash === requestHash) {
1217
+ touch(fp, entry);
1218
+ return {
1219
+ fingerprint: fp,
1220
+ dsl: entry.dsl,
1221
+ ...entry.prismIr !== void 0 ? { cachedIr: entry.prismIr } : {},
1222
+ ...entry.intent !== void 0 ? { intent: entry.intent } : {},
1223
+ ...entry.shape !== void 0 ? { shape: entry.shape } : {},
1224
+ ...entry.refresh !== void 0 ? { refresh: entry.refresh } : {},
1225
+ hit: true,
1226
+ replaced: false
1227
+ };
1228
+ }
1229
+ if (entry.protected === true) {
1230
+ throw new VexError(
1231
+ "fingerprint_protected",
1232
+ `Fingerprint "${fp}" is protected and this request no longer matches its stored one. Replay it with the fingerprint alone, or use a new name.`
1233
+ );
1234
+ }
1235
+ return { fingerprint: fp, hit: false, replaced: true };
1236
+ }
1237
+ if (!hasRequest) {
1238
+ throw new VexError("cache_miss", `Unknown fingerprint "${fp}" \u2014 pass intent + shape to (re)generate it.`);
1239
+ }
1240
+ return { fingerprint: fp, hit: false, replaced: false };
1241
+ };
1242
+ const callerOf = (policy, scope, tables) => ({
1243
+ bindings: scopeBindings(behaviors ?? {}, tables, scope),
1244
+ read: async (dsl) => {
1245
+ const { compiled, warnings } = runPipeline(pruneOptional(dsl, "all"), policy);
1246
+ requireScope(compiled, scope);
1247
+ if (compiled.paramSlots.some((slot) => slot.kind === "semantic")) {
1248
+ return { rows: [], sql: compiled.sql, warnings: [...warnings, "Semantic params present \u2014 execution skipped, SQL structure validated only"] };
1249
+ }
1250
+ const params = compiled.paramSlots.map((slot) => slot.kind === "scope" ? scope[slot.key] : null);
1251
+ return { rows: await adapter.execute(compiled, params), sql: compiled.sql, warnings };
1252
+ }
1253
+ });
1254
+ const generateMissingDsl = async (validRequest, flightKey, negKey, entities, policy, scope) => {
1255
+ if (generateDsl === void 0) {
1256
+ throw new VexError("agent_failed", "No query generation function available and no cached query found");
1257
+ }
1258
+ const fullSchema = ensureSchema();
1259
+ const agentSchema = {
1260
+ ...fullSchema,
1261
+ entities: fullSchema.entities.filter(
1262
+ (e) => (entities === void 0 || entities.includes(e.name)) && (policy === void 0 || canReadTable(policy, e.name))
1263
+ )
1264
+ };
1265
+ const generate = async () => {
1266
+ try {
1267
+ return await generateDsl(validRequest, agentSchema, callerOf(policy, scope, agentSchema.entities.map((e) => e.name)));
1268
+ } catch (err) {
1269
+ if (err instanceof VexError && err.code === "unsatisfiable") {
1270
+ const now = Date.now();
1271
+ await cache.set(negKey, {
1272
+ kind: "unsatisfiable",
1273
+ reason: err.message,
1274
+ createdAt: now,
1275
+ expiresAt: now + unsatisfiableTtlMs,
1276
+ ...validRequest.intent !== void 0 ? { intent: validRequest.intent } : {},
1277
+ shape: validRequest.shape,
1278
+ ...cachedFingerprint !== void 0 ? { schemaFingerprint: cachedFingerprint } : {}
1279
+ });
1280
+ }
1281
+ throw err;
1282
+ }
1283
+ };
1284
+ const existing = inFlight.get(flightKey);
1285
+ if (existing !== void 0) return existing;
1286
+ const generation = generate();
1287
+ inFlight.set(flightKey, generation);
1288
+ try {
1289
+ return await generation;
1290
+ } finally {
1291
+ inFlight.delete(flightKey);
1292
+ }
1293
+ };
1294
+ const mapRows = (rows, shape, ir, context, scope) => {
1295
+ const single = !Array.isArray(shape);
1296
+ const source = {
1297
+ result: single ? rows[0] ?? null : rows,
1298
+ context,
1299
+ scope
1300
+ };
1301
+ return execute(ir, source);
1302
+ };
1303
+ const executeAndMap = async (compiled, validRequest, cachedIr, context, scope) => {
1304
+ const execStart = Date.now();
1305
+ const rows = await executeQuery(compiled, context, scope, adapter, embed);
1306
+ const executionMs = Date.now() - execStart;
1307
+ emit({ type: "query.rows", count: rows.length, executionMs });
1308
+ let result = rows;
1309
+ let mappingMs;
1310
+ let mappedIr = cachedIr;
1311
+ if (validRequest.shape !== void 0) {
1312
+ if (cachedIr !== void 0) {
1313
+ const mapStart = Date.now();
1314
+ result = mapRows(rows, validRequest.shape, cachedIr, context, scope);
1315
+ mappingMs = Date.now() - mapStart;
1316
+ } else if (mapToShape !== void 0) {
1317
+ const mapStart = Date.now();
1318
+ const mapped = await mapToShape(rows, validRequest.shape);
1319
+ mappingMs = Date.now() - mapStart;
1320
+ result = mapped.transformed;
1321
+ mappedIr = mapped.ir;
1322
+ }
1323
+ if (mappingMs !== void 0) emit({ type: "query.mapped", mappingMs });
1324
+ }
1325
+ return { result, executionMs, mappingMs, mappedIr };
1326
+ };
1327
+ const execute$1 = async (request, options) => {
1328
+ if (exceedsDepth(request)) throw new VexError("invalid_request", `Invalid request: ${depthRefusal()}`);
1329
+ const parsed = QueryRequestSchema.safeParse(request);
1330
+ if (!parsed.success) {
1331
+ throw new VexError("invalid_request", `Invalid request: ${parsed.error.message}`);
1332
+ }
1333
+ const validRequest = parsed.data;
1334
+ const scope = options?.scope ?? {};
1335
+ const activePolicy = options?.scopePolicy ?? scopePolicy;
1336
+ const t0 = Date.now();
1337
+ const hasRequest = validRequest.shape !== void 0 && validRequest.shape !== null;
1338
+ if (validRequest.fingerprint === void 0 && !hasRequest) {
1339
+ throw new VexError("invalid_request", "Pass a fingerprint (replay) or intent + shape (generate) \u2014 or both (named slot).");
1340
+ }
1341
+ const requestHash = hasRequest ? computeRequestHash(validRequest) : void 0;
1342
+ const flightKey = requestHash !== void 0 ? `${requestHash}:${computePolicyKey(activePolicy)}` : void 0;
1343
+ const negKey = flightKey !== void 0 ? `neg:${flightKey}` : void 0;
1344
+ emit({
1345
+ type: "query.start",
1346
+ intent: validRequest.intent,
1347
+ shape: validRequest.shape,
1348
+ fingerprint: validRequest.fingerprint,
1349
+ entities: options?.entities
1350
+ });
1351
+ const cached = await resolveFingerprint(validRequest, hasRequest, requestHash);
1352
+ emit({ type: "query.cache", hit: cached.hit, fingerprint: cached.fingerprint, replaced: cached.replaced });
1353
+ let dsl = cached.dsl;
1354
+ let agentMs;
1355
+ if (dsl === void 0) {
1356
+ if (options?.locked === true) {
1357
+ throw new VexError("locked", "This endpoint is replay-only \u2014 unknown or changed fingerprints cannot generate here.");
1358
+ }
1359
+ if (flightKey === void 0 || negKey === void 0) {
1360
+ throw new VexError("invalid_request", "Generation needs intent + shape.");
1361
+ }
1362
+ const negative = await cache.get(negKey);
1363
+ if (negative?.kind === "unsatisfiable" && freshOrEvict(negative, negKey)) {
1364
+ emit({ type: "query.error", code: "unsatisfiable", message: negative.reason });
1365
+ throw new VexError("unsatisfiable", negative.reason);
1366
+ }
1367
+ const agentStart = Date.now();
1368
+ dsl = await generateMissingDsl(validRequest, flightKey, negKey, options?.entities, activePolicy, scope);
1369
+ agentMs = Date.now() - agentStart;
1370
+ emit({ type: "query.dsl", dsl, agentMs });
1371
+ }
1372
+ const presence = presenceOf(validRequest.context);
1373
+ const shaped = pruneOptional(applySortContext(dsl, validRequest.context), presence);
1374
+ const { compiled, warnings } = runPipeline(shaped, activePolicy);
1375
+ noteVariant(cached.fingerprint, presenceSignature(dsl, presence), warnings);
1376
+ emit({ type: "query.sql", sql: compiled.sql, warnings });
1377
+ requireScope(compiled, scope);
1378
+ const context = validRequest.context;
1379
+ const missingKeys = findMissingContext(compiled, context);
1380
+ if (missingKeys.length > 0) {
1381
+ return {
1382
+ result: [],
1383
+ meta: {
1384
+ cache: {
1385
+ hit: cached.hit,
1386
+ fingerprint: cached.fingerprint,
1387
+ intent: cached.intent ?? validRequest.intent,
1388
+ ...cached.replaced ? { replaced: true } : {}
1389
+ },
1390
+ context: buildContextContract(compiled, optionalKeysOf(dsl)),
1391
+ warnings: warnings.length > 0 ? warnings : void 0,
1392
+ missingContext: missingKeys
1393
+ }
1394
+ };
1395
+ }
1396
+ const effectiveRequest = hasRequest ? validRequest : { ...validRequest, shape: cached.shape };
1397
+ const reactiveIr = cached.cachedIr;
1398
+ if (cached.hit && cached.refresh === "reactive" && (effectiveRequest.shape === void 0 || reactiveIr !== void 0)) {
1399
+ const shape = effectiveRequest.shape;
1400
+ const shapeRows = (rows2) => shape === void 0 || reactiveIr === void 0 ? rows2 : mapRows(rows2, shape, reactiveIr, context, scope);
1401
+ const params = await resolveParams(compiled.paramSlots, context, scope, embed);
1402
+ const key = canonicalHash([compiled.sql, params]);
1403
+ const source = { tables: [...discoverEntities(shaped)], fetch: () => adapter.execute(compiled, params) };
1404
+ const execStart = Date.now();
1405
+ const rows = await live.read(key, source);
1406
+ const executionMs2 = Date.now() - execStart;
1407
+ emit({ type: "query.rows", count: rows.length, executionMs: executionMs2 });
1408
+ const result2 = shapeRows(rows);
1409
+ const meta = {
1410
+ cache: {
1411
+ hit: cached.hit,
1412
+ fingerprint: cached.fingerprint,
1413
+ intent: cached.intent ?? validRequest.intent
1414
+ },
1415
+ context: buildContextContract(compiled, optionalKeysOf(dsl)),
1416
+ warnings: warnings.length > 0 ? warnings : void 0
1417
+ };
1418
+ const { signal, onChange } = options ?? {};
1419
+ if (signal !== void 0 && onChange !== void 0) {
1420
+ let lastHash = canonicalHash(result2);
1421
+ live.follow(key, source, rows, {
1422
+ deliver: (next) => {
1423
+ const nextResult = shapeRows(next);
1424
+ const nextHash = canonicalHash(nextResult);
1425
+ if (nextHash === lastHash) return;
1426
+ lastHash = nextHash;
1427
+ onChange({ result: nextResult, meta });
1428
+ }
1429
+ }, signal);
1430
+ }
1431
+ emit({ type: "query.done", totalMs: Date.now() - t0 });
1432
+ return { result: result2, meta: { ...meta, timing: { executionMs: executionMs2 } } };
1433
+ }
1434
+ const { result, executionMs, mappingMs, mappedIr } = await executeAndMap(
1435
+ compiled,
1436
+ effectiveRequest,
1437
+ cached.cachedIr,
1438
+ context,
1439
+ scope
1440
+ );
1441
+ if (!cached.hit) {
1442
+ const now = Date.now();
1443
+ const entry = {
1444
+ kind: "ok",
1445
+ dsl,
1446
+ ...mappedIr !== void 0 ? { prismIr: mappedIr } : {},
1447
+ createdAt: now,
1448
+ lastUsedAt: now,
1449
+ ...requestHash !== void 0 ? { requestHash } : {},
1450
+ ...validRequest.intent !== void 0 ? { intent: validRequest.intent } : {},
1451
+ shape: validRequest.shape,
1452
+ ...cachedFingerprint !== void 0 ? { schemaFingerprint: cachedFingerprint } : {}
1453
+ };
1454
+ await cache.set(cached.fingerprint, entry);
1455
+ }
1456
+ emit({ type: "query.done", totalMs: Date.now() - t0 });
1457
+ return {
1458
+ result,
1459
+ meta: {
1460
+ cache: {
1461
+ hit: cached.hit,
1462
+ fingerprint: cached.fingerprint,
1463
+ intent: cached.intent ?? validRequest.intent,
1464
+ ...cached.replaced ? { replaced: true } : {}
1465
+ },
1466
+ context: buildContextContract(compiled, optionalKeysOf(dsl)),
1467
+ timing: {
1468
+ ...agentMs !== void 0 ? { agentMs } : {},
1469
+ executionMs,
1470
+ ...mappingMs !== void 0 ? { mappingMs } : {}
1471
+ },
1472
+ warnings: warnings.length > 0 ? warnings : void 0
1473
+ }
1474
+ };
1475
+ };
1476
+ const getDslSchema = () => z.toJSONSchema(QuerySchema, { target: "draft-7", reused: "ref" });
1477
+ const getSchema = () => cachedSchema;
1478
+ return {
1479
+ introspect,
1480
+ execute: execute$1,
1481
+ compile: compile2,
1482
+ test,
1483
+ getDslSchema,
1484
+ getSchema,
1485
+ cache,
1486
+ invalidate: live.invalidate,
1487
+ rows: { stats: live.stats, stop: live.stop }
1488
+ };
1489
+ };
1490
+
1491
+ // src/adapters/postgres/introspect.ts
1492
+ var normalizeType = (pgType) => {
1493
+ const lower = pgType.toLowerCase();
1494
+ if (lower.startsWith("varchar") || lower.startsWith("character varying") || lower === "text" || lower.startsWith("char") || lower === "name" || lower === "citext") {
1495
+ return "string";
1496
+ }
1497
+ if (lower === "integer" || lower === "int" || lower === "bigint" || lower === "smallint" || lower === "serial" || lower === "bigserial" || lower === "smallserial" || lower === "numeric" || lower.startsWith("numeric") || lower === "decimal" || lower.startsWith("decimal") || lower === "real" || lower === "double precision" || lower === "float" || lower.startsWith("float")) {
1498
+ return "number";
1499
+ }
1500
+ if (lower === "boolean" || lower === "bool") return "boolean";
1501
+ if (lower === "date") return "date";
1502
+ if (lower.startsWith("timestamp")) return "timestamp";
1503
+ if (lower === "uuid") return "uuid";
1504
+ if (lower === "json" || lower === "jsonb") return "json";
1505
+ if (lower === "array" || lower.endsWith("[]") || lower.startsWith("_")) return "array";
1506
+ if (lower === "vector" || lower.startsWith("vector")) return "vector";
1507
+ return "unknown";
1508
+ };
1509
+ var extractVectorDimensions = (pgType) => {
1510
+ const match = /vector\((\d+)\)/i.exec(pgType);
1511
+ if (match !== null && match[1] !== void 0) {
1512
+ return parseInt(match[1], 10);
1513
+ }
1514
+ return void 0;
1515
+ };
1516
+ var TABLES_QUERY = `
1517
+ SELECT t.table_name, obj_description(cl.oid, 'pg_class') AS description
1518
+ FROM information_schema.tables t
1519
+ JOIN pg_namespace ns ON ns.nspname = t.table_schema
1520
+ JOIN pg_class cl ON cl.relname = t.table_name AND cl.relnamespace = ns.oid
1521
+ WHERE t.table_schema = $1
1522
+ AND t.table_type = 'BASE TABLE'
1523
+ ORDER BY t.table_name
1524
+ `;
1525
+ var COLUMNS_QUERY = `
1526
+ SELECT
1527
+ c.table_name,
1528
+ c.column_name,
1529
+ c.data_type,
1530
+ c.udt_name,
1531
+ c.is_nullable,
1532
+ c.column_default,
1533
+ CASE
1534
+ WHEN c.data_type = 'USER-DEFINED' THEN c.udt_name
1535
+ WHEN c.data_type = 'ARRAY' THEN c.udt_name
1536
+ ELSE c.data_type
1537
+ END AS effective_type,
1538
+ COALESCE(
1539
+ (SELECT format_type(a.atttypid, a.atttypmod)
1540
+ FROM pg_attribute a
1541
+ JOIN pg_class cl ON a.attrelid = cl.oid
1542
+ JOIN pg_namespace ns ON cl.relnamespace = ns.oid
1543
+ WHERE cl.relname = c.table_name
1544
+ AND ns.nspname = $1
1545
+ AND a.attname = c.column_name
1546
+ AND a.attnum > 0),
1547
+ c.data_type
1548
+ ) AS full_type,
1549
+ (SELECT col_description(a.attrelid, a.attnum)
1550
+ FROM pg_attribute a
1551
+ JOIN pg_class cl ON a.attrelid = cl.oid
1552
+ JOIN pg_namespace ns ON cl.relnamespace = ns.oid
1553
+ WHERE cl.relname = c.table_name
1554
+ AND ns.nspname = $1
1555
+ AND a.attname = c.column_name
1556
+ AND a.attnum > 0) AS description
1557
+ FROM information_schema.columns c
1558
+ WHERE c.table_schema = $1
1559
+ ORDER BY c.table_name, c.ordinal_position
1560
+ `;
1561
+ var CONSTRAINTS_QUERY = `
1562
+ SELECT
1563
+ c.contype::text AS kind,
1564
+ rel.relname AS from_table,
1565
+ frel.relname AS to_table,
1566
+ array_agg(a.attname ORDER BY k.n)::text[] AS from_columns,
1567
+ array_agg(fa.attname ORDER BY k.n)::text[] AS to_columns
1568
+ FROM pg_constraint c
1569
+ JOIN pg_class rel ON rel.oid = c.conrelid
1570
+ JOIN pg_namespace ns ON ns.oid = rel.relnamespace
1571
+ LEFT JOIN pg_class frel ON frel.oid = c.confrelid AND frel.relnamespace = rel.relnamespace
1572
+ CROSS JOIN LATERAL unnest(c.conkey, c.confkey) WITH ORDINALITY AS k(attnum, fattnum, n)
1573
+ JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = k.attnum
1574
+ LEFT JOIN pg_attribute fa ON fa.attrelid = c.confrelid AND fa.attnum = k.fattnum
1575
+ WHERE ns.nspname = $1
1576
+ AND c.contype IN ('p', 'u', 'f')
1577
+ GROUP BY c.oid, c.contype, rel.relname, frel.relname
1578
+ ORDER BY c.oid
1579
+ `;
1580
+ var INDEXES_QUERY = `
1581
+ SELECT
1582
+ i.tablename AS table_name,
1583
+ i.indexname AS index_name,
1584
+ ix.indisunique AS is_unique,
1585
+ am.amname AS index_type,
1586
+ array_agg(a.attname ORDER BY k.n)::text[] AS columns
1587
+ FROM pg_indexes i
1588
+ JOIN pg_class c ON c.relname = i.indexname
1589
+ JOIN pg_index ix ON ix.indexrelid = c.oid
1590
+ JOIN pg_am am ON am.oid = c.relam
1591
+ CROSS JOIN LATERAL unnest(ix.indkey) WITH ORDINALITY AS k(attnum, n)
1592
+ JOIN pg_attribute a ON a.attrelid = ix.indrelid AND a.attnum = k.attnum
1593
+ WHERE i.schemaname = $1
1594
+ GROUP BY i.tablename, i.indexname, ix.indisunique, am.amname
1595
+ ORDER BY i.tablename, i.indexname
1596
+ `;
1597
+ var ROW_COUNTS_QUERY = `
1598
+ SELECT
1599
+ relname AS table_name,
1600
+ n_live_tup AS row_count
1601
+ FROM pg_stat_user_tables
1602
+ WHERE schemaname = $1
1603
+ `;
1604
+ var introspectPostgres = async (pool, options) => {
1605
+ const schemaName = options?.schema ?? "public";
1606
+ const [tablesResult, columnsResult, keysResult, indexesResult, rowCountsResult] = await Promise.all([
1607
+ pool.query(TABLES_QUERY, [schemaName]),
1608
+ pool.query(COLUMNS_QUERY, [schemaName]),
1609
+ pool.query(CONSTRAINTS_QUERY, [schemaName]),
1610
+ pool.query(INDEXES_QUERY, [schemaName]),
1611
+ pool.query(ROW_COUNTS_QUERY, [schemaName])
1612
+ ]);
1613
+ const keys = keysResult.rows.map((row) => ({
1614
+ kind: row["kind"],
1615
+ fromTable: row["from_table"],
1616
+ toTable: row["to_table"] ?? null,
1617
+ fromColumns: row["from_columns"],
1618
+ toColumns: row["to_columns"]
1619
+ }));
1620
+ const pkMap = /* @__PURE__ */ new Map();
1621
+ const uniqueSets = /* @__PURE__ */ new Map();
1622
+ for (const key of keys) {
1623
+ if (key.kind === "f") continue;
1624
+ if (key.kind === "p") {
1625
+ let cols = pkMap.get(key.fromTable);
1626
+ if (cols === void 0) {
1627
+ cols = /* @__PURE__ */ new Set();
1628
+ pkMap.set(key.fromTable, cols);
1629
+ }
1630
+ for (const col of key.fromColumns) cols.add(col);
1631
+ }
1632
+ let sets = uniqueSets.get(key.fromTable);
1633
+ if (sets === void 0) {
1634
+ sets = [];
1635
+ uniqueSets.set(key.fromTable, sets);
1636
+ }
1637
+ sets.push(key.fromColumns);
1638
+ }
1639
+ const rowCountMap = /* @__PURE__ */ new Map();
1640
+ for (const row of rowCountsResult.rows) {
1641
+ const table = row["table_name"];
1642
+ const count = Number(row["row_count"] ?? 0);
1643
+ rowCountMap.set(table, count);
1644
+ }
1645
+ const columnsByTable = /* @__PURE__ */ new Map();
1646
+ for (const row of columnsResult.rows) {
1647
+ const table = row["table_name"];
1648
+ const colName = row["column_name"];
1649
+ const dataType = row["effective_type"];
1650
+ const fullType = row["full_type"];
1651
+ const isNullable = row["is_nullable"];
1652
+ const colDefault = row["column_default"];
1653
+ const colDescription = row["description"];
1654
+ const tablePks = pkMap.get(table);
1655
+ const isPk = tablePks !== void 0 && tablePks.has(colName);
1656
+ const nt = normalizeType(fullType ?? dataType);
1657
+ const vecDims = nt === "vector" ? extractVectorDimensions(fullType ?? dataType) : void 0;
1658
+ const field = {
1659
+ name: colName,
1660
+ type: fullType ?? dataType,
1661
+ normalizedType: nt,
1662
+ nullable: isNullable === "YES",
1663
+ primaryKey: isPk,
1664
+ ...colDefault !== null ? { defaultValue: colDefault } : {},
1665
+ ...colDescription !== null && colDescription !== "" ? { description: colDescription } : {},
1666
+ ...vecDims !== void 0 ? { vectorDimensions: vecDims } : {}
1667
+ };
1668
+ let fields = columnsByTable.get(table);
1669
+ if (fields === void 0) {
1670
+ fields = [];
1671
+ columnsByTable.set(table, fields);
1672
+ }
1673
+ fields.push(field);
1674
+ }
1675
+ const relationsByTable = /* @__PURE__ */ new Map();
1676
+ const addRelation = (table, relation) => {
1677
+ let rels = relationsByTable.get(table);
1678
+ if (rels === void 0) {
1679
+ rels = [];
1680
+ relationsByTable.set(table, rels);
1681
+ }
1682
+ rels.push(relation);
1683
+ };
1684
+ for (const key of keys) {
1685
+ if (key.kind !== "f" || key.toTable === null) continue;
1686
+ const foreignFields = key.toColumns.filter((col) => col !== null);
1687
+ if (foreignFields.length !== key.fromColumns.length) continue;
1688
+ const isFkUnique = (uniqueSets.get(key.fromTable) ?? []).some(
1689
+ (set) => set.every((col) => key.fromColumns.includes(col))
1690
+ );
1691
+ addRelation(key.fromTable, {
1692
+ type: "belongsTo",
1693
+ entity: key.toTable,
1694
+ localFields: key.fromColumns,
1695
+ foreignFields
1696
+ });
1697
+ addRelation(key.toTable, {
1698
+ type: isFkUnique ? "hasOne" : "hasMany",
1699
+ entity: key.fromTable,
1700
+ localFields: foreignFields,
1701
+ foreignFields: key.fromColumns
1702
+ });
1703
+ }
1704
+ const indexesByTable = /* @__PURE__ */ new Map();
1705
+ for (const row of indexesResult.rows) {
1706
+ const table = row["table_name"];
1707
+ const indexName = row["index_name"];
1708
+ const isUnique = row["is_unique"];
1709
+ const indexType = row["index_type"];
1710
+ const columns = row["columns"];
1711
+ const mappedType = mapIndexType(indexType);
1712
+ const idx = {
1713
+ name: indexName,
1714
+ fields: columns,
1715
+ unique: isUnique,
1716
+ type: mappedType
1717
+ };
1718
+ let idxList = indexesByTable.get(table);
1719
+ if (idxList === void 0) {
1720
+ idxList = [];
1721
+ indexesByTable.set(table, idxList);
1722
+ }
1723
+ idxList.push(idx);
1724
+ }
1725
+ const filteredTables = tablesResult.rows.filter((row) => {
1726
+ const name = row["table_name"];
1727
+ if (options?.entities !== void 0 && !options.entities.includes(name)) return false;
1728
+ if (options?.exclude !== void 0 && options.exclude.includes(name)) return false;
1729
+ return true;
1730
+ });
1731
+ const entities = filteredTables.map((row) => {
1732
+ const tableName = row["table_name"];
1733
+ const tableDescription = row["description"];
1734
+ return {
1735
+ name: tableName,
1736
+ table: tableName,
1737
+ ...tableDescription !== null && tableDescription !== "" ? { description: tableDescription } : {},
1738
+ fields: columnsByTable.get(tableName) ?? [],
1739
+ relations: relationsByTable.get(tableName) ?? [],
1740
+ indexes: indexesByTable.get(tableName) ?? [],
1741
+ rowCount: rowCountMap.get(tableName)
1742
+ };
1743
+ });
1744
+ return { entities };
1745
+ };
1746
+ var mapIndexType = (pgType) => {
1747
+ const lower = pgType.toLowerCase();
1748
+ if (lower === "btree") return "btree";
1749
+ if (lower === "hash") return "hash";
1750
+ if (lower === "gin") return "gin";
1751
+ if (lower === "gist") return "gist";
1752
+ if (lower === "ivfflat") return "ivfflat";
1753
+ if (lower === "hnsw") return "hnsw";
1754
+ return "other";
1755
+ };
1756
+
1757
+ // src/adapters/postgres/compile.ts
1758
+ var compileQuery = (resolved) => {
1759
+ const paramSlots = [];
1760
+ const paramCounter = { value: 0 };
1761
+ const ctx = {
1762
+ resolvedPaths: resolved.filter?.resolvedPaths ?? /* @__PURE__ */ new Map(),
1763
+ aliasMap: resolved.aliasMap,
1764
+ paramSlots,
1765
+ paramCounter,
1766
+ ...resolved.existsMap !== void 0 ? { existsMap: resolved.existsMap } : {}
1767
+ };
1768
+ const sqlParts = [];
1769
+ const selectParts = [];
1770
+ if (resolved.distinct) {
1771
+ selectParts.push("DISTINCT");
1772
+ }
1773
+ const fieldColumns = resolved.fields.map(
1774
+ (f) => `${f.alias}.${f.column} AS ${quoteIdent(f.outputName)}`
1775
+ );
1776
+ const computeColumns = resolved.computes.map((c) => {
1777
+ const expr = compileCompute(c.expression, ctx);
1778
+ return `${expr} AS ${quoteIdent(c.name)}`;
1779
+ });
1780
+ const aggregateColumns = resolved.aggregates.map((a) => {
1781
+ const expr = compileAggregate(a.expression, ctx);
1782
+ return `${expr} AS ${quoteIdent(a.name)}`;
1783
+ });
1784
+ const semanticColumns = [];
1785
+ if (resolved.semantic !== void 0) {
1786
+ const col = `${resolved.semantic.field.alias}.${resolved.semantic.field.column}`;
1787
+ const semanticParamIndex = findSemanticParamIndex(paramSlots);
1788
+ if (semanticParamIndex !== void 0) {
1789
+ semanticColumns.push(`1 - (${col} <=> $${semanticParamIndex}) AS "$score"`);
1790
+ }
1791
+ }
1792
+ const allColumns = [...fieldColumns, ...computeColumns, ...aggregateColumns, ...semanticColumns];
1793
+ if (selectParts.length > 0) {
1794
+ sqlParts.push(`SELECT ${selectParts.join(" ")} ${allColumns.join(", ")}`);
1795
+ } else {
1796
+ sqlParts.push(`SELECT ${allColumns.join(", ")}`);
1797
+ }
1798
+ const firstSource = resolved.sources[0];
1799
+ if (firstSource !== void 0) {
1800
+ if (firstSource.subquery !== void 0) {
1801
+ const subSql = compileQuery(firstSource.subquery);
1802
+ mergeSubqueryParams(subSql, paramSlots, paramCounter);
1803
+ sqlParts.push(`FROM (${subSql.sql}) AS ${firstSource.alias}`);
1804
+ } else if (firstSource.table !== void 0) {
1805
+ sqlParts.push(`FROM ${firstSource.table} AS ${firstSource.alias}`);
1806
+ }
1807
+ }
1808
+ for (const join of resolved.joins) {
1809
+ const joinSource = resolved.sources.find((s) => s.alias === join.toAlias);
1810
+ if (joinSource !== void 0) {
1811
+ const keyword = join.kind === "left" ? "LEFT JOIN" : "JOIN";
1812
+ const conditions = [
1813
+ ...compileJoinPairs(join),
1814
+ ...(join.on ?? []).map((extra) => compileFilter(extra.original, ctx))
1815
+ ];
1816
+ const on = conditions.join(" AND ");
1817
+ if (joinSource.subquery !== void 0) {
1818
+ const subSql = compileQuery(joinSource.subquery);
1819
+ mergeSubqueryParams(subSql, paramSlots, paramCounter);
1820
+ sqlParts.push(`${keyword} (${subSql.sql}) AS ${join.toAlias} ON ${on}`);
1821
+ } else {
1822
+ sqlParts.push(`${keyword} ${join.toTable} AS ${join.toAlias} ON ${on}`);
1823
+ }
1824
+ }
1825
+ }
1826
+ const joinedAliases = new Set(resolved.joins.map((j) => j.toAlias));
1827
+ for (const source of resolved.sources) {
1828
+ if (source.alias === firstSource?.alias || joinedAliases.has(source.alias)) continue;
1829
+ if (source.subquery !== void 0) {
1830
+ const subSql = compileQuery(source.subquery);
1831
+ mergeSubqueryParams(subSql, paramSlots, paramCounter);
1832
+ sqlParts.push(`CROSS JOIN (${subSql.sql}) AS ${source.alias}`);
1833
+ } else if (source.table !== void 0) {
1834
+ sqlParts.push(`CROSS JOIN ${source.table} AS ${source.alias}`);
1835
+ }
1836
+ }
1837
+ if (resolved.filter !== void 0) {
1838
+ const whereClause = compileFilter(resolved.filter.original, ctx);
1839
+ sqlParts.push(`WHERE ${whereClause}`);
1840
+ }
1841
+ if (resolved.groupBy.length > 0) {
1842
+ const groupByParts = resolved.groupBy.map((f) => `${f.alias}.${f.column}`);
1843
+ sqlParts.push(`GROUP BY ${groupByParts.join(", ")}`);
1844
+ }
1845
+ if (resolved.sort.length > 0) {
1846
+ const orderByParts = resolved.sort.map((s) => {
1847
+ if (typeof s.field === "string") {
1848
+ return `${quoteIdent(s.field)} ${s.dir === "desc" ? "DESC" : "ASC"}`;
1849
+ }
1850
+ return `${s.field.alias}.${s.field.column} ${s.dir === "desc" ? "DESC" : "ASC"}`;
1851
+ });
1852
+ sqlParts.push(`ORDER BY ${orderByParts.join(", ")}`);
1853
+ } else if (resolved.semantic !== void 0) {
1854
+ const semanticIdx = findSemanticParamIndex(paramSlots);
1855
+ if (semanticIdx !== void 0) {
1856
+ const col = `${resolved.semantic.field.alias}.${resolved.semantic.field.column}`;
1857
+ sqlParts.push(`ORDER BY ${col} <=> $${semanticIdx} ASC`);
1858
+ }
1859
+ }
1860
+ if (resolved.limit !== void 0) {
1861
+ if (!Number.isInteger(resolved.limit) || resolved.limit < 1) {
1862
+ throw new VexError("invalid_dsl", `LIMIT must be a positive integer, not ${String(resolved.limit)}.`);
1863
+ }
1864
+ sqlParts.push(`LIMIT ${resolved.limit}`);
1865
+ }
1866
+ const contextContract = {};
1867
+ for (const slot of paramSlots) {
1868
+ contextContract[slot.key] = { type: slot.type, kind: slot.kind };
1869
+ }
1870
+ return {
1871
+ sql: sqlParts.join(" "),
1872
+ paramSlots,
1873
+ contextContract
1874
+ };
1875
+ };
1876
+ var findSemanticParamIndex = (slots) => {
1877
+ for (let i = 0; i < slots.length; i++) {
1878
+ const slot = slots[i];
1879
+ if (slot !== void 0 && slot.kind === "semantic") {
1880
+ return i + 1;
1881
+ }
1882
+ }
1883
+ return void 0;
1884
+ };
1885
+ var mergeSubqueryParams = (subCompiled, parentSlots, parentCounter) => {
1886
+ for (const slot of subCompiled.paramSlots) {
1887
+ parentCounter.value += 1;
1888
+ parentSlots.push(slot);
1889
+ }
1890
+ };
1891
+
1892
+ // src/adapters/postgres/statement-timeout.ts
1893
+ var UNIT_MS = { "": 1, ms: 1, s: 1e3, min: 6e4, h: 36e5, d: 864e5 };
1894
+ var parseTimeout = (shown) => {
1895
+ const match = /^\s*(\d+(?:\.\d+)?)\s*(ms|s|min|h|d)?\s*$/.exec(shown);
1896
+ if (match === null) return void 0;
1897
+ const unit = UNIT_MS[match[2] ?? ""];
1898
+ return unit === void 0 ? void 0 : Number(match[1]) * unit;
1899
+ };
1900
+ var enforcementFor = async (pool, ceilingMs) => {
1901
+ if (pool.statementTimeouts === false) return "unenforced";
1902
+ const shown = await pool.query("SHOW statement_timeout");
1903
+ const current = parseTimeout(String(shown.rows[0]?.["statement_timeout"] ?? ""));
1904
+ if (current !== void 0 && current > 0 && current <= ceilingMs) return "connection";
1905
+ return pool.transaction === void 0 ? "unenforced" : "statement";
1906
+ };
1907
+
1908
+ // src/adapters/postgres/postgres.adapter.ts
1909
+ var NUMERIC_OIDS = /* @__PURE__ */ new Set([
1910
+ 20,
1911
+ // int8
1912
+ 700,
1913
+ // float4
1914
+ 701,
1915
+ // float8
1916
+ 1700
1917
+ // numeric
1918
+ ]);
1919
+ var coerceNumericColumns = (rows, fields) => {
1920
+ const numericKeys = fields.filter((f) => NUMERIC_OIDS.has(f.dataTypeID)).map((f) => f.name);
1921
+ if (numericKeys.length === 0 || rows.length === 0) return rows;
1922
+ return rows.map((row) => {
1923
+ const out = { ...row };
1924
+ for (const key of numericKeys) {
1925
+ const v = out[key];
1926
+ if (typeof v === "string") {
1927
+ const n = Number(v);
1928
+ if (Number.isFinite(n)) out[key] = n;
1929
+ }
1930
+ }
1931
+ return out;
1932
+ });
1933
+ };
1934
+ var createPostgresAdapter = (config) => {
1935
+ const { pool, schema = "public", exclude } = config;
1936
+ const capabilities = {
1937
+ vectorSearch: true,
1938
+ fuzzyMatch: false,
1939
+ // Requires pg_trgm extension, not guaranteed
1940
+ jsonFields: true,
1941
+ fullTextSearch: true,
1942
+ returningClause: true,
1943
+ cte: true,
1944
+ windowFunctions: true,
1945
+ statementTimeout: true
1946
+ };
1947
+ const introspect = async (options) => introspectPostgres(pool, {
1948
+ ...options,
1949
+ schema: options?.schema ?? schema,
1950
+ exclude: options?.exclude ?? exclude
1951
+ });
1952
+ const compile2 = (resolved) => compileQuery(resolved);
1953
+ let perStatementMs;
1954
+ const limitReads = async (ms) => {
1955
+ perStatementMs = void 0;
1956
+ if (ms <= 0) return "unenforced";
1957
+ const enforcement = await enforcementFor(pool, ms);
1958
+ if (enforcement === "statement") perStatementMs = Math.round(ms);
1959
+ return enforcement;
1960
+ };
1961
+ const execute = async (query, params) => {
1962
+ const { transaction } = pool;
1963
+ const limit = perStatementMs;
1964
+ const result = limit === void 0 || transaction === void 0 ? await pool.query(query.sql, params) : await transaction(async (tx) => {
1965
+ await tx.query(`SET LOCAL statement_timeout = ${limit}`);
1966
+ return tx.query(query.sql, params);
1967
+ });
1968
+ return coerceNumericColumns(result.rows, result.fields);
1969
+ };
1970
+ return {
1971
+ id: "postgres",
1972
+ introspect,
1973
+ compile: compile2,
1974
+ execute,
1975
+ capabilities,
1976
+ limitReads
1977
+ };
1978
+ };
1979
+
1980
+ // src/guide.ts
1981
+ var vexGuide = () => [
1982
+ "VEX \u2014 how to read data. A Vex endpoint answers POST with a JSON body and returns { result, meta }.",
1983
+ "",
1984
+ "The request body takes one of three postures:",
1985
+ ' 1. GENERATE: { intent, shape, context? } \u2014 intent is plain English (all detail: filters, thresholds, sorting, grouping); shape is a JSON EXAMPLE of the output (an ARRAY with one example element returns a LIST; a plain OBJECT returns ONE record; values are type markers: "" 0 false). The result is cached and meta.cache.fingerprint carries its identity.',
1986
+ " 2. REPLAY: { fingerprint, context? } \u2014 re-runs the exact cached query. Never regenerates. Unknown fingerprint \u2192 error cache_miss.",
1987
+ " 3. NAMED SLOT: { fingerprint, intent, shape, context? } \u2014 hit when the stored request matches; regenerate-and-replace when it differs (protected slots refuse with fingerprint_protected).",
1988
+ "",
1989
+ "context \u2014 runtime values, bound as SQL parameters:",
1990
+ " - Keys are part of the query's contract; VALUES vary freely per call. Replaying one fingerprint with different context values re-runs the same query with new parameters \u2014 this is how a search term, an id, a threshold, or a date flows in per call.",
1991
+ ' - The query binds ONLY keys you pass at generation. To parameterize a query: name the value in the intent AND pass the key with a real value in context \u2014 e.g. intent "companies whose name contains the search text" with context { "q": "acme" }. Replays then pass new values for the same keys.',
1992
+ ' - Reserved keys: sortBy (an "entity.field", schema-validated) and sortDir ("asc"|"desc") drive ORDER BY directly on any replay.',
1993
+ ' - A value the query filters with ILIKE is a pattern: "%text%" matches contains.',
1994
+ ' - OPTIONAL keys: meta.context marks some keys `optional: true`. Those switch a condition ON \u2014 send the key and it applies, omit it and the condition is not in the query at all (it does not match everything by accident, and omitting it is never an error). A key marked `absent: true` is one you did not send on this run. This is how one fingerprint answers "everyone", "everyone matching a search", and "one by id".',
1995
+ "",
1996
+ "result \u2014 exactly the requested shape (array, object, or scalar). meta.cache = { hit, fingerprint, replaced? }; meta.missingContext lists REQUIRED context keys you did not send \u2014 the query ran without them, so the result is WRONG. Supply the keys and re-run before trusting it. Optional keys never appear there; leaving one out is a choice, not a mistake.",
1997
+ "",
1998
+ "GET on the same URL returns the endpoint's self-description: its entities, the query body contract, and every existing named fingerprint with its intent \u2014 check it before generating a query that may already exist."
1999
+ ].join("\n");
2000
+
2001
+ // src/cache/cache.types.ts
2002
+ var REFRESH_MODES = ["snapshot", "reactive"];
2003
+ var isRefresh = (value) => REFRESH_MODES.some((mode) => mode === value);
2004
+ var isCompiledIr = (value) => {
2005
+ if (value === null || typeof value !== "object") return false;
2006
+ const ir = value;
2007
+ if (ir["irVersion"] !== 1) return false;
2008
+ if (!("core" in ir)) return false;
2009
+ const tables = ir["tables"];
2010
+ if (tables === null || typeof tables !== "object") return false;
2011
+ const t = tables;
2012
+ return Array.isArray(t["paths"]) && Array.isArray(t["strings"]);
2013
+ };
2014
+ var validateEntry = (entry) => {
2015
+ if (typeof entry.createdAt !== "number") return "createdAt must be a number";
2016
+ if (entry.expiresAt !== void 0 && typeof entry.expiresAt !== "number") {
2017
+ return "expiresAt must be a number when present";
2018
+ }
2019
+ if (entry.kind === "unsatisfiable") {
2020
+ return typeof entry.reason === "string" && entry.reason.length > 0 ? null : "unsatisfiable entry requires a non-empty reason";
2021
+ }
2022
+ if (entry.kind === "ok") {
2023
+ if (exceedsDepth(entry.dsl)) return `invalid dsl: ${depthRefusal()}`;
2024
+ const parsed = QuerySchema.safeParse(entry.dsl);
2025
+ if (!parsed.success) return `invalid dsl: ${parsed.error.message}`;
2026
+ if (entry.prismIr !== void 0 && !isCompiledIr(entry.prismIr)) {
2027
+ return "invalid prismIr: not a CompiledIr structure";
2028
+ }
2029
+ if (entry.refresh !== void 0 && !isRefresh(entry.refresh)) {
2030
+ return `invalid refresh: ${String(entry.refresh)}`;
2031
+ }
2032
+ return null;
2033
+ }
2034
+ if (entry.kind === "mutation") {
2035
+ if (exceedsDepth(entry.mutation)) return `invalid mutation: ${depthRefusal()}`;
2036
+ const parsed = MutationDefinitionSchema.safeParse(entry.mutation);
2037
+ return parsed.success ? null : `invalid mutation: ${parsed.error.message}`;
2038
+ }
2039
+ return `unknown cache entry kind: ${String(entry.kind)}`;
2040
+ };
2041
+ var IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;
2042
+ var quoteIdent2 = (name, label) => {
2043
+ if (!IDENT.test(name)) {
2044
+ throw new Error(`Invalid ${label} identifier for postgres cache: "${name}"`);
2045
+ }
2046
+ return `"${name}"`;
2047
+ };
2048
+ var SELECT_COLS = "key, kind, intent, shape, dsl, prism_ir, reach, reason, created_at, expires_at, schema_fingerprint, protected, last_used_at, request_hash, refresh";
2049
+ var rowToEntry = (row) => {
2050
+ const createdAt = row["created_at"].getTime();
2051
+ const expiresAtRaw = row["expires_at"];
2052
+ const lastUsedRaw = row["last_used_at"];
2053
+ const fingerprint = row["schema_fingerprint"];
2054
+ const meta = {
2055
+ createdAt,
2056
+ ...expiresAtRaw ? { expiresAt: expiresAtRaw.getTime() } : {},
2057
+ ...lastUsedRaw ? { lastUsedAt: lastUsedRaw.getTime() } : {},
2058
+ ...row["protected"] === true ? { protected: true } : {},
2059
+ ...row["request_hash"] != null ? { requestHash: String(row["request_hash"]) } : {},
2060
+ ...fingerprint ? { schemaFingerprint: fingerprint } : {},
2061
+ ...row["intent"] != null ? { intent: String(row["intent"]) } : {},
2062
+ ...row["shape"] != null ? { shape: row["shape"] } : {}
2063
+ };
2064
+ if (row["kind"] === "unsatisfiable") {
2065
+ return { kind: "unsatisfiable", reason: String(row["reason"] ?? ""), ...meta };
2066
+ }
2067
+ if (row["kind"] === "mutation") {
2068
+ return {
2069
+ kind: "mutation",
2070
+ mutation: row["dsl"],
2071
+ ...row["reach"] != null ? { reach: row["reach"] } : {},
2072
+ ...meta
2073
+ };
2074
+ }
2075
+ return {
2076
+ kind: "ok",
2077
+ dsl: row["dsl"],
2078
+ ...row["prism_ir"] != null ? { prismIr: row["prism_ir"] } : {},
2079
+ // A DECLARED REACH IS PART OF THE ENTRY, so it has to survive the round
2080
+ // trip. Dropping it here would not fail loudly — the read would simply be
2081
+ // served at the caller's own, wider reach, which is the exact thing the
2082
+ // field exists to prevent.
2083
+ ...row["reach"] != null ? { reach: row["reach"] } : {},
2084
+ // So must the refresh mode: dropped, a reactive read would quietly answer
2085
+ // once and never again.
2086
+ ...isRefresh(row["refresh"]) ? { refresh: row["refresh"] } : {},
2087
+ ...meta
2088
+ };
2089
+ };
2090
+ var createPostgresCache = (config) => {
2091
+ const { pool, onError } = config;
2092
+ const schema = quoteIdent2(config.schema ?? "public", "schema");
2093
+ const table = quoteIdent2(config.table ?? "vex_cache", "table");
2094
+ const qualified = `${schema}.${table}`;
2095
+ const isDefault = (config.schema ?? "public") === "public" && (config.table ?? "vex_cache") === "vex_cache";
2096
+ const slug = `${config.schema ?? "public"}-${config.table ?? "vex_cache"}`.toLowerCase().replace(/[^a-z0-9-]/g, "-");
2097
+ const sequence = {
2098
+ id: isDefault ? "nisc.vex.cache" : `nisc.vex.cache.${slug}`,
2099
+ migrations: [
2100
+ {
2101
+ description: "The vex cache table, converged from any earlier shape",
2102
+ steps: [
2103
+ { kind: "sql", sql: `CREATE SCHEMA IF NOT EXISTS ${schema}` },
2104
+ {
2105
+ kind: "sql",
2106
+ sql: `CREATE TABLE IF NOT EXISTS ${qualified} (
2107
+ key text PRIMARY KEY,
2108
+ kind text NOT NULL DEFAULT 'ok',
2109
+ intent text,
2110
+ shape jsonb,
2111
+ dsl jsonb,
2112
+ prism_ir jsonb,
2113
+ reach text,
2114
+ reason text,
2115
+ created_at timestamptz NOT NULL DEFAULT now(),
2116
+ expires_at timestamptz,
2117
+ schema_fingerprint text,
2118
+ protected boolean NOT NULL DEFAULT false,
2119
+ last_used_at timestamptz,
2120
+ request_hash text,
2121
+ refresh text
2122
+ )`
2123
+ },
2124
+ { kind: "sql", sql: `ALTER TABLE ${qualified} ADD COLUMN IF NOT EXISTS protected boolean NOT NULL DEFAULT false` },
2125
+ { kind: "sql", sql: `ALTER TABLE ${qualified} ADD COLUMN IF NOT EXISTS last_used_at timestamptz` },
2126
+ { kind: "sql", sql: `ALTER TABLE ${qualified} ADD COLUMN IF NOT EXISTS request_hash text` },
2127
+ { kind: "sql", sql: `ALTER TABLE ${qualified} ADD COLUMN IF NOT EXISTS reach text` },
2128
+ { kind: "sql", sql: `ALTER TABLE ${qualified} ADD COLUMN IF NOT EXISTS refresh text` }
2129
+ ]
2130
+ }
2131
+ ]
2132
+ };
2133
+ const init = async () => {
2134
+ await migrate(pool, [sequence]);
2135
+ };
2136
+ const evict = (key, reason) => {
2137
+ fireAndForget(pool.query(`DELETE FROM ${qualified} WHERE key = $1`, [key]), onError);
2138
+ const err = new Error(`[vex:cache:postgres] evicted invalid row for key "${key}": ${reason}`);
2139
+ if (onError) onError(err);
2140
+ else console.error(err);
2141
+ };
2142
+ const get = async (key) => {
2143
+ const res = await pool.query(
2144
+ `SELECT ${SELECT_COLS} FROM ${qualified}
2145
+ WHERE key = $1 AND (expires_at IS NULL OR expires_at > now())`,
2146
+ [key]
2147
+ );
2148
+ const row = res.rows[0];
2149
+ if (row === void 0) return void 0;
2150
+ const entry = rowToEntry(row);
2151
+ const error = validateEntry(entry);
2152
+ if (error !== null) {
2153
+ evict(key, error);
2154
+ return void 0;
2155
+ }
2156
+ return entry;
2157
+ };
2158
+ const set = async (key, entry) => {
2159
+ const error = validateEntry(entry);
2160
+ if (error !== null) {
2161
+ const wrapped = new Error(
2162
+ `[vex:cache:postgres] refusing to write invalid entry for key "${key}": ${error}`
2163
+ );
2164
+ if (onError) {
2165
+ onError(wrapped);
2166
+ return;
2167
+ }
2168
+ throw wrapped;
2169
+ }
2170
+ const isOk = entry.kind === "ok";
2171
+ const dsl = isOk ? JSON.stringify(entry.dsl) : entry.kind === "mutation" ? JSON.stringify(entry.mutation) : null;
2172
+ const prismIr = isOk && entry.prismIr !== void 0 ? JSON.stringify(entry.prismIr) : null;
2173
+ const reason = entry.kind === "unsatisfiable" ? entry.reason : null;
2174
+ const intent = entry.intent ?? null;
2175
+ const shape = entry.shape !== void 0 ? JSON.stringify(entry.shape) : null;
2176
+ const createdAt = new Date(entry.createdAt);
2177
+ const expiresAt = entry.expiresAt !== void 0 ? new Date(entry.expiresAt) : null;
2178
+ const fingerprint = entry.schemaFingerprint ?? null;
2179
+ const isProtected = entry.protected === true;
2180
+ const lastUsedAt = entry.lastUsedAt !== void 0 ? new Date(entry.lastUsedAt) : null;
2181
+ const requestHash = entry.requestHash ?? null;
2182
+ const reach = entry.kind === "unsatisfiable" ? null : entry.reach ?? null;
2183
+ const refresh = entry.kind === "ok" ? entry.refresh ?? null : null;
2184
+ await pool.query(
2185
+ `INSERT INTO ${qualified} (key, kind, intent, shape, dsl, prism_ir, reach, reason, created_at, expires_at, schema_fingerprint, protected, last_used_at, request_hash, refresh)
2186
+ VALUES ($1, $2, $3, $4::jsonb, $5::jsonb, $6::jsonb, $7, $8, $9, $10, $11, $12, $13, $14, $15)
2187
+ ON CONFLICT (key) DO UPDATE SET
2188
+ kind = EXCLUDED.kind,
2189
+ intent = EXCLUDED.intent,
2190
+ shape = EXCLUDED.shape,
2191
+ dsl = EXCLUDED.dsl,
2192
+ prism_ir = EXCLUDED.prism_ir,
2193
+ reach = EXCLUDED.reach,
2194
+ reason = EXCLUDED.reason,
2195
+ created_at = EXCLUDED.created_at,
2196
+ expires_at = EXCLUDED.expires_at,
2197
+ schema_fingerprint = EXCLUDED.schema_fingerprint,
2198
+ protected = EXCLUDED.protected,
2199
+ last_used_at = EXCLUDED.last_used_at,
2200
+ request_hash = EXCLUDED.request_hash,
2201
+ refresh = EXCLUDED.refresh`,
2202
+ [key, entry.kind, intent, shape, dsl, prismIr, reach, reason, createdAt, expiresAt, fingerprint, isProtected, lastUsedAt, requestHash, refresh]
2203
+ );
2204
+ };
2205
+ const del = async (key) => {
2206
+ await pool.query(`DELETE FROM ${qualified} WHERE key = $1`, [key]);
2207
+ };
2208
+ const clear = async () => {
2209
+ await pool.query(`DELETE FROM ${qualified}`);
2210
+ };
2211
+ const keys = async () => {
2212
+ const res = await pool.query(
2213
+ `SELECT key FROM ${qualified} WHERE expires_at IS NULL OR expires_at > now()`
2214
+ );
2215
+ return res.rows.map((r) => String(r["key"]));
2216
+ };
2217
+ const entries = async () => {
2218
+ const res = await pool.query(
2219
+ `SELECT ${SELECT_COLS} FROM ${qualified}
2220
+ WHERE expires_at IS NULL OR expires_at > now()`
2221
+ );
2222
+ const out = [];
2223
+ for (const row of res.rows) {
2224
+ const key = String(row["key"]);
2225
+ const entry = rowToEntry(row);
2226
+ const error = validateEntry(entry);
2227
+ if (error !== null) {
2228
+ evict(key, error);
2229
+ continue;
2230
+ }
2231
+ out.push({ key, entry });
2232
+ }
2233
+ return out;
2234
+ };
2235
+ return { init, sequence, get, set, delete: del, clear, keys, entries };
2236
+ };
2237
+
2238
+ // src/cache/tiered.ts
2239
+ var createTieredCache = (config) => {
2240
+ const { l1, l2, onError } = config;
2241
+ const warmup = config.warmup ?? "full";
2242
+ const promote = async (key, entry) => {
2243
+ const error = validateEntry(entry);
2244
+ if (error !== null) {
2245
+ const wrapped = new Error(`[vex:cache:tiered] evicting invalid L2 entry for key "${key}": ${error}`);
2246
+ if (onError) onError(wrapped);
2247
+ else console.error(wrapped);
2248
+ fireAndForget(l2.delete(key), onError);
2249
+ return false;
2250
+ }
2251
+ await l1.set(key, entry);
2252
+ return true;
2253
+ };
2254
+ const init = async () => {
2255
+ await l2.init?.();
2256
+ await l1.init?.();
2257
+ if (warmup === "lazy") return;
2258
+ if (typeof warmup === "object" && warmup.mode === "partial") {
2259
+ for (const key of warmup.fingerprints) {
2260
+ const entry = await l2.get(key);
2261
+ if (entry !== void 0) await promote(key, entry);
2262
+ }
2263
+ return;
2264
+ }
2265
+ if (l2.entries) {
2266
+ const all = await l2.entries();
2267
+ for (const { key, entry } of all) await promote(key, entry);
2268
+ return;
2269
+ }
2270
+ const keys2 = await l2.keys();
2271
+ for (const key of keys2) {
2272
+ const entry = await l2.get(key);
2273
+ if (entry !== void 0) await promote(key, entry);
2274
+ }
2275
+ };
2276
+ const get = async (key) => {
2277
+ const hit = await l1.get(key);
2278
+ if (hit !== void 0) return hit;
2279
+ const fromL2 = await l2.get(key);
2280
+ if (fromL2 === void 0) return void 0;
2281
+ const ok = await promote(key, fromL2);
2282
+ return ok ? fromL2 : void 0;
2283
+ };
2284
+ const set = async (key, entry) => {
2285
+ await l1.set(key, entry);
2286
+ fireAndForget(l2.set(key, entry), onError);
2287
+ };
2288
+ const del = async (key) => {
2289
+ await l1.delete(key);
2290
+ fireAndForget(l2.delete(key), onError);
2291
+ };
2292
+ const clear = async () => {
2293
+ await l1.clear();
2294
+ fireAndForget(l2.clear(), onError);
2295
+ };
2296
+ const keys = async () => l1.keys();
2297
+ return { init, get, set, delete: del, clear, keys, ...l2.sequence !== void 0 ? { sequence: l2.sequence } : {} };
2298
+ };
2299
+ var same = (a, b) => a === void 0 || b === void 0 ? a === b : canonicalText(a) === canonicalText(b);
2300
+ var seedCache = async (cache, entries) => {
2301
+ for (const entry of entries) {
2302
+ const existing = await cache.get(entry.fingerprint);
2303
+ if ("mutation" in entry) {
2304
+ const issues = lintMutation(entry.mutation);
2305
+ if (issues.length > 0) {
2306
+ throw new Error(`Mutation seed "${entry.fingerprint}" fails the authoring lint:
2307
+ ${issues.join("\n ")}`);
2308
+ }
2309
+ const current2 = existing?.kind === "mutation" && existing.protected === true && same(existing.mutation, entry.mutation) && same(existing.reach, entry.reach) && same(existing.intent, entry.intent);
2310
+ if (current2) continue;
2311
+ await cache.set(entry.fingerprint, {
2312
+ kind: "mutation",
2313
+ mutation: entry.mutation,
2314
+ ...entry.reach !== void 0 ? { reach: entry.reach } : {},
2315
+ ...entry.intent !== void 0 ? { intent: entry.intent } : {},
2316
+ protected: true,
2317
+ createdAt: Date.now()
2318
+ });
2319
+ continue;
2320
+ }
2321
+ const prismIr = await compile(entry.mapping ?? { $ref: "$.result" });
2322
+ const current = existing?.kind === "ok" && existing.protected === true && existing.prismIr?.meta.fingerprint === prismIr.meta.fingerprint && same(existing.dsl, entry.dsl) && same(existing.shape, entry.shape) && same(existing.reach, entry.reach) && same(existing.intent, entry.intent) && (existing.refresh ?? "snapshot") === (entry.refresh ?? "snapshot");
2323
+ if (current) continue;
2324
+ await cache.set(entry.fingerprint, {
2325
+ kind: "ok",
2326
+ ...entry.refresh !== void 0 ? { refresh: entry.refresh } : {},
2327
+ dsl: entry.dsl,
2328
+ prismIr,
2329
+ ...entry.reach !== void 0 ? { reach: entry.reach } : {},
2330
+ ...entry.intent !== void 0 ? { intent: entry.intent } : {},
2331
+ ...entry.shape !== void 0 ? { shape: entry.shape } : {},
2332
+ protected: true,
2333
+ createdAt: Date.now()
2334
+ });
2335
+ }
2336
+ };
2337
+
2338
+ export { REFRESH_MODES, SCOPE_VERBS, analyze, createMemoryCache, createPostgresAdapter, createPostgresCache, createQueryEngine, createScopePolicy, createTieredCache, discoverEntities, isRefresh, mergeScopePolicies, resolve, scopeBindings, scopeGrants, scopeProfiles, seedCache, validateEntry, vexGuide };
2339
+ //# sourceMappingURL=index.js.map
2340
+ //# sourceMappingURL=index.js.map