@niscorp/vex 0.3.0 → 0.4.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 (52) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/DESIGN.md +30 -14
  3. package/DOCS.md +65 -13
  4. package/dist/adapters/express/index.cjs +7 -25
  5. package/dist/adapters/express/index.cjs.map +1 -1
  6. package/dist/adapters/express/index.d.cts +3 -2
  7. package/dist/adapters/express/index.d.ts +3 -2
  8. package/dist/adapters/express/index.js +3 -2
  9. package/dist/adapters/express/index.js.map +1 -1
  10. package/dist/adapters/hono/index.cjs +7 -25
  11. package/dist/adapters/hono/index.cjs.map +1 -1
  12. package/dist/adapters/hono/index.d.cts +3 -2
  13. package/dist/adapters/hono/index.d.ts +3 -2
  14. package/dist/adapters/hono/index.js +3 -2
  15. package/dist/adapters/hono/index.js.map +1 -1
  16. package/dist/adapters/pglite/index.cjs.map +1 -1
  17. package/dist/adapters/pglite/index.js.map +1 -1
  18. package/dist/agent/index.cjs +9 -14
  19. package/dist/agent/index.cjs.map +1 -1
  20. package/dist/agent/index.d.cts +3 -2
  21. package/dist/agent/index.d.ts +3 -2
  22. package/dist/agent/index.js +8 -9
  23. package/dist/agent/index.js.map +1 -1
  24. package/dist/{chunk-IQM4SQE2.js → chunk-7F2OH4IP.js} +8 -22
  25. package/dist/chunk-7F2OH4IP.js.map +1 -0
  26. package/dist/chunk-F7RDSWYF.js +7 -0
  27. package/dist/chunk-F7RDSWYF.js.map +1 -0
  28. package/dist/{chunk-H4BHW76Q.js → chunk-UPQMKAAX.js} +6 -24
  29. package/dist/chunk-UPQMKAAX.js.map +1 -0
  30. package/dist/chunk-XTOK7YOR.js +18 -0
  31. package/dist/chunk-XTOK7YOR.js.map +1 -0
  32. package/dist/{handler-BGCL6_Si.d.ts → handler-Bw7xVmBM.d.ts} +2 -1
  33. package/dist/{handler-CMrjTXNx.d.cts → handler-Cy0gNM6K.d.cts} +2 -1
  34. package/dist/index.cjs +44 -90
  35. package/dist/index.cjs.map +1 -1
  36. package/dist/index.d.cts +17 -63
  37. package/dist/index.d.ts +17 -63
  38. package/dist/index.js +46 -74
  39. package/dist/index.js.map +1 -1
  40. package/dist/migrations/index.cjs +173 -0
  41. package/dist/migrations/index.cjs.map +1 -0
  42. package/dist/migrations/index.d.cts +20 -0
  43. package/dist/migrations/index.d.ts +20 -0
  44. package/dist/migrations/index.js +23 -0
  45. package/dist/migrations/index.js.map +1 -0
  46. package/dist/query.schema-B-LVNfyX.d.cts +461 -0
  47. package/dist/query.schema-B-LVNfyX.d.ts +461 -0
  48. package/dist/{types-Bi-Lg86b.d.cts → types-Bs_9VM9p.d.ts} +16 -583
  49. package/dist/{types-Bi-Lg86b.d.ts → types-DO-rYZci.d.cts} +16 -583
  50. package/package.json +17 -7
  51. package/dist/chunk-H4BHW76Q.js.map +0 -1
  52. package/dist/chunk-IQM4SQE2.js.map +0 -1
package/dist/index.d.cts CHANGED
@@ -1,10 +1,12 @@
1
- import { Q as QueryEngineConfig, a as QueryEngine, b as Query, D as DatabaseSchema, R as ResolvedQuery, A as AnalysisConfig, c as AnalysisResult, C as CompiledQuery, d as ContextMeta, e as DatabaseAdapter, f as Row, F as FieldSchema, P as ParamSlot, g as ResolvedExists, h as FieldOrValue, i as Filter, j as QueryErrorCode, S as ScopePolicy, k as CacheBackend, l as CacheEntry, m as Refresh, M as MutationDefinition, n as ContextContract } from './types-Bi-Lg86b.cjs';
2
- export { o as AdapterCapabilities, p as AggregateExpression, q as AggregateExpressionSchema, B as BoundParams, r as ComputeExpression, s as ComputeExpressionSchema, t as ContextRef, u as CoreMutation, E as EntitySchema, v as ExecuteOptions, w as FilterSchema, G as GenerateDsl, x as GenerationCaller, I as IndexSchema, y as IntrospectOptions, z as ItemRef, L as LiveRowsConfig, H as LiveRowsStats, J as LookupValue, K as MapToShape, N as Mutation, O as MutationCacheEntry, T as MutationDefinitionSchema, U as MutationSchema, V as MutationValue, W as NamedScopeBehaviors, X as NormalizedType, Y as OkCacheEntry, Z as QueryErrorResponse, _ as QueryRequest, $ as QueryRequestSchema, a0 as QueryResponse, a1 as QuerySchema, a2 as REFRESH_MODES, a3 as RelationSchema, a4 as ResolvedField, a5 as ResolvedFilter, a6 as ResolvedJoin, a7 as ResolvedMutation, a8 as ResolvedOnConflict, a9 as ResolvedSemantic, aa as ResolvedSource, ab as ReturnedRef, ac as SCOPE_VERBS, ad as ScopeBehaviors, ae as ScopeBinding, af as ScopeEntityRule, ag as ScopeMatch, ah as ScopeRef, ai as ScopeRule, aj as ScopeRules, ak as ScopeSet, al as ScopeValues, am as SortEntry, an as Source, ao as TestResult, ap as UnsatisfiableCacheEntry, aq as VexEvent, ar as VexEventHandler, as as createScopePolicy, at as isRefresh, au as mergeScopePolicies, av as scopeBindings, aw as scopeGrants, ax as scopeProfiles } from './types-Bi-Lg86b.cjs';
1
+ import { Q as QueryEngineConfig, a as QueryEngine, D as DatabaseSchema, R as ResolvedQuery, A as AnalysisConfig, b as AnalysisResult, C as CompiledQuery, c as ContextMeta, d as DatabaseAdapter, e as Row, F as FieldSchema, P as ParamSlot, f as ResolvedExists, g as QueryErrorCode, S as ScopePolicy, h as CacheBackend, i as CacheEntry, j as Refresh, M as MutationDefinition, k as ContextContract } from './types-DO-rYZci.cjs';
2
+ export { l as AdapterCapabilities, B as BoundParams, m as CoreMutation, E as EntitySchema, n as ExecuteOptions, G as GenerateDsl, o as GenerationCaller, I as IndexSchema, p as IntrospectOptions, q as ItemRef, L as LiveRowsConfig, r as LiveRowsStats, s as LookupValue, t as MapToShape, u as Mutation, v as MutationCacheEntry, w as MutationDefinitionSchema, x as MutationSchema, y as MutationValue, N as NamedScopeBehaviors, z as NormalizedType, O as OkCacheEntry, H as QueryErrorResponse, J as QueryRequest, K as QueryRequestSchema, T as QueryResponse, U as REFRESH_MODES, V as RelationSchema, W as ResolvedField, X as ResolvedFilter, Y as ResolvedJoin, Z as ResolvedMutation, _ as ResolvedOnConflict, $ as ResolvedSemantic, a0 as ResolvedSource, a1 as ReturnedRef, a2 as SCOPE_VERBS, a3 as ScopeBehaviors, a4 as ScopeBinding, a5 as ScopeEntityRule, a6 as ScopeMatch, a7 as ScopeRule, a8 as ScopeRules, a9 as ScopeSet, aa as ScopeValues, ab as TestResult, ac as UnsatisfiableCacheEntry, ad as VexEvent, ae as VexEventHandler, af as createScopePolicy, ag as isRefresh, ah as mergeScopePolicies, ai as scopeBindings, aj as scopeGrants, ak as scopeProfiles } from './types-DO-rYZci.cjs';
3
+ import { Q as Query, F as FieldOrValue, a as Filter } from './query.schema-B-LVNfyX.cjs';
4
+ export { A as AggregateExpression, b as AggregateExpressionSchema, C as ComputeExpression, c as ComputeExpressionSchema, d as ContextRef, e as FilterSchema, f as QuerySchema, S as ScopeRef, g as SortEntry, h as Source } from './query.schema-B-LVNfyX.cjs';
3
5
  import { P as PgPool } from './introspect-D3OaXHBc.cjs';
