@voltro/database 0.63.0 → 0.65.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/dist/index.js CHANGED
@@ -1,13 +1,13 @@
1
- import { $ as e, $t as t, A as n, At as r, B as i, Bt as a, C as o, Ct as s, D as c, Dt as l, E as u, Et as d, F as f, Ft as p, G as m, Gt as h, H as g, Ht as _, I as ee, It as te, J as ne, Jt as v, K as y, Kt as re, L as b, Lt as ie, M as ae, Mt as oe, N as x, Nt as se, O as ce, Ot as le, P as ue, Pt as de, Q as fe, Qt as pe, R as me, Rt as he, S as ge, St as _e, T as ve, Tt as ye, U as be, Ut as S, V as xe, Vt as Se, W as Ce, Wt as we, X as Te, Xt as Ee, Y as De, Yt as Oe, Z as ke, Zt as Ae, _ as je, _t as Me, a as Ne, at as Pe, b as Fe, bt as Ie, c as Le, ct as Re, d as ze, dt as Be, en as C, et as Ve, f as He, ft as Ue, g as We, gt as Ge, h as w, ht as Ke, it as T, j as qe, jt as Je, k as Ye, kt as Xe, l as Ze, lt as Qe, m as $e, mt as et, n as tt, nt, o as rt, ot as it, p as at, pt as ot, q as E, qt as st, r as ct, rt as lt, s as ut, st as dt, t as ft, tn as pt, tt as mt, u as ht, ut as gt, v as _t, vt, w as yt, wt as bt, x as xt, xt as St, y as Ct, yt as wt, z as Tt, zt as Et } from "./frameworkLiveTables-X6rOAleu.js";
2
- import { timestampMs as Dt, timestampMsOrNull as Ot } from "./wire.js";
3
- import { Cause as kt, Chunk as At, Data as jt, Effect as D, Exit as Mt, Metric as O, MetricBoundaries as Nt, Option as k, Runtime as Pt, Schedule as Ft, Schema as A, Stream as It } from "effect";
4
- import { createHash as Lt } from "node:crypto";
5
- import { AsyncLocalStorage as Rt } from "node:async_hooks";
6
- import { TransactionConnection as zt } from "@effect/sql/SqlClient";
7
- import { ansi as j } from "@voltro/logger";
8
- import { SqlClient as Bt } from "@effect/sql";
1
+ import { $ as e, $t as t, A as n, At as r, B as i, Bt as a, C as o, Ct as s, D as c, Dt as l, E as u, Et as d, F as f, Ft as p, G as m, Gt as h, H as g, Ht as ee, I as te, It as ne, J as re, Jt as _, K as ie, Kt as ae, L as v, Lt as oe, M as y, Mt as se, N as b, Nt as ce, O as le, Ot as ue, P as de, Pt as fe, Q as pe, Qt as me, R as he, Rt as ge, S as _e, St as ve, T as ye, Tt as be, U as xe, Ut as Se, V as Ce, Vt as we, W as Te, Wt as Ee, X as De, Xt as x, Y as Oe, Yt as ke, Z as S, Zt as Ae, _ as je, _t as Me, a as Ne, an as C, at as Pe, b as Fe, bt as Ie, c as Le, ct as w, d as Re, dt as ze, en as Be, et as Ve, f as He, ft as Ue, g as We, gt as Ge, h as Ke, ht as qe, i as Je, in as Ye, it as Xe, j as Ze, jt as Qe, k as $e, kt as et, l as tt, lt as nt, m as rt, mt as it, n as at, nn as ot, nt as st, o as ct, on as T, ot as lt, p as ut, pt as dt, q as ft, qt as E, r as pt, rn as mt, rt as ht, s as gt, sn as _t, st as vt, t as yt, tn as bt, tt as xt, u as St, ut as Ct, v as wt, vt as Tt, w as Et, wt as Dt, x as Ot, xt as kt, y as D, yt as At, z as jt, zt as Mt } from "./frameworkLiveTables-BURogL9N.js";
2
+ import { a as Nt, i as Pt, n as Ft, o as It, r as Lt, s as Rt, t as zt } from "./wire-B28cPjEp.js";
3
+ import { Cause as O, Chunk as Bt, Data as Vt, Effect as k, Exit as Ht, Metric as A, MetricBoundaries as Ut, Option as j, Runtime as Wt, Schedule as Gt, Schema as M, Stream as Kt } from "effect";
4
+ import { createHash as qt } from "node:crypto";
5
+ import { AsyncLocalStorage as Jt } from "node:async_hooks";
6
+ import { TransactionConnection as Yt } from "@effect/sql/SqlClient";
7
+ import { ansi as N } from "@voltro/logger";
8
+ import { SqlClient as Xt } from "@effect/sql";
9
9
  //#region src/actorSnapshot.ts
10
- var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n) => {
10
+ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n) => {
11
11
  if (t != null && t !== "") try {
12
12
  let r = (await e.query({
13
13
  table: "actors",
@@ -23,20 +23,20 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
23
23
  }))[0];
24
24
  return r === void 0 ? void 0 : {
25
25
  id: t,
26
- type: Vt(r.kind) ?? n,
27
- displayName: Vt(r.displayName),
28
- email: Vt(r.email)
26
+ type: Zt(r.kind) ?? n,
27
+ displayName: Zt(r.displayName),
28
+ email: Zt(r.email)
29
29
  };
30
30
  } catch {
31
31
  return;
32
32
  }
33
- }, Ut = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqlite", Wt = (e) => {
33
+ }, $t = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqlite", en = (e) => {
34
34
  let t = [];
35
35
  for (let [n, r] of Object.entries(e.fields)) r.type === "array" && t.push(n);
36
36
  return t;
