@niscorp/vex 0.2.0 → 0.2.3
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/CHANGELOG.md +161 -0
- package/DESIGN.md +78 -3
- package/DOCS.md +167 -14
- package/README.md +2 -1
- package/dist/adapters/express/index.cjs +241 -19
- package/dist/adapters/express/index.cjs.map +1 -1
- package/dist/adapters/express/index.d.cts +2 -2
- package/dist/adapters/express/index.d.ts +2 -2
- package/dist/adapters/express/index.js +2 -2
- package/dist/adapters/hono/index.cjs +260 -24
- package/dist/adapters/hono/index.cjs.map +1 -1
- package/dist/adapters/hono/index.d.cts +2 -2
- package/dist/adapters/hono/index.d.ts +2 -2
- package/dist/adapters/hono/index.js +21 -7
- package/dist/adapters/hono/index.js.map +1 -1
- package/dist/agent/index.cjs +2 -0
- package/dist/agent/index.cjs.map +1 -1
- package/dist/agent/index.d.cts +1 -1
- package/dist/agent/index.d.ts +1 -1
- package/dist/agent/index.js +1 -1
- package/dist/{chunk-HF25Q53I.js → chunk-H4BHW76Q.js} +6 -3
- package/dist/chunk-H4BHW76Q.js.map +1 -0
- package/dist/{chunk-5CBKESBJ.js → chunk-IQM4SQE2.js} +279 -29
- package/dist/chunk-IQM4SQE2.js.map +1 -0
- package/dist/{handler-Cql8SJ3F.d.cts → handler-BGCL6_Si.d.ts} +3 -2
- package/dist/{handler-mICf9ins.d.ts → handler-CMrjTXNx.d.cts} +3 -2
- package/dist/index.cjs +320 -57
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +45 -37
- package/dist/index.js.map +1 -1
- package/dist/{types-BRvMB6IM.d.cts → types-Bi-Lg86b.d.cts} +48 -2
- package/dist/{types-BRvMB6IM.d.ts → types-Bi-Lg86b.d.ts} +48 -2
- package/package.json +9 -8
- package/dist/chunk-5CBKESBJ.js.map +0 -1
- package/dist/chunk-HF25Q53I.js.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { a as QueryEngine,
|
|
2
|
-
import { V as VexHandlerConfig } from '../../handler-
|
|
1
|
+
import { a as QueryEngine, al as ScopeValues } from '../../types-Bi-Lg86b.cjs';
|
|
2
|
+
import { V as VexHandlerConfig } from '../../handler-CMrjTXNx.cjs';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import '@niscorp/prism';
|
|
5
5
|
import '@niscorp/strata';
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { a as QueryEngine,
|
|
2
|
-
import { V as VexHandlerConfig } from '../../handler-
|
|
1
|
+
import { a as QueryEngine, al as ScopeValues } from '../../types-Bi-Lg86b.js';
|
|
2
|
+
import { V as VexHandlerConfig } from '../../handler-BGCL6_Si.js';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import '@niscorp/prism';
|
|
5
5
|
import '@niscorp/strata';
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { handleDiscovery, handleQuery, handleFingerprintPatch, handleFingerprintDelete } from '../../chunk-
|
|
2
|
-
import '../../chunk-
|
|
1
|
+
import { handleDiscovery, handleQuery, handleFingerprintPatch, handleFingerprintDelete } from '../../chunk-IQM4SQE2.js';
|
|
2
|
+
import '../../chunk-H4BHW76Q.js';
|
|
3
3
|
|
|
4
4
|
// src/adapters/express/index.ts
|
|
5
5
|
var fingerprintFromBody = (body) => {
|
|
@@ -2,7 +2,6 @@
|
|
|
2
2
|
|
|
3
3
|
var hono = require('hono');
|
|
4
4
|
var zod = require('zod');
|
|
5
|
-
var crypto = require('crypto');
|
|
6
5
|
var strata = require('@niscorp/strata');
|
|
7
6
|
|
|
8
7
|
// src/adapters/hono/index.ts
|
|
@@ -185,6 +184,144 @@ var isEntryFresh = (entry, currentFingerprint) => {
|
|
|
185
184
|
const stale = entry.schemaFingerprint !== void 0 && currentFingerprint !== void 0 && entry.schemaFingerprint !== currentFingerprint;
|
|
186
185
|
return !expired && !stale;
|
|
187
186
|
};
|
|
187
|
+
|
|
188
|
+
// src/utils/sha256.ts
|
|
189
|
+
var ROUND_CONSTANTS = new Uint32Array([
|
|
190
|
+
1116352408,
|
|
191
|
+
1899447441,
|
|
192
|
+
3049323471,
|
|
193
|
+
3921009573,
|
|
194
|
+
961987163,
|
|
195
|
+
1508970993,
|
|
196
|
+
2453635748,
|
|
197
|
+
2870763221,
|
|
198
|
+
3624381080,
|
|
199
|
+
310598401,
|
|
200
|
+
607225278,
|
|
201
|
+
1426881987,
|
|
202
|
+
1925078388,
|
|
203
|
+
2162078206,
|
|
204
|
+
2614888103,
|
|
205
|
+
3248222580,
|
|
206
|
+
3835390401,
|
|
207
|
+
4022224774,
|
|
208
|
+
264347078,
|
|
209
|
+
604807628,
|
|
210
|
+
770255983,
|
|
211
|
+
1249150122,
|
|
212
|
+
1555081692,
|
|
213
|
+
1996064986,
|
|
214
|
+
2554220882,
|
|
215
|
+
2821834349,
|
|
216
|
+
2952996808,
|
|
217
|
+
3210313671,
|
|
218
|
+
3336571891,
|
|
219
|
+
3584528711,
|
|
220
|
+
113926993,
|
|
221
|
+
338241895,
|
|
222
|
+
666307205,
|
|
223
|
+
773529912,
|
|
224
|
+
1294757372,
|
|
225
|
+
1396182291,
|
|
226
|
+
1695183700,
|
|
227
|
+
1986661051,
|
|
228
|
+
2177026350,
|
|
229
|
+
2456956037,
|
|
230
|
+
2730485921,
|
|
231
|
+
2820302411,
|
|
232
|
+
3259730800,
|
|
233
|
+
3345764771,
|
|
234
|
+
3516065817,
|
|
235
|
+
3600352804,
|
|
236
|
+
4094571909,
|
|
237
|
+
275423344,
|
|
238
|
+
430227734,
|
|
239
|
+
506948616,
|
|
240
|
+
659060556,
|
|
241
|
+
883997877,
|
|
242
|
+
958139571,
|
|
243
|
+
1322822218,
|
|
244
|
+
1537002063,
|
|
245
|
+
1747873779,
|
|
246
|
+
1955562222,
|
|
247
|
+
2024104815,
|
|
248
|
+
2227730452,
|
|
249
|
+
2361852424,
|
|
250
|
+
2428436474,
|
|
251
|
+
2756734187,
|
|
252
|
+
3204031479,
|
|
253
|
+
3329325298
|
|
254
|
+
]);
|
|
255
|
+
var BLOCK_BYTES = 64;
|
|
256
|
+
var rotateRight = (word, bits) => word >>> bits | word << 32 - bits;
|
|
257
|
+
var wordHex = (word) => (word >>> 0).toString(16).padStart(8, "0");
|
|
258
|
+
var sha256Hex = (text) => {
|
|
259
|
+
const bytes = new TextEncoder().encode(text);
|
|
260
|
+
const padded = new Uint8Array(Math.ceil((bytes.length + 9) / BLOCK_BYTES) * BLOCK_BYTES);
|
|
261
|
+
padded.set(bytes);
|
|
262
|
+
padded[bytes.length] = 128;
|
|
263
|
+
const view = new DataView(padded.buffer);
|
|
264
|
+
const bitLength = bytes.length * 8;
|
|
265
|
+
view.setUint32(padded.length - 8, Math.floor(bitLength / 4294967296));
|
|
266
|
+
view.setUint32(padded.length - 4, bitLength >>> 0);
|
|
267
|
+
let h0 = 1779033703;
|
|
268
|
+
let h1 = 3144134277;
|
|
269
|
+
let h2 = 1013904242;
|
|
270
|
+
let h3 = 2773480762;
|
|
271
|
+
let h4 = 1359893119;
|
|
272
|
+
let h5 = 2600822924;
|
|
273
|
+
let h6 = 528734635;
|
|
274
|
+
let h7 = 1541459225;
|
|
275
|
+
const schedule = new Uint32Array(64);
|
|
276
|
+
for (let offset = 0; offset < padded.length; offset += BLOCK_BYTES) {
|
|
277
|
+
for (let i = 0; i < 16; i += 1) schedule[i] = view.getUint32(offset + i * 4);
|
|
278
|
+
for (let i = 16; i < 64; i += 1) {
|
|
279
|
+
const w15 = schedule[i - 15] ?? 0;
|
|
280
|
+
const w2 = schedule[i - 2] ?? 0;
|
|
281
|
+
const s0 = rotateRight(w15, 7) ^ rotateRight(w15, 18) ^ w15 >>> 3;
|
|
282
|
+
const s1 = rotateRight(w2, 17) ^ rotateRight(w2, 19) ^ w2 >>> 10;
|
|
283
|
+
schedule[i] = (schedule[i - 16] ?? 0) + s0 + (schedule[i - 7] ?? 0) + s1;
|
|
284
|
+
}
|
|
285
|
+
let a = h0;
|
|
286
|
+
let b = h1;
|
|
287
|
+
let c = h2;
|
|
288
|
+
let d = h3;
|
|
289
|
+
let e = h4;
|
|
290
|
+
let f = h5;
|
|
291
|
+
let g = h6;
|
|
292
|
+
let h = h7;
|
|
293
|
+
for (let i = 0; i < 64; i += 1) {
|
|
294
|
+
const sum1 = rotateRight(e, 6) ^ rotateRight(e, 11) ^ rotateRight(e, 25);
|
|
295
|
+
const choice = e & f ^ ~e & g;
|
|
296
|
+
const temp1 = h + sum1 + choice + (ROUND_CONSTANTS[i] ?? 0) + (schedule[i] ?? 0) | 0;
|
|
297
|
+
const sum0 = rotateRight(a, 2) ^ rotateRight(a, 13) ^ rotateRight(a, 22);
|
|
298
|
+
const majority = a & b ^ a & c ^ b & c;
|
|
299
|
+
const temp2 = sum0 + majority | 0;
|
|
300
|
+
h = g;
|
|
301
|
+
g = f;
|
|
302
|
+
f = e;
|
|
303
|
+
e = d + temp1 | 0;
|
|
304
|
+
d = c;
|
|
305
|
+
c = b;
|
|
306
|
+
b = a;
|
|
307
|
+
a = temp1 + temp2 | 0;
|
|
308
|
+
}
|
|
309
|
+
h0 = h0 + a | 0;
|
|
310
|
+
h1 = h1 + b | 0;
|
|
311
|
+
h2 = h2 + c | 0;
|
|
312
|
+
h3 = h3 + d | 0;
|
|
313
|
+
h4 = h4 + e | 0;
|
|
314
|
+
h5 = h5 + f | 0;
|
|
315
|
+
h6 = h6 + g | 0;
|
|
316
|
+
h7 = h7 + h | 0;
|
|
317
|
+
}
|
|
318
|
+
return wordHex(h0) + wordHex(h1) + wordHex(h2) + wordHex(h3) + wordHex(h4) + wordHex(h5) + wordHex(h6) + wordHex(h7);
|
|
319
|
+
};
|
|
320
|
+
|
|
321
|
+
// src/utils/canonical.ts
|
|
322
|
+
var hashText = (text) => sha256Hex(text);
|
|
323
|
+
|
|
324
|
+
// src/cache/hash.ts
|
|
188
325
|
var computeSchemaFingerprint = (schema) => {
|
|
189
326
|
const byName = (a, b) => a.name.localeCompare(b.name);
|
|
190
327
|
const stable = {
|
|
@@ -214,10 +351,11 @@ var computeSchemaFingerprint = (schema) => {
|
|
|
214
351
|
}))
|
|
215
352
|
}))
|
|
216
353
|
};
|
|
217
|
-
return
|
|
354
|
+
return hashText(JSON.stringify(stable));
|
|
218
355
|
};
|
|
219
356
|
|
|
220
357
|
// src/errors.ts
|
|
358
|
+
var VEX_ERROR = /* @__PURE__ */ Symbol.for("@niscorp/vex:VexError");
|
|
221
359
|
var VexError = class extends Error {
|
|
222
360
|
code;
|
|
223
361
|
details;
|
|
@@ -228,6 +366,8 @@ var VexError = class extends Error {
|
|
|
228
366
|
this.details = details;
|
|
229
367
|
}
|
|
230
368
|
};
|
|
369
|
+
Object.defineProperty(VexError.prototype, VEX_ERROR, { value: true });
|
|
370
|
+
var isVexError = (err) => err instanceof VexError || err instanceof Error && Reflect.get(err, VEX_ERROR) === true;
|
|
231
371
|
|
|
232
372
|
// src/engine/optional.ts
|
|
233
373
|
var refuseOptional = (where) => {
|
|
@@ -506,13 +646,21 @@ var LookupSchema = zod.z.object({
|
|
|
506
646
|
where: FilterSchema.describe("Bounds the lookup \u2014 should match at most one row")
|
|
507
647
|
}).strict()
|
|
508
648
|
}).strict().describe("Scalar subquery: reads one value from another table at write time; read scope rules apply");
|
|
649
|
+
var ReturnedSchema = zod.z.object({
|
|
650
|
+
$returned: FieldPathSchema.describe(
|
|
651
|
+
"`table.column`: `table` is written by exactly one earlier statement of this batch; `column` is a column of that table, including one the database generated."
|
|
652
|
+
)
|
|
653
|
+
}).strict().describe(
|
|
654
|
+
"A column of the one row an earlier statement of this batch (an insert, update, upsert or delete) returned \u2014 how a later row gets an id the database generated. That statement must return exactly one row; none (its `where` matched no row, or scope kept the row back) or several fails the whole batch and nothing is written. Allowed only as the value of a column a statement sets; never inside a `where`, a `$lookup` or `items`, and never naming an `insertEach` or an `insert` whose `onConflict` has no `set`."
|
|
655
|
+
);
|
|
509
656
|
var ValueSchema = zod.z.union([
|
|
510
657
|
zod.z.string(),
|
|
511
658
|
zod.z.number(),
|
|
512
659
|
zod.z.boolean(),
|
|
513
660
|
zod.z.null(),
|
|
514
661
|
zod.z.object({ $context: zod.z.string() }).strict(),
|
|
515
|
-
LookupSchema
|
|
662
|
+
LookupSchema,
|
|
663
|
+
ReturnedSchema
|
|
516
664
|
]);
|
|
517
665
|
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
666
|
var OnConflictSchema = zod.z.object({
|
|
@@ -610,17 +758,23 @@ var walkFilter = (filter, schema, sig) => {
|
|
|
610
758
|
};
|
|
611
759
|
var isLookupRef = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && "$lookup" in v;
|
|
612
760
|
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 ?? {} } : {};
|
|
761
|
+
var positionsSetBy = (m) => {
|
|
762
|
+
const positions = (cols, insertOnly = false) => Object.entries(cols ?? {}).map(([column, value]) => ({ column, value, insertOnly }));
|
|
763
|
+
if (m.op === "insert" || m.op === "insertEach") return [...positions(m.values), ...positions(m.onConflict?.set)];
|
|
764
|
+
if (m.op === "update") return positions(m.set);
|
|
765
|
+
if (m.op === "upsert") return [...positions(m.columns), ...positions(m.insert, true)];
|
|
766
|
+
return [];
|
|
767
|
+
};
|
|
613
768
|
var collectMutationContext = (def, schema) => {
|
|
614
769
|
const sig = {};
|
|
615
770
|
const list = Array.isArray(def) ? def : [def];
|
|
616
771
|
for (const m of list) {
|
|
617
|
-
for (const
|
|
772
|
+
for (const { column: col, value: v, insertOnly } of positionsSetBy(m)) {
|
|
618
773
|
if (isLookupRef(v)) {
|
|
619
774
|
walkFilter(v.$lookup.where, schema, sig);
|
|
620
775
|
continue;
|
|
621
776
|
}
|
|
622
777
|
if (!isContextRef(v)) continue;
|
|
623
|
-
const insertOnly = m.op === "upsert" && m.insert !== void 0 && col in m.insert;
|
|
624
778
|
addField(sig, v.$context, { ...columnInfo(`${m.table}.${col}`, schema), ...insertOnly ? { note: "insert only" } : {} });
|
|
625
779
|
}
|
|
626
780
|
if (m.op === "update" || m.op === "delete") walkFilter(m.where, schema, sig);
|
|
@@ -658,8 +812,7 @@ var mutationEffect = (def) => {
|
|
|
658
812
|
};
|
|
659
813
|
var requiredContextKeys = (m) => {
|
|
660
814
|
const keys = /* @__PURE__ */ new Set();
|
|
661
|
-
const
|
|
662
|
-
for (const v of Object.values(cols)) {
|
|
815
|
+
for (const { value: v } of positionsSetBy(m)) {
|
|
663
816
|
if (isContextRef(v)) keys.add(v.$context);
|
|
664
817
|
else if (isLookupRef(v)) {
|
|
665
818
|
const sub = {};
|
|
@@ -675,10 +828,41 @@ var requiredContextKeys = (m) => {
|
|
|
675
828
|
}
|
|
676
829
|
return [...keys].sort();
|
|
677
830
|
};
|
|
831
|
+
var isReturnedRef = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && "$returned" in v && typeof v.$returned === "string";
|
|
832
|
+
var returnedIn = (list, at) => {
|
|
833
|
+
const refs = /* @__PURE__ */ new Map();
|
|
834
|
+
const issues = [];
|
|
835
|
+
const m = list[at];
|
|
836
|
+
if (m === void 0) return { refs, issues };
|
|
837
|
+
const judged = /* @__PURE__ */ new Set();
|
|
838
|
+
for (const { value: v } of positionsSetBy(m)) {
|
|
839
|
+
if (!isReturnedRef(v) || judged.has(v.$returned)) continue;
|
|
840
|
+
judged.add(v.$returned);
|
|
841
|
+
const dot = v.$returned.indexOf(".");
|
|
842
|
+
const table = v.$returned.slice(0, dot);
|
|
843
|
+
const column = v.$returned.slice(dot + 1);
|
|
844
|
+
const reads = `${m.op} on "${m.table}" reads "${v.$returned}"`;
|
|
845
|
+
const earlier = list.flatMap((s, i) => i < at && s.table === table ? [{ s, i }] : []);
|
|
846
|
+
const source = earlier[0];
|
|
847
|
+
if (source === void 0) {
|
|
848
|
+
issues.push(`${reads}, and no earlier statement writes "${table}" \u2014 put the statement that writes it before this one, in the same batch`);
|
|
849
|
+
} else if (earlier.length > 1) {
|
|
850
|
+
issues.push(`${reads}, and ${earlier.length} earlier statements write "${table}" \u2014 a reference cannot tell them apart`);
|
|
851
|
+
} else if (source.s.op === "insertEach") {
|
|
852
|
+
issues.push(`${reads} from an insertEach, which writes a row per element \u2014 there is no one row to read`);
|
|
853
|
+
} else if (source.s.op === "insert" && source.s.onConflict !== void 0 && source.s.onConflict.set === void 0) {
|
|
854
|
+
issues.push(`${reads} from an insert that does nothing on conflict, which then returns no row \u2014 give its onConflict a \`set\``);
|
|
855
|
+
} else {
|
|
856
|
+
refs.set(v.$returned, { statement: source.i, table, column });
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
return { refs, issues };
|
|
860
|
+
};
|
|
678
861
|
|
|
679
862
|
// src/mutations/engine.ts
|
|
680
863
|
var isLookup = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && "$lookup" in v;
|
|
681
864
|
var isItemRef = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && "$item" in v;
|
|
865
|
+
var isReturned = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && "$returned" in v;
|
|
682
866
|
var collectLookups = (m) => {
|
|
683
867
|
const out = [];
|
|
684
868
|
const scan = (cols) => {
|
|
@@ -776,6 +960,13 @@ var assertWritableColumns = (m, schema) => {
|
|
|
776
960
|
if (m.onConflict.where !== void 0) assertFilterColumns(m.onConflict.where, m.table, schema, "onConflict");
|
|
777
961
|
}
|
|
778
962
|
};
|
|
963
|
+
var assertReturnedColumns = (refs, schema) => {
|
|
964
|
+
for (const [ref, source] of refs) {
|
|
965
|
+
if (findEntity(source.table, schema)?.fields.some((f) => f.name === source.column) !== true) {
|
|
966
|
+
throw new VexError("invalid_dsl", `Unknown column "${ref}" in $returned.`);
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
};
|
|
779
970
|
var readMatchesFor = (table, policy) => {
|
|
780
971
|
const rule = policy.entities[table];
|
|
781
972
|
if (rule === void 0) {
|
|
@@ -884,7 +1075,8 @@ var newCtx = () => ({
|
|
|
884
1075
|
resolvedPaths: /* @__PURE__ */ new Map(),
|
|
885
1076
|
aliasMap: /* @__PURE__ */ new Map(),
|
|
886
1077
|
paramSlots: [],
|
|
887
|
-
paramCounter: { value: 0 }
|
|
1078
|
+
paramCounter: { value: 0 },
|
|
1079
|
+
returned: /* @__PURE__ */ new Map()
|
|
888
1080
|
});
|
|
889
1081
|
var indexFilterFields = (filter, aliasMap) => {
|
|
890
1082
|
for (const path of filterColumns(filter)) aliasMap.set(path, path);
|
|
@@ -895,13 +1087,19 @@ var compileValue = (v, ctx) => {
|
|
|
895
1087
|
const where = compileFilter(v.$lookup.where, ctx);
|
|
896
1088
|
return `(SELECT ${v.$lookup.field} FROM ${v.$lookup.from} WHERE ${where})`;
|
|
897
1089
|
}
|
|
1090
|
+
if (isReturned(v)) {
|
|
1091
|
+
ctx.paramCounter.value += 1;
|
|
1092
|
+
ctx.returned.set(ctx.paramSlots.length, v.$returned);
|
|
1093
|
+
ctx.paramSlots.push({ key: v.$returned, kind: "context", type: "string" });
|
|
1094
|
+
return `$${ctx.paramCounter.value}`;
|
|
1095
|
+
}
|
|
898
1096
|
return compileFieldOrValue(v, ctx);
|
|
899
1097
|
};
|
|
900
1098
|
var compileColumnValue = (table, column, v, ctx, schema) => {
|
|
901
1099
|
const before = ctx.paramSlots.length;
|
|
902
1100
|
const sql = compileValue(v, ctx);
|
|
903
1101
|
const json = findEntity(table, schema)?.fields.find((f) => f.name === column)?.normalizedType === "json";
|
|
904
|
-
if (json && typeof v === "object" && v !== null && "$context" in v) {
|
|
1102
|
+
if (json && typeof v === "object" && v !== null && ("$context" in v || "$returned" in v)) {
|
|
905
1103
|
const slot = ctx.paramSlots[before];
|
|
906
1104
|
if (slot !== void 0) ctx.paramSlots[before] = { ...slot, encode: "json" };
|
|
907
1105
|
}
|
|
@@ -932,7 +1130,7 @@ var compileMutation = (m, schema) => {
|
|
|
932
1130
|
const entries = Object.entries(m.values);
|
|
933
1131
|
const cols = entries.map(([c]) => c);
|
|
934
1132
|
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 };
|
|
1133
|
+
return { sql: `INSERT INTO ${m.table} (${cols.join(", ")}) VALUES (${vals.join(", ")})${compileConflict(m, ctx, schema)} RETURNING *`, slots: ctx.paramSlots, returned: ctx.returned };
|
|
936
1134
|
}
|
|
937
1135
|
if (m.op === "insertEach") {
|
|
938
1136
|
const entity = findEntity(m.table, schema);
|
|
@@ -946,25 +1144,26 @@ var compileMutation = (m, schema) => {
|
|
|
946
1144
|
const raw = `(item.value->>${quoteLiteral(v.$item)})`;
|
|
947
1145
|
return cast === void 0 ? raw : `${raw}::${cast}`;
|
|
948
1146
|
}
|
|
949
|
-
return compileValue(v, ctx);
|
|
1147
|
+
return isReturned(v) ? compileColumnValue(m.table, col, v, ctx, schema) : compileValue(v, ctx);
|
|
950
1148
|
});
|
|
951
1149
|
ctx.paramCounter.value += 1;
|
|
952
1150
|
ctx.paramSlots.push({ key: m.items.$context, kind: "context", type: "json" });
|
|
953
1151
|
const source = `jsonb_array_elements($${ctx.paramCounter.value}::jsonb) AS item`;
|
|
954
1152
|
return {
|
|
955
1153
|
sql: `INSERT INTO ${m.table} (${cols.join(", ")}) SELECT ${exprs.join(", ")} FROM ${source}${compileConflict(m, ctx, schema)} RETURNING *`,
|
|
956
|
-
slots: ctx.paramSlots
|
|
1154
|
+
slots: ctx.paramSlots,
|
|
1155
|
+
returned: ctx.returned
|
|
957
1156
|
};
|
|
958
1157
|
}
|
|
959
1158
|
if (m.op === "update") {
|
|
960
1159
|
const sets = Object.entries(m.set).map(([c, v]) => `${c} = ${compileColumnValue(m.table, c, v, ctx, schema)}`);
|
|
961
1160
|
indexFilterFields(m.where, ctx.aliasMap);
|
|
962
1161
|
const where2 = compileFilter(m.where, ctx);
|
|
963
|
-
return { sql: `UPDATE ${m.table} SET ${sets.join(", ")} WHERE ${where2} RETURNING *`, slots: ctx.paramSlots };
|
|
1162
|
+
return { sql: `UPDATE ${m.table} SET ${sets.join(", ")} WHERE ${where2} RETURNING *`, slots: ctx.paramSlots, returned: ctx.returned };
|
|
964
1163
|
}
|
|
965
1164
|
indexFilterFields(m.where, ctx.aliasMap);
|
|
966
1165
|
const where = compileFilter(m.where, ctx);
|
|
967
|
-
return { sql: `DELETE FROM ${m.table} WHERE ${where} RETURNING *`, slots: ctx.paramSlots };
|
|
1166
|
+
return { sql: `DELETE FROM ${m.table} WHERE ${where} RETURNING *`, slots: ctx.paramSlots, returned: ctx.returned };
|
|
968
1167
|
};
|
|
969
1168
|
var SUGAR = {
|
|
970
1169
|
upsert: (m, context) => {
|
|
@@ -979,24 +1178,47 @@ var desugarMutation = (m, context) => {
|
|
|
979
1178
|
var executeWrites = async (client, def, mctx) => {
|
|
980
1179
|
const parsed = MutationDefinitionSchema.parse(def);
|
|
981
1180
|
const entries = Array.isArray(parsed) ? parsed : [parsed];
|
|
982
|
-
const
|
|
983
|
-
|
|
1181
|
+
const cores = entries.map((entry) => desugarMutation(entry, mctx.context));
|
|
1182
|
+
const compiled = cores.map((core, at) => {
|
|
984
1183
|
const missing = requiredContextKeys(core).filter((k) => mctx.context[k] === void 0);
|
|
985
1184
|
if (missing.length > 0) {
|
|
986
1185
|
throw new VexError("missing_context", `Mutation is missing context: ${missing.join(", ")}.`, {
|
|
987
1186
|
expected: collectMutationContext(parsed, mctx.schema)
|
|
988
1187
|
});
|
|
989
1188
|
}
|
|
1189
|
+
const returned = returnedIn(cores, at);
|
|
1190
|
+
if (returned.issues.length > 0) throw new VexError("invalid_dsl", `${returned.issues.join("; ")}.`);
|
|
990
1191
|
const m = scopeMutation(core, mctx.policy);
|
|
991
1192
|
assertWritableColumns(m, mctx.schema);
|
|
1193
|
+
assertReturnedColumns(returned.refs, mctx.schema);
|
|
992
1194
|
const statement = compileMutation(m, mctx.schema);
|
|
993
1195
|
requireScope({ paramSlots: statement.slots }, mctx.scope);
|
|
994
|
-
|
|
1196
|
+
const reads = [...statement.returned].map(([slot, ref]) => {
|
|
1197
|
+
const source = returned.refs.get(ref);
|
|
1198
|
+
if (source === void 0) throw new VexError("invalid_dsl", `"${ref}" names no earlier statement of the batch.`);
|
|
1199
|
+
return { slot, ref, source };
|
|
1200
|
+
});
|
|
1201
|
+
return { ...statement, reads, table: m.table, op: m.op === "insertEach" ? "insert" : m.op };
|
|
995
1202
|
});
|
|
996
1203
|
const runAll = async (q) => {
|
|
997
1204
|
const results = [];
|
|
998
1205
|
for (const c of compiled) {
|
|
999
1206
|
const params = await resolveParams(c.slots, mctx.context, mctx.scope);
|
|
1207
|
+
for (const read of c.reads) {
|
|
1208
|
+
const rows = results[read.source.statement]?.rows ?? [];
|
|
1209
|
+
const row = rows[0];
|
|
1210
|
+
if (rows.length !== 1 || row === void 0) {
|
|
1211
|
+
throw new VexError(
|
|
1212
|
+
"execution_error",
|
|
1213
|
+
`"${read.ref}" needs exactly one row from statement ${read.source.statement + 1} of the batch, which wrote ${rows.length}. Nothing was written.`,
|
|
1214
|
+
{ returned: read.ref, rows: rows.length }
|
|
1215
|
+
);
|
|
1216
|
+
}
|
|
1217
|
+
if (!(read.source.column in row)) {
|
|
1218
|
+
throw new VexError("execution_error", `"${read.ref}": the row statement ${read.source.statement + 1} returned has no "${read.source.column}" key. Nothing was written.`, { returned: read.ref });
|
|
1219
|
+
}
|
|
1220
|
+
params[read.slot] = row[read.source.column];
|
|
1221
|
+
}
|
|
1000
1222
|
const bound = params.map((value, i) => {
|
|
1001
1223
|
if (c.slots[i]?.encode === "json") return value !== null && typeof value === "object" ? JSON.stringify(value) : value;
|
|
1002
1224
|
if (c.slots[i]?.type !== "json") return value;
|
|
@@ -1294,11 +1516,11 @@ var runQuery = async (config, body, scope, probe, live) => {
|
|
|
1294
1516
|
}
|
|
1295
1517
|
return { status: 200, body: response };
|
|
1296
1518
|
} catch (err) {
|
|
1297
|
-
if (err
|
|
1519
|
+
if (isVexError(err) && err.code === "missing_scope") {
|
|
1298
1520
|
console.error("[vex] refused a statement the host did not scope:", err.message);
|
|
1299
1521
|
return { status: 500, body: { error: "missing_scope", message: "The server did not supply the scope this request needs." } };
|
|
1300
1522
|
}
|
|
1301
|
-
if (err
|
|
1523
|
+
if (isVexError(err)) {
|
|
1302
1524
|
const status = err.code === "fingerprint_protected" ? 409 : err.code === "cache_miss" ? 404 : 400;
|
|
1303
1525
|
return {
|
|
1304
1526
|
status,
|
|
@@ -1363,8 +1585,18 @@ var fingerprintFromBody = (body) => {
|
|
|
1363
1585
|
const fp = body["fingerprint"];
|
|
1364
1586
|
return typeof fp === "string" && fp.length > 0 ? fp : void 0;
|
|
1365
1587
|
};
|
|
1588
|
+
var NOT_JSON = { error: "invalid_request", message: "Body must be JSON" };
|
|
1366
1589
|
var vex = (config) => {
|
|
1367
1590
|
const app = new hono.Hono();
|
|
1591
|
+
const jsonBodyOf = async (c) => {
|
|
1592
|
+
try {
|
|
1593
|
+
const body = await c.req.json();
|
|
1594
|
+
return { parsed: true, body };
|
|
1595
|
+
} catch (err) {
|
|
1596
|
+
if (err instanceof SyntaxError) return { parsed: false };
|
|
1597
|
+
throw err;
|
|
1598
|
+
}
|
|
1599
|
+
};
|
|
1368
1600
|
const requestConfig = async (c) => {
|
|
1369
1601
|
const policy = config.getPolicy ? await config.getPolicy(c) : void 0;
|
|
1370
1602
|
const mutationPolicy = policy ?? config.mutations?.policy;
|
|
@@ -1392,12 +1624,15 @@ var vex = (config) => {
|
|
|
1392
1624
|
app.get("/", async (c) => c.json(await handleDiscovery(await requestConfig(c))));
|
|
1393
1625
|
app.post("/", async (c) => {
|
|
1394
1626
|
const scope = config.getScope ? await config.getScope(c) : {};
|
|
1395
|
-
const
|
|
1396
|
-
|
|
1627
|
+
const read = await jsonBodyOf(c);
|
|
1628
|
+
if (!read.parsed) return c.json(NOT_JSON, 400);
|
|
1629
|
+
const result = await handleQuery(await requestConfig(c), read.body, scope, liveOf(c.env));
|
|
1397
1630
|
return c.json(result.body, result.status);
|
|
1398
1631
|
});
|
|
1399
1632
|
app.patch("/", async (c) => {
|
|
1400
|
-
const
|
|
1633
|
+
const read = await jsonBodyOf(c);
|
|
1634
|
+
if (!read.parsed) return c.json(NOT_JSON, 400);
|
|
1635
|
+
const body = read.body;
|
|
1401
1636
|
const fingerprint = fingerprintFromBody(body);
|
|
1402
1637
|
if (fingerprint === void 0) {
|
|
1403
1638
|
return c.json({ error: "invalid_request", message: "Body must include { fingerprint }" }, 400);
|
|
@@ -1409,8 +1644,9 @@ var vex = (config) => {
|
|
|
1409
1644
|
return c.json(result.body, result.status);
|
|
1410
1645
|
});
|
|
1411
1646
|
app.delete("/", async (c) => {
|
|
1412
|
-
const
|
|
1413
|
-
|
|
1647
|
+
const read = await jsonBodyOf(c);
|
|
1648
|
+
if (!read.parsed) return c.json(NOT_JSON, 400);
|
|
1649
|
+
const fingerprint = fingerprintFromBody(read.body);
|
|
1414
1650
|
if (fingerprint === void 0) {
|
|
1415
1651
|
return c.json({ error: "invalid_request", message: "Body must include { fingerprint }" }, 400);
|
|
1416
1652
|
}
|