4
6
  import { Sequence } from '@niscorp/strata';
5
- export { C as ContextField, a as ContextSignature, D as DiscoveryFingerprint, b as DiscoveryResponse, E as ExecuteRecord, M as MutationClient, c as MutationContext, d as MutationEffect, e as MutationTx, Q as QueryResult, V as VexHandlerConfig, f as VexLive, W as WriteEvent, g as WriteResult, h as collectMutationContext, i as collectQueryContext, j as executeMutation, k as executeWrites, l as handleDiscovery, m as handleFingerprintDelete, n as handleFingerprintPatch, o as handleQuery, p as lintMutation, q as mutationEffect, r as mutationMisfits, s as requiredContextKeys, t as tablesChangedBy } from './handler-CMrjTXNx.cjs';
6
- import 'zod';
7
+ export { C as ContextField, a as ContextSignature, D as DiscoveryFingerprint, b as DiscoveryResponse, E as ExecuteRecord, M as MutationClient, c as MutationContext, d as MutationEffect, e as MutationTx, Q as QueryResult, V as VexHandlerConfig, f as VexLive, W as WriteEvent, g as WriteResult, h as collectMutationContext, i as collectQueryContext, j as executeMutation, k as executeWrites, l as handleDiscovery, m as handleFingerprintDelete, n as handleFingerprintPatch, o as handleQuery, p as lintMutation, q as mutationEffect, r as mutationMisfits, s as requiredContextKeys, t as tablesChangedBy } from './handler-Cy0gNM6K.cjs';
7
8
  import '@niscorp/prism';
9
+ import 'zod';
8
10
 
9
11
  declare const createQueryEngine: (engineConfig: QueryEngineConfig) => QueryEngine;
10
12
 
