@niscorp/vex 0.4.5 → 0.5.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 (40) hide show
  1. package/CHANGELOG.md +78 -0
  2. package/DESIGN.md +72 -45
  3. package/DOCS.md +130 -21
  4. package/README.md +17 -0
  5. package/dist/adapters/express/index.cjs +606 -173
  6. package/dist/adapters/express/index.cjs.map +1 -1
  7. package/dist/adapters/express/index.d.cts +6 -2
  8. package/dist/adapters/express/index.d.ts +6 -2
  9. package/dist/adapters/express/index.js +16 -3
  10. package/dist/adapters/express/index.js.map +1 -1
  11. package/dist/adapters/hono/index.cjs +597 -173
  12. package/dist/adapters/hono/index.cjs.map +1 -1
  13. package/dist/adapters/hono/index.d.cts +5 -2
  14. package/dist/adapters/hono/index.d.ts +5 -2
  15. package/dist/adapters/hono/index.js +7 -3
  16. package/dist/adapters/hono/index.js.map +1 -1
  17. package/dist/agent/index.cjs +12 -12
  18. package/dist/agent/index.cjs.map +1 -1
  19. package/dist/agent/index.d.cts +1 -1
  20. package/dist/agent/index.d.ts +1 -1
  21. package/dist/agent/index.js +12 -12
  22. package/dist/agent/index.js.map +1 -1
  23. package/dist/{chunk-W5MYFJKT.js → chunk-F7OXXJIH.js} +562 -192
  24. package/dist/chunk-F7OXXJIH.js.map +1 -0
  25. package/dist/{chunk-F7RDSWYF.js → chunk-VHNCSQPO.js} +2 -2
  26. package/dist/{chunk-F7RDSWYF.js.map → chunk-VHNCSQPO.js.map} +1 -1
  27. package/dist/{handler-O6XslV-S.d.ts → handler-DdfaWN_J.d.ts} +7 -1
  28. package/dist/{handler-CB0BqKsY.d.cts → handler-kvZkxwaN.d.cts} +7 -1
  29. package/dist/index.cjs +493 -232
  30. package/dist/index.cjs.map +1 -1
  31. package/dist/index.d.cts +5 -3
  32. package/dist/index.d.ts +5 -3
  33. package/dist/index.js +118 -221
  34. package/dist/index.js.map +1 -1
  35. package/dist/migrations/index.cjs.map +1 -1
  36. package/dist/migrations/index.js +1 -1
  37. package/dist/{types-BmHuPfPS.d.cts → types-BxkRxTTx.d.cts} +5 -0
  38. package/dist/{types-D5CCaqcd.d.ts → types-DgUZNKii.d.ts} +5 -0
  39. package/package.json +8 -8
  40. package/dist/chunk-W5MYFJKT.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
- import { isRefresh } from './chunk-F7RDSWYF.js';
2
- export { REFRESH_MODES, isRefresh } from './chunk-F7RDSWYF.js';
3
- import { MutationDefinitionSchema, lintMutation, computeSchemaFingerprint, pruneOptional, buildValidationContext, requireScope, executeQuery, QueryRequestSchema, computeRequestHash, computePolicyKey, presenceOf, presenceSignature, findMissingContext, buildContextContract, optionalKeysOf, resolveParams, canonicalHash, fireAndForget, isSetMatch, refuseOptional, canonicalText, checkScope, scopeResolved, mintFingerprint, isEntryFresh, canReadTable, hashText, quoteIdent, compileCompute, compileAggregate, compileJoinPairs, compileFilter, isTouchDue } from './chunk-W5MYFJKT.js';
4
- 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, mutationMisfits, normalizeShape, optionalKeysOf, presenceOf, pruneOptional, requiredContextKeys, resolveParams, scopeResolved, sweepCache, tablesChangedBy } from './chunk-W5MYFJKT.js';
1
+ import { isRefresh } from './chunk-VHNCSQPO.js';
2
+ export { REFRESH_MODES, isRefresh } from './chunk-VHNCSQPO.js';
3
+ import { MutationDefinitionSchema, lintMutation, computeSchemaFingerprint, pruneOptional, buildValidationContext, requireScope, executeQuery, QueryRequestSchema, dropNullIntentAndFingerprint, computeRequestHash, computePolicyKey, presenceOf, presenceSignature, findMissingContext, buildContextContract, optionalKeysOf, resolveParams, canonicalHash, discoverEntities, fireAndForget, isSetMatch, refuseOptional, canonicalText, checkScope, scopeResolved, mintFingerprint, isEntryFresh, canReadTable, hashText, columnSql, quoteIdent, compileCompute, compileAggregate, sqlName, tableSql, compileJoinPairs, compileFilter, isTouchDue, touchEntry } from './chunk-F7OXXJIH.js';
4
+ export { MutationDefinitionSchema, MutationSchema, QueryRequestSchema, VexScopeError, applyScope, buildContextContract, buildValidationContext, checkScope, collectMutationContext, collectQueryContext, compileFieldOrValue, compileFilter, computeRequestHash, computeSchemaFingerprint, discoverEntities, executeMutation, executeQuery, executeWrites, findMissingContext, handleDiscovery, handleFingerprintDelete, handleFingerprintPatch, handleQuery, lintMutation, mintFingerprint, mutationEffect, mutationMisfits, normalizeShape, optionalKeysOf, presenceOf, pruneOptional, requiredContextKeys, resolveParams, scopeResolved, sweepCache, tablesChangedBy } from './chunk-F7OXXJIH.js';
5
5
  import { VexError, isVexError } from './chunk-XTOK7YOR.js';
