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