@@ -16,38 +18,13 @@ declare const executeQuery: (compiled: CompiledQuery, context: Record<string, un
16
18
  declare const buildContextContract: (compiled: CompiledQuery, optionalKeys?: readonly string[]) => Record<string, ContextMeta>;
17
19
  declare const findMissingContext: (compiled: CompiledQuery, context: Record<string, unknown>) => string[];
18
20
 
19
- /** Every optional key mentioned anywhere in a query, in declaration order. */
20
21
  declare const optionalKeysOf: (dsl: Query) => string[];
21
- /** Which context keys the caller actually supplied.
22
- *
23
- * ABSENT MEANS MISSING, `undefined`, OR `null`. The empty string is a value —
24
- * searching for `''` is a real search — but null is not, for two reasons that
25
- * agree:
26
- *
27
- * · SQL. A bound null in a comparison can never match: `col = NULL` and
28
- * `col ILIKE NULL` are both NULL, never true. So "send null" could only ever
29
- * have meant "I have nothing", and vex already has `isNull`/`isNotNull` for
30
- * the question people actually mean by it. Nothing is lost.
31
- *
32
- * · The wire. JSON has no `undefined`, and a request prism assembles a fixed
33
- * object — it cannot conditionally omit a key. Without null counting as
34
- * absent, every caller with an empty search box would have to bind a
35
- * sentinel again, which is the exact thing this feature removes.
36
- *
37
- * This is deliberately WIDER than `findMissingContext`'s test, which stays on
38
- * `undefined` alone. A required key sent as null still binds null and matches
39
- * nothing; an optional key sent as null drops its condition. That reads like a
40
- * contradiction and is not: the author chose which keys are optional, and for
41
- * those they have already said absence means "this does not apply". A caller
42
- * gains nothing by it either — omitting the key does the same thing, and scope
43
- * is injected after this either way. */
22
+ /** null counts as absent, wider than `findMissingContext`'s `undefined`: JSON
23
+ * has no `undefined`, and a bound null never matches in a comparison anyway.
24
+ * The empty string is a value. */
44
25
  declare const presenceOf: (context: Record<string, unknown>) => ReadonlySet<string>;
45
- /** Resolve every optional condition against the keys a caller supplied.
46
- *
47
- * A query whose filter prunes away entirely comes back with NO filter, which
48
- * is the point: `people/list` with no lens, no search and no cursor is the
49
- * whole roll, and it says so by having nothing to say. Scope is injected
50
- * after this, so "no filter" still never means "every tenant". */
26
+ /** Scope is injected after this, so a filter pruned away entirely still never
27
+ * means every tenant. */
51
28
  declare const pruneOptional: (dsl: Query, present: ReadonlySet<string> | "all") => Query;
52
29
 
53
30
  type PostgresAdapterConfig = {
@@ -90,18 +67,19 @@ declare class VexScopeError extends VexError {
90
67
  }
91
68
  declare const checkScope: (entities: Set<string>, policy: ScopePolicy) => void;
92
69
  declare const scopeResolved: (resolved: ResolvedQuery, policy: ScopePolicy) => ResolvedQuery;
70
+ /**
71
+ * @deprecated Checks access only and returns the query as it came, with no row
72
+ * rule added. Use `checkScope`; row rules are placed by `scopeResolved`, on the
73
+ * resolved query.
74
+ */
93
75
  declare const applyScope: (dsl: Query, entities: Set<string>, policy: ScopePolicy) => Query;
94
76
 
95
77
  declare const createMemoryCache: () => CacheBackend;
96
78
 
97
79
  type PostgresCacheConfig = {
98
- /** A pg Pool (or anything matching its query shape). The caller owns its lifecycle. */
99
80
  pool: PgPool;
100
- /** Schema to place the cache table in. Default: 'public'. */
101
81
  schema?: string;
102
- /** Table name. Default: 'vex_cache'. */
103
82
  table?: string;
104
- /** Called on rejected writes and evicted-on-read invalid rows. */
105
83
  onError?: (err: unknown) => void;
106
84
  };
107
85
  type PostgresCache = CacheBackend & {
@@ -114,24 +92,14 @@ type PostgresCache = CacheBackend & {
114
92
  };
115
93
  declare const createPostgresCache: (config: PostgresCacheConfig) => PostgresCache;
116
94
 
117
- type WarmupMode =
118
- /** Load all of L2 into L1 on init (default). Start fully hot. */
119
- 'full'
120
- /** Don't preload; L1 fills on demand via get→promote. Bounded memory. */
121
- | 'lazy'
122
- /** Preload only these fingerprints; lazy-fill the rest. */
123
- | {
95
+ type WarmupMode = 'full' | 'lazy' | {
124
96
  mode: 'partial';
125
97
  fingerprints: string[];
126
98
  };
127
99
  type TieredCacheConfig = {
128
- /** Fast, volatile tier (e.g. createMemoryCache()). */
129
100
  l1: CacheBackend;
130
- /** Durable source of truth (e.g. createPostgresCache(...)). */
131
101
  l2: CacheBackend;
132
- /** Warm-up strategy run by init(). Default: 'full'. */
133
102
  warmup?: WarmupMode;
134
- /** Called on background failures (async L2 writes) and dropped invalid entries. */
135
103
  onError?: (err: unknown) => void;
136
104
  };
137
105
  type TieredCache = CacheBackend & {
@@ -139,10 +107,6 @@ type TieredCache = CacheBackend & {
139
107
  };
140
108
  declare const createTieredCache: (config: TieredCacheConfig) => TieredCache;
141
109
 
142
- /**
143
- * Returns `null` if the entry is valid, or a human-readable reason
144
- * string if it is not.
145
- */
146
110
  declare const validateEntry: (entry: CacheEntry) => string | null;
147
111
 
148
112
  declare const normalizeShape: (shape: unknown) => unknown;
@@ -154,13 +118,6 @@ declare const computeRequestHash: (request: {
154
118
  }) => string;
155
119
  declare const computeSchemaFingerprint: (schema: DatabaseSchema) => string;
156
120
 
157
- /**
158
- * Lifetime = usage. Evicts unprotected entries that have not been
159
- * replayed within `maxIdleMs` (falling back to createdAt for entries
160
- * never touched). Protected entries never sweep. Run it on whatever
161
- * cadence suits the app (startup, a timer, a cron) — it is hygiene,
162
- * not a correctness requirement: entries are single-digit KB.
163
- */
164
121
  declare const sweepCache: (cache: {
165
122
  entries?: () => Promise<Array<{
166
123
  key: string;
@@ -179,16 +136,13 @@ type SeedEntry = {
179
136
  shape?: unknown;
180
137
  dsl: Query;
181
138
  mapping?: unknown;
182
- /** The reach this read requires whatever the caller holds — see `OkCacheEntry.reach`. */
183
139
  reach?: string;
184
- /** When this read's answer is refreshed — see `Refresh`. Absent means 'snapshot'. */
185
140
  refresh?: Refresh;
186
141
  };
187
142
  type SeedMutation = {
188
143
  fingerprint: string;
189
144
  intent?: string;
190
145
  mutation: MutationDefinition;
191
- /** The reach this write requires whatever the caller holds — see `MutationCacheEntry.reach`. */
192
146
  reach?: string;
193
147
  };
194
148
  declare const seedCache: (cache: CacheBackend, entries: readonly (SeedEntry | SeedMutation)[]) => Promise<void>;
package/dist/index.d.ts CHANGED
@@ -1,10 +1,12 @@
1
- import { Q as QueryEngineConfig, a as QueryEngine, b as Query, D as DatabaseSchema, R as ResolvedQuery, A as AnalysisConfig, c as AnalysisResult, C as CompiledQuery, d as ContextMeta, e as DatabaseAdapter, f as Row, F as FieldSchema, P as ParamSlot, g as ResolvedExists, h as FieldOrValue, i as Filter, j as QueryErrorCode, S as ScopePolicy, k as CacheBackend, l as CacheEntry, m as Refresh, M as MutationDefinition, n as ContextContract } from './types-Bi-Lg86b.js';
2
- export { o as AdapterCapabilities, p as AggregateExpression, q as AggregateExpressionSchema, B as BoundParams, r as ComputeExpression, s as ComputeExpressionSchema, t as ContextRef, u as CoreMutation, E as EntitySchema, v as ExecuteOptions, w as FilterSchema, G as GenerateDsl, x as GenerationCaller, I as IndexSchema, y as IntrospectOptions, z as ItemRef, L as LiveRowsConfig, H as LiveRowsStats, J as LookupValue, K as MapToShape, N as Mutation, O as MutationCacheEntry, T as MutationDefinitionSchema, U as MutationSchema, V as MutationValue, W as NamedScopeBehaviors, X as NormalizedType, Y as OkCacheEntry, Z as QueryErrorResponse, _ as QueryRequest, $ as QueryRequestSchema, a0 as QueryResponse, a1 as QuerySchema, a2 as REFRESH_MODES, a3 as RelationSchema, a4 as ResolvedField, a5 as ResolvedFilter, a6 as ResolvedJoin, a7 as ResolvedMutation, a8 as ResolvedOnConflict, a9 as ResolvedSemantic, aa as ResolvedSource, ab as ReturnedRef, ac as SCOPE_VERBS, ad as ScopeBehaviors, ae as ScopeBinding, af as ScopeEntityRule, ag as ScopeMatch, ah as ScopeRef, ai as ScopeRule, aj as ScopeRules, ak as ScopeSet, al as ScopeValues, am as SortEntry, an as Source, ao as TestResult, ap as UnsatisfiableCacheEntry, aq as VexEvent, ar as VexEventHandler, as as createScopePolicy, at as isRefresh, au as mergeScopePolicies, av as scopeBindings, aw as scopeGrants, ax as scopeProfiles } from './types-Bi-Lg86b.js';
1
+ import { Q as QueryEngineConfig, a as QueryEngine, D as DatabaseSchema, R as ResolvedQuery, A as AnalysisConfig, b as AnalysisResult, C as CompiledQuery, c as ContextMeta, d as DatabaseAdapter, e as Row, F as FieldSchema, P as ParamSlot, f as ResolvedExists, g as QueryErrorCode, S as ScopePolicy, h as CacheBackend, i as CacheEntry, j as Refresh, M as MutationDefinition, k as ContextContract } from './types-Bs_9VM9p.js';
2
+ export { l as AdapterCapabilities, B as BoundParams, m as CoreMutation, E as EntitySchema, n as ExecuteOptions, G as GenerateDsl, o as GenerationCaller, I as IndexSchema, p as IntrospectOptions, q as ItemRef, L as LiveRowsConfig, r as LiveRowsStats, s as LookupValue, t as MapToShape, u as Mutation, v as MutationCacheEntry, w as MutationDefinitionSchema, x as MutationSchema, y as MutationValue, N as NamedScopeBehaviors, z as NormalizedType, O as OkCacheEntry, H as QueryErrorResponse, J as QueryRequest, K as QueryRequestSchema, T as QueryResponse, U as REFRESH_MODES, V as RelationSchema, W as ResolvedField, X as ResolvedFilter, Y as ResolvedJoin, Z as ResolvedMutation, _ as ResolvedOnConflict, $ as ResolvedSemantic, a0 as ResolvedSource, a1 as ReturnedRef, a2 as SCOPE_VERBS, a3 as ScopeBehaviors, a4 as ScopeBinding, a5 as ScopeEntityRule, a6 as ScopeMatch, a7 as ScopeRule, a8 as ScopeRules, a9 as ScopeSet, aa as ScopeValues, ab as TestResult, ac as UnsatisfiableCacheEntry, ad as VexEvent, ae as VexEventHandler, af as createScopePolicy, ag as isRefresh, ah as mergeScopePolicies, ai as scopeBindings, aj as scopeGrants, ak as scopeProfiles } from './types-Bs_9VM9p.js';
3
+ import { Q as Query, F as FieldOrValue, a as Filter } from './query.schema-B-LVNfyX.js';
4
+ export { A as AggregateExpression, b as AggregateExpressionSchema, C as ComputeExpression, c as ComputeExpressionSchema, d as ContextRef, e as FilterSchema, f as QuerySchema, S as ScopeRef, g as SortEntry, h as Source } from './query.schema-B-LVNfyX.js';
3
5
  import { P as PgPool } from './introspect-D3OaXHBc.js';
4
6
  import { Sequence } from '@niscorp/strata';
5
- export { C as ContextField, a as ContextSignature, D as DiscoveryFingerprint, b as DiscoveryResponse, E as ExecuteRecord, M as MutationClient, c as MutationContext, d as MutationEffect, e as MutationTx, Q as QueryResult, V as VexHandlerConfig, f as VexLive, W as WriteEvent, g as WriteResult, h as collectMutationContext, i as collectQueryContext, j as executeMutation, k as executeWrites, l as handleDiscovery, m as handleFingerprintDelete, n as handleFingerprintPatch, o as handleQuery, p as lintMutation, q as mutationEffect, r as mutationMisfits, s as requiredContextKeys, t as tablesChangedBy } from './handler-BGCL6_Si.js';
6
- import 'zod';
7
+ export { C as ContextField, a as ContextSignature, D as DiscoveryFingerprint, b as DiscoveryResponse, E as ExecuteRecord, M as MutationClient, c as MutationContext, d as MutationEffect, e as MutationTx, Q as QueryResult, V as VexHandlerConfig, f as VexLive, W as WriteEvent, g as WriteResult, h as collectMutationContext, i as collectQueryContext, j as executeMutation, k as executeWrites, l as handleDiscovery, m as handleFingerprintDelete, n as handleFingerprintPatch, o as handleQuery, p as lintMutation, q as mutationEffect, r as mutationMisfits, s as requiredContextKeys, t as tablesChangedBy } from './handler-Bw7xVmBM.js';
7
8
  import '@niscorp/prism';
9
+ import 'zod';
8
10
 
9
11
  declare const createQueryEngine: (engineConfig: QueryEngineConfig) => QueryEngine;
10
12
 
@@ -16,38 +18,13 @@ declare const executeQuery: (compiled: CompiledQuery, context: Record<string, un
16
18
  declare const buildContextContract: (compiled: CompiledQuery, optionalKeys?: readonly string[]) => Record<string, ContextMeta>;
17
19
  declare const findMissingContext: (compiled: CompiledQuery, context: Record<string, unknown>) => string[];
18
20
 
19
- /** Every optional key mentioned anywhere in a query, in declaration order. */
20
21
  declare const optionalKeysOf: (dsl: Query) => string[];
21
- /** Which context keys the caller actually supplied.
22
- *
23
- * ABSENT MEANS MISSING, `undefined`, OR `null`. The empty string is a value —
24
- * searching for `''` is a real search — but null is not, for two reasons that
25
- * agree:
26
- *
27
- * · SQL. A bound null in a comparison can never match: `col = NULL` and
28
- * `col ILIKE NULL` are both NULL, never true. So "send null" could only ever
29
- * have meant "I have nothing", and vex already has `isNull`/`isNotNull` for
30
- * the question people actually mean by it. Nothing is lost.
31
- *
32
- * · The wire. JSON has no `undefined`, and a request prism assembles a fixed
33
- * object — it cannot conditionally omit a key. Without null counting as
34
- * absent, every caller with an empty search box would have to bind a
35
- * sentinel again, which is the exact thing this feature removes.
36
- *
37
- * This is deliberately WIDER than `findMissingContext`'s test, which stays on
38
- * `undefined` alone. A required key sent as null still binds null and matches
39
- * nothing; an optional key sent as null drops its condition. That reads like a
40
- * contradiction and is not: the author chose which keys are optional, and for
41
- * those they have already said absence means "this does not apply". A caller
42
- * gains nothing by it either — omitting the key does the same thing, and scope
43
- * is injected after this either way. */
22
+ /** null counts as absent, wider than `findMissingContext`'s `undefined`: JSON
23
+ * has no `undefined`, and a bound null never matches in a comparison anyway.
24
+ * The empty string is a value. */
44
25
  declare const presenceOf: (context: Record<string, unknown>) => ReadonlySet<string>;
45
- /** Resolve every optional condition against the keys a caller supplied.
46
- *
47
- * A query whose filter prunes away entirely comes back with NO filter, which
48
- * is the point: `people/list` with no lens, no search and no cursor is the
49
- * whole roll, and it says so by having nothing to say. Scope is injected
50
- * after this, so "no filter" still never means "every tenant". */
26
+ /** Scope is injected after this, so a filter pruned away entirely still never
27
+ * means every tenant. */
51
28
  declare const pruneOptional: (dsl: Query, present: ReadonlySet<string> | "all") => Query;
52
29
 
53
30
  type PostgresAdapterConfig = {
@@ -90,18 +67,19 @@ declare class VexScopeError extends VexError {
90
67
  }
91
68
  declare const checkScope: (entities: Set<string>, policy: ScopePolicy) => void;
92
69
  declare const scopeResolved: (resolved: ResolvedQuery, policy: ScopePolicy) => ResolvedQuery;
70
+ /**
71
+ * @deprecated Checks access only and returns the query as it came, with no row
72
+ * rule added. Use `checkScope`; row rules are placed by `scopeResolved`, on the
73
+ * resolved query.
74
+ */
93
75
  declare const applyScope: (dsl: Query, entities: Set<string>, policy: ScopePolicy) => Query;
94
76
 
95
77
  declare const createMemoryCache: () => CacheBackend;
96
78
 
97
79
  type PostgresCacheConfig = {
98
- /** A pg Pool (or anything matching its query shape). The caller owns its lifecycle. */
99
80
  pool: PgPool;
100
- /** Schema to place the cache table in. Default: 'public'. */
101
81
  schema?: string;
102
- /** Table name. Default: 'vex_cache'. */
103
82
  table?: string;
104
- /** Called on rejected writes and evicted-on-read invalid rows. */
105
83
  onError?: (err: unknown) => void;
106
84
  };
107
85
  type PostgresCache = CacheBackend & {
@@ -114,24 +92,14 @@ type PostgresCache = CacheBackend & {
114
92
  };
115
93
  declare const createPostgresCache: (config: PostgresCacheConfig) => PostgresCache;
116
94
 
117
- type WarmupMode =
118
- /** Load all of L2 into L1 on init (default). Start fully hot. */
119
- 'full'
120
- /** Don't preload; L1 fills on demand via get→promote. Bounded memory. */
121
- | 'lazy'
122
- /** Preload only these fingerprints; lazy-fill the rest. */
123
- | {
95
+ type WarmupMode = 'full' | 'lazy' | {
124
96
  mode: 'partial';
125
97
  fingerprints: string[];
126
98
  };
127
99
  type TieredCacheConfig = {
128
- /** Fast, volatile tier (e.g. createMemoryCache()). */
129
100
  l1: CacheBackend;
130
- /** Durable source of truth (e.g. createPostgresCache(...)). */
131
101
  l2: CacheBackend;
132
- /** Warm-up strategy run by init(). Default: 'full'. */
133
102
  warmup?: WarmupMode;
134
- /** Called on background failures (async L2 writes) and dropped invalid entries. */
135
103
  onError?: (err: unknown) => void;
136
104
  };
137
105
  type TieredCache = CacheBackend & {
@@ -139,10 +107,6 @@ type TieredCache = CacheBackend & {
139
107
  };
140
108
  declare const createTieredCache: (config: TieredCacheConfig) => TieredCache;
141
109
 
142
- /**
143
- * Returns `null` if the entry is valid, or a human-readable reason
144
- * string if it is not.
145
- */
146
110
  declare const validateEntry: (entry: CacheEntry) => string | null;
147
111
 
148
112
  declare const normalizeShape: (shape: unknown) => unknown;
@@ -154,13 +118,6 @@ declare const computeRequestHash: (request: {
154
118
  }) => string;
155
119
  declare const computeSchemaFingerprint: (schema: DatabaseSchema) => string;
156
120
 
157
- /**
158
- * Lifetime = usage. Evicts unprotected entries that have not been
159
- * replayed within `maxIdleMs` (falling back to createdAt for entries
160
- * never touched). Protected entries never sweep. Run it on whatever
161
- * cadence suits the app (startup, a timer, a cron) — it is hygiene,
162
- * not a correctness requirement: entries are single-digit KB.
163
- */
164
121
  declare const sweepCache: (cache: {
165
122
  entries?: () => Promise<Array<{
166
123
  key: string;
@@ -179,16 +136,13 @@ type SeedEntry = {
179
136
  shape?: unknown;
180
137
  dsl: Query;
181
138
  mapping?: unknown;
182
- /** The reach this read requires whatever the caller holds — see `OkCacheEntry.reach`. */
183
139
  reach?: string;
184
- /** When this read's answer is refreshed — see `Refresh`. Absent means 'snapshot'. */
185
140
  refresh?: Refresh;
186
141
  };
187
142
  type SeedMutation = {
188
143
  fingerprint: string;
189
144
  intent?: string;
190
145
  mutation: MutationDefinition;
191
- /** The reach this write requires whatever the caller holds — see `MutationCacheEntry.reach`. */
192
146
  reach?: string;
193
147
  };
194
148
  declare const seedCache: (cache: CacheBackend, entries: readonly (SeedEntry | SeedMutation)[]) => Promise<void>;
package/dist/index.js CHANGED
@@ -1,7 +1,11 @@
1
- import { MutationDefinitionSchema, lintMutation, computeSchemaFingerprint, pruneOptional, buildValidationContext, requireScope, executeQuery, QueryRequestSchema, computeRequestHash, computePolicyKey, presenceOf, presenceSignature, findMissingContext, buildContextContract, optionalKeysOf, resolveParams, canonicalHash, fireAndForget, isSetMatch, refuseOptional, canonicalText, quoteIdent, compileCompute, compileAggregate, compileJoinPairs, compileFilter, checkScope, scopeResolved, mintFingerprint, isEntryFresh, canReadTable, hashText, isTouchDue } from './chunk-IQM4SQE2.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, mutationMisfits, normalizeShape, optionalKeysOf, presenceOf, pruneOptional, requiredContextKeys, resolveParams, scopeResolved, sweepCache, tablesChangedBy } from './chunk-IQM4SQE2.js';
3
- import { VexError, QuerySchema, isIdentifier, isFieldPathShape, isVexError } from './chunk-H4BHW76Q.js';
4
- export { AggregateExpressionSchema, ComputeExpressionSchema, FilterSchema, QuerySchema, VexError } from './chunk-H4BHW76Q.js';
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-7F2OH4IP.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-7F2OH4IP.js';
5
+ import { VexError, isVexError } from './chunk-XTOK7YOR.js';
6
+ export { VexError } from './chunk-XTOK7YOR.js';
7
+ import { QuerySchema, isIdentifier, isFieldPathShape } from './chunk-UPQMKAAX.js';
8
+ export { AggregateExpressionSchema, ComputeExpressionSchema, FilterSchema, QuerySchema } from './chunk-UPQMKAAX.js';
5
9
  import { z } from 'zod';
6
10
  import { exceedsDepth, depthRefusal } from '@niscorp/strata';
7
11
  import { compile, execute } from '@niscorp/prism';
@@ -1202,12 +1206,12 @@ var createQueryEngine = (engineConfig) => {
1202
1206
  const now = Date.now();
1203
1207
  if (isTouchDue(entry, now)) fireAndForget(cache.set(key, { ...entry, lastUsedAt: now }));
1204
1208
  };
1205
- const resolveFingerprint = async (validRequest, hasRequest, requestHash) => {
1209
+ const resolveFingerprint = async (validRequest, hasRequest, requestHash, scope) => {
1206
1210
  const fp = validRequest.fingerprint;
1207
1211
  if (fp === void 0) {
1208
1212
  return { fingerprint: mintFingerprint(), hit: false, replaced: false };
1209
1213
  }
1210
- const entry = await cache.get(fp);
1214
+ const entry = await cache.get(fp, scope);
1211
1215
  if (entry?.kind === "mutation") {
1212
1216
  throw new VexError(
1213
1217
  "invalid_request",
@@ -1311,6 +1315,7 @@ var createQueryEngine = (engineConfig) => {
1311
1315
  let result = rows;
1312
1316
  let mappingMs;
1313
1317
  let mappedIr = cachedIr;
1318
+ let mappedConfig;
1314
1319
  if (validRequest.shape !== void 0) {
1315
1320
  if (cachedIr !== void 0) {
1316
1321
  const mapStart = Date.now();
@@ -1322,10 +1327,11 @@ var createQueryEngine = (engineConfig) => {
1322
1327
  mappingMs = Date.now() - mapStart;
1323
1328
  result = mapped.transformed;
1324
1329
  mappedIr = mapped.ir;
1330
+ mappedConfig = mapped.config;
1325
1331
  }
1326
1332
  if (mappingMs !== void 0) emit({ type: "query.mapped", mappingMs });
1327
1333
  }
1328
- return { result, rowCount: rows.length, executionMs, mappingMs, mappedIr };
1334
+ return { result, rowCount: rows.length, executionMs, mappingMs, mappedIr, ...mappedConfig !== void 0 ? { mappedConfig } : {} };
1329
1335
  };
1330
1336
  const execute$1 = async (request, options) => {
1331
1337
  if (exceedsDepth(request)) throw new VexError("invalid_request", `Invalid request: ${depthRefusal()}`);
@@ -1351,7 +1357,7 @@ var createQueryEngine = (engineConfig) => {
1351
1357
  fingerprint: validRequest.fingerprint,
1352
1358
  entities: options?.entities
1353
1359
  });
1354
- const cached = await resolveFingerprint(validRequest, hasRequest, requestHash);
1360
+ const cached = await resolveFingerprint(validRequest, hasRequest, requestHash, scope);
1355
1361
  emit({ type: "query.cache", hit: cached.hit, fingerprint: cached.fingerprint, replaced: cached.replaced });
1356
1362
  let dsl = cached.dsl;
1357
1363
  let agentMs;
@@ -1438,7 +1444,7 @@ var createQueryEngine = (engineConfig) => {
1438
1444
  emit({ type: "query.done", totalMs: Date.now() - t0 });
1439
1445
  return { result: result2, meta: { ...metaOf(rows.length), timing: { executionMs: executionMs2 } } };
1440
1446
  }
1441
- const { result, rowCount, executionMs, mappingMs, mappedIr } = await executeAndMap(
1447
+ const { result, rowCount, executionMs, mappingMs, mappedIr, mappedConfig } = await executeAndMap(
1442
1448
  compiled,
1443
1449
  effectiveRequest,
1444
1450
  cached.cachedIr,
@@ -1453,6 +1459,7 @@ var createQueryEngine = (engineConfig) => {
1453
1459
  kind: "ok",
1454
1460
  dsl,
1455
1461
  ...mappedIr !== void 0 ? { prismIr: mappedIr } : {},
1462
+ ...mappedConfig !== void 0 ? { mapping: mappedConfig } : {},
1456
1463
  createdAt: now,
1457
1464
  lastUsedAt: now,
1458
1465
  ...requestHash !== void 0 ? { requestHash } : {},
@@ -1766,7 +1773,14 @@ var mapIndexType = (pgType) => {
1766
1773
  // src/adapters/postgres/compile.ts
1767
1774
  var compileQuery = (resolved) => {
1768
1775
  const paramSlots = [];
1769
- const paramCounter = { value: 0 };
1776
+ const sql = compileLevel(resolved, paramSlots, { value: 0 });
1777
+ const contextContract = {};
1778
+ for (const slot of paramSlots) {
1779
+ contextContract[slot.key] = { type: slot.type, kind: slot.kind };
1780
+ }
1781
+ return { sql, paramSlots, contextContract };
1782
+ };
1783
+ var compileLevel = (resolved, paramSlots, paramCounter) => {
1770
1784
  const ctx = {
1771
1785
  resolvedPaths: resolved.filter?.resolvedPaths ?? /* @__PURE__ */ new Map(),
1772
1786
  aliasMap: resolved.aliasMap,
@@ -1790,15 +1804,7 @@ var compileQuery = (resolved) => {
1790
1804
  const expr = compileAggregate(a.expression, ctx);
1791
1805
  return `${expr} AS ${quoteIdent(a.name)}`;
1792
1806
  });
1793
- const semanticColumns = [];
1794
- if (resolved.semantic !== void 0) {
1795
- const col = `${resolved.semantic.field.alias}.${resolved.semantic.field.column}`;
1796
- const semanticParamIndex = findSemanticParamIndex(paramSlots);
1797
- if (semanticParamIndex !== void 0) {
1798
- semanticColumns.push(`1 - (${col} <=> $${semanticParamIndex}) AS "$score"`);
1799
- }
1800
- }
1801
- const allColumns = [...fieldColumns, ...computeColumns, ...aggregateColumns, ...semanticColumns];
1807
+ const allColumns = [...fieldColumns, ...computeColumns, ...aggregateColumns];
1802
1808
  if (selectParts.length > 0) {
1803
1809
  sqlParts.push(`SELECT ${selectParts.join(" ")} ${allColumns.join(", ")}`);
1804
1810
  } else {
@@ -1807,9 +1813,7 @@ var compileQuery = (resolved) => {
1807
1813
  const firstSource = resolved.sources[0];
1808
1814
  if (firstSource !== void 0) {
1809
1815
  if (firstSource.subquery !== void 0) {
1810
- const subSql = compileQuery(firstSource.subquery);
1811
- mergeSubqueryParams(subSql, paramSlots, paramCounter);
1812
- sqlParts.push(`FROM (${subSql.sql}) AS ${firstSource.alias}`);
1816
+ sqlParts.push(`FROM (${compileLevel(firstSource.subquery, paramSlots, paramCounter)}) AS ${firstSource.alias}`);
1813
1817
  } else if (firstSource.table !== void 0) {
1814
1818
  sqlParts.push(`FROM ${firstSource.table} AS ${firstSource.alias}`);
1815
1819
  }
@@ -1824,9 +1828,7 @@ var compileQuery = (resolved) => {
1824
1828
  ];
1825
1829
  const on = conditions.join(" AND ");
1826
1830
  if (joinSource.subquery !== void 0) {
1827
- const subSql = compileQuery(joinSource.subquery);
1828
- mergeSubqueryParams(subSql, paramSlots, paramCounter);
1829
- sqlParts.push(`${keyword} (${subSql.sql}) AS ${join.toAlias} ON ${on}`);
1831
+ sqlParts.push(`${keyword} (${compileLevel(joinSource.subquery, paramSlots, paramCounter)}) AS ${join.toAlias} ON ${on}`);
1830
1832
  } else {
1831
1833
  sqlParts.push(`${keyword} ${join.toTable} AS ${join.toAlias} ON ${on}`);
1832
1834
  }
@@ -1836,9 +1838,7 @@ var compileQuery = (resolved) => {
1836
1838
  for (const source of resolved.sources) {
1837
1839
  if (source.alias === firstSource?.alias || joinedAliases.has(source.alias)) continue;
1838
1840
  if (source.subquery !== void 0) {
1839
- const subSql = compileQuery(source.subquery);
1840
- mergeSubqueryParams(subSql, paramSlots, paramCounter);
1841
- sqlParts.push(`CROSS JOIN (${subSql.sql}) AS ${source.alias}`);
1841
+ sqlParts.push(`CROSS JOIN (${compileLevel(source.subquery, paramSlots, paramCounter)}) AS ${source.alias}`);
1842
1842
  } else if (source.table !== void 0) {
1843
1843
  sqlParts.push(`CROSS JOIN ${source.table} AS ${source.alias}`);
1844
1844
  }
@@ -1860,11 +1860,9 @@ var compileQuery = (resolved) => {
1860
1860
  });
1861
1861
  sqlParts.push(`ORDER BY ${orderByParts.join(", ")}`);
1862
1862
  } else if (resolved.semantic !== void 0) {
1863
- const semanticIdx = findSemanticParamIndex(paramSlots);
1864
- if (semanticIdx !== void 0) {
1865
- const col = `${resolved.semantic.field.alias}.${resolved.semantic.field.column}`;
1866
- sqlParts.push(`ORDER BY ${col} <=> $${semanticIdx} ASC`);
1867
- }
1863
+ const { field, contextPath } = resolved.semantic;
1864
+ const position = paramSlots.findIndex((slot) => slot.kind === "semantic" && slot.key === contextPath) + 1;
1865
+ if (position > 0) sqlParts.push(`ORDER BY ${field.alias}.${field.column} <=> $${position} ASC`);
1868
1866
  }
1869
1867
  if (resolved.limit !== void 0) {
1870
1868
  if (!Number.isInteger(resolved.limit) || resolved.limit < 1) {
@@ -1872,30 +1870,7 @@ var compileQuery = (resolved) => {
1872
1870
  }
1873
1871
  sqlParts.push(`LIMIT ${resolved.limit}`);
1874
1872
  }
1875
- const contextContract = {};
1876
- for (const slot of paramSlots) {
1877
- contextContract[slot.key] = { type: slot.type, kind: slot.kind };
1878
- }
1879
- return {
1880
- sql: sqlParts.join(" "),
1881
- paramSlots,
1882
- contextContract
1883
- };
1884
- };
1885
- var findSemanticParamIndex = (slots) => {
1886
- for (let i = 0; i < slots.length; i++) {
1887
- const slot = slots[i];
1888
- if (slot !== void 0 && slot.kind === "semantic") {
1889
- return i + 1;
1890
- }
1891
- }
1892
- return void 0;
1893
- };
1894
- var mergeSubqueryParams = (subCompiled, parentSlots, parentCounter) => {
1895
- for (const slot of subCompiled.paramSlots) {
1896
- parentCounter.value += 1;
1897
- parentSlots.push(slot);
1898
- }
1873
+ return sqlParts.join(" ");
1899
1874
  };
1900
1875
 
1901
1876
  // src/adapters/postgres/statement-timeout.ts
@@ -1945,7 +1920,7 @@ var createPostgresAdapter = (config) => {
1945
1920
  const capabilities = {
1946
1921
  vectorSearch: true,
1947
1922
  fuzzyMatch: false,
1948
- // Requires pg_trgm extension, not guaranteed
1923
+ // needs the pg_trgm extension, which may not be installed
1949
1924
  jsonFields: true,
1950
1925
  fullTextSearch: true,
1951
1926
  returningClause: true,
@@ -2005,10 +1980,6 @@ var vexGuide = () => [
2005
1980
  "",
2006
1981
  "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."
2007
1982
  ].join("\n");
2008
-
2009
- // src/cache/cache.types.ts
2010
- var REFRESH_MODES = ["snapshot", "reactive"];
2011
- var isRefresh = (value) => REFRESH_MODES.some((mode) => mode === value);
2012
1983
  var isCompiledIr = (value) => {
2013
1984
  if (value === null || typeof value !== "object") return false;
2014
1985
  const ir = value;
@@ -2053,7 +2024,7 @@ var quoteIdent2 = (name, label) => {
2053
2024
  }
2054
2025
  return `"${name}"`;
2055
2026
  };
2056
- 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";
2027
+ var SELECT_COLS = "key, kind, intent, shape, dsl, prism_ir, mapping, reach, reason, created_at, expires_at, schema_fingerprint, protected, last_used_at, request_hash, refresh";
2057
2028
  var rowToEntry = (row) => {
2058
2029
  const createdAt = row["created_at"].getTime();
2059
2030
  const expiresAtRaw = row["expires_at"];
@@ -2084,13 +2055,8 @@ var rowToEntry = (row) => {
2084
2055
  kind: "ok",
2085
2056
  dsl: row["dsl"],
2086
2057
  ...row["prism_ir"] != null ? { prismIr: row["prism_ir"] } : {},
2087
- // A DECLARED REACH IS PART OF THE ENTRY, so it has to survive the round
2088
- // trip. Dropping it here would not fail loudly — the read would simply be
2089
- // served at the caller's own, wider reach, which is the exact thing the
2090
- // field exists to prevent.
2058
+ ...row["mapping"] != null ? { mapping: row["mapping"] } : {},
2091
2059
  ...row["reach"] != null ? { reach: row["reach"] } : {},
2092
- // So must the refresh mode: dropped, a reactive read would quietly answer
2093
- // once and never again.
2094
2060
  ...isRefresh(row["refresh"]) ? { refresh: row["refresh"] } : {},
2095
2061
  ...meta
2096
2062
  };
@@ -2135,6 +2101,10 @@ var createPostgresCache = (config) => {
2135
2101
  { kind: "sql", sql: `ALTER TABLE ${qualified} ADD COLUMN IF NOT EXISTS reach text` },
2136
2102
  { kind: "sql", sql: `ALTER TABLE ${qualified} ADD COLUMN IF NOT EXISTS refresh text` }
2137
2103
  ]
2104
+ },
2105
+ {
2106
+ description: "The prism config a mapping was compiled from",
2107
+ steps: [{ kind: "sql", sql: `ALTER TABLE ${qualified} ADD COLUMN IF NOT EXISTS mapping jsonb` }]
2138
2108
  }
2139
2109
  ]
2140
2110
  };
@@ -2178,6 +2148,7 @@ var createPostgresCache = (config) => {
2178
2148
  const isOk = entry.kind === "ok";
2179
2149
  const dsl = isOk ? JSON.stringify(entry.dsl) : entry.kind === "mutation" ? JSON.stringify(entry.mutation) : null;
2180
2150
  const prismIr = isOk && entry.prismIr !== void 0 ? JSON.stringify(entry.prismIr) : null;
2151
+ const mapping = isOk && entry.mapping !== void 0 ? JSON.stringify(entry.mapping) : null;
2181
2152
  const reason = entry.kind === "unsatisfiable" ? entry.reason : null;
2182
2153
  const intent = entry.intent ?? null;
2183
2154
  const shape = entry.shape !== void 0 ? JSON.stringify(entry.shape) : null;
@@ -2190,8 +2161,8 @@ var createPostgresCache = (config) => {
2190
2161
  const reach = entry.kind === "unsatisfiable" ? null : entry.reach ?? null;
2191
2162
  const refresh = entry.kind === "ok" ? entry.refresh ?? null : null;
2192
2163
  await pool.query(
2193
- `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)
2194
- VALUES ($1, $2, $3, $4::jsonb, $5::jsonb, $6::jsonb, $7, $8, $9, $10, $11, $12, $13, $14, $15)
2164
+ `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, mapping)
2165
+ VALUES ($1, $2, $3, $4::jsonb, $5::jsonb, $6::jsonb, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16::jsonb)
2195
2166
  ON CONFLICT (key) DO UPDATE SET
2196
2167
  kind = EXCLUDED.kind,
2197
2168
  intent = EXCLUDED.intent,
@@ -2206,8 +2177,9 @@ var createPostgresCache = (config) => {
2206
2177
  protected = EXCLUDED.protected,
2207
2178
  last_used_at = EXCLUDED.last_used_at,
2208
2179
  request_hash = EXCLUDED.request_hash,
2209
- refresh = EXCLUDED.refresh`,
2210
- [key, entry.kind, intent, shape, dsl, prismIr, reach, reason, createdAt, expiresAt, fingerprint, isProtected, lastUsedAt, requestHash, refresh]
2180
+ refresh = EXCLUDED.refresh,
2181
+ mapping = EXCLUDED.mapping`,
2182
+ [key, entry.kind, intent, shape, dsl, prismIr, reach, reason, createdAt, expiresAt, fingerprint, isProtected, lastUsedAt, requestHash, refresh, mapping]
2211
2183
  );
2212
2184
  };
2213
2185
  const del = async (key) => {
@@ -2343,6 +2315,6 @@ var seedCache = async (cache, entries) => {
2343
2315
  }
2344
2316
  };
2345
2317
 
2346
- export { REFRESH_MODES, SCOPE_VERBS, analyze, createMemoryCache, createPostgresAdapter, createPostgresCache, createQueryEngine, createScopePolicy, createTieredCache, discoverEntities, isRefresh, mergeScopePolicies, resolve, scopeBindings, scopeGrants, scopeProfiles, seedCache, validateEntry, vexGuide };
2318
+ export { SCOPE_VERBS, analyze, createMemoryCache, createPostgresAdapter, createPostgresCache, createQueryEngine, createScopePolicy, createTieredCache, discoverEntities, mergeScopePolicies, resolve, scopeBindings, scopeGrants, scopeProfiles, seedCache, validateEntry, vexGuide };
2347
2319
  //# sourceMappingURL=index.js.map
2348
2320
  //# sourceMappingURL=index.js.map