@voltro/database 0.54.0 → 0.55.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 ee, I as te, It as ne, J as re, Jt as ie, K as _, Kt as ae, L as v, Lt as oe, M as se, Mt as ce, N as le, Nt as ue, O as de, Ot as fe, P as pe, Pt as me, Q as he, Qt as y, R as ge, Rt as _e, S as ve, St as ye, T as be, Tt as xe, U as Se, Ut as b, V as Ce, Vt as x, W as we, Wt as Te, X as Ee, Xt as De, Y as Oe, Yt as ke, Z as Ae, Zt as S, _ 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, et as Ve, f as He, ft as Ue, g as We, gt as Ge, h as Ke, ht as qe, i as Je, it as Ye, j as C, jt as Xe, k as Ze, kt as Qe, l as $e, lt as et, m as tt, mt as nt, n as rt, nt as w, o as it, ot as at, p as T, pt as ot, q as st, qt as ct, rt as lt, s as ut, st as dt, t as ft, tt as pt, u as mt, ut as ht, v as gt, vt as _t, w as vt, wt as yt, x as bt, xt, y as St, yt as Ct, z as wt, zt as Tt } from "./frameworkLiveTables-ChVR-C5F.js";
2
- import { timestampMs as Et, timestampMsOrNull as Dt } from "./wire.js";
3
- import { Cause as Ot, Chunk as kt, Data as At, Effect as E, Exit as jt, Metric as D, MetricBoundaries as Mt, Option as O, Runtime as Nt, Schedule as Pt, Schema as k, Stream as Ft } from "effect";
4
- import { AsyncLocalStorage as It } from "node:async_hooks";
5
- import { createHash as Lt } from "node:crypto";
6
- import { TransactionConnection as Rt } from "@effect/sql/SqlClient";
7
- import { ansi as A } from "@voltro/logger";
8
- import { SqlClient as zt } 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 _, 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-CwDemhjW.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 { AsyncLocalStorage as Lt } from "node:async_hooks";
5
+ import { createHash as Rt } from "node:crypto";
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";
9
9
  //#region src/actorSnapshot.ts
10
- var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n) => {
10
+ var Vt = (e) => typeof e == "string" && e !== "" ? e : null, Ht = 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 Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
23
23
  }))[0];
24
24
  return r === void 0 ? void 0 : {
25
25
  id: t,
26
- type: Bt(r.kind) ?? n,
27
- displayName: Bt(r.displayName),
28
- email: Bt(r.email)
26
+ type: Vt(r.kind) ?? n,
27
+ displayName: Vt(r.displayName),
28
+ email: Vt(r.email)
29
29
  };
30
30
  } catch {
31
31
  return;
32
32
  }
33
- }, Ht = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqlite", Ut = (e) => {
33
+ }, Ut = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqlite", Wt = (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
- }, Wt = (e, t, n) => {
38
- if (!Ht(n) || !t) return e;
39
- let r = Ut(t);
37
+ }, Gt = (e, t, n) => {
38
+ if (!Ut(n) || !t) return e;
39
+ let r = Wt(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 Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
44
44
  Array.isArray(t) && (i[e] = JSON.stringify(t));
45
45
  }
46
46
  return i;
47
- }, Gt = (e, t, n) => {
48
- if (!Ht(n) || !t) return e;
49
- let r = Ut(t);
47
+ }, Kt = (e, t, n) => {
48
+ if (!Ut(n) || !t) return e;
49
+ let r = Wt(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,7 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
58
58
  }
59
59
  return t ?? e;
60
60
  });