37
- }, Gt = (e, t, n) => {
38
- if (!Ut(n) || !t) return e;
39
- let r = Wt(t);
37
+ }, tn = (e, t, n) => {
38
+ if (!$t(n) || !t) return e;
39
+ let r = en(t);
40
40
  if (r.length === 0) return e;
41
41
  let i = { ...e };
42
42
  for (let e of r) {
@@ -44,9 +44,9 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
44
44
  Array.isArray(t) && (i[e] = JSON.stringify(t));
45
45
  }
46
46
  return i;
47
- }, Kt = (e, t, n) => {
48
- if (!Ut(n) || !t) return e;
49
- let r = Wt(t);
47
+ }, nn = (e, t, n) => {
48
+ if (!$t(n) || !t) return e;
49
+ let r = en(t);
50
50
  return r.length === 0 ? e : e.map((e) => {
51
51
  let t;
52
52
  for (let n of r) {
@@ -58,7 +58,13 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
58
58
  }
59
59
  return t ?? e;
60
60
  });
61
- }, qt = "enc:v1:", Jt = class extends Error {
61
+ }, rn = "enc:v1:", an = "enc:v2:", on = (e, t, n) => {
62
+ let r = `${e}:${t}`, i = n == null || n === "" ? void 0 : String(n);
63
+ return i === void 0 ? { column: r } : {
64
+ column: r,
65
+ row: `${r}:${i}`
66
+ };
67
+ }, sn = (e) => typeof e == "string" && e.startsWith("enc:v2:"), cn = class extends Error {
62
68
  _tag = "FieldDecryptionError";
63
69
  table;
64
70
  column;
@@ -66,7 +72,7 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
66
72
  constructor(e) {
67
73
  super(`column "${e.table}.${e.column}" is .encrypted() but could not be decrypted (${e.reason}) — the stored value was most likely encrypted under a different key`), this.name = "FieldDecryptionError", this.table = e.table, this.column = e.column, this.reason = e.reason;
68
74
  }
69
- }, Yt = (e) => typeof e == "object" && !!e && e._tag === "FieldDecryptionError", Xt = (e) => typeof e == "string" && e.startsWith("enc:v1:"), Zt = (e, t) => e.encrypt(JSON.stringify(t)), Qt = /* @__PURE__ */ new Set([
75
+ }, ln = (e) => typeof e == "object" && !!e && e._tag === "FieldDecryptionError", un = (e) => typeof e == "string" && (e.startsWith("enc:v1:") || e.startsWith("enc:v2:")), dn = (e, t, n) => e.encrypt(JSON.stringify(t), n), fn = /* @__PURE__ */ new Set([
70
76
  "text",
71
77
  "id",
72
78
  "reference",
@@ -74,51 +80,51 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
74
80
  "uuid",
75
81
  "email",
76
82
  "url"
77
- ]), $t = (e, t, n) => {
78
- let r = e.decrypt(t), i;
83
+ ]), pn = (e, t, n, r) => {
84
+ let i = e.decrypt(t, r), a;
79
85
  try {
80
- i = JSON.parse(r);
86
+ a = JSON.parse(i);
81
87
  } catch {
82
- return r;
88
+ return i;
83
89
  }
84
- return typeof i == "string" ? i : n === void 0 || Qt.has(n) ? r : i;
85
- }, en = (e, t, n) => {
86
- let r = e.decrypt(t);
90
+ return typeof a == "string" ? a : n === void 0 || fn.has(n) ? i : a;
91
+ }, mn = (e, t, n, r) => {
92
+ let i = e.decrypt(t, r);
87
93
  try {
88
- return typeof JSON.parse(r) == "string" ? !1 : n === void 0 || Qt.has(n) ? !0 : void 0;
94
+ return typeof JSON.parse(i) == "string" ? !1 : n === void 0 || fn.has(n) ? !0 : void 0;
89
95
  } catch {
90
96
  return !0;
91
97
  }
92
- }, tn = (e, t) => e.fields[t]?.type, nn = (e) => {
98
+ }, hn = (e, t) => e.fields[t]?.type, gn = (e) => {
93
99
  let t = [];
94
100
  for (let [n, r] of Object.entries(e.fields)) r.encrypted === !0 && t.push(n);
95
101
  return t;
96
- }, rn = (e, t, n) => {
102
+ }, _n = "id", vn = (e, t, n, r) => {
97
103
  if (!t) return e;
98
- let r = nn(t);
99
- if (r.length === 0) return e;
100
- let i = { ...e };
101
- for (let e of r) {
102
- let r = i[e];
103
- if (!(r == null || Xt(r))) {
104
- if (!n) throw Error(`column "${t.tableName ?? "?"}.${e}" is .encrypted() but no field cipher is registered — wire @voltro/plugin-governance's fieldEncryption (key via the Secrets-Resolver)`);
105
- i[e] = Zt(n, r);
104
+ let i = gn(t);
105
+ if (i.length === 0) return e;
106
+ let a = t.tableName ?? "?", o = r ?? e[_n], s = { ...e };
107
+ for (let e of i) {
108
+ let t = s[e];
109
+ if (!(t == null || un(t))) {
110
+ if (!n) throw Error(`column "${a}.${e}" is .encrypted() but no field cipher is registered — set VOLTRO_FIELD_ENCRYPTION_KEY (\`voltro dev\` mints one; \`voltro serve\` refuses to boot without it)`);
111
+ s[e] = dn(n, t, on(a, e, o));
106
112
  }
107
113
  }
108
- return i;
109
- }, an = (e, t, n, r) => {
114
+ return s;
115
+ }, yn = (e, t, n, r) => {
110
116
  if (!t) return e;
111
- let i = nn(t);
117
+ let i = gn(t);
112
118
  if (i.length === 0 || !n) return e;
113
119
  let a = r?.onError ?? "throw", o = t.tableName ?? "?";
114
120
  return e.map((e) => {
115
121
  let s;
116
122
  for (let c of i) {
117
123
  let i = e[c];
118
- if (Xt(i)) {
124
+ if (un(i)) {
119
125
  s ??= { ...e };
120
126
  try {
121
- s[c] = $t(n, i, tn(t, c));
127
+ s[c] = pn(n, i, hn(t, c), on(o, c, r?.rowId ?? e[_n]));
122
128
  } catch (e) {
123
129
  let t = String(e?.message ?? e);
124
130
  if (a === "null") {
@@ -129,7 +135,7 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
129
135
  });
130
136
  continue;
131
137
  }
132
- throw new Jt({
138
+ throw new cn({
133
139
  table: o,
134
140
  column: c,
135
141
  reason: t
@@ -139,125 +145,136 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
139
145
  }
140
146
  return s ?? e;
141
147
  });
142
- }, on = (e) => {
148
+ }, bn = (e) => {
143
149
  let t = e;
144
- for (let e = 0; e < 4 && Pt.isFiberFailure(t); e++) t = kt.squash(t[Pt.FiberFailureCauseId]);
150
+ for (let e = 0; e < 4 && Wt.isFiberFailure(t); e++) t = O.squash(t[Wt.FiberFailureCauseId]);
145
151
  return t;
146
- }, sn = (e, t = 0) => {
147
- if (t >= 4 || !Pt.isFiberFailure(e)) return [e];
148
- let n = e[Pt.FiberFailureCauseId], r = [...kt.failures(n), ...kt.defects(n)];
149
- if (r.length === 0) return [kt.squash(n)];
152
+ }, xn = (e, t = 0) => {
153
+ if (t >= 4 || !Wt.isFiberFailure(e)) return [e];
154
+ let n = e[Wt.FiberFailureCauseId], r = [...O.failures(n), ...O.defects(n)];
155
+ if (r.length === 0) return [O.squash(n)];
150
156
  let i = [];
151
- for (let e of r.slice(0, 8)) i.push(...sn(e, t + 1));
157
+ for (let e of r.slice(0, 8)) i.push(...xn(e, t + 1));
152
158
  return i;
153
- }, cn = (e) => e.dbCode !== void 0 || e.dbErrno !== void 0 || e.dbNumber !== void 0 || e.dbSqlState !== void 0 || e.dbConstraint !== void 0, ln = (e) => {
154
- let t = {}, n = [], r = on(e);
159
+ }, Sn = (e) => e.dbCode !== void 0 || e.dbErrno !== void 0 || e.dbNumber !== void 0 || e.dbSqlState !== void 0 || e.dbConstraint !== void 0, Cn = (e) => {
160
+ let t = {}, n = [], r = bn(e);
155
161
  for (let e = 0; e < 8 && typeof r == "object" && r; e++) {
156
162
  let e = r;
157
163
  t.dbCode === void 0 && (typeof e.code == "string" || typeof e.code == "number") && (t.dbCode = e.code), t.dbErrno === void 0 && typeof e.errno == "number" && (t.dbErrno = e.errno), t.dbNumber === void 0 && typeof e.number == "number" && (t.dbNumber = e.number), t.dbSqlState === void 0 && typeof e.sqlState == "string" && (t.dbSqlState = e.sqlState), t.dbBindings === void 0 && typeof e.voltroBindings == "string" && (t.dbBindings = e.voltroBindings), t.dbStatement === void 0 && typeof e.sql == "string" && e.sql.includes("?") && (t.dbStatement = e.sql, t.dbPlaceholders = (e.sql.match(/\?/g) ?? []).length), t.dbFatal === void 0 && typeof e.fatal == "boolean" && (t.dbFatal = e.fatal), t.dbConstraint === void 0 && typeof e.constraint == "string" && (t.dbConstraint = e.constraint), t.dbTable === void 0 && typeof e.table == "string" && (t.dbTable = e.table), t.dbColumn === void 0 && typeof e.column == "string" && (t.dbColumn = e.column), t.dbSchema === void 0 && typeof e.schema == "string" && (t.dbSchema = e.schema);
158
164
  let i = e.sqlMessage ?? e.detail;
159
165
  t.dbMessage === void 0 && typeof i == "string" && (t.dbMessage = i);
160
166
  let a = typeof e.constructor == "function" ? e.constructor.name : void 0, o = typeof e._tag == "string" && e._tag || typeof e.name == "string" && e.name || (typeof a == "string" && a !== "Object" ? a : void 0), s = typeof e.message == "string" ? e.message : void 0;
161
- (o || s) && n.push(`${o || "Error"}${s ? `: ${s.slice(0, 200)}` : ""}`), r = on(e.cause);
167
+ (o || s) && n.push(`${o || "Error"}${s ? `: ${s.slice(0, 200)}` : ""}`), r = bn(e.cause);
162
168
  }
163
169
  return n.length > 0 && (t.dbCauseChain = n.join(" ← "), t.dbMessage === void 0 && (t.dbMessage = n[n.length - 1])), t;
164
- }, un = (e) => {
165
- let t = sn(e).map(ln);
170
+ }, wn = (e) => {
171
+ let t = xn(e).map(Cn);
166
172
  if (t.length <= 1) return t[0] ?? {};
167
- let n = t.find(cn) ?? t[0], r = t.filter((e) => e !== n).map((e) => e.dbCauseChain).filter((e) => typeof e == "string");
173
+ let n = t.find(Sn) ?? t[0], r = t.filter((e) => e !== n).map((e) => e.dbCauseChain).filter((e) => typeof e == "string");
168
174
  if (r.length === 0) return n;
169
175
  let i = typeof n.dbCauseChain == "string" ? n.dbCauseChain : void 0;
170
176
  return {
171
177
  ...n,
172
178
  dbCauseChain: [i, ...r].filter(Boolean).join(" ‖ ")
173
179
  };
174
- }, dn = /^[A-Za-z_][A-Za-z0-9_$]*$/, M = (e) => e !== void 0 && e.length <= 128 && dn.test(e) ? e : void 0, fn = (e) => e === void 0 ? void 0 : e.split(".").pop() ?? e, N = (e, ...t) => {
180
+ }, Tn = (e, t) => {
181
+ let n = wn(e), r = jn(n, t);
182
+ if (r !== void 0) {
183
+ let e = r.constraint ?? r.column;
184
+ return e === void 0 ? r.kind : `${r.kind}: ${e}`;
185
+ }
186
+ let i = n.dbCode ?? n.dbSqlState ?? n.dbErrno ?? n.dbNumber, a = On(e);
187
+ return i !== void 0 && En.test(String(i)) ? `${a} (${String(i)})` : a;
188
+ }, En = /^[A-Za-z0-9_]{1,32}$/, Dn = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/, On = (e) => {
189
+ let t = e?._tag, n = e?.name, r = (typeof t == "string" ? t : typeof n == "string" ? n : "").split(/[^A-Za-z0-9_]+/).filter(Boolean).pop();
190
+ return r !== void 0 && Dn.test(r) ? r : "unknown";
191
+ }, kn = /^[A-Za-z_][A-Za-z0-9_$]*$/, P = (e) => e !== void 0 && e.length <= 128 && kn.test(e) ? e : void 0, An = (e) => e === void 0 ? void 0 : e.split(".").pop() ?? e, F = (e, ...t) => {
175
192
  for (let n of t) {
176
193
  let t = n.exec(e);
177
194
  if (t?.[1] !== void 0) return t[1];
178
195
  }
179
- }, pn = (e, t) => {
196
+ }, jn = (e, t) => {
180
197
  let n = e.dbCode, r = e.dbErrno, i = e.dbNumber, a = typeof e.dbMessage == "string" ? e.dbMessage : "", o = `${typeof e.dbCauseChain == "string" ? e.dbCauseChain : ""} ${a}`;
181
198
  if (n === "23503") {
182
- let t = M(e.dbConstraint);
199
+ let t = P(e.dbConstraint);
183
200
  return {
184
201
  kind: /is still referenced from table/i.test(o) ? "foreignKeyInUse" : "foreignKey",
185
202
  ...t === void 0 ? {} : { constraint: t }
186
203
  };
187
204
  }
188
205
  if (n === "23505") {
189
- let t = M(e.dbConstraint);
206
+ let t = P(e.dbConstraint);
190
207
  return {
191
208
  kind: "unique",
192
209
  ...t === void 0 ? {} : { constraint: t }
193
210
  };
194
211
  }
195
212
  if (n === "23502") {
196
- let t = M(e.dbColumn);
213
+ let t = P(e.dbColumn);
197
214
  return {
198
215
  kind: "notNull",
199
216
  ...t === void 0 ? {} : { column: t }
200
217
  };
201
218
  }
202
219
  if (n === "23514") {
203
- let t = M(e.dbConstraint);
220
+ let t = P(e.dbConstraint);
204
221
  return {
205
222
  kind: "check",
206
223
  ...t === void 0 ? {} : { constraint: t }
207
224
  };
208
225
  }
209
226
  if (r === 1452 || r === 1451) {
210
- let e = M(N(o, /CONSTRAINT `([^`]+)`/));
227
+ let e = P(F(o, /CONSTRAINT `([^`]+)`/));
211
228
  return {
212
229
  kind: r === 1451 ? "foreignKeyInUse" : "foreignKey",
213
230
  ...e === void 0 ? {} : { constraint: e }
214
231
  };
215
232
  }
216
233
  if (r === 1062) {
217
- let e = M(fn(N(o, /for key '([^']+)'/)));
234
+ let e = P(An(F(o, /for key '([^']+)'/)));
218
235
  return {
219
236
  kind: "unique",
220
237
  ...e === void 0 ? {} : { constraint: e }
221
238
  };
222
239
  }
223
240
  if (r === 1048 || r === 1364) {
224
- let e = M(N(o, /Column '([^']+)' cannot be null/, /Field '([^']+)' doesn't have a default value/));
241
+ let e = P(F(o, /Column '([^']+)' cannot be null/, /Field '([^']+)' doesn't have a default value/));
225
242
  return {
226
243
  kind: "notNull",
227
244
  ...e === void 0 ? {} : { column: e }
228
245
  };
229
246
  }
230
247
  if (r === 3819 || r === 4025) {
231
- let e = M(N(o, /Check constraint '([^']+)'/, /CONSTRAINT `([^`]+)` failed/));
248
+ let e = P(F(o, /Check constraint '([^']+)'/, /CONSTRAINT `([^`]+)` failed/));
232
249
  return {
233
250
  kind: "check",
234
251
  ...e === void 0 ? {} : { constraint: e }
235
252
  };
236
253
  }
237
254
  if (i === 547) {
238
- let e = N(o, /(?:FOREIGN KEY|REFERENCE) constraint "([^"]+)"/), t = N(o, /CHECK constraint "([^"]+)"/);
255
+ let e = F(o, /(?:FOREIGN KEY|REFERENCE) constraint "([^"]+)"/), t = F(o, /CHECK constraint "([^"]+)"/);
239
256
  if (t !== void 0 && e === void 0) {
240
- let e = M(t);
257
+ let e = P(t);
241
258
  return {
242
259
  kind: "check",
243
260
  ...e === void 0 ? {} : { constraint: e }
244
261
  };
245
262
  }
246
- let n = /REFERENCE constraint/.test(o), r = M(e);
263
+ let n = /REFERENCE constraint/.test(o), r = P(e);
247
264
  return {
248
265
  kind: n ? "foreignKeyInUse" : "foreignKey",
249
266
  ...r === void 0 ? {} : { constraint: r }
250
267
  };
251
268
  }
252
269
  if (i === 2627 || i === 2601) {
253
- let e = M(N(o, /(?:UNIQUE KEY|PRIMARY KEY) constraint '([^']+)'/, /index '([^']+)'/));
270
+ let e = P(F(o, /(?:UNIQUE KEY|PRIMARY KEY) constraint '([^']+)'/, /index '([^']+)'/));
254
271
  return {
255
272
  kind: "unique",
256
273
  ...e === void 0 ? {} : { constraint: e }
257
274
  };
258
275
  }
259
276
  if (i === 515) {
260
- let e = M(N(o, /Cannot insert the value NULL into column '([^']+)'/));
277
+ let e = P(F(o, /Cannot insert the value NULL into column '([^']+)'/));
261
278
  return {
262
279
  kind: "notNull",
263
280
  ...e === void 0 ? {} : { column: e }
@@ -265,34 +282,34 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
265
282
  }
266
283
  if (n === "SQLITE_CONSTRAINT_FOREIGNKEY") return { kind: t === "delete" || t === "deleteMany" || t === "hardDelete" ? "foreignKeyInUse" : "foreignKey" };
267
284
  if (n === "SQLITE_CONSTRAINT_UNIQUE" || n === "SQLITE_CONSTRAINT_PRIMARYKEY") {
268
- let e = M(fn(N(o, /UNIQUE constraint failed: ([^,\s]+)/)));
285
+ let e = P(An(F(o, /UNIQUE constraint failed: ([^,\s]+)/)));
269
286
  return {
270
287
  kind: "unique",
271
288
  ...e === void 0 ? {} : { column: e }
272
289
  };
273
290
  }
274
291
  if (n === "SQLITE_CONSTRAINT_NOTNULL") {
275
- let e = M(fn(N(o, /NOT NULL constraint failed: ([^,\s]+)/)));
292
+ let e = P(An(F(o, /NOT NULL constraint failed: ([^,\s]+)/)));
276
293
  return {
277
294
  kind: "notNull",
278
295
  ...e === void 0 ? {} : { column: e }
279
296
  };
280
297
  }
281
298
  if (n === "SQLITE_CONSTRAINT_CHECK") {
282
- let e = M(N(a, /CHECK constraint failed: (.+)$/));
299
+ let e = P(F(a, /CHECK constraint failed: (.+)$/));
283
300
  return {
284
301
  kind: "check",
285
302
  ...e === void 0 ? {} : { constraint: e }
286
303
  };
287
304
  }
288
- }, mn = (e) => {
289
- let t = pn(e)?.kind;
305
+ }, Mn = (e) => {
306
+ let t = jn(e)?.kind;
290
307
  return t === "foreignKey" || t === "foreignKeyInUse";
291
- }, hn = (e) => {
308
+ }, Nn = (e) => {
292
309
  let t = e.dbCode, n = e.dbErrno;
293
310
  return t === "57014" || n === 3024 || n === 1969 || t === "ETIMEOUT" || t === "SQLITE_INTERRUPT";
294
- }, gn = (e) => {
295
- let t = un(e), n = [
311
+ }, Pn = (e) => {
312
+ let t = wn(e), n = [
296
313
  t.dbCode === void 0 ? void 0 : `code=${String(t.dbCode)}`,
297
314
  t.dbErrno === void 0 ? void 0 : `errno=${String(t.dbErrno)}`,
298
315
  t.dbNumber === void 0 ? void 0 : `number=${String(t.dbNumber)}`,
@@ -301,7 +318,7 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
301
318
  t.dbPlaceholders === void 0 ? void 0 : `placeholders=${String(t.dbPlaceholders)}`
302
319
  ].filter((e) => e !== void 0), r = typeof e?.message == "string" ? e.message : void 0, i = typeof t.dbMessage == "string" ? t.dbMessage : void 0, a = i === void 0 ? void 0 : n.length > 0 || i !== r && i !== `Error: ${String(r)}` ? i : void 0, o = typeof t.dbBindings == "string" ? `\n bindings: ${t.dbBindings}` : "", s = typeof t.dbStatement == "string" ? `\n statement: ${t.dbStatement.length <= 400 ? t.dbStatement : `${t.dbStatement.slice(0, 400)}…`}` : "";
303
320
  if (a !== void 0 || n.length !== 0) return [a, n.length > 0 ? `[${n.join(" ")}]` : void 0].filter((e) => e !== void 0 && e !== "").join(" ") + s + o;
304
- }, _n = (e) => Object.entries(e).map(([e, t]) => `${e}:${vn(t)}`).join(" "), vn = (e) => {
321
+ }, Fn = (e) => Object.entries(e).map(([e, t]) => `${e}:${In(t)}`).join(" "), In = (e) => {
305
322
  if (e === null) return "null";
306
323
  if (e === void 0) return "undefined";
307
324
  if (typeof e == "bigint") return "bigint";
@@ -311,77 +328,77 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
311
328
  if (globalThis.Buffer !== void 0 && globalThis.Buffer.isBuffer(e)) return "Buffer";
312
329
  let t = e.constructor?.name;
313
330
  return typeof t == "string" && t !== "" ? t : "Object";
314
- }, yn = Symbol.for("@voltro/database/storeRefusal"), bn = (e) => {
331
+ }, Ln = Symbol.for("@voltro/database/storeRefusal"), Rn = (e) => {
315
332
  let t = Error(e.detail);
316
- return Object.defineProperty(t, yn, {
333
+ return Object.defineProperty(t, Ln, {
317
334
  value: e,
318
335
  enumerable: !1
319
336
  }), t;
320
- }, xn = (e) => {
321
- for (let t of sn(e)) {
337
+ }, zn = (e) => {
338
+ for (let t of xn(e)) {
322
339
  let e = t;
323
340
  for (let t = 0; e != null && t < 8; t += 1) {
324
- let t = e[yn];
341
+ let t = e[Ln];
325
342
  if (t !== void 0) return t;
326
343
  e = e.cause;
327
344
  }
328
345
  }
329
- }, Sn = (e) => {
346
+ }, Bn = (e) => {
330
347
  let t = (() => {
331
348
  switch (e.type) {
332
349
  case "id":
333
350
  case "reference":
334
351
  case "text":
335
- case "enum": return A.String;
352
+ case "enum": return M.String;
336
353
  case "integer":
337
354
  case "real":
338
- case "decimal": return A.Number;
339
- case "boolean": return A.Boolean;
355
+ case "decimal": return M.Number;
356
+ case "boolean": return M.Boolean;
340
357
  case "timestamp":
341
- case "date": return Dt;
342
- case "bigint": return A.BigInt;
343
- case "bytes": return A.Uint8ArrayFromBase64;
344
- case "array": return A.Array(A.Unknown);
345
- case "interval": return A.String;
346
- default: return A.Unknown;
358
+ case "date": return zt;
359
+ case "bigint": return M.BigInt;
360
+ case "bytes": return M.Uint8ArrayFromBase64;
361
+ case "array": return M.Array(M.Unknown);
362
+ case "interval": return M.String;
363
+ default: return M.Unknown;
347
364
  }
348
365
  })();
349
- return e.nullable === !0 ? A.NullOr(t) : t;
350
- }, Cn = (e, t) => {
366
+ return e.nullable === !0 ? M.NullOr(t) : t;
367
+ }, Vn = (e, t) => {
351
368
  let n = new Set(t?.omit ?? []), r = {};
352
- for (let [t, i] of Object.entries(e.fields)) n.has(t) || (r[t] = Sn(i));
353
- return A.Struct(r);
354
- }, wn = (e) => typeof e == "function" ? e : () => e, Tn = (e, t) => ({
369
+ for (let [t, i] of Object.entries(e.fields)) n.has(t) || (r[t] = Bn(i));
370
+ return M.Struct(r);
371
+ }, Hn = (e) => typeof e == "function" ? e : () => e, Un = (e, t) => ({
355
372
  kind: "one",
356
- target: wn(e),
373
+ target: Hn(e),
357
374
  ...t?.foreignKey === void 0 ? {} : { foreignKey: t.foreignKey },
358
375
  ...t?.sourceKey === void 0 ? {} : { sourceKey: t.sourceKey }
359
- }), En = (e, t) => ({
376
+ }), Wn = (e, t) => ({
360
377
  kind: "many",
361
- target: wn(e),
378
+ target: Hn(e),
362
379
  ...t?.foreignKey === void 0 ? {} : { foreignKey: t.foreignKey },
363
380
  ...t?.sourceKey === void 0 ? {} : { sourceKey: t.sourceKey }
364
- }), Dn = (e, t) => ({
381
+ }), Gn = (e, t) => ({
365
382
  kind: "manyToMany",
366
- target: wn(e),
367
- through: wn(t.through),
383
+ target: Hn(e),
384
+ through: Hn(t.through),
368
385
  sourceKey: t.sourceKey,
369
386
  targetKey: t.targetKey
370
- }), On = {
371
- one: Tn,
372
- many: En,
373
- manyToMany: Dn
374
- }, kn = (e, t) => {
387
+ }), Kn = {
388
+ one: Un,
389
+ many: Wn,
390
+ manyToMany: Gn
391
+ }, qn = (e, t) => {
375
392
  let n = typeof e == "function" ? e : () => e;
376
393
  return {
377
394
  source: n,
378
- relations: t(On, n())
395
+ relations: t(Kn, n())
379
396
  };
380
- }, An = (e) => {
397
+ }, Jn = (e) => {
381
398
  if (typeof e != "object" || !e) return !1;
382
399
  let t = e;
383
400
  return typeof t.source != "function" || typeof t.relations != "object" || t.relations === null ? !1 : Object.keys(t.relations).length === 0;
384
- }, jn = (e) => {
401
+ }, Yn = (e) => {
385
402
  if (typeof e != "object" || !e) return !1;
386
403
  let t = e;
387
404
  if (typeof t.source != "function" || typeof t.relations != "object" || t.relations === null) return !1;
@@ -390,35 +407,35 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
390
407
  let t = e?.kind;
391
408
  return t === "one" || t === "many" || t === "manyToMany";
392
409
  });
393
- }, Mn = Tn, Nn = En, Pn = Dn, Fn = (e, t, n) => {
410
+ }, Xn = Un, Zn = Wn, Qn = Gn, $n = (e, t, n) => {
394
411
  let r = [];
395
412
  for (let [n, i] of Object.entries(e.fields)) i.type === "reference" && i.references?.()?.tableName === t && r.push(n);
396
413
  if (r.length === 0) throw Error(`relation '${n}': no reference() column on '${e.tableName}' points at '${t}'. Either add one or pass an explicit { foreignKey: '<column>' }.`);
397
414
  if (r.length > 1) throw Error(`relation '${n}': multiple reference() columns on '${e.tableName}' point at '${t}' (${r.join(", ")}). Pass an explicit { foreignKey: '<column>' } to disambiguate.`);
398
415
  return r[0];
399
- }, In = (e) => Object.keys(e.fields), Ln = (e, t) => Object.prototype.hasOwnProperty.call(e.fields, t), Rn = (e) => {
400
- let t = In(e);
416
+ }, er = (e) => Object.keys(e.fields), tr = (e, t) => Object.prototype.hasOwnProperty.call(e.fields, t), nr = (e) => {
417
+ let t = er(e);
401
418
  return t.length === 0 ? "<none>" : t.join(", ");
402
- }, zn = (e, t, n) => {
419
+ }, rr = (e, t, n) => {
403
420
  let r = `relation '${t}' on '${e.tableName}'`, i = n.target();
404
421
  if (n.kind === "manyToMany") {
405
422
  let t = n.through();
406
- for (let [a, o] of [["sourceKey", n.sourceKey], ["targetKey", n.targetKey]]) if (!Ln(t, o)) throw Error(`${r}: manyToMany ${a} '${o}' is not a column on the junction table '${t.tableName}'. Both keys name columns on the JUNCTION — ${a === "sourceKey" ? `sourceKey points at '${e.tableName}'` : `targetKey points at '${i.tableName}'`}. Columns on '${t.tableName}': ${Rn(t)}.`);
423
+ for (let [a, o] of [["sourceKey", n.sourceKey], ["targetKey", n.targetKey]]) if (!tr(t, o)) throw Error(`${r}: manyToMany ${a} '${o}' is not a column on the junction table '${t.tableName}'. Both keys name columns on the JUNCTION — ${a === "sourceKey" ? `sourceKey points at '${e.tableName}'` : `targetKey points at '${i.tableName}'`}. Columns on '${t.tableName}': ${nr(t)}.`);
407
424
  return;
408
425
  }
409
426
  if (n.sourceKey !== void 0 && n.foreignKey !== void 0) throw Error(`${r}: pass EITHER sourceKey OR foreignKey, not both. sourceKey '${n.sourceKey}' names a column on the source ('${e.tableName}') holding the target's id; foreignKey '${n.foreignKey}' names a column on the target ('${i.tableName}') holding the source's id. With both, foreignKey is ignored.`);
410
- if (n.sourceKey !== void 0 && !Ln(e, n.sourceKey)) {
411
- let t = Ln(i, n.sourceKey);
412
- throw Error(`${r}: sourceKey '${n.sourceKey}' is not a column on the source table '${e.tableName}'.` + (t ? ` It IS a column on the target '${i.tableName}' — you probably want { foreignKey: '${n.sourceKey}' }, which names the column on the TARGET that holds this table's id.` : ` Columns on '${e.tableName}': ${Rn(e)}.`));
427
+ if (n.sourceKey !== void 0 && !tr(e, n.sourceKey)) {
428
+ let t = tr(i, n.sourceKey);
429
+ throw Error(`${r}: sourceKey '${n.sourceKey}' is not a column on the source table '${e.tableName}'.` + (t ? ` It IS a column on the target '${i.tableName}' — you probably want { foreignKey: '${n.sourceKey}' }, which names the column on the TARGET that holds this table's id.` : ` Columns on '${e.tableName}': ${nr(e)}.`));
413
430
  }
414
- if (n.foreignKey !== void 0 && !Ln(i, n.foreignKey)) {
415
- let t = Ln(e, n.foreignKey);
416
- throw Error(`${r}: foreignKey '${n.foreignKey}' is not a column on the target table '${i.tableName}'.` + (t ? ` It IS a column on the source '${e.tableName}' — you want { sourceKey: '${n.foreignKey}' }. foreignKey names the column on the TARGET that points back at this table; sourceKey names the column on THIS table that holds the target's id.` : ` Columns on '${i.tableName}': ${Rn(i)}.`));
431
+ if (n.foreignKey !== void 0 && !tr(i, n.foreignKey)) {
432
+ let t = tr(e, n.foreignKey);
433
+ throw Error(`${r}: foreignKey '${n.foreignKey}' is not a column on the target table '${i.tableName}'.` + (t ? ` It IS a column on the source '${e.tableName}' — you want { sourceKey: '${n.foreignKey}' }. foreignKey names the column on the TARGET that points back at this table; sourceKey names the column on THIS table that holds the target's id.` : ` Columns on '${i.tableName}': ${nr(i)}.`));
417
434
  }
418
- }, Bn = Symbol.for("@voltro/database/relationsRegistry"), Vn = globalThis, P = Vn[Bn] ?? (Vn[Bn] = /* @__PURE__ */ new Map()), Hn = (e) => {
419
- let t = e.source(), n = P.get(t.tableName);
435
+ }, ir = Symbol.for("@voltro/database/relationsRegistry"), ar = globalThis, I = ar[ir] ?? (ar[ir] = /* @__PURE__ */ new Map()), or = (e) => {
436
+ let t = e.source(), n = I.get(t.tableName);
420
437
  if (n === void 0) {
421
- P.set(t.tableName, new Map(Object.entries(e.relations)));
438
+ I.set(t.tableName, new Map(Object.entries(e.relations)));
422
439
  return;
423
440
  }
424
441
  for (let [r, i] of Object.entries(e.relations)) {
@@ -428,33 +445,33 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
428
445
  n.set(r, i);
429
446
  }
430
447
  }
431
- }, Un = (e) => {
448
+ }, sr = (e) => {
432
449
  let t = 0;
433
- for (let n of Object.values(e)) jn(n) && (Hn(n), t += 1);
450
+ for (let n of Object.values(e)) Yn(n) && (or(n), t += 1);
434
451
  return t;
435
- }, Wn = (e) => {
436
- let t = P.get(e);
452
+ }, cr = (e) => {
453
+ let t = I.get(e);
437
454
  if (t !== void 0) return Object.fromEntries(t);
438
- }, Gn = (e, t) => P.get(e)?.get(t), Kn = () => {
455
+ }, lr = (e, t) => I.get(e)?.get(t), ur = () => {
439
456
  let e = [];
440
- for (let [t, n] of P) for (let [r, i] of n) e.push({
457
+ for (let [t, n] of I) for (let [r, i] of n) e.push({
441
458
  source: t,
442
459
  name: r,
443
460
  relation: i
444
461
  });
445
462
  return e;
446
- }, qn = () => {
447
- for (let [e, t] of P) {
448
- let n = E(e);
449
- if (n !== void 0) for (let [e, r] of t) zn(n, e, r);
450
- }
451
- }, Jn = () => {
452
- P.clear();
453
- }, Yn = 4, Xn = (e) => Object.keys(e.fields), Zn = (e, t) => Object.prototype.hasOwnProperty.call(e.fields, t), Qn = (e, t) => {
463
+ }, dr = () => {
464
+ for (let [e, t] of I) {
465
+ let n = S(e);
466
+ if (n !== void 0) for (let [e, r] of t) rr(n, e, r);
467
+ }
468
+ }, fr = () => {
469
+ I.clear();
470
+ }, pr = 4, mr = (e) => Object.keys(e.fields), hr = (e, t) => Object.prototype.hasOwnProperty.call(e.fields, t), gr = (e, t) => {
454
471
  let n = [];
455
472
  for (let [r, i] of Object.entries(e.fields)) i.type === "reference" && i.references?.()?.tableName === t && n.push(r);
456
473
  return n;
457
- }, $n = (e, t) => {
474
+ }, _r = (e, t) => {
458
475
  let n = [];
459
476
  for (let r of t) {
460
477
  if (r.source !== e) continue;
@@ -471,7 +488,7 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
471
488
  } catch {
472
489
  continue;
473
490
  }
474
- if (!Zn(e, t.sourceKey)) continue;
491
+ if (!hr(e, t.sourceKey)) continue;
475
492
  n.push({
476
493
  table: e.tableName,
477
494
  foreignKey: t.sourceKey,
@@ -480,24 +497,24 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
480
497
  continue;
481
498
  }
482
499
  if (t.sourceKey !== void 0) continue;
483
- let a = Qn(i, e), o = t.foreignKey ?? (a.length === 1 ? a[0] : void 0);
484
- o === void 0 || !Zn(i, o) || n.push({
500
+ let a = gr(i, e), o = t.foreignKey ?? (a.length === 1 ? a[0] : void 0);
501
+ o === void 0 || !hr(i, o) || n.push({
485
502
  table: i.tableName,
486
503
  foreignKey: o,
487
504
  parentKey: "id"
488
505
  });
489
506
  }
490
507
  return n;
491
- }, er = (e, t) => {
508
+ }, vr = (e, t) => {
492
509
  let n = [];
493
- for (let r of t) if (r.tableName !== e) for (let t of Qn(r, e)) n.push({
510
+ for (let r of t) if (r.tableName !== e) for (let t of gr(r, e)) n.push({
494
511
  table: r.tableName,
495
512
  foreignKey: t,
496
513
  parentKey: "id"
497
514
  });
498
515
  return n;
499
- }, tr = (e) => `${e.table}\u0000${e.hops.map((e) => `${e.table}.${e.foreignKey}<-${e.parentKey}`).join("|")}`, nr = (e) => {
500
- let t = e.tables ?? Ce(), n = e.relations ?? Kn(), r = e.maxDepth ?? 4, i = new Set(e.exclude ?? []), a = new Map(t.map((e) => [e.tableName, e])), o = [];
516
+ }, yr = (e) => `${e.table}\u0000${e.hops.map((e) => `${e.table}.${e.foreignKey}<-${e.parentKey}`).join("|")}`, br = (e) => {
517
+ let t = e.tables ?? re(), n = e.relations ?? ur(), r = e.maxDepth ?? 4, i = new Set(e.exclude ?? []), a = new Map(t.map((e) => [e.tableName, e])), o = [];
501
518
  if (!a.has(e.subjectTable)) return {
502
519
  subjectTable: e.subjectTable,
503
520
  paths: [],
@@ -512,11 +529,11 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
512
529
  hops: [],
513
530
  depth: 0,
514
531
  via: "relation"
515
- }, c = [s], l = /* @__PURE__ */ new Set([tr(s)]), u = /* @__PURE__ */ new Set(), d = [s];
532
+ }, c = [s], l = /* @__PURE__ */ new Set([yr(s)]), u = /* @__PURE__ */ new Set(), d = [s];
516
533
  for (let e = 1; e <= r; e++) {
517
534
  let r = [];
518
535
  for (let a of d) {
519
- let s = $n(a.table, n), d = er(a.table, t), f = [...s.map((e) => [e, "relation"]), ...d.map((e) => [e, "reference"])];
536
+ let s = _r(a.table, n), d = vr(a.table, t), f = [...s.map((e) => [e, "relation"]), ...d.map((e) => [e, "reference"])];
520
537
  for (let [t, n] of f) {
521
538
  if (i.has(t.table)) {
522
539
  o.push({
@@ -534,7 +551,7 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
534
551
  hops: [...a.hops, t],
535
552
  depth: e,
536
553
  via: n
537
- }, f = tr(d);
554
+ }, f = yr(d);
538
555
  l.has(f) || (l.add(f), c.push(d), r.push(d));
539
556
  }
540
557
  }
@@ -544,7 +561,7 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
544
561
  }
545
562
  d = r;
546
563
  }
547
- for (let e of d) ($n(e.table, n).length > 0 || er(e.table, t).length > 0) && o.push({
564
+ for (let e of d) (_r(e.table, n).length > 0 || vr(e.table, t).length > 0) && o.push({
548
565
  kind: "depth-truncated",
549
566
  table: e.table,
550
567
  detail: `stopped at maxDepth ${r}; tables linked FROM '${e.table}' were not explored`
@@ -553,14 +570,14 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
553
570
  for (let n of t) f.has(n.tableName) || i.has(n.tableName) || o.push({
554
571
  kind: "unreachable",
555
572
  table: n.tableName,
556
- detail: `no relation() and no reference() column links '${n.tableName}' to '${e.subjectTable}'. If it holds subject data through a plain column, a polymorphic (type,id) pair, JSON or free text, add an explicit subjectScopes entry — this derivation cannot see it. Columns: ${Xn(n).join(", ")}`
573
+ detail: `no relation() and no reference() column links '${n.tableName}' to '${e.subjectTable}'. If it holds subject data through a plain column, a polymorphic (type,id) pair, JSON or free text, add an explicit subjectScopes entry — this derivation cannot see it. Columns: ${mr(n).join(", ")}`
557
574
  });
558
575
  return {
559
576
  subjectTable: e.subjectTable,
560
577
  paths: c,
561
578
  limitations: o
562
579
  };
563
- }, rr = (e) => {
580
+ }, xr = (e) => {
564
581
  let t = [`subject graph · ${e.subjectTable} · ${e.paths.length} table(s) reachable`];
565
582
  for (let n of e.paths) {
566
583
  let r = n.hops.length === 0 ? `${e.subjectTable} (the subject row itself)` : [e.subjectTable, ...n.hops.map((e) => `${e.table}.${e.foreignKey}`)].join(" → ");
@@ -568,7 +585,7 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
568
585
  }
569
586
  let n = e.limitations.filter((e) => e.kind === "depth-truncated"), r = e.limitations.filter((e) => e.kind === "unreachable"), i = e.limitations.filter((e) => e.kind === "excluded");
570
587
  return t.push(""), t.push(" WHAT THIS CANNOT SEE — a DSAR is only as complete as this list is short:"), n.length > 0 && t.push(` depth-truncated (${n.length}): ${n.map((e) => e.table).join(", ")}`), i.length > 0 && t.push(` excluded (${i.length}): ${[...new Set(i.map((e) => e.table))].join(", ")}`), t.push(r.length === 0 ? " unreachable: none — every registered table is linked to the subject." : ` unreachable (${r.length}): ${r.map((e) => e.table).join(", ")}`), t.push(" Always outside this graph: object storage / uploaded files, external processors,"), t.push(" log and metric sinks, backups, and any subject id embedded in JSON or free text."), t.join("\n");
571
- }, ir = (e) => e == null || typeof e == "boolean" ? e : typeof e == "number" ? e !== 0 : typeof e == "bigint" ? e !== 0n : typeof e == "string" ? e === "1" || e.toLowerCase() === "true" : e, ar = (e) => {
588
+ }, Sr = (e) => e == null || typeof e == "boolean" ? e : typeof e == "number" ? e !== 0 : typeof e == "bigint" ? e !== 0n : typeof e == "string" ? e === "1" || e.toLowerCase() === "true" : e, Cr = (e) => {
572
589
  if (e == null || typeof e != "string") return e;
573
590
  let t = e.trim();
574
591
  if (t.length === 0) return e;
@@ -579,7 +596,7 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
579
596
  } catch {
580
597
  return e;
581
598
  }
582
- }, or = (e) => e == null || typeof e == "string" ? e : typeof e == "number" || typeof e == "bigint" ? String(e) : e, sr = (e) => {
599
+ }, wr = (e) => e == null || typeof e == "string" ? e : typeof e == "number" || typeof e == "bigint" ? String(e) : e, Tr = (e) => {
583
600
  if (e == null || e instanceof Date) return e;
584
601
  if (typeof e == "string") {
585
602
  let t = new Date(e);
@@ -590,21 +607,21 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
590
607
  return isNaN(t.getTime()) ? e : t;
591
608
  }
592
609
  return e;
593
- }, cr = (e, t, n) => {
610
+ }, Er = (e, t, n) => {
594
611
  if (e == null) return e;
595
612
  switch (t) {
596
- case "boolean": return n === "postgres" ? e : ir(e);
613
+ case "boolean": return n === "postgres" ? e : Sr(e);
597
614
  case "json":
598
- case "array": return n === "postgres" ? e : ar(e);
615
+ case "array": return n === "postgres" ? e : Cr(e);
599
616
  case "timestamp":
600
- case "date": return n === "sqlite" || n === "turso" ? sr(e) : e;
617
+ case "date": return n === "sqlite" || n === "turso" ? Tr(e) : e;
601
618
  case "decimal":
602
- case "bigint": return or(e);
619
+ case "bigint": return wr(e);
603
620
  default: return e;
604
621
  }
605
- }, lr = (e, t, n) => {
622
+ }, Dr = (e, t, n) => {
606
623
  if (e.length === 0) return e;
607
- let r = E(t);
624
+ let r = S(t);
608
625
  if (r === void 0) return e;
609
626
  let i = r.fields, a = [];
610
627
  for (let [e, t] of Object.entries(i)) a.push({
@@ -613,36 +630,36 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
613
630
  });
614
631
  return e.map((e) => {
615
632
  let t = { ...e };
616
- for (let { key: e, type: r } of a) e in t && (t[e] = cr(t[e], r, n));
633
+ for (let { key: e, type: r } of a) e in t && (t[e] = Er(t[e], r, n));
617
634
  return t;
618
635
  });
619
- }, ur = (e, t) => {
636
+ }, Or = (e, t) => {
620
637
  if (e == null) return e;
621
638
  switch (t) {
622
639
  case "json":
623
640
  case "array": return typeof e == "string" ? e : JSON.stringify(e);
624
641
  default: return e;
625
642
  }
626
- }, dr = (e, t, n = ["json", "array"]) => {
627
- let r = E(t);
643
+ }, kr = (e, t, n = ["json", "array"]) => {
644
+ let r = S(t);
628
645
  if (r === void 0) return e;
629
646
  let i = r.fields, a = null;
630
647
  for (let [t, r] of Object.entries(i)) if (n.includes(r.type) && t in e) {
631
- let n = ur(e[t], r.type);
648
+ let n = Or(e[t], r.type);
632
649
  n !== e[t] && (a === null && (a = { ...e }), a[t] = n);
633
650
  }
634
651
  return a ?? e;
635
- }, fr = class extends Error {
652
+ }, Ar = class extends Error {
636
653
  _tag = "EagerCardinalityError";
637
654
  constructor(e) {
638
655
  super(e), this.name = "EagerCardinalityError";
639
656
  }
640
- }, pr = (e) => {
657
+ }, jr = (e) => {
641
658
  let { relationName: t, sourceTableName: n, targetTableName: r, foreignKey: i, sourceKey: a } = e, o = r === n;
642
659
  return `relation '${t}' on '${n}' is declared \`one\`, but ${r}.${i} matches MORE than one row for the same ${n}.${a} — so there is no single related row to return.` + (o ? ` Because this relation is self-referential, check which side the key is on: \`foreignKey: '${i}'\` means "rows whose ${i} points AT me" (my children — there can be many). If you meant "the row my ${i} points to" (my parent), that is \`sourceKey: '${i}'\`.` : " Use `many(...)` if several are expected, or narrow the key.");
643
- }, mr = async (e, t, n, r) => {
660
+ }, Mr = async (e, t, n, r) => {
644
661
  if (e.length === 0) return e;
645
- let i = Wn(n.tableName);
662
+ let i = cr(n.tableName);
646
663
  if (i === void 0) throw Error(`cannot eager-load on '${n.tableName}': no relations registered. Did you forget to declare \`relations(${n.tableName}, ...)\` or import the file that does?`);
647
664
  let a = e.map((e) => ({ ...e }));
648
665
  for (let [e, o] of Object.entries(t)) {
@@ -651,36 +668,36 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
651
668
  let t = Object.keys(i).join(", ") || "<none>";
652
669
  throw Error(`unknown relation '${e}' on '${n.tableName}'. Registered relations: ${t}.`);
653
670
  }
654
- zn(n, e, t), await hr(a, e, t, o === !0 ? {} : o, n, r);
671
+ rr(n, e, t), await Nr(a, e, t, o === !0 ? {} : o, n, r);
655
672
  }
656
673
  return a;
657
- }, hr = async (e, t, n, r, i, a) => {
674
+ }, Nr = async (e, t, n, r, i, a) => {
658
675
  switch (n.kind) {
659
676
  case "one":
660
- await gr(e, t, n, r, i, a);
677
+ await Pr(e, t, n, r, i, a);
661
678
  return;
662
679
  case "many":
663
- await _r(e, t, n, r, i, a);
680
+ await Fr(e, t, n, r, i, a);
664
681
  return;
665
682
  case "manyToMany":
666
- await yr(e, t, n, r, i, a);
683
+ await Lr(e, t, n, r, i, a);
667
684
  return;
668
685
  }
669
- }, gr = async (e, t, n, r, i, a) => {
670
- let o = n.target(), s = n.sourceKey ?? br(i, o.tableName);
686
+ }, Pr = async (e, t, n, r, i, a) => {
687
+ let o = n.target(), s = n.sourceKey ?? Rr(i, o.tableName);
671
688
  if (s !== void 0) {
672
- let n = xr(e, s), i = n.length === 0 ? [] : await Sr(o, "id", n, r, a), c = new Map(i.map((e) => [e.id, e]));
689
+ let n = zr(e, s), i = n.length === 0 ? [] : await Br(o, "id", n, r, a), c = new Map(i.map((e) => [e.id, e]));
673
690
  for (let n of e) {
674
691
  let e = n[s];
675
692
  n[t] = e == null ? null : c.get(e) ?? null;
676
693
  }
677
- await Cr(i, r.with, o, a);
694
+ await Vr(i, r.with, o, a);
678
695
  return;
679
696
  }
680
- let c = n.foreignKey ?? Fn(o, i.tableName, t), l = n.sourceKey ?? "id", u = xr(e, l), d = u.length === 0 ? [] : await Sr(o, c, u, r, a), f = /* @__PURE__ */ new Map();
697
+ let c = n.foreignKey ?? $n(o, i.tableName, t), l = n.sourceKey ?? "id", u = zr(e, l), d = u.length === 0 ? [] : await Br(o, c, u, r, a), f = /* @__PURE__ */ new Map();
681
698
  for (let e of d) {
682
699
  let n = e[c];
683
- if (f.has(n)) throw new fr(pr({
700
+ if (f.has(n)) throw new Ar(jr({
684
701
  relationName: t,
685
702
  sourceTableName: i.tableName,
686
703
  targetTableName: o.tableName,
@@ -693,9 +710,9 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
693
710
  let e = n[l];
694
711
  n[t] = e == null ? null : f.get(e) ?? null;
695
712
  }
696
- await Cr(d, r.with, o, a);
697
- }, _r = async (e, t, n, r, i, a) => {
698
- let o = n.target(), s = n.foreignKey ?? Fn(o, i.tableName, t), c = n.sourceKey ?? "id", l = xr(e, c), u = vr(r), d = l.length === 0 ? [] : await Sr(o, s, l, u, a), f = /* @__PURE__ */ new Map();
713
+ await Vr(d, r.with, o, a);
714
+ }, Fr = async (e, t, n, r, i, a) => {
715
+ let o = n.target(), s = n.foreignKey ?? $n(o, i.tableName, t), c = n.sourceKey ?? "id", l = zr(e, c), u = Ir(r), d = l.length === 0 ? [] : await Br(o, s, l, u, a), f = /* @__PURE__ */ new Map();
699
716
  for (let e of d) {
700
717
  let t = e[s], n = f.get(t);
701
718
  n ? n.push(e) : f.set(t, [e]);
@@ -711,12 +728,12 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
711
728
  let e = n[c];
712
729
  n[t] = f.get(e) ?? [];
713
730
  }
714
- await Cr(d, r.with, o, a);
715
- }, vr = (e) => {
731
+ await Vr(d, r.with, o, a);
732
+ }, Ir = (e) => {
716
733
  let { limit: t, offset: n, ...r } = e;
717
734
  return r;
718
- }, yr = async (e, t, n, r, i, a) => {
719
- let o = n.target(), s = n.through(), c = xr(e, "id");
735
+ }, Lr = async (e, t, n, r, i, a) => {
736
+ let o = n.target(), s = n.through(), c = zr(e, "id");
720
737
  if (c.length === 0) {
721
738
  for (let n of e) n[t] = [];
722
739
  return;
@@ -737,8 +754,8 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
737
754
  for (let n of e) n[t] = [];
738
755
  return;
739
756
  }
740
- let f = await Sr(o, "id", xr(d, n.targetKey), r, a), p = new Map(f.map((e) => [e.id, e]));
741
- await Cr(f, r.with, o, a);
757
+ let f = await Br(o, "id", zr(d, n.targetKey), r, a), p = new Map(f.map((e) => [e.id, e]));
758
+ await Vr(f, r.with, o, a);
742
759
  let m = r.junction === void 0 ? void 0 : r.junction === !0 ? Object.keys(s.fields) : r.junction, h = /* @__PURE__ */ new Map();
743
760
  for (let e of d) {
744
761
  let t = e[n.sourceKey], r = e[n.targetKey], i = p.get(r);
@@ -750,16 +767,16 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
750
767
  o ? o.push(a) : h.set(t, [a]);
751
768
  }
752
769
  for (let n of e) n[t] = h.get(n.id) ?? [];
753
- }, br = (e, t) => {
770
+ }, Rr = (e, t) => {
754
771
  for (let [n, r] of Object.entries(e.fields)) if (r.type === "reference" && r.references?.()?.tableName === t) return n;
755
- }, xr = (e, t) => {
772
+ }, zr = (e, t) => {
756
773
  let n = /* @__PURE__ */ new Set();
757
774
  for (let r of e) {
758
775
  let e = r[t];
759
776
  e != null && n.add(e);
760
777
  }
761
778
  return [...n];
762
- }, Sr = (e, t, n, r, i) => {
779
+ }, Br = (e, t, n, r, i) => {
763
780
  let a = {
764
781
  column: t,
765
782
  op: "in",
@@ -773,63 +790,63 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
773
790
  skip: r.offset,
774
791
  projection: void 0
775
792
  });
776
- }, Cr = async (e, t, n, r) => {
777
- t !== void 0 && e.length !== 0 && (await mr(e, t, n, r)).forEach((t, n) => {
793
+ }, Vr = async (e, t, n, r) => {
794
+ t !== void 0 && e.length !== 0 && (await Mr(e, t, n, r)).forEach((t, n) => {
778
795
  let r = e[n];
779
796
  for (let [e, n] of Object.entries(t)) e in r || (r[e] = n);
780
797
  });
781
- }, wr = (e) => e.eager !== void 0 && Object.keys(e.eager).length > 0, Tr = class extends Error {
798
+ }, Hr = (e) => e.eager !== void 0 && Object.keys(e.eager).length > 0, Ur = class extends Error {
782
799
  _tag = "TenantNamespaceUnresolved";
783
800
  constructor(e) {
784
801
  super(e), this.name = "TenantNamespaceUnresolved";
785
802
  }
786
- }, Er = class extends Error {
803
+ }, Wr = class extends Error {
787
804
  _tag = "TenantNamespaceInvalid";
788
805
  constructor(e) {
789
806
  super(e), this.name = "TenantNamespaceInvalid";
790
807
  }
791
- }, Dr = 63, Or = "tenant_", kr = (e) => e.toLowerCase().replace(/[^a-z0-9_]/g, "_"), Ar = (e) => {
792
- if (e == null || e === "") throw new Tr("namespace isolation is on but the request has no resolvable tenant (subject.tenantId is null/empty). Refusing to run against a shared/default namespace — this would be a cross-tenant read. Authenticate with a tenant-scoped subject, or disable namespace isolation for this surface.");
793
- let t = kr(e);
794
- if (t.replace(/_/g, "") === "") throw new Er(`tenant id '${e}' has no usable identifier characters after sanitisation — cannot derive a distinct namespace.`);
795
- let n = `${Or}${t}`;
796
- if (n.length > Dr) throw new Er(`namespace '${n}' for tenant '${e}' exceeds the ${Dr}-byte identifier limit. Use a shorter tenant id.`);
808
+ }, Gr = 63, Kr = "tenant_", qr = (e) => e.toLowerCase().replace(/[^a-z0-9_]/g, "_"), Jr = (e) => {
809
+ if (e == null || e === "") throw new Ur("namespace isolation is on but the request has no resolvable tenant (subject.tenantId is null/empty). Refusing to run against a shared/default namespace — this would be a cross-tenant read. Authenticate with a tenant-scoped subject, or disable namespace isolation for this surface.");
810
+ let t = qr(e);
811
+ if (t.replace(/_/g, "") === "") throw new Wr(`tenant id '${e}' has no usable identifier characters after sanitisation — cannot derive a distinct namespace.`);
812
+ let n = `${Kr}${t}`;
813
+ if (n.length > Gr) throw new Wr(`namespace '${n}' for tenant '${e}' exceeds the ${Gr}-byte identifier limit. Use a shorter tenant id.`);
797
814
  return n;
798
- }, jr = (e, t) => e === null ? t : `${e}.${t}`, Mr = /* @__PURE__ */ new Set(["timestamp", "date"]), Nr = /^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2})?/, Pr = (e, t) => {
799
- if (e === void 0 || t == null || !Mr.has(e) || t instanceof Date) return t;
815
+ }, Yr = (e, t) => e === null ? t : `${e}.${t}`, Xr = /* @__PURE__ */ new Set(["timestamp", "date"]), Zr = /^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2})?/, Qr = (e, t) => {
816
+ if (e === void 0 || t == null || !Xr.has(e) || t instanceof Date) return t;
800
817
  if (typeof t == "number" && Number.isFinite(t)) return new Date(t);
801
- if (typeof t == "string" && Nr.test(t)) {
818
+ if (typeof t == "string" && Zr.test(t)) {
802
819
  let e = new Date(t);
803
820
  return Number.isNaN(e.getTime()) ? t : e;
804
821
  }
805
822
  return t;
806
- }, Fr = (e, t) => e === void 0 || !Mr.has(e) ? t : t.map((t) => Pr(e, t)), Ir = (e, t) => {
823
+ }, $r = (e, t) => e === void 0 || !Xr.has(e) ? t : t.map((t) => Qr(e, t)), ei = (e, t) => {
807
824
  let { strings: n, values: r } = e, i = t.unsafe(n[0] ?? "");
808
825
  for (let e = 0; e < r.length; e++) i = t`${i}${r[e]}${t.unsafe(n[e + 1] ?? "")}`;
809
826
  return t`${i}`;
810
- }, Lr = (e) => e.replace(/[\\%_]/g, (e) => `\\${e}`), F = (e, t, n = null, r) => {
811
- if ("not" in e) return t`NOT (${F(e.not, t, n, r)})`;
812
- if ("and" in e) return e.and.length === 0 ? t`TRUE` : t.and(e.and.map((e) => F(e, t, n, r)));
813
- if ("or" in e) return e.or.length === 0 ? t`FALSE` : t.or(e.or.map((e) => F(e, t, n, r)));
827
+ }, ti = (e) => e.replace(/[\\%_]/g, (e) => `\\${e}`), L = (e, t, n = null, r) => {
828
+ if ("not" in e) return t`NOT (${L(e.not, t, n, r)})`;
829
+ if ("and" in e) return e.and.length === 0 ? t`TRUE` : t.and(e.and.map((e) => L(e, t, n, r)));
830
+ if ("or" in e) return e.or.length === 0 ? t`FALSE` : t.or(e.or.map((e) => L(e, t, n, r)));
814
831
  if (e.op === "subquery-in" || e.op === "subquery-not-in") {
815
- let r = e, i = I(r.subquery, t, n);
832
+ let r = e, i = fi(r.subquery, t, n);
816
833
  return r.op === "subquery-in" ? t`${t(r.column)} IN (${i})` : t`${t(r.column)} NOT IN (${i})`;
817
834
  }
818
835
  if (e.op === "exists" || e.op === "not-exists") {
819
- let r = e, i = I(r.subquery, t, n);
836
+ let r = e, i = fi(r.subquery, t, n);
820
837
  return r.op === "exists" ? t`EXISTS (${i})` : t`NOT EXISTS (${i})`;
821
838
  }
822
839
  let i = e, a = t(i.column), o = i.path, s = o !== void 0 && o.length > 0, c = () => t.onDialectOrElse({
823
- mysql: () => t.unsafe(w(i.column, o, "mysql")),
824
- mssql: () => t.unsafe(w(i.column, o, "mssql")),
825
- sqlite: () => t.unsafe(w(i.column, o, "sqlite")),
826
- orElse: () => t.unsafe(w(i.column, o, "postgres"))
840
+ mysql: () => t.unsafe(D(i.column, o, "mysql")),
841
+ mssql: () => t.unsafe(D(i.column, o, "mssql")),
842
+ sqlite: () => t.unsafe(D(i.column, o, "sqlite")),
843
+ orElse: () => t.unsafe(D(i.column, o, "postgres"))
827
844
  }), l = () => t.onDialectOrElse({
828
- mysql: () => t.unsafe(w(i.column, o, "mysql", { numeric: !0 })),
829
- mssql: () => t.unsafe(w(i.column, o, "mssql", { numeric: !0 })),
830
- sqlite: () => t.unsafe(w(i.column, o, "sqlite", { numeric: !0 })),
831
- orElse: () => t.unsafe(w(i.column, o, "postgres", { numeric: !0 }))
832
- }), u = s ? c() : a, d = s ? l() : a, f = (e) => s && e != null ? String(e) : e, p = (e) => s ? Number(e) : e, m = s || r === void 0 ? void 0 : E(r)?.fields?.[i.column]?.type, h = (e) => Pr(m, e);
845
+ mysql: () => t.unsafe(D(i.column, o, "mysql", { numeric: !0 })),
846
+ mssql: () => t.unsafe(D(i.column, o, "mssql", { numeric: !0 })),
847
+ sqlite: () => t.unsafe(D(i.column, o, "sqlite", { numeric: !0 })),
848
+ orElse: () => t.unsafe(D(i.column, o, "postgres", { numeric: !0 }))
849
+ }), u = s ? c() : a, d = s ? l() : a, f = (e) => s && e != null ? String(e) : e, p = (e) => s ? Number(e) : e, m = s || r === void 0 ? void 0 : S(r)?.fields?.[i.column]?.type, h = (e) => Qr(m, e);
833
850
  switch (i.op) {
834
851
  case "eq": return t`${u} = ${f(h(i.value))}`;
835
852
  case "neq": return t`${u} <> ${f(h(i.value))}`;
@@ -846,7 +863,7 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
846
863
  return e.length === 0 ? t`TRUE` : t`${u} NOT IN ${t.in(s ? e.map((e) => f(e)) : e)}`;
847
864
  }
848
865
  case "contains": {
849
- let e = `%${Lr(typeof i.value == "string" ? i.value : String(i.value ?? ""))}%`;
866
+ let e = `%${ti(typeof i.value == "string" ? i.value : String(i.value ?? ""))}%`;
850
867
  return t.onDialectOrElse({
851
868
  mysql: () => t`LOWER(${u}) LIKE LOWER(${e})`,
852
869
  mssql: () => t`LOWER(${u}) LIKE LOWER(${e})`,
@@ -855,7 +872,7 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
855
872
  });
856
873
  }
857
874
  case "startsWith": {
858
- let e = `${Lr(typeof i.value == "string" ? i.value : String(i.value ?? ""))}%`;
875
+ let e = `${ti(typeof i.value == "string" ? i.value : String(i.value ?? ""))}%`;
859
876
  return t.onDialectOrElse({
860
877
  mysql: () => t`${u} LIKE ${e}`,
861
878
  orElse: () => t`${u} LIKE ${e} ESCAPE '\\'`
@@ -903,13 +920,13 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
903
920
  });
904
921
  }
905
922
  }
906
- }, Rr = (e, t) => {
923
+ }, ni = (e, t) => {
907
924
  let n = [];
908
925
  return e.partitionBy && e.partitionBy.length > 0 && n.push(t`PARTITION BY ${t.csv(e.partitionBy.map((e) => t`${t(e)}`))}`), e.orderBy && e.orderBy.length > 0 && n.push(t`ORDER BY ${t.csv(e.orderBy.map((e) => e.direction === "desc" ? t`${t(e.column)} DESC` : t`${t(e.column)} ASC`))}`), n.length === 0 ? t`` : n.length === 1 ? n[0] : n.reduce((e, n, r) => r === 0 ? n : t`${e} ${n}`);
909
- }, zr = (e, t) => t.csv(e.map((e) => {
926
+ }, ri = (e, t) => t.csv(e.map((e) => {
910
927
  let n = e.column === void 0 ? t.unsafe("*") : t`${t(e.column)}`;
911
928
  if (e.op.startsWith("window-")) {
912
- let r = Rr(e.window ?? {}, t);
929
+ let r = ni(e.window ?? {}, t);
913
930
  switch (e.op) {
914
931
  case "window-row-number": return t`ROW_NUMBER() OVER (${r}) AS ${t(e.alias)}`;
915
932
  case "window-rank": return t`RANK() OVER (${r}) AS ${t(e.alias)}`;
@@ -933,44 +950,44 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
933
950
  return t`${t(e.column)} AS ${t(e.alias)}`;
934
951
  default: throw Error(`compileAggregateProjection: unknown op '${e.op}'`);
935
952
  }
936
- })), Br = (e) => `[${e.join(",")}]`, Vr = (e, t) => {
953
+ })), ii = (e) => `[${e.join(",")}]`, ai = (e, t) => {
937
954
  if (e.queryVector === void 0) return null;
938
- let n = t(e.column), r = Br(e.queryVector), i = e.distance === "cosine" ? "<=>" : e.distance === "l2" ? "<->" : "<#>", a = e.distance === "cosine" ? "VEC_DISTANCE_COSINE" : "VEC_DISTANCE_EUCLIDEAN";
955
+ let n = t(e.column), r = ii(e.queryVector), i = e.distance === "cosine" ? "<=>" : e.distance === "l2" ? "<->" : "<#>", a = e.distance === "cosine" ? "VEC_DISTANCE_COSINE" : "VEC_DISTANCE_EUCLIDEAN";
939
956
  return t.onDialectOrElse({
940
957
  mysql: () => t`${t.unsafe(a)}(${n}, ${r})`,
941
958
  mssql: () => t`NULL`,
942
959
  sqlite: () => t`NULL`,
943
960
  orElse: () => t`${n} ${t.unsafe(i)} ${r}::vector`
944
961
  });
945
- }, Hr = (e, t) => {
962
+ }, oi = (e, t) => {
946
963
  let n = t.unsafe(e.useGeography ? "::geography" : "::geometry");
947
964
  return t`ST_Distance(${t(e.column)}${n}, ${e.geom}${n})`;
948
- }, Ur = (e, t) => t`${t(e.column)} <-> ${e.geom}::geometry`, Wr = (e, t) => t`${t(`${e.indexName}_tsv`)}`, Gr = (e, t) => `${t}_${e.indexName}_fts`, Kr = (e, t, n) => {
949
- let r = n.csv(e.columns.map((e) => n`${n(e)}`)), i = `%${Lr(e.query)}%`;
965
+ }, si = (e, t) => t`${t(e.column)} <-> ${e.geom}::geometry`, ci = (e, t) => t`${t(`${e.indexName}_tsv`)}`, li = (e, t) => `${t}_${e.indexName}_fts`, ui = (e, t, n) => {
966
+ let r = n.csv(e.columns.map((e) => n`${n(e)}`)), i = `%${ti(e.query)}%`;
950
967
  return n.onDialectOrElse({
951
968
  mysql: () => n`MATCH(${r}) AGAINST(${e.query} IN NATURAL LANGUAGE MODE)`,
952
969
  sqlite: () => {
953
- let r = n(Gr(e, t));
970
+ let r = n(li(e, t));
954
971
  return n`${n("id")} IN (SELECT ${n("row_id")} FROM ${r} WHERE ${r} MATCH ${e.query})`;
955
972
  },
956
973
  mssql: () => n.or(e.columns.map((e) => n`LOWER(${n(e)}) LIKE LOWER(${i}) ESCAPE '\\'`)),
957
- orElse: () => n`${Wr(e, n)} @@ plainto_tsquery(${e.config ?? "english"}, ${e.query})`
974
+ orElse: () => n`${ci(e, n)} @@ plainto_tsquery(${e.config ?? "english"}, ${e.query})`
958
975
  });
959
- }, qr = (e, t, n) => {
960
- let r = `%${Lr(e.query)}%`;
976
+ }, di = (e, t, n) => {
977
+ let r = `%${ti(e.query)}%`;
961
978
  return n.onDialectOrElse({
962
979
  mysql: () => n`MATCH(${n.csv(e.columns.map((e) => n`${n(e)}`))}) AGAINST(${e.query} IN NATURAL LANGUAGE MODE)`,
963
980
  sqlite: () => {
964
- let r = n(Gr(e, t));
981
+ let r = n(li(e, t));
965
982
  return n`COALESCE((SELECT -bm25(${r}) FROM ${r} WHERE ${r} MATCH ${e.query} AND ${r}.${n("row_id")} = ${n("id")}), 0)`;
966
983
  },
967
984
  mssql: () => e.columns.map((e) => n`(CASE WHEN LOWER(${n(e)}) LIKE LOWER(${r}) ESCAPE '\\' THEN 1 ELSE 0 END)`).reduce((e, t, r) => r === 0 ? t : n`${e} + ${t}`),
968
- orElse: () => n`ts_rank(${Wr(e, n)}, plainto_tsquery(${e.config ?? "english"}, ${e.query}))`
985
+ orElse: () => n`ts_rank(${ci(e, n)}, plainto_tsquery(${e.config ?? "english"}, ${e.query}))`
969
986
  });
970
- }, I = (e, t, n = null) => {
987
+ }, fi = (e, t, n = null) => {
971
988
  if (e.setOp && e.setOp.queries.length >= 2) {
972
- let r = e.setOp.kind === "union" ? "UNION" : e.setOp.kind === "union-all" ? "UNION ALL" : e.setOp.kind === "intersect" ? "INTERSECT" : "EXCEPT", i = e.setOp.queries.map((e) => t`(${I(e, t, n)})`).reduce((e, n, i) => i === 0 ? n : t`${e} ${t.unsafe(r)} ${n}`), a = [];
973
- if (x(e).length > 0 && a.push(t` ORDER BY ${t.csv(x(e).map((e) => e.direction === "desc" ? t`${t(e.column)} DESC` : t`${t(e.column)} ASC`))}`), e.take !== void 0) {
989
+ let r = e.setOp.kind === "union" ? "UNION" : e.setOp.kind === "union-all" ? "UNION ALL" : e.setOp.kind === "intersect" ? "INTERSECT" : "EXCEPT", i = e.setOp.queries.map((e) => t`(${fi(e, t, n)})`).reduce((e, n, i) => i === 0 ? n : t`${e} ${t.unsafe(r)} ${n}`), a = [];
990
+ if (v(e).length > 0 && a.push(t` ORDER BY ${t.csv(v(e).map((e) => e.direction === "desc" ? t`${t(e.column)} DESC` : t`${t(e.column)} ASC`))}`), e.take !== void 0) {
974
991
  if (!Number.isInteger(e.take) || e.take < 0) throw Error(`compileSelect: invalid take ${e.take}`);
975
992
  a.push(t` LIMIT ${t.unsafe(String(e.take))}`);
976
993
  }
@@ -980,7 +997,7 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
980
997
  }
981
998
  return t`${i}${a.reduce((e, n) => t`${e}${n}`, t``)}`;
982
999
  }
983
- let r = e.annClause === void 0 ? null : Vr(e.annClause, t);
1000
+ let r = e.annClause === void 0 ? null : ai(e.annClause, t);
984
1001
  e.spatialClause !== void 0 && t.onDialectOrElse({
985
1002
  mysql: () => {
986
1003
  throw Error("@voltro/plugin-postgis: spatial distance / KNN ordering is postgres-only");
@@ -993,57 +1010,64 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
993
1010
  },
994
1011
  orElse: () => t``
995
1012
  });
996
- let i = e.spatialClause?.projectAs === void 0 ? null : Hr(e.spatialClause, t), a = e.aggregations && e.aggregations.length > 0 ? zr(e.aggregations, t) : e.joinedProjection && e.joinedProjection.length > 0 ? t.csv(e.joinedProjection.map((e) => t`${t(e.source)} AS ${t(e.outputKey)}`)) : e.projection && e.projection.length > 0 ? t.csv(e.projection.map((e) => t`${t(e)}`)) : t`*`, o = (e.aggregations && e.aggregations.length > 0) === !0, s = r !== null && !o ? t`${a}, ${r} AS ${t("distance")}` : a, c = e.fullTextSearch, l = c?.rank !== void 0 && !o ? qr(c, e.table, t) : null, u = l !== null && c?.rank !== void 0 ? t`${s}, ${l} AS ${t(c.rank.alias)}` : s, d = i !== null && !o && e.spatialClause?.projectAs !== void 0 ? t`${u}, ${i} AS ${t(e.spatialClause.projectAs)}` : u, f = e.distinctOn && e.distinctOn.length > 0 ? t.onDialectOrElse({
1013
+ let i = e.spatialClause?.projectAs === void 0 ? null : oi(e.spatialClause, t), a = e.aggregations && e.aggregations.length > 0 ? ri(e.aggregations, t) : e.joinedProjection && e.joinedProjection.length > 0 ? t.csv(e.joinedProjection.map((e) => t`${t(e.source)} AS ${t(e.outputKey)}`)) : e.projection && e.projection.length > 0 ? t.csv(e.projection.map((e) => t`${t(e)}`)) : t`*`, o = (e.aggregations && e.aggregations.length > 0) === !0, s = r !== null && !o ? t`${a}, ${r} AS ${t("distance")}` : a, c = e.fullTextSearch, l = c?.rank !== void 0 && !o ? di(c, e.table, t) : null, u = l !== null && c?.rank !== void 0 ? t`${s}, ${l} AS ${t(c.rank.alias)}` : s, d = i !== null && !o && e.spatialClause?.projectAs !== void 0 ? t`${u}, ${i} AS ${t(e.spatialClause.projectAs)}` : u, f = e.distinctOn && e.distinctOn.length > 0 ? t.onDialectOrElse({
997
1014
  orElse: () => t`DISTINCT ON (${t.csv(e.distinctOn.map((e) => t`${t(e)}`))}) `,
998
1015
  mysql: () => t`DISTINCT `,
999
1016
  mssql: () => t`DISTINCT `,
1000
1017
  sqlite: () => t`DISTINCT `
1001
- }) : e.distinct ? t`DISTINCT ` : t``, p = e.alias === void 0 ? t`${t(jr(n, e.table))}` : t`${t(jr(n, e.table))} AS ${t(e.alias)}`, m = (e.joins ?? []).map((e) => {
1018
+ }) : e.distinct ? t`DISTINCT ` : t``, p = e.lock === "update", m = p ? t.onDialectOrElse({
1019
+ mssql: () => t` WITH (UPDLOCK, ROWLOCK)`,
1020
+ orElse: () => t``
1021
+ }) : t``, h = p ? t.onDialectOrElse({
1022
+ mssql: () => t``,
1023
+ sqlite: () => t``,
1024
+ orElse: () => t` FOR UPDATE`
1025
+ }) : t``, g = e.alias === void 0 ? t`${t(Yr(n, e.table))}${m}` : t`${t(Yr(n, e.table))} AS ${t(e.alias)}${m}`, ee = (e.joins ?? []).map((e) => {
1002
1026
  let r = e.kind === "inner" ? "INNER" : "LEFT";
1003
- return t` ${t.unsafe(r)} JOIN ${t(jr(n, e.table))} AS ${t(e.alias)} ON ${F(e.on, t, n)}`;
1004
- }), h = m.length > 0 ? m.reduce((e, n) => t`${e}${n}`, p) : p, g = c === void 0 ? null : Kr(c, e.table, t), _ = [e.predicate ? F(e.predicate, t, n, e.table) : null, g].filter((e) => e !== null), ee = _.length > 0 ? t` WHERE ${t.and(_)}` : t``, te = e.groupBy && e.groupBy.length > 0 ? t` GROUP BY ${t.csv(e.groupBy.map((e) => t`${t(e)}`))}` : t``, ne = e.having ? t` HAVING ${F(e.having, t, n, e.table)}` : t``, v = e.skip !== void 0, y = [];
1005
- r !== null && y.push(t`${r} ASC`), e.spatialClause?.order !== void 0 && y.push(e.spatialClause.order === "desc" ? t`${Ur(e.spatialClause, t)} DESC` : t`${Ur(e.spatialClause, t)} ASC`), l !== null && c?.rank?.order === !0 && y.push(t`${l} DESC`);
1006
- for (let n of x(e)) y.push(n.direction === "desc" ? t`${t(n.column)} DESC` : t`${t(n.column)} ASC`);
1007
- let re = y.length > 0 ? t` ORDER BY ${t.csv(y)}` : v ? t.onDialectOrElse({
1027
+ return t` ${t.unsafe(r)} JOIN ${t(Yr(n, e.table))} AS ${t(e.alias)} ON ${L(e.on, t, n)}`;
1028
+ }), te = ee.length > 0 ? ee.reduce((e, n) => t`${e}${n}`, g) : g, ne = c === void 0 ? null : ui(c, e.table, t), re = [e.predicate ? L(e.predicate, t, n, e.table) : null, ne].filter((e) => e !== null), _ = re.length > 0 ? t` WHERE ${t.and(re)}` : t``, ie = e.groupBy && e.groupBy.length > 0 ? t` GROUP BY ${t.csv(e.groupBy.map((e) => t`${t(e)}`))}` : t``, ae = e.having ? t` HAVING ${L(e.having, t, n, e.table)}` : t``, oe = e.skip !== void 0, y = [];
1029
+ r !== null && y.push(t`${r} ASC`), e.spatialClause?.order !== void 0 && y.push(e.spatialClause.order === "desc" ? t`${si(e.spatialClause, t)} DESC` : t`${si(e.spatialClause, t)} ASC`), l !== null && c?.rank?.order === !0 && y.push(t`${l} DESC`);
1030
+ for (let n of v(e)) y.push(n.direction === "desc" ? t`${t(n.column)} DESC` : t`${t(n.column)} ASC`);
1031
+ let se = y.length > 0 ? t` ORDER BY ${t.csv(y)}` : oe ? t.onDialectOrElse({
1008
1032
  mssql: () => t` ORDER BY (SELECT NULL)`,
1009
1033
  orElse: () => t``
1010
1034
  }) : t``, b = (e) => {
1011
1035
  if (!Number.isFinite(e) || !Number.isInteger(e) || e < 0) throw Error(`compileSelect: expected non-negative integer take/skip, got ${e}`);
1012
1036
  return t.unsafe(String(e));
1013
- }, ie = (e.ctes ?? []).map((e) => t`${t(e.name)} AS (${I(e.descriptor, t, n)})`), ae = (e.ctes ?? []).some((e) => e.recursive === !0), oe = ie.length > 0 ? t`WITH ${t.unsafe(ae ? "RECURSIVE " : "")}${t.csv(ie)} ` : t``;
1037
+ }, ce = (e.ctes ?? []).map((e) => t`${t(e.name)} AS (${fi(e.descriptor, t, n)})`), le = (e.ctes ?? []).some((e) => e.recursive === !0), ue = ce.length > 0 ? t`WITH ${t.unsafe(le ? "RECURSIVE " : "")}${t.csv(ce)} ` : t``;
1014
1038
  return t.onDialectOrElse({
1015
1039
  mssql: () => {
1016
- let n = e.take !== void 0 && !v ? t`TOP ${b(e.take)} ` : t``, r = v ? t` OFFSET ${b(e.skip)} ROWS FETCH NEXT ${b(e.take ?? 2 ** 53 - 1)} ROWS ONLY` : t``;
1017
- return t`${oe}SELECT ${n}${f}${d} FROM ${h}${ee}${te}${ne}${re}${r}`;
1040
+ let n = e.take !== void 0 && !oe ? t`TOP ${b(e.take)} ` : t``, r = oe ? t` OFFSET ${b(e.skip)} ROWS FETCH NEXT ${b(e.take ?? 2 ** 53 - 1)} ROWS ONLY` : t``;
1041
+ return t`${ue}SELECT ${n}${f}${d} FROM ${te}${_}${ie}${ae}${se}${r}`;
1018
1042
  },
1019
1043
  orElse: () => {
1020
- let n = e.take === void 0 ? t`` : t` LIMIT ${b(e.take)}`, r = v ? t` OFFSET ${b(e.skip)}` : t``;
1021
- return t`${oe}SELECT ${f}${d} FROM ${h}${ee}${te}${ne}${re}${n}${r}`;
1044
+ let n = e.take === void 0 ? t`` : t` LIMIT ${b(e.take)}`, r = oe ? t` OFFSET ${b(e.skip)}` : t``;
1045
+ return t`${ue}SELECT ${f}${d} FROM ${te}${_}${ie}${ae}${se}${n}${r}${h}`;
1022
1046
  }
1023
1047
  });
1024
- }, Jr = (e, t, n) => {
1048
+ }, pi = (e, t, n) => {
1025
1049
  if (e.eager === void 0) return null;
1026
- let r = Xr(e.table, e.eager, e.sourceTable);
1050
+ let r = gi(e.table, e.eager, e.sourceTable);
1027
1051
  if (r === null) return null;
1028
- let i = ri(n, e, r, ni(t, n));
1052
+ let i = Ci(n, e, r, Si(t, n));
1029
1053
  return i === null ? null : {
1030
1054
  fragment: i,
1031
- decode: oi(r, n)
1055
+ decode: Ei(r, n)
1032
1056
  };
1033
- }, L = (e) => e.relation.kind === "one" && e.fkSide === "target", Yr = (e) => ({
1057
+ }, mi = (e) => e.relation.kind === "one" && e.fkSide === "target", hi = (e) => ({
1034
1058
  ...e,
1035
1059
  branch: {
1036
1060
  ...e.branch,
1037
1061
  limit: 2
1038
1062
  }
1039
- }), Xr = (e, t, n) => {
1040
- let r = n ?? Te(e), i = Wn(e);
1063
+ }), gi = (e, t, n) => {
1064
+ let r = n ?? Ve(e), i = cr(e);
1041
1065
  if (i === void 0) return null;
1042
1066
  let a = [];
1043
1067
  for (let [e, n] of Object.entries(t)) {
1044
1068
  let t = i[e];
1045
1069
  if (t === void 0) return null;
1046
- let o = Zr(e, t, r, n === !0 ? {} : n);
1070
+ let o = _i(e, t, r, n === !0 ? {} : n);
1047
1071
  if (o === null) return null;
1048
1072
  a.push(o);
1049
1073
  }
@@ -1051,30 +1075,30 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
1051
1075
  table: r,
1052
1076
  children: a
1053
1077
  };
1054
- }, Zr = (e, t, n, r) => {
1078
+ }, _i = (e, t, n, r) => {
1055
1079
  let i = t.target(), a = (t.kind === "manyToMany" ? void 0 : t.sourceKey) ?? "id", o, s;
1056
1080
  if (t.kind === "manyToMany") o = t.targetKey, s = "target";
1057
1081
  else if (t.kind === "one") {
1058
- let r = t.sourceKey ?? ti(n, i.tableName);
1082
+ let r = t.sourceKey ?? xi(n, i.tableName);
1059
1083
  if (r !== void 0) o = r, s = "source";
1060
1084
  else try {
1061
- o = t.foreignKey ?? Fn(i, n.tableName, e), s = "target";
1085
+ o = t.foreignKey ?? $n(i, n.tableName, e), s = "target";
1062
1086
  } catch {
1063
1087
  return null;
1064
1088
  }
1065
1089
  } else try {
1066
- o = t.foreignKey ?? Fn(i, n.tableName, e), s = "target";
1090
+ o = t.foreignKey ?? $n(i, n.tableName, e), s = "target";
1067
1091
  } catch {
1068
1092
  return null;
1069
1093
  }
1070
1094
  let c = r.with === void 0 ? [] : (() => {
1071
- let e = Wn(i.tableName);
1095
+ let e = cr(i.tableName);
1072
1096
  if (e === void 0 && Object.keys(r.with).length > 0) return null;
1073
1097
  let t = [];
1074
1098
  for (let [n, a] of Object.entries(r.with)) {
1075
1099
  let r = e?.[n];
1076
1100
  if (r === void 0) return null;
1077
- let o = Zr(n, r, i, a === !0 ? {} : a);
1101
+ let o = _i(n, r, i, a === !0 ? {} : a);
1078
1102
  if (o === null) return null;
1079
1103
  t.push(o);
1080
1104
  }
@@ -1090,9 +1114,9 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
1090
1114
  fkSide: s,
1091
1115
  branch: r,
1092
1116
  children: c,
1093
- junction: Qr(t, r)
1117
+ junction: vi(t, r)
1094
1118
  };
1095
- }, Qr = (e, t) => {
1119
+ }, vi = (e, t) => {
1096
1120
  if (e.kind !== "manyToMany" || t.junction === void 0) return;
1097
1121
  let n = e.through(), r = t.junction === !0 ? Object.keys(n.fields) : t.junction, i = r.filter((e) => e in n.fields);
1098
1122
  return {
@@ -1104,35 +1128,35 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
1104
1128
  return t !== void 0 && (t.type === "timestamp" || t.type === "date");
1105
1129
  })
1106
1130
  };
1107
- }, $r = (e) => `__j_${e}`, ei = "__j", ti = (e, t) => {
1131
+ }, yi = (e) => `__j_${e}`, bi = "__j", xi = (e, t) => {
1108
1132
  for (let [n, r] of Object.entries(e.fields)) if (r.type === "reference" && r.references?.()?.tableName === t) return n;
1109
- }, ni = (e, t) => {
1133
+ }, Si = (e, t) => {
1110
1134
  let n = 0;
1111
1135
  return {
1112
1136
  sql: e,
1113
1137
  dialect: t,
1114
1138
  nextAlias: () => `__a${n++}`
1115
1139
  };
1116
- }, ri = (e, t, n, r) => {
1140
+ }, Ci = (e, t, n, r) => {
1117
1141
  switch (e) {
1118
- case "postgres": return li(t, n, r);
1142
+ case "postgres": return ki(t, n, r);
1119
1143
  case "sqlite":
1120
- case "turso": return _i(t, n, r);
1144
+ case "turso": return Li(t, n, r);
1121
1145
  case "mysql":
1122
- case "mariadb": return Di(t, n, r);
1123
- case "mssql": return Pi(t, n, r);
1146
+ case "mariadb": return qi(t, n, r);
1147
+ case "mssql": return ea(t, n, r);
1124
1148
  }
1125
- }, ii = (e, t) => t === "mssql" && !ai.test(e) ? /* @__PURE__ */ new Date(`${e}Z`) : new Date(e), ai = /(?:Z|[+-]\d{2}:?\d{2})$/, oi = (e, t) => {
1126
- let n = si(e.table, e.children, t);
1149
+ }, wi = (e, t) => t === "mssql" && !Ti.test(e) ? /* @__PURE__ */ new Date(`${e}Z`) : new Date(e), Ti = /(?:Z|[+-]\d{2}:?\d{2})$/, Ei = (e, t) => {
1150
+ let n = Di(e.table, e.children, t);
1127
1151
  return (e) => e.map((e) => {
1128
1152
  let t = e.__row, r = typeof t == "string" ? JSON.parse(t) : t;
1129
1153
  return n(r);
1130
1154
  });
1131
- }, si = (e, t, n) => {
1155
+ }, Di = (e, t, n) => {
1132
1156
  let r = [];
1133
1157
  for (let [t, n] of Object.entries(e.fields)) (n.type === "timestamp" || n.type === "date") && r.push(t);
1134
1158
  let i = t.map((e) => {
1135
- let t = si(e.target, e.children, n), r = e.relation.kind === "one", i = L(e), a = i ? pr({
1159
+ let t = Di(e.target, e.children, n), r = e.relation.kind === "one", i = mi(e), a = i ? jr({
1136
1160
  relationName: e.relationName,
1137
1161
  sourceTableName: e.source.tableName,
1138
1162
  targetTableName: e.target.tableName,
@@ -1145,14 +1169,14 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
1145
1169
  isSingle: r,
1146
1170
  fromOverFetch: i,
1147
1171
  cardinalityMessage: a,
1148
- junction: ci(e.junction, n)
1172
+ junction: Oi(e.junction, n)
1149
1173
  };
1150
1174
  });
1151
1175
  return (e) => {
1152
1176
  let t = { ...e };
1153
1177
  for (let e of r) {
1154
1178
  let r = t[e];
1155
- typeof r == "string" && (t[e] = ii(r, n));
1179
+ typeof r == "string" && (t[e] = wi(r, n));
1156
1180
  }
1157
1181
  for (let e of i) {
1158
1182
  let n = t[e.name];
@@ -1162,7 +1186,7 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
1162
1186
  }
1163
1187
  if (e.fromOverFetch) {
1164
1188
  let r = n;
1165
- if (r.length > 1) throw new fr(e.cardinalityMessage);
1189
+ if (r.length > 1) throw new Ar(e.cardinalityMessage);
1166
1190
  t[e.name] = r.length === 0 ? null : e.decode(r[0]);
1167
1191
  continue;
1168
1192
  }
@@ -1174,202 +1198,202 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
1174
1198
  }
1175
1199
  return t;
1176
1200
  };
1177
- }, ci = (e, t) => {
1201
+ }, Oi = (e, t) => {
1178
1202
  if (e === void 0) return;
1179
1203
  let n = new Set(e.dateColumns), r = e.requested;
1180
1204
  return (e) => {
1181
1205
  let i = e._junction ?? {}, a = {};
1182
1206
  for (let e of r) {
1183
1207
  let r = i[e];
1184
- a[e] = n.has(e) && typeof r == "string" ? ii(r, t) : r;
1208
+ a[e] = n.has(e) && typeof r == "string" ? wi(r, t) : r;
1185
1209
  }
1186
1210
  return {
1187
1211
  ...e,
1188
1212
  _junction: a
1189
1213
  };
1190
1214
  };
1191
- }, li = (e, t, n) => {
1192
- let r = n.sql, i = n.nextAlias(), a = r(t.table.tableName), o = r(i), s = ui(i, t.children, n);
1193
- return s === null ? null : r`SELECT ${s} AS "__row" FROM ${a} AS ${o}${e.predicate ? r` WHERE ${U(e.predicate, i, r)}` : r``}${x(e).length > 0 ? r` ORDER BY ${r.csv(x(e).map((e) => e.direction === "desc" ? r`${B(i, e.column, r)} DESC` : r`${B(i, e.column, r)} ASC`))}` : r``}${e.take === void 0 ? r`` : r` LIMIT ${H(e.take, r)}`}${e.skip === void 0 ? r`` : r` OFFSET ${H(e.skip, r)}`}`;
1194
- }, ui = (e, t, n, r) => {
1195
- let i = n.sql, a = r === void 0 ? i`to_jsonb(${i(e)}.*)` : i`(to_jsonb(${i(e)}.*) - ${V(ei, i)}::text)`;
1215
+ }, ki = (e, t, n) => {
1216
+ let r = n.sql, i = n.nextAlias(), a = r(t.table.tableName), o = r(i), s = Ai(i, t.children, n);
1217
+ return s === null ? null : r`SELECT ${s} AS "__row" FROM ${a} AS ${o}${e.predicate ? r` WHERE ${U(e.predicate, i, r)}` : r``}${v(e).length > 0 ? r` ORDER BY ${r.csv(v(e).map((e) => e.direction === "desc" ? r`${B(i, e.column, r)} DESC` : r`${B(i, e.column, r)} ASC`))}` : r``}${e.take === void 0 ? r`` : r` LIMIT ${H(e.take, r)}`}${e.skip === void 0 ? r`` : r` OFFSET ${H(e.skip, r)}`}`;
1218
+ }, Ai = (e, t, n, r) => {
1219
+ let i = n.sql, a = r === void 0 ? i`to_jsonb(${i(e)}.*)` : i`(to_jsonb(${i(e)}.*) - ${V(bi, i)}::text)`;
1196
1220
  if (t.length === 0 && r === void 0) return a;
1197
1221
  let o = [];
1198
- r !== void 0 && o.push(i`${V("_junction", i)}, ${B(e, ei, i)}`);
1222
+ r !== void 0 && o.push(i`${V("_junction", i)}, ${B(e, bi, i)}`);
1199
1223
  for (let r of t) {
1200
- let t = di(r, e, n);
1224
+ let t = ji(r, e, n);
1201
1225
  if (t === null) return null;
1202
1226
  o.push(i`${V(r.relationName, i)}, ${t}`);
1203
1227
  }
1204
1228
  return i`${a} || jsonb_build_object(${i.csv(o)})`;
1205
- }, di = (e, t, n) => {
1229
+ }, ji = (e, t, n) => {
1206
1230
  switch (e.relation.kind) {
1207
- case "one": return L(e) ? pi(Yr(e), t, n) : fi(e, t, n);
1208
- case "many": return pi(e, t, n);
1209
- case "manyToMany": return mi(e, t, n);
1231
+ case "one": return mi(e) ? Ni(hi(e), t, n) : Mi(e, t, n);
1232
+ case "many": return Ni(e, t, n);
1233
+ case "manyToMany": return Pi(e, t, n);
1210
1234
  }
1211
- }, fi = (e, t, n) => {
1212
- let r = n.sql, i = n.nextAlias(), a = ui(i, e.children, n);
1235
+ }, Mi = (e, t, n) => {
1236
+ let r = n.sql, i = n.nextAlias(), a = Ai(i, e.children, n);
1213
1237
  if (a === null) return null;
1214
1238
  let o = e.fkSide === "source" ? r`${B(i, "id", r)} = ${B(t, e.foreignKey, r)}` : r`${B(i, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${U(e.branch.where, i, r)}`, c = R(i, e.branch.orderBy, r);
1215
1239
  return r`(SELECT ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o}${s}${c} LIMIT 1)`;
1216
- }, pi = (e, t, n) => {
1217
- let r = n.sql, i = n.nextAlias(), a = ui(i, e.children, n);
1240
+ }, Ni = (e, t, n) => {
1241
+ let r = n.sql, i = n.nextAlias(), a = Ai(i, e.children, n);
1218
1242
  if (a === null) return null;
1219
- let o = r`${B(void 0, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${F(e.branch.where, r)}`, c = gi(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`;
1243
+ let o = r`${B(void 0, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${L(e.branch.where, r)}`, c = Ii(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`;
1220
1244
  return r`COALESCE((SELECT jsonb_agg(${a}) FROM (SELECT * FROM ${r(e.target.tableName)} WHERE ${o}${s}${c}${l}${u}) AS ${r(i)}), '[]'::jsonb)`;
1221
- }, mi = (e, t, n) => {
1222
- let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = ui(o, e.children, n, e.junction);
1245
+ }, Pi = (e, t, n) => {
1246
+ let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = Ai(o, e.children, n, e.junction);
1223
1247
  if (c === null) return null;
1224
- let l = e.branch.where === void 0 ? r`` : r` AND ${F(e.branch.where, r)}`, u = Hi(e, s, r), d = R(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : r`, ${hi(e.junction, s, r)} AS ${r(ei)}`;
1248
+ let l = e.branch.where === void 0 ? r`` : r` AND ${L(e.branch.where, r)}`, u = ca(e, s, r), d = R(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : r`, ${Fi(e.junction, s, r)} AS ${r(bi)}`;
1225
1249
  return r`COALESCE((SELECT jsonb_agg(${c}) FROM (SELECT ${r(o)}.*${m} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${B(o, "id", r)} = ${B(s, i.targetKey, r)} WHERE ${B(s, i.sourceKey, r)} = ${B(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), '[]'::jsonb)`;
1226
- }, hi = (e, t, n) => e.present.length === 0 ? n`jsonb_build_object()` : n`jsonb_build_object(${n.csv(e.present.map((e) => n`${V(e, n)}, ${B(t, e, n)}`))})`, R = (e, t, n) => t === void 0 || t.length === 0 ? n`` : n` ORDER BY ${n.csv(t.map((t) => t.direction === "desc" ? n`${B(e, t.column, n)} DESC` : n`${B(e, t.column, n)} ASC`))}`, gi = (e, t) => e === void 0 || e.length === 0 ? t`` : t` ORDER BY ${t.csv(e.map((e) => e.direction === "desc" ? t`${t(e.column)} DESC` : t`${t(e.column)} ASC`))}`, _i = (e, t, n) => {
1227
- let r = n.sql, i = n.nextAlias(), a = vi(i, t.table, t.children, n);
1250
+ }, Fi = (e, t, n) => e.present.length === 0 ? n`jsonb_build_object()` : n`jsonb_build_object(${n.csv(e.present.map((e) => n`${V(e, n)}, ${B(t, e, n)}`))})`, R = (e, t, n) => t === void 0 || t.length === 0 ? n`` : n` ORDER BY ${n.csv(t.map((t) => t.direction === "desc" ? n`${B(e, t.column, n)} DESC` : n`${B(e, t.column, n)} ASC`))}`, Ii = (e, t) => e === void 0 || e.length === 0 ? t`` : t` ORDER BY ${t.csv(e.map((e) => e.direction === "desc" ? t`${t(e.column)} DESC` : t`${t(e.column)} ASC`))}`, Li = (e, t, n) => {
1251
+ let r = n.sql, i = n.nextAlias(), a = Ri(i, t.table, t.children, n);
1228
1252
  if (a === null) return null;
1229
- let o = e.predicate ? r` WHERE ${U(e.predicate, i, r)}` : r``, s = x(e).length > 0 ? r` ORDER BY ${r.csv(x(e).map((e) => e.direction === "desc" ? r`${B(i, e.column, r)} DESC` : r`${B(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${H(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${H(e.skip, r)}`;
1253
+ let o = e.predicate ? r` WHERE ${U(e.predicate, i, r)}` : r``, s = v(e).length > 0 ? r` ORDER BY ${r.csv(v(e).map((e) => e.direction === "desc" ? r`${B(i, e.column, r)} DESC` : r`${B(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${H(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${H(e.skip, r)}`;
1230
1254
  return r`SELECT ${a} AS "__row" FROM ${r(t.table.tableName)} AS ${r(i)}${o}${s}${c}${l}`;
1231
- }, vi = (e, t, n, r, i) => {
1255
+ }, Ri = (e, t, n, r, i) => {
1232
1256
  let a = r.sql, o = [];
1233
1257
  for (let n of Object.keys(t.fields)) o.push(a`${V(n, a)}, ${B(e, n, a)}`);
1234
1258
  if (i !== void 0) {
1235
- let e = yi(i.projection, i.source, a);
1259
+ let e = zi(i.projection, i.source, a);
1236
1260
  o.push(a`${V("_junction", a)}, json_object(${e})`);
1237
1261
  }
1238
1262
  for (let t of n) {
1239
- let n = Ci(t, e, r);
1263
+ let n = Ui(t, e, r);
1240
1264
  if (n === null) return null;
1241
1265
  o.push(a`${V(t.relationName, a)}, ${n}`);
1242
1266
  }
1243
1267
  return a`json_object(${a.csv(o)})`;
1244
- }, yi = (e, t, n) => e.present.length === 0 ? n`` : n.csv(e.present.map((e) => n`${V(e, n)}, ${B(t.alias, t.physical(e), n)}`)), bi = (e, t, n) => e.present.length === 0 ? n`` : n`, ${n.csv(e.present.map((e) => n`${B(t, e, n)} AS ${n($r(e))}`))}`, xi = (e) => ({
1268
+ }, zi = (e, t, n) => e.present.length === 0 ? n`` : n.csv(e.present.map((e) => n`${V(e, n)}, ${B(t.alias, t.physical(e), n)}`)), Bi = (e, t, n) => e.present.length === 0 ? n`` : n`, ${n.csv(e.present.map((e) => n`${B(t, e, n)} AS ${n(yi(e))}`))}`, Vi = (e) => ({
1245
1269
  alias: e,
1246
- physical: $r
1247
- }), Si = (e) => ({
1270
+ physical: yi
1271
+ }), Hi = (e) => ({
1248
1272
  alias: e,
1249
1273
  physical: (e) => e
1250
- }), Ci = (e, t, n) => {
1274
+ }), Ui = (e, t, n) => {
1251
1275
  switch (e.relation.kind) {
1252
- case "one": return L(e) ? Ti(Yr(e), t, n) : wi(e, t, n);
1253
- case "many": return Ti(e, t, n);
1254
- case "manyToMany": return Ei(e, t, n);
1276
+ case "one": return mi(e) ? Gi(hi(e), t, n) : Wi(e, t, n);
1277
+ case "many": return Gi(e, t, n);
1278
+ case "manyToMany": return Ki(e, t, n);
1255
1279
  }
1256
- }, wi = (e, t, n) => {
1257
- let r = n.sql, i = n.nextAlias(), a = vi(i, e.target, e.children, n);
1280
+ }, Wi = (e, t, n) => {
1281
+ let r = n.sql, i = n.nextAlias(), a = Ri(i, e.target, e.children, n);
1258
1282
  if (a === null) return null;
1259
1283
  let o = e.fkSide === "source" ? r`${B(i, "id", r)} = ${B(t, e.foreignKey, r)}` : r`${B(i, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`;
1260
1284
  return r`(SELECT ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o} LIMIT 1)`;
1261
- }, Ti = (e, t, n) => {
1262
- let r = n.sql, i = n.nextAlias(), a = vi(i, e.target, e.children, n);
1285
+ }, Gi = (e, t, n) => {
1286
+ let r = n.sql, i = n.nextAlias(), a = Ri(i, e.target, e.children, n);
1263
1287
  if (a === null) return null;
1264
- let o = r`${B(void 0, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${F(W(e.branch.where), r)}`, c = gi(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`;
1288
+ let o = r`${B(void 0, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${L(W(e.branch.where), r)}`, c = Ii(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`;
1265
1289
  return r`COALESCE((SELECT json_group_array(${a}) FROM (SELECT * FROM ${r(e.target.tableName)} WHERE ${o}${s}${c}${l}${u}) AS ${r(i)}), json('[]'))`;
1266
- }, Ei = (e, t, n) => {
1267
- let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = vi(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1290
+ }, Ki = (e, t, n) => {
1291
+ let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = Ri(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1268
1292
  projection: e.junction,
1269
- source: xi(o)
1293
+ source: Vi(o)
1270
1294
  });
1271
1295
  if (c === null) return null;
1272
- let l = e.branch.where === void 0 ? r`` : r` AND ${F(W(e.branch.where), r)}`, u = Hi(e, s, r, !0), d = R(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : bi(e.junction, s, r);
1296
+ let l = e.branch.where === void 0 ? r`` : r` AND ${L(W(e.branch.where), r)}`, u = ca(e, s, r, !0), d = R(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : Bi(e.junction, s, r);
1273
1297
  return r`COALESCE((SELECT json_group_array(${c}) FROM (SELECT ${r(o)}.*${m} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${B(o, "id", r)} = ${B(s, i.targetKey, r)} WHERE ${B(s, i.sourceKey, r)} = ${B(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), json('[]'))`;
1274
- }, Di = (e, t, n) => {
1298
+ }, qi = (e, t, n) => {
1275
1299
  let r = n.sql, i = n.nextAlias(), a = z(i, t.table, t.children, n);
1276
1300
  if (a === null) return null;
1277
- let o = e.predicate ? r` WHERE ${U(e.predicate, i, r)}` : r``, s = x(e).length > 0 ? r` ORDER BY ${r.csv(x(e).map((e) => e.direction === "desc" ? r`${B(i, e.column, r)} DESC` : r`${B(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${H(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${H(e.skip, r)}`;
1301
+ let o = e.predicate ? r` WHERE ${U(e.predicate, i, r)}` : r``, s = v(e).length > 0 ? r` ORDER BY ${r.csv(v(e).map((e) => e.direction === "desc" ? r`${B(i, e.column, r)} DESC` : r`${B(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${H(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${H(e.skip, r)}`;
1278
1302
  return r`SELECT ${a} AS \`__row\` FROM ${r(t.table.tableName)} AS ${r(i)}${o}${s}${c}${l}`;
1279
1303
  }, z = (e, t, n, r, i) => {
1280
1304
  let a = r.sql, o = [];
1281
1305
  for (let n of Object.keys(t.fields)) o.push(a`${V(n, a)}, ${B(e, n, a)}`);
1282
1306
  if (i !== void 0) {
1283
- let e = yi(i.projection, i.source, a);
1307
+ let e = zi(i.projection, i.source, a);
1284
1308
  o.push(a`${V("_junction", a)}, JSON_OBJECT(${e})`);
1285
1309
  }
1286
1310
  for (let t of n) {
1287
- let n = Oi(t, e, r);
1311
+ let n = Ji(t, e, r);
1288
1312
  if (n === null) return null;
1289
1313
  o.push(a`${V(t.relationName, a)}, ${n}`);
1290
1314
  }
1291
1315
  return a`JSON_OBJECT(${a.csv(o)})`;
1292
- }, Oi = (e, t, n) => {
1316
+ }, Ji = (e, t, n) => {
1293
1317
  switch (e.relation.kind) {
1294
1318
  case "one":
1295
- if (L(e)) {
1296
- let r = Yr(e);
1297
- return n.dialect === "mariadb" ? Mi(r, t, n) : Ai(r, t, n);
1319
+ if (mi(e)) {
1320
+ let r = hi(e);
1321
+ return n.dialect === "mariadb" ? Qi(r, t, n) : Xi(r, t, n);
1298
1322
  }
1299
- return ki(e, t, n);
1300
- case "many": return n.dialect === "mariadb" ? Mi(e, t, n) : Ai(e, t, n);
1301
- case "manyToMany": return n.dialect === "mariadb" ? Ni(e, t, n) : ji(e, t, n);
1323
+ return Yi(e, t, n);
1324
+ case "many": return n.dialect === "mariadb" ? Qi(e, t, n) : Xi(e, t, n);
1325
+ case "manyToMany": return n.dialect === "mariadb" ? $i(e, t, n) : Zi(e, t, n);
1302
1326
  }
1303
- }, ki = (e, t, n) => {
1327
+ }, Yi = (e, t, n) => {
1304
1328
  let r = n.sql, i = n.nextAlias(), a = z(i, e.target, e.children, n);
1305
1329
  if (a === null) return null;
1306
1330
  let o = e.fkSide === "source" ? r`${B(i, "id", r)} = ${B(t, e.foreignKey, r)}` : r`${B(i, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`;
1307
1331
  return r`(SELECT ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o} LIMIT 1)`;
1308
- }, Ai = (e, t, n) => {
1332
+ }, Xi = (e, t, n) => {
1309
1333
  let r = n.sql, i = n.nextAlias(), a = z(i, e.target, e.children, n);
1310
1334
  if (a === null) return null;
1311
- let o = r`${B(void 0, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${F(W(e.branch.where), r)}`, c = gi(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`;
1335
+ let o = r`${B(void 0, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${L(W(e.branch.where), r)}`, c = Ii(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`;
1312
1336
  return r`COALESCE((SELECT JSON_ARRAYAGG(${a}) FROM (SELECT * FROM ${r(e.target.tableName)} WHERE ${o}${s}${c}${l}${u}) AS ${r(i)}), JSON_ARRAY())`;
1313
- }, ji = (e, t, n) => {
1337
+ }, Zi = (e, t, n) => {
1314
1338
  let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = z(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1315
1339
  projection: e.junction,
1316
- source: xi(o)
1340
+ source: Vi(o)
1317
1341
  });
1318
1342
  if (c === null) return null;
1319
- let l = e.branch.where === void 0 ? r`` : r` AND ${F(W(e.branch.where), r)}`, u = Hi(e, s, r, !0), d = R(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : bi(e.junction, s, r);
1343
+ let l = e.branch.where === void 0 ? r`` : r` AND ${L(W(e.branch.where), r)}`, u = ca(e, s, r, !0), d = R(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : Bi(e.junction, s, r);
1320
1344
  return r`COALESCE((SELECT JSON_ARRAYAGG(${c}) FROM (SELECT ${r(o)}.*${m} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${B(o, "id", r)} = ${B(s, i.targetKey, r)} WHERE ${B(s, i.sourceKey, r)} = ${B(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), JSON_ARRAY())`;
1321
- }, Mi = (e, t, n) => {
1345
+ }, Qi = (e, t, n) => {
1322
1346
  let r = n.sql, i = n.nextAlias(), a = z(i, e.target, e.children, n);
1323
1347
  if (a === null) return null;
1324
- let o = r`${B(i, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${F(W(e.branch.where), r)}`, c = e.branch.orderBy ?? [];
1348
+ let o = r`${B(i, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${L(W(e.branch.where), r)}`, c = e.branch.orderBy ?? [];
1325
1349
  if (e.branch.limit === void 0 && e.branch.offset === void 0) return r`COALESCE((SELECT JSON_ARRAYAGG(${a}${c.length > 0 ? r` ORDER BY ${r.csv(c.map((e) => e.direction === "desc" ? r`${B(i, e.column, r)} DESC` : r`${B(i, e.column, r)} ASC`))}` : r``}) FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o}${s}), JSON_ARRAY())`;
1326
1350
  let l = c.length > 0 ? r` ORDER BY ${r.csv(c.map((e) => e.direction === "desc" ? r`${r(e.column)} DESC` : r`${r(e.column)} ASC`))}` : r` ORDER BY ${r("id")}`, u = e.branch.limit, d = e.branch.offset, f = u !== void 0 && d !== void 0 ? r` AND ${B(i, "rn", r)} > ${H(d, r)} AND ${B(i, "rn", r)} <= ${H(d + u, r)}` : u === void 0 ? r` AND ${B(i, "rn", r)} > ${H(d, r)}` : r` AND ${B(i, "rn", r)} <= ${H(u, r)}`;
1327
1351
  return r`COALESCE((SELECT JSON_ARRAYAGG(${a} ORDER BY ${B(i, "rn", r)}) FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY ${r(e.foreignKey)}${l}) AS rn FROM ${r(e.target.tableName)}) AS ${r(i)} WHERE ${o}${s}${f}), JSON_ARRAY())`;
1328
- }, Ni = (e, t, n) => {
1352
+ }, $i = (e, t, n) => {
1329
1353
  let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = (t) => e.junction === void 0 ? void 0 : {
1330
1354
  projection: e.junction,
1331
1355
  source: t
1332
- }, l = r`${B(s, i.sourceKey, r)} = ${B(t, "id", r)}`, u = r`${B(o, "id", r)} = ${B(s, i.targetKey, r)}`, d = e.branch.where === void 0 ? r`` : r` AND ${F(W(e.branch.where), r)}`, f = Hi(e, s, r, !0), p = e.branch.orderBy ?? [];
1356
+ }, l = r`${B(s, i.sourceKey, r)} = ${B(t, "id", r)}`, u = r`${B(o, "id", r)} = ${B(s, i.targetKey, r)}`, d = e.branch.where === void 0 ? r`` : r` AND ${L(W(e.branch.where), r)}`, f = ca(e, s, r, !0), p = e.branch.orderBy ?? [];
1333
1357
  if (e.branch.limit === void 0 && e.branch.offset === void 0) {
1334
- let t = z(o, e.target, e.children, n, c(Si(s)));
1358
+ let t = z(o, e.target, e.children, n, c(Hi(s)));
1335
1359
  return t === null ? null : r`COALESCE((SELECT JSON_ARRAYAGG(${t}${p.length > 0 ? r` ORDER BY ${r.csv(p.map((e) => e.direction === "desc" ? r`${B(o, e.column, r)} DESC` : r`${B(o, e.column, r)} ASC`))}` : r``}) FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${u} WHERE ${l}${f}${d}), JSON_ARRAY())`;
1336
1360
  }
1337
- let m = p.length > 0 ? r` ORDER BY ${r.csv(p.map((e) => e.direction === "desc" ? r`${B(o, e.column, r)} DESC` : r`${B(o, e.column, r)} ASC`))}` : r` ORDER BY ${B(o, "id", r)}`, h = e.branch.limit, g = e.branch.offset, _ = h !== void 0 && g !== void 0 ? r` AND ${B(o, "rn", r)} > ${H(g, r)} AND ${B(o, "rn", r)} <= ${H(g + h, r)}` : h === void 0 ? r` AND ${B(o, "rn", r)} > ${H(g, r)}` : r` AND ${B(o, "rn", r)} <= ${H(h, r)}`, ee = e.branch.onJunction === void 0 ? r`` : r` WHERE ${U(W(e.branch.onJunction), s, r)}`, te = z(o, e.target, e.children, n, c(xi(o)));
1338
- if (te === null) return null;
1339
- let ne = e.junction === void 0 ? r`` : bi(e.junction, s, r);
1340
- return r`COALESCE((SELECT JSON_ARRAYAGG(${te} ORDER BY ${B(o, "rn", r)}) FROM (SELECT ${r(o)}.*${ne}, ${B(s, i.sourceKey, r)} AS ${r(`__src_${i.sourceKey}`)}, ROW_NUMBER() OVER (PARTITION BY ${B(s, i.sourceKey, r)}${m}) AS rn FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${u}${ee}) AS ${r(o)} WHERE ${B(o, `__src_${i.sourceKey}`, r)} = ${B(t, "id", r)}${d}${_}), JSON_ARRAY())`;
1341
- }, Pi = (e, t, n) => {
1342
- let r = n.sql, i = n.nextAlias(), a = Fi(i, t.table, t.children, n);
1361
+ let m = p.length > 0 ? r` ORDER BY ${r.csv(p.map((e) => e.direction === "desc" ? r`${B(o, e.column, r)} DESC` : r`${B(o, e.column, r)} ASC`))}` : r` ORDER BY ${B(o, "id", r)}`, h = e.branch.limit, g = e.branch.offset, ee = h !== void 0 && g !== void 0 ? r` AND ${B(o, "rn", r)} > ${H(g, r)} AND ${B(o, "rn", r)} <= ${H(g + h, r)}` : h === void 0 ? r` AND ${B(o, "rn", r)} > ${H(g, r)}` : r` AND ${B(o, "rn", r)} <= ${H(h, r)}`, te = e.branch.onJunction === void 0 ? r`` : r` WHERE ${U(W(e.branch.onJunction), s, r)}`, ne = z(o, e.target, e.children, n, c(Vi(o)));
1362
+ if (ne === null) return null;
1363
+ let re = e.junction === void 0 ? r`` : Bi(e.junction, s, r);
1364
+ return r`COALESCE((SELECT JSON_ARRAYAGG(${ne} ORDER BY ${B(o, "rn", r)}) FROM (SELECT ${r(o)}.*${re}, ${B(s, i.sourceKey, r)} AS ${r(`__src_${i.sourceKey}`)}, ROW_NUMBER() OVER (PARTITION BY ${B(s, i.sourceKey, r)}${m}) AS rn FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${u}${te}) AS ${r(o)} WHERE ${B(o, `__src_${i.sourceKey}`, r)} = ${B(t, "id", r)}${d}${ee}), JSON_ARRAY())`;
1365
+ }, ea = (e, t, n) => {
1366
+ let r = n.sql, i = n.nextAlias(), a = ta(i, t.table, t.children, n);
1343
1367
  if (a === null) return null;
1344
- let o = e.predicate ? r` WHERE ${U(e.predicate, i, r)}` : r``, s = x(e).length > 0 ? r` ORDER BY ${r.csv(x(e).map((e) => e.direction === "desc" ? r`${B(i, e.column, r)} DESC` : r`${B(i, e.column, r)} ASC`))}` : r``, c = r``, l = r``;
1368
+ let o = e.predicate ? r` WHERE ${U(e.predicate, i, r)}` : r``, s = v(e).length > 0 ? r` ORDER BY ${r.csv(v(e).map((e) => e.direction === "desc" ? r`${B(i, e.column, r)} DESC` : r`${B(i, e.column, r)} ASC`))}` : r``, c = r``, l = r``;
1345
1369
  if (e.skip !== void 0) {
1346
- let t = x(e).length > 0 ? s : r` ORDER BY (SELECT NULL)`;
1370
+ let t = v(e).length > 0 ? s : r` ORDER BY (SELECT NULL)`;
1347
1371
  l = e.take === void 0 ? r`${t} OFFSET ${H(e.skip, r)} ROWS` : r`${t} OFFSET ${H(e.skip, r)} ROWS FETCH NEXT ${H(e.take, r)} ROWS ONLY`;
1348
1372
  } else e.take !== void 0 && (c = r`TOP ${H(e.take, r)} `);
1349
1373
  let u = e.skip === void 0 ? s : r``;
1350
1374
  return r`SELECT ${c}(SELECT ${a} FOR JSON PATH, INCLUDE_NULL_VALUES, WITHOUT_ARRAY_WRAPPER) AS ${r("__row")} FROM ${r(t.table.tableName)} AS ${r(i)}${o}${u}${l}`;
1351
- }, Fi = (e, t, n, r, i) => {
1375
+ }, ta = (e, t, n, r, i) => {
1352
1376
  let a = r.sql, o = [];
1353
1377
  for (let n of Object.keys(t.fields)) o.push(a`${B(e, n, a)} AS ${a(n)}`);
1354
- if (i !== void 0) for (let e of i.projection.present) o.push(a`${B(i.source.alias, i.source.physical(e), a)} AS ${Ii(`_junction.${e}`, a)}`);
1378
+ if (i !== void 0) for (let e of i.projection.present) o.push(a`${B(i.source.alias, i.source.physical(e), a)} AS ${na(`_junction.${e}`, a)}`);
1355
1379
  for (let t of n) {
1356
- let n = Li(t, e, r);
1380
+ let n = ra(t, e, r);
1357
1381
  if (n === null) return null;
1358
1382
  o.push(n);
1359
1383
  }
1360
1384
  return a.csv(o);
1361
- }, Ii = (e, t) => t.unsafe(`[${e.replace(/]/g, "]]")}]`), Li = (e, t, n) => {
1385
+ }, na = (e, t) => t.unsafe(`[${e.replace(/]/g, "]]")}]`), ra = (e, t, n) => {
1362
1386
  switch (e.relation.kind) {
1363
- case "one": return L(e) ? Bi(Yr(e), t, n) : Ri(e, t, n);
1364
- case "many": return Bi(e, t, n);
1365
- case "manyToMany": return Vi(e, t, n);
1387
+ case "one": return mi(e) ? oa(hi(e), t, n) : ia(e, t, n);
1388
+ case "many": return oa(e, t, n);
1389
+ case "manyToMany": return sa(e, t, n);
1366
1390
  }
1367
- }, Ri = (e, t, n) => {
1368
- let r = n.sql, i = n.nextAlias(), a = Fi(i, e.target, e.children, n);
1391
+ }, ia = (e, t, n) => {
1392
+ let r = n.sql, i = n.nextAlias(), a = ta(i, e.target, e.children, n);
1369
1393
  if (a === null) return null;
1370
1394
  let o = e.fkSide === "source" ? r`${B(i, "id", r)} = ${B(t, e.foreignKey, r)}` : r`${B(i, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`;
1371
1395
  return r`JSON_QUERY((SELECT TOP 1 ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o} FOR JSON PATH, INCLUDE_NULL_VALUES, WITHOUT_ARRAY_WRAPPER)) AS ${r(e.relationName)}`;
1372
- }, zi = (e, t, n) => {
1396
+ }, aa = (e, t, n) => {
1373
1397
  if (e.offset !== void 0) {
1374
1398
  let r = e.orderBy && e.orderBy.length > 0 ? t : n` ORDER BY (SELECT NULL)`, i = e.limit === void 0 ? n`${r} OFFSET ${H(e.offset, n)} ROWS` : n`${r} OFFSET ${H(e.offset, n)} ROWS FETCH NEXT ${H(e.limit, n)} ROWS ONLY`;
1375
1399
  return {
@@ -1383,29 +1407,29 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
1383
1407
  pagination: n``,
1384
1408
  finalOrder: t
1385
1409
  };
1386
- }, Bi = (e, t, n) => {
1387
- let r = n.sql, i = n.nextAlias(), a = Fi(i, e.target, e.children, n);
1410
+ }, oa = (e, t, n) => {
1411
+ let r = n.sql, i = n.nextAlias(), a = ta(i, e.target, e.children, n);
1388
1412
  if (a === null) return null;
1389
- let o = e.branch.where === void 0 ? r`` : r` AND ${U(e.branch.where, i, r)}`, s = R(i, e.branch.orderBy, r), { top: c, pagination: l, finalOrder: u } = zi(e.branch, s, r);
1413
+ let o = e.branch.where === void 0 ? r`` : r` AND ${U(e.branch.where, i, r)}`, s = R(i, e.branch.orderBy, r), { top: c, pagination: l, finalOrder: u } = aa(e.branch, s, r);
1390
1414
  return r`ISNULL(JSON_QUERY((SELECT ${c}${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${B(i, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}${o}${u}${l} FOR JSON PATH, INCLUDE_NULL_VALUES)), JSON_QUERY('[]')) AS ${r(e.relationName)}`;
1391
- }, Vi = (e, t, n) => {
1392
- let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = Fi(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1415
+ }, sa = (e, t, n) => {
1416
+ let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = ta(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1393
1417
  projection: e.junction,
1394
- source: Si(s)
1418
+ source: Hi(s)
1395
1419
  });
1396
1420
  if (c === null) return null;
1397
- let l = e.branch.where === void 0 ? r`` : r` AND ${U(e.branch.where, o, r)}`, u = Hi(e, s, r), d = R(o, e.branch.orderBy, r), { top: f, pagination: p, finalOrder: m } = zi(e.branch, d, r);
1421
+ let l = e.branch.where === void 0 ? r`` : r` AND ${U(e.branch.where, o, r)}`, u = ca(e, s, r), d = R(o, e.branch.orderBy, r), { top: f, pagination: p, finalOrder: m } = aa(e.branch, d, r);
1398
1422
  return r`ISNULL(JSON_QUERY((SELECT ${f}${c} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${B(o, "id", r)} = ${B(s, i.targetKey, r)} WHERE ${B(s, i.sourceKey, r)} = ${B(t, "id", r)}${u}${l}${m}${p} FOR JSON PATH, INCLUDE_NULL_VALUES)), JSON_QUERY('[]')) AS ${r(e.relationName)}`;
1399
1423
  }, B = (e, t, n) => e === void 0 ? n`${n(t)}` : n`${n(e)}.${n(t)}`, V = (e, t) => t.unsafe(`'${e.replace(/'/g, "''")}'`), H = (e, t) => {
1400
1424
  if (!Number.isFinite(e) || !Number.isInteger(e) || e < 0) throw Error(`literalInt: expected non-negative integer, got ${e}`);
1401
1425
  return t.unsafe(String(e));
1402
- }, U = (e, t, n) => F(Ui(e, t), n), Hi = (e, t, n, r = !1) => {
1426
+ }, U = (e, t, n) => L(la(e, t), n), ca = (e, t, n, r = !1) => {
1403
1427
  let i = e.branch.onJunction;
1404
1428
  return i === void 0 ? n`` : n` AND ${U(r ? W(i) : i, t, n)}`;
1405
- }, Ui = (e, t) => {
1406
- if ("not" in e) return { not: Ui(e.not, t) };
1407
- if ("and" in e) return { and: e.and.map((e) => Ui(e, t)) };
1408
- if ("or" in e) return { or: e.or.map((e) => Ui(e, t)) };
1429
+ }, la = (e, t) => {
1430
+ if ("not" in e) return { not: la(e.not, t) };
1431
+ if ("and" in e) return { and: e.and.map((e) => la(e, t)) };
1432
+ if ("or" in e) return { or: e.or.map((e) => la(e, t)) };
1409
1433
  if (e.op === "subquery-in" || e.op === "subquery-not-in") {
1410
1434
  let n = e;
1411
1435
  return {
@@ -1427,91 +1451,91 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
1427
1451
  let t = e;
1428
1452
  return {
1429
1453
  ...t,
1430
- value: Wi(t.value)
1454
+ value: ua(t.value)
1431
1455
  };
1432
- }, Wi = (e) => e == null ? e : e instanceof Date ? e.toISOString() : typeof e == "boolean" ? +!!e : Array.isArray(e) ? e.map((e) => Wi(e)) : e, Gi = Symbol.for("@voltro/database/coreTablesRegistry"), Ki = globalThis, qi = Ki[Gi] ?? (Ki[Gi] = {}), Ji = (e) => {
1433
- e.actors !== void 0 && (qi.actors = e.actors), e.tenants !== void 0 && (qi.tenants = e.tenants);
1434
- }, Yi = (e, t) => () => {
1456
+ }, ua = (e) => e == null ? e : e instanceof Date ? e.toISOString() : typeof e == "boolean" ? +!!e : Array.isArray(e) ? e.map((e) => ua(e)) : e, da = Symbol.for("@voltro/database/coreTablesRegistry"), fa = globalThis, pa = fa[da] ?? (fa[da] = {}), ma = (e) => {
1457
+ e.actors !== void 0 && (pa.actors = e.actors), e.tenants !== void 0 && (pa.tenants = e.tenants);
1458
+ }, ha = (e, t) => () => {
1435
1459
  let n = e();
1436
1460
  if (n === void 0) throw Error(`core '${t}' table not registered; expected the framework CLI or your migrate step to call registerCoreTables({ ${t}: () => ${t}Table }) before the database handle is constructed`);
1437
1461
  return n();
1438
- }, Xi = () => Yi(() => qi.actors, "actors"), Zi = () => Yi(() => qi.tenants, "tenants"), Qi = T("actors", {
1439
- id: _(),
1440
- kind: t().oneOf([
1462
+ }, ga = () => ha(() => pa.actors, "actors"), _a = () => ha(() => pa.tenants, "tenants"), va = w("actors", {
1463
+ id: E(),
1464
+ kind: C().oneOf([
1441
1465
  "user",
1442
1466
  "serviceAccount",
1443
1467
  "apiKey",
1444
1468
  "system"
1445
1469
  ]),
1446
- displayName: t().nullable(),
1447
- createdAt: C().default("now")
1448
- }), $i = (e, t) => ({
1470
+ displayName: C().nullable(),
1471
+ createdAt: T().default("now")
1472
+ }), ya = (e, t) => ({
1449
1473
  column: e,
1450
1474
  op: "eq",
1451
1475
  value: t
1452
- }), ea = (e, t) => ({
1476
+ }), ba = (e, t) => ({
1453
1477
  column: e,
1454
1478
  op: "neq",
1455
1479
  value: t
1456
- }), ta = (e, t) => ({
1480
+ }), xa = (e, t) => ({
1457
1481
  column: e,
1458
1482
  op: "gt",
1459
1483
  value: t
1460
- }), na = (e, t) => ({
1484
+ }), Sa = (e, t) => ({
1461
1485
  column: e,
1462
1486
  op: "gte",
1463
1487
  value: t
1464
- }), ra = (e, t) => ({
1488
+ }), Ca = (e, t) => ({
1465
1489
  column: e,
1466
1490
  op: "lt",
1467
1491
  value: t
1468
- }), ia = (e, t) => ({
1492
+ }), wa = (e, t) => ({
1469
1493
  column: e,
1470
1494
  op: "lte",
1471
1495
  value: t
1472
- }), aa = (e, t) => ({
1496
+ }), Ta = (e, t) => ({
1473
1497
  column: e,
1474
1498
  op: "in",
1475
1499
  value: t
1476
- }), oa = (e, t) => ({
1500
+ }), Ea = (e, t) => ({
1477
1501
  column: e,
1478
1502
  op: "notIn",
1479
1503
  value: t
1480
- }), sa = (e, t) => ({
1504
+ }), Da = (e, t) => ({
1481
1505
  column: e,
1482
1506
  op: "contains",
1483
1507
  value: t
1484
- }), ca = (e, t) => ({
1508
+ }), Oa = (e, t) => ({
1485
1509
  column: e,
1486
1510
  op: "startsWith",
1487
1511
  value: t
1488
- }), la = (e, t) => ({
1512
+ }), ka = (e, t) => ({
1489
1513
  column: e,
1490
1514
  op: "arrayContains",
1491
1515
  value: t
1492
- }), ua = (e, t) => ({
1516
+ }), Aa = (e, t) => ({
1493
1517
  column: e,
1494
1518
  op: "arrayOverlaps",
1495
1519
  value: t
1496
- }), da = (e, t) => ({
1520
+ }), ja = (e, t) => ({
1497
1521
  column: e,
1498
1522
  op: "arrayHas",
1499
1523
  value: t
1500
- }), fa = {
1524
+ }), Ma = {
1501
1525
  column: "id",
1502
1526
  op: "in",
1503
1527
  value: []
1504
- }, pa = (e) => ({
1528
+ }, Na = (e) => ({
1505
1529
  column: e,
1506
1530
  op: "isNull"
1507
- }), ma = (e) => ({
1531
+ }), Pa = (e) => ({
1508
1532
  column: e,
1509
1533
  op: "isNotNull"
1510
- }), ha = (e, t) => ({
1534
+ }), Fa = (e, t) => ({
1511
1535
  column: e,
1512
1536
  op: "spatial",
1513
1537
  value: t
1514
- }), ga = (...e) => ({ and: e }), _a = (...e) => ({ or: e }), va = (e) => ({ not: e }), ya = (e, ...t) => {
1538
+ }), Ia = (...e) => ({ and: e }), La = (...e) => ({ or: e }), Ra = (e) => ({ not: e }), za = (e, ...t) => {
1515
1539
  if (t.length === 0) throw Error(`jsonField("${e}"): at least one path segment is required`);
1516
1540
  let n = (n, r) => ({
1517
1541
  column: e,
@@ -1533,33 +1557,33 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
1533
1557
  isNull: () => n("isNull"),
1534
1558
  isNotNull: () => n("isNotNull")
1535
1559
  };
1536
- }, ba = (e) => "descriptor" in e ? e.descriptor : e, xa = (e, t) => ({
1560
+ }, Ba = (e) => "descriptor" in e ? e.descriptor : e, Va = (e, t) => ({
1537
1561
  column: e,
1538
1562
  op: "subquery-in",
1539
- subquery: ba(t)
1540
- }), Sa = (e, t) => ({
1563
+ subquery: Ba(t)
1564
+ }), Ha = (e, t) => ({
1541
1565
  column: e,
1542
1566
  op: "subquery-not-in",
1543
- subquery: ba(t)
1544
- }), Ca = (e) => ({
1567
+ subquery: Ba(t)
1568
+ }), Ua = (e) => ({
1545
1569
  op: "exists",
1546
- subquery: ba(e)
1547
- }), wa = (e) => ({
1570
+ subquery: Ba(e)
1571
+ }), Wa = (e) => ({
1548
1572
  op: "not-exists",
1549
- subquery: ba(e)
1550
- }), Ta = (e, t) => e === t || e instanceof Date && t instanceof Date && e.getTime() === t.getTime(), Ea = (e, t) => {
1573
+ subquery: Ba(e)
1574
+ }), Ga = (e, t) => e === t || e instanceof Date && t instanceof Date && e.getTime() === t.getTime(), Ka = (e, t) => {
1551
1575
  if (e == null || t == null) return null;
1552
1576
  let n = e instanceof Date ? e.getTime() : e, r = t instanceof Date ? t.getTime() : t;
1553
1577
  return typeof n == typeof r ? n === r ? 0 : n > r ? 1 : -1 : null;
1554
- }, Da = (e, t, n = null) => {
1578
+ }, qa = (e, t, n = null) => {
1555
1579
  if (!t) return !1;
1556
- if ("not" in e) return !Da(e.not, t, n);
1580
+ if ("not" in e) return !qa(e.not, t, n);
1557
1581
  if ("and" in e) {
1558
- for (let r of e.and) if (!Da(r, t, n)) return !1;
1582
+ for (let r of e.and) if (!qa(r, t, n)) return !1;
1559
1583
  return !0;
1560
1584
  }
1561
1585
  if ("or" in e) {
1562
- for (let r of e.or) if (Da(r, t, n)) return !0;
1586
+ for (let r of e.or) if (qa(r, t, n)) return !0;
1563
1587
  return !1;
1564
1588
  }
1565
1589
  if (e.op === "subquery-in" || e.op === "subquery-not-in") {
@@ -1576,14 +1600,14 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
1576
1600
  }
1577
1601
  let r = e, i = t[r.column];
1578
1602
  switch (r.op) {
1579
- case "eq": return Ta(i, r.value);
1580
- case "neq": return !Ta(i, r.value);
1581
- case "gt": return (Ea(i, r.value) ?? -1) > 0;
1582
- case "gte": return (Ea(i, r.value) ?? -1) >= 0;
1583
- case "lt": return (Ea(i, r.value) ?? 1) < 0;
1584
- case "lte": return (Ea(i, r.value) ?? 1) <= 0;
1585
- case "in": return Array.isArray(r.value) && r.value.some((e) => Ta(i, e));
1586
- case "notIn": return Array.isArray(r.value) && !r.value.some((e) => Ta(i, e));
1603
+ case "eq": return Ga(i, r.value);
1604
+ case "neq": return !Ga(i, r.value);
1605
+ case "gt": return (Ka(i, r.value) ?? -1) > 0;
1606
+ case "gte": return (Ka(i, r.value) ?? -1) >= 0;
1607
+ case "lt": return (Ka(i, r.value) ?? 1) < 0;
1608
+ case "lte": return (Ka(i, r.value) ?? 1) <= 0;
1609
+ case "in": return Array.isArray(r.value) && r.value.some((e) => Ga(i, e));
1610
+ case "notIn": return Array.isArray(r.value) && !r.value.some((e) => Ga(i, e));
1587
1611
  case "contains": return typeof i == "string" && typeof r.value == "string" && i.toLowerCase().includes(r.value.toLowerCase());
1588
1612
  case "startsWith": return typeof i == "string" && typeof r.value == "string" && i.startsWith(r.value);
1589
1613
  case "arrayContains": {
@@ -1599,17 +1623,17 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
1599
1623
  case "isNotNull": return i != null;
1600
1624
  case "spatial": throw Error("@voltro/plugin-postgis: spatial predicates (ST_DWithin / ST_Contains / ST_Within / ST_Intersects / bbox &&) are not evaluable in-memory — use them in one-shot ctx.store.query reads, not reactive subscriptions.");
1601
1625
  }
1602
- }, Oa = function* (e) {
1626
+ }, Ja = function* (e) {
1603
1627
  if ("not" in e) {
1604
- yield* Oa(e.not);
1628
+ yield* Ja(e.not);
1605
1629
  return;
1606
1630
  }
1607
1631
  if ("and" in e) {
1608
- for (let t of e.and) yield* Oa(t);
1632
+ for (let t of e.and) yield* Ja(t);
1609
1633
  return;
1610
1634
  }
1611
1635
  if ("or" in e) {
1612
- for (let t of e.or) yield* Oa(t);
1636
+ for (let t of e.or) yield* Ja(t);
1613
1637
  return;
1614
1638
  }
1615
1639
  e.op === "subquery-in" || e.op === "subquery-not-in" ? yield {
@@ -1619,46 +1643,46 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
1619
1643
  kind: "exists",
1620
1644
  descriptor: e.subquery
1621
1645
  });
1622
- }, ka = function* (e, t = !0) {
1646
+ }, Ya = function* (e, t = !0) {
1623
1647
  if ("not" in e) {
1624
- yield* ka(e.not, !1);
1648
+ yield* Ya(e.not, !1);
1625
1649
  return;
1626
1650
  }
1627
1651
  if ("and" in e) {
1628
- for (let n of e.and) yield* ka(n, t);
1652
+ for (let n of e.and) yield* Ya(n, t);
1629
1653
  return;
1630
1654
  }
1631
1655
  if ("or" in e) {
1632
- for (let t of e.or) yield* ka(t, !1);
1656
+ for (let t of e.or) yield* Ya(t, !1);
1633
1657
  return;
1634
1658
  }
1635
1659
  e.op !== "subquery-in" && e.op !== "subquery-not-in" && e.op !== "exists" && e.op !== "not-exists" && (yield {
1636
1660
  ...e,
1637
1661
  conjunctive: t
1638
1662
  });
1639
- }, Aa = (e, t) => ({
1663
+ }, Xa = (e, t) => ({
1640
1664
  ...t,
1641
1665
  ...e,
1642
1666
  origin: e.origin ?? "injected"
1643
- }), ja = (e, t, n = {}) => ({
1667
+ }), Za = (e, t, n = {}) => ({
1644
1668
  table: e,
1645
1669
  op: "insert",
1646
1670
  old: null,
1647
1671
  new: t,
1648
1672
  ...n
1649
- }), Ma = (e, t, n, r = {}) => ({
1673
+ }), Qa = (e, t, n, r = {}) => ({
1650
1674
  table: e,
1651
1675
  op: "update",
1652
1676
  old: t,
1653
1677
  new: n,
1654
1678
  ...r
1655
- }), Na = (e, t, n = {}) => ({
1679
+ }), $a = (e, t, n = {}) => ({
1656
1680
  table: e,
1657
1681
  op: "delete",
1658
1682
  old: t,
1659
1683
  new: null,
1660
1684
  ...n
1661
- }), Pa = (e, t, n = {}) => {
1685
+ }), eo = (e, t, n = {}) => {
1662
1686
  let { at: r = "2026-01-01T00:00:00.000Z", column: i = "deletedAt", ...a } = n;
1663
1687
  return {
1664
1688
  table: e,
@@ -1673,13 +1697,13 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
1673
1697
  },
1674
1698
  ...a
1675
1699
  };
1676
- }, Fa = (e) => e == null ? "null" : e instanceof Date ? JSON.stringify(e.toISOString()) : typeof e == "bigint" ? JSON.stringify(e.toString()) : Array.isArray(e) ? `[${e.map(Fa).join(",")}]` : typeof e == "object" ? `{${Object.entries(e).filter(([, e]) => e !== void 0).sort(([e], [t]) => e < t ? -1 : +(e > t)).map(([e, t]) => `${JSON.stringify(e)}:${Fa(t)}`).join(",")}}` : JSON.stringify(e) ?? "null", Ia = (e) => Lt("sha256").update([
1700
+ }, to = (e) => e == null ? "null" : e instanceof Date ? JSON.stringify(e.toISOString()) : typeof e == "bigint" ? JSON.stringify(e.toString()) : Array.isArray(e) ? `[${e.map(to).join(",")}]` : typeof e == "object" ? `{${Object.entries(e).filter(([, e]) => e !== void 0).sort(([e], [t]) => e < t ? -1 : +(e > t)).map(([e, t]) => `${JSON.stringify(e)}:${to(t)}`).join(",")}}` : JSON.stringify(e) ?? "null", no = (e) => qt("sha256").update([
1677
1701
  e.pipe,
1678
1702
  e.op,
1679
1703
  e.key,
1680
- Fa(e.next),
1681
- Fa(e.prev)
1682
- ].join("\0")).digest("hex").slice(0, 32), La = (e, t) => `${e}:${t}`, Ra = (e) => {
1704
+ to(e.next),
1705
+ to(e.prev)
1706
+ ].join("\0")).digest("hex").slice(0, 32), ro = (e, t) => `${e}:${t}`, io = (e) => {
1683
1707
  let t = e.lastIndexOf(":");
1684
1708
  if (t <= 0) return null;
1685
1709
  let n = Number(e.slice(t + 1));
@@ -1687,7 +1711,7 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
1687
1711
  digest: e.slice(0, t),
1688
1712
  occurrence: n
1689
1713
  };
1690
- }, za = class {
1714
+ }, ao = class {
1691
1715
  #e = /* @__PURE__ */ new Map();
1692
1716
  #t;
1693
1717
  #n;
@@ -1709,7 +1733,7 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
1709
1733
  }
1710
1734
  seedFromChangeKeys(e, t) {
1711
1735
  for (let n of e) {
1712
- let e = Ra(n);
1736
+ let e = io(n);
1713
1737
  if (e === null) continue;
1714
1738
  let r = this.#e.get(e.digest), i = Math.max(r?.count ?? 0, e.occurrence + 1);
1715
1739
  this.#e.set(e.digest, {
@@ -1730,29 +1754,29 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
1730
1754
  this.#e.delete(e.value);
1731
1755
  }
1732
1756
  }
1733
- }, Ba = "VOLTRO_CHANGE_CLAIMS_TTL_HOURS", Va = 1, Ha = (e = process.env) => {
1734
- let t = Number(e[Ba]);
1757
+ }, oo = "VOLTRO_CHANGE_CLAIMS_TTL_HOURS", so = 1, co = (e = process.env) => {
1758
+ let t = Number(e[oo]);
1735
1759
  return (Number.isFinite(t) && t > 0 ? t : 1) * 2 * 36e5;
1736
- }, Ua = new Rt(), Wa = (e, t) => Ua.run(e, t), Ga = () => Ua.getStore(), Ka = (e) => {
1737
- let t = e ?? Ua.getStore();
1760
+ }, lo = new Jt(), uo = (e, t) => lo.run(e, t), fo = () => lo.getStore(), po = (e) => {
1761
+ let t = e ?? lo.getStore();
1738
1762
  return t === void 0 ? {} : {
1739
1763
  ...t.traceId === void 0 ? {} : { traceId: t.traceId },
1740
1764
  ...t.subjectId === void 0 ? {} : { subjectId: t.subjectId },
1741
1765
  ...t.procedure === void 0 ? {} : { procedure: t.procedure },
1742
1766
  ...t.via === void 0 ? {} : { via: t.via }
1743
1767
  };
1744
- }, qa = (e) => {
1745
- let t = Ua.getStore();
1746
- return t === void 0 ? e(void 0) : Ua.run(t, () => e(t));
1747
- }, Ja = 3e4, Ya = 1e4, G = /* @__PURE__ */ new Map(), K = 0, Xa = (e, t, n) => `${e}\u0000${t}\u0000${String(n)}`, Za = (e) => {
1768
+ }, mo = (e) => {
1769
+ let t = lo.getStore();
1770
+ return t === void 0 ? e(void 0) : lo.run(t, () => e(t));
1771
+ }, ho = 3e4, go = 1e4, G = /* @__PURE__ */ new Map(), K = 0, _o = (e, t, n) => `${e}\u0000${t}\u0000${String(n)}`, vo = (e) => {
1748
1772
  for (let [t, n] of G) {
1749
- let r = n.filter((t) => e - t.at < Ja);
1773
+ let r = n.filter((t) => e - t.at < ho);
1750
1774
  K -= n.length - r.length, r.length === 0 ? G.delete(t) : r.length !== n.length && G.set(t, r);
1751
1775
  }
1752
- }, Qa = (e, t) => {
1776
+ }, yo = (e, t) => {
1753
1777
  if (t.traceId === void 0 && t.subjectId === void 0 && t.procedure === void 0) return;
1754
1778
  let n = Date.now();
1755
- if (K >= Ya && Za(n), K >= Ya) return;
1779
+ if (K >= go && vo(n), K >= go) return;
1756
1780
  let r = G.get(e);
1757
1781
  r === void 0 ? G.set(e, [{
1758
1782
  attribution: t,
@@ -1761,38 +1785,38 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
1761
1785
  attribution: t,
1762
1786
  at: n
1763
1787
  }), K += 1;
1764
- }, $a = (e) => {
1788
+ }, bo = (e) => {
1765
1789
  let t = G.get(e);
1766
1790
  if (t === void 0 || t.length === 0) return;
1767
1791
  let n = t.shift();
1768
- if (--K, t.length === 0 && G.delete(e), !(Date.now() - n.at >= Ja)) return n.attribution;
1769
- }, eo = (e) => (G.get(e)?.length ?? 0) > 0, q = /* @__PURE__ */ new Map(), to = /* @__PURE__ */ new Map(), no = /* @__PURE__ */ new Map(), ro = 250, io = (e) => {
1770
- let t = to.get(e);
1792
+ if (--K, t.length === 0 && G.delete(e), !(Date.now() - n.at >= ho)) return n.attribution;
1793
+ }, xo = (e) => (G.get(e)?.length ?? 0) > 0, q = /* @__PURE__ */ new Map(), So = /* @__PURE__ */ new Map(), Co = /* @__PURE__ */ new Map(), wo = 250, To = (e) => {
1794
+ let t = So.get(e);
1771
1795
  if (t === void 0) return;
1772
- to.delete(e);
1773
- let n = no.get(e);
1774
- n !== void 0 && (clearTimeout(n), no.delete(e));
1796
+ So.delete(e);
1797
+ let n = Co.get(e);
1798
+ n !== void 0 && (clearTimeout(n), Co.delete(e));
1775
1799
  for (let e of t) e();
1776
- }, ao = (e) => {
1800
+ }, Eo = (e) => {
1777
1801
  q.set(e, (q.get(e) ?? 0) + 1);
1778
- }, oo = (e) => {
1802
+ }, Do = (e) => {
1779
1803
  let t = (q.get(e) ?? 0) - 1;
1780
1804
  if (t > 0) {
1781
1805
  q.set(e, t);
1782
1806
  return;
1783
1807
  }
1784
- q.delete(e), io(e);
1785
- }, so = (e, t, n, r) => {
1786
- let i = n == null ? void 0 : Xa(e, t, n), a = () => r(i === void 0 ? void 0 : $a(i));
1808
+ q.delete(e), To(e);
1809
+ }, Oo = (e, t, n, r) => {
1810
+ let i = n == null ? void 0 : _o(e, t, n), a = () => r(i === void 0 ? void 0 : bo(i));
1787
1811
  if (i === void 0) {
1788
1812
  a();
1789
1813
  return;
1790
1814
  }
1791
- if (eo(i)) {
1815
+ if (xo(i)) {
1792
1816
  a();
1793
1817
  return;
1794
1818
  }
1795
- let o = to.get(e);
1819
+ let o = So.get(e);
1796
1820
  if (o === void 0 && (q.get(e) ?? 0) === 0) {
1797
1821
  a();
1798
1822
  return;
@@ -1801,91 +1825,91 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
1801
1825
  o.push(a);
1802
1826
  return;
1803
1827
  }
1804
- to.set(e, [a]);
1805
- let s = setTimeout(() => io(e), ro);
1806
- typeof s == "object" && typeof s.unref == "function" && s.unref(), no.set(e, s);
1807
- }, co = () => {
1828
+ So.set(e, [a]);
1829
+ let s = setTimeout(() => To(e), wo);
1830
+ typeof s == "object" && typeof s.unref == "function" && s.unref(), Co.set(e, s);
1831
+ }, ko = () => {
1808
1832
  G.clear(), K = 0, q.clear();
1809
- for (let e of no.values()) clearTimeout(e);
1810
- no.clear(), to.clear();
1811
- }, lo = () => K, uo = 64, fo = "\0", po = 32, mo = (e, ...t) => `${e}_${Lt("sha256").update(t.map(String).join(fo)).digest("hex").slice(0, po)}`, ho = (e) => e.length + 1 + po, J = /* @__PURE__ */ new Map(), go = (e, t) => {
1833
+ for (let e of Co.values()) clearTimeout(e);
1834
+ Co.clear(), So.clear();
1835
+ }, Ao = () => K, jo = 64, Mo = "\0", No = 32, Po = (e, ...t) => `${e}_${qt("sha256").update(t.map(String).join(Mo)).digest("hex").slice(0, No)}`, Fo = (e) => e.length + 1 + No, J = /* @__PURE__ */ new Map(), Io = (e, t) => {
1812
1836
  J.set(e, {
1813
1837
  recorder: t.recorder,
1814
1838
  tables: new Set(t.tables),
1815
1839
  ownTables: new Set(t.ownTables)
1816
1840
  });
1817
- }, _o = (e) => {
1841
+ }, Lo = (e) => {
1818
1842
  J.delete(e);
1819
- }, vo = () => J.clear(), yo = new Rt(), bo = (e) => yo.run({ n: 1 }, e), xo = (e) => D.suspend(() => {
1820
- let t = yo.getStore();
1821
- if (t !== void 0) return t.n += 1, D.ensuring(e, D.sync(() => {
1843
+ }, Ro = () => J.clear(), zo = new Jt(), Bo = (e) => zo.run({ n: 1 }, e), Vo = (e) => k.suspend(() => {
1844
+ let t = zo.getStore();
1845
+ if (t !== void 0) return t.n += 1, k.ensuring(e, k.sync(() => {
1822
1846
  --t.n;
1823
1847
  }));
1824
1848
  let n = { n: 1 };
1825
- return yo.enterWith(n), D.ensuring(e, D.sync(() => {
1849
+ return zo.enterWith(n), k.ensuring(e, k.sync(() => {
1826
1850
  --n.n;
1827
1851
  }));
1828
- }), So = () => (yo.getStore()?.n ?? 0) > 0, Co = (e) => {
1829
- if (J.size === 0 || (yo.getStore()?.n ?? 0) > 0) return !1;
1852
+ }), Ho = () => (zo.getStore()?.n ?? 0) > 0, Uo = (e) => {
1853
+ if (J.size === 0 || (zo.getStore()?.n ?? 0) > 0) return !1;
1830
1854
  for (let t of J.values()) if (!t.ownTables.has(e) && t.tables.has(e)) return !0;
1831
1855
  return !1;
1832
- }, wo = async (e, t) => {
1856
+ }, Wo = async (e, t) => {
1833
1857
  if (J.size !== 0) {
1834
1858
  for (let [n, r] of J.entries()) if (!r.ownTables.has(t.table) && r.tables.has(t.table)) try {
1835
1859
  await r.recorder(e, t);
1836
1860
  } catch (e) {
1837
- let r = gn(e);
1861
+ let r = Pn(e);
1838
1862
  throw r === void 0 ? e : Error(`write recorder '${n}' failed while recording a ${t.op} on '${t.table}': ${r}`, { cause: e });
1839
1863
  }
1840
1864
  }
1841
- }, To = Nt.exponential({
1865
+ }, Go = Ut.exponential({
1842
1866
  start: 5e-4,
1843
1867
  factor: 2,
1844
1868
  count: 16
1845
- }), Eo = O.counter("voltro_db_queries_total", { description: "Database operations executed, by dialect and operation kind." }), Do = O.histogram("voltro_db_query_duration_seconds", To, "Database operation duration in seconds, by dialect and operation kind."), Oo = O.counter("voltro_db_errors_total", { description: "Database operations that threw, by dialect and operation kind." }), ko = O.gauge("voltro_db_operations_in_flight", { description: "Database operations currently executing, by dialect. An upper bound on connections the framework holds; NOT the driver pool's waiting count." }), Ao = O.counter("voltro_db_eager_fallback_total", { description: "Eager-load queries that degraded from the single-roundtrip JSON-agg path to the multi-query walker, by dialect and reason." }), jo = [], Mo = /* @__PURE__ */ new Map(), No = /* @__PURE__ */ new Map(), Po = /* @__PURE__ */ new Map(), Fo = (e, t) => {
1846
- let n = `${e}\u0000${t}`, r = Mo.get(n);
1869
+ }), Ko = A.counter("voltro_db_queries_total", { description: "Database operations executed, by dialect and operation kind." }), qo = A.histogram("voltro_db_query_duration_seconds", Go, "Database operation duration in seconds, by dialect and operation kind."), Jo = A.counter("voltro_db_errors_total", { description: "Database operations that threw, by dialect and operation kind." }), Yo = A.gauge("voltro_db_operations_in_flight", { description: "Database operations currently executing, by dialect. An upper bound on connections the framework holds; NOT the driver pool's waiting count." }), Xo = A.counter("voltro_db_eager_fallback_total", { description: "Eager-load queries that degraded from the single-roundtrip JSON-agg path to the multi-query walker, by dialect and reason." }), Zo = [], Qo = /* @__PURE__ */ new Map(), $o = /* @__PURE__ */ new Map(), es = /* @__PURE__ */ new Map(), ts = (e, t) => {
1870
+ let n = `${e}\u0000${t}`, r = Qo.get(n);
1847
1871
  if (r !== void 0) return r;
1848
- let i = (n) => O.tagged(O.tagged(n, "dialect", e), "op", t), a = {
1849
- count: i(Eo),
1850
- duration: i(Do),
1851
- errors: i(Oo)
1872
+ let i = (n) => A.tagged(A.tagged(n, "dialect", e), "op", t), a = {
1873
+ count: i(Ko),
1874
+ duration: i(qo),
1875
+ errors: i(Jo)
1852
1876
  };
1853
- return Mo.set(n, a), a;
1854
- }, Io = () => {
1855
- Mo.clear(), No.clear(), Po.clear();
1856
- }, Lo = () => Mo.size + No.size + Po.size, Ro = /* @__PURE__ */ new Map(), zo = (e, t) => {
1857
- let n = Math.max(0, (Ro.get(e) ?? 0) + t);
1858
- n === 0 ? Ro.delete(e) : Ro.set(e, n);
1859
- let r = No.get(e);
1860
- r === void 0 && (r = O.tagged(ko, "dialect", e), No.set(e, r)), r.unsafeUpdate(n, jo);
1861
- }, Bo = (e) => Ro.get(e) ?? 0, Vo = (e) => {
1862
- let t = Fo(String(e.dialect), e.op);
1863
- t.count.unsafeUpdate(1, jo), t.duration.unsafeUpdate(e.durationMs / 1e3, jo), e.status === "error" && t.errors.unsafeUpdate(1, jo);
1864
- }, Ho = async (e, t, n) => {
1877
+ return Qo.set(n, a), a;
1878
+ }, ns = () => {
1879
+ Qo.clear(), $o.clear(), es.clear();
1880
+ }, rs = () => Qo.size + $o.size + es.size, is = /* @__PURE__ */ new Map(), as = (e, t) => {
1881
+ let n = Math.max(0, (is.get(e) ?? 0) + t);
1882
+ n === 0 ? is.delete(e) : is.set(e, n);
1883
+ let r = $o.get(e);
1884
+ r === void 0 && (r = A.tagged(Yo, "dialect", e), $o.set(e, r)), r.unsafeUpdate(n, Zo);
1885
+ }, os = (e) => is.get(e) ?? 0, ss = (e) => {
1886
+ let t = ts(String(e.dialect), e.op);
1887
+ t.count.unsafeUpdate(1, Zo), t.duration.unsafeUpdate(e.durationMs / 1e3, Zo), e.status === "error" && t.errors.unsafeUpdate(1, Zo);
1888
+ }, cs = async (e, t, n) => {
1865
1889
  let r = performance.now(), i = String(e);
1866
- zo(i, 1);
1890
+ as(i, 1);
1867
1891
  let a = "ok";
1868
1892
  try {
1869
1893
  return await n();
1870
1894
  } catch (e) {
1871
1895
  throw a = "error", e;
1872
1896
  } finally {
1873
- zo(i, -1), Vo({
1897
+ as(i, -1), ss({
1874
1898
  dialect: e,
1875
1899
  op: t,
1876
1900
  durationMs: performance.now() - r,
1877
1901
  status: a
1878
1902
  });
1879
1903
  }
1880
- }, Uo = 3e5, Wo = (e) => {
1904
+ }, ls = 3e5, us = (e) => {
1881
1905
  if (e == null || e === "") return;
1882
1906
  let t = Number(e);
1883
1907
  return Number.isFinite(t) && t >= 0 ? Math.floor(t) : void 0;
1884
- }, Go = (e, t = process.env) => Wo(t.VOLTRO_DB_EAGER_FALLBACK_WARN_INTERVAL_MS) ?? Wo(e) ?? 3e5, Ko = (e, t = {}) => {
1885
- let n = Go(t.warnIntervalMs), r = t.now ?? (() => Date.now()), i = /* @__PURE__ */ new Map();
1908
+ }, ds = (e, t = process.env) => us(t.VOLTRO_DB_EAGER_FALLBACK_WARN_INTERVAL_MS) ?? us(e) ?? 3e5, fs = (e, t = {}) => {
1909
+ let n = ds(t.warnIntervalMs), r = t.now ?? (() => Date.now()), i = /* @__PURE__ */ new Map();
1886
1910
  return (t) => {
1887
- let a = `${t.dialect} ${t.reason}`, o = Po.get(a);
1888
- o === void 0 && (o = O.tagged(O.tagged(Ao, "dialect", String(t.dialect)), "reason", t.reason), Po.set(a, o)), o.unsafeUpdate(1, jo);
1911
+ let a = `${t.dialect} ${t.reason}`, o = es.get(a);
1912
+ o === void 0 && (o = A.tagged(A.tagged(Xo, "dialect", String(t.dialect)), "reason", t.reason), es.set(a, o)), o.unsafeUpdate(1, Zo);
1889
1913
  let s = `${t.table}\u0000${t.reason}`, c = i.get(s), l = c === void 0 || n > 0 && r() - c >= n, u = {
1890
1914
  table: t.table,
1891
1915
  dialect: String(t.dialect),
@@ -1899,24 +1923,24 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
1899
1923
  }
1900
1924
  i.set(s, r()), e.warn(t.reason === "execute-failed" ? "eager-load JSON-agg statement FAILED and was re-run on the multi-query walker — this query pays both paths on every call. Counted as voltro_db_eager_fallback_total{reason=\"execute-failed\"}." : "eager-load could not be compiled to a single JSON-agg roundtrip and is running on the multi-query walker — one round trip per relation level, on every call. Counted as voltro_db_eager_fallback_total{reason=\"not-compilable\"}.", u);
1901
1925
  };
1902
- }, qo = (e) => {
1903
- if (Mt.isSuccess(e)) return e.value;
1904
- throw kt.squash(e.cause);
1905
- }, Jo = "10 millis", Yo = 3, Xo = async (e) => {
1906
- let t = 0, n = D.suspend(() => {
1926
+ }, ps = (e) => {
1927
+ if (Ht.isSuccess(e)) return e.value;
1928
+ throw O.squash(e.cause);
1929
+ }, ms = "10 millis", hs = 3, gs = async (e) => {
1930
+ let t = 0, n = k.suspend(() => {
1907
1931
  let n = ++t;
1908
- return e.withTransaction(D.flatMap(D.serviceOption(zt), (t) => {
1909
- if (k.isNone(t)) return D.fail(/* @__PURE__ */ Error(`${e.label}: TransactionConnection unexpectedly missing inside withTransaction.`));
1910
- let r = t.value, i = D.tryPromise({
1932
+ return e.withTransaction(k.flatMap(k.serviceOption(Yt), (t) => {
1933
+ if (j.isNone(t)) return k.fail(/* @__PURE__ */ Error(`${e.label}: TransactionConnection unexpectedly missing inside withTransaction.`));
1934
+ let r = t.value, i = k.tryPromise({
1911
1935
  try: () => e.body(r, n),
1912
1936
  catch: (e) => e
1913
1937
  });
1914
- return e.prepare === void 0 ? i : D.flatMap(e.prepare(r), () => i);
1915
- })).pipe(D.catchAllDefect((t) => e.isRetryable(t) ? D.fail(t) : D.die(t)));
1916
- }), r = Ft.exponential(Jo).pipe(Ft.compose(Ft.recurs(Yo)), Ft.whileInput(e.isRetryable)), i = n.pipe(D.retry(r), D.withSpan(e.span.name, { attributes: { ...e.span.attributes } }));
1917
- return Ho(e.dialect, "transaction", async () => qo(await e.runPromiseExit(e.wrapProgram === void 0 ? i : e.wrapProgram(i))));
1918
- }, Zo = async (e) => {
1919
- let t = Ga(), n = t === void 0 ? (e) => e() : (e) => Wa(t, e), r = await Xo({
1938
+ return e.prepare === void 0 ? i : k.flatMap(e.prepare(r), () => i);
1939
+ })).pipe(k.catchAllDefect((t) => e.isRetryable(t) ? k.fail(t) : k.die(t)));
1940
+ }), r = Gt.exponential(ms).pipe(Gt.compose(Gt.recurs(hs)), Gt.whileInput(e.isRetryable)), i = n.pipe(k.retry(r), k.withSpan(e.span.name, { attributes: { ...e.span.attributes } }));
1941
+ return cs(e.dialect, "transaction", async () => ps(await e.runPromiseExit(e.wrapProgram === void 0 ? i : e.wrapProgram(i))));
1942
+ }, _s = async (e) => {
1943
+ let t = fo(), n = t === void 0 ? (e) => e() : (e) => uo(t, e), r = await gs({
1920
1944
  ...e,
1921
1945
  body: (r) => {
1922
1946
  let i = e.makeView(r, t);
@@ -1927,48 +1951,50 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
1927
1951
  }
1928
1952
  });
1929
1953
  return r.view.commitEvents(), r.result;
1930
- }, Qo = class extends A.TaggedError()("VersionConflict", {
1931
- table: A.String,
1932
- id: A.String,
1933
- expected: A.Number,
1934
- actual: A.NullOr(A.Number)
1935
- }) {}, $o = (e) => {
1936
- for (let [t, n] of Object.entries(e)) if (n?.definition?.versionColumn === !0) return t;
1937
- }, es = (e) => {
1938
- let { versionColumn: t, patch: n } = e;
1939
- if (t === void 0) return {
1940
- nextVersion: void 0,
1941
- expected: void 0,
1942
- patch: { ...n }
1943
- };
1944
- let r = n[t], i = typeof r == "number" && Number.isFinite(r) ? r : void 0, a = { ...n };
1945
- return delete a[t], {
1946
- nextVersion: i === void 0 ? void 0 : i + 1,
1947
- expected: i,
1948
- patch: a
1949
- };
1950
- }, ts = (e) => {
1951
- if (e.expected !== void 0 && (e.current === null || e.current !== e.expected)) return new Qo({
1952
- table: e.table,
1953
- id: e.id,
1954
- expected: e.expected,
1955
- actual: e.current
1956
- });
1957
- }, ns = 1, rs = "voltro/expires", is = () => it({
1958
- id: rs,
1959
- fields: { expiresAt: C().nullable() },
1954
+ }, vs = /* @__PURE__ */ new Set([
1955
+ "1213",
1956
+ "ER_LOCK_DEADLOCK",
1957
+ "1205",
1958
+ "ER_LOCK_WAIT_TIMEOUT",
1959
+ "1020",
1960
+ "ER_CHECKREAD"
1961
+ ]), ys = /* @__PURE__ */ new Set(["40001", "40P01"]), bs = /* @__PURE__ */ new Set(["1205"]), xs = /* @__PURE__ */ new Set([
1962
+ "SQLITE_BUSY",
1963
+ "5",
1964
+ "SQLITE_LOCKED",
1965
+ "6"
1966
+ ]), Ss = /write-write conflict|write-read conflict|database is locked|table is locked|database is busy/i, Cs = /* @__PURE__ */ new Set([
1967
+ 1213,
1968
+ 1205,
1969
+ 1020
1970
+ ]), ws = /* @__PURE__ */ new Set([
1971
+ ...vs,
1972
+ ...ys,
1973
+ ...bs,
1974
+ ...xs
1975
+ ]), Ts = (e) => xn(e).some(Es), Es = (e) => {
1976
+ let t = e;
1977
+ for (let e = 0; e < 6 && typeof t == "object" && t; e++) {
1978
+ let e = t;
1979
+ if (typeof e.errno == "number" && Cs.has(e.errno) || typeof e.number == "number" && bs.has(String(e.number)) || typeof e.code == "string" && ws.has(e.code) || typeof e.sqlState == "string" && ys.has(e.sqlState) || typeof e.message == "string" && Ss.test(e.message)) return !0;
1980
+ t = e.cause;
1981
+ }
1982
+ return !1;
1983
+ }, Ds = "voltro/expires", Os = () => Ct({
1984
+ id: Ds,
1985
+ fields: { expiresAt: T().nullable() },
1960
1986
  behaviors: { defaultWhere: () => "expiresAt IS NULL OR expiresAt > now()" }
1961
- }), as = "voltro/localFirst", os = () => it({
1962
- id: as,
1987
+ }), ks = "voltro/localFirst", As = () => Ct({
1988
+ id: ks,
1963
1989
  fields: {}
1964
- }), ss = (e) => e.appliedMixins.some((e) => e.id === as), cs = (e) => {
1990
+ }), js = (e) => e.appliedMixins.some((e) => e.id === ks), Ms = (e) => {
1965
1991
  let t = [];
1966
- for (let n of Object.values(e)) ss(n) && t.push(n.tableName);
1992
+ for (let n of Object.values(e)) js(n) && t.push(n.tableName);
1967
1993
  return t;
1968
- }, ls = class extends jt.TaggedError("TableStreamError") {}, us = 1e3, ds = (e, t, n, r) => {
1969
- let i = k.match(r, {
1994
+ }, Ns = class extends Vt.TaggedError("TableStreamError") {}, Ps = 1e3, Fs = (e, t, n, r) => {
1995
+ let i = j.match(r, {
1970
1996
  onNone: () => e.where,
1971
- onSome: (n) => e.where ? ga(e.where, ta(t, n)) : ta(t, n)
1997
+ onSome: (n) => e.where ? Ia(e.where, xa(t, n)) : xa(t, n)
1972
1998
  });
1973
1999
  return {
1974
2000
  table: e.table,
@@ -1983,19 +2009,19 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
1983
2009
  ...e.includeDeleted === void 0 ? {} : { includeDeleted: e.includeDeleted },
1984
2010
  ...e.crossTenant === void 0 ? {} : { crossTenant: e.crossTenant }
1985
2011
  };
1986
- }, fs = (e, t) => {
1987
- let n = t.pk ?? "id", r = t.chunkSize ?? us;
1988
- return It.paginateChunkEffect(k.none(), (i) => {
1989
- let a = D.tryPromise({
1990
- try: () => e.query(ds(t, n, r, i)),
1991
- catch: (e) => new ls({
2012
+ }, Is = (e, t) => {
2013
+ let n = t.pk ?? "id", r = t.chunkSize ?? Ps;
2014
+ return Kt.paginateChunkEffect(j.none(), (i) => {
2015
+ let a = k.tryPromise({
2016
+ try: () => e.query(Fs(t, n, r, i)),
2017
+ catch: (e) => new Ns({
1992
2018
  table: t.table,
1993
2019
  cause: e
1994
2020
  })
1995
2021
  });
1996
- return (t.retry ? a.pipe(D.retry(t.retry)) : a).pipe(D.map((e) => [At.fromIterable(e), e.length === r && e.length > 0 ? k.some(k.some(e[e.length - 1][n])) : k.none()]));
2022
+ return (t.retry ? a.pipe(k.retry(t.retry)) : a).pipe(k.map((e) => [Bt.fromIterable(e), e.length === r && e.length > 0 ? j.some(j.some(e[e.length - 1][n])) : j.none()]));
1997
2023
  });
1998
- }, ps = (e) => {
2024
+ }, Ls = (e) => {
1999
2025
  let t = e.alpha ?? .5;
2000
2026
  if (t < 0 || t > 1) throw Error(`hybridSearch: alpha must be in [0, 1], got ${t}`);
2001
2027
  return (n) => {
@@ -2009,7 +2035,7 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
2009
2035
  queryText: e.vector.query,
2010
2036
  distance: e.vector.distance ?? "cosine",
2011
2037
  alpha: t
2012
- }, i = me(n.table, e.fts.indexName, n.fullTextIndexes);
2038
+ }, i = g(n.table, e.fts.indexName, n.fullTextIndexes);
2013
2039
  return {
2014
2040
  ...n,
2015
2041
  annClause: r,
@@ -2022,17 +2048,17 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
2022
2048
  }
2023
2049
  };
2024
2050
  };
2025
- }, ms = async (e, t) => {
2051
+ }, Rs = async (e, t) => {
2026
2052
  let n = e.as ?? "embedding", r = t.row[e.from];
2027
2053
  if (typeof r != "string" || r.length === 0) return {};
2028
2054
  let i = await t.embed(r);
2029
2055
  return { [n]: i };
2030
- }, hs = (e) => {
2056
+ }, zs = (e) => {
2031
2057
  if (!Number.isInteger(e.dimensions) || e.dimensions <= 0) throw Error(`vectorEmbedding: dimensions must be a positive integer, got ${String(e.dimensions)}.`);
2032
- let t = e.as ?? "embedding", n = (t) => ms(e, t);
2033
- return it({
2058
+ let t = e.as ?? "embedding", n = (t) => Rs(e, t);
2059
+ return Ct({
2034
2060
  id: "voltro/vectorEmbedding",
2035
- fields: { [t]: pt(e.dimensions) },
2061
+ fields: { [t]: _t(e.dimensions) },
2036
2062
  ...e.index === !1 ? {} : { indexes: [{
2037
2063
  fields: [t],
2038
2064
  kind: "hnsw",
@@ -2047,19 +2073,19 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
2047
2073
  beforeUpdate: n
2048
2074
  }
2049
2075
  });
2050
- }, gs = 63, _s = "br_pr", Y = class extends Error {
2076
+ }, Bs = 63, Vs = "br_pr", Y = class extends Error {
2051
2077
  _tag = "BranchNameInvalid";
2052
2078
  constructor(e) {
2053
2079
  super(e), this.name = "BranchNameInvalid";
2054
2080
  }
2055
- }, vs = (e, t) => {
2081
+ }, Hs = (e, t) => {
2056
2082
  if (!Number.isInteger(t) || t < 0) throw new Y(`prNumber must be a non-negative integer, got ${String(t)}`);
2057
- let n = kr(e);
2083
+ let n = qr(e);
2058
2084
  if (n.replace(/_/g, "") === "") throw new Y(`app slug '${e}' has no usable identifier characters`);
2059
- let r = `${_s}${t}_${n}`;
2060
- if (r.length > gs) throw new Y(`branch namespace '${r}' exceeds the ${gs}-byte identifier limit — use a shorter app slug`);
2085
+ let r = `${Vs}${t}_${n}`;
2086
+ if (r.length > Bs) throw new Y(`branch namespace '${r}' exceeds the ${Bs}-byte identifier limit — use a shorter app slug`);
2061
2087
  return r;
2062
- }, ys = (e) => e.startsWith(_s), bs = {
2088
+ }, Us = (e) => e.startsWith(Vs), Ws = {
2063
2089
  requested: {
2064
2090
  provision: "provisioning",
2065
2091
  destroy: "destroying"
@@ -2078,18 +2104,18 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
2078
2104
  fail: "failed"
2079
2105
  },
2080
2106
  destroyed: {}
2081
- }, xs = class extends Error {
2107
+ }, Gs = class extends Error {
2082
2108
  from;
2083
2109
  event;
2084
2110
  _tag = "BranchTransitionInvalid";
2085
2111
  constructor(e, t) {
2086
2112
  super(`invalid branch transition: ${e} --${t}-->`), this.from = e, this.event = t, this.name = "BranchTransitionInvalid";
2087
2113
  }
2088
- }, Ss = (e, t) => {
2089
- let n = bs[e][t];
2090
- if (n === void 0) throw new xs(e, t);
2114
+ }, Ks = (e, t) => {
2115
+ let n = Ws[e][t];
2116
+ if (n === void 0) throw new Gs(e, t);
2091
2117
  return n;
2092
- }, Cs = (e, t, n, r, i = [], a = []) => {
2118
+ }, qs = (e, t, n, r, i = [], a = []) => {
2093
2119
  if (n === "copy" && (r === void 0 || r === "")) throw new Y("seed 'copy' requires a parentNamespace to snapshot from");
2094
2120
  let o = [{
2095
2121
  kind: "create-namespace",
@@ -2119,13 +2145,13 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
2119
2145
  kind: "seed",
2120
2146
  detail: `run boot seeds into ${e}`
2121
2147
  }), o;
2122
- }, ws = (e) => {
2123
- if (!ys(e)) throw new Y(`refusing to plan teardown of '${e}' — not a branch namespace`);
2148
+ }, Js = (e) => {
2149
+ if (!Us(e)) throw new Y(`refusing to plan teardown of '${e}' — not a branch namespace`);
2124
2150
  return [{
2125
2151
  kind: "drop-namespace",
2126
2152
  detail: e
2127
2153
  }];
2128
- }, Ts = (e) => {
2154
+ }, Ys = (e) => {
2129
2155
  if (e === void 0 || e === "") return !1;
2130
2156
  try {
2131
2157
  let t = new URL(e).hostname.toLowerCase();
@@ -2133,27 +2159,27 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
2133
2159
  } catch {
2134
2160
  return /\bneon\.(tech|build)\b/i.test(e);
2135
2161
  }
2136
- }, Es = (e) => e.prefer === void 0 ? e.seed === "copy" && Ts(e.dbUrl) ? "neon-cow" : "namespace" : e.prefer, Ds = (e, t = {}) => [{
2162
+ }, Xs = (e) => e.prefer === void 0 ? e.seed === "copy" && Ys(e.dbUrl) ? "neon-cow" : "namespace" : e.prefer, Zs = (e, t = {}) => [{
2137
2163
  kind: "neon-branch-create",
2138
2164
  detail: `${t.parentBranch ?? "main"} → ${e} (copy-on-write)`
2139
- }], Os = (e) => {
2140
- if (!ys(e)) throw new Y(`refusing to plan teardown of '${e}' — not a branch namespace`);
2165
+ }], Qs = (e) => {
2166
+ if (!Us(e)) throw new Y(`refusing to plan teardown of '${e}' — not a branch namespace`);
2141
2167
  return [{
2142
2168
  kind: "neon-branch-delete",
2143
2169
  detail: e
2144
2170
  }];
2145
- }, ks = (e) => e.mechanism === "neon-cow" ? Ds(e.branchId, e.neonParentBranch === void 0 ? {} : { parentBranch: e.neonParentBranch }) : Cs(e.branchId, e.tableNames, e.seed, e.parentNamespace, e.foreignKeys, e.indexNames), As = (e, t) => e === "neon-cow" ? Os(t) : ws(t), js = (e, t, n) => {
2171
+ }, $s = (e) => e.mechanism === "neon-cow" ? Zs(e.branchId, e.neonParentBranch === void 0 ? {} : { parentBranch: e.neonParentBranch }) : qs(e.branchId, e.tableNames, e.seed, e.parentNamespace, e.foreignKeys, e.indexNames), ec = (e, t) => e === "neon-cow" ? Qs(t) : Js(t), tc = (e, t, n) => {
2146
2172
  let r = e.filter((e) => e.state !== "destroyed" && e.state !== "destroying"), i = r.filter((e) => n - e.createdAtMs > t.ttlMs).map((e) => e.namespace), a = new Set(i);
2147
2173
  return {
2148
2174
  evict: i,
2149
2175
  rejectNew: r.filter((e) => !a.has(e.namespace)).length >= t.maxBranches
2150
2176
  };
2151
- }, Ms = async (e, t) => {
2152
- let n = vs(e.appSlug, e.prNumber), r = Es({
2177
+ }, nc = async (e, t) => {
2178
+ let n = Hs(e.appSlug, e.prNumber), r = Xs({
2153
2179
  seed: e.seed,
2154
2180
  ...e.dbUrl === void 0 ? {} : { dbUrl: e.dbUrl },
2155
2181
  ...e.prefer === void 0 ? {} : { prefer: e.prefer }
2156
- }), i = ks({
2182
+ }), i = $s({
2157
2183
  mechanism: r,
2158
2184
  branchId: n,
2159
2185
  tableNames: e.tableNames,
@@ -2182,15 +2208,15 @@ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = async (e, t, n
2182
2208
  mechanism: r,
2183
2209
  steps: i
2184
2210
  };
2185
- }, Ns = async (e, t, n) => {
2186
- let r = As(t, e);
2211
+ }, rc = async (e, t, n) => {
2212
+ let r = ec(t, e);
2187
2213
  return t === "neon-cow" ? await n.neonBranchDelete(e) : await n.dropNamespace(e), r;
2188
- }, Ps = (e, t, n) => js(e, t, n), X = (e) => `"${e.replace(/"/g, "\"\"")}"`, Fs = {
2214
+ }, ic = (e, t, n) => tc(e, t, n), X = (e) => `"${e.replace(/"/g, "\"\"")}"`, ac = {
2189
2215
  cascade: "CASCADE",
2190
2216
  restrict: "RESTRICT",
2191
2217
  setNull: "SET NULL",
2192
2218
  noAction: "NO ACTION"
2193
- }, Z = (e) => `'${e.replace(/'/g, "''")}'`, Is = (e, t) => {
2219
+ }, Z = (e) => `'${e.replace(/'/g, "''")}'`, oc = (e, t) => {
2194
2220
  let n = t.columns.map(Z).join(", ");
2195
2221
  return `DO $voltro_branch$
2196
2222
  DECLARE derived name;
@@ -2217,10 +2243,10 @@ BEGIN
2217
2243
  END IF;
2218
2244
  END
2219
2245
  $voltro_branch$`;
2220
- }, Ls = (e, t) => {
2221
- let n = t.onDelete === void 0 ? "" : ` ON DELETE ${Fs[t.onDelete]}`, r = t.onUpdate === void 0 ? "" : ` ON UPDATE ${Fs[t.onUpdate]}`;
2246
+ }, sc = (e, t) => {
2247
+ let n = t.onDelete === void 0 ? "" : ` ON DELETE ${ac[t.onDelete]}`, r = t.onUpdate === void 0 ? "" : ` ON UPDATE ${ac[t.onUpdate]}`;
2222
2248
  return `ALTER TABLE ${X(e)}.${X(t.table)} ADD FOREIGN KEY (${X(t.column)}) REFERENCES ${X(e)}.${X(t.targetTable)} (${X(t.targetColumn)})${n}${r}`;
2223
- }, Rs = (e) => {
2249
+ }, cc = (e) => {
2224
2250
  let t = () => {
2225
2251
  throw Error("namespace branch executor: Neon ops require a neon-cow executor (use a Neon connection for copy-on-write branches)");
2226
2252
  };
@@ -2228,24 +2254,24 @@ $voltro_branch$`;
2228
2254
  createNamespace: (t) => e.run(`CREATE SCHEMA IF NOT EXISTS ${X(t)}`),
2229
2255
  createTable: (t, n) => e.run(`CREATE TABLE IF NOT EXISTS ${X(t)}.${X(n)} (LIKE ${X(n)} INCLUDING ALL)`),
2230
2256
  copyTable: (t, n, r) => e.run(`INSERT INTO ${X(n)}.${X(r)} SELECT * FROM ${X(t)}.${X(r)}`),
2231
- addForeignKey: (t, n) => e.run(Ls(t, n)),
2232
- restoreIndexName: (t, n) => e.run(Is(t, n)),
2257
+ addForeignKey: (t, n) => e.run(sc(t, n)),
2258
+ restoreIndexName: (t, n) => e.run(oc(t, n)),
2233
2259
  dropNamespace: (t) => e.run(`DROP SCHEMA IF EXISTS ${X(t)} CASCADE`),
2234
2260
  neonBranchCreate: t,
2235
2261
  neonBranchDelete: t
2236
2262
  };
2237
- }, zs = class extends Error {
2263
+ }, lc = class extends Error {
2238
2264
  _tag = "TenantResidencyUnresolved";
2239
2265
  constructor(e) {
2240
2266
  super(e), this.name = "TenantResidencyUnresolved";
2241
2267
  }
2242
- }, Bs = class extends Error {
2268
+ }, uc = class extends Error {
2243
2269
  region;
2244
2270
  _tag = "TenantRegionUnavailable";
2245
2271
  constructor(e, t) {
2246
2272
  super(t), this.region = e, this.name = "TenantRegionUnavailable";
2247
2273
  }
2248
- }, Vs, Hs = (e) => {
2274
+ }, dc, fc = (e) => {
2249
2275
  if (e.homes === void 0) throw Error("setResidencyConfig: `homes` is required");
2250
2276
  if (e.servableRegions === void 0 || e.servableRegions.length === 0) throw Error("setResidencyConfig: `servableRegions` must be non-empty (which regions this deployment serves)");
2251
2277
  let t = /* @__PURE__ */ new Map();
@@ -2254,55 +2280,55 @@ $voltro_branch$`;
2254
2280
  if (e !== void 0 && e !== n.region) throw Error(`residency: tenant '${n.tenantId}' is mapped to two regions ('${e}' and '${n.region}')`);
2255
2281
  t.set(n.tenantId, n.region);
2256
2282
  }
2257
- return Vs = e, e;
2258
- }, Us = () => Vs, Ws = () => {
2259
- Vs = void 0;
2260
- }, Gs = (e, t) => {
2261
- if (e == null || e === "") throw new zs("residency is on but the request has no resolvable tenant — refusing to bind a store");
2283
+ return dc = e, e;
2284
+ }, pc = () => dc, mc = () => {
2285
+ dc = void 0;
2286
+ }, hc = (e, t) => {
2287
+ if (e == null || e === "") throw new lc("residency is on but the request has no resolvable tenant — refusing to bind a store");
2262
2288
  let n = t.homes.find((t) => t.tenantId === e);
2263
- if (n === void 0) throw new zs(`no residency home is mapped for tenant '${e}' — refusing to fall back to a default store (would be a residency violation)`);
2289
+ if (n === void 0) throw new lc(`no residency home is mapped for tenant '${e}' — refusing to fall back to a default store (would be a residency violation)`);
2264
2290
  return n;
2265
- }, Ks = (e, t) => t.servableRegions.includes(e), qs = (e, t) => {
2266
- let n = Gs(e.tenantId, t), r = Ar(n.tenantId);
2291
+ }, gc = (e, t) => t.servableRegions.includes(e), _c = (e, t) => {
2292
+ let n = hc(e.tenantId, t), r = Jr(n.tenantId);
2267
2293
  return {
2268
2294
  region: n.region,
2269
2295
  namespace: r,
2270
2296
  ...n.connectionKey === void 0 ? {} : { connectionKey: n.connectionKey }
2271
2297
  };
2272
- }, Js = (e, t, n) => {
2273
- let r = qs(e, t);
2274
- if (!Ks(r.region, t)) throw new Bs(r.region, `tenant homed in region '${r.region}', which this deployment does not serve — route to the home region`);
2298
+ }, vc = (e, t, n) => {
2299
+ let r = _c(e, t);
2300
+ if (!gc(r.region, t)) throw new uc(r.region, `tenant homed in region '${r.region}', which this deployment does not serve — route to the home region`);
2275
2301
  let i = n.get(r.region);
2276
- if (i === void 0) throw new Bs(r.region, `no store handle for home region '${r.region}' (declared servable but not wired) — failing closed`);
2302
+ if (i === void 0) throw new uc(r.region, `no store handle for home region '${r.region}' (declared servable but not wired) — failing closed`);
2277
2303
  return {
2278
2304
  store: i,
2279
2305
  placement: r
2280
2306
  };
2281
- }, Ys = async (e, t, n, r) => {
2282
- let { store: i, placement: a } = Js(e, t, n);
2307
+ }, yc = async (e, t, n, r) => {
2308
+ let { store: i, placement: a } = vc(e, t, n);
2283
2309
  return await r(i, a), a;
2284
- }, Xs = (e) => {
2310
+ }, bc = (e) => {
2285
2311
  if (typeof e == "string") return e;
2286
2312
  if ("jsonPath" in e) {
2287
2313
  let { column: t, path: n, numeric: r } = e.jsonPath;
2288
2314
  return `(json:${t}->${n.join(".")}${r ? "::num" : ""})`;
2289
2315
  }
2290
2316
  return `(${e.expr})`;
2291
- }, Q = (e) => e.map(Xs), Zs = (e, t) => {
2317
+ }, Q = (e) => e.map(bc), xc = (e, t) => {
2292
2318
  if (e.length !== t.length) return !1;
2293
- for (let n = 0; n < e.length; n++) if (Xs(e[n]) !== Xs(t[n])) return !1;
2319
+ for (let n = 0; n < e.length; n++) if (bc(e[n]) !== bc(t[n])) return !1;
2294
2320
  return !0;
2295
- }, Qs = (e, t) => {
2321
+ }, Sc = (e, t) => {
2296
2322
  if (e.length >= t.length) return !1;
2297
- for (let n = 0; n < e.length; n++) if (Xs(e[n]) !== Xs(t[n])) return !1;
2323
+ for (let n = 0; n < e.length; n++) if (bc(e[n]) !== bc(t[n])) return !1;
2298
2324
  return !0;
2299
- }, $s = (e) => {
2325
+ }, Cc = (e) => {
2300
2326
  let t = [], n = e.appliedIndexes, r = e.tableName;
2301
2327
  for (let e = 0; e < n.length; e++) {
2302
2328
  let i = n[e];
2303
2329
  for (let a = e + 1; a < n.length; a++) {
2304
2330
  let e = n[a];
2305
- if (Zs(i.fields, e.fields)) {
2331
+ if (xc(i.fields, e.fields)) {
2306
2332
  let [n, a] = i.name < e.name ? [i, e] : [e, i];
2307
2333
  t.push({
2308
2334
  kind: "duplicate-fields",
@@ -2313,13 +2339,13 @@ $voltro_branch$`;
2313
2339
  });
2314
2340
  continue;
2315
2341
  }
2316
- Qs(i.fields, e.fields) ? t.push({
2342
+ Sc(i.fields, e.fields) ? t.push({
2317
2343
  kind: "redundant-prefix",
2318
2344
  table: r,
2319
2345
  redundant: i,
2320
2346
  coveredBy: e,
2321
2347
  message: `'${r}' index '${i.name}' on [${Q(i.fields).join(", ")}] is a leading prefix of '${e.name}' on [${Q(e.fields).join(", ")}]. Every B-tree dialect we support (Postgres / MySQL / MariaDB / MSSQL / SQLite) can serve a [${Q(i.fields).join(", ")}] query from '${e.name}' too via the leading-prefix rule, so '${i.name}' adds write cost without read benefit. Drop '${i.name}' — unless you specifically need a smaller index for cache locality on a write-heavy table (rare; profile first).`
2322
- }) : Qs(e.fields, i.fields) && t.push({
2348
+ }) : Sc(e.fields, i.fields) && t.push({
2323
2349
  kind: "redundant-prefix",
2324
2350
  table: r,
2325
2351
  redundant: e,
@@ -2329,23 +2355,23 @@ $voltro_branch$`;
2329
2355
  }
2330
2356
  }
2331
2357
  return t;
2332
- }, ec = (e) => {
2358
+ }, wc = (e) => {
2333
2359
  let t = [];
2334
- for (let n of e) t.push(...$s(n));
2360
+ for (let n of e) t.push(...Cc(n));
2335
2361
  return t;
2336
- }, tc = "\x1B[", nc = `${tc}38;2;245;158;11m`, rc = `${tc}38;2;16;185;129m`, ic = (e, t) => `${e}${t}${j.reset}`, $ = (e, t, n) => e ? typeof t == "function" ? t(n) : ic(t, n) : n, ac = (e, t = {}) => {
2337
- let n = t.color ?? !0, r = t.indent ?? " ", i = (e) => $(n, j.dim, e.padEnd(11)), a = (e) => $(n, (e) => j.bold(j.brand(e)), e), o = (e) => $(n, j.brightRed24, e), s = (e) => $(n, rc, e), c = (e) => $(n, nc, e), l = (e) => $(n, j.dim, e), u = `${c("index audit")} ${l("·")} ${$(n, j.bold, e.kind)}`, d = e.redundant.fields.length, f = Q(e.coveredBy.fields.slice(d)), p = (e, t) => {
2362
+ }, Tc = "\x1B[", Ec = `${Tc}38;2;245;158;11m`, Dc = `${Tc}38;2;16;185;129m`, Oc = (e, t) => `${e}${t}${N.reset}`, $ = (e, t, n) => e ? typeof t == "function" ? t(n) : Oc(t, n) : n, kc = (e, t = {}) => {
2363
+ let n = t.color ?? !0, r = t.indent ?? " ", i = (e) => $(n, N.dim, e.padEnd(11)), a = (e) => $(n, (e) => N.bold(N.brand(e)), e), o = (e) => $(n, N.brightRed24, e), s = (e) => $(n, Dc, e), c = (e) => $(n, Ec, e), l = (e) => $(n, N.dim, e), u = `${c("index audit")} ${l("·")} ${$(n, N.bold, e.kind)}`, d = e.redundant.fields.length, f = Q(e.coveredBy.fields.slice(d)), p = (e, t) => {
2338
2364
  let n = e.slice(0, t), r = e.slice(t), i = [];
2339
2365
  return n.length > 0 && i.push(s(`[${n.join(", ")}]`)), r.length > 0 && i.push(c(`+ [${r.join(", ")}]`)), i.join(" ");
2340
2366
  }, m = [];
2341
- return m.push(u), m.push(""), m.push(`${i("table")}${a(e.table)}`), m.push(""), m.push(`${i("redundant")}${o(e.redundant.name)}`), m.push(`${i("")}${p(Q(e.redundant.fields), d)}`), m.push(""), m.push(`${i("covered by")}${s(e.coveredBy.name)}`), m.push(`${i("")}${p(Q(e.coveredBy.fields), d)}`), f.length > 0 && m.push(`${i("")}${l(`└ extra columns: ${f.join(", ")}`)}`), m.push(""), e.kind === "redundant-prefix" ? (m.push(`${i("why")}B-tree indexes serve queries that filter on a LEADING PREFIX of`), m.push(`${i("")}their column list. The wider index already covers every`), m.push(`${i("")}query the narrower one can serve.`), m.push(`${i("")}${l("Same rule on Postgres / MySQL / MariaDB / MSSQL / SQLite.")}`)) : (m.push(`${i("why")}Two indexes on the same columns under different names.`), m.push(`${i("")}The B-tree engine builds both — same coverage, double cost.`), m.push(`${i("")}${l("Same rule on Postgres / MySQL / MariaDB / MSSQL / SQLite.")}`)), m.push(""), m.push(`${i("cost")}Every ${a("INSERT")} / ${a("UPDATE")} / ${a("DELETE")} on this table writes`), m.push(`${i("")}to ${$(n, j.bold, "both")} B-trees. Pure write overhead, zero read benefit.`), m.push(""), m.push(`${i("fix")}Drop ${o(e.redundant.name)}`), m.push(`${i("")}${l("Keep only if profiling shows the smaller index gives a")}`), m.push(`${i("")}${l("measurable cache-locality boost on a write-heavy hot path.")}`), m.push(`${i("")}${l("Silence with VOLTRO_INDEX_AUDIT=off if intentional.")}`), m.map((e) => `${r}${e}`).join("\n");
2342
- }, oc = (e, { apply: t, undo: n }) => ({
2367
+ return m.push(u), m.push(""), m.push(`${i("table")}${a(e.table)}`), m.push(""), m.push(`${i("redundant")}${o(e.redundant.name)}`), m.push(`${i("")}${p(Q(e.redundant.fields), d)}`), m.push(""), m.push(`${i("covered by")}${s(e.coveredBy.name)}`), m.push(`${i("")}${p(Q(e.coveredBy.fields), d)}`), f.length > 0 && m.push(`${i("")}${l(`└ extra columns: ${f.join(", ")}`)}`), m.push(""), e.kind === "redundant-prefix" ? (m.push(`${i("why")}B-tree indexes serve queries that filter on a LEADING PREFIX of`), m.push(`${i("")}their column list. The wider index already covers every`), m.push(`${i("")}query the narrower one can serve.`), m.push(`${i("")}${l("Same rule on Postgres / MySQL / MariaDB / MSSQL / SQLite.")}`)) : (m.push(`${i("why")}Two indexes on the same columns under different names.`), m.push(`${i("")}The B-tree engine builds both — same coverage, double cost.`), m.push(`${i("")}${l("Same rule on Postgres / MySQL / MariaDB / MSSQL / SQLite.")}`)), m.push(""), m.push(`${i("cost")}Every ${a("INSERT")} / ${a("UPDATE")} / ${a("DELETE")} on this table writes`), m.push(`${i("")}to ${$(n, N.bold, "both")} B-trees. Pure write overhead, zero read benefit.`), m.push(""), m.push(`${i("fix")}Drop ${o(e.redundant.name)}`), m.push(`${i("")}${l("Keep only if profiling shows the smaller index gives a")}`), m.push(`${i("")}${l("measurable cache-locality boost on a write-heavy hot path.")}`), m.push(`${i("")}${l("Silence with VOLTRO_INDEX_AUDIT=off if intentional.")}`), m.map((e) => `${r}${e}`).join("\n");
2368
+ }, Ac = (e, { apply: t, undo: n }) => ({
2343
2369
  name: e,
2344
2370
  apply: t,
2345
2371
  undo: n
2346
- }), sc = (e) => {
2372
+ }), jc = (e) => {
2347
2373
  if (!/^\d{14}_/.test(e.id)) throw Error(`migration "${e.id}": id must start with a 14-digit timestamp followed by "_" (convention: <YYYYMMDDHHMMSS>_<slug>)`);
2348
- let t = e.steps({ step: oc });
2374
+ let t = e.steps({ step: Ac });
2349
2375
  if (t.length === 0) throw Error(`migration "${e.id}": at least one step is required`);
2350
2376
  return {
2351
2377
  __migration: !0,
@@ -2353,106 +2379,106 @@ $voltro_branch$`;
2353
2379
  name: e.name,
2354
2380
  steps: t
2355
2381
  };
2356
- }, cc = (e) => typeof e == "object" && !!e && "__migration" in e && e.__migration === !0, lc = T("_voltro_migrations", {
2357
- id: _({ prefix: "mig" }),
2358
- name: t(),
2359
- hash: t(),
2360
- status: t(),
2361
- appliedAt: C().nullable(),
2362
- durationMs: S().nullable(),
2363
- errorMessage: t().nullable(),
2364
- errorStack: t().nullable(),
2365
- workflowRunId: t().nullable(),
2366
- createdAt: C().default("now"),
2367
- updatedAt: C().default("now").onUpdate("now")
2368
- }).index(["status"]), uc = T("_voltro_seeds", {
2369
- id: _({ prefix: "seed" }),
2370
- name: t(),
2371
- lifecycle: t(),
2372
- fingerprint: t(),
2373
- cronSchedule: t().nullable(),
2374
- watchedTables: h().nullable(),
2375
- nextRunAt: C().nullable(),
2376
- lastRunStatus: t().nullable(),
2377
- lastRunAt: C().nullable(),
2378
- lastRunDurationMs: S().nullable(),
2379
- lastRunRowsTouched: S().nullable(),
2380
- lastError: t().nullable(),
2381
- workflowRunId: t().nullable(),
2382
- createdAt: C().default("now"),
2383
- updatedAt: C().default("now").onUpdate("now")
2384
- }).index(["lifecycle"]).index(["nextRunAt"]), dc = T("_voltro_migration_plans", {
2385
- id: _({ prefix: "plan" }),
2386
- fingerprint: t(),
2387
- liveFingerprint: t().nullable(),
2388
- operations: h(),
2389
- rollbackPlan: h().nullable(),
2390
- appliedBy: t(),
2391
- environment: t(),
2392
- source: t(),
2393
- onlineStrategy: t().nullable(),
2394
- durationMs: S(),
2395
- notes: t().nullable(),
2396
- squashedAt: C().nullable(),
2397
- appliedAt: C().default("now"),
2398
- createdAt: C().default("now"),
2399
- updatedAt: C().default("now").onUpdate("now")
2400
- }).index(["fingerprint"]).index(["environment"]), fc = T("_voltro_idempotency", {
2401
- id: _({ prefix: "idem" }),
2402
- scope: t(),
2403
- key: t(),
2404
- status: t(),
2405
- response: h().nullable(),
2406
- createdAt: C().default("now")
2407
- }).unique(["scope", "key"]).index(["createdAt"]), pc = T("_voltro_kv", {
2408
- id: _({ prefix: "kv" }),
2409
- key: t().unique(),
2410
- value: t().nullable(),
2411
- expiresAt: C().nullable(),
2412
- createdAt: C().default("now"),
2413
- updatedAt: C().default("now").onUpdate("now")
2414
- }).index(["expiresAt"]), mc = T("_voltro_api_keys", {
2415
- id: _({ prefix: "apikey" }),
2416
- tenantId: t().nullable(),
2417
- name: t(),
2418
- hashedKey: t().maxLength(64).unique(),
2419
- keyPrefix: t(),
2420
- scopes: h().nullable(),
2421
- lastUsedAt: C().nullable(),
2422
- requestCount: S().default(0),
2423
- expiresAt: C().nullable(),
2424
- revokedAt: C().nullable(),
2425
- createdBy: t().nullable(),
2426
- onBehalfOf: t().nullable(),
2427
- metadata: h().nullable(),
2428
- createdAt: C().default("now")
2429
- }).index("byApiKeyTenant", ["tenantId"]), hc = T("_voltro_replica_observations", {
2430
- id: _({ prefix: "robs" }),
2431
- replicaId: t().maxLength(191),
2432
- startedAt: C(),
2433
- version: t().maxLength(64).nullable(),
2434
- kind: t().maxLength(64),
2435
- payload: t().nullable(),
2436
- reachableAt: t().maxLength(255).nullable(),
2437
- writtenAt: C().default("now").onUpdate("now")
2438
- }).unique(["replicaId", "kind"]).index(["kind"]), gc = [
2439
- lc,
2440
- uc,
2441
- dc
2442
- ], _c = "_voltro_replace_in_progress", vc = T(_c, {
2443
- id: _({ prefix: "repl" }),
2444
- startedAt: C().default("now"),
2445
- kind: t().default("replace"),
2446
- tables: t().nullable(),
2447
- capture: t().nullable(),
2448
- via: t(),
2449
- staging: t().nullable(),
2450
- heartbeatAt: C().nullable(),
2451
- resumable: r().nullable()
2452
- }), yc = 30, bc = (e, t) => {
2382
+ }, Mc = (e) => typeof e == "object" && !!e && "__migration" in e && e.__migration === !0, Nc = w("_voltro_migrations", {
2383
+ id: E({ prefix: "mig" }),
2384
+ name: C(),
2385
+ hash: C(),
2386
+ status: C(),
2387
+ appliedAt: T().nullable(),
2388
+ durationMs: _().nullable(),
2389
+ errorMessage: C().nullable(),
2390
+ errorStack: C().nullable(),
2391
+ workflowRunId: C().nullable(),
2392
+ createdAt: T().default("now"),
2393
+ updatedAt: T().default("now").onUpdate("now")
2394
+ }).index(["status"]), Pc = w("_voltro_seeds", {
2395
+ id: E({ prefix: "seed" }),
2396
+ name: C(),
2397
+ lifecycle: C(),
2398
+ fingerprint: C(),
2399
+ cronSchedule: C().nullable(),
2400
+ watchedTables: x().nullable(),
2401
+ nextRunAt: T().nullable(),
2402
+ lastRunStatus: C().nullable(),
2403
+ lastRunAt: T().nullable(),
2404
+ lastRunDurationMs: _().nullable(),
2405
+ lastRunRowsTouched: _().nullable(),
2406
+ lastError: C().nullable(),
2407
+ workflowRunId: C().nullable(),
2408
+ createdAt: T().default("now"),
2409
+ updatedAt: T().default("now").onUpdate("now")
2410
+ }).index(["lifecycle"]).index(["nextRunAt"]), Fc = w("_voltro_migration_plans", {
2411
+ id: E({ prefix: "plan" }),
2412
+ fingerprint: C(),
2413
+ liveFingerprint: C().nullable(),
2414
+ operations: x(),
2415
+ rollbackPlan: x().nullable(),
2416
+ appliedBy: C(),
2417
+ environment: C(),
2418
+ source: C(),
2419
+ onlineStrategy: C().nullable(),
2420
+ durationMs: _(),
2421
+ notes: C().nullable(),
2422
+ squashedAt: T().nullable(),
2423
+ appliedAt: T().default("now"),
2424
+ createdAt: T().default("now"),
2425
+ updatedAt: T().default("now").onUpdate("now")
2426
+ }).index(["fingerprint"]).index(["environment"]), Ic = w("_voltro_idempotency", {
2427
+ id: E({ prefix: "idem" }),
2428
+ scope: C(),
2429
+ key: C(),
2430
+ status: C(),
2431
+ response: x().nullable(),
2432
+ createdAt: T().default("now")
2433
+ }).unique(["scope", "key"]).index(["createdAt"]), Lc = w("_voltro_kv", {
2434
+ id: E({ prefix: "kv" }),
2435
+ key: C().unique(),
2436
+ value: C().nullable(),
2437
+ expiresAt: T().nullable(),
2438
+ createdAt: T().default("now"),
2439
+ updatedAt: T().default("now").onUpdate("now")
2440
+ }).index(["expiresAt"]), Rc = w("_voltro_api_keys", {
2441
+ id: E({ prefix: "apikey" }),
2442
+ tenantId: C().nullable(),
2443
+ name: C(),
2444
+ hashedKey: C().maxLength(64).unique(),
2445
+ keyPrefix: C(),
2446
+ scopes: x().nullable(),
2447
+ lastUsedAt: T().nullable(),
2448
+ requestCount: _().default(0),
2449
+ expiresAt: T().nullable(),
2450
+ revokedAt: T().nullable(),
2451
+ createdBy: C().nullable(),
2452
+ onBehalfOf: C().nullable(),
2453
+ metadata: x().nullable(),
2454
+ createdAt: T().default("now")
2455
+ }).index("byApiKeyTenant", ["tenantId"]), zc = w("_voltro_replica_observations", {
2456
+ id: E({ prefix: "robs" }),
2457
+ replicaId: C().maxLength(191),
2458
+ startedAt: T(),
2459
+ version: C().maxLength(64).nullable(),
2460
+ kind: C().maxLength(64),
2461
+ payload: C().nullable(),
2462
+ reachableAt: C().maxLength(255).nullable(),
2463
+ writtenAt: T().default("now").onUpdate("now")
2464
+ }).unique(["replicaId", "kind"]).index(["kind"]), Bc = [
2465
+ Nc,
2466
+ Pc,
2467
+ Fc
2468
+ ], Vc = "_voltro_replace_in_progress", Hc = w(Vc, {
2469
+ id: E({ prefix: "repl" }),
2470
+ startedAt: T().default("now"),
2471
+ kind: C().default("replace"),
2472
+ tables: C().nullable(),
2473
+ capture: C().nullable(),
2474
+ via: C(),
2475
+ staging: C().nullable(),
2476
+ heartbeatAt: T().nullable(),
2477
+ resumable: p().nullable()
2478
+ }), Uc = 30, Wc = (e, t) => {
2453
2479
  let n = typeof t == "number" && Number.isFinite(t) && t > 0 ? t : 30, r = Number(e.VOLTRO_STAGING_STALE_MINUTES);
2454
2480
  return (Number.isFinite(r) && r > 0 ? r : n) * 6e4;
2455
- }, xc = (e) => e == null || String(e).length === 0 ? [] : String(e).split(",").map((e) => e.trim()).filter((e) => e.length > 0), Sc = (e) => {
2481
+ }, Gc = (e) => e == null || String(e).length === 0 ? [] : String(e).split(",").map((e) => e.trim()).filter((e) => e.length > 0), Kc = (e) => {
2456
2482
  let t = e.filter((e) => e.kind !== "staging");
2457
2483
  if (t.length !== 0) return `refusing to start: a destructive data operation did not finish.
2458
2484
  ${t.map((e) => {
@@ -2467,7 +2493,7 @@ ${t.map((e) => {
2467
2493
 
2468
2494
  When the data is back, or you have decided the current state is correct, clear the marker:
2469
2495
  voltro data clear-replace-marker --yes`;
2470
- }, Cc = (e, t, n) => {
2496
+ }, qc = (e, t, n) => {
2471
2497
  let r = e.filter((e) => e.kind === "staging");
2472
2498
  return {
2473
2499
  all: r,
@@ -2477,7 +2503,7 @@ ${t.map((e) => {
2477
2503
  return Number.isFinite(r) ? t - r >= n : !1;
2478
2504
  })
2479
2505
  };
2480
- }, wc = (e, t) => {
2506
+ }, Jc = (e, t) => {
2481
2507
  if (e.all.length === 0) return;
2482
2508
  let n = new Set(e.droppable.map((e) => e.id));
2483
2509
  return `staged data-import leftovers:
@@ -2486,22 +2512,22 @@ ${e.all.map((e) => {
2486
2512
  return n.has(e.id) ? ` - ${a} — DROPPED: the run is not resumable and has been silent long enough that nothing is loading into them.` : e.resumable ? ` - ${a} — KEPT: the run was started \`--no-atomic\`, so these ARE its resume point. Re-run the same\n bundle to continue from them, or drop them with: voltro data clear-staging --yes` : ` - ${a} — KEPT: still beating, so an import is loading into them right now.`;
2487
2513
  }).join("\n")}\n The target of a staged \`replace\` is untouched until one short swap at the end, so none of this is
2488
2514
  a reason to refuse the boot — it is a reason to know the disk is holding a copy of a bundle.`;
2489
- }, Tc = "id", Ec = (e, t) => {
2490
- let n = E(e);
2515
+ }, Yc = "id", Xc = (e, t) => {
2516
+ let n = S(e);
2491
2517
  if (n === void 0) return t;
2492
- let r = n.fields[Tc]?.idScheme;
2493
- if (r === void 0 || t[Tc] != null) return t;
2518
+ let r = n.fields[Yc]?.idScheme;
2519
+ if (r === void 0 || t[Yc] != null) return t;
2494
2520
  if (r.kind === "numeric") {
2495
- if (!(Tc in t)) return t;
2521
+ if (!(Yc in t)) return t;
2496
2522
  let e = { ...t };
2497
- return delete e[Tc], e;
2523
+ return delete e[Yc], e;
2498
2524
  }
2499
- let i = gt(r, e);
2525
+ let i = it(r, e);
2500
2526
  return i === null ? t : {
2501
2527
  ...t,
2502
- [Tc]: i
2528
+ [Yc]: i
2503
2529
  };
2504
- }, Dc = (e, t) => t.map((t) => Ec(e, t)), Oc = {
2530
+ }, Zc = (e, t) => t.map((t) => Xc(e, t)), Qc = {
2505
2531
  postgres: { maxBindParameters: 65535 },
2506
2532
  mysql: { maxBindParameters: 65535 },
2507
2533
  mariadb: { maxBindParameters: 65535 },
@@ -2511,25 +2537,25 @@ ${e.all.map((e) => {
2511
2537
  },
2512
2538
  sqlite: { maxBindParameters: 32766 },
2513
2539
  turso: { maxBindParameters: 32766 }
2514
- }, kc = (e) => Oc[e], Ac = (e) => {
2540
+ }, $c = (e) => Qc[e], el = (e) => {
2515
2541
  let t = /* @__PURE__ */ new Set();
2516
2542
  for (let n of e) for (let e of Object.keys(n)) t.add(e);
2517
2543
  return t.size;
2518
- }, jc = (e, t) => {
2544
+ }, tl = (e, t) => {
2519
2545
  if (t === void 0 || e.length === 0) return [e];
2520
- let n = Math.max(1, Ac(e)), r = Math.floor(t.maxBindParameters / n), i = t.maxRowsPerStatement ?? Infinity, a = Math.max(1, Math.min(r, i));
2546
+ let n = Math.max(1, el(e)), r = Math.floor(t.maxBindParameters / n), i = t.maxRowsPerStatement ?? Infinity, a = Math.max(1, Math.min(r, i));
2521
2547
  if (e.length <= a) return [e];
2522
2548
  let o = [];
2523
2549
  for (let t = 0; t < e.length; t += a) o.push(e.slice(t, t + a));
2524
2550
  return o;
2525
- }, Mc = (e, t) => {
2551
+ }, nl = (e, t) => {
2526
2552
  let n = [], r = t;
2527
2553
  for (let [t, i] of Object.entries(e.fields)) {
2528
2554
  let e = i;
2529
2555
  e.nullable || e.hasDefault || e.idScheme !== void 0 || e.generatedAs !== void 0 || (r[t] === void 0 || r[t] === null) && n.push(t);
2530
2556
  }
2531
2557
  return n;
2532
- }, Nc = (e, t, n) => {
2558
+ }, rl = (e, t, n) => {
2533
2559
  let r = n, i = new Set(e === void 0 ? [] : Object.entries(e.fields).filter(([, e]) => e.generatedAs !== void 0).map(([e]) => e)), a = [];
2534
2560
  for (let e of t) i.has(e) || (r[e] === void 0 ? a.push({
2535
2561
  column: e,
@@ -2539,28 +2565,28 @@ ${e.all.map((e) => {
2539
2565
  reason: "null"
2540
2566
  }));
2541
2567
  return a;
2542
- }, Pc = (e, t, n) => e.insert(t.tableName, n), Fc = (e, t, n, r) => e.upsert(t.tableName, n, {
2568
+ }, il = (e, t, n) => e.insert(t.tableName, n), al = (e, t, n, r) => e.upsert(t.tableName, n, {
2543
2569
  conflictColumns: r.conflictColumns,
2544
2570
  ...r.update === void 0 ? {} : { update: r.update }
2545
- }), Ic = (e, t, n, r) => e.updateMany(t.tableName, n, { where: r.where }), Lc = 512, Rc = (e) => {
2571
+ }), ol = (e, t, n, r) => e.updateMany(t.tableName, n, { where: r.where }), sl = 512, cl = (e) => {
2546
2572
  e.setMaxListeners(512);
2547
- }, zc = (e, t, n) => ({
2573
+ }, ll = (e, t, n) => ({
2548
2574
  _tag: "PrimaryKeyConflictError",
2549
2575
  table: e,
2550
2576
  key: t,
2551
2577
  cause: n
2552
- }), Bc = (e) => typeof e == "object" && !!e && e._tag === "PrimaryKeyConflictError", Vc = {
2578
+ }), ul = (e) => typeof e == "object" && !!e && e._tag === "PrimaryKeyConflictError", dl = {
2553
2579
  postgres: 5432,
2554
2580
  mysql: 3306,
2555
2581
  mariadb: 3306,
2556
2582
  mssql: 1433
2557
- }, Hc = /* @__PURE__ */ new Set([
2583
+ }, fl = /* @__PURE__ */ new Set([
2558
2584
  "localhost",
2559
2585
  "127.0.0.1",
2560
2586
  "::1",
2561
2587
  "[::1]",
2562
2588
  "0.0.0.0"
2563
- ]), Uc = (e) => {
2589
+ ]), pl = (e) => {
2564
2590
  let t = e.host, n = e.port, r = e.database;
2565
2591
  if (e.url !== void 0 && e.url !== "") try {
2566
2592
  let i = new URL(e.url);
@@ -2569,29 +2595,29 @@ ${e.all.map((e) => {
2569
2595
  return;
2570
2596
  }
2571
2597
  if (t === void 0 || t === "" || r === void 0 || r === "") return;
2572
- let i = n ?? Vc[(e.dialect ?? "").toLowerCase()];
2598
+ let i = n ?? dl[(e.dialect ?? "").toLowerCase()];
2573
2599
  if (i === void 0 || !Number.isFinite(i)) return;
2574
2600
  let a = t.toLowerCase();
2575
2601
  return {
2576
- host: Hc.has(a) ? "localhost" : a,
2602
+ host: fl.has(a) ? "localhost" : a,
2577
2603
  port: i,
2578
2604
  database: r.toLowerCase()
2579
2605
  };
2580
- }, Wc = (e) => {
2581
- let t = Uc(e);
2582
- if (t !== void 0) return Lt("sha256").update(`${t.host}\u0000${t.port}\u0000${t.database}`).digest("hex").slice(0, 32);
2583
- }, Gc = (e, t) => e === void 0 || t === void 0 ? "unknown" : e === t ? "same" : "different", Kc = {
2606
+ }, ml = (e) => {
2607
+ let t = pl(e);
2608
+ if (t !== void 0) return qt("sha256").update(`${t.host}\u0000${t.port}\u0000${t.database}`).digest("hex").slice(0, 32);
2609
+ }, hl = (e, t) => e === void 0 || t === void 0 ? "unknown" : e === t ? "same" : "different", gl = {
2584
2610
  app: 3,
2585
2611
  plugin: 2,
2586
2612
  framework: 1
2587
- }, qc = /* @__PURE__ */ new Map(), Jc = [], Yc = () => [...Jc], Xc = (e) => {
2613
+ }, _l = /* @__PURE__ */ new Map(), vl = [], yl = () => [...vl], bl = (e) => {
2588
2614
  if (!e.table || !e.timeColumn) throw Error("registerRetention: table + timeColumn are required");
2589
2615
  if (!Number.isFinite(e.ttlMs) || e.ttlMs <= 0) throw Error(`registerRetention(${e.table}): ttlMs must be a positive number`);
2590
- let t = e.source ?? "app", n = qc.get(e.table);
2616
+ let t = e.source ?? "app", n = _l.get(e.table);
2591
2617
  if (n !== void 0) {
2592
2618
  let r = n.source ?? "app", i = n.ttlMs !== e.ttlMs || n.where !== void 0 != (e.where !== void 0);
2593
- if (Kc[t] < Kc[r]) {
2594
- i && Jc.push({
2619
+ if (gl[t] < gl[r]) {
2620
+ i && vl.push({
2595
2621
  table: e.table,
2596
2622
  kept: {
2597
2623
  source: r,
@@ -2604,7 +2630,7 @@ ${e.all.map((e) => {
2604
2630
  });
2605
2631
  return;
2606
2632
  }
2607
- i && r !== t && Jc.push({
2633
+ i && r !== t && vl.push({
2608
2634
  table: e.table,
2609
2635
  kept: {
2610
2636
  source: t,
@@ -2616,51 +2642,59 @@ ${e.all.map((e) => {
2616
2642
  }
2617
2643
  });
2618
2644
  }
2619
- qc.set(e.table, {
2645
+ _l.set(e.table, {
2620
2646
  ...e,
2621
2647
  source: t
2622
2648
  });
2623
- }, Zc = () => [...qc.values()], Qc = () => {
2624
- qc.clear(), Jc.length = 0;
2625
- }, $c = async (e, t, n, r = 2e4) => {
2649
+ }, xl = () => [..._l.values()], Sl = () => {
2650
+ _l.clear(), vl.length = 0;
2651
+ }, Cl = async (e, t, n, r = 2e4) => {
2626
2652
  let i = new Date(t - e.ttlMs), a = 0;
2627
- for (;;) {
2628
- let t = await n(e.table, e.timeColumn, i, r, e.where);
2629
- if (a += t, t < r) break;
2653
+ try {
2654
+ for (;;) {
2655
+ let t = await n(e.table, e.timeColumn, i, r, e.where);
2656
+ if (a += t, t < r) break;
2657
+ }
2658
+ } catch (t) {
2659
+ throw k.runSync(A.increment(A.tagged(Tl, "table", e.table))), t;
2630
2660
  }
2631
- return a;
2632
- }, el = (e, t) => {
2661
+ return a > 0 && k.runSync(A.incrementBy(A.tagged(wl, "table", e.table), a)), a;
2662
+ }, wl = A.counter("voltro_retention_swept_rows_total"), Tl = A.counter("voltro_retention_sweep_errors_total"), El = (e, t) => {
2633
2663
  let n = Number(e ?? String(t));
2634
2664
  return (Number.isFinite(n) && n > 0 ? n : t) * 36e5;
2635
- }, tl = "_voltro_cdc_offsets", nl = T(tl, {
2636
- id: _({ prefix: "cdcoff" }),
2637
- replicaId: t(),
2638
- streamName: t(),
2639
- binlogFile: t(),
2640
- binlogPosition: t(),
2641
- updatedAt: C()
2642
- }).index(["replicaId"]), rl = T(tl, {
2643
- id: _({ prefix: "cdcoff" }),
2644
- replicaId: t(),
2645
- streamName: t(),
2646
- ctVersion: t(),
2647
- updatedAt: C()
2648
- }).index(["replicaId"]), il = "_voltro_data_transfers", al = T(il, {
2649
- id: _({ prefix: "dimp" }),
2650
- startedAt: C().default("now"),
2651
- finishedAt: C().nullable(),
2652
- direction: t().default("import"),
2653
- mode: t(),
2654
- via: t(),
2655
- bundle: t().nullable(),
2656
- sourceFingerprint: t().nullable(),
2657
- tablesWritten: S().default(0),
2658
- rowsWritten: S().default(0),
2659
- failure: t().nullable(),
2660
- staged: r().nullable()
2661
- }).renamedFrom("_voltro_data_imports").nonReactive(), ol = (e) => {
2665
+ }, Dl = "_voltro_cdc_offsets", Ol = w(Dl, {
2666
+ id: E({ prefix: "cdcoff" }),
2667
+ replicaId: C(),
2668
+ streamName: C(),
2669
+ binlogFile: C(),
2670
+ binlogPosition: C(),
2671
+ updatedAt: T()
2672
+ }).index(["replicaId"]), kl = w(Dl, {
2673
+ id: E({ prefix: "cdcoff" }),
2674
+ replicaId: C(),
2675
+ streamName: C(),
2676
+ ctVersion: C(),
2677
+ updatedAt: T()
2678
+ }).index(["replicaId"]), Al = "_voltro_data_transfers", jl = w(Al, {
2679
+ id: E({ prefix: "dimp" }),
2680
+ startedAt: T().default("now"),
2681
+ finishedAt: T().nullable(),
2682
+ direction: C().default("import"),
2683
+ mode: C(),
2684
+ via: C(),
2685
+ bundle: C().nullable(),
2686
+ sourceFingerprint: C().nullable(),
2687
+ tablesWritten: _().default(0),
2688
+ rowsWritten: _().default(0),
2689
+ failure: C().nullable(),
2690
+ staged: p().nullable()
2691
+ }).renamedFrom("_voltro_data_imports").nonReactive(), Ml = (e) => {
2662
2692
  let t = Number.isFinite(e.startedAt.getTime()) ? e.startedAt.toISOString() : "an unknown time", n = e.direction === "import" ? e.mode : `${e.direction} ${e.mode}`, r = e.failure === null ? e.finishedAt === null ? `${n} — started and never reported finishing` : e.direction === "backup" || e.direction === "restore" ? `${n} — finished${e.rowsWritten > 0 ? ` (${e.rowsWritten} blob(s))` : ""}` : `${n} — ${e.rowsWritten} row(s) across ${e.tablesWritten} table(s)` : `FAILED ${n} — ${e.failure}`, i = e.staged === null ? "" : e.staged ? " · staged (target untouched until the swap)" : " · NOT staged (target emptied first)";
2663
2693
  return `${t} · ${r} · via ${e.via}${i}` + (e.bundle === null ? "" : ` · from ${e.bundle}`) + (e.sourceFingerprint === null ? "" : ` · source schema ${e.sourceFingerprint}`);
2664
- }, sl = "postgres";
2694
+ }, Nl = 255, Pl = (e) => e == null ? "null" : typeof e == "string" || typeof e == "number" || typeof e == "boolean" ? JSON.stringify(e) : Array.isArray(e) ? `[${e.map(Pl).join(",")}]` : typeof e == "object" ? `{${Object.entries(e).filter(([, e]) => e !== void 0).sort(([e], [t]) => e < t ? -1 : +(e > t)).map(([e, t]) => `${JSON.stringify(e)}:${Pl(t)}`).join(",")}}` : JSON.stringify(String(e)), Fl = (e) => {
2695
+ if (e == null) return null;
2696
+ let t = typeof e == "string" ? e : Pl(e);
2697
+ return t.length > 255 ? t.slice(0, 255) : t;
2698
+ }, Il = "postgres";
2665
2699
  //#endregion
2666
- export { nt as AUTO_FILLED_COLUMNS, Oc as BULK_INSERT_LIMITS, Y as BranchNameInvalid, xs as BranchTransitionInvalid, tl as CDC_OFFSETS_TABLE, Ba as CHANGE_CLAIM_TTL_ENV, Lc as CHANGE_LISTENER_CEILING, l as ColumnBuilder, il as DATA_TRANSFERS_TABLE, fe as DEFAULT_ACQUIRE_TIMEOUT_MS, Va as DEFAULT_CHANGE_CLAIM_TTL_HOURS, Uo as DEFAULT_EAGER_FALLBACK_WARN_INTERVAL_MS, Yn as DEFAULT_SUBJECT_GRAPH_DEPTH, qt as ENCRYPTED_PREFIX, sl as ENGINE, fr as EagerCardinalityError, rt as FILE_MIGRATION_PATTERN, ft as FRAMEWORK_LIVE_TABLES, Jt as FieldDecryptionError, uo as ID_COLUMN_MAX_LENGTH, ns as INITIAL_VERSION, fa as MATCHES_NO_ROWS, et as MAX_IDENTIFIER_LENGTH, za as OccurrenceCounter, _c as REPLACE_IN_PROGRESS_TABLE, yc as STAGING_STALE_MINUTES, tt as STAGING_TABLE_PREFIX, Bt as SqlClient, ls as TableStreamError, Er as TenantNamespaceInvalid, Tr as TenantNamespaceUnresolved, Bs as TenantRegionUnavailable, zs as TenantResidencyUnresolved, rs as VOLTRO_EXPIRES_MIXIN_ID, as as VOLTRO_LOCAL_FIRST_MIXIN_ID, Qo as VersionConflict, Ke as WARN_IDENTIFIER_LENGTH, mc as _voltroApiKeysTable, nl as _voltroCdcOffsetsTable, al as _voltroDataTransfersTable, fc as _voltroIdempotencyTable, pc as _voltroKvTable, dc as _voltroMigrationPlansTable, lc as _voltroMigrationsTable, rl as _voltroMssqlCdcOffsetsTable, vc as _voltroReplaceInProgressTable, hc as _voltroReplicaObservationsTable, uc as _voltroSeedsTable, Qi as actorsTable, Ps as admitBranch, St as allEnumRenames, Kn as allRegisteredRelations, Ce as allRegisteredTables, ga as and, le as array, la as arrayContains, da as arrayHas, ua as arrayOverlaps, mr as attachEagerLoads, Ka as attributionFields, Xa as attributionKey, ec as auditAllTableIndexes, $s as auditTableIndexes, Fe as avg, xt as avgOver, ao as beginLocalWrite, Xe as bigint, Js as bindResidentStore, r as boolean, vs as branchNamespaceName, kc as bulkInsertLimitsFor, Je as bytes, sn as causeBranches, Na as changeDelete, Ia as changeDigest, ja as changeInsert, Pa as changeSoftDelete, Ma as changeUpdate, jc as chunkRowsForInsert, $a as claimPendingAttribution, pn as classifyConstraintViolation, _e as clearEnumRenames, co as clearPendingAttribution, Jn as clearRelationsRegistry, Ws as clearResidencyConfig, Qc as clearRetentions, m as clearTableRegistry, vo as clearWriteRecorders, W as coercePredicateForSqlite, Pr as coercePredicateValue, Fr as coercePredicateValues, Wi as coerceValueForSqlite, Oa as collectSubqueries, ge as column, Sn as columnSchema, Ac as columnsPerRow, Jr as compileEagerJson, F as compilePredicate, Ir as compileRawFragment, I as compileSelect, La as composeChangeKey, ms as computeEmbedding, Wc as connectionIdentity, sa as contains, o as count, yt as countDistinct, oe as crdtDoc, se as crdtManagedColumns, de as crdtManagedColumnsOf, p as crdtText, Ga as currentWriteAttribution, ve as databaseHandle, te as date, ie as dbEnum, Lo as dbMetricTagCacheSizeForTests, Bo as dbOperationsInFlight, he as decimal, s as declareEnumRename, $t as decodeFieldValue, lr as decodeRowsFromSchema, an as decryptFieldsOnRead, sc as defineMigration, it as defineMixin, Ze as defineSeed, u as denseRank, nr as deriveSubjectGraph, Qe as deriveTypeIdPrefix, mo as derivedRowId, ho as derivedRowIdLength, gn as describeDriverError, _n as describeRowBindings, ol as describeTransferRun, Kt as deserializeArraysOnRead, Ge as drainIdentifierWarnings, Et as dropped, Zt as encodeFieldValue, dr as encodeRowForSchema, rn as encryptFieldsForWrite, nn as encryptedColumnsOf, oo as endLocalWrite, js as enforceBranchLimits, y as ensureTableRegistered, $i as eq, Lr as escapeLike, Da as evaluatePredicate, c as except, Ca as exists, is as expires, Aa as externalChangeEvent, un as extractDbCause, ht as fireSchemaChangeSeeds, ze as fireTenantCreateSeeds, ac as formatIndexAuditIssue, rr as formatSubjectGraph, gc as frameworkTables, gt as generateId, Ue as generateSnowflake, a as geography, Se as geometry, bt as getEnumRenames, Gn as getRelation, Wn as getRelations, Us as getResidencyConfig, E as getTable, ta as gt, na as gte, wr as hasEagerLoads, ps as hybridSearch, _ as id, aa as inSet, xa as inSubquery, Fn as inferForeignKey, Pc as insertRow, S as integer, Sc as interruptedReplaceRefusal, ce as intersect, we as interval, ys as isBranchNamespace, An as isEmptyRelationsSpec, Xt as isEncrypted, Yt as isFieldDecryptionError, ut as isFileMigration, mn as isForeignKeyViolation, ct as isFrameworkOwnedLiveTable, ss as isLocalFirst, cc as isMigrationDefinition, e as isMysqlFamily, Ts as isNeonConnection, ma as isNotNull, pa as isNull, Bc as isPrimaryKeyConflictError, hn as isQueryTimeout, en as isRawEncoding, Ks as isRegionServable, jn as isRelationsSpec, He as isSeedDefinition, Ve as isSqliteFamily, Ne as isStagingTableName, ne as isTableReactive, We as isView, h as json, ya as jsonField, lt as jsonIndex, Ye as lag, n as lead, Yc as listRetentionConflicts, Zc as listRetentions, os as localFirst, cs as localFirstTables, ra as lt, ia as lte, Ko as makeEagerFallbackReporter, Rs as makeNamespaceBranchExecutor, Nn as many, Pn as manyToMany, re as materializeFields, qe as max, Le as migration, ae as min, Nc as missingConflictColumns, Mc as missingRequiredColumns, dt as mixin, ea as neq, Ss as nextBranchState, Uc as normaliseTarget, va as not, wa as notExists, oa as notInSet, Sa as notInSubquery, st as numeric, Ho as observeDbOp, Ha as occurrenceWindowMs, Mn as one, pr as oneCardinalityMessage, _a as or, x as orderClausesOf, ue as paginateBy, f as paginateById, Ra as parseChangeKey, lo as pendingAttributionCount, ks as planBranch, Cs as planBranchProvision, ws as planBranchTeardown, As as planBranchTeardownFor, Ds as planNeonBranchProvision, Os as planNeonBranchTeardown, es as planVersionedUpdate, ye as pluginRef, d as pluginRefSpecOf, zc as primaryKeyConflictError, Ms as provisionBranch, Ys as provisionResidentTenant, jr as qualifyTable, ee as queryFor, je as queryForView, mt as quoteIdent, Rc as raiseChangeListenerCeiling, b as rank, v as raw, Oe as readableByColumns, Ee as real, Vo as recordDbOp, Co as recordsTable, Ae as reference, bn as refuseWrite, Ji as registerCoreTables, Un as registerDiscoveredRelations, Qa as registerPendingAttribution, Hn as registerRelations, Xc as registerRetention, De as registerTable, go as registerWriteRecorder, kn as relations, Xi as requireActors, Te as requireTable, Zi as requireTenants, Io as resetDbMetricTagCacheForTests, ot as resetSnowflake, qs as residentPlacement, Ht as resolveActorSnapshot, Es as resolveBranchMechanism, Go as resolveEagerFallbackWarnIntervalMs, so as resolveEchoAttribution, me as resolveFullTextIndex, Be as resolveIdScheme, Re as resolveMixinGraph, Gs as resolveTenantHome, Ar as resolveTenantNamespace, el as retentionTtlMsFromEnv, Tt as rowNumber, Cn as rowSchema, Xo as runRetryingTransaction, Zo as runStoreTransaction, Wa as runWithWriteAttribution, wo as runWriteRecorders, Gc as sameDatabase, kr as sanitizeIdentifierFragment, Gt as serializeArraysForWrite, pe as serverOnlyColumns, Hs as setResidencyConfig, at as setSchemaChangeSeedHook, $e as setTenantCreateSeedHook, qo as settleTransactionExit, ts as settleVersionedUpdate, ha as spatialPredicate, wc as stagingLeftoverReport, Cc as stagingLeftovers, xc as stagingNamesOf, bc as stagingStaleAfterMs, Ec as stampGeneratedId, Dc as stampGeneratedIds, ca as startsWith, xn as storeRefusalOf, fs as streamTable, i as sum, xe as sumOver, bo as suspendWriteRecorders, xo as suspendWriteRecordersEffect, $c as sweepRetention, T as table, Ns as teardownBranch, t as text, C as timestamp, Dt as timestampMs, Ot as timestampMsOrNull, g as union, be as unionAll, ke as unregisterTable, _o as unregisterWriteRecorder, Ic as updateManyRow, Fc as upsertRow, Me as validateColumnName, vt as validateIndexName, qn as validateRegisteredRelations, zn as validateRelationConfig, wt as validateTableName, Ie as validateTypeIdPrefix, pt as vector, Pe as vectorDistanceToOpclass, hs as vectorEmbedding, $o as versionColumnOf, _t as view, Ct as viewSql, ka as walkLeaves, qa as withCapturedAttribution, So as writeRecordersSuspended };
2700
+ export { lt as AUTO_FILLED_COLUMNS, an as BOUND_ENCRYPTED_PREFIX, Qc as BULK_INSERT_LIMITS, Y as BranchNameInvalid, Gs as BranchTransitionInvalid, Dl as CDC_OFFSETS_TABLE, oo as CHANGE_CLAIM_TTL_ENV, sl as CHANGE_LISTENER_CEILING, Qe as ColumnBuilder, Al as DATA_TRANSFERS_TABLE, st as DEFAULT_ACQUIRE_TIMEOUT_MS, so as DEFAULT_CHANGE_CLAIM_TTL_HOURS, ls as DEFAULT_EAGER_FALLBACK_WARN_INTERVAL_MS, yt as DEFAULT_SOFT_DROP_RETENTION_DAYS, pr as DEFAULT_SUBJECT_GRAPH_DEPTH, rn as ENCRYPTED_PREFIX, Il as ENGINE, Ar as EagerCardinalityError, St as FILE_MIGRATION_PATTERN, at as FRAMEWORK_LIVE_TABLES, cn as FieldDecryptionError, jo as ID_COLUMN_MAX_LENGTH, Lt as INITIAL_VERSION, Ma as MATCHES_NO_ROWS, Tt as MAX_IDENTIFIER_LENGTH, bs as MSSQL_TRANSIENT_NUMBERS, vs as MYSQL_TRANSIENT_CODES, ao as OccurrenceCounter, ys as POSTGRES_TRANSIENT_STATES, Vc as REPLACE_IN_PROGRESS_TABLE, Nl as SCOPE_KEY_MAX_LENGTH, se as SELF_REFERENCE_TARGET, xs as SQLITE_TRANSIENT_CODES, Uc as STAGING_STALE_MINUTES, pt as STAGING_TABLE_PREFIX, Xt as SqlClient, Ss as TURSO_TRANSIENT_MESSAGE, Ns as TableStreamError, Wr as TenantNamespaceInvalid, Ur as TenantNamespaceUnresolved, uc as TenantRegionUnavailable, lc as TenantResidencyUnresolved, Ds as VOLTRO_EXPIRES_MIXIN_ID, ks as VOLTRO_LOCAL_FIRST_MIXIN_ID, Pt as VersionConflict, At as WARN_IDENTIFIER_LENGTH, Rc as _voltroApiKeysTable, Ol as _voltroCdcOffsetsTable, jl as _voltroDataTransfersTable, Ic as _voltroIdempotencyTable, Lc as _voltroKvTable, Fc as _voltroMigrationPlansTable, Nc as _voltroMigrationsTable, kl as _voltroMssqlCdcOffsetsTable, Hc as _voltroReplaceInProgressTable, zc as _voltroReplicaObservationsTable, Pc as _voltroSeedsTable, va as actorsTable, ic as admitBranch, Je as agedSoftDropSnapshots, be as allEnumRenames, ur as allRegisteredRelations, re as allRegisteredTables, Ia as and, ce as array, ka as arrayContains, ja as arrayHas, Aa as arrayOverlaps, Mr as attachEagerLoads, po as attributionFields, _o as attributionKey, wc as auditAllTableIndexes, Cc as auditTableIndexes, Et as avg, ye as avgOver, Eo as beginLocalWrite, fe as bigint, vc as bindResidentStore, p as boolean, Hs as branchNamespaceName, $c as bulkInsertLimitsFor, ne as bytes, xn as causeBranches, $a as changeDelete, no as changeDigest, Za as changeInsert, eo as changeSoftDelete, Qa as changeUpdate, tl as chunkRowsForInsert, bo as claimPendingAttribution, jn as classifyConstraintViolation, d as clearEnumRenames, ko as clearPendingAttribution, fr as clearRelationsRegistry, mc as clearResidencyConfig, Sl as clearRetentions, Oe as clearTableRegistry, Ro as clearWriteRecorders, W as coercePredicateForSqlite, Qr as coercePredicateValue, $r as coercePredicateValues, ua as coerceValueForSqlite, Ja as collectSubqueries, u as column, Bn as columnSchema, el as columnsPerRow, pi as compileEagerJson, L as compilePredicate, ei as compileRawFragment, fi as compileSelect, ro as composeChangeKey, Rs as computeEmbedding, ml as connectionIdentity, Da as contains, c as count, le as countDistinct, oe as crdtDoc, ge as crdtManagedColumns, Mt as crdtManagedColumnsOf, a as crdtText, fo as currentWriteAttribution, $e as databaseHandle, we as date, ee as dbEnum, rs as dbMetricTagCacheSizeForTests, os as dbOperationsInFlight, Se as decimal, l as declareEnumRename, pn as decodeFieldValue, Dr as decodeRowsFromSchema, yn as decryptFieldsOnRead, jc as defineMigration, Ct as defineMixin, ut as defineSeed, n as denseRank, br as deriveSubjectGraph, dt as deriveTypeIdPrefix, Po as derivedRowId, Fo as derivedRowIdLength, Ne as describeAgedSoftDropSnapshots, Pn as describeDriverError, Fn as describeRowBindings, Ml as describeTransferRun, nn as deserializeArraysOnRead, Ie as drainIdentifierWarnings, Ee as dropped, dn as encodeFieldValue, kr as encodeRowForSchema, vn as encryptFieldsForWrite, gn as encryptedColumnsOf, Do as endLocalWrite, tc as enforceBranchLimits, De as ensureTableRegistered, ya as eq, ti as escapeLike, qa as evaluatePredicate, Ze as except, Ua as exists, Os as expires, Xa as externalChangeEvent, wn as extractDbCause, on as fieldBinding, rt as fireSchemaChangeSeeds, Ke as fireTenantCreateSeeds, kc as formatIndexAuditIssue, xr as formatSubjectGraph, Bc as frameworkTables, it as generateId, Ge as generateSnowflake, h as geography, ae as geometry, ue as getEnumRenames, lr as getRelation, cr as getRelations, pc as getResidencyConfig, S as getTable, xa as gt, Sa as gte, Hr as hasEagerLoads, Ls as hybridSearch, E as id, Ta as inSet, Va as inSubquery, $n as inferForeignKey, il as insertRow, _ as integer, Kc as interruptedReplaceRefusal, y as intersect, ke as interval, sn as isBoundCiphertext, Us as isBranchNamespace, Jn as isEmptyRelationsSpec, un as isEncrypted, ln as isFieldDecryptionError, Re as isFileMigration, Mn as isForeignKeyViolation, ct as isFrameworkOwnedLiveTable, js as isLocalFirst, Mc as isMigrationDefinition, ht as isMysqlFamily, Ys as isNeonConnection, Pa as isNotNull, Na as isNull, ul as isPrimaryKeyConflictError, Nn as isQueryTimeout, mn as isRawEncoding, gc as isRegionServable, Yn as isRelationsSpec, We as isSeedDefinition, gt as isSoftDropSnapshotName, Xe as isSqliteFamily, Le as isStagingTableName, pe as isTableReactive, Ts as isTransientContention, Fe as isView, x as json, za as jsonField, vt as jsonIndex, b as lag, de as lead, yl as listRetentionConflicts, xl as listRetentions, As as localFirst, Ms as localFirstTables, Ca as lt, wa as lte, fs as makeEagerFallbackReporter, cc as makeNamespaceBranchExecutor, Zn as many, Qn as manyToMany, Ae as materializeFields, f as max, He as migration, te as min, rl as missingConflictColumns, nl as missingRequiredColumns, ze as mixin, ba as neq, Ks as nextBranchState, pl as normaliseTarget, Ra as not, Wa as notExists, Ea as notInSet, Ha as notInSubquery, me as numeric, cs as observeDbOp, co as occurrenceWindowMs, Xn as one, jr as oneCardinalityMessage, La as or, v as orderClausesOf, he as paginateBy, jt as paginateById, io as parseChangeKey, Ao as pendingAttributionCount, $s as planBranch, qs as planBranchProvision, Js as planBranchTeardown, ec as planBranchTeardownFor, Zs as planNeonBranchProvision, Qs as planNeonBranchTeardown, Nt as planVersionedUpdate, et as pluginRef, r as pluginRefSpecOf, ll as primaryKeyConflictError, nc as provisionBranch, yc as provisionResidentTenant, Yr as qualifyTable, i as queryFor, Ot as queryForView, Pe as quoteIdent, cl as raiseChangeListenerCeiling, Ce as rank, t as raw, Be as readableByColumns, bt as real, ss as recordDbOp, Uo as recordsTable, ot as reference, Rn as refuseWrite, ma as registerCoreTables, sr as registerDiscoveredRelations, yo as registerPendingAttribution, or as registerRelations, bl as registerRetention, e as registerTable, Io as registerWriteRecorder, qn as relations, ga as requireActors, Ve as requireTable, _a as requireTenants, ns as resetDbMetricTagCacheForTests, Me as resetSnowflake, _c as residentPlacement, Qt as resolveActorSnapshot, Xs as resolveBranchMechanism, ds as resolveEagerFallbackWarnIntervalMs, Oo as resolveEchoAttribution, g as resolveFullTextIndex, qe as resolveIdScheme, Ue as resolveMixinGraph, hc as resolveTenantHome, Jr as resolveTenantNamespace, El as retentionTtlMsFromEnv, xe as rowNumber, Vn as rowSchema, gs as runRetryingTransaction, _s as runStoreTransaction, uo as runWithWriteAttribution, Wo as runWriteRecorders, hl as sameDatabase, qr as sanitizeIdentifierFragment, Fl as scopeKeyOf, mt as selfReference, tn as serializeArraysForWrite, Ye as serverOnlyColumns, fc as setResidencyConfig, je as setSchemaChangeSeedHook, wt as setTenantCreateSeedHook, ps as settleTransactionExit, It as settleVersionedUpdate, tt as softDropSnapshotStamp, Fa as spatialPredicate, Jc as stagingLeftoverReport, qc as stagingLeftovers, Gc as stagingNamesOf, Wc as stagingStaleAfterMs, Xc as stampGeneratedId, Zc as stampGeneratedIds, Oa as startsWith, zn as storeRefusalOf, Is as streamTable, Te as sum, m as sumOver, Bo as suspendWriteRecorders, Vo as suspendWriteRecordersEffect, Cl as sweepRetention, w as table, rc as teardownBranch, C as text, T as timestamp, zt as timestampMs, Ft as timestampMsOrNull, ie as union, ft as unionAll, xt as unregisterTable, Lo as unregisterWriteRecorder, ol as updateManyRow, al as upsertRow, kt as validateColumnName, ve as validateIndexName, dr as validateRegisteredRelations, rr as validateRelationConfig, s as validateTableName, Dt as validateTypeIdPrefix, _t as vector, nt as vectorDistanceToOpclass, zs as vectorEmbedding, Rt as versionColumnOf, _e as view, o as viewSql, Ya as walkLeaves, Tn as wireSafeCause, mo as withCapturedAttribution, Ho as writeRecordersSuspended };