6
6
  export { VexError } from './chunk-XTOK7YOR.js';
7
7
  import { QuerySchema, isIdentifier, isFieldPathShape } from './chunk-UPQMKAAX.js';
@@ -11,179 +11,6 @@ import { exceedsDepth, depthRefusal } from '@niscorp/strata';
11
11
  import { compile, execute } from '@niscorp/prism';
12
12
  import { migrate } from '@niscorp/strata/postgres';
13
13
 
14
- // src/scope/discover.ts
15
- var extractEntityFromPath = (path) => {
16
- const parts = path.split(".");
17
- return parts.length === 2 ? parts[0] : void 0;
18
- };
19
- var collectFromFieldOrValue = (fov, out) => {
20
- if (isFieldPathShape(fov)) {
21
- const entity = extractEntityFromPath(fov);
22
- if (entity !== void 0) out.add(entity);
23
- }
24
- };
25
- var collectFromFilter = (filter, out) => {
26
- if ("exists" in filter) {
27
- for (const entity of filter.exists.from) out.add(entity);
28
- if (filter.exists.filter !== void 0) collectFromFilter(filter.exists.filter, out);
29
- return;
30
- }
31
- if ("eq" in filter || "neq" in filter || "gt" in filter || "gte" in filter || "lt" in filter || "lte" in filter) {
32
- 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;
33
- collectFromFieldOrValue(pair[0], out);
34
- collectFromFieldOrValue(pair[1], out);
35
- return;
36
- }
37
- if ("in" in filter || "notIn" in filter) {
38
- const tuple = "in" in filter ? filter.in : filter.notIn;
39
- const entity = extractEntityFromPath(tuple[0]);
40
- if (entity !== void 0) out.add(entity);
41
- const target = tuple[1];
42
- if (Array.isArray(target)) {
43
- for (const v of target) {
44
- collectFromFieldOrValue(v, out);
45
- }
46
- }
47
- return;
48
- }
49
- if ("like" in filter || "ilike" in filter) {
50
- const tuple = "like" in filter ? filter.like : filter.ilike;
51
- const entity = extractEntityFromPath(tuple[0]);
52
- if (entity !== void 0) out.add(entity);
53
- collectFromFieldOrValue(tuple[1], out);
54
- return;
55
- }
56
- if ("isNull" in filter) {
57
- const entity = extractEntityFromPath(filter.isNull);
58
- if (entity !== void 0) out.add(entity);
59
- return;
60
- }
61
- if ("isNotNull" in filter) {
62
- const entity = extractEntityFromPath(filter.isNotNull);
63
- if (entity !== void 0) out.add(entity);
64
- return;
65
- }
66
- if ("and" in filter) {
67
- for (const sub of filter.and) {
68
- collectFromFilter(sub, out);
69
- }
70
- return;
71
- }
72
- if ("or" in filter) {
73
- for (const sub of filter.or) {
74
- collectFromFilter(sub, out);
75
- }
76
- return;
77
- }
78
- if ("not" in filter) {
79
- collectFromFilter(filter.not, out);
80
- return;
81
- }
82
- if ("semantic" in filter) {
83
- const entity = extractEntityFromPath(filter.semantic.field);
84
- if (entity !== void 0) out.add(entity);
85
- return;
86
- }
87
- if ("fuzzy" in filter) {
88
- const entity = extractEntityFromPath(filter.fuzzy.field);
89
- if (entity !== void 0) out.add(entity);
90
- return;
91
- }
92
- if ("optional" in filter) refuseOptional("scope discovery");
93
- };
94
- var collectFromCompute = (expr, out) => {
95
- if ("add" in expr || "subtract" in expr || "multiply" in expr || "divide" in expr) {
96
- const pair = "add" in expr ? expr.add : "subtract" in expr ? expr.subtract : "multiply" in expr ? expr.multiply : expr.divide;
97
- collectFromFieldOrValue(pair[0], out);
98
- collectFromFieldOrValue(pair[1], out);
99
- return;
100
- }
101
- if ("concat" in expr) {
102
- for (const v of expr.concat) {
103
- collectFromFieldOrValue(v, out);
104
- }
105
- return;
106
- }
107
- if ("coalesce" in expr) {
108
- for (const v of expr.coalesce) {
109
- collectFromFieldOrValue(v, out);
110
- }
111
- return;
112
- }
113
- if ("case" in expr) {
114
- for (const when of expr.case.when) {
115
- collectFromFilter(when.condition, out);
116
- collectFromFieldOrValue(when.then, out);
117
- }
118
- collectFromFieldOrValue(expr.case.else, out);
119
- return;
120
- }
121
- };
122
- var collectFromAggregate = (expr, out) => {
123
- 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;
124
- if (typeof arg !== "string") {
125
- collectFromCompute(arg, out);
126
- return;
127
- }
128
- const entity = extractEntityFromPath(arg);
129
- if (entity !== void 0) out.add(entity);
130
- };
131
- var collectFromQuery = (dsl, out) => {
132
- const aliases = /* @__PURE__ */ new Set();
133
- const local = /* @__PURE__ */ new Set();
134
- for (const source of dsl.from) {
135
- if (typeof source === "string") {
136
- out.add(source);
137
- } else {
138
- aliases.add(source.as);
139
- collectFromQuery(source.query, out);
140
- }
141
- }
142
- for (const ref of dsl.fields ?? []) {
143
- const entity = extractEntityFromPath(typeof ref === "string" ? ref : ref.field);
144
- if (entity !== void 0) local.add(entity);
145
- }
146
- if (dsl.filter !== void 0) {
147
- collectFromFilter(dsl.filter, local);
148
- }
149
- if (dsl.compute !== void 0) {
150
- for (const key of Object.keys(dsl.compute)) {
151
- const expr = dsl.compute[key];
152
- if (expr !== void 0) {
153
- collectFromCompute(expr, local);
154
- }
155
- }
156
- }
157
- if (dsl.aggregate !== void 0) {
158
- for (const key of Object.keys(dsl.aggregate)) {
159
- const expr = dsl.aggregate[key];
160
- if (expr !== void 0) {
161
- collectFromAggregate(expr, local);
162
- }
163
- }
164
- }
165
- if (dsl.groupBy !== void 0) {
166
- for (const path of dsl.groupBy) {
167
- const entity = extractEntityFromPath(path);
168
- if (entity !== void 0) local.add(entity);
169
- }
170
- }
171
- if (dsl.sort !== void 0) {
172
- for (const entry of dsl.sort) {
173
- const entity = extractEntityFromPath(entry.field);
174
- if (entity !== void 0) local.add(entity);
175
- }
176
- }
177
- for (const entity of local) {
178
- if (!aliases.has(entity)) out.add(entity);
179
- }
180
- };
181
- var discoverEntities = (dsl) => {
182
- const entities = /* @__PURE__ */ new Set();
183
- collectFromQuery(dsl, entities);
184
- return entities;
185
- };
186
-
187
14
  // src/scope/grants.ts