61
- }, Kt = "enc:v1:", qt = class extends Error {
61
+ }, qt = "enc:v1:", Jt = class extends Error {
62
62
  _tag = "FieldDecryptionError";
63
63
  table;
64
64
  column;
@@ -66,7 +66,7 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
66
66
  constructor(e) {
67
67
  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
68
  }
69
- }, Jt = (e) => typeof e == "object" && !!e && e._tag === "FieldDecryptionError", Yt = (e) => typeof e == "string" && e.startsWith("enc:v1:"), Xt = (e, t) => e.encrypt(JSON.stringify(t)), Zt = /* @__PURE__ */ new Set([
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([
70
70
  "text",
71
71
  "id",
72
72
  "reference",
@@ -74,51 +74,51 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
74
74
  "uuid",
75
75
  "email",
76
76
  "url"
77
- ]), Qt = (e, t, n) => {
77
+ ]), $t = (e, t, n) => {
78
78
  let r = e.decrypt(t), i;
79
79
  try {
80
80
  i = JSON.parse(r);
81
81
  } catch {
82
82
  return r;
83
83
  }
84
- return typeof i == "string" ? i : n === void 0 || Zt.has(n) ? r : i;
85
- }, $t = (e, t, n) => {
84
+ return typeof i == "string" ? i : n === void 0 || Qt.has(n) ? r : i;
85
+ }, en = (e, t, n) => {
86
86
  let r = e.decrypt(t);
87
87
  try {
88
- return typeof JSON.parse(r) == "string" ? !1 : n === void 0 || Zt.has(n) ? !0 : void 0;
88
+ return typeof JSON.parse(r) == "string" ? !1 : n === void 0 || Qt.has(n) ? !0 : void 0;
89
89
  } catch {
90
90
  return !0;
91
91
  }
92
- }, en = (e, t) => e.fields[t]?.type, tn = (e) => {
92
+ }, tn = (e, t) => e.fields[t]?.type, nn = (e) => {
93
93
  let t = [];
94
94
  for (let [n, r] of Object.entries(e.fields)) r.encrypted === !0 && t.push(n);
95
95
  return t;
96
- }, nn = (e, t, n) => {
96
+ }, rn = (e, t, n) => {
97
97
  if (!t) return e;
98
- let r = tn(t);
98
+ let r = nn(t);
99
99
  if (r.length === 0) return e;
100
100
  let i = { ...e };
101
101
  for (let e of r) {
102
102
  let r = i[e];
103
- if (!(r == null || Yt(r))) {
103
+ if (!(r == null || Xt(r))) {
104
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] = Xt(n, r);
105
+ i[e] = Zt(n, r);
106
106
  }
107
107
  }
108
108
  return i;
109
- }, rn = (e, t, n, r) => {
109
+ }, an = (e, t, n, r) => {
110
110
  if (!t) return e;
111
- let i = tn(t);
111
+ let i = nn(t);
112
112
  if (i.length === 0 || !n) return e;
113
113
  let a = r?.onError ?? "throw", o = t.tableName ?? "?";
114
114
  return e.map((e) => {
115
115
  let s;
116
116
  for (let c of i) {
117
117
  let i = e[c];
118
- if (Yt(i)) {
118
+ if (Xt(i)) {
119
119
  s ??= { ...e };
120
120
  try {
121
- s[c] = Qt(n, i, en(t, c));
121
+ s[c] = $t(n, i, tn(t, c));
122
122
  } catch (e) {
123
123
  let t = String(e?.message ?? e);
124
124
  if (a === "null") {
@@ -129,7 +129,7 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
129
129
  });
130
130
  continue;
131
131
  }
132
- throw new qt({
132
+ throw new Jt({
133
133
  table: o,
134
134
  column: c,
135
135
  reason: t
@@ -139,125 +139,125 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
139
139
  }
140
140
  return s ?? e;
141
141
  });
142
- }, an = (e) => {
142
+ }, on = (e) => {
143
143
  let t = e;
144
- for (let e = 0; e < 4 && Nt.isFiberFailure(t); e++) t = Ot.squash(t[Nt.FiberFailureCauseId]);
144
+ for (let e = 0; e < 4 && Pt.isFiberFailure(t); e++) t = kt.squash(t[Pt.FiberFailureCauseId]);
145
145
  return t;
146
- }, on = (e, t = 0) => {
147
- if (t >= 4 || !Nt.isFiberFailure(e)) return [e];
148
- let n = e[Nt.FiberFailureCauseId], r = [...Ot.failures(n), ...Ot.defects(n)];
149
- if (r.length === 0) return [Ot.squash(n)];
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)];
150
150
  let i = [];
151
- for (let e of r.slice(0, 8)) i.push(...on(e, t + 1));
151
+ for (let e of r.slice(0, 8)) i.push(...sn(e, t + 1));
152
152
  return i;
153
- }, sn = (e) => e.dbCode !== void 0 || e.dbErrno !== void 0 || e.dbNumber !== void 0 || e.dbSqlState !== void 0 || e.dbConstraint !== void 0, cn = (e) => {
154
- let t = {}, n = [], r = an(e);
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);
155
155
  for (let e = 0; e < 8 && typeof r == "object" && r; e++) {
156
156
  let e = r;
157
157
  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
158
  let i = e.sqlMessage ?? e.detail;
159
159
  t.dbMessage === void 0 && typeof i == "string" && (t.dbMessage = i);
160
160
  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 = an(e.cause);
161
+ (o || s) && n.push(`${o || "Error"}${s ? `: ${s.slice(0, 200)}` : ""}`), r = on(e.cause);
162
162
  }
163
163
  return n.length > 0 && (t.dbCauseChain = n.join(" ← "), t.dbMessage === void 0 && (t.dbMessage = n[n.length - 1])), t;
164
- }, ln = (e) => {
165
- let t = on(e).map(cn);
164
+ }, un = (e) => {
165
+ let t = sn(e).map(ln);
166
166
  if (t.length <= 1) return t[0] ?? {};
167
- let n = t.find(sn) ?? t[0], r = t.filter((e) => e !== n).map((e) => e.dbCauseChain).filter((e) => typeof e == "string");
167
+ let n = t.find(cn) ?? t[0], r = t.filter((e) => e !== n).map((e) => e.dbCauseChain).filter((e) => typeof e == "string");
168
168
  if (r.length === 0) return n;
169
169
  let i = typeof n.dbCauseChain == "string" ? n.dbCauseChain : void 0;
170
170
  return {
171
171
  ...n,
172
172
  dbCauseChain: [i, ...r].filter(Boolean).join(" ‖ ")
173
173
  };
174
- }, un = /^[A-Za-z_][A-Za-z0-9_$]*$/, j = (e) => e !== void 0 && e.length <= 128 && un.test(e) ? e : void 0, dn = (e) => e === void 0 ? void 0 : e.split(".").pop() ?? e, M = (e, ...t) => {
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) => {
175
175
  for (let n of t) {
176
176
  let t = n.exec(e);
177
177
  if (t?.[1] !== void 0) return t[1];
178
178
  }
179
- }, fn = (e, t) => {
179
+ }, pn = (e, t) => {
180
180
  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
181
  if (n === "23503") {
182
- let t = j(e.dbConstraint);
182
+ let t = M(e.dbConstraint);
183
183
  return {
184
184
  kind: /is still referenced from table/i.test(o) ? "foreignKeyInUse" : "foreignKey",
185
185
  ...t === void 0 ? {} : { constraint: t }
186
186
  };
187
187
  }
188
188
  if (n === "23505") {
189
- let t = j(e.dbConstraint);
189
+ let t = M(e.dbConstraint);
190
190
  return {
191
191
  kind: "unique",
192
192
  ...t === void 0 ? {} : { constraint: t }
193
193
  };
194
194
  }
195
195
  if (n === "23502") {
196
- let t = j(e.dbColumn);
196
+ let t = M(e.dbColumn);
197
197
  return {
198
198
  kind: "notNull",
199
199
  ...t === void 0 ? {} : { column: t }
200
200
  };
201
201
  }
202
202
  if (n === "23514") {
203
- let t = j(e.dbConstraint);
203
+ let t = M(e.dbConstraint);
204
204
  return {
205
205
  kind: "check",
206
206
  ...t === void 0 ? {} : { constraint: t }
207
207
  };
208
208
  }
209
209
  if (r === 1452 || r === 1451) {
210
- let e = j(M(o, /CONSTRAINT `([^`]+)`/));
210
+ let e = M(N(o, /CONSTRAINT `([^`]+)`/));
211
211
  return {
212
212
  kind: r === 1451 ? "foreignKeyInUse" : "foreignKey",
213
213
  ...e === void 0 ? {} : { constraint: e }
214
214
  };
215
215
  }
216
216
  if (r === 1062) {
217
- let e = j(dn(M(o, /for key '([^']+)'/)));
217
+ let e = M(fn(N(o, /for key '([^']+)'/)));
218
218
  return {
219
219
  kind: "unique",
220
220
  ...e === void 0 ? {} : { constraint: e }
221
221
  };
222
222
  }
223
223
  if (r === 1048 || r === 1364) {
224
- let e = j(M(o, /Column '([^']+)' cannot be null/, /Field '([^']+)' doesn't have a default value/));
224
+ let e = M(N(o, /Column '([^']+)' cannot be null/, /Field '([^']+)' doesn't have a default value/));
225
225
  return {
226
226
  kind: "notNull",
227
227
  ...e === void 0 ? {} : { column: e }
228
228
  };
229
229
  }
230
230
  if (r === 3819 || r === 4025) {
231
- let e = j(M(o, /Check constraint '([^']+)'/, /CONSTRAINT `([^`]+)` failed/));
231
+ let e = M(N(o, /Check constraint '([^']+)'/, /CONSTRAINT `([^`]+)` failed/));
232
232
  return {
233
233
  kind: "check",
234
234
  ...e === void 0 ? {} : { constraint: e }
235
235
  };
236
236
  }
237
237
  if (i === 547) {
238
- let e = M(o, /(?:FOREIGN KEY|REFERENCE) constraint "([^"]+)"/), t = M(o, /CHECK constraint "([^"]+)"/);
238
+ let e = N(o, /(?:FOREIGN KEY|REFERENCE) constraint "([^"]+)"/), t = N(o, /CHECK constraint "([^"]+)"/);
239
239
  if (t !== void 0 && e === void 0) {
240
- let e = j(t);
240
+ let e = M(t);
241
241
  return {
242
242
  kind: "check",
243
243
  ...e === void 0 ? {} : { constraint: e }
244
244
  };
245
245
  }
246
- let n = /REFERENCE constraint/.test(o), r = j(e);
246
+ let n = /REFERENCE constraint/.test(o), r = M(e);
247
247
  return {
248
248
  kind: n ? "foreignKeyInUse" : "foreignKey",
249
249
  ...r === void 0 ? {} : { constraint: r }
250
250
  };
251
251
  }
252
252
  if (i === 2627 || i === 2601) {
253
- let e = j(M(o, /(?:UNIQUE KEY|PRIMARY KEY) constraint '([^']+)'/, /index '([^']+)'/));
253
+ let e = M(N(o, /(?:UNIQUE KEY|PRIMARY KEY) constraint '([^']+)'/, /index '([^']+)'/));
254
254
  return {
255
255
  kind: "unique",
256
256
  ...e === void 0 ? {} : { constraint: e }
257
257
  };
258
258
  }
259
259
  if (i === 515) {
260
- let e = j(M(o, /Cannot insert the value NULL into column '([^']+)'/));
260
+ let e = M(N(o, /Cannot insert the value NULL into column '([^']+)'/));
261
261
  return {
262
262
  kind: "notNull",
263
263
  ...e === void 0 ? {} : { column: e }
@@ -265,34 +265,34 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
265
265
  }
266
266
  if (n === "SQLITE_CONSTRAINT_FOREIGNKEY") return { kind: t === "delete" || t === "deleteMany" || t === "hardDelete" ? "foreignKeyInUse" : "foreignKey" };
267
267
  if (n === "SQLITE_CONSTRAINT_UNIQUE" || n === "SQLITE_CONSTRAINT_PRIMARYKEY") {
268
- let e = j(dn(M(o, /UNIQUE constraint failed: ([^,\s]+)/)));
268
+ let e = M(fn(N(o, /UNIQUE constraint failed: ([^,\s]+)/)));
269
269
  return {
270
270
  kind: "unique",
271
271
  ...e === void 0 ? {} : { column: e }
272
272
  };
273
273
  }
274
274
  if (n === "SQLITE_CONSTRAINT_NOTNULL") {
275
- let e = j(dn(M(o, /NOT NULL constraint failed: ([^,\s]+)/)));
275
+ let e = M(fn(N(o, /NOT NULL constraint failed: ([^,\s]+)/)));
276
276
  return {
277
277
  kind: "notNull",
278
278
  ...e === void 0 ? {} : { column: e }
279
279
  };
280
280
  }
281
281
  if (n === "SQLITE_CONSTRAINT_CHECK") {
282
- let e = j(M(a, /CHECK constraint failed: (.+)$/));
282
+ let e = M(N(a, /CHECK constraint failed: (.+)$/));
283
283
  return {
284
284
  kind: "check",
285
285
  ...e === void 0 ? {} : { constraint: e }
286
286
  };
287
287
  }
288
- }, pn = (e) => {
289
- let t = fn(e)?.kind;
290
- return t === "foreignKey" || t === "foreignKeyInUse";
291
288
  }, mn = (e) => {
289
+ let t = pn(e)?.kind;
290
+ return t === "foreignKey" || t === "foreignKeyInUse";
291
+ }, hn = (e) => {
292
292
  let t = e.dbCode, n = e.dbErrno;
293
293
  return t === "57014" || n === 3024 || n === 1969 || t === "ETIMEOUT" || t === "SQLITE_INTERRUPT";
294
- }, hn = (e) => {
295
- let t = ln(e), n = [
294
+ }, gn = (e) => {
295
+ let t = un(e), n = [
296
296
  t.dbCode === void 0 ? void 0 : `code=${String(t.dbCode)}`,
297
297
  t.dbErrno === void 0 ? void 0 : `errno=${String(t.dbErrno)}`,
298
298
  t.dbNumber === void 0 ? void 0 : `number=${String(t.dbNumber)}`,
@@ -301,7 +301,7 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
301
301
  t.dbPlaceholders === void 0 ? void 0 : `placeholders=${String(t.dbPlaceholders)}`
302
302
  ].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
303
  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
- }, gn = (e) => Object.entries(e).map(([e, t]) => `${e}:${_n(t)}`).join(" "), _n = (e) => {
304
+ }, _n = (e) => Object.entries(e).map(([e, t]) => `${e}:${vn(t)}`).join(" "), vn = (e) => {
305
305
  if (e === null) return "null";
306
306
  if (e === void 0) return "undefined";
307
307
  if (typeof e == "bigint") return "bigint";
@@ -311,62 +311,62 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
311
311
  if (globalThis.Buffer !== void 0 && globalThis.Buffer.isBuffer(e)) return "Buffer";
312
312
  let t = e.constructor?.name;
313
313
  return typeof t == "string" && t !== "" ? t : "Object";
314
- }, vn = (e) => {
314
+ }, yn = (e) => {
315
315
  let t = (() => {
316
316
  switch (e.type) {
317
317
  case "id":
318
318
  case "reference":
319
319
  case "text":
320
- case "enum": return k.String;
320
+ case "enum": return A.String;
321
321
  case "integer":
322
322
  case "real":
323
- case "decimal": return k.Number;
324
- case "boolean": return k.Boolean;
323
+ case "decimal": return A.Number;
324
+ case "boolean": return A.Boolean;
325
325
  case "timestamp":
326
- case "date": return Et;
327
- case "bigint": return k.BigInt;
328
- case "bytes": return k.Uint8ArrayFromBase64;
329
- case "array": return k.Array(k.Unknown);
330
- case "interval": return k.String;
331
- default: return k.Unknown;
326
+ case "date": return Dt;
327
+ case "bigint": return A.BigInt;
328
+ case "bytes": return A.Uint8ArrayFromBase64;
329
+ case "array": return A.Array(A.Unknown);
330
+ case "interval": return A.String;
331
+ default: return A.Unknown;
332
332
  }
333
333
  })();
334
- return e.nullable === !0 ? k.NullOr(t) : t;
335
- }, yn = (e, t) => {
334
+ return e.nullable === !0 ? A.NullOr(t) : t;
335
+ }, bn = (e, t) => {
336
336
  let n = new Set(t?.omit ?? []), r = {};
337
- for (let [t, i] of Object.entries(e.fields)) n.has(t) || (r[t] = vn(i));
338
- return k.Struct(r);
339
- }, bn = (e) => typeof e == "function" ? e : () => e, xn = (e, t) => ({
337
+ for (let [t, i] of Object.entries(e.fields)) n.has(t) || (r[t] = yn(i));
338
+ return A.Struct(r);
339
+ }, xn = (e) => typeof e == "function" ? e : () => e, Sn = (e, t) => ({
340
340
  kind: "one",
341
- target: bn(e),
341
+ target: xn(e),
342
342
  ...t?.foreignKey === void 0 ? {} : { foreignKey: t.foreignKey },
343
343
  ...t?.sourceKey === void 0 ? {} : { sourceKey: t.sourceKey }
344
- }), Sn = (e, t) => ({
344
+ }), Cn = (e, t) => ({
345
345
  kind: "many",
346
- target: bn(e),
346
+ target: xn(e),
347
347
  ...t?.foreignKey === void 0 ? {} : { foreignKey: t.foreignKey },
348
348
  ...t?.sourceKey === void 0 ? {} : { sourceKey: t.sourceKey }
349
- }), Cn = (e, t) => ({
349
+ }), wn = (e, t) => ({
350
350
  kind: "manyToMany",
351
- target: bn(e),
352
- through: bn(t.through),
351
+ target: xn(e),
352
+ through: xn(t.through),
353
353
  sourceKey: t.sourceKey,
354
354
  targetKey: t.targetKey
355
- }), wn = {
356
- one: xn,
357
- many: Sn,
358
- manyToMany: Cn
359
- }, Tn = (e, t) => {
355
+ }), Tn = {
356
+ one: Sn,
357
+ many: Cn,
358
+ manyToMany: wn
359
+ }, En = (e, t) => {
360
360
  let n = typeof e == "function" ? e : () => e;
361
361
  return {
362
362
  source: n,
363
- relations: t(wn, n())
363
+ relations: t(Tn, n())
364
364
  };
365
- }, En = (e) => {
365
+ }, Dn = (e) => {
366
366
  if (typeof e != "object" || !e) return !1;
367
367
  let t = e;
368
368
  return typeof t.source != "function" || typeof t.relations != "object" || t.relations === null ? !1 : Object.keys(t.relations).length === 0;
369
- }, Dn = (e) => {
369
+ }, On = (e) => {
370
370
  if (typeof e != "object" || !e) return !1;
371
371
  let t = e;
372
372
  if (typeof t.source != "function" || typeof t.relations != "object" || t.relations === null) return !1;
@@ -375,7 +375,7 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
375
375
  let t = e?.kind;
376
376
  return t === "one" || t === "many" || t === "manyToMany";
377
377
  });
378
- }, On = xn, kn = Sn, An = Cn, jn = (e, t, n) => {
378
+ }, kn = Sn, An = Cn, jn = wn, P = (e, t, n) => {
379
379
  let r = [];
380
380
  for (let [n, i] of Object.entries(e.fields)) i.type === "reference" && i.references?.()?.tableName === t && r.push(n);
381
381
  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>' }.`);
@@ -400,10 +400,10 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
400
400
  let t = Nn(e, n.foreignKey);
401
401
  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}': ${Pn(i)}.`));
402
402
  }
403
- }, In = Symbol.for("@voltro/database/relationsRegistry"), Ln = globalThis, N = Ln[In] ?? (Ln[In] = /* @__PURE__ */ new Map()), Rn = (e) => {
404
- let t = e.source(), n = N.get(t.tableName);
403
+ }, In = Symbol.for("@voltro/database/relationsRegistry"), Ln = globalThis, F = Ln[In] ?? (Ln[In] = /* @__PURE__ */ new Map()), Rn = (e) => {
404
+ let t = e.source(), n = F.get(t.tableName);
405
405
  if (n === void 0) {
406
- N.set(t.tableName, new Map(Object.entries(e.relations)));
406
+ F.set(t.tableName, new Map(Object.entries(e.relations)));
407
407
  return;
408
408
  }
409
409
  for (let [r, i] of Object.entries(e.relations)) {
@@ -415,26 +415,26 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
415
415
  }
416
416
  }, zn = (e) => {
417
417
  let t = 0;
418
- for (let n of Object.values(e)) Dn(n) && (Rn(n), t += 1);
418
+ for (let n of Object.values(e)) On(n) && (Rn(n), t += 1);
419
419
  return t;
420
420
  }, Bn = (e) => {
421
- let t = N.get(e);
421
+ let t = F.get(e);
422
422
  if (t !== void 0) return Object.fromEntries(t);
423
- }, Vn = (e, t) => N.get(e)?.get(t), Hn = () => {
423
+ }, Vn = (e, t) => F.get(e)?.get(t), Hn = () => {
424
424
  let e = [];
425
- for (let [t, n] of N) for (let [r, i] of n) e.push({
425
+ for (let [t, n] of F) for (let [r, i] of n) e.push({
426
426
  source: t,
427
427
  name: r,
428
428
  relation: i
429
429
  });
430
430
  return e;
431
431
  }, Un = () => {
432
- for (let [e, t] of N) {
433
- let n = m(e);
432
+ for (let [e, t] of F) {
433
+ let n = E(e);
434
434
  if (n !== void 0) for (let [e, r] of t) Fn(n, e, r);
435
435
  }
436
436
  }, Wn = () => {
437
- N.clear();
437
+ F.clear();
438
438
  }, Gn = 4, Kn = (e) => Object.keys(e.fields), qn = (e, t) => Object.prototype.hasOwnProperty.call(e.fields, t), Jn = (e, t) => {
439
439
  let n = [];
440
440
  for (let [r, i] of Object.entries(e.fields)) i.type === "reference" && i.references?.()?.tableName === t && n.push(r);
@@ -482,7 +482,7 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
482
482
  });
483
483
  return n;
484
484
  }, Zn = (e) => `${e.table}\u0000${e.hops.map((e) => `${e.table}.${e.foreignKey}<-${e.parentKey}`).join("|")}`, Qn = (e) => {
485
- let t = e.tables ?? g(), n = e.relations ?? Hn(), r = e.maxDepth ?? 4, i = new Set(e.exclude ?? []), a = new Map(t.map((e) => [e.tableName, e])), o = [];
485
+ let t = e.tables ?? Ce(), n = e.relations ?? Hn(), r = e.maxDepth ?? 4, i = new Set(e.exclude ?? []), a = new Map(t.map((e) => [e.tableName, e])), o = [];
486
486
  if (!a.has(e.subjectTable)) return {
487
487
  subjectTable: e.subjectTable,
488
488
  paths: [],
@@ -589,7 +589,7 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
589
589
  }
590
590
  }, ar = (e, t, n) => {
591
591
  if (e.length === 0) return e;
592
- let r = m(t);
592
+ let r = E(t);
593
593
  if (r === void 0) return e;
594
594
  let i = r.fields, a = [];
595
595
  for (let [e, t] of Object.entries(i)) a.push({
@@ -609,7 +609,7 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
609
609
  default: return e;
610
610
  }
611
611
  }, sr = (e, t, n = ["json", "array"]) => {
612
- let r = m(t);
612
+ let r = E(t);
613
613
  if (r === void 0) return e;
614
614
  let i = r.fields, a = null;
615
615
  for (let [t, r] of Object.entries(i)) if (n.includes(r.type) && t in e) {
@@ -654,15 +654,15 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
654
654
  }, fr = async (e, t, n, r, i, a) => {
655
655
  let o = n.target(), s = n.sourceKey ?? gr(i, o.tableName);
656
656
  if (s !== void 0) {
657
- let n = P(e, s), i = n.length === 0 ? [] : await _r(o, "id", n, r, a), c = new Map(i.map((e) => [e.id, e]));
657
+ let n = _r(e, s), i = n.length === 0 ? [] : await vr(o, "id", n, r, a), c = new Map(i.map((e) => [e.id, e]));
658
658
  for (let n of e) {
659
659
  let e = n[s];
660
660
  n[t] = e == null ? null : c.get(e) ?? null;
661
661
  }
662
- await vr(i, r.with, o, a);
662
+ await yr(i, r.with, o, a);
663
663
  return;
664
664
  }
665
- let c = n.foreignKey ?? jn(o, i.tableName, t), l = n.sourceKey ?? "id", u = P(e, l), d = u.length === 0 ? [] : await _r(o, c, u, r, a), f = /* @__PURE__ */ new Map();
665
+ let c = n.foreignKey ?? P(o, i.tableName, t), l = n.sourceKey ?? "id", u = _r(e, l), d = u.length === 0 ? [] : await vr(o, c, u, r, a), f = /* @__PURE__ */ new Map();
666
666
  for (let e of d) {
667
667
  let n = e[c];
668
668
  if (f.has(n)) throw new cr(lr({
@@ -678,9 +678,9 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
678
678
  let e = n[l];
679
679
  n[t] = e == null ? null : f.get(e) ?? null;
680
680
  }
681
- await vr(d, r.with, o, a);
681
+ await yr(d, r.with, o, a);
682
682
  }, pr = async (e, t, n, r, i, a) => {
683
- let o = n.target(), s = n.foreignKey ?? jn(o, i.tableName, t), c = n.sourceKey ?? "id", l = P(e, c), u = mr(r), d = l.length === 0 ? [] : await _r(o, s, l, u, a), f = /* @__PURE__ */ new Map();
683
+ let o = n.target(), s = n.foreignKey ?? P(o, i.tableName, t), c = n.sourceKey ?? "id", l = _r(e, c), u = mr(r), d = l.length === 0 ? [] : await vr(o, s, l, u, a), f = /* @__PURE__ */ new Map();
684
684
  for (let e of d) {
685
685
  let t = e[s], n = f.get(t);
686
686
  n ? n.push(e) : f.set(t, [e]);
@@ -696,12 +696,12 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
696
696
  let e = n[c];
697
697
  n[t] = f.get(e) ?? [];
698
698
  }
699
- await vr(d, r.with, o, a);
699
+ await yr(d, r.with, o, a);
700
700
  }, mr = (e) => {
701
701
  let { limit: t, offset: n, ...r } = e;
702
702
  return r;
703
703
  }, hr = async (e, t, n, r, i, a) => {
704
- let o = n.target(), s = n.through(), c = P(e, "id");
704
+ let o = n.target(), s = n.through(), c = _r(e, "id");
705
705
  if (c.length === 0) {
706
706
  for (let n of e) n[t] = [];
707
707
  return;
@@ -722,8 +722,8 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
722
722
  for (let n of e) n[t] = [];
723
723
  return;
724
724
  }
725
- let f = await _r(o, "id", P(d, n.targetKey), r, a), p = new Map(f.map((e) => [e.id, e]));
726
- await vr(f, r.with, o, a);
725
+ let f = await vr(o, "id", _r(d, n.targetKey), r, a), p = new Map(f.map((e) => [e.id, e]));
726
+ await yr(f, r.with, o, a);
727
727
  let m = r.junction === void 0 ? void 0 : r.junction === !0 ? Object.keys(s.fields) : r.junction, h = /* @__PURE__ */ new Map();
728
728
  for (let e of d) {
729
729
  let t = e[n.sourceKey], r = e[n.targetKey], i = p.get(r);
@@ -737,14 +737,14 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
737
737
  for (let n of e) n[t] = h.get(n.id) ?? [];
738
738
  }, gr = (e, t) => {
739
739
  for (let [n, r] of Object.entries(e.fields)) if (r.type === "reference" && r.references?.()?.tableName === t) return n;
740
- }, P = (e, t) => {
740
+ }, _r = (e, t) => {
741
741
  let n = /* @__PURE__ */ new Set();
742
742
  for (let r of e) {
743
743
  let e = r[t];
744
744
  e != null && n.add(e);
745
745
  }
746
746
  return [...n];
747
- }, _r = (e, t, n, r, i) => {
747
+ }, vr = (e, t, n, r, i) => {
748
748
  let a = {
749
749
  column: t,
750
750
  op: "in",
@@ -758,66 +758,66 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
758
758
  skip: r.offset,
759
759
  projection: void 0
760
760
  });
761
- }, vr = async (e, t, n, r) => {
761
+ }, yr = async (e, t, n, r) => {
762
762
  t !== void 0 && e.length !== 0 && (await ur(e, t, n, r)).forEach((t, n) => {
763
763
  let r = e[n];
764
764
  for (let [e, n] of Object.entries(t)) e in r || (r[e] = n);
765
765
  });
766
- }, yr = (e) => e.eager !== void 0 && Object.keys(e.eager).length > 0, br = class extends Error {
766
+ }, br = (e) => e.eager !== void 0 && Object.keys(e.eager).length > 0, xr = class extends Error {
767
767
  _tag = "TenantNamespaceUnresolved";
768
768
  constructor(e) {
769
769
  super(e), this.name = "TenantNamespaceUnresolved";
770
770
  }
771
- }, xr = class extends Error {
771
+ }, Sr = class extends Error {
772
772
  _tag = "TenantNamespaceInvalid";
773
773
  constructor(e) {
774
774
  super(e), this.name = "TenantNamespaceInvalid";
775
775
  }
776
- }, Sr = 63, Cr = "tenant_", wr = (e) => e.toLowerCase().replace(/[^a-z0-9_]/g, "_"), Tr = (e) => {
777
- if (e == null || e === "") throw new br("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.");
778
- let t = wr(e);
779
- if (t.replace(/_/g, "") === "") throw new xr(`tenant id '${e}' has no usable identifier characters after sanitisation — cannot derive a distinct namespace.`);
780
- let n = `${Cr}${t}`;
781
- if (n.length > Sr) throw new xr(`namespace '${n}' for tenant '${e}' exceeds the ${Sr}-byte identifier limit. Use a shorter tenant id.`);
776
+ }, Cr = 63, wr = "tenant_", Tr = (e) => e.toLowerCase().replace(/[^a-z0-9_]/g, "_"), Er = (e) => {
777
+ if (e == null || e === "") throw new xr("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.");
778
+ let t = Tr(e);
779
+ if (t.replace(/_/g, "") === "") throw new Sr(`tenant id '${e}' has no usable identifier characters after sanitisation — cannot derive a distinct namespace.`);
780
+ let n = `${wr}${t}`;
781
+ if (n.length > Cr) throw new Sr(`namespace '${n}' for tenant '${e}' exceeds the ${Cr}-byte identifier limit. Use a shorter tenant id.`);
782
782
  return n;
783
- }, Er = (e, t) => e === null ? t : `${e}.${t}`, Dr = /* @__PURE__ */ new Set(["timestamp", "date"]), Or = /^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2})?/, kr = (e, t) => {
784
- if (e === void 0 || t == null || !Dr.has(e) || t instanceof Date) return t;
783
+ }, Dr = (e, t) => e === null ? t : `${e}.${t}`, Or = /* @__PURE__ */ new Set(["timestamp", "date"]), kr = /^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2})?/, Ar = (e, t) => {
784
+ if (e === void 0 || t == null || !Or.has(e) || t instanceof Date) return t;
785
785
  if (typeof t == "number" && Number.isFinite(t)) return new Date(t);
786
- if (typeof t == "string" && Or.test(t)) {
786
+ if (typeof t == "string" && kr.test(t)) {
787
787
  let e = new Date(t);
788
788
  return Number.isNaN(e.getTime()) ? t : e;
789
789
  }
790
790
  return t;
791
- }, Ar = (e, t) => e === void 0 || !Dr.has(e) ? t : t.map((t) => kr(e, t)), jr = (e, t) => {
791
+ }, jr = (e, t) => e === void 0 || !Or.has(e) ? t : t.map((t) => Ar(e, t)), Mr = (e, t) => {
792
792
  let { strings: n, values: r } = e, i = t.unsafe(n[0] ?? "");
793
793
  for (let e = 0; e < r.length; e++) i = t`${i}${r[e]}${t.unsafe(n[e + 1] ?? "")}`;
794
794
  return t`${i}`;
795
- }, F = (e) => e.replace(/[\\%_]/g, (e) => `\\${e}`), I = (e, t, n = null, r) => {
795
+ }, Nr = (e) => e.replace(/[\\%_]/g, (e) => `\\${e}`), I = (e, t, n = null, r) => {
796
796
  if ("not" in e) return t`NOT (${I(e.not, t, n, r)})`;
797
797
  if ("and" in e) return e.and.length === 0 ? t`TRUE` : t.and(e.and.map((e) => I(e, t, n, r)));
798
798
  if ("or" in e) return e.or.length === 0 ? t`FALSE` : t.or(e.or.map((e) => I(e, t, n, r)));
799
799
  if (e.op === "subquery-in" || e.op === "subquery-not-in") {
800
- let r = e, i = Hr(r.subquery, t, n);
800
+ let r = e, i = Wr(r.subquery, t, n);
801
801
  return r.op === "subquery-in" ? t`${t(r.column)} IN (${i})` : t`${t(r.column)} NOT IN (${i})`;
802
802
  }
803
803
  if (e.op === "exists" || e.op === "not-exists") {
804
- let r = e, i = Hr(r.subquery, t, n);
804
+ let r = e, i = Wr(r.subquery, t, n);
805
805
  return r.op === "exists" ? t`EXISTS (${i})` : t`NOT EXISTS (${i})`;
806
806
  }
807
807
  let i = e, a = t(i.column), o = i.path, s = o !== void 0 && o.length > 0, c = () => t.onDialectOrElse({
808
- mysql: () => t.unsafe(T(i.column, o, "mysql")),
809
- mssql: () => t.unsafe(T(i.column, o, "mssql")),
810
- sqlite: () => t.unsafe(T(i.column, o, "sqlite")),
811
- orElse: () => t.unsafe(T(i.column, o, "postgres"))
808
+ mysql: () => t.unsafe(w(i.column, o, "mysql")),
809
+ mssql: () => t.unsafe(w(i.column, o, "mssql")),
810
+ sqlite: () => t.unsafe(w(i.column, o, "sqlite")),
811
+ orElse: () => t.unsafe(w(i.column, o, "postgres"))
812
812
  }), l = () => t.onDialectOrElse({
813
- mysql: () => t.unsafe(T(i.column, o, "mysql", { numeric: !0 })),
814
- mssql: () => t.unsafe(T(i.column, o, "mssql", { numeric: !0 })),
815
- sqlite: () => t.unsafe(T(i.column, o, "sqlite", { numeric: !0 })),
816
- orElse: () => t.unsafe(T(i.column, o, "postgres", { numeric: !0 }))
817
- }), u = s ? c() : a, d = s ? l() : a, f = (e) => s && e != null ? String(e) : e, p = (e) => s ? Number(e) : e, h = s || r === void 0 ? void 0 : m(r)?.fields?.[i.column]?.type, g = (e) => kr(h, e);
813
+ mysql: () => t.unsafe(w(i.column, o, "mysql", { numeric: !0 })),
814
+ mssql: () => t.unsafe(w(i.column, o, "mssql", { numeric: !0 })),
815
+ sqlite: () => t.unsafe(w(i.column, o, "sqlite", { numeric: !0 })),
816
+ orElse: () => t.unsafe(w(i.column, o, "postgres", { numeric: !0 }))
817
+ }), 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) => Ar(m, e);
818
818
  switch (i.op) {
819
- case "eq": return t`${u} = ${f(g(i.value))}`;
820
- case "neq": return t`${u} <> ${f(g(i.value))}`;
819
+ case "eq": return t`${u} = ${f(h(i.value))}`;
820
+ case "neq": return t`${u} <> ${f(h(i.value))}`;
821
821
  case "gt": return t`${d} > ${p(i.value)}`;
822
822
  case "gte": return t`${d} >= ${p(i.value)}`;
823
823
  case "lt": return t`${d} < ${p(i.value)}`;
@@ -831,7 +831,7 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
831
831
  return e.length === 0 ? t`TRUE` : t`${u} NOT IN ${t.in(s ? e.map((e) => f(e)) : e)}`;
832
832
  }
833
833
  case "contains": {
834
- let e = `%${F(typeof i.value == "string" ? i.value : String(i.value ?? ""))}%`;
834
+ let e = `%${Nr(typeof i.value == "string" ? i.value : String(i.value ?? ""))}%`;
835
835
  return t.onDialectOrElse({
836
836
  mysql: () => t`LOWER(${u}) LIKE LOWER(${e})`,
837
837
  mssql: () => t`LOWER(${u}) LIKE LOWER(${e})`,
@@ -840,7 +840,7 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
840
840
  });
841
841
  }
842
842
  case "startsWith": {
843
- let e = `${F(typeof i.value == "string" ? i.value : String(i.value ?? ""))}%`;
843
+ let e = `${Nr(typeof i.value == "string" ? i.value : String(i.value ?? ""))}%`;
844
844
  return t.onDialectOrElse({
845
845
  mysql: () => t`${u} LIKE ${e}`,
846
846
  orElse: () => t`${u} LIKE ${e} ESCAPE '\\'`
@@ -888,13 +888,13 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
888
888
  });
889
889
  }
890
890
  }
891
- }, Mr = (e, t) => {
891
+ }, Pr = (e, t) => {
892
892
  let n = [];
893
893
  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}`);
894
- }, Nr = (e, t) => t.csv(e.map((e) => {
894
+ }, Fr = (e, t) => t.csv(e.map((e) => {
895
895
  let n = e.column === void 0 ? t.unsafe("*") : t`${t(e.column)}`;
896
896
  if (e.op.startsWith("window-")) {
897
- let r = Mr(e.window ?? {}, t);
897
+ let r = Pr(e.window ?? {}, t);
898
898
  switch (e.op) {
899
899
  case "window-row-number": return t`ROW_NUMBER() OVER (${r}) AS ${t(e.alias)}`;
900
900
  case "window-rank": return t`RANK() OVER (${r}) AS ${t(e.alias)}`;
@@ -918,44 +918,44 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
918
918
  return t`${t(e.column)} AS ${t(e.alias)}`;
919
919
  default: throw Error(`compileAggregateProjection: unknown op '${e.op}'`);
920
920
  }
921
- })), Pr = (e) => `[${e.join(",")}]`, Fr = (e, t) => {
921
+ })), Ir = (e) => `[${e.join(",")}]`, Lr = (e, t) => {
922
922
  if (e.queryVector === void 0) return null;
923
- let n = t(e.column), r = Pr(e.queryVector), i = e.distance === "cosine" ? "<=>" : e.distance === "l2" ? "<->" : "<#>", a = e.distance === "cosine" ? "VEC_DISTANCE_COSINE" : "VEC_DISTANCE_EUCLIDEAN";
923
+ let n = t(e.column), r = Ir(e.queryVector), i = e.distance === "cosine" ? "<=>" : e.distance === "l2" ? "<->" : "<#>", a = e.distance === "cosine" ? "VEC_DISTANCE_COSINE" : "VEC_DISTANCE_EUCLIDEAN";
924
924
  return t.onDialectOrElse({
925
925
  mysql: () => t`${t.unsafe(a)}(${n}, ${r})`,
926
926
  mssql: () => t`NULL`,
927
927
  sqlite: () => t`NULL`,
928
928
  orElse: () => t`${n} ${t.unsafe(i)} ${r}::vector`
929
929
  });
930
- }, Ir = (e, t) => {
930
+ }, Rr = (e, t) => {
931
931
  let n = t.unsafe(e.useGeography ? "::geography" : "::geometry");
932
932
  return t`ST_Distance(${t(e.column)}${n}, ${e.geom}${n})`;
933
- }, Lr = (e, t) => t`${t(e.column)} <-> ${e.geom}::geometry`, Rr = (e, t) => t`${t(`${e.indexName}_tsv`)}`, zr = (e, t) => `${t}_${e.indexName}_fts`, Br = (e, t, n) => {
934
- let r = n.csv(e.columns.map((e) => n`${n(e)}`)), i = `%${F(e.query)}%`;
933
+ }, zr = (e, t) => t`${t(e.column)} <-> ${e.geom}::geometry`, Br = (e, t) => t`${t(`${e.indexName}_tsv`)}`, Vr = (e, t) => `${t}_${e.indexName}_fts`, Hr = (e, t, n) => {
934
+ let r = n.csv(e.columns.map((e) => n`${n(e)}`)), i = `%${Nr(e.query)}%`;
935
935
  return n.onDialectOrElse({
936
936
  mysql: () => n`MATCH(${r}) AGAINST(${e.query} IN NATURAL LANGUAGE MODE)`,
937
937
  sqlite: () => {
938
- let r = n(zr(e, t));
938
+ let r = n(Vr(e, t));
939
939
  return n`${n("id")} IN (SELECT ${n("row_id")} FROM ${r} WHERE ${r} MATCH ${e.query})`;
940
940
  },
941
941
  mssql: () => n.or(e.columns.map((e) => n`LOWER(${n(e)}) LIKE LOWER(${i}) ESCAPE '\\'`)),
942
- orElse: () => n`${Rr(e, n)} @@ plainto_tsquery(${e.config ?? "english"}, ${e.query})`
942
+ orElse: () => n`${Br(e, n)} @@ plainto_tsquery(${e.config ?? "english"}, ${e.query})`
943
943
  });
944
- }, Vr = (e, t, n) => {
945
- let r = `%${F(e.query)}%`;
944
+ }, Ur = (e, t, n) => {
945
+ let r = `%${Nr(e.query)}%`;
946
946
  return n.onDialectOrElse({
947
947
  mysql: () => n`MATCH(${n.csv(e.columns.map((e) => n`${n(e)}`))}) AGAINST(${e.query} IN NATURAL LANGUAGE MODE)`,
948
948
  sqlite: () => {
949
- let r = n(zr(e, t));
949
+ let r = n(Vr(e, t));
950
950
  return n`COALESCE((SELECT -bm25(${r}) FROM ${r} WHERE ${r} MATCH ${e.query} AND ${r}.${n("row_id")} = ${n("id")}), 0)`;
951
951
  },
952
952
  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}`),
953
- orElse: () => n`ts_rank(${Rr(e, n)}, plainto_tsquery(${e.config ?? "english"}, ${e.query}))`
953
+ orElse: () => n`ts_rank(${Br(e, n)}, plainto_tsquery(${e.config ?? "english"}, ${e.query}))`
954
954
  });
955
- }, Hr = (e, t, n = null) => {
955
+ }, Wr = (e, t, n = null) => {
956
956
  if (e.setOp && e.setOp.queries.length >= 2) {
957
- 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`(${Hr(e, t, n)})`).reduce((e, n, i) => i === 0 ? n : t`${e} ${t.unsafe(r)} ${n}`), a = [];
958
- if (C(e).length > 0 && a.push(t` ORDER BY ${t.csv(C(e).map((e) => e.direction === "desc" ? t`${t(e.column)} DESC` : t`${t(e.column)} ASC`))}`), e.take !== void 0) {
957
+ 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`(${Wr(e, t, n)})`).reduce((e, n, i) => i === 0 ? n : t`${e} ${t.unsafe(r)} ${n}`), a = [];
958
+ 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) {
959
959
  if (!Number.isInteger(e.take) || e.take < 0) throw Error(`compileSelect: invalid take ${e.take}`);
960
960
  a.push(t` LIMIT ${t.unsafe(String(e.take))}`);
961
961
  }
@@ -965,7 +965,7 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
965
965
  }
966
966
  return t`${i}${a.reduce((e, n) => t`${e}${n}`, t``)}`;
967
967
  }
968
- let r = e.annClause === void 0 ? null : Fr(e.annClause, t);
968
+ let r = e.annClause === void 0 ? null : Lr(e.annClause, t);
969
969
  e.spatialClause !== void 0 && t.onDialectOrElse({
970
970
  mysql: () => {
971
971
  throw Error("@voltro/plugin-postgis: spatial distance / KNN ordering is postgres-only");
@@ -978,57 +978,57 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
978
978
  },
979
979
  orElse: () => t``
980
980
  });
981
- let i = e.spatialClause?.projectAs === void 0 ? null : Ir(e.spatialClause, t), a = e.aggregations && e.aggregations.length > 0 ? Nr(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 ? Vr(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({
981
+ let i = e.spatialClause?.projectAs === void 0 ? null : Rr(e.spatialClause, t), a = e.aggregations && e.aggregations.length > 0 ? Fr(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 ? Ur(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({
982
982
  orElse: () => t`DISTINCT ON (${t.csv(e.distinctOn.map((e) => t`${t(e)}`))}) `,
983
983
  mysql: () => t`DISTINCT `,
984
984
  mssql: () => t`DISTINCT `,
985
985
  sqlite: () => t`DISTINCT `
986
- }) : e.distinct ? t`DISTINCT ` : t``, p = e.alias === void 0 ? t`${t(Er(n, e.table))}` : t`${t(Er(n, e.table))} AS ${t(e.alias)}`, m = (e.joins ?? []).map((e) => {
986
+ }) : e.distinct ? t`DISTINCT ` : t``, p = e.alias === void 0 ? t`${t(Dr(n, e.table))}` : t`${t(Dr(n, e.table))} AS ${t(e.alias)}`, m = (e.joins ?? []).map((e) => {
987
987
  let r = e.kind === "inner" ? "INNER" : "LEFT";
988
- return t` ${t.unsafe(r)} JOIN ${t(Er(n, e.table))} AS ${t(e.alias)} ON ${I(e.on, t, n)}`;
989
- }), h = m.length > 0 ? m.reduce((e, n) => t`${e}${n}`, p) : p, g = c === void 0 ? null : Br(c, e.table, t), ee = [e.predicate ? I(e.predicate, t, n, e.table) : null, g].filter((e) => e !== null), te = ee.length > 0 ? t` WHERE ${t.and(ee)}` : t``, ne = e.groupBy && e.groupBy.length > 0 ? t` GROUP BY ${t.csv(e.groupBy.map((e) => t`${t(e)}`))}` : t``, re = e.having ? t` HAVING ${I(e.having, t, n, e.table)}` : t``, ie = e.skip !== void 0, _ = [];
990
- r !== null && _.push(t`${r} ASC`), e.spatialClause?.order !== void 0 && _.push(e.spatialClause.order === "desc" ? t`${Lr(e.spatialClause, t)} DESC` : t`${Lr(e.spatialClause, t)} ASC`), l !== null && c?.rank?.order === !0 && _.push(t`${l} DESC`);
991
- for (let n of C(e)) _.push(n.direction === "desc" ? t`${t(n.column)} DESC` : t`${t(n.column)} ASC`);
992
- let ae = _.length > 0 ? t` ORDER BY ${t.csv(_)}` : ie ? t.onDialectOrElse({
988
+ return t` ${t.unsafe(r)} JOIN ${t(Dr(n, e.table))} AS ${t(e.alias)} ON ${I(e.on, t, n)}`;
989
+ }), h = m.length > 0 ? m.reduce((e, n) => t`${e}${n}`, p) : p, g = c === void 0 ? null : Hr(c, e.table, t), _ = [e.predicate ? I(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 ${I(e.having, t, n, e.table)}` : t``, v = e.skip !== void 0, y = [];
990
+ r !== null && y.push(t`${r} ASC`), e.spatialClause?.order !== void 0 && y.push(e.spatialClause.order === "desc" ? t`${zr(e.spatialClause, t)} DESC` : t`${zr(e.spatialClause, t)} ASC`), l !== null && c?.rank?.order === !0 && y.push(t`${l} DESC`);
991
+ for (let n of x(e)) y.push(n.direction === "desc" ? t`${t(n.column)} DESC` : t`${t(n.column)} ASC`);
992
+ let re = y.length > 0 ? t` ORDER BY ${t.csv(y)}` : v ? t.onDialectOrElse({
993
993
  mssql: () => t` ORDER BY (SELECT NULL)`,
994
994
  orElse: () => t``
995
- }) : t``, v = (e) => {
995
+ }) : t``, b = (e) => {
996
996
  if (!Number.isFinite(e) || !Number.isInteger(e) || e < 0) throw Error(`compileSelect: expected non-negative integer take/skip, got ${e}`);
997
997
  return t.unsafe(String(e));
998
- }, oe = (e.ctes ?? []).map((e) => t`${t(e.name)} AS (${Hr(e.descriptor, t, n)})`), se = (e.ctes ?? []).some((e) => e.recursive === !0), ce = oe.length > 0 ? t`WITH ${t.unsafe(se ? "RECURSIVE " : "")}${t.csv(oe)} ` : t``;
998
+ }, ie = (e.ctes ?? []).map((e) => t`${t(e.name)} AS (${Wr(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``;
999
999
  return t.onDialectOrElse({
1000
1000
  mssql: () => {
1001
- let n = e.take !== void 0 && !ie ? t`TOP ${v(e.take)} ` : t``, r = ie ? t` OFFSET ${v(e.skip)} ROWS FETCH NEXT ${v(e.take ?? 2 ** 53 - 1)} ROWS ONLY` : t``;
1002
- return t`${ce}SELECT ${n}${f}${d} FROM ${h}${te}${ne}${re}${ae}${r}`;
1001
+ 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``;
1002
+ return t`${oe}SELECT ${n}${f}${d} FROM ${h}${ee}${te}${ne}${re}${r}`;
1003
1003
  },
1004
1004
  orElse: () => {
1005
- let n = e.take === void 0 ? t`` : t` LIMIT ${v(e.take)}`, r = ie ? t` OFFSET ${v(e.skip)}` : t``;
1006
- return t`${ce}SELECT ${f}${d} FROM ${h}${te}${ne}${re}${ae}${n}${r}`;
1005
+ let n = e.take === void 0 ? t`` : t` LIMIT ${b(e.take)}`, r = v ? t` OFFSET ${b(e.skip)}` : t``;
1006
+ return t`${oe}SELECT ${f}${d} FROM ${h}${ee}${te}${ne}${re}${n}${r}`;
1007
1007
  }
1008
1008
  });
1009
- }, Ur = (e, t, n) => {
1009
+ }, Gr = (e, t, n) => {
1010
1010
  if (e.eager === void 0) return null;
1011
- let r = Kr(e.table, e.eager, e.sourceTable);
1011
+ let r = Jr(e.table, e.eager, e.sourceTable);
1012
1012
  if (r === null) return null;
1013
- let i = $r(n, e, r, Qr(t, n));
1013
+ let i = ti(n, e, r, ei(t, n));
1014
1014
  return i === null ? null : {
1015
1015
  fragment: i,
1016
- decode: ni(r, n)
1016
+ decode: ii(r, n)
1017
1017
  };
1018
- }, Wr = (e) => e.relation.kind === "one" && e.fkSide === "target", Gr = (e) => ({
1018
+ }, Kr = (e) => e.relation.kind === "one" && e.fkSide === "target", qr = (e) => ({
1019
1019
  ...e,
1020
1020
  branch: {
1021
1021
  ...e.branch,
1022
1022
  limit: 2
1023
1023
  }
1024
- }), Kr = (e, t, n) => {
1025
- let r = n ?? re(e), i = Bn(e);
1024
+ }), Jr = (e, t, n) => {
1025
+ let r = n ?? Te(e), i = Bn(e);
1026
1026
  if (i === void 0) return null;
1027
1027
  let a = [];
1028
1028
  for (let [e, n] of Object.entries(t)) {
1029
1029
  let t = i[e];
1030
1030
  if (t === void 0) return null;
1031
- let o = qr(e, t, r, n === !0 ? {} : n);
1031
+ let o = Yr(e, t, r, n === !0 ? {} : n);
1032
1032
  if (o === null) return null;
1033
1033
  a.push(o);
1034
1034
  }
@@ -1036,19 +1036,19 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
1036
1036
  table: r,
1037
1037
  children: a
1038
1038
  };
1039
- }, qr = (e, t, n, r) => {
1039
+ }, Yr = (e, t, n, r) => {
1040
1040
  let i = t.target(), a = (t.kind === "manyToMany" ? void 0 : t.sourceKey) ?? "id", o, s;
1041
1041
  if (t.kind === "manyToMany") o = t.targetKey, s = "target";
1042
1042
  else if (t.kind === "one") {
1043
- let r = t.sourceKey ?? Zr(n, i.tableName);
1043
+ let r = t.sourceKey ?? $r(n, i.tableName);
1044
1044
  if (r !== void 0) o = r, s = "source";
1045
1045
  else try {
1046
- o = t.foreignKey ?? jn(i, n.tableName, e), s = "target";
1046
+ o = t.foreignKey ?? P(i, n.tableName, e), s = "target";
1047
1047
  } catch {
1048
1048
  return null;
1049
1049
  }
1050
1050
  } else try {
1051
- o = t.foreignKey ?? jn(i, n.tableName, e), s = "target";
1051
+ o = t.foreignKey ?? P(i, n.tableName, e), s = "target";
1052
1052
  } catch {
1053
1053
  return null;
1054
1054
  }
@@ -1059,7 +1059,7 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
1059
1059
  for (let [n, a] of Object.entries(r.with)) {
1060
1060
  let r = e?.[n];
1061
1061
  if (r === void 0) return null;
1062
- let o = qr(n, r, i, a === !0 ? {} : a);
1062
+ let o = Yr(n, r, i, a === !0 ? {} : a);
1063
1063
  if (o === null) return null;
1064
1064
  t.push(o);
1065
1065
  }
@@ -1075,9 +1075,9 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
1075
1075
  fkSide: s,
1076
1076
  branch: r,
1077
1077
  children: c,
1078
- junction: Jr(t, r)
1078
+ junction: Xr(t, r)
1079
1079
  };
1080
- }, Jr = (e, t) => {
1080
+ }, Xr = (e, t) => {
1081
1081
  if (e.kind !== "manyToMany" || t.junction === void 0) return;
1082
1082
  let n = e.through(), r = t.junction === !0 ? Object.keys(n.fields) : t.junction, i = r.filter((e) => e in n.fields);
1083
1083
  return {
@@ -1089,35 +1089,35 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
1089
1089
  return t !== void 0 && (t.type === "timestamp" || t.type === "date");
1090
1090
  })
1091
1091
  };
1092
- }, Yr = (e) => `__j_${e}`, Xr = "__j", Zr = (e, t) => {
1092
+ }, Zr = (e) => `__j_${e}`, Qr = "__j", $r = (e, t) => {
1093
1093
  for (let [n, r] of Object.entries(e.fields)) if (r.type === "reference" && r.references?.()?.tableName === t) return n;
1094
- }, Qr = (e, t) => {
1094
+ }, ei = (e, t) => {
1095
1095
  let n = 0;
1096
1096
  return {
1097
1097
  sql: e,
1098
1098
  dialect: t,
1099
1099
  nextAlias: () => `__a${n++}`
1100
1100
  };
1101
- }, $r = (e, t, n, r) => {
1101
+ }, ti = (e, t, n, r) => {
1102
1102
  switch (e) {
1103
- case "postgres": return ai(t, n, r);
1103
+ case "postgres": return si(t, n, r);
1104
1104
  case "sqlite":
1105
- case "turso": return pi(t, n, r);
1105
+ case "turso": return hi(t, n, r);
1106
1106
  case "mysql":
1107
- case "mariadb": return Ci(t, n, r);
1108
- case "mssql": return Ai(t, n, r);
1107
+ case "mariadb": return Ti(t, n, r);
1108
+ case "mssql": return Mi(t, n, r);
1109
1109
  }
1110
- }, ei = (e, t) => t === "mssql" && !ti.test(e) ? /* @__PURE__ */ new Date(`${e}Z`) : new Date(e), ti = /(?:Z|[+-]\d{2}:?\d{2})$/, ni = (e, t) => {
1111
- let n = ri(e.table, e.children, t);
1110
+ }, ni = (e, t) => t === "mssql" && !ri.test(e) ? /* @__PURE__ */ new Date(`${e}Z`) : new Date(e), ri = /(?:Z|[+-]\d{2}:?\d{2})$/, ii = (e, t) => {
1111
+ let n = ai(e.table, e.children, t);
1112
1112
  return (e) => e.map((e) => {
1113
1113
  let t = e.__row, r = typeof t == "string" ? JSON.parse(t) : t;
1114
1114
  return n(r);
1115
1115
  });
1116
- }, ri = (e, t, n) => {
1116
+ }, ai = (e, t, n) => {
1117
1117
  let r = [];
1118
1118
  for (let [t, n] of Object.entries(e.fields)) (n.type === "timestamp" || n.type === "date") && r.push(t);
1119
1119
  let i = t.map((e) => {
1120
- let t = ri(e.target, e.children, n), r = e.relation.kind === "one", i = Wr(e), a = i ? lr({
1120
+ let t = ai(e.target, e.children, n), r = e.relation.kind === "one", i = Kr(e), a = i ? lr({
1121
1121
  relationName: e.relationName,
1122
1122
  sourceTableName: e.source.tableName,
1123
1123
  targetTableName: e.target.tableName,
@@ -1130,14 +1130,14 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
1130
1130
  isSingle: r,
1131
1131
  fromOverFetch: i,
1132
1132
  cardinalityMessage: a,
1133
- junction: ii(e.junction, n)
1133
+ junction: oi(e.junction, n)
1134
1134
  };
1135
1135
  });
1136
1136
  return (e) => {
1137
1137
  let t = { ...e };
1138
1138
  for (let e of r) {
1139
1139
  let r = t[e];
1140
- typeof r == "string" && (t[e] = ei(r, n));
1140
+ typeof r == "string" && (t[e] = ni(r, n));
1141
1141
  }
1142
1142
  for (let e of i) {
1143
1143
  let n = t[e.name];
@@ -1159,202 +1159,202 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
1159
1159
  }
1160
1160
  return t;
1161
1161
  };
1162
- }, ii = (e, t) => {
1162
+ }, oi = (e, t) => {
1163
1163
  if (e === void 0) return;
1164
1164
  let n = new Set(e.dateColumns), r = e.requested;
1165
1165
  return (e) => {
1166
1166
  let i = e._junction ?? {}, a = {};
1167
1167
  for (let e of r) {
1168
1168
  let r = i[e];
1169
- a[e] = n.has(e) && typeof r == "string" ? ei(r, t) : r;
1169
+ a[e] = n.has(e) && typeof r == "string" ? ni(r, t) : r;
1170
1170
  }
1171
1171
  return {
1172
1172
  ...e,
1173
1173
  _junction: a
1174
1174
  };
1175
1175
  };
1176
- }, ai = (e, t, n) => {
1177
- let r = n.sql, i = n.nextAlias(), a = r(t.table.tableName), o = r(i), s = oi(i, t.children, n);
1178
- return s === null ? null : r`SELECT ${s} AS "__row" FROM ${a} AS ${o}${e.predicate ? r` WHERE ${H(e.predicate, i, r)}` : r``}${C(e).length > 0 ? r` ORDER BY ${r.csv(C(e).map((e) => e.direction === "desc" ? r`${z(i, e.column, r)} DESC` : r`${z(i, e.column, r)} ASC`))}` : r``}${e.take === void 0 ? r`` : r` LIMIT ${V(e.take, r)}`}${e.skip === void 0 ? r`` : r` OFFSET ${V(e.skip, r)}`}`;
1179
- }, oi = (e, t, n, r) => {
1180
- let i = n.sql, a = r === void 0 ? i`to_jsonb(${i(e)}.*)` : i`(to_jsonb(${i(e)}.*) - ${B(Xr, i)}::text)`;
1176
+ }, si = (e, t, n) => {
1177
+ let r = n.sql, i = n.nextAlias(), a = r(t.table.tableName), o = r(i), s = ci(i, t.children, n);
1178
+ return s === null ? null : r`SELECT ${s} AS "__row" FROM ${a} AS ${o}${e.predicate ? r` WHERE ${H(e.predicate, i, r)}` : r``}${x(e).length > 0 ? r` ORDER BY ${r.csv(x(e).map((e) => e.direction === "desc" ? r`${z(i, e.column, r)} DESC` : r`${z(i, e.column, r)} ASC`))}` : r``}${e.take === void 0 ? r`` : r` LIMIT ${V(e.take, r)}`}${e.skip === void 0 ? r`` : r` OFFSET ${V(e.skip, r)}`}`;
1179
+ }, ci = (e, t, n, r) => {
1180
+ let i = n.sql, a = r === void 0 ? i`to_jsonb(${i(e)}.*)` : i`(to_jsonb(${i(e)}.*) - ${B(Qr, i)}::text)`;
1181
1181
  if (t.length === 0 && r === void 0) return a;
1182
1182
  let o = [];
1183
- r !== void 0 && o.push(i`${B("_junction", i)}, ${z(e, Xr, i)}`);
1183
+ r !== void 0 && o.push(i`${B("_junction", i)}, ${z(e, Qr, i)}`);
1184
1184
  for (let r of t) {
1185
- let t = si(r, e, n);
1185
+ let t = li(r, e, n);
1186
1186
  if (t === null) return null;
1187
1187
  o.push(i`${B(r.relationName, i)}, ${t}`);
1188
1188
  }
1189
1189
  return i`${a} || jsonb_build_object(${i.csv(o)})`;
1190
- }, si = (e, t, n) => {
1190
+ }, li = (e, t, n) => {
1191
1191
  switch (e.relation.kind) {
1192
- case "one": return Wr(e) ? li(Gr(e), t, n) : ci(e, t, n);
1193
- case "many": return li(e, t, n);
1194
- case "manyToMany": return ui(e, t, n);
1192
+ case "one": return Kr(e) ? di(qr(e), t, n) : ui(e, t, n);
1193
+ case "many": return di(e, t, n);
1194
+ case "manyToMany": return fi(e, t, n);
1195
1195
  }
1196
- }, ci = (e, t, n) => {
1197
- let r = n.sql, i = n.nextAlias(), a = oi(i, e.children, n);
1196
+ }, ui = (e, t, n) => {
1197
+ let r = n.sql, i = n.nextAlias(), a = ci(i, e.children, n);
1198
1198
  if (a === null) return null;
1199
1199
  let o = e.fkSide === "source" ? r`${z(i, "id", r)} = ${z(t, e.foreignKey, r)}` : r`${z(i, e.foreignKey, r)} = ${z(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${H(e.branch.where, i, r)}`, c = L(i, e.branch.orderBy, r);
1200
1200
  return r`(SELECT ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o}${s}${c} LIMIT 1)`;
1201
- }, li = (e, t, n) => {
1202
- let r = n.sql, i = n.nextAlias(), a = oi(i, e.children, n);
1201
+ }, di = (e, t, n) => {
1202
+ let r = n.sql, i = n.nextAlias(), a = ci(i, e.children, n);
1203
1203
  if (a === null) return null;
1204
- let o = r`${z(void 0, e.foreignKey, r)} = ${z(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${I(e.branch.where, r)}`, c = fi(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${V(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${V(e.branch.offset, r)}`;
1204
+ let o = r`${z(void 0, e.foreignKey, r)} = ${z(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${I(e.branch.where, r)}`, c = mi(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${V(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${V(e.branch.offset, r)}`;
1205
1205
  return r`COALESCE((SELECT jsonb_agg(${a}) FROM (SELECT * FROM ${r(e.target.tableName)} WHERE ${o}${s}${c}${l}${u}) AS ${r(i)}), '[]'::jsonb)`;
1206
- }, ui = (e, t, n) => {
1207
- let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = oi(o, e.children, n, e.junction);
1206
+ }, fi = (e, t, n) => {
1207
+ let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = ci(o, e.children, n, e.junction);
1208
1208
  if (c === null) return null;
1209
- let l = e.branch.where === void 0 ? r`` : r` AND ${I(e.branch.where, r)}`, u = Ri(e, s, r), d = L(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${V(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${V(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : r`, ${di(e.junction, s, r)} AS ${r(Xr)}`;
1209
+ let l = e.branch.where === void 0 ? r`` : r` AND ${I(e.branch.where, r)}`, u = U(e, s, r), d = L(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${V(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${V(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : r`, ${pi(e.junction, s, r)} AS ${r(Qr)}`;
1210
1210
  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 ${z(o, "id", r)} = ${z(s, i.targetKey, r)} WHERE ${z(s, i.sourceKey, r)} = ${z(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), '[]'::jsonb)`;
1211
- }, di = (e, t, n) => e.present.length === 0 ? n`jsonb_build_object()` : n`jsonb_build_object(${n.csv(e.present.map((e) => n`${B(e, n)}, ${z(t, e, n)}`))})`, L = (e, t, n) => t === void 0 || t.length === 0 ? n`` : n` ORDER BY ${n.csv(t.map((t) => t.direction === "desc" ? n`${z(e, t.column, n)} DESC` : n`${z(e, t.column, n)} ASC`))}`, fi = (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`))}`, pi = (e, t, n) => {
1212
- let r = n.sql, i = n.nextAlias(), a = mi(i, t.table, t.children, n);
1211
+ }, pi = (e, t, n) => e.present.length === 0 ? n`jsonb_build_object()` : n`jsonb_build_object(${n.csv(e.present.map((e) => n`${B(e, n)}, ${z(t, e, n)}`))})`, L = (e, t, n) => t === void 0 || t.length === 0 ? n`` : n` ORDER BY ${n.csv(t.map((t) => t.direction === "desc" ? n`${z(e, t.column, n)} DESC` : n`${z(e, t.column, n)} ASC`))}`, mi = (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`))}`, hi = (e, t, n) => {
1212
+ let r = n.sql, i = n.nextAlias(), a = gi(i, t.table, t.children, n);
1213
1213
  if (a === null) return null;
1214
- let o = e.predicate ? r` WHERE ${H(e.predicate, i, r)}` : r``, s = C(e).length > 0 ? r` ORDER BY ${r.csv(C(e).map((e) => e.direction === "desc" ? r`${z(i, e.column, r)} DESC` : r`${z(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${V(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${V(e.skip, r)}`;
1214
+ let o = e.predicate ? r` WHERE ${H(e.predicate, i, r)}` : r``, s = x(e).length > 0 ? r` ORDER BY ${r.csv(x(e).map((e) => e.direction === "desc" ? r`${z(i, e.column, r)} DESC` : r`${z(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${V(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${V(e.skip, r)}`;
1215
1215
  return r`SELECT ${a} AS "__row" FROM ${r(t.table.tableName)} AS ${r(i)}${o}${s}${c}${l}`;
1216
- }, mi = (e, t, n, r, i) => {
1216
+ }, gi = (e, t, n, r, i) => {
1217
1217
  let a = r.sql, o = [];
1218
1218
  for (let n of Object.keys(t.fields)) o.push(a`${B(n, a)}, ${z(e, n, a)}`);
1219
1219
  if (i !== void 0) {
1220
- let e = hi(i.projection, i.source, a);
1220
+ let e = _i(i.projection, i.source, a);
1221
1221
  o.push(a`${B("_junction", a)}, json_object(${e})`);
1222
1222
  }
1223
1223
  for (let t of n) {
1224
- let n = yi(t, e, r);
1224
+ let n = xi(t, e, r);
1225
1225
  if (n === null) return null;
1226
1226
  o.push(a`${B(t.relationName, a)}, ${n}`);
1227
1227
  }
1228
1228
  return a`json_object(${a.csv(o)})`;
1229
- }, hi = (e, t, n) => e.present.length === 0 ? n`` : n.csv(e.present.map((e) => n`${B(e, n)}, ${z(t.alias, t.physical(e), n)}`)), gi = (e, t, n) => e.present.length === 0 ? n`` : n`, ${n.csv(e.present.map((e) => n`${z(t, e, n)} AS ${n(Yr(e))}`))}`, _i = (e) => ({
1229
+ }, _i = (e, t, n) => e.present.length === 0 ? n`` : n.csv(e.present.map((e) => n`${B(e, n)}, ${z(t.alias, t.physical(e), n)}`)), vi = (e, t, n) => e.present.length === 0 ? n`` : n`, ${n.csv(e.present.map((e) => n`${z(t, e, n)} AS ${n(Zr(e))}`))}`, yi = (e) => ({
1230
1230
  alias: e,
1231
- physical: Yr
1232
- }), vi = (e) => ({
1231
+ physical: Zr
1232
+ }), bi = (e) => ({
1233
1233
  alias: e,
1234
1234
  physical: (e) => e
1235
- }), yi = (e, t, n) => {
1235
+ }), xi = (e, t, n) => {
1236
1236
  switch (e.relation.kind) {
1237
- case "one": return Wr(e) ? xi(Gr(e), t, n) : bi(e, t, n);
1238
- case "many": return xi(e, t, n);
1239
- case "manyToMany": return Si(e, t, n);
1237
+ case "one": return Kr(e) ? Ci(qr(e), t, n) : Si(e, t, n);
1238
+ case "many": return Ci(e, t, n);
1239
+ case "manyToMany": return wi(e, t, n);
1240
1240
  }
1241
- }, bi = (e, t, n) => {
1242
- let r = n.sql, i = n.nextAlias(), a = mi(i, e.target, e.children, n);
1241
+ }, Si = (e, t, n) => {
1242
+ let r = n.sql, i = n.nextAlias(), a = gi(i, e.target, e.children, n);
1243
1243
  if (a === null) return null;
1244
1244
  let o = e.fkSide === "source" ? r`${z(i, "id", r)} = ${z(t, e.foreignKey, r)}` : r`${z(i, e.foreignKey, r)} = ${z(t, e.sourceKey, r)}`;
1245
1245
  return r`(SELECT ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o} LIMIT 1)`;
1246
- }, xi = (e, t, n) => {
1247
- let r = n.sql, i = n.nextAlias(), a = mi(i, e.target, e.children, n);
1246
+ }, Ci = (e, t, n) => {
1247
+ let r = n.sql, i = n.nextAlias(), a = gi(i, e.target, e.children, n);
1248
1248
  if (a === null) return null;
1249
- let o = r`${z(void 0, e.foreignKey, r)} = ${z(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${I(U(e.branch.where), r)}`, c = fi(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${V(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${V(e.branch.offset, r)}`;
1249
+ let o = r`${z(void 0, e.foreignKey, r)} = ${z(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${I(W(e.branch.where), r)}`, c = mi(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${V(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${V(e.branch.offset, r)}`;
1250
1250
  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('[]'))`;
1251
- }, Si = (e, t, n) => {
1252
- let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = mi(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1251
+ }, wi = (e, t, n) => {
1252
+ let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = gi(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1253
1253
  projection: e.junction,
1254
- source: _i(o)
1254
+ source: yi(o)
1255
1255
  });
1256
1256
  if (c === null) return null;
1257
- let l = e.branch.where === void 0 ? r`` : r` AND ${I(U(e.branch.where), r)}`, u = Ri(e, s, r, !0), d = L(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${V(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${V(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : gi(e.junction, s, r);
1257
+ let l = e.branch.where === void 0 ? r`` : r` AND ${I(W(e.branch.where), r)}`, u = U(e, s, r, !0), d = L(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${V(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${V(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : vi(e.junction, s, r);
1258
1258
  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 ${z(o, "id", r)} = ${z(s, i.targetKey, r)} WHERE ${z(s, i.sourceKey, r)} = ${z(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), json('[]'))`;
1259
- }, Ci = (e, t, n) => {
1259
+ }, Ti = (e, t, n) => {
1260
1260
  let r = n.sql, i = n.nextAlias(), a = R(i, t.table, t.children, n);
1261
1261
  if (a === null) return null;
1262
- let o = e.predicate ? r` WHERE ${H(e.predicate, i, r)}` : r``, s = C(e).length > 0 ? r` ORDER BY ${r.csv(C(e).map((e) => e.direction === "desc" ? r`${z(i, e.column, r)} DESC` : r`${z(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${V(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${V(e.skip, r)}`;
1262
+ let o = e.predicate ? r` WHERE ${H(e.predicate, i, r)}` : r``, s = x(e).length > 0 ? r` ORDER BY ${r.csv(x(e).map((e) => e.direction === "desc" ? r`${z(i, e.column, r)} DESC` : r`${z(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${V(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${V(e.skip, r)}`;
1263
1263
  return r`SELECT ${a} AS \`__row\` FROM ${r(t.table.tableName)} AS ${r(i)}${o}${s}${c}${l}`;
1264
1264
  }, R = (e, t, n, r, i) => {
1265
1265
  let a = r.sql, o = [];
1266
1266
  for (let n of Object.keys(t.fields)) o.push(a`${B(n, a)}, ${z(e, n, a)}`);
1267
1267
  if (i !== void 0) {
1268
- let e = hi(i.projection, i.source, a);
1268
+ let e = _i(i.projection, i.source, a);
1269
1269
  o.push(a`${B("_junction", a)}, JSON_OBJECT(${e})`);
1270
1270
  }
1271
1271
  for (let t of n) {
1272
- let n = wi(t, e, r);
1272
+ let n = Ei(t, e, r);
1273
1273
  if (n === null) return null;
1274
1274
  o.push(a`${B(t.relationName, a)}, ${n}`);
1275
1275
  }
1276
1276
  return a`JSON_OBJECT(${a.csv(o)})`;
1277
- }, wi = (e, t, n) => {
1277
+ }, Ei = (e, t, n) => {
1278
1278
  switch (e.relation.kind) {
1279
1279
  case "one":
1280
- if (Wr(e)) {
1281
- let r = Gr(e);
1282
- return n.dialect === "mariadb" ? Oi(r, t, n) : Ei(r, t, n);
1280
+ if (Kr(e)) {
1281
+ let r = qr(e);
1282
+ return n.dialect === "mariadb" ? Ai(r, t, n) : Oi(r, t, n);
1283
1283
  }
1284
- return Ti(e, t, n);
1285
- case "many": return n.dialect === "mariadb" ? Oi(e, t, n) : Ei(e, t, n);
1286
- case "manyToMany": return n.dialect === "mariadb" ? ki(e, t, n) : Di(e, t, n);
1284
+ return Di(e, t, n);
1285
+ case "many": return n.dialect === "mariadb" ? Ai(e, t, n) : Oi(e, t, n);
1286
+ case "manyToMany": return n.dialect === "mariadb" ? ji(e, t, n) : ki(e, t, n);
1287
1287
  }
1288
- }, Ti = (e, t, n) => {
1288
+ }, Di = (e, t, n) => {
1289
1289
  let r = n.sql, i = n.nextAlias(), a = R(i, e.target, e.children, n);
1290
1290
  if (a === null) return null;
1291
1291
  let o = e.fkSide === "source" ? r`${z(i, "id", r)} = ${z(t, e.foreignKey, r)}` : r`${z(i, e.foreignKey, r)} = ${z(t, e.sourceKey, r)}`;
1292
1292
  return r`(SELECT ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o} LIMIT 1)`;
1293
- }, Ei = (e, t, n) => {
1293
+ }, Oi = (e, t, n) => {
1294
1294
  let r = n.sql, i = n.nextAlias(), a = R(i, e.target, e.children, n);
1295
1295
  if (a === null) return null;
1296
- let o = r`${z(void 0, e.foreignKey, r)} = ${z(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${I(U(e.branch.where), r)}`, c = fi(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${V(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${V(e.branch.offset, r)}`;
1296
+ let o = r`${z(void 0, e.foreignKey, r)} = ${z(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${I(W(e.branch.where), r)}`, c = mi(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${V(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${V(e.branch.offset, r)}`;
1297
1297
  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())`;
1298
- }, Di = (e, t, n) => {
1298
+ }, ki = (e, t, n) => {
1299
1299
  let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = R(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1300
1300
  projection: e.junction,
1301
- source: _i(o)
1301
+ source: yi(o)
1302
1302
  });
1303
1303
  if (c === null) return null;
1304
- let l = e.branch.where === void 0 ? r`` : r` AND ${I(U(e.branch.where), r)}`, u = Ri(e, s, r, !0), d = L(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${V(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${V(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : gi(e.junction, s, r);
1304
+ let l = e.branch.where === void 0 ? r`` : r` AND ${I(W(e.branch.where), r)}`, u = U(e, s, r, !0), d = L(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${V(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${V(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : vi(e.junction, s, r);
1305
1305
  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 ${z(o, "id", r)} = ${z(s, i.targetKey, r)} WHERE ${z(s, i.sourceKey, r)} = ${z(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), JSON_ARRAY())`;
1306
- }, Oi = (e, t, n) => {
1306
+ }, Ai = (e, t, n) => {
1307
1307
  let r = n.sql, i = n.nextAlias(), a = R(i, e.target, e.children, n);
1308
1308
  if (a === null) return null;
1309
- let o = r`${z(i, e.foreignKey, r)} = ${z(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${I(U(e.branch.where), r)}`, c = e.branch.orderBy ?? [];
1309
+ let o = r`${z(i, e.foreignKey, r)} = ${z(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${I(W(e.branch.where), r)}`, c = e.branch.orderBy ?? [];
1310
1310
  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`${z(i, e.column, r)} DESC` : r`${z(i, e.column, r)} ASC`))}` : r``}) FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o}${s}), JSON_ARRAY())`;
1311
1311
  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 ${z(i, "rn", r)} > ${V(d, r)} AND ${z(i, "rn", r)} <= ${V(d + u, r)}` : u === void 0 ? r` AND ${z(i, "rn", r)} > ${V(d, r)}` : r` AND ${z(i, "rn", r)} <= ${V(u, r)}`;
1312
1312
  return r`COALESCE((SELECT JSON_ARRAYAGG(${a} ORDER BY ${z(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())`;
1313
- }, ki = (e, t, n) => {
1313
+ }, ji = (e, t, n) => {
1314
1314
  let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = (t) => e.junction === void 0 ? void 0 : {
1315
1315
  projection: e.junction,
1316
1316
  source: t
1317
- }, l = r`${z(s, i.sourceKey, r)} = ${z(t, "id", r)}`, u = r`${z(o, "id", r)} = ${z(s, i.targetKey, r)}`, d = e.branch.where === void 0 ? r`` : r` AND ${I(U(e.branch.where), r)}`, f = Ri(e, s, r, !0), p = e.branch.orderBy ?? [];
1317
+ }, l = r`${z(s, i.sourceKey, r)} = ${z(t, "id", r)}`, u = r`${z(o, "id", r)} = ${z(s, i.targetKey, r)}`, d = e.branch.where === void 0 ? r`` : r` AND ${I(W(e.branch.where), r)}`, f = U(e, s, r, !0), p = e.branch.orderBy ?? [];
1318
1318
  if (e.branch.limit === void 0 && e.branch.offset === void 0) {
1319
- let t = R(o, e.target, e.children, n, c(vi(s)));
1319
+ let t = R(o, e.target, e.children, n, c(bi(s)));
1320
1320
  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`${z(o, e.column, r)} DESC` : r`${z(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())`;
1321
1321
  }
1322
- let m = p.length > 0 ? r` ORDER BY ${r.csv(p.map((e) => e.direction === "desc" ? r`${z(o, e.column, r)} DESC` : r`${z(o, e.column, r)} ASC`))}` : r` ORDER BY ${z(o, "id", r)}`, h = e.branch.limit, g = e.branch.offset, ee = h !== void 0 && g !== void 0 ? r` AND ${z(o, "rn", r)} > ${V(g, r)} AND ${z(o, "rn", r)} <= ${V(g + h, r)}` : h === void 0 ? r` AND ${z(o, "rn", r)} > ${V(g, r)}` : r` AND ${z(o, "rn", r)} <= ${V(h, r)}`, te = e.branch.onJunction === void 0 ? r`` : r` WHERE ${H(U(e.branch.onJunction), s, r)}`, ne = R(o, e.target, e.children, n, c(_i(o)));
1323
- if (ne === null) return null;
1324
- let re = e.junction === void 0 ? r`` : gi(e.junction, s, r);
1325
- return r`COALESCE((SELECT JSON_ARRAYAGG(${ne} ORDER BY ${z(o, "rn", r)}) FROM (SELECT ${r(o)}.*${re}, ${z(s, i.sourceKey, r)} AS ${r(`__src_${i.sourceKey}`)}, ROW_NUMBER() OVER (PARTITION BY ${z(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 ${z(o, `__src_${i.sourceKey}`, r)} = ${z(t, "id", r)}${d}${ee}), JSON_ARRAY())`;
1326
- }, Ai = (e, t, n) => {
1327
- let r = n.sql, i = n.nextAlias(), a = ji(i, t.table, t.children, n);
1322
+ let m = p.length > 0 ? r` ORDER BY ${r.csv(p.map((e) => e.direction === "desc" ? r`${z(o, e.column, r)} DESC` : r`${z(o, e.column, r)} ASC`))}` : r` ORDER BY ${z(o, "id", r)}`, h = e.branch.limit, g = e.branch.offset, _ = h !== void 0 && g !== void 0 ? r` AND ${z(o, "rn", r)} > ${V(g, r)} AND ${z(o, "rn", r)} <= ${V(g + h, r)}` : h === void 0 ? r` AND ${z(o, "rn", r)} > ${V(g, r)}` : r` AND ${z(o, "rn", r)} <= ${V(h, r)}`, ee = e.branch.onJunction === void 0 ? r`` : r` WHERE ${H(W(e.branch.onJunction), s, r)}`, te = R(o, e.target, e.children, n, c(yi(o)));
1323
+ if (te === null) return null;
1324
+ let ne = e.junction === void 0 ? r`` : vi(e.junction, s, r);
1325
+ return r`COALESCE((SELECT JSON_ARRAYAGG(${te} ORDER BY ${z(o, "rn", r)}) FROM (SELECT ${r(o)}.*${ne}, ${z(s, i.sourceKey, r)} AS ${r(`__src_${i.sourceKey}`)}, ROW_NUMBER() OVER (PARTITION BY ${z(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 ${z(o, `__src_${i.sourceKey}`, r)} = ${z(t, "id", r)}${d}${_}), JSON_ARRAY())`;
1326
+ }, Mi = (e, t, n) => {
1327
+ let r = n.sql, i = n.nextAlias(), a = Ni(i, t.table, t.children, n);
1328
1328
  if (a === null) return null;
1329
- let o = e.predicate ? r` WHERE ${H(e.predicate, i, r)}` : r``, s = C(e).length > 0 ? r` ORDER BY ${r.csv(C(e).map((e) => e.direction === "desc" ? r`${z(i, e.column, r)} DESC` : r`${z(i, e.column, r)} ASC`))}` : r``, c = r``, l = r``;
1329
+ let o = e.predicate ? r` WHERE ${H(e.predicate, i, r)}` : r``, s = x(e).length > 0 ? r` ORDER BY ${r.csv(x(e).map((e) => e.direction === "desc" ? r`${z(i, e.column, r)} DESC` : r`${z(i, e.column, r)} ASC`))}` : r``, c = r``, l = r``;
1330
1330
  if (e.skip !== void 0) {
1331
- let t = C(e).length > 0 ? s : r` ORDER BY (SELECT NULL)`;
1331
+ let t = x(e).length > 0 ? s : r` ORDER BY (SELECT NULL)`;
1332
1332
  l = e.take === void 0 ? r`${t} OFFSET ${V(e.skip, r)} ROWS` : r`${t} OFFSET ${V(e.skip, r)} ROWS FETCH NEXT ${V(e.take, r)} ROWS ONLY`;
1333
1333
  } else e.take !== void 0 && (c = r`TOP ${V(e.take, r)} `);
1334
1334
  let u = e.skip === void 0 ? s : r``;
1335
1335
  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}`;
1336
- }, ji = (e, t, n, r, i) => {
1336
+ }, Ni = (e, t, n, r, i) => {
1337
1337
  let a = r.sql, o = [];
1338
1338
  for (let n of Object.keys(t.fields)) o.push(a`${z(e, n, a)} AS ${a(n)}`);
1339
- if (i !== void 0) for (let e of i.projection.present) o.push(a`${z(i.source.alias, i.source.physical(e), a)} AS ${Mi(`_junction.${e}`, a)}`);
1339
+ if (i !== void 0) for (let e of i.projection.present) o.push(a`${z(i.source.alias, i.source.physical(e), a)} AS ${Pi(`_junction.${e}`, a)}`);
1340
1340
  for (let t of n) {
1341
- let n = Ni(t, e, r);
1341
+ let n = Fi(t, e, r);
1342
1342
  if (n === null) return null;
1343
1343
  o.push(n);
1344
1344
  }
1345
1345
  return a.csv(o);
1346
- }, Mi = (e, t) => t.unsafe(`[${e.replace(/]/g, "]]")}]`), Ni = (e, t, n) => {
1346
+ }, Pi = (e, t) => t.unsafe(`[${e.replace(/]/g, "]]")}]`), Fi = (e, t, n) => {
1347
1347
  switch (e.relation.kind) {
1348
- case "one": return Wr(e) ? Ii(Gr(e), t, n) : Pi(e, t, n);
1349
- case "many": return Ii(e, t, n);
1350
- case "manyToMany": return Li(e, t, n);
1348
+ case "one": return Kr(e) ? Ri(qr(e), t, n) : Ii(e, t, n);
1349
+ case "many": return Ri(e, t, n);
1350
+ case "manyToMany": return zi(e, t, n);
1351
1351
  }
1352
- }, Pi = (e, t, n) => {
1353
- let r = n.sql, i = n.nextAlias(), a = ji(i, e.target, e.children, n);
1352
+ }, Ii = (e, t, n) => {
1353
+ let r = n.sql, i = n.nextAlias(), a = Ni(i, e.target, e.children, n);
1354
1354
  if (a === null) return null;
1355
1355
  let o = e.fkSide === "source" ? r`${z(i, "id", r)} = ${z(t, e.foreignKey, r)}` : r`${z(i, e.foreignKey, r)} = ${z(t, e.sourceKey, r)}`;
1356
1356
  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)}`;
1357
- }, Fi = (e, t, n) => {
1357
+ }, Li = (e, t, n) => {
1358
1358
  if (e.offset !== void 0) {
1359
1359
  let r = e.orderBy && e.orderBy.length > 0 ? t : n` ORDER BY (SELECT NULL)`, i = e.limit === void 0 ? n`${r} OFFSET ${V(e.offset, n)} ROWS` : n`${r} OFFSET ${V(e.offset, n)} ROWS FETCH NEXT ${V(e.limit, n)} ROWS ONLY`;
1360
1360
  return {
@@ -1368,29 +1368,29 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
1368
1368
  pagination: n``,
1369
1369
  finalOrder: t
1370
1370
  };
1371
- }, Ii = (e, t, n) => {
1372
- let r = n.sql, i = n.nextAlias(), a = ji(i, e.target, e.children, n);
1371
+ }, Ri = (e, t, n) => {
1372
+ let r = n.sql, i = n.nextAlias(), a = Ni(i, e.target, e.children, n);
1373
1373
  if (a === null) return null;
1374
- let o = e.branch.where === void 0 ? r`` : r` AND ${H(e.branch.where, i, r)}`, s = L(i, e.branch.orderBy, r), { top: c, pagination: l, finalOrder: u } = Fi(e.branch, s, r);
1374
+ let o = e.branch.where === void 0 ? r`` : r` AND ${H(e.branch.where, i, r)}`, s = L(i, e.branch.orderBy, r), { top: c, pagination: l, finalOrder: u } = Li(e.branch, s, r);
1375
1375
  return r`ISNULL(JSON_QUERY((SELECT ${c}${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${z(i, e.foreignKey, r)} = ${z(t, e.sourceKey, r)}${o}${u}${l} FOR JSON PATH, INCLUDE_NULL_VALUES)), JSON_QUERY('[]')) AS ${r(e.relationName)}`;
1376
- }, Li = (e, t, n) => {
1377
- let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = ji(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1376
+ }, zi = (e, t, n) => {
1377
+ let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = Ni(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1378
1378
  projection: e.junction,
1379
- source: vi(s)
1379
+ source: bi(s)
1380
1380
  });
1381
1381
  if (c === null) return null;
1382
- let l = e.branch.where === void 0 ? r`` : r` AND ${H(e.branch.where, o, r)}`, u = Ri(e, s, r), d = L(o, e.branch.orderBy, r), { top: f, pagination: p, finalOrder: m } = Fi(e.branch, d, r);
1382
+ let l = e.branch.where === void 0 ? r`` : r` AND ${H(e.branch.where, o, r)}`, u = U(e, s, r), d = L(o, e.branch.orderBy, r), { top: f, pagination: p, finalOrder: m } = Li(e.branch, d, r);
1383
1383
  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 ${z(o, "id", r)} = ${z(s, i.targetKey, r)} WHERE ${z(s, i.sourceKey, r)} = ${z(t, "id", r)}${u}${l}${m}${p} FOR JSON PATH, INCLUDE_NULL_VALUES)), JSON_QUERY('[]')) AS ${r(e.relationName)}`;
1384
1384
  }, z = (e, t, n) => e === void 0 ? n`${n(t)}` : n`${n(e)}.${n(t)}`, B = (e, t) => t.unsafe(`'${e.replace(/'/g, "''")}'`), V = (e, t) => {
1385
1385
  if (!Number.isFinite(e) || !Number.isInteger(e) || e < 0) throw Error(`literalInt: expected non-negative integer, got ${e}`);
1386
1386
  return t.unsafe(String(e));
1387
- }, H = (e, t, n) => I(zi(e, t), n), Ri = (e, t, n, r = !1) => {
1387
+ }, H = (e, t, n) => I(Bi(e, t), n), U = (e, t, n, r = !1) => {
1388
1388
  let i = e.branch.onJunction;
1389
- return i === void 0 ? n`` : n` AND ${H(r ? U(i) : i, t, n)}`;
1390
- }, zi = (e, t) => {
1391
- if ("not" in e) return { not: zi(e.not, t) };
1392
- if ("and" in e) return { and: e.and.map((e) => zi(e, t)) };
1393
- if ("or" in e) return { or: e.or.map((e) => zi(e, t)) };
1389
+ return i === void 0 ? n`` : n` AND ${H(r ? W(i) : i, t, n)}`;
1390
+ }, Bi = (e, t) => {
1391
+ if ("not" in e) return { not: Bi(e.not, t) };
1392
+ if ("and" in e) return { and: e.and.map((e) => Bi(e, t)) };
1393
+ if ("or" in e) return { or: e.or.map((e) => Bi(e, t)) };
1394
1394
  if (e.op === "subquery-in" || e.op === "subquery-not-in") {
1395
1395
  let n = e;
1396
1396
  return {
@@ -1404,99 +1404,99 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
1404
1404
  ...n,
1405
1405
  column: `${t}.${n.column}`
1406
1406
  };
1407
- }, U = (e) => {
1408
- if ("not" in e) return { not: U(e.not) };
1409
- if ("and" in e) return { and: e.and.map((e) => U(e)) };
1410
- if ("or" in e) return { or: e.or.map((e) => U(e)) };
1407
+ }, W = (e) => {
1408
+ if ("not" in e) return { not: W(e.not) };
1409
+ if ("and" in e) return { and: e.and.map((e) => W(e)) };
1410
+ if ("or" in e) return { or: e.or.map((e) => W(e)) };
1411
1411
  if (e.op === "subquery-in" || e.op === "subquery-not-in" || e.op === "exists" || e.op === "not-exists") return e;
1412
1412
  let t = e;
1413
1413
  return {
1414
1414
  ...t,
1415
- value: Bi(t.value)
1415
+ value: Vi(t.value)
1416
1416
  };
1417
- }, Bi = (e) => e == null ? e : e instanceof Date ? e.toISOString() : typeof e == "boolean" ? +!!e : Array.isArray(e) ? e.map((e) => Bi(e)) : e, Vi = Symbol.for("@voltro/database/coreTablesRegistry"), Hi = globalThis, Ui = Hi[Vi] ?? (Hi[Vi] = {}), Wi = (e) => {
1418
- e.actors !== void 0 && (Ui.actors = e.actors), e.tenants !== void 0 && (Ui.tenants = e.tenants);
1419
- }, Gi = (e, t) => () => {
1417
+ }, Vi = (e) => e == null ? e : e instanceof Date ? e.toISOString() : typeof e == "boolean" ? +!!e : Array.isArray(e) ? e.map((e) => Vi(e)) : e, Hi = Symbol.for("@voltro/database/coreTablesRegistry"), Ui = globalThis, Wi = Ui[Hi] ?? (Ui[Hi] = {}), Gi = (e) => {
1418
+ e.actors !== void 0 && (Wi.actors = e.actors), e.tenants !== void 0 && (Wi.tenants = e.tenants);
1419
+ }, Ki = (e, t) => () => {
1420
1420
  let n = e();
1421
1421
  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`);
1422
1422
  return n();
1423
- }, Ki = () => Gi(() => Ui.actors, "actors"), qi = () => Gi(() => Ui.tenants, "tenants"), Ji = w("actors", {
1424
- id: a(),
1425
- kind: S().oneOf([
1423
+ }, qi = () => Ki(() => Wi.actors, "actors"), Ji = () => Ki(() => Wi.tenants, "tenants"), Yi = T("actors", {
1424
+ id: _(),
1425
+ kind: t().oneOf([
1426
1426
  "user",
1427
1427
  "serviceAccount",
1428
1428
  "apiKey",
1429
1429
  "system"
1430
1430
  ]),
1431
- displayName: S().nullable(),
1432
- createdAt: y().default("now")
1433
- }), Yi = (e, t) => ({
1431
+ displayName: t().nullable(),
1432
+ createdAt: C().default("now")
1433
+ }), Xi = (e, t) => ({
1434
1434
  column: e,
1435
1435
  op: "eq",
1436
1436
  value: t
1437
- }), Xi = (e, t) => ({
1437
+ }), Zi = (e, t) => ({
1438
1438
  column: e,
1439
1439
  op: "neq",
1440
1440
  value: t
1441
- }), Zi = (e, t) => ({
1441
+ }), Qi = (e, t) => ({
1442
1442
  column: e,
1443
1443
  op: "gt",
1444
1444
  value: t
1445
- }), Qi = (e, t) => ({
1445
+ }), $i = (e, t) => ({
1446
1446
  column: e,
1447
1447
  op: "gte",
1448
1448
  value: t
1449
- }), $i = (e, t) => ({
1449
+ }), ea = (e, t) => ({
1450
1450
  column: e,
1451
1451
  op: "lt",
1452
1452
  value: t
1453
- }), ea = (e, t) => ({
1453
+ }), ta = (e, t) => ({
1454
1454
  column: e,
1455
1455
  op: "lte",
1456
1456
  value: t
1457
- }), ta = (e, t) => ({
1457
+ }), na = (e, t) => ({
1458
1458
  column: e,
1459
1459
  op: "in",
1460
1460
  value: t
1461
- }), na = (e, t) => ({
1461
+ }), ra = (e, t) => ({
1462
1462
  column: e,
1463
1463
  op: "notIn",
1464
1464
  value: t
1465
- }), ra = (e, t) => ({
1465
+ }), ia = (e, t) => ({
1466
1466
  column: e,
1467
1467
  op: "contains",
1468
1468
  value: t
1469
- }), ia = (e, t) => ({
1469
+ }), aa = (e, t) => ({
1470
1470
  column: e,
1471
1471
  op: "startsWith",
1472
1472
  value: t
1473
- }), aa = (e, t) => ({
1473
+ }), oa = (e, t) => ({
1474
1474
  column: e,
1475
1475
  op: "arrayContains",
1476
1476
  value: t
1477
- }), oa = (e, t) => ({
1477
+ }), sa = (e, t) => ({
1478
1478
  column: e,
1479
1479
  op: "arrayOverlaps",
1480
1480
  value: t
1481
- }), sa = (e, t) => ({
1481
+ }), ca = (e, t) => ({
1482
1482
  column: e,
1483
1483
  op: "arrayHas",
1484
1484
  value: t
1485
- }), ca = {
1485
+ }), la = {
1486
1486
  column: "id",
1487
1487
  op: "in",
1488
1488
  value: []
1489
- }, la = (e) => ({
1489
+ }, ua = (e) => ({
1490
1490
  column: e,
1491
1491
  op: "isNull"
1492
- }), ua = (e) => ({
1492
+ }), da = (e) => ({
1493
1493
  column: e,
1494
1494
  op: "isNotNull"
1495
- }), da = (e, t) => ({
1495
+ }), fa = (e, t) => ({
1496
1496
  column: e,
1497
1497
  op: "spatial",
1498
1498
  value: t
1499
- }), fa = (...e) => ({ and: e }), pa = (...e) => ({ or: e }), ma = (e) => ({ not: e }), ha = (e, ...t) => {
1499
+ }), pa = (...e) => ({ and: e }), ma = (...e) => ({ or: e }), ha = (e) => ({ not: e }), ga = (e, ...t) => {
1500
1500
  if (t.length === 0) throw Error(`jsonField("${e}"): at least one path segment is required`);
1501
1501
  let n = (n, r) => ({
1502
1502
  column: e,
@@ -1518,33 +1518,33 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
1518
1518
  isNull: () => n("isNull"),
1519
1519
  isNotNull: () => n("isNotNull")
1520
1520
  };
1521
- }, ga = (e) => "descriptor" in e ? e.descriptor : e, _a = (e, t) => ({
1521
+ }, _a = (e) => "descriptor" in e ? e.descriptor : e, va = (e, t) => ({
1522
1522
  column: e,
1523
1523
  op: "subquery-in",
1524
- subquery: ga(t)
1525
- }), va = (e, t) => ({
1524
+ subquery: _a(t)
1525
+ }), ya = (e, t) => ({
1526
1526
  column: e,
1527
1527
  op: "subquery-not-in",
1528
- subquery: ga(t)
1529
- }), ya = (e) => ({
1530
- op: "exists",
1531
- subquery: ga(e)
1528
+ subquery: _a(t)
1532
1529
  }), ba = (e) => ({
1530
+ op: "exists",
1531
+ subquery: _a(e)
1532
+ }), xa = (e) => ({
1533
1533
  op: "not-exists",
1534
- subquery: ga(e)
1535
- }), xa = (e, t) => e === t || e instanceof Date && t instanceof Date && e.getTime() === t.getTime(), Sa = (e, t) => {
1534
+ subquery: _a(e)
1535
+ }), Sa = (e, t) => e === t || e instanceof Date && t instanceof Date && e.getTime() === t.getTime(), Ca = (e, t) => {
1536
1536
  if (e == null || t == null) return null;
1537
1537
  let n = e instanceof Date ? e.getTime() : e, r = t instanceof Date ? t.getTime() : t;
1538
1538
  return typeof n == typeof r ? n === r ? 0 : n > r ? 1 : -1 : null;
1539
- }, Ca = (e, t, n = null) => {
1539
+ }, wa = (e, t, n = null) => {
1540
1540
  if (!t) return !1;
1541
- if ("not" in e) return !Ca(e.not, t, n);
1541
+ if ("not" in e) return !wa(e.not, t, n);
1542
1542
  if ("and" in e) {
1543
- for (let r of e.and) if (!Ca(r, t, n)) return !1;
1543
+ for (let r of e.and) if (!wa(r, t, n)) return !1;
1544
1544
  return !0;
1545
1545
  }
1546
1546
  if ("or" in e) {
1547
- for (let r of e.or) if (Ca(r, t, n)) return !0;
1547
+ for (let r of e.or) if (wa(r, t, n)) return !0;
1548
1548
  return !1;
1549
1549
  }
1550
1550
  if (e.op === "subquery-in" || e.op === "subquery-not-in") {
@@ -1561,14 +1561,14 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
1561
1561
  }
1562
1562
  let r = e, i = t[r.column];
1563
1563
  switch (r.op) {
1564
- case "eq": return xa(i, r.value);
1565
- case "neq": return !xa(i, r.value);
1566
- case "gt": return (Sa(i, r.value) ?? -1) > 0;
1567
- case "gte": return (Sa(i, r.value) ?? -1) >= 0;
1568
- case "lt": return (Sa(i, r.value) ?? 1) < 0;
1569
- case "lte": return (Sa(i, r.value) ?? 1) <= 0;
1570
- case "in": return Array.isArray(r.value) && r.value.some((e) => xa(i, e));
1571
- case "notIn": return Array.isArray(r.value) && !r.value.some((e) => xa(i, e));
1564
+ case "eq": return Sa(i, r.value);
1565
+ case "neq": return !Sa(i, r.value);
1566
+ case "gt": return (Ca(i, r.value) ?? -1) > 0;
1567
+ case "gte": return (Ca(i, r.value) ?? -1) >= 0;
1568
+ case "lt": return (Ca(i, r.value) ?? 1) < 0;
1569
+ case "lte": return (Ca(i, r.value) ?? 1) <= 0;
1570
+ case "in": return Array.isArray(r.value) && r.value.some((e) => Sa(i, e));
1571
+ case "notIn": return Array.isArray(r.value) && !r.value.some((e) => Sa(i, e));
1572
1572
  case "contains": return typeof i == "string" && typeof r.value == "string" && i.toLowerCase().includes(r.value.toLowerCase());
1573
1573
  case "startsWith": return typeof i == "string" && typeof r.value == "string" && i.startsWith(r.value);
1574
1574
  case "arrayContains": {
@@ -1584,17 +1584,17 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
1584
1584
  case "isNotNull": return i != null;
1585
1585
  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.");
1586
1586
  }
1587
- }, wa = function* (e) {
1587
+ }, Ta = function* (e) {
1588
1588
  if ("not" in e) {
1589
- yield* wa(e.not);
1589
+ yield* Ta(e.not);
1590
1590
  return;
1591
1591
  }
1592
1592
  if ("and" in e) {
1593
- for (let t of e.and) yield* wa(t);
1593
+ for (let t of e.and) yield* Ta(t);
1594
1594
  return;
1595
1595
  }
1596
1596
  if ("or" in e) {
1597
- for (let t of e.or) yield* wa(t);
1597
+ for (let t of e.or) yield* Ta(t);
1598
1598
  return;
1599
1599
  }
1600
1600
  e.op === "subquery-in" || e.op === "subquery-not-in" ? yield {
@@ -1604,46 +1604,46 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
1604
1604
  kind: "exists",
1605
1605
  descriptor: e.subquery
1606
1606
  });
1607
- }, Ta = function* (e, t = !0) {
1607
+ }, Ea = function* (e, t = !0) {
1608
1608
  if ("not" in e) {
1609
- yield* Ta(e.not, !1);
1609
+ yield* Ea(e.not, !1);
1610
1610
  return;
1611
1611
  }
1612
1612
  if ("and" in e) {
1613
- for (let n of e.and) yield* Ta(n, t);
1613
+ for (let n of e.and) yield* Ea(n, t);
1614
1614
  return;
1615
1615
  }
1616
1616
  if ("or" in e) {
1617
- for (let t of e.or) yield* Ta(t, !1);
1617
+ for (let t of e.or) yield* Ea(t, !1);
1618
1618
  return;
1619
1619
  }
1620
1620
  e.op !== "subquery-in" && e.op !== "subquery-not-in" && e.op !== "exists" && e.op !== "not-exists" && (yield {
1621
1621
  ...e,
1622
1622
  conjunctive: t
1623
1623
  });
1624
- }, Ea = (e, t) => ({
1624
+ }, Da = (e, t) => ({
1625
1625
  ...t,
1626
1626
  ...e,
1627
1627
  origin: e.origin ?? "injected"
1628
- }), Da = (e, t, n = {}) => ({
1628
+ }), Oa = (e, t, n = {}) => ({
1629
1629
  table: e,
1630
1630
  op: "insert",
1631
1631
  old: null,
1632
1632
  new: t,
1633
1633
  ...n
1634
- }), Oa = (e, t, n, r = {}) => ({
1634
+ }), ka = (e, t, n, r = {}) => ({
1635
1635
  table: e,
1636
1636
  op: "update",
1637
1637
  old: t,
1638
1638
  new: n,
1639
1639
  ...r
1640
- }), ka = (e, t, n = {}) => ({
1640
+ }), Aa = (e, t, n = {}) => ({
1641
1641
  table: e,
1642
1642
  op: "delete",
1643
1643
  old: t,
1644
1644
  new: null,
1645
1645
  ...n
1646
- }), Aa = (e, t, n = {}) => {
1646
+ }), ja = (e, t, n = {}) => {
1647
1647
  let { at: r = "2026-01-01T00:00:00.000Z", column: i = "deletedAt", ...a } = n;
1648
1648
  return {
1649
1649
  table: e,
@@ -1658,67 +1658,67 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
1658
1658
  },
1659
1659
  ...a
1660
1660
  };
1661
- }, ja = new It(), Ma = (e, t) => ja.run(e, t), Na = () => ja.getStore(), Pa = (e) => {
1662
- let t = e ?? ja.getStore();
1661
+ }, Ma = new Lt(), Na = (e, t) => Ma.run(e, t), Pa = () => Ma.getStore(), Fa = (e) => {
1662
+ let t = e ?? Ma.getStore();
1663
1663
  return t === void 0 ? {} : {
1664
1664
  ...t.traceId === void 0 ? {} : { traceId: t.traceId },
1665
1665
  ...t.subjectId === void 0 ? {} : { subjectId: t.subjectId },
1666
1666
  ...t.procedure === void 0 ? {} : { procedure: t.procedure },
1667
1667
  ...t.via === void 0 ? {} : { via: t.via }
1668
1668
  };
1669
- }, Fa = (e) => {
1670
- let t = ja.getStore();
1671
- return t === void 0 ? e(void 0) : ja.run(t, () => e(t));
1672
- }, Ia = 3e4, La = 1e4, W = /* @__PURE__ */ new Map(), G = 0, Ra = (e, t, n) => `${e}\u0000${t}\u0000${String(n)}`, za = (e) => {
1673
- for (let [t, n] of W) {
1674
- let r = n.filter((t) => e - t.at < Ia);
1675
- G -= n.length - r.length, r.length === 0 ? W.delete(t) : r.length !== n.length && W.set(t, r);
1676
- }
1677
- }, Ba = (e, t) => {
1669
+ }, Ia = (e) => {
1670
+ let t = Ma.getStore();
1671
+ return t === void 0 ? e(void 0) : Ma.run(t, () => e(t));
1672
+ }, La = 3e4, Ra = 1e4, G = /* @__PURE__ */ new Map(), K = 0, za = (e, t, n) => `${e}\u0000${t}\u0000${String(n)}`, Ba = (e) => {
1673
+ for (let [t, n] of G) {
1674
+ let r = n.filter((t) => e - t.at < La);
1675
+ K -= n.length - r.length, r.length === 0 ? G.delete(t) : r.length !== n.length && G.set(t, r);
1676
+ }
1677
+ }, Va = (e, t) => {
1678
1678
  if (t.traceId === void 0 && t.subjectId === void 0 && t.procedure === void 0) return;
1679
1679
  let n = Date.now();
1680
- if (G >= La && za(n), G >= La) return;
1681
- let r = W.get(e);
1682
- r === void 0 ? W.set(e, [{
1680
+ if (K >= Ra && Ba(n), K >= Ra) return;
1681
+ let r = G.get(e);
1682
+ r === void 0 ? G.set(e, [{
1683
1683
  attribution: t,
1684
1684
  at: n
1685
1685
  }]) : r.push({
1686
1686
  attribution: t,
1687
1687
  at: n
1688
- }), G += 1;
1689
- }, Va = (e) => {
1690
- let t = W.get(e);
1688
+ }), K += 1;
1689
+ }, Ha = (e) => {
1690
+ let t = G.get(e);
1691
1691
  if (t === void 0 || t.length === 0) return;
1692
1692
  let n = t.shift();
1693
- if (--G, t.length === 0 && W.delete(e), !(Date.now() - n.at >= Ia)) return n.attribution;
1694
- }, Ha = (e) => (W.get(e)?.length ?? 0) > 0, K = /* @__PURE__ */ new Map(), Ua = /* @__PURE__ */ new Map(), Wa = /* @__PURE__ */ new Map(), Ga = 250, Ka = (e) => {
1695
- let t = Ua.get(e);
1693
+ if (--K, t.length === 0 && G.delete(e), !(Date.now() - n.at >= La)) return n.attribution;
1694
+ }, Ua = (e) => (G.get(e)?.length ?? 0) > 0, q = /* @__PURE__ */ new Map(), Wa = /* @__PURE__ */ new Map(), Ga = /* @__PURE__ */ new Map(), Ka = 250, qa = (e) => {
1695
+ let t = Wa.get(e);
1696
1696
  if (t === void 0) return;
1697
- Ua.delete(e);
1698
- let n = Wa.get(e);
1699
- n !== void 0 && (clearTimeout(n), Wa.delete(e));
1697
+ Wa.delete(e);
1698
+ let n = Ga.get(e);
1699
+ n !== void 0 && (clearTimeout(n), Ga.delete(e));
1700
1700
  for (let e of t) e();
1701
- }, qa = (e) => {
1702
- K.set(e, (K.get(e) ?? 0) + 1);
1703
1701
  }, Ja = (e) => {
1704
- let t = (K.get(e) ?? 0) - 1;
1702
+ q.set(e, (q.get(e) ?? 0) + 1);
1703
+ }, Ya = (e) => {
1704
+ let t = (q.get(e) ?? 0) - 1;
1705
1705
  if (t > 0) {
1706
- K.set(e, t);
1706
+ q.set(e, t);
1707
1707
  return;
1708
1708
  }
1709
- K.delete(e), Ka(e);
1710
- }, Ya = (e, t, n, r) => {
1711
- let i = n == null ? void 0 : Ra(e, t, n), a = () => r(i === void 0 ? void 0 : Va(i));
1709
+ q.delete(e), qa(e);
1710
+ }, Xa = (e, t, n, r) => {
1711
+ let i = n == null ? void 0 : za(e, t, n), a = () => r(i === void 0 ? void 0 : Ha(i));
1712
1712
  if (i === void 0) {
1713
1713
  a();
1714
1714
  return;
1715
1715
  }
1716
- if (Ha(i)) {
1716
+ if (Ua(i)) {
1717
1717
  a();
1718
1718
  return;
1719
1719
  }
1720
- let o = Ua.get(e);
1721
- if (o === void 0 && (K.get(e) ?? 0) === 0) {
1720
+ let o = Wa.get(e);
1721
+ if (o === void 0 && (q.get(e) ?? 0) === 0) {
1722
1722
  a();
1723
1723
  return;
1724
1724
  }
@@ -1726,91 +1726,91 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
1726
1726
  o.push(a);
1727
1727
  return;
1728
1728
  }
1729
- Ua.set(e, [a]);
1730
- let s = setTimeout(() => Ka(e), Ga);
1731
- typeof s == "object" && typeof s.unref == "function" && s.unref(), Wa.set(e, s);
1732
- }, Xa = () => {
1733
- W.clear(), G = 0, K.clear();
1734
- for (let e of Wa.values()) clearTimeout(e);
1735
- Wa.clear(), Ua.clear();
1736
- }, Za = () => G, Qa = 64, $a = "\0", eo = 32, to = (e, ...t) => `${e}_${Lt("sha256").update(t.map(String).join($a)).digest("hex").slice(0, eo)}`, no = (e) => e.length + 1 + eo, q = /* @__PURE__ */ new Map(), ro = (e, t) => {
1737
- q.set(e, {
1729
+ Wa.set(e, [a]);
1730
+ let s = setTimeout(() => qa(e), Ka);
1731
+ typeof s == "object" && typeof s.unref == "function" && s.unref(), Ga.set(e, s);
1732
+ }, Za = () => {
1733
+ G.clear(), K = 0, q.clear();
1734
+ for (let e of Ga.values()) clearTimeout(e);
1735
+ Ga.clear(), Wa.clear();
1736
+ }, Qa = () => K, $a = 64, eo = "\0", to = 32, no = (e, ...t) => `${e}_${Rt("sha256").update(t.map(String).join(eo)).digest("hex").slice(0, to)}`, ro = (e) => e.length + 1 + to, J = /* @__PURE__ */ new Map(), io = (e, t) => {
1737
+ J.set(e, {
1738
1738
  recorder: t.recorder,
1739
1739
  tables: new Set(t.tables),
1740
1740
  ownTables: new Set(t.ownTables)
1741
1741
  });
1742
- }, io = (e) => {
1743
- q.delete(e);
1744
- }, ao = () => q.clear(), oo = new It(), so = (e) => oo.run({ n: 1 }, e), co = (e) => E.suspend(() => {
1745
- let t = oo.getStore();
1746
- if (t !== void 0) return t.n += 1, E.ensuring(e, E.sync(() => {
1742
+ }, ao = (e) => {
1743
+ J.delete(e);
1744
+ }, oo = () => J.clear(), so = new Lt(), co = (e) => so.run({ n: 1 }, e), lo = (e) => D.suspend(() => {
1745
+ let t = so.getStore();
1746
+ if (t !== void 0) return t.n += 1, D.ensuring(e, D.sync(() => {
1747
1747
  --t.n;
1748
1748
  }));
1749
1749
  let n = { n: 1 };
1750
- return oo.enterWith(n), E.ensuring(e, E.sync(() => {
1750
+ return so.enterWith(n), D.ensuring(e, D.sync(() => {
1751
1751
  --n.n;
1752
1752
  }));
1753
- }), lo = () => (oo.getStore()?.n ?? 0) > 0, uo = (e) => {
1754
- if (q.size === 0 || (oo.getStore()?.n ?? 0) > 0) return !1;
1755
- for (let t of q.values()) if (!t.ownTables.has(e) && t.tables.has(e)) return !0;
1753
+ }), uo = () => (so.getStore()?.n ?? 0) > 0, fo = (e) => {
1754
+ if (J.size === 0 || (so.getStore()?.n ?? 0) > 0) return !1;
1755
+ for (let t of J.values()) if (!t.ownTables.has(e) && t.tables.has(e)) return !0;
1756
1756
  return !1;
1757
- }, fo = async (e, t) => {
1758
- if (q.size !== 0) {
1759
- for (let [n, r] of q.entries()) if (!r.ownTables.has(t.table) && r.tables.has(t.table)) try {
1757
+ }, po = async (e, t) => {
1758
+ if (J.size !== 0) {
1759
+ for (let [n, r] of J.entries()) if (!r.ownTables.has(t.table) && r.tables.has(t.table)) try {
1760
1760
  await r.recorder(e, t);
1761
1761
  } catch (e) {
1762
- let r = hn(e);
1762
+ let r = gn(e);
1763
1763
  throw r === void 0 ? e : Error(`write recorder '${n}' failed while recording a ${t.op} on '${t.table}': ${r}`, { cause: e });
1764
1764
  }
1765
1765
  }
1766
- }, po = Mt.exponential({
1766
+ }, mo = Nt.exponential({
1767
1767
  start: 5e-4,
1768
1768
  factor: 2,
1769
1769
  count: 16
1770
- }), mo = D.counter("voltro_db_queries_total", { description: "Database operations executed, by dialect and operation kind." }), ho = D.histogram("voltro_db_query_duration_seconds", po, "Database operation duration in seconds, by dialect and operation kind."), go = D.counter("voltro_db_errors_total", { description: "Database operations that threw, by dialect and operation kind." }), _o = D.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." }), vo = D.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." }), yo = [], bo = /* @__PURE__ */ new Map(), xo = /* @__PURE__ */ new Map(), So = /* @__PURE__ */ new Map(), Co = (e, t) => {
1771
- let n = `${e}\u0000${t}`, r = bo.get(n);
1770
+ }), ho = O.counter("voltro_db_queries_total", { description: "Database operations executed, by dialect and operation kind." }), go = O.histogram("voltro_db_query_duration_seconds", mo, "Database operation duration in seconds, by dialect and operation kind."), _o = O.counter("voltro_db_errors_total", { description: "Database operations that threw, by dialect and operation kind." }), vo = 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." }), yo = 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." }), bo = [], xo = /* @__PURE__ */ new Map(), So = /* @__PURE__ */ new Map(), Co = /* @__PURE__ */ new Map(), wo = (e, t) => {
1771
+ let n = `${e}\u0000${t}`, r = xo.get(n);
1772
1772
  if (r !== void 0) return r;
1773
- let i = (n) => D.tagged(D.tagged(n, "dialect", e), "op", t), a = {
1774
- count: i(mo),
1775
- duration: i(ho),
1776
- errors: i(go)
1773
+ let i = (n) => O.tagged(O.tagged(n, "dialect", e), "op", t), a = {
1774
+ count: i(ho),
1775
+ duration: i(go),
1776
+ errors: i(_o)
1777
1777
  };
1778
- return bo.set(n, a), a;
1779
- }, wo = () => {
1780
- bo.clear(), xo.clear(), So.clear();
1781
- }, To = () => bo.size + xo.size + So.size, Eo = /* @__PURE__ */ new Map(), Do = (e, t) => {
1782
- let n = Math.max(0, (Eo.get(e) ?? 0) + t);
1783
- n === 0 ? Eo.delete(e) : Eo.set(e, n);
1784
- let r = xo.get(e);
1785
- r === void 0 && (r = D.tagged(_o, "dialect", e), xo.set(e, r)), r.unsafeUpdate(n, yo);
1786
- }, Oo = (e) => Eo.get(e) ?? 0, ko = (e) => {
1787
- let t = Co(String(e.dialect), e.op);
1788
- t.count.unsafeUpdate(1, yo), t.duration.unsafeUpdate(e.durationMs / 1e3, yo), e.status === "error" && t.errors.unsafeUpdate(1, yo);
1789
- }, Ao = async (e, t, n) => {
1778
+ return xo.set(n, a), a;
1779
+ }, To = () => {
1780
+ xo.clear(), So.clear(), Co.clear();
1781
+ }, Eo = () => xo.size + So.size + Co.size, Do = /* @__PURE__ */ new Map(), Oo = (e, t) => {
1782
+ let n = Math.max(0, (Do.get(e) ?? 0) + t);
1783
+ n === 0 ? Do.delete(e) : Do.set(e, n);
1784
+ let r = So.get(e);
1785
+ r === void 0 && (r = O.tagged(vo, "dialect", e), So.set(e, r)), r.unsafeUpdate(n, bo);
1786
+ }, ko = (e) => Do.get(e) ?? 0, Ao = (e) => {
1787
+ let t = wo(String(e.dialect), e.op);
1788
+ t.count.unsafeUpdate(1, bo), t.duration.unsafeUpdate(e.durationMs / 1e3, bo), e.status === "error" && t.errors.unsafeUpdate(1, bo);
1789
+ }, jo = async (e, t, n) => {
1790
1790
  let r = performance.now(), i = String(e);
1791
- Do(i, 1);
1791
+ Oo(i, 1);
1792
1792
  let a = "ok";
1793
1793
  try {
1794
1794
  return await n();
1795
1795
  } catch (e) {
1796
1796
  throw a = "error", e;
1797
1797
  } finally {
1798
- Do(i, -1), ko({
1798
+ Oo(i, -1), Ao({
1799
1799
  dialect: e,
1800
1800
  op: t,
1801
1801
  durationMs: performance.now() - r,
1802
1802
  status: a
1803
1803
  });
1804
1804
  }
1805
- }, jo = 3e5, Mo = (e) => {
1805
+ }, Mo = 3e5, No = (e) => {
1806
1806
  if (e == null || e === "") return;
1807
1807
  let t = Number(e);
1808
1808
  return Number.isFinite(t) && t >= 0 ? Math.floor(t) : void 0;
1809
- }, No = (e, t = process.env) => Mo(t.VOLTRO_DB_EAGER_FALLBACK_WARN_INTERVAL_MS) ?? Mo(e) ?? 3e5, Po = (e, t = {}) => {
1810
- let n = No(t.warnIntervalMs), r = t.now ?? (() => Date.now()), i = /* @__PURE__ */ new Map();
1809
+ }, Po = (e, t = process.env) => No(t.VOLTRO_DB_EAGER_FALLBACK_WARN_INTERVAL_MS) ?? No(e) ?? 3e5, Fo = (e, t = {}) => {
1810
+ let n = Po(t.warnIntervalMs), r = t.now ?? (() => Date.now()), i = /* @__PURE__ */ new Map();
1811
1811
  return (t) => {
1812
- let a = `${t.dialect} ${t.reason}`, o = So.get(a);
1813
- o === void 0 && (o = D.tagged(D.tagged(vo, "dialect", String(t.dialect)), "reason", t.reason), So.set(a, o)), o.unsafeUpdate(1, yo);
1812
+ let a = `${t.dialect} ${t.reason}`, o = Co.get(a);
1813
+ o === void 0 && (o = O.tagged(O.tagged(yo, "dialect", String(t.dialect)), "reason", t.reason), Co.set(a, o)), o.unsafeUpdate(1, bo);
1814
1814
  let s = `${t.table}\u0000${t.reason}`, c = i.get(s), l = c === void 0 || n > 0 && r() - c >= n, u = {
1815
1815
  table: t.table,
1816
1816
  dialect: String(t.dialect),
@@ -1824,24 +1824,24 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
1824
1824
  }
1825
1825
  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);
1826
1826
  };
1827
- }, Fo = (e) => {
1828
- if (jt.isSuccess(e)) return e.value;
1829
- throw Ot.squash(e.cause);
1830
- }, Io = "10 millis", Lo = 3, Ro = async (e) => {
1831
- let t = 0, n = E.suspend(() => {
1827
+ }, Io = (e) => {
1828
+ if (Mt.isSuccess(e)) return e.value;
1829
+ throw kt.squash(e.cause);
1830
+ }, Lo = "10 millis", Ro = 3, zo = async (e) => {
1831
+ let t = 0, n = D.suspend(() => {
1832
1832
  let n = ++t;
1833
- return e.withTransaction(E.flatMap(E.serviceOption(Rt), (t) => {
1834
- if (O.isNone(t)) return E.fail(/* @__PURE__ */ Error(`${e.label}: TransactionConnection unexpectedly missing inside withTransaction.`));
1835
- let r = t.value, i = E.tryPromise({
1833
+ return e.withTransaction(D.flatMap(D.serviceOption(zt), (t) => {
1834
+ if (k.isNone(t)) return D.fail(/* @__PURE__ */ Error(`${e.label}: TransactionConnection unexpectedly missing inside withTransaction.`));
1835
+ let r = t.value, i = D.tryPromise({
1836
1836
  try: () => e.body(r, n),
1837
1837
  catch: (e) => e
1838
1838
  });
1839
- return e.prepare === void 0 ? i : E.flatMap(e.prepare(r), () => i);
1840
- })).pipe(E.catchAllDefect((t) => e.isRetryable(t) ? E.fail(t) : E.die(t)));
1841
- }), r = Pt.exponential(Io).pipe(Pt.compose(Pt.recurs(Lo)), Pt.whileInput(e.isRetryable)), i = n.pipe(E.retry(r), E.withSpan(e.span.name, { attributes: { ...e.span.attributes } }));
1842
- return Ao(e.dialect, "transaction", async () => Fo(await e.runPromiseExit(e.wrapProgram === void 0 ? i : e.wrapProgram(i))));
1843
- }, zo = async (e) => {
1844
- let t = Na(), n = t === void 0 ? (e) => e() : (e) => Ma(t, e), r = await Ro({
1839
+ return e.prepare === void 0 ? i : D.flatMap(e.prepare(r), () => i);
1840
+ })).pipe(D.catchAllDefect((t) => e.isRetryable(t) ? D.fail(t) : D.die(t)));
1841
+ }), r = Ft.exponential(Lo).pipe(Ft.compose(Ft.recurs(Ro)), Ft.whileInput(e.isRetryable)), i = n.pipe(D.retry(r), D.withSpan(e.span.name, { attributes: { ...e.span.attributes } }));
1842
+ return jo(e.dialect, "transaction", async () => Io(await e.runPromiseExit(e.wrapProgram === void 0 ? i : e.wrapProgram(i))));
1843
+ }, Bo = async (e) => {
1844
+ let t = Pa(), n = t === void 0 ? (e) => e() : (e) => Na(t, e), r = await zo({
1845
1845
  ...e,
1846
1846
  body: (r) => {
1847
1847
  let i = e.makeView(r, t);
@@ -1852,14 +1852,14 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
1852
1852
  }
1853
1853
  });
1854
1854
  return r.view.commitEvents(), r.result;
1855
- }, Bo = class extends k.TaggedError()("VersionConflict", {
1856
- table: k.String,
1857
- id: k.String,
1858
- expected: k.Number,
1859
- actual: k.NullOr(k.Number)
1860
- }) {}, Vo = (e) => {
1855
+ }, Vo = class extends A.TaggedError()("VersionConflict", {
1856
+ table: A.String,
1857
+ id: A.String,
1858
+ expected: A.Number,
1859
+ actual: A.NullOr(A.Number)
1860
+ }) {}, Ho = (e) => {
1861
1861
  for (let [t, n] of Object.entries(e)) if (n?.definition?.versionColumn === !0) return t;
1862
- }, Ho = (e) => {
1862
+ }, Uo = (e) => {
1863
1863
  let { versionColumn: t, patch: n } = e;
1864
1864
  if (t === void 0) return {
1865
1865
  nextVersion: void 0,
@@ -1872,28 +1872,28 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
1872
1872
  expected: i,
1873
1873
  patch: a
1874
1874
  };
1875
- }, Uo = (e) => {
1876
- if (e.expected !== void 0 && (e.current === null || e.current !== e.expected)) return new Bo({
1875
+ }, Wo = (e) => {
1876
+ if (e.expected !== void 0 && (e.current === null || e.current !== e.expected)) return new Vo({
1877
1877
  table: e.table,
1878
1878
  id: e.id,
1879
1879
  expected: e.expected,
1880
1880
  actual: e.current
1881
1881
  });
1882
- }, Wo = 1, Go = "voltro/expires", Ko = () => Ye({
1883
- id: Go,
1884
- fields: { expiresAt: y().nullable() },
1882
+ }, Go = 1, Ko = "voltro/expires", qo = () => it({
1883
+ id: Ko,
1884
+ fields: { expiresAt: C().nullable() },
1885
1885
  behaviors: { defaultWhere: () => "expiresAt IS NULL OR expiresAt > now()" }
1886
- }), qo = "voltro/localFirst", Jo = () => Ye({
1887
- id: qo,
1886
+ }), Jo = "voltro/localFirst", Yo = () => it({
1887
+ id: Jo,
1888
1888
  fields: {}
1889
- }), Yo = (e) => e.appliedMixins.some((e) => e.id === qo), Xo = (e) => {
1889
+ }), Xo = (e) => e.appliedMixins.some((e) => e.id === Jo), Zo = (e) => {
1890
1890
  let t = [];
1891
- for (let n of Object.values(e)) Yo(n) && t.push(n.tableName);
1891
+ for (let n of Object.values(e)) Xo(n) && t.push(n.tableName);
1892
1892
  return t;
1893
- }, Zo = class extends At.TaggedError("TableStreamError") {}, Qo = 1e3, $o = (e, t, n, r) => {
1894
- let i = O.match(r, {
1893
+ }, Qo = class extends jt.TaggedError("TableStreamError") {}, $o = 1e3, es = (e, t, n, r) => {
1894
+ let i = k.match(r, {
1895
1895
  onNone: () => e.where,
1896
- onSome: (n) => e.where ? fa(e.where, Zi(t, n)) : Zi(t, n)
1896
+ onSome: (n) => e.where ? pa(e.where, Qi(t, n)) : Qi(t, n)
1897
1897
  });
1898
1898
  return {
1899
1899
  table: e.table,
@@ -1908,19 +1908,19 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
1908
1908
  ...e.includeDeleted === void 0 ? {} : { includeDeleted: e.includeDeleted },
1909
1909
  ...e.crossTenant === void 0 ? {} : { crossTenant: e.crossTenant }
1910
1910
  };
1911
- }, es = (e, t) => {
1912
- let n = t.pk ?? "id", r = t.chunkSize ?? Qo;
1913
- return Ft.paginateChunkEffect(O.none(), (i) => {
1914
- let a = E.tryPromise({
1915
- try: () => e.query($o(t, n, r, i)),
1916
- catch: (e) => new Zo({
1911
+ }, ts = (e, t) => {
1912
+ let n = t.pk ?? "id", r = t.chunkSize ?? $o;
1913
+ return It.paginateChunkEffect(k.none(), (i) => {
1914
+ let a = D.tryPromise({
1915
+ try: () => e.query(es(t, n, r, i)),
1916
+ catch: (e) => new Qo({
1917
1917
  table: t.table,
1918
1918
  cause: e
1919
1919
  })
1920
1920
  });
1921
- return (t.retry ? a.pipe(E.retry(t.retry)) : a).pipe(E.map((e) => [kt.fromIterable(e), e.length === r && e.length > 0 ? O.some(O.some(e[e.length - 1][n])) : O.none()]));
1921
+ 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()]));
1922
1922
  });
1923
- }, ts = (e) => {
1923
+ }, ns = (e) => {
1924
1924
  let t = e.alpha ?? .5;
1925
1925
  if (t < 0 || t > 1) throw Error(`hybridSearch: alpha must be in [0, 1], got ${t}`);
1926
1926
  return (n) => {
@@ -1934,7 +1934,7 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
1934
1934
  queryText: e.vector.query,
1935
1935
  distance: e.vector.distance ?? "cosine",
1936
1936
  alpha: t
1937
- }, i = te(n.table, e.fts.indexName, n.fullTextIndexes);
1937
+ }, i = me(n.table, e.fts.indexName, n.fullTextIndexes);
1938
1938
  return {
1939
1939
  ...n,
1940
1940
  annClause: r,
@@ -1947,19 +1947,19 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
1947
1947
  }
1948
1948
  };
1949
1949
  };
1950
- }, ns = async (e, t) => {
1950
+ }, rs = async (e, t) => {
1951
1951
  let n = e.as ?? "embedding", r = t.row[e.from];
1952
1952
  if (typeof r != "string" || r.length === 0) return {};
1953
1953
  let i = await t.embed(r);
1954
1954
  return { [n]: i };
1955
- }, rs = (e) => {
1955
+ }, is = (e) => {
1956
1956
  if (!Number.isInteger(e.dimensions) || e.dimensions <= 0) throw Error(`vectorEmbedding: dimensions must be a positive integer, got ${String(e.dimensions)}.`);
1957
- let n = e.as ?? "embedding", r = (t) => ns(e, t);
1958
- return Ye({
1957
+ let t = e.as ?? "embedding", n = (t) => rs(e, t);
1958
+ return it({
1959
1959
  id: "voltro/vectorEmbedding",
1960
- fields: { [n]: t(e.dimensions) },
1960
+ fields: { [t]: pt(e.dimensions) },
1961
1961
  ...e.index === !1 ? {} : { indexes: [{
1962
- fields: [n],
1962
+ fields: [t],
1963
1963
  kind: "hnsw",
1964
1964
  kindOptions: { hnsw: {
1965
1965
  ...e.index?.m === void 0 ? {} : { m: e.index.m },
@@ -1968,23 +1968,23 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
1968
1968
  } }
1969
1969
  }] },
1970
1970
  behaviors: {
1971
- beforeInsert: r,
1972
- beforeUpdate: r
1971
+ beforeInsert: n,
1972
+ beforeUpdate: n
1973
1973
  }
1974
1974
  });
1975
- }, is = 63, as = "br_pr", J = class extends Error {
1975
+ }, as = 63, os = "br_pr", Y = class extends Error {
1976
1976
  _tag = "BranchNameInvalid";
1977
1977
  constructor(e) {
1978
1978
  super(e), this.name = "BranchNameInvalid";
1979
1979
  }
1980
- }, os = (e, t) => {
1981
- if (!Number.isInteger(t) || t < 0) throw new J(`prNumber must be a non-negative integer, got ${String(t)}`);
1982
- let n = wr(e);
1983
- if (n.replace(/_/g, "") === "") throw new J(`app slug '${e}' has no usable identifier characters`);
1984
- let r = `${as}${t}_${n}`;
1985
- if (r.length > is) throw new J(`branch namespace '${r}' exceeds the ${is}-byte identifier limit — use a shorter app slug`);
1980
+ }, ss = (e, t) => {
1981
+ if (!Number.isInteger(t) || t < 0) throw new Y(`prNumber must be a non-negative integer, got ${String(t)}`);
1982
+ let n = Tr(e);
1983
+ if (n.replace(/_/g, "") === "") throw new Y(`app slug '${e}' has no usable identifier characters`);
1984
+ let r = `${os}${t}_${n}`;
1985
+ if (r.length > as) throw new Y(`branch namespace '${r}' exceeds the ${as}-byte identifier limit — use a shorter app slug`);
1986
1986
  return r;
1987
- }, ss = (e) => e.startsWith(as), cs = {
1987
+ }, cs = (e) => e.startsWith(os), ls = {
1988
1988
  requested: {
1989
1989
  provision: "provisioning",
1990
1990
  destroy: "destroying"
@@ -2003,19 +2003,19 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
2003
2003
  fail: "failed"
2004
2004
  },
2005
2005
  destroyed: {}
2006
- }, ls = class extends Error {
2006
+ }, us = class extends Error {
2007
2007
  from;
2008
2008
  event;
2009
2009
  _tag = "BranchTransitionInvalid";
2010
2010
  constructor(e, t) {
2011
2011
  super(`invalid branch transition: ${e} --${t}-->`), this.from = e, this.event = t, this.name = "BranchTransitionInvalid";
2012
2012
  }
2013
- }, us = (e, t) => {
2014
- let n = cs[e][t];
2015
- if (n === void 0) throw new ls(e, t);
2013
+ }, ds = (e, t) => {
2014
+ let n = ls[e][t];
2015
+ if (n === void 0) throw new us(e, t);
2016
2016
  return n;
2017
- }, ds = (e, t, n, r, i = [], a = []) => {
2018
- if (n === "copy" && (r === void 0 || r === "")) throw new J("seed 'copy' requires a parentNamespace to snapshot from");
2017
+ }, fs = (e, t, n, r, i = [], a = []) => {
2018
+ if (n === "copy" && (r === void 0 || r === "")) throw new Y("seed 'copy' requires a parentNamespace to snapshot from");
2019
2019
  let o = [{
2020
2020
  kind: "create-namespace",
2021
2021
  detail: e
@@ -2044,13 +2044,13 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
2044
2044
  kind: "seed",
2045
2045
  detail: `run boot seeds into ${e}`
2046
2046
  }), o;
2047
- }, fs = (e) => {
2048
- if (!ss(e)) throw new J(`refusing to plan teardown of '${e}' — not a branch namespace`);
2047
+ }, ps = (e) => {
2048
+ if (!cs(e)) throw new Y(`refusing to plan teardown of '${e}' — not a branch namespace`);
2049
2049
  return [{
2050
2050
  kind: "drop-namespace",
2051
2051
  detail: e
2052
2052
  }];
2053
- }, ps = (e) => {
2053
+ }, ms = (e) => {
2054
2054
  if (e === void 0 || e === "") return !1;
2055
2055
  try {
2056
2056
  let t = new URL(e).hostname.toLowerCase();
@@ -2058,27 +2058,27 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
2058
2058
  } catch {
2059
2059
  return /\bneon\.(tech|build)\b/i.test(e);
2060
2060
  }
2061
- }, ms = (e) => e.prefer === void 0 ? e.seed === "copy" && ps(e.dbUrl) ? "neon-cow" : "namespace" : e.prefer, hs = (e, t = {}) => [{
2061
+ }, hs = (e) => e.prefer === void 0 ? e.seed === "copy" && ms(e.dbUrl) ? "neon-cow" : "namespace" : e.prefer, gs = (e, t = {}) => [{
2062
2062
  kind: "neon-branch-create",
2063
2063
  detail: `${t.parentBranch ?? "main"} → ${e} (copy-on-write)`
2064
- }], gs = (e) => {
2065
- if (!ss(e)) throw new J(`refusing to plan teardown of '${e}' — not a branch namespace`);
2064
+ }], _s = (e) => {
2065
+ if (!cs(e)) throw new Y(`refusing to plan teardown of '${e}' — not a branch namespace`);
2066
2066
  return [{
2067
2067
  kind: "neon-branch-delete",
2068
2068
  detail: e
2069
2069
  }];
2070
- }, _s = (e) => e.mechanism === "neon-cow" ? hs(e.branchId, e.neonParentBranch === void 0 ? {} : { parentBranch: e.neonParentBranch }) : ds(e.branchId, e.tableNames, e.seed, e.parentNamespace, e.foreignKeys, e.indexNames), vs = (e, t) => e === "neon-cow" ? gs(t) : fs(t), ys = (e, t, n) => {
2070
+ }, vs = (e) => e.mechanism === "neon-cow" ? gs(e.branchId, e.neonParentBranch === void 0 ? {} : { parentBranch: e.neonParentBranch }) : fs(e.branchId, e.tableNames, e.seed, e.parentNamespace, e.foreignKeys, e.indexNames), ys = (e, t) => e === "neon-cow" ? _s(t) : ps(t), bs = (e, t, n) => {
2071
2071
  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);
2072
2072
  return {
2073
2073
  evict: i,
2074
2074
  rejectNew: r.filter((e) => !a.has(e.namespace)).length >= t.maxBranches
2075
2075
  };
2076
- }, bs = async (e, t) => {
2077
- let n = os(e.appSlug, e.prNumber), r = ms({
2076
+ }, xs = async (e, t) => {
2077
+ let n = ss(e.appSlug, e.prNumber), r = hs({
2078
2078
  seed: e.seed,
2079
2079
  ...e.dbUrl === void 0 ? {} : { dbUrl: e.dbUrl },
2080
2080
  ...e.prefer === void 0 ? {} : { prefer: e.prefer }
2081
- }), i = _s({
2081
+ }), i = vs({
2082
2082
  mechanism: r,
2083
2083
  branchId: n,
2084
2084
  tableNames: e.tableNames,
@@ -2107,16 +2107,16 @@ var Bt = (e) => typeof e == "string" && e !== "" ? e : null, Vt = async (e, t, n
2107
2107
  mechanism: r,
2108
2108
  steps: i
2109
2109
  };
2110
- }, xs = async (e, t, n) => {
2111
- let r = vs(t, e);
2110
+ }, Ss = async (e, t, n) => {
2111
+ let r = ys(t, e);
2112
2112
  return t === "neon-cow" ? await n.neonBranchDelete(e) : await n.dropNamespace(e), r;
2113
- }, Ss = (e, t, n) => ys(e, t, n), Y = (e) => `"${e.replace(/"/g, "\"\"")}"`, Cs = {
2113
+ }, Cs = (e, t, n) => bs(e, t, n), X = (e) => `"${e.replace(/"/g, "\"\"")}"`, ws = {
2114
2114
  cascade: "CASCADE",
2115
2115
  restrict: "RESTRICT",
2116
2116
  setNull: "SET NULL",
2117
2117
  noAction: "NO ACTION"
2118
- }, X = (e) => `'${e.replace(/'/g, "''")}'`, ws = (e, t) => {
2119
- let n = t.columns.map(X).join(", ");
2118
+ }, Z = (e) => `'${e.replace(/'/g, "''")}'`, Ts = (e, t) => {
2119
+ let n = t.columns.map(Z).join(", ");
2120
2120
  return `DO $voltro_branch$
2121
2121
  DECLARE derived name;
2122
2122
  BEGIN
@@ -2125,11 +2125,11 @@ BEGIN
2125
2125
  JOIN pg_class i ON i.oid = x.indexrelid
2126
2126
  JOIN pg_class c ON c.oid = x.indrelid
2127
2127
  JOIN pg_namespace nsp ON nsp.oid = c.relnamespace
2128
- WHERE nsp.nspname = ${X(e)}
2129
- AND c.relname = ${X(t.table)}
2128
+ WHERE nsp.nspname = ${Z(e)}
2129
+ AND c.relname = ${Z(t.table)}
2130
2130
  AND NOT x.indisprimary
2131
2131
  AND x.indisunique = ${t.unique ? "true" : "false"}
2132
- AND i.relname <> ${X(t.name)}
2132
+ AND i.relname <> ${Z(t.name)}
2133
2133
  AND (
2134
2134
  SELECT array_agg(att.attname::text ORDER BY k.ord)
2135
2135
  FROM unnest(x.indkey::int2[]) WITH ORDINALITY AS k(attnum, ord)
@@ -2138,39 +2138,39 @@ BEGIN
2138
2138
  LIMIT 1;
2139
2139
  IF derived IS NOT NULL THEN
2140
2140
  EXECUTE format('ALTER INDEX %I.%I RENAME TO %I',
2141
- ${X(e)}, derived, ${X(t.name)});
2141
+ ${Z(e)}, derived, ${Z(t.name)});
2142
2142
  END IF;
2143
2143
  END
2144
2144
  $voltro_branch$`;
2145
- }, Ts = (e, t) => {
2146
- let n = t.onDelete === void 0 ? "" : ` ON DELETE ${Cs[t.onDelete]}`, r = t.onUpdate === void 0 ? "" : ` ON UPDATE ${Cs[t.onUpdate]}`;
2147
- return `ALTER TABLE ${Y(e)}.${Y(t.table)} ADD FOREIGN KEY (${Y(t.column)}) REFERENCES ${Y(e)}.${Y(t.targetTable)} (${Y(t.targetColumn)})${n}${r}`;
2148
- }, Es = (e) => {
2145
+ }, Es = (e, t) => {
2146
+ let n = t.onDelete === void 0 ? "" : ` ON DELETE ${ws[t.onDelete]}`, r = t.onUpdate === void 0 ? "" : ` ON UPDATE ${ws[t.onUpdate]}`;
2147
+ 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}`;
2148
+ }, Ds = (e) => {
2149
2149
  let t = () => {
2150
2150
  throw Error("namespace branch executor: Neon ops require a neon-cow executor (use a Neon connection for copy-on-write branches)");
2151
2151
  };
2152
2152
  return {
2153
- createNamespace: (t) => e.run(`CREATE SCHEMA IF NOT EXISTS ${Y(t)}`),
2154
- createTable: (t, n) => e.run(`CREATE TABLE IF NOT EXISTS ${Y(t)}.${Y(n)} (LIKE ${Y(n)} INCLUDING ALL)`),
2155
- copyTable: (t, n, r) => e.run(`INSERT INTO ${Y(n)}.${Y(r)} SELECT * FROM ${Y(t)}.${Y(r)}`),
2156
- addForeignKey: (t, n) => e.run(Ts(t, n)),
2157
- restoreIndexName: (t, n) => e.run(ws(t, n)),
2158
- dropNamespace: (t) => e.run(`DROP SCHEMA IF EXISTS ${Y(t)} CASCADE`),
2153
+ createNamespace: (t) => e.run(`CREATE SCHEMA IF NOT EXISTS ${X(t)}`),
2154
+ createTable: (t, n) => e.run(`CREATE TABLE IF NOT EXISTS ${X(t)}.${X(n)} (LIKE ${X(n)} INCLUDING ALL)`),
2155
+ copyTable: (t, n, r) => e.run(`INSERT INTO ${X(n)}.${X(r)} SELECT * FROM ${X(t)}.${X(r)}`),
2156
+ addForeignKey: (t, n) => e.run(Es(t, n)),
2157
+ restoreIndexName: (t, n) => e.run(Ts(t, n)),
2158
+ dropNamespace: (t) => e.run(`DROP SCHEMA IF EXISTS ${X(t)} CASCADE`),
2159
2159
  neonBranchCreate: t,
2160
2160
  neonBranchDelete: t
2161
2161
  };
2162
- }, Ds = class extends Error {
2162
+ }, Os = class extends Error {
2163
2163
  _tag = "TenantResidencyUnresolved";
2164
2164
  constructor(e) {
2165
2165
  super(e), this.name = "TenantResidencyUnresolved";
2166
2166
  }
2167
- }, Os = class extends Error {
2167
+ }, ks = class extends Error {
2168
2168
  region;
2169
2169
  _tag = "TenantRegionUnavailable";
2170
2170
  constructor(e, t) {
2171
2171
  super(t), this.region = e, this.name = "TenantRegionUnavailable";
2172
2172
  }
2173
- }, ks, As = (e) => {
2173
+ }, As, js = (e) => {
2174
2174
  if (e.homes === void 0) throw Error("setResidencyConfig: `homes` is required");
2175
2175
  if (e.servableRegions === void 0 || e.servableRegions.length === 0) throw Error("setResidencyConfig: `servableRegions` must be non-empty (which regions this deployment serves)");
2176
2176
  let t = /* @__PURE__ */ new Map();
@@ -2179,98 +2179,98 @@ $voltro_branch$`;
2179
2179
  if (e !== void 0 && e !== n.region) throw Error(`residency: tenant '${n.tenantId}' is mapped to two regions ('${e}' and '${n.region}')`);
2180
2180
  t.set(n.tenantId, n.region);
2181
2181
  }
2182
- return ks = e, e;
2183
- }, js = () => ks, Ms = () => {
2184
- ks = void 0;
2185
- }, Ns = (e, t) => {
2186
- if (e == null || e === "") throw new Ds("residency is on but the request has no resolvable tenant — refusing to bind a store");
2182
+ return As = e, e;
2183
+ }, Ms = () => As, Ns = () => {
2184
+ As = void 0;
2185
+ }, Ps = (e, t) => {
2186
+ if (e == null || e === "") throw new Os("residency is on but the request has no resolvable tenant — refusing to bind a store");
2187
2187
  let n = t.homes.find((t) => t.tenantId === e);
2188
- if (n === void 0) throw new Ds(`no residency home is mapped for tenant '${e}' — refusing to fall back to a default store (would be a residency violation)`);
2188
+ if (n === void 0) throw new Os(`no residency home is mapped for tenant '${e}' — refusing to fall back to a default store (would be a residency violation)`);
2189
2189
  return n;
2190
- }, Ps = (e, t) => t.servableRegions.includes(e), Fs = (e, t) => {
2191
- let n = Ns(e.tenantId, t), r = Tr(n.tenantId);
2190
+ }, Fs = (e, t) => t.servableRegions.includes(e), Is = (e, t) => {
2191
+ let n = Ps(e.tenantId, t), r = Er(n.tenantId);
2192
2192
  return {
2193
2193
  region: n.region,
2194
2194
  namespace: r,
2195
2195
  ...n.connectionKey === void 0 ? {} : { connectionKey: n.connectionKey }
2196
2196
  };
2197
- }, Is = (e, t, n) => {
2198
- let r = Fs(e, t);
2199
- if (!Ps(r.region, t)) throw new Os(r.region, `tenant homed in region '${r.region}', which this deployment does not serve — route to the home region`);
2197
+ }, Ls = (e, t, n) => {
2198
+ let r = Is(e, t);
2199
+ if (!Fs(r.region, t)) throw new ks(r.region, `tenant homed in region '${r.region}', which this deployment does not serve — route to the home region`);
2200
2200
  let i = n.get(r.region);
2201
- if (i === void 0) throw new Os(r.region, `no store handle for home region '${r.region}' (declared servable but not wired) — failing closed`);
2201
+ if (i === void 0) throw new ks(r.region, `no store handle for home region '${r.region}' (declared servable but not wired) — failing closed`);
2202
2202
  return {
2203
2203
  store: i,
2204
2204
  placement: r
2205
2205
  };
2206
- }, Ls = async (e, t, n, r) => {
2207
- let { store: i, placement: a } = Is(e, t, n);
2206
+ }, Rs = async (e, t, n, r) => {
2207
+ let { store: i, placement: a } = Ls(e, t, n);
2208
2208
  return await r(i, a), a;
2209
- }, Rs = (e) => {
2209
+ }, zs = (e) => {
2210
2210
  if (typeof e == "string") return e;
2211
2211
  if ("jsonPath" in e) {
2212
2212
  let { column: t, path: n, numeric: r } = e.jsonPath;
2213
2213
  return `(json:${t}->${n.join(".")}${r ? "::num" : ""})`;
2214
2214
  }
2215
2215
  return `(${e.expr})`;
2216
- }, Z = (e) => e.map(Rs), zs = (e, t) => {
2216
+ }, Q = (e) => e.map(zs), Bs = (e, t) => {
2217
2217
  if (e.length !== t.length) return !1;
2218
- for (let n = 0; n < e.length; n++) if (Rs(e[n]) !== Rs(t[n])) return !1;
2218
+ for (let n = 0; n < e.length; n++) if (zs(e[n]) !== zs(t[n])) return !1;
2219
2219
  return !0;
2220
- }, Bs = (e, t) => {
2220
+ }, Vs = (e, t) => {
2221
2221
  if (e.length >= t.length) return !1;
2222
- for (let n = 0; n < e.length; n++) if (Rs(e[n]) !== Rs(t[n])) return !1;
2222
+ for (let n = 0; n < e.length; n++) if (zs(e[n]) !== zs(t[n])) return !1;
2223
2223
  return !0;
2224
- }, Vs = (e) => {
2224
+ }, Hs = (e) => {
2225
2225
  let t = [], n = e.appliedIndexes, r = e.tableName;
2226
2226
  for (let e = 0; e < n.length; e++) {
2227
2227
  let i = n[e];
2228
2228
  for (let a = e + 1; a < n.length; a++) {
2229
2229
  let e = n[a];
2230
- if (zs(i.fields, e.fields)) {
2230
+ if (Bs(i.fields, e.fields)) {
2231
2231
  let [n, a] = i.name < e.name ? [i, e] : [e, i];
2232
2232
  t.push({
2233
2233
  kind: "duplicate-fields",
2234
2234
  table: r,
2235
2235
  redundant: n,
2236
2236
  coveredBy: a,
2237
- message: `'${r}' has two indexes on the same fields [${Z(i.fields).join(", ")}]: '${i.name}' and '${e.name}'. The B-tree engine builds both, costing write throughput + disk space for no read benefit. Drop '${n.name}' (or '${a.name}' if you prefer the other name). Applies to every supported dialect (Postgres / MySQL / MariaDB / MSSQL / SQLite).`
2237
+ message: `'${r}' has two indexes on the same fields [${Q(i.fields).join(", ")}]: '${i.name}' and '${e.name}'. The B-tree engine builds both, costing write throughput + disk space for no read benefit. Drop '${n.name}' (or '${a.name}' if you prefer the other name). Applies to every supported dialect (Postgres / MySQL / MariaDB / MSSQL / SQLite).`
2238
2238
  });
2239
2239
  continue;
2240
2240
  }
2241
- Bs(i.fields, e.fields) ? t.push({
2241
+ Vs(i.fields, e.fields) ? t.push({
2242
2242
  kind: "redundant-prefix",
2243
2243
  table: r,
2244
2244
  redundant: i,
2245
2245
  coveredBy: e,
2246
- message: `'${r}' index '${i.name}' on [${Z(i.fields).join(", ")}] is a leading prefix of '${e.name}' on [${Z(e.fields).join(", ")}]. Every B-tree dialect we support (Postgres / MySQL / MariaDB / MSSQL / SQLite) can serve a [${Z(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).`
2247
- }) : Bs(e.fields, i.fields) && t.push({
2246
+ 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).`
2247
+ }) : Vs(e.fields, i.fields) && t.push({
2248
2248
  kind: "redundant-prefix",
2249
2249
  table: r,
2250
2250
  redundant: e,
2251
2251
  coveredBy: i,
2252
- message: `'${r}' index '${e.name}' on [${Z(e.fields).join(", ")}] is a leading prefix of '${i.name}' on [${Z(i.fields).join(", ")}]. Every B-tree dialect we support (Postgres / MySQL / MariaDB / MSSQL / SQLite) can serve a [${Z(e.fields).join(", ")}] query from '${i.name}' too via the leading-prefix rule, so '${e.name}' adds write cost without read benefit. Drop '${e.name}' — unless you specifically need a smaller index for cache locality on a write-heavy table (rare; profile first).`
2252
+ message: `'${r}' index '${e.name}' on [${Q(e.fields).join(", ")}] is a leading prefix of '${i.name}' on [${Q(i.fields).join(", ")}]. Every B-tree dialect we support (Postgres / MySQL / MariaDB / MSSQL / SQLite) can serve a [${Q(e.fields).join(", ")}] query from '${i.name}' too via the leading-prefix rule, so '${e.name}' adds write cost without read benefit. Drop '${e.name}' — unless you specifically need a smaller index for cache locality on a write-heavy table (rare; profile first).`
2253
2253
  });
2254
2254
  }
2255
2255
  }
2256
2256
  return t;
2257
- }, Hs = (e) => {
2257
+ }, Us = (e) => {
2258
2258
  let t = [];
2259
- for (let n of e) t.push(...Vs(n));
2259
+ for (let n of e) t.push(...Hs(n));
2260
2260
  return t;
2261
- }, Us = "\x1B[", Ws = `${Us}38;2;245;158;11m`, Gs = `${Us}38;2;16;185;129m`, Ks = (e, t) => `${e}${t}${A.reset}`, Q = (e, t, n) => e ? typeof t == "function" ? t(n) : Ks(t, n) : n, qs = (e, t = {}) => {
2262
- let n = t.color ?? !0, r = t.indent ?? " ", i = (e) => Q(n, A.dim, e.padEnd(11)), a = (e) => Q(n, (e) => A.bold(A.brand(e)), e), o = (e) => Q(n, A.brightRed24, e), s = (e) => Q(n, Gs, e), c = (e) => Q(n, Ws, e), l = (e) => Q(n, A.dim, e), u = `${c("index audit")} ${l("·")} ${Q(n, A.bold, e.kind)}`, d = e.redundant.fields.length, f = Z(e.coveredBy.fields.slice(d)), p = (e, t) => {
2261
+ }, Ws = "\x1B[", Gs = `${Ws}38;2;245;158;11m`, Ks = `${Ws}38;2;16;185;129m`, qs = (e, t) => `${e}${t}${j.reset}`, $ = (e, t, n) => e ? typeof t == "function" ? t(n) : qs(t, n) : n, Js = (e, t = {}) => {
2262
+ 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, Ks, e), c = (e) => $(n, Gs, 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) => {
2263
2263
  let n = e.slice(0, t), r = e.slice(t), i = [];
2264
2264
  return n.length > 0 && i.push(s(`[${n.join(", ")}]`)), r.length > 0 && i.push(c(`+ [${r.join(", ")}]`)), i.join(" ");
2265
2265
  }, m = [];
2266
- 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(Z(e.redundant.fields), d)}`), m.push(""), m.push(`${i("covered by")}${s(e.coveredBy.name)}`), m.push(`${i("")}${p(Z(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 ${Q(n, A.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");
2267
- }, Js = (e, { apply: t, undo: n }) => ({
2266
+ 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");
2267
+ }, Ys = (e, { apply: t, undo: n }) => ({
2268
2268
  name: e,
2269
2269
  apply: t,
2270
2270
  undo: n
2271
- }), Ys = (e) => {
2271
+ }), Xs = (e) => {
2272
2272
  if (!/^\d{14}_/.test(e.id)) throw Error(`migration "${e.id}": id must start with a 14-digit timestamp followed by "_" (convention: <YYYYMMDDHHMMSS>_<slug>)`);
2273
- let t = e.steps({ step: Js });
2273
+ let t = e.steps({ step: Ys });
2274
2274
  if (t.length === 0) throw Error(`migration "${e.id}": at least one step is required`);
2275
2275
  return {
2276
2276
  __migration: !0,
@@ -2278,93 +2278,100 @@ $voltro_branch$`;
2278
2278
  name: e.name,
2279
2279
  steps: t
2280
2280
  };
2281
- }, Xs = (e) => typeof e == "object" && !!e && "__migration" in e && e.__migration === !0, Zs = w("_voltro_migrations", {
2282
- id: a({ prefix: "mig" }),
2283
- name: S(),
2284
- hash: S(),
2285
- status: S(),
2286
- appliedAt: y().nullable(),
2287
- durationMs: x().nullable(),
2288
- errorMessage: S().nullable(),
2289
- errorStack: S().nullable(),
2290
- workflowRunId: S().nullable(),
2291
- createdAt: y().default("now"),
2292
- updatedAt: y().default("now").onUpdate("now")
2293
- }).index(["status"]), Qs = w("_voltro_seeds", {
2294
- id: a({ prefix: "seed" }),
2295
- name: S(),
2296
- lifecycle: S(),
2297
- fingerprint: S(),
2298
- cronSchedule: S().nullable(),
2299
- watchedTables: b().nullable(),
2300
- nextRunAt: y().nullable(),
2301
- lastRunStatus: S().nullable(),
2302
- lastRunAt: y().nullable(),
2303
- lastRunDurationMs: x().nullable(),
2304
- lastRunRowsTouched: x().nullable(),
2305
- lastError: S().nullable(),
2306
- workflowRunId: S().nullable(),
2307
- createdAt: y().default("now"),
2308
- updatedAt: y().default("now").onUpdate("now")
2309
- }).index(["lifecycle"]).index(["nextRunAt"]), $s = w("_voltro_migration_plans", {
2310
- id: a({ prefix: "plan" }),
2311
- fingerprint: S(),
2312
- liveFingerprint: S().nullable(),
2313
- operations: b(),
2314
- rollbackPlan: b().nullable(),
2315
- appliedBy: S(),
2316
- environment: S(),
2317
- source: S(),
2318
- onlineStrategy: S().nullable(),
2319
- durationMs: x(),
2320
- notes: S().nullable(),
2321
- squashedAt: y().nullable(),
2322
- appliedAt: y().default("now"),
2323
- createdAt: y().default("now"),
2324
- updatedAt: y().default("now").onUpdate("now")
2325
- }).index(["fingerprint"]).index(["environment"]), ec = w("_voltro_idempotency", {
2326
- id: a({ prefix: "idem" }),
2327
- scope: S(),
2328
- key: S(),
2329
- status: S(),
2330
- response: b().nullable(),
2331
- createdAt: y().default("now")
2332
- }).unique(["scope", "key"]).index(["createdAt"]), tc = w("_voltro_kv", {
2333
- id: a({ prefix: "kv" }),
2334
- key: S().unique(),
2335
- value: S().nullable(),
2336
- expiresAt: y().nullable(),
2337
- createdAt: y().default("now"),
2338
- updatedAt: y().default("now").onUpdate("now")
2339
- }).index(["expiresAt"]), nc = w("_voltro_api_keys", {
2340
- id: a({ prefix: "apikey" }),
2341
- tenantId: S().nullable(),
2342
- name: S(),
2343
- hashedKey: S().maxLength(64).unique(),
2344
- keyPrefix: S(),
2345
- scopes: b().nullable(),
2346
- lastUsedAt: y().nullable(),
2347
- requestCount: x().default(0),
2348
- expiresAt: y().nullable(),
2349
- revokedAt: y().nullable(),
2350
- createdBy: S().nullable(),
2351
- onBehalfOf: S().nullable(),
2352
- metadata: b().nullable(),
2353
- createdAt: y().default("now")
2354
- }).index("byApiKeyTenant", ["tenantId"]), rc = [
2355
- Zs,
2281
+ }, Zs = (e) => typeof e == "object" && !!e && "__migration" in e && e.__migration === !0, Qs = T("_voltro_migrations", {
2282
+ id: _({ prefix: "mig" }),
2283
+ name: t(),
2284
+ hash: t(),
2285
+ status: t(),
2286
+ appliedAt: C().nullable(),
2287
+ durationMs: S().nullable(),
2288
+ errorMessage: t().nullable(),
2289
+ errorStack: t().nullable(),
2290
+ workflowRunId: t().nullable(),
2291
+ createdAt: C().default("now"),
2292
+ updatedAt: C().default("now").onUpdate("now")
2293
+ }).index(["status"]), $s = T("_voltro_seeds", {
2294
+ id: _({ prefix: "seed" }),
2295
+ name: t(),
2296
+ lifecycle: t(),
2297
+ fingerprint: t(),
2298
+ cronSchedule: t().nullable(),
2299
+ watchedTables: h().nullable(),
2300
+ nextRunAt: C().nullable(),
2301
+ lastRunStatus: t().nullable(),
2302
+ lastRunAt: C().nullable(),
2303
+ lastRunDurationMs: S().nullable(),
2304
+ lastRunRowsTouched: S().nullable(),
2305
+ lastError: t().nullable(),
2306
+ workflowRunId: t().nullable(),
2307
+ createdAt: C().default("now"),
2308
+ updatedAt: C().default("now").onUpdate("now")
2309
+ }).index(["lifecycle"]).index(["nextRunAt"]), ec = T("_voltro_migration_plans", {
2310
+ id: _({ prefix: "plan" }),
2311
+ fingerprint: t(),
2312
+ liveFingerprint: t().nullable(),
2313
+ operations: h(),
2314
+ rollbackPlan: h().nullable(),
2315
+ appliedBy: t(),
2316
+ environment: t(),
2317
+ source: t(),
2318
+ onlineStrategy: t().nullable(),
2319
+ durationMs: S(),
2320
+ notes: t().nullable(),
2321
+ squashedAt: C().nullable(),
2322
+ appliedAt: C().default("now"),
2323
+ createdAt: C().default("now"),
2324
+ updatedAt: C().default("now").onUpdate("now")
2325
+ }).index(["fingerprint"]).index(["environment"]), tc = T("_voltro_idempotency", {
2326
+ id: _({ prefix: "idem" }),
2327
+ scope: t(),
2328
+ key: t(),
2329
+ status: t(),
2330
+ response: h().nullable(),
2331
+ createdAt: C().default("now")
2332
+ }).unique(["scope", "key"]).index(["createdAt"]), nc = T("_voltro_kv", {
2333
+ id: _({ prefix: "kv" }),
2334
+ key: t().unique(),
2335
+ value: t().nullable(),
2336
+ expiresAt: C().nullable(),
2337
+ createdAt: C().default("now"),
2338
+ updatedAt: C().default("now").onUpdate("now")
2339
+ }).index(["expiresAt"]), rc = T("_voltro_api_keys", {
2340
+ id: _({ prefix: "apikey" }),
2341
+ tenantId: t().nullable(),
2342
+ name: t(),
2343
+ hashedKey: t().maxLength(64).unique(),
2344
+ keyPrefix: t(),
2345
+ scopes: h().nullable(),
2346
+ lastUsedAt: C().nullable(),
2347
+ requestCount: S().default(0),
2348
+ expiresAt: C().nullable(),
2349
+ revokedAt: C().nullable(),
2350
+ createdBy: t().nullable(),
2351
+ onBehalfOf: t().nullable(),
2352
+ metadata: h().nullable(),
2353
+ createdAt: C().default("now")
2354
+ }).index("byApiKeyTenant", ["tenantId"]), ic = [
2356
2355
  Qs,
2357
- $s
2358
- ], ic = "_voltro_replace_in_progress", ac = w(ic, {
2359
- id: a({ prefix: "repl" }),
2360
- startedAt: y().default("now"),
2361
- kind: S().default("replace"),
2362
- tables: S().nullable(),
2363
- capture: S().nullable(),
2364
- via: S()
2365
- }), oc = (e) => {
2366
- if (e.length !== 0) return `refusing to start: a destructive data operation did not finish.
2367
- ${e.map((e) => {
2356
+ $s,
2357
+ ec
2358
+ ], ac = "_voltro_replace_in_progress", oc = T(ac, {
2359
+ id: _({ prefix: "repl" }),
2360
+ startedAt: C().default("now"),
2361
+ kind: t().default("replace"),
2362
+ tables: t().nullable(),
2363
+ capture: t().nullable(),
2364
+ via: t(),
2365
+ staging: t().nullable(),
2366
+ heartbeatAt: C().nullable(),
2367
+ resumable: r().nullable()
2368
+ }), sc = 30, cc = (e, t) => {
2369
+ let n = typeof t == "number" && Number.isFinite(t) && t > 0 ? t : 30, r = Number(e.VOLTRO_STAGING_STALE_MINUTES);
2370
+ return (Number.isFinite(r) && r > 0 ? r : n) * 6e4;
2371
+ }, lc = (e) => e == null || String(e).length === 0 ? [] : String(e).split(",").map((e) => e.trim()).filter((e) => e.length > 0), uc = (e) => {
2372
+ let t = e.filter((e) => e.kind !== "staging");
2373
+ if (t.length !== 0) return `refusing to start: a destructive data operation did not finish.
2374
+ ${t.map((e) => {
2368
2375
  let t = Number.isFinite(e.startedAt.getTime()) ? `${Math.max(0, Math.round((Date.now() - e.startedAt.getTime()) / 6e4))} minute(s) ago` : "at an unknown time";
2369
2376
  if (e.kind === "restore") return ` - a native \`restore\` over ${e.via} began loading an artefact over this database ${t}\n and never reported finishing.\n` + (e.capture === null ? " The artefact it was loading was not recorded. Re-run the restore from your backup\n directory, or restore from another backup." : ` The artefact it was loading:\n ${e.capture}\n Re-run it to completion with: voltro data restore ${e.capture} --allow-live`);
2370
2377
  let n = e.tables === null ? "this database" : `${e.tables} table(s)`;
@@ -2376,22 +2383,41 @@ ${e.map((e) => {
2376
2383
 
2377
2384
  When the data is back, or you have decided the current state is correct, clear the marker:
2378
2385
  voltro data clear-replace-marker --yes`;
2379
- }, $ = "id", sc = (e, t) => {
2380
- let n = m(e);
2386
+ }, dc = (e, t, n) => {
2387
+ let r = e.filter((e) => e.kind === "staging");
2388
+ return {
2389
+ all: r,
2390
+ droppable: r.filter((e) => {
2391
+ if (e.resumable) return !1;
2392
+ let r = (e.heartbeatAt ?? e.startedAt).getTime();
2393
+ return Number.isFinite(r) ? t - r >= n : !1;
2394
+ })
2395
+ };
2396
+ }, fc = (e, t) => {
2397
+ if (e.all.length === 0) return;
2398
+ let n = new Set(e.droppable.map((e) => e.id));
2399
+ return `staged data-import leftovers:
2400
+ ${e.all.map((e) => {
2401
+ let r = e.heartbeatAt ?? e.startedAt, i = Number.isFinite(r.getTime()) ? `${Math.max(0, Math.round((t - r.getTime()) / 6e4))} minute(s) ago` : "at an unknown time", a = `${e.staging.length} staging table(s) from a \`replace\` over ${e.via}, last active ${i}`;
2402
+ 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.`;
2403
+ }).join("\n")}\n The target of a staged \`replace\` is untouched until one short swap at the end, so none of this is
2404
+ a reason to refuse the boot — it is a reason to know the disk is holding a copy of a bundle.`;
2405
+ }, pc = "id", mc = (e, t) => {
2406
+ let n = E(e);
2381
2407
  if (n === void 0) return t;
2382
- let r = n.fields[$]?.idScheme;
2383
- if (r === void 0 || t[$] != null) return t;
2408
+ let r = n.fields[pc]?.idScheme;
2409
+ if (r === void 0 || t[pc] != null) return t;
2384
2410
  if (r.kind === "numeric") {
2385
- if (!($ in t)) return t;
2411
+ if (!(pc in t)) return t;
2386
2412
  let e = { ...t };
2387
- return delete e[$], e;
2413
+ return delete e[pc], e;
2388
2414
  }
2389
- let i = Re(r, e);
2415
+ let i = gt(r, e);
2390
2416
  return i === null ? t : {
2391
2417
  ...t,
2392
- [$]: i
2418
+ [pc]: i
2393
2419
  };
2394
- }, cc = (e, t) => t.map((t) => sc(e, t)), lc = {
2420
+ }, hc = (e, t) => t.map((t) => mc(e, t)), gc = {
2395
2421
  postgres: { maxBindParameters: 65535 },
2396
2422
  mysql: { maxBindParameters: 65535 },
2397
2423
  mariadb: { maxBindParameters: 65535 },
@@ -2401,25 +2427,25 @@ ${e.map((e) => {
2401
2427
  },
2402
2428
  sqlite: { maxBindParameters: 32766 },
2403
2429
  turso: { maxBindParameters: 32766 }
2404
- }, uc = (e) => lc[e], dc = (e) => {
2430
+ }, _c = (e) => gc[e], vc = (e) => {
2405
2431
  let t = /* @__PURE__ */ new Set();
2406
2432
  for (let n of e) for (let e of Object.keys(n)) t.add(e);
2407
2433
  return t.size;
2408
- }, fc = (e, t) => {
2434
+ }, yc = (e, t) => {
2409
2435
  if (t === void 0 || e.length === 0) return [e];
2410
- let n = Math.max(1, dc(e)), r = Math.floor(t.maxBindParameters / n), i = t.maxRowsPerStatement ?? Infinity, a = Math.max(1, Math.min(r, i));
2436
+ let n = Math.max(1, vc(e)), r = Math.floor(t.maxBindParameters / n), i = t.maxRowsPerStatement ?? Infinity, a = Math.max(1, Math.min(r, i));
2411
2437
  if (e.length <= a) return [e];
2412
2438
  let o = [];
2413
2439
  for (let t = 0; t < e.length; t += a) o.push(e.slice(t, t + a));
2414
2440
  return o;
2415
- }, pc = (e, t) => {
2441
+ }, bc = (e, t) => {
2416
2442
  let n = [], r = t;
2417
2443
  for (let [t, i] of Object.entries(e.fields)) {
2418
2444
  let e = i;
2419
2445
  e.nullable || e.hasDefault || e.idScheme !== void 0 || e.generatedAs !== void 0 || (r[t] === void 0 || r[t] === null) && n.push(t);
2420
2446
  }
2421
2447
  return n;
2422
- }, mc = (e, t, n) => {
2448
+ }, xc = (e, t, n) => {
2423
2449
  let r = n, i = new Set(e === void 0 ? [] : Object.entries(e.fields).filter(([, e]) => e.generatedAs !== void 0).map(([e]) => e)), a = [];
2424
2450
  for (let e of t) i.has(e) || (r[e] === void 0 ? a.push({
2425
2451
  column: e,
@@ -2429,28 +2455,28 @@ ${e.map((e) => {
2429
2455
  reason: "null"
2430
2456
  }));
2431
2457
  return a;
2432
- }, hc = (e, t, n) => e.insert(t.tableName, n), gc = (e, t, n, r) => e.upsert(t.tableName, n, {
2458
+ }, Sc = (e, t, n) => e.insert(t.tableName, n), Cc = (e, t, n, r) => e.upsert(t.tableName, n, {
2433
2459
  conflictColumns: r.conflictColumns,
2434
2460
  ...r.update === void 0 ? {} : { update: r.update }
2435
- }), _c = (e, t, n, r) => e.updateMany(t.tableName, n, { where: r.where }), vc = 512, yc = (e) => {
2461
+ }), wc = (e, t, n, r) => e.updateMany(t.tableName, n, { where: r.where }), Tc = 512, Ec = (e) => {
2436
2462
  e.setMaxListeners(512);
2437
- }, bc = (e, t, n) => ({
2463
+ }, Dc = (e, t, n) => ({
2438
2464
  _tag: "PrimaryKeyConflictError",
2439
2465
  table: e,
2440
2466
  key: t,
2441
2467
  cause: n
2442
- }), xc = (e) => typeof e == "object" && !!e && e._tag === "PrimaryKeyConflictError", Sc = {
2468
+ }), Oc = (e) => typeof e == "object" && !!e && e._tag === "PrimaryKeyConflictError", kc = {
2443
2469
  postgres: 5432,
2444
2470
  mysql: 3306,
2445
2471
  mariadb: 3306,
2446
2472
  mssql: 1433
2447
- }, Cc = /* @__PURE__ */ new Set([
2473
+ }, Ac = /* @__PURE__ */ new Set([
2448
2474
  "localhost",
2449
2475
  "127.0.0.1",
2450
2476
  "::1",
2451
2477
  "[::1]",
2452
2478
  "0.0.0.0"
2453
- ]), wc = (e) => {
2479
+ ]), jc = (e) => {
2454
2480
  let t = e.host, n = e.port, r = e.database;
2455
2481
  if (e.url !== void 0 && e.url !== "") try {
2456
2482
  let i = new URL(e.url);
@@ -2459,29 +2485,29 @@ ${e.map((e) => {
2459
2485
  return;
2460
2486
  }
2461
2487
  if (t === void 0 || t === "" || r === void 0 || r === "") return;
2462
- let i = n ?? Sc[(e.dialect ?? "").toLowerCase()];
2488
+ let i = n ?? kc[(e.dialect ?? "").toLowerCase()];
2463
2489
  if (i === void 0 || !Number.isFinite(i)) return;
2464
2490
  let a = t.toLowerCase();
2465
2491
  return {
2466
- host: Cc.has(a) ? "localhost" : a,
2492
+ host: Ac.has(a) ? "localhost" : a,
2467
2493
  port: i,
2468
2494
  database: r.toLowerCase()
2469
2495
  };
2470
- }, Tc = (e) => {
2471
- let t = wc(e);
2472
- if (t !== void 0) return Lt("sha256").update(`${t.host}\u0000${t.port}\u0000${t.database}`).digest("hex").slice(0, 32);
2473
- }, Ec = (e, t) => e === void 0 || t === void 0 ? "unknown" : e === t ? "same" : "different", Dc = {
2496
+ }, Mc = (e) => {
2497
+ let t = jc(e);
2498
+ if (t !== void 0) return Rt("sha256").update(`${t.host}\u0000${t.port}\u0000${t.database}`).digest("hex").slice(0, 32);
2499
+ }, Nc = (e, t) => e === void 0 || t === void 0 ? "unknown" : e === t ? "same" : "different", Pc = {
2474
2500
  app: 3,
2475
2501
  plugin: 2,
2476
2502
  framework: 1
2477
- }, Oc = /* @__PURE__ */ new Map(), kc = [], Ac = () => [...kc], jc = (e) => {
2503
+ }, Fc = /* @__PURE__ */ new Map(), Ic = [], Lc = () => [...Ic], Rc = (e) => {
2478
2504
  if (!e.table || !e.timeColumn) throw Error("registerRetention: table + timeColumn are required");
2479
2505
  if (!Number.isFinite(e.ttlMs) || e.ttlMs <= 0) throw Error(`registerRetention(${e.table}): ttlMs must be a positive number`);
2480
- let t = e.source ?? "app", n = Oc.get(e.table);
2506
+ let t = e.source ?? "app", n = Fc.get(e.table);
2481
2507
  if (n !== void 0) {
2482
2508
  let r = n.source ?? "app", i = n.ttlMs !== e.ttlMs || n.where !== void 0 != (e.where !== void 0);
2483
- if (Dc[t] < Dc[r]) {
2484
- i && kc.push({
2509
+ if (Pc[t] < Pc[r]) {
2510
+ i && Ic.push({
2485
2511
  table: e.table,
2486
2512
  kept: {
2487
2513
  source: r,
@@ -2494,7 +2520,7 @@ ${e.map((e) => {
2494
2520
  });
2495
2521
  return;
2496
2522
  }
2497
- i && r !== t && kc.push({
2523
+ i && r !== t && Ic.push({
2498
2524
  table: e.table,
2499
2525
  kept: {
2500
2526
  source: t,
@@ -2506,51 +2532,51 @@ ${e.map((e) => {
2506
2532
  }
2507
2533
  });
2508
2534
  }
2509
- Oc.set(e.table, {
2535
+ Fc.set(e.table, {
2510
2536
  ...e,
2511
2537
  source: t
2512
2538
  });
2513
- }, Mc = () => [...Oc.values()], Nc = () => {
2514
- Oc.clear(), kc.length = 0;
2515
- }, Pc = async (e, t, n, r = 2e4) => {
2539
+ }, zc = () => [...Fc.values()], Bc = () => {
2540
+ Fc.clear(), Ic.length = 0;
2541
+ }, Vc = async (e, t, n, r = 2e4) => {
2516
2542
  let i = new Date(t - e.ttlMs), a = 0;
2517
2543
  for (;;) {
2518
2544
  let t = await n(e.table, e.timeColumn, i, r, e.where);
2519
2545
  if (a += t, t < r) break;
2520
2546
  }
2521
2547
  return a;
2522
- }, Fc = (e, t) => {
2548
+ }, Hc = (e, t) => {
2523
2549
  let n = Number(e ?? String(t));
2524
2550
  return (Number.isFinite(n) && n > 0 ? n : t) * 36e5;
2525
- }, Ic = "_voltro_cdc_offsets", Lc = w(Ic, {
2526
- id: a({ prefix: "cdcoff" }),
2527
- replicaId: S(),
2528
- streamName: S(),
2529
- binlogFile: S(),
2530
- binlogPosition: S(),
2531
- updatedAt: y()
2532
- }).index(["replicaId"]), Rc = w(Ic, {
2533
- id: a({ prefix: "cdcoff" }),
2534
- replicaId: S(),
2535
- streamName: S(),
2536
- ctVersion: S(),
2537
- updatedAt: y()
2538
- }).index(["replicaId"]), zc = "_voltro_data_transfers", Bc = w(zc, {
2539
- id: a({ prefix: "dimp" }),
2540
- startedAt: y().default("now"),
2541
- finishedAt: y().nullable(),
2542
- direction: S().default("import"),
2543
- mode: S(),
2544
- via: S(),
2545
- bundle: S().nullable(),
2546
- sourceFingerprint: S().nullable(),
2547
- tablesWritten: x().default(0),
2548
- rowsWritten: x().default(0),
2549
- failure: S().nullable(),
2550
- staged: fe().nullable()
2551
- }).renamedFrom("_voltro_data_imports").nonReactive(), Vc = (e) => {
2551
+ }, Uc = "_voltro_cdc_offsets", Wc = T(Uc, {
2552
+ id: _({ prefix: "cdcoff" }),
2553
+ replicaId: t(),
2554
+ streamName: t(),
2555
+ binlogFile: t(),
2556
+ binlogPosition: t(),
2557
+ updatedAt: C()
2558
+ }).index(["replicaId"]), Gc = T(Uc, {
2559
+ id: _({ prefix: "cdcoff" }),
2560
+ replicaId: t(),
2561
+ streamName: t(),
2562
+ ctVersion: t(),
2563
+ updatedAt: C()
2564
+ }).index(["replicaId"]), Kc = "_voltro_data_transfers", qc = T(Kc, {
2565
+ id: _({ prefix: "dimp" }),
2566
+ startedAt: C().default("now"),
2567
+ finishedAt: C().nullable(),
2568
+ direction: t().default("import"),
2569
+ mode: t(),
2570
+ via: t(),
2571
+ bundle: t().nullable(),
2572
+ sourceFingerprint: t().nullable(),
2573
+ tablesWritten: S().default(0),
2574
+ rowsWritten: S().default(0),
2575
+ failure: t().nullable(),
2576
+ staged: r().nullable()
2577
+ }).renamedFrom("_voltro_data_imports").nonReactive(), Jc = (e) => {
2552
2578
  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)";
2553
2579
  return `${t} · ${r} · via ${e.via}${i}` + (e.bundle === null ? "" : ` · from ${e.bundle}`) + (e.sourceFingerprint === null ? "" : ` · source schema ${e.sourceFingerprint}`);
2554
- }, Hc = "postgres";
2580
+ }, Yc = "postgres";
2555
2581
  //#endregion
2556
- export { Ve as AUTO_FILLED_COLUMNS, lc as BULK_INSERT_LIMITS, J as BranchNameInvalid, ls as BranchTransitionInvalid, Ic as CDC_OFFSETS_TABLE, vc as CHANGE_LISTENER_CEILING, xe as ColumnBuilder, zc as DATA_TRANSFERS_TABLE, Ee as DEFAULT_ACQUIRE_TIMEOUT_MS, jo as DEFAULT_EAGER_FALLBACK_WARN_INTERVAL_MS, Gn as DEFAULT_SUBJECT_GRAPH_DEPTH, Kt as ENCRYPTED_PREFIX, Hc as ENGINE, cr as EagerCardinalityError, Je as FILE_MIGRATION_PATTERN, ft as FRAMEWORK_LIVE_TABLES, qt as FieldDecryptionError, Qa as ID_COLUMN_MAX_LENGTH, Wo as INITIAL_VERSION, ca as MATCHES_NO_ROWS, Ue as MAX_IDENTIFIER_LENGTH, ic as REPLACE_IN_PROGRESS_TABLE, zt as SqlClient, Zo as TableStreamError, xr as TenantNamespaceInvalid, br as TenantNamespaceUnresolved, Os as TenantRegionUnavailable, Ds as TenantResidencyUnresolved, Go as VOLTRO_EXPIRES_MIXIN_ID, qo as VOLTRO_LOCAL_FIRST_MIXIN_ID, Bo as VersionConflict, ot as WARN_IDENTIFIER_LENGTH, nc as _voltroApiKeysTable, Lc as _voltroCdcOffsetsTable, Bc as _voltroDataTransfersTable, ec as _voltroIdempotencyTable, tc as _voltroKvTable, $s as _voltroMigrationPlansTable, Zs as _voltroMigrationsTable, Rc as _voltroMssqlCdcOffsetsTable, ac as _voltroReplaceInProgressTable, Qs as _voltroSeedsTable, Ji as actorsTable, Ss as admitBranch, Ct as allEnumRenames, Hn as allRegisteredRelations, g as allRegisteredTables, fa as and, d as array, aa as arrayContains, sa as arrayHas, oa as arrayOverlaps, ur as attachEagerLoads, Pa as attributionFields, Ra as attributionKey, Hs as auditAllTableIndexes, Vs as auditTableIndexes, gt as avg, St as avgOver, qa as beginLocalWrite, l as bigint, Is as bindResidentStore, fe as boolean, os as branchNamespaceName, uc as bulkInsertLimitsFor, Qe as bytes, ka as changeDelete, Da as changeInsert, Aa as changeSoftDelete, Oa as changeUpdate, fc as chunkRowsForInsert, Va as claimPendingAttribution, fn as classifyConstraintViolation, Ie as clearEnumRenames, Xa as clearPendingAttribution, Wn as clearRelationsRegistry, Ms as clearResidencyConfig, Nc as clearRetentions, Se as clearTableRegistry, ao as clearWriteRecorders, U as coercePredicateForSqlite, kr as coercePredicateValue, Ar as coercePredicateValues, Bi as coerceValueForSqlite, wa as collectSubqueries, Fe as column, vn as columnSchema, dc as columnsPerRow, Ur as compileEagerJson, I as compilePredicate, jr as compileRawFragment, Hr as compileSelect, ns as computeEmbedding, Tc as connectionIdentity, ra as contains, bt as count, ve as countDistinct, r as crdtDoc, Xe as crdtManagedColumns, ce as crdtManagedColumnsOf, ue as crdtText, Na as currentWriteAttribution, o as databaseHandle, me as date, p as dbEnum, To as dbMetricTagCacheSizeForTests, Oo as dbOperationsInFlight, ne as decimal, xt as declareEnumRename, Qt as decodeFieldValue, ar as decodeRowsFromSchema, rn as decryptFieldsOnRead, Ys as defineMigration, Ye as defineMixin, ut as defineSeed, vt as denseRank, Qn as deriveSubjectGraph, dt as deriveTypeIdPrefix, to as derivedRowId, no as derivedRowIdLength, hn as describeDriverError, gn as describeRowBindings, Vc as describeTransferRun, Gt as deserializeArraysOnRead, nt as drainIdentifierWarnings, oe as dropped, Xt as encodeFieldValue, sr as encodeRowForSchema, nn as encryptFieldsForWrite, tn as encryptedColumnsOf, Ja as endLocalWrite, ys as enforceBranchLimits, we as ensureTableRegistered, Yi as eq, F as escapeLike, Ca as evaluatePredicate, be as except, ya as exists, Ko as expires, Ea as externalChangeEvent, ln as extractDbCause, Le as fireSchemaChangeSeeds, $e as fireTenantCreateSeeds, qs as formatIndexAuditIssue, $n as formatSubjectGraph, rc as frameworkTables, Re as generateId, ht as generateSnowflake, _e as geography, Tt as geometry, ye as getEnumRenames, Vn as getRelation, Bn as getRelations, js as getResidencyConfig, m as getTable, Zi as gt, Qi as gte, yr as hasEagerLoads, ts as hybridSearch, a as id, ta as inSet, _a as inSubquery, jn as inferForeignKey, hc as insertRow, x as integer, oc as interruptedReplaceRefusal, u as intersect, ee as interval, ss as isBranchNamespace, En as isEmptyRelationsSpec, Yt as isEncrypted, Jt as isFieldDecryptionError, Ne as isFileMigration, pn as isForeignKeyViolation, rt as isFrameworkOwnedLiveTable, Yo as isLocalFirst, Xs as isMigrationDefinition, Ae as isMysqlFamily, ps as isNeonConnection, ua as isNotNull, la as isNull, xc as isPrimaryKeyConflictError, mn as isQueryTimeout, $t as isRawEncoding, Ps as isRegionServable, Dn as isRelationsSpec, mt as isSeedDefinition, he as isSqliteFamily, _ as isTableReactive, tt as isView, b as json, ha as jsonField, pt as jsonIndex, c as lag, de as lead, Ac as listRetentionConflicts, Mc as listRetentions, Jo as localFirst, Xo as localFirstTables, $i as lt, ea as lte, Po as makeEagerFallbackReporter, Es as makeNamespaceBranchExecutor, kn as many, An as manyToMany, Te as materializeFields, Ze as max, it as migration, n as min, mc as missingConflictColumns, pc as missingRequiredColumns, Pe as mixin, Xi as neq, us as nextBranchState, wc as normaliseTarget, ma as not, ba as notExists, na as notInSet, va as notInSubquery, h as numeric, Ao as observeDbOp, On as one, lr as oneCardinalityMessage, pa as or, C as orderClausesOf, se as paginateBy, le as paginateById, Za as pendingAttributionCount, _s as planBranch, ds as planBranchProvision, fs as planBranchTeardown, vs as planBranchTeardownFor, hs as planNeonBranchProvision, gs as planNeonBranchTeardown, Ho as planVersionedUpdate, s as pluginRef, yt as pluginRefSpecOf, bc as primaryKeyConflictError, bs as provisionBranch, Ls as provisionResidentTenant, Er as qualifyTable, pe as queryFor, Ke as queryForView, e as quoteIdent, yc as raiseChangeListenerCeiling, f as rank, ae as raw, ct as readableByColumns, ie as real, ko as recordDbOp, uo as recordsTable, ke as reference, Wi as registerCoreTables, zn as registerDiscoveredRelations, Ba as registerPendingAttribution, Rn as registerRelations, jc as registerRetention, st as registerTable, ro as registerWriteRecorder, Tn as relations, Ki as requireActors, re as requireTable, qi as requireTenants, wo as resetDbMetricTagCacheForTests, Be as resetSnowflake, Fs as residentPlacement, Vt as resolveActorSnapshot, ms as resolveBranchMechanism, No as resolveEagerFallbackWarnIntervalMs, Ya as resolveEchoAttribution, te as resolveFullTextIndex, et as resolveIdScheme, at as resolveMixinGraph, Ns as resolveTenantHome, Tr as resolveTenantNamespace, Fc as retentionTtlMsFromEnv, v as rowNumber, yn as rowSchema, Ro as runRetryingTransaction, zo as runStoreTransaction, Ma as runWithWriteAttribution, fo as runWriteRecorders, Ec as sameDatabase, wr as sanitizeIdentifierFragment, Wt as serializeArraysForWrite, De as serverOnlyColumns, As as setResidencyConfig, ze as setSchemaChangeSeedHook, He as setTenantCreateSeedHook, Fo as settleTransactionExit, Uo as settleVersionedUpdate, da as spatialPredicate, sc as stampGeneratedId, cc as stampGeneratedIds, ia as startsWith, es as streamTable, ge as sum, wt as sumOver, so as suspendWriteRecorders, co as suspendWriteRecordersEffect, Pc as sweepRetention, w as table, xs as teardownBranch, S as text, y as timestamp, Et as timestampMs, Dt as timestampMsOrNull, i as union, Ce as unionAll, Oe as unregisterTable, io as unregisterWriteRecorder, _c as updateManyRow, gc as upsertRow, qe as validateColumnName, Ge as validateIndexName, Un as validateRegisteredRelations, Fn as validateRelationConfig, Me as validateTableName, _t as validateTypeIdPrefix, t as vector, lt as vectorDistanceToOpclass, rs as vectorEmbedding, Vo as versionColumnOf, We as view, je as viewSql, Ta as walkLeaves, Fa as withCapturedAttribution, lo as writeRecordersSuspended };
2582
+ export { nt as AUTO_FILLED_COLUMNS, gc as BULK_INSERT_LIMITS, Y as BranchNameInvalid, us as BranchTransitionInvalid, Uc as CDC_OFFSETS_TABLE, Tc as CHANGE_LISTENER_CEILING, l as ColumnBuilder, Kc as DATA_TRANSFERS_TABLE, fe as DEFAULT_ACQUIRE_TIMEOUT_MS, Mo as DEFAULT_EAGER_FALLBACK_WARN_INTERVAL_MS, Gn as DEFAULT_SUBJECT_GRAPH_DEPTH, qt as ENCRYPTED_PREFIX, Yc as ENGINE, cr as EagerCardinalityError, rt as FILE_MIGRATION_PATTERN, ft as FRAMEWORK_LIVE_TABLES, Jt as FieldDecryptionError, $a as ID_COLUMN_MAX_LENGTH, Go as INITIAL_VERSION, la as MATCHES_NO_ROWS, et as MAX_IDENTIFIER_LENGTH, ac as REPLACE_IN_PROGRESS_TABLE, sc as STAGING_STALE_MINUTES, tt as STAGING_TABLE_PREFIX, Bt as SqlClient, Qo as TableStreamError, Sr as TenantNamespaceInvalid, xr as TenantNamespaceUnresolved, ks as TenantRegionUnavailable, Os as TenantResidencyUnresolved, Ko as VOLTRO_EXPIRES_MIXIN_ID, Jo as VOLTRO_LOCAL_FIRST_MIXIN_ID, Vo as VersionConflict, Ke as WARN_IDENTIFIER_LENGTH, rc as _voltroApiKeysTable, Wc as _voltroCdcOffsetsTable, qc as _voltroDataTransfersTable, tc as _voltroIdempotencyTable, nc as _voltroKvTable, ec as _voltroMigrationPlansTable, Qs as _voltroMigrationsTable, Gc as _voltroMssqlCdcOffsetsTable, oc as _voltroReplaceInProgressTable, $s as _voltroSeedsTable, Yi as actorsTable, Cs as admitBranch, St as allEnumRenames, Hn as allRegisteredRelations, Ce as allRegisteredTables, pa as and, le as array, oa as arrayContains, ca as arrayHas, sa as arrayOverlaps, ur as attachEagerLoads, Fa as attributionFields, za as attributionKey, Us as auditAllTableIndexes, Hs as auditTableIndexes, Fe as avg, xt as avgOver, Ja as beginLocalWrite, Xe as bigint, Ls as bindResidentStore, r as boolean, ss as branchNamespaceName, _c as bulkInsertLimitsFor, Je as bytes, Aa as changeDelete, Oa as changeInsert, ja as changeSoftDelete, ka as changeUpdate, yc as chunkRowsForInsert, Ha as claimPendingAttribution, pn as classifyConstraintViolation, _e as clearEnumRenames, Za as clearPendingAttribution, Wn as clearRelationsRegistry, Ns as clearResidencyConfig, Bc as clearRetentions, m as clearTableRegistry, oo as clearWriteRecorders, W as coercePredicateForSqlite, Ar as coercePredicateValue, jr as coercePredicateValues, Vi as coerceValueForSqlite, Ta as collectSubqueries, ge as column, yn as columnSchema, vc as columnsPerRow, Gr as compileEagerJson, I as compilePredicate, Mr as compileRawFragment, Wr as compileSelect, rs as computeEmbedding, Mc as connectionIdentity, ia as contains, o as count, yt as countDistinct, oe as crdtDoc, se as crdtManagedColumns, de as crdtManagedColumnsOf, p as crdtText, Pa as currentWriteAttribution, ve as databaseHandle, te as date, ie as dbEnum, Eo as dbMetricTagCacheSizeForTests, ko as dbOperationsInFlight, he as decimal, s as declareEnumRename, $t as decodeFieldValue, ar as decodeRowsFromSchema, an as decryptFieldsOnRead, Xs as defineMigration, it as defineMixin, Ze as defineSeed, u as denseRank, Qn as deriveSubjectGraph, Qe as deriveTypeIdPrefix, no as derivedRowId, ro as derivedRowIdLength, gn as describeDriverError, _n as describeRowBindings, Jc as describeTransferRun, Kt as deserializeArraysOnRead, Ge as drainIdentifierWarnings, Et as dropped, Zt as encodeFieldValue, sr as encodeRowForSchema, rn as encryptFieldsForWrite, nn as encryptedColumnsOf, Ya as endLocalWrite, bs as enforceBranchLimits, y as ensureTableRegistered, Xi as eq, Nr as escapeLike, wa as evaluatePredicate, c as except, ba as exists, qo as expires, Da as externalChangeEvent, un as extractDbCause, ht as fireSchemaChangeSeeds, ze as fireTenantCreateSeeds, Js as formatIndexAuditIssue, $n as formatSubjectGraph, ic as frameworkTables, gt as generateId, Ue as generateSnowflake, a as geography, Se as geometry, bt as getEnumRenames, Vn as getRelation, Bn as getRelations, Ms as getResidencyConfig, E as getTable, Qi as gt, $i as gte, br as hasEagerLoads, ns as hybridSearch, _ as id, na as inSet, va as inSubquery, P as inferForeignKey, Sc as insertRow, S as integer, uc as interruptedReplaceRefusal, ce as intersect, we as interval, cs as isBranchNamespace, Dn as isEmptyRelationsSpec, Xt as isEncrypted, Yt as isFieldDecryptionError, ut as isFileMigration, mn as isForeignKeyViolation, ct as isFrameworkOwnedLiveTable, Xo as isLocalFirst, Zs as isMigrationDefinition, e as isMysqlFamily, ms as isNeonConnection, da as isNotNull, ua as isNull, Oc as isPrimaryKeyConflictError, hn as isQueryTimeout, en as isRawEncoding, Fs as isRegionServable, On as isRelationsSpec, He as isSeedDefinition, Ve as isSqliteFamily, Ne as isStagingTableName, ne as isTableReactive, We as isView, h as json, ga as jsonField, lt as jsonIndex, Ye as lag, n as lead, Lc as listRetentionConflicts, zc as listRetentions, Yo as localFirst, Zo as localFirstTables, ea as lt, ta as lte, Fo as makeEagerFallbackReporter, Ds as makeNamespaceBranchExecutor, An as many, jn as manyToMany, re as materializeFields, qe as max, Le as migration, ae as min, xc as missingConflictColumns, bc as missingRequiredColumns, dt as mixin, Zi as neq, ds as nextBranchState, jc as normaliseTarget, ha as not, xa as notExists, ra as notInSet, ya as notInSubquery, st as numeric, jo as observeDbOp, kn as one, lr as oneCardinalityMessage, ma as or, x as orderClausesOf, ue as paginateBy, f as paginateById, Qa as pendingAttributionCount, vs as planBranch, fs as planBranchProvision, ps as planBranchTeardown, ys as planBranchTeardownFor, gs as planNeonBranchProvision, _s as planNeonBranchTeardown, Uo as planVersionedUpdate, ye as pluginRef, d as pluginRefSpecOf, Dc as primaryKeyConflictError, xs as provisionBranch, Rs as provisionResidentTenant, Dr as qualifyTable, ee as queryFor, je as queryForView, mt as quoteIdent, Ec as raiseChangeListenerCeiling, b as rank, v as raw, Oe as readableByColumns, Ee as real, Ao as recordDbOp, fo as recordsTable, Ae as reference, Gi as registerCoreTables, zn as registerDiscoveredRelations, Va as registerPendingAttribution, Rn as registerRelations, Rc as registerRetention, De as registerTable, io as registerWriteRecorder, En as relations, qi as requireActors, Te as requireTable, Ji as requireTenants, To as resetDbMetricTagCacheForTests, ot as resetSnowflake, Is as residentPlacement, Ht as resolveActorSnapshot, hs as resolveBranchMechanism, Po as resolveEagerFallbackWarnIntervalMs, Xa as resolveEchoAttribution, me as resolveFullTextIndex, Be as resolveIdScheme, Re as resolveMixinGraph, Ps as resolveTenantHome, Er as resolveTenantNamespace, Hc as retentionTtlMsFromEnv, Tt as rowNumber, bn as rowSchema, zo as runRetryingTransaction, Bo as runStoreTransaction, Na as runWithWriteAttribution, po as runWriteRecorders, Nc as sameDatabase, Tr as sanitizeIdentifierFragment, Gt as serializeArraysForWrite, pe as serverOnlyColumns, js as setResidencyConfig, at as setSchemaChangeSeedHook, $e as setTenantCreateSeedHook, Io as settleTransactionExit, Wo as settleVersionedUpdate, fa as spatialPredicate, fc as stagingLeftoverReport, dc as stagingLeftovers, lc as stagingNamesOf, cc as stagingStaleAfterMs, mc as stampGeneratedId, hc as stampGeneratedIds, aa as startsWith, ts as streamTable, i as sum, xe as sumOver, co as suspendWriteRecorders, lo as suspendWriteRecordersEffect, Vc as sweepRetention, T as table, Ss as teardownBranch, t as text, C as timestamp, Dt as timestampMs, Ot as timestampMsOrNull, g as union, be as unionAll, ke as unregisterTable, ao as unregisterWriteRecorder, wc as updateManyRow, Cc as upsertRow, Me as validateColumnName, vt as validateIndexName, Un as validateRegisteredRelations, Fn as validateRelationConfig, wt as validateTableName, Ie as validateTypeIdPrefix, pt as vector, Pe as vectorDistanceToOpclass, is as vectorEmbedding, Ho as versionColumnOf, _t as view, Ct as viewSql, Ea as walkLeaves, Ia as withCapturedAttribution, uo as writeRecordersSuspended };