188
15
  var SCOPE_VERBS = ["read", "write.insert", "write.update", "write.delete"];
189
16
  var scopeGrants = (tables) => tables.flatMap((t) => SCOPE_VERBS.map((v) => `${t}.${v}`));
@@ -245,11 +72,24 @@ var createScopePolicy = (grants, behaviors = {}, scoping) => {
245
72
  return { default: "deny", entities };
246
73
  };
247
74
  var matchCount = (rules) => (rules ?? []).filter((r) => "match" in r).length;
75
+ var phasesOf = (rule) => {
76
+ if (rule === void 0 || "deny" in rule) return {};
77
+ if ("public" in rule) return { read: [], insert: [], update: [], delete: [] };
78
+ const { read, write, insert, update, delete: del } = rule;
79
+ const withWrite = (common, own) => [...common ?? [], ...own ?? []];
80
+ return {
81
+ ...read !== void 0 ? { read } : {},
82
+ ...write !== void 0 || insert !== void 0 ? { insert: withWrite(write, insert) } : {},
83
+ ...write !== void 0 || update !== void 0 ? { update: withWrite(write, update) } : {},
84
+ ...write !== void 0 || del !== void 0 ? { delete: withWrite(write && onlyMatches(write), del) } : {}
85
+ };
86
+ };
248
87
  var mergeScopePolicies = (policies) => {
249
88
  const entities = {};
250
89
  for (const policy of policies) {
251
- for (const [table, rule] of Object.entries(policy.entities)) {
252
- if (rule === void 0 || "public" in rule || "deny" in rule) continue;
90
+ for (const [table, listed] of Object.entries(policy.entities)) {
91
+ const rule = phasesOf(listed);
92
+ if (Object.keys(rule).length === 0) continue;
253
93
  const into = entities[table] ??= {};
254
94
  for (const phase of ["read", "insert", "update", "delete"]) {
255
95
  const incoming = rule[phase];
@@ -302,9 +142,9 @@ var findClosest = (target, candidates) => {
302
142
  };
303
143
  var generateAlias = (name, counter) => {
304
144
  const prefix = name.charAt(0).toLowerCase();
305
- const current = counter.get(prefix) ?? 0;
306
- const next = current + 1;
307
- counter.set(prefix, next);
145
+ let next = (counter.counts.get(prefix) ?? 0) + 1;
146
+ while (counter.taken.has(`${prefix}${next}`)) next += 1;
147
+ counter.counts.set(prefix, next);
308
148
  return `${prefix}${next}`;
309
149
  };
310
150
  var findEntity = (name, schema) => {
@@ -553,7 +393,10 @@ var extractSemantic = (filter, entityLookup, schema) => {
553
393
  return void 0;
554
394
  };
555
395
  var resolve = (dsl, schema) => {
556
- const aliasCounter = /* @__PURE__ */ new Map();
396
+ const aliasCounter = {
397
+ counts: /* @__PURE__ */ new Map(),
398
+ taken: /* @__PURE__ */ new Set([...schema.entities.map((e) => e.name), ...dsl.from.flatMap((source) => typeof source === "string" ? [] : [source.as])])
399
+ };
557
400
  const entityLookup = /* @__PURE__ */ new Map();
558
401
  const aliasMap = /* @__PURE__ */ new Map();
559
402
  const sources = [];
@@ -650,7 +493,7 @@ var resolve = (dsl, schema) => {
650
493
  for (const [name, expr] of Object.entries(dsl.aggregate)) {
651
494
  if (expr !== void 0) {
652
495
  assertName(name, "aggregate name");
653
- resolveAggregatePaths(expr, entityLookup, schema, aliasMap);
496
+ resolveAggregatePaths(expr, entityLookup, schema, aliasMap, existsMap, aliasCounter);
654
497
  aggregates.push({ name, expression: expr });
655
498
  }
656
499
  }
@@ -729,11 +572,11 @@ var resolveComputePaths = (expr, entityLookup, schema, aliasMap, existsOut, alia
729
572
  resolveFieldOrValue(expr.case.else);
730
573
  }
731
574
  };
732
- var resolveAggregatePaths = (expr, entityLookup, schema, aliasMap) => {
575
+ var resolveAggregatePaths = (expr, entityLookup, schema, aliasMap, existsOut, aliasCounter) => {
733
576
  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;
734
577
  if (arg === "*") return;
735
578
  if (typeof arg !== "string") {
736
- resolveComputePaths(arg, entityLookup, schema, aliasMap);
579
+ resolveComputePaths(arg, entityLookup, schema, aliasMap, existsOut, aliasCounter);
737
580
  return;
738
581
  }
739
582
  if (!aliasMap.has(arg)) {
@@ -781,8 +624,8 @@ var hasCartesianProduct = (resolved) => {
781
624
  };
782
625
  var findUnindexedFilterColumns = (resolved) => {
783
626
  if (resolved.filter === void 0) return [];
784
- const unindexed = [];
785
- for (const [path, res] of resolved.filter.resolvedPaths) {
627
+ const unindexed = /* @__PURE__ */ new Set();
628
+ for (const res of resolved.filter.resolvedPaths.values()) {
786
629
  const source = resolved.sources.find((s) => s.alias === res.alias);
787
630
  if (source === void 0 || source.entity === void 0) continue;
788
631
  const isIndexed = source.entity.indexes.some(
@@ -792,10 +635,10 @@ var findUnindexedFilterColumns = (resolved) => {
792
635
  (f) => f.name === res.column && f.primaryKey
793
636
  );
794
637
  if (!isIndexed && !isPrimaryKey) {
795
- unindexed.push(path);
638
+ unindexed.add(`${source.entity.name}.${res.column}`);
796
639
  }
797
640
  }
798
- return unindexed;
641
+ return [...unindexed];
799
642
  };
800
643
  var hasAggregatesWithoutGroupBy = (resolved) => resolved.aggregates.length > 0 && resolved.groupBy.length === 0;
801
644
  var analyze = (resolved, config) => {
@@ -866,7 +709,11 @@ var createMemoryCache = () => {
866
709
  const entries = async () => {
867
710
  return [...store.entries()].map(([key, entry]) => ({ key, entry }));
868
711
  };
869
- return { get, set, delete: del, clear, keys, entries };
712
+ const touch = async (key, lastUsedAt) => {
713
+ const entry = store.get(key);
714
+ if (entry !== void 0) store.set(key, { ...entry, lastUsedAt });
715
+ };
716
+ return { get, set, delete: del, clear, keys, entries, touch };
870
717
  };
871
718
 
872
719
  // src/engine/live.ts
@@ -1200,6 +1047,12 @@ var DEFAULT_MAX_LIMIT = 1e3;
1200
1047
  var DEFAULT_STATEMENT_TIMEOUT_MS = 1e4;
1201
1048
  var DEFAULT_UNSATISFIABLE_TTL_MS = 3e5;
1202
1049
  var DEFAULT_MAX_PRESENCE_VARIANTS = 32;
1050
+ var REMEMBERED_FINGERPRINTS = 1024;
1051
+ var forgetOldest = (noted) => {
1052
+ if (noted.size <= REMEMBERED_FINGERPRINTS) return;
1053
+ const oldest = noted.keys().next();
1054
+ if (oldest.done !== true) noted.delete(oldest.value);
1055
+ };
1203
1056
  var createQueryEngine = (engineConfig) => {
1204
1057
  const { adapter, scope: scopePolicy, generateDsl, mapToShape, embed, behaviors, upgrader } = engineConfig;
1205
1058
  const parsedColumns = UpgradedColumnsSchema.safeParse(engineConfig.upgradedColumns ?? {});
@@ -1241,6 +1094,7 @@ var createQueryEngine = (engineConfig) => {
1241
1094
  if (seen === void 0) {
1242
1095
  seen = /* @__PURE__ */ new Set();
1243
1096
  variantsSeen.set(fingerprint, seen);
1097
+ forgetOldest(variantsSeen);
1244
1098
  }
1245
1099
  if (seen.has(signature)) return;
1246
1100
  seen.add(signature);
@@ -1309,12 +1163,27 @@ var createQueryEngine = (engineConfig) => {
1309
1163
  return { compiled, warnings: analysis.warnings, upgrades: columnUpgrades(processedDsl, upgradedColumns), ...engineLimit !== void 0 ? { engineLimit } : {} };
1310
1164
  };
1311
1165
  const cutSaid = /* @__PURE__ */ new Set();
1166
+ const reachUnasked = /* @__PURE__ */ new Set();
1167
+ const policyAtReach = async (fingerprint, reach, current, options) => {
1168
+ if (options?.policyForReach === void 0) {
1169
+ if (!reachUnasked.has(fingerprint)) {
1170
+ reachUnasked.add(fingerprint);
1171
+ forgetOldest(reachUnasked);
1172
+ console.warn(`[vex] "${fingerprint}" declares reach "${reach}" and was replayed without policyForReach, so it ran under the caller's own policy. Pass policyForReach to serve it at its reach.`);
1173
+ }
1174
+ return current;
1175
+ }
1176
+ const narrowed = await options.policyForReach(reach);
1177
+ if (narrowed === void 0) throw new VexError("scope_denied", `Reach "${reach}" is not available to this principal.`);
1178
+ return narrowed;
1179
+ };
1312
1180
  const cutNote = (engineLimit, stated, rowCount, shape, fingerprint) => {
1313
1181
  if (engineLimit === void 0 || rowCount !== engineLimit) return void 0;
1314
1182
  if (shape !== void 0 && !Array.isArray(shape)) return void 0;
1315
1183
  const note = stated === void 0 ? `This list states no limit, so it ran with the engine's defaultLimit of ${engineLimit}, and exactly ${engineLimit} rows came back \u2014 it may have been cut. State a \`limit\`.` : `This query asks for ${stated} rows, the engine's maxLimit is ${engineLimit}, and exactly ${engineLimit} came back \u2014 the list may have been cut. Raise \`maxLimit\` to read more.`;
1316
1184
  if (fingerprint !== void 0 && !cutSaid.has(fingerprint)) {
1317
1185
  cutSaid.add(fingerprint);
1186
+ forgetOldest(cutSaid);
1318
1187
  console.warn(`[vex] "${fingerprint}": ${note}`);
1319
1188
  }
1320
1189
  return note;
@@ -1341,7 +1210,7 @@ var createQueryEngine = (engineConfig) => {
1341
1210
  };
1342
1211
  const touch = (key, entry) => {
1343
1212
  const now = Date.now();
1344
- if (isTouchDue(entry, now)) fireAndForget(cache.set(key, { ...entry, lastUsedAt: now }));
1213
+ if (isTouchDue(entry, now)) fireAndForget(touchEntry(cache, key, entry, now));
1345
1214
  };
1346
1215
  const resolveFingerprint = async (validRequest, hasRequest, requestHash, scope) => {
1347
1216
  const fp = validRequest.fingerprint;
@@ -1365,6 +1234,7 @@ var createQueryEngine = (engineConfig) => {
1365
1234
  ...entry.intent !== void 0 ? { intent: entry.intent } : {},
1366
1235
  ...entry.shape !== void 0 ? { shape: entry.shape } : {},
1367
1236
  ...entry.refresh !== void 0 ? { refresh: entry.refresh } : {},
1237
+ ...entry.reach !== void 0 ? { reach: entry.reach } : {},
1368
1238
  seeded: entry.protected === true && entry.requestHash === void 0,
1369
1239
  hit: true,
1370
1240
  replaced: false
@@ -1389,7 +1259,7 @@ var createQueryEngine = (engineConfig) => {
1389
1259
  const pruned = pruneOptional(dsl, "all");
1390
1260
  const { compiled, warnings, upgrades } = runPipeline(pruned, policy);
1391
1261
  requireScope(compiled, scope);
1392
- if (compiled.paramSlots.some((slot) => slot.kind === "semantic")) {
1262
+ if (compiled.paramSlots.some((slot) => slot.kind === "semantic" || slot.embed === true)) {
1393
1263
  return { rows: [], sql: compiled.sql, warnings: [...warnings, "Semantic params present \u2014 execution skipped, SQL structure validated only"] };
1394
1264
  }
1395
1265
  const params = compiled.paramSlots.map((slot) => slot.kind === "scope" ? scope[slot.key] : null);
@@ -1475,13 +1345,13 @@ var createQueryEngine = (engineConfig) => {
1475
1345
  };
1476
1346
  const execute$1 = async (request, options) => {
1477
1347
  if (exceedsDepth(request)) throw new VexError("invalid_request", `Invalid request: ${depthRefusal()}`);
1478
- const parsed = QueryRequestSchema.safeParse(request);
1348
+ const parsed = QueryRequestSchema.safeParse(dropNullIntentAndFingerprint(request));
1479
1349
  if (!parsed.success) {
1480
1350
  throw new VexError("invalid_request", `Invalid request: ${parsed.error.message}`);
1481
1351
  }
1482
1352
  const validRequest = parsed.data;
1483
1353
  const scope = options?.scope ?? {};
1484
- const activePolicy = options?.scopePolicy ?? scopePolicy;
1354
+ let activePolicy = options?.scopePolicy ?? scopePolicy;
1485
1355
  const t0 = Date.now();
1486
1356
  const hasRequest = validRequest.shape !== void 0 && validRequest.shape !== null;
1487
1357
  if (validRequest.fingerprint === void 0 && !hasRequest) {
@@ -1499,6 +1369,7 @@ var createQueryEngine = (engineConfig) => {
1499
1369
  });
1500
1370
  const cached = await resolveFingerprint(validRequest, hasRequest, requestHash, scope);
1501
1371
  emit({ type: "query.cache", hit: cached.hit, fingerprint: cached.fingerprint, replaced: cached.replaced });
1372
+ if (cached.reach !== void 0) activePolicy = await policyAtReach(cached.fingerprint, cached.reach, activePolicy, options);
1502
1373
  let dsl = cached.dsl;
1503
1374
  let agentMs;
1504
1375
  if (dsl === void 0) {
@@ -1644,6 +1515,7 @@ var createQueryEngine = (engineConfig) => {
1644
1515
  getDslSchema,
1645
1516
  getSchema,
1646
1517
  cache,
1518
+ ...scopePolicy !== void 0 ? { scopePolicy } : {},
1647
1519
  invalidate: live.invalidate,
1648
1520
  rows: { stats: live.stats, stop: live.stop }
1649
1521
  };
@@ -1691,6 +1563,8 @@ var COLUMNS_QUERY = `
1691
1563
  c.udt_name,
1692
1564
  c.is_nullable,
1693
1565
  c.column_default,
1566
+ c.is_identity,
1567
+ c.identity_generation,
1694
1568
  CASE
1695
1569
  WHEN c.data_type = 'USER-DEFINED' THEN c.udt_name
1696
1570
  WHEN c.data_type = 'ARRAY' THEN c.udt_name
@@ -1810,7 +1684,7 @@ var introspectPostgres = async (pool, options) => {
1810
1684
  const dataType = row["effective_type"];
1811
1685
  const fullType = row["full_type"];
1812
1686
  const isNullable = row["is_nullable"];
1813
- const colDefault = row["column_default"];
1687
+ const colDefault = row["column_default"] ?? (row["is_identity"] === "YES" ? `GENERATED ${String(row["identity_generation"])} AS IDENTITY` : null);
1814
1688
  const colDescription = row["description"];
1815
1689
  const tablePks = pkMap.get(table);
1816
1690
  const isPk = tablePks !== void 0 && tablePks.has(colName);
@@ -1916,22 +1790,23 @@ var mapIndexType = (pgType) => {
1916
1790
  };
1917
1791
 
1918
1792
  // src/adapters/postgres/compile.ts
1919
- var compileQuery = (resolved) => {
1793
+ var compileQuery = (resolved, namespace) => {
1920
1794
  const paramSlots = [];
1921
- const sql = compileLevel(resolved, paramSlots, { value: 0 });
1795
+ const sql = compileLevel(resolved, paramSlots, { value: 0 }, namespace);
1922
1796
  const contextContract = {};
1923
1797
  for (const slot of paramSlots) {
1924
1798
  contextContract[slot.key] = { type: slot.type, kind: slot.kind };
1925
1799
  }
1926
1800
  return { sql, paramSlots, contextContract };
1927
1801
  };
1928
- var compileLevel = (resolved, paramSlots, paramCounter) => {
1802
+ var compileLevel = (resolved, paramSlots, paramCounter, namespace) => {
1929
1803
  const ctx = {
1930
1804
  resolvedPaths: resolved.filter?.resolvedPaths ?? /* @__PURE__ */ new Map(),
1931
1805
  aliasMap: resolved.aliasMap,
1932
1806
  paramSlots,
1933
1807
  paramCounter,
1934
- ...resolved.existsMap !== void 0 ? { existsMap: resolved.existsMap } : {}
1808
+ ...resolved.existsMap !== void 0 ? { existsMap: resolved.existsMap } : {},
1809
+ ...namespace !== void 0 ? { namespace } : {}
1935
1810
  };
1936
1811
  const sqlParts = [];
1937
1812
  const selectParts = [];
@@ -1939,7 +1814,7 @@ var compileLevel = (resolved, paramSlots, paramCounter) => {
1939
1814
  selectParts.push("DISTINCT");
1940
1815
  }
1941
1816
  const fieldColumns = resolved.fields.map(
1942
- (f) => `${f.alias}.${f.column} AS ${quoteIdent(f.outputName)}`
1817
+ (f) => `${columnSql(f.alias, f.column)} AS ${quoteIdent(f.outputName)}`
1943
1818
  );
1944
1819
  const computeColumns = resolved.computes.map((c) => {
1945
1820
  const expr = compileCompute(c.expression, ctx);
@@ -1958,9 +1833,9 @@ var compileLevel = (resolved, paramSlots, paramCounter) => {
1958
1833
  const firstSource = resolved.sources[0];
1959
1834
  if (firstSource !== void 0) {
1960
1835
  if (firstSource.subquery !== void 0) {
1961
- sqlParts.push(`FROM (${compileLevel(firstSource.subquery, paramSlots, paramCounter)}) AS ${firstSource.alias}`);
1836
+ sqlParts.push(`FROM (${compileLevel(firstSource.subquery, paramSlots, paramCounter, namespace)}) AS ${sqlName(firstSource.alias)}`);
1962
1837
  } else if (firstSource.table !== void 0) {
1963
- sqlParts.push(`FROM ${firstSource.table} AS ${firstSource.alias}`);
1838
+ sqlParts.push(`FROM ${tableSql(firstSource.table, namespace)} AS ${sqlName(firstSource.alias)}`);
1964
1839
  }
1965
1840
  }
1966
1841
  for (const join of resolved.joins) {
@@ -1973,9 +1848,9 @@ var compileLevel = (resolved, paramSlots, paramCounter) => {
1973
1848
  ];
1974
1849
  const on = conditions.join(" AND ");
1975
1850
  if (joinSource.subquery !== void 0) {
1976
- sqlParts.push(`${keyword} (${compileLevel(joinSource.subquery, paramSlots, paramCounter)}) AS ${join.toAlias} ON ${on}`);
1851
+ sqlParts.push(`${keyword} (${compileLevel(joinSource.subquery, paramSlots, paramCounter, namespace)}) AS ${sqlName(join.toAlias)} ON ${on}`);
1977
1852
  } else {
1978
- sqlParts.push(`${keyword} ${join.toTable} AS ${join.toAlias} ON ${on}`);
1853
+ sqlParts.push(`${keyword} ${tableSql(join.toTable, namespace)} AS ${sqlName(join.toAlias)} ON ${on}`);
1979
1854
  }
1980
1855
  }
1981
1856
  }
@@ -1983,9 +1858,9 @@ var compileLevel = (resolved, paramSlots, paramCounter) => {
1983
1858
  for (const source of resolved.sources) {
1984
1859
  if (source.alias === firstSource?.alias || joinedAliases.has(source.alias)) continue;
1985
1860
  if (source.subquery !== void 0) {
1986
- sqlParts.push(`CROSS JOIN (${compileLevel(source.subquery, paramSlots, paramCounter)}) AS ${source.alias}`);
1861
+ sqlParts.push(`CROSS JOIN (${compileLevel(source.subquery, paramSlots, paramCounter, namespace)}) AS ${sqlName(source.alias)}`);
1987
1862
  } else if (source.table !== void 0) {
1988
- sqlParts.push(`CROSS JOIN ${source.table} AS ${source.alias}`);
1863
+ sqlParts.push(`CROSS JOIN ${tableSql(source.table, namespace)} AS ${sqlName(source.alias)}`);
1989
1864
  }
1990
1865
  }
1991
1866
  if (resolved.filter !== void 0) {
@@ -1993,7 +1868,7 @@ var compileLevel = (resolved, paramSlots, paramCounter) => {
1993
1868
  sqlParts.push(`WHERE ${whereClause}`);
1994
1869
  }
1995
1870
  if (resolved.groupBy.length > 0) {
1996
- const groupByParts = resolved.groupBy.map((f) => `${f.alias}.${f.column}`);
1871
+ const groupByParts = resolved.groupBy.map((f) => columnSql(f.alias, f.column));
1997
1872
  sqlParts.push(`GROUP BY ${groupByParts.join(", ")}`);
1998
1873
  }
1999
1874
  if (resolved.sort.length > 0) {
@@ -2001,13 +1876,13 @@ var compileLevel = (resolved, paramSlots, paramCounter) => {
2001
1876
  if (typeof s.field === "string") {
2002
1877
  return `${quoteIdent(s.field)} ${s.dir === "desc" ? "DESC" : "ASC"}`;
2003
1878
  }
2004
- return `${s.field.alias}.${s.field.column} ${s.dir === "desc" ? "DESC" : "ASC"}`;
1879
+ return `${columnSql(s.field.alias, s.field.column)} ${s.dir === "desc" ? "DESC" : "ASC"}`;
2005
1880
  });
2006
1881
  sqlParts.push(`ORDER BY ${orderByParts.join(", ")}`);
2007
1882
  } else if (resolved.semantic !== void 0) {
2008
1883
  const { field, contextPath } = resolved.semantic;
2009
- const position = paramSlots.findIndex((slot) => slot.kind === "semantic" && slot.key === contextPath) + 1;
2010
- if (position > 0) sqlParts.push(`ORDER BY ${field.alias}.${field.column} <=> $${position} ASC`);
1884
+ const position = paramSlots.findIndex((slot) => (slot.kind === "semantic" || slot.embed === true) && slot.key === contextPath) + 1;
1885
+ if (position > 0) sqlParts.push(`ORDER BY ${columnSql(field.alias, field.column)} <=> $${position} ASC`);
2011
1886
  }
2012
1887
  if (resolved.limit !== void 0) {
2013
1888
  if (!Number.isInteger(resolved.limit) || resolved.limit < 1) {
@@ -2062,6 +1937,7 @@ var coerceNumericColumns = (rows, fields) => {
2062
1937
  };
2063
1938
  var createPostgresAdapter = (config) => {
2064
1939
  const { pool, schema = "public", exclude } = config;
1940
+ const namespace = config.qualifyTables === true ? schema : void 0;
2065
1941
  const capabilities = {
2066
1942
  vectorSearch: true,
2067
1943
  fuzzyMatch: false,
@@ -2073,12 +1949,15 @@ var createPostgresAdapter = (config) => {
2073
1949
  windowFunctions: true,
2074
1950
  statementTimeout: true
2075
1951
  };
2076
- const introspect = async (options) => introspectPostgres(pool, {
2077
- ...options,
2078
- schema: options?.schema ?? schema,
2079
- exclude: options?.exclude ?? exclude
2080
- });
2081
- const compile2 = (resolved) => compileQuery(resolved);
1952
+ const introspect = async (options) => {
1953
+ const introspected = await introspectPostgres(pool, {
1954
+ ...options,
1955
+ schema: options?.schema ?? schema,
1956
+ exclude: options?.exclude ?? exclude
1957
+ });
1958
+ return namespace === void 0 ? introspected : { ...introspected, namespace };
1959
+ };
1960
+ const compile2 = (resolved) => compileQuery(resolved, namespace);
2082
1961
  let perStatementMs;
2083
1962
  const limitReads = async (ms) => {
2084
1963
  perStatementMs = void 0;
@@ -2121,7 +2000,7 @@ var vexGuide = () => [
2121
2000
  ' - A value the query filters with ILIKE is a pattern: "%text%" matches contains.',
2122
2001
  ' - 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".',
2123
2002
  "",
2124
- "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.",
2003
+ "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 did NOT run, and the result is an empty list whatever the shape. Supply the keys and send the request again. Optional keys never appear there; leaving one out is a choice, not a mistake.",
2125
2004
  "",
2126
2005
  "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."
2127
2006
  ].join("\n");
@@ -2357,7 +2236,10 @@ var createPostgresCache = (config) => {
2357
2236
  }
2358
2237
  return out;
2359
2238
  };
2360
- return { init, sequence, get, set, delete: del, clear, keys, entries };
2239
+ const touch = async (key, lastUsedAt) => {
2240
+ await pool.query(`UPDATE ${qualified} SET last_used_at = $2 WHERE key = $1`, [key, new Date(lastUsedAt)]);
2241
+ };
2242
+ return { init, sequence, get, set, delete: del, clear, keys, entries, touch };
2361
2243
  };
2362
2244
 
2363
2245
  // src/cache/tiered.ts
@@ -2419,7 +2301,22 @@ var createTieredCache = (config) => {
2419
2301
  fireAndForget(l2.clear(), onError);
2420
2302
  };
2421
2303
  const keys = async () => l1.keys();
2422
- return { init, get, set, delete: del, clear, keys, ...l2.sequence !== void 0 ? { sequence: l2.sequence } : {} };
2304
+ const { touch: touchL1 } = l1;
2305
+ const { touch: touchL2 } = l2;
2306
+ const touch = touchL1 === void 0 || touchL2 === void 0 ? void 0 : async (key, lastUsedAt) => {
2307
+ await touchL1(key, lastUsedAt);
2308
+ fireAndForget(touchL2(key, lastUsedAt), onError);
2309
+ };
2310
+ return {
2311
+ init,
2312
+ get,
2313
+ set,
2314
+ delete: del,
2315
+ clear,
2316
+ keys,
2317
+ ...touch !== void 0 ? { touch } : {},
2318
+ ...l2.sequence !== void 0 ? { sequence: l2.sequence } : {}
2319
+ };
2423
2320
  };
2424
2321
  var same = (a, b) => a === void 0 || b === void 0 ? a === b : canonicalText(a) === canonicalText(b);
2425
2322
  var seedCache = async (cache, entries) => {
@@ -2460,6 +2357,6 @@ var seedCache = async (cache, entries) => {
2460
2357
  }
2461
2358
  };
2462
2359
 
2463
- export { SCOPE_VERBS, UNREADABLE_MODES, UpgradedColumnsSchema, analyze, createMemoryCache, createPostgresAdapter, createPostgresCache, createQueryEngine, createScopePolicy, createTieredCache, discoverEntities, mergeScopePolicies, resolve, scopeBindings, scopeGrants, scopeProfiles, seedCache, validateEntry, vexGuide };
2360
+ export { SCOPE_VERBS, UNREADABLE_MODES, UpgradedColumnsSchema, analyze, createMemoryCache, createPostgresAdapter, createPostgresCache, createQueryEngine, createScopePolicy, createTieredCache, mergeScopePolicies, resolve, scopeBindings, scopeGrants, scopeProfiles, seedCache, validateEntry, vexGuide };
2464
2361
  //# sourceMappingURL=index.js.map
2465
2362
  //# sourceMappingURL=index.js.map