@voltro/database 0.81.0 → 0.83.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, $n as t, $t as n, A as r, An as i, Ar as a, At as o, B as s, Bn as c, Bt as l, C as u, Cn as d, Cr as f, Ct as p, D as m, Dn as h, Dr as g, Dt as _, E as v, En as ee, Er as te, Et as ne, F as re, Fn as ie, Fr as y, Ft as ae, G as oe, Gn as se, Gt as ce, H as le, Hn as ue, Ht as de, I as fe, In as pe, Ir as b, It as me, J as he, Jn as ge, Jt as _e, K as ve, Kn as ye, Kt as be, L as xe, Ln as Se, Lr as Ce, Lt as we, M as Te, Mn as Ee, Mr as De, Mt as Oe, N as ke, Nn as Ae, Nr as je, Nt as Me, On as Ne, Or as Pe, Ot as Fe, P as Ie, Pn as Le, Pr as Re, Q as ze, Qn as Be, Qt as Ve, R as He, Rn as Ue, Rt as We, S as Ge, Sn as Ke, Sr as qe, St as Je, T as Ye, Tn as Xe, Tr as Ze, Tt as Qe, U as $e, Un as et, Ut as tt, V as nt, Vn as rt, Vt as it, W as at, Wn as x, Wt as ot, X as st, Xn as ct, Xt as lt, Y as ut, Yn as dt, Yt as ft, Z as pt, Zn as mt, Zt as ht, _ as gt, _n as _t, _r as vt, _t as yt, a as bt, an as xt, ar as St, at as Ct, b as wt, bn as Tt, br as Et, bt as Dt, c as Ot, cn as kt, cr as At, ct as jt, d as Mt, dn as Nt, dr as Pt, dt as Ft, en as It, er as Lt, et as Rt, f as zt, fn as Bt, fr as Vt, ft as Ht, g as Ut, gn as Wt, gr as Gt, gt as Kt, h as qt, hn as Jt, hr as Yt, ht as Xt, i as Zt, in as Qt, ir as $t, it as en, j as tn, jn as nn, jr as rn, jt as an, k as on, kn as sn, kr as cn, kt as ln, l as un, ln as dn, lr as fn, lt as pn, m as mn, mn as hn, mr as gn, mt as _n, n as vn, nn as S, nr as yn, nt as bn, o as xn, on as Sn, or as Cn, ot as wn, p as Tn, pn as En, pr as Dn, pt as On, q as kn, qn as An, qt as jn, r as Mn, rn as Nn, rr as Pn, rt as Fn, s as In, sn as Ln, sr as Rn, st as zn, t as Bn, tn as Vn, tr as Hn, tt as Un, u as Wn, un as Gn, ur as Kn, ut as qn, v as Jn, vn as Yn, vr as Xn, vt as Zn, w as Qn, wn as $n, wr as er, wt as tr, x as nr, xn as rr, xr as ir, xt as ar, y as or, yn as sr, yr as cr, yt as lr, z as ur, zn as dr, zt as fr } from "./replaceInProgress-C_aXxOIX.js";
2
- import { a as pr, i as mr, n as hr, o as gr, r as _r, s as vr, t as yr } from "./wire-B28cPjEp.js";
3
- import { Cause as br, Chunk as xr, Data as Sr, Effect as C, Exit as Cr, Metric as w, MetricBoundaries as wr, Option as T, Schedule as Tr, Schema as E, Stream as Er } from "effect";
4
- import { createHash as Dr } from "node:crypto";
5
- import { AsyncLocalStorage as Or } from "node:async_hooks";
6
- import { TransactionConnection as kr } from "@effect/sql/SqlClient";
7
- import { ansi as D } from "@voltro/logger";
8
- import { SqlClient as Ar } from "@effect/sql";
1
+ import { $ as e, $n as t, $t as n, A as r, An as i, Ar as a, At as o, B as s, Bn as c, Br as l, Bt as u, C as d, Cn as f, Cr as p, Ct as m, D as h, Dn as g, Dr as _, Dt as v, E as ee, En as te, Er as ne, Et as re, F as ie, Fn as ae, Fr as oe, Ft as se, G as ce, Gn as le, Gt as ue, H as de, Hn as fe, Hr as pe, Ht as me, I as he, In as ge, Ir as _e, J as ve, Jn as ye, Jt as be, K as xe, Kn as Se, Kt as Ce, L as we, Ln as Te, Lr as Ee, Lt as De, M as Oe, Mn as ke, Mr as Ae, Mt as je, N as Me, Nn as Ne, Nr as Pe, Nt as Fe, O as Ie, On as Le, Or as y, Ot as Re, P as ze, Pn as Be, Pr as Ve, Pt as He, Q as Ue, Qn as We, Qt as Ge, R as Ke, Rn as qe, Rr as Je, Rt as Ye, S as Xe, Sn as Ze, Sr as Qe, St as $e, T as et, Tn as tt, Tr as nt, Tt as rt, U as it, Un as at, Ut as ot, V as st, Vn as ct, Vr as b, Vt as lt, W as ut, Wn as dt, Wt as ft, X as pt, Xn as mt, Xt as ht, Y as gt, Yn as x, Yt as _t, Z as vt, Zn as yt, Zt as bt, _ as xt, _n as St, _r as Ct, _t as wt, a as Tt, an as Et, ar as Dt, at as Ot, b as kt, bn as At, br as jt, bt as Mt, c as Nt, cn as Pt, cr as Ft, ct as It, d as Lt, dn as Rt, dr as zt, dt as Bt, en as Vt, er as Ht, et as Ut, f as Wt, fn as Gt, fr as Kt, ft as qt, g as Jt, gn as Yt, gr as Xt, gt as Zt, h as Qt, hn as $t, hr as en, ht as tn, i as nn, in as rn, ir as an, it as on, j as sn, jn as cn, jr as ln, jt as un, kn as dn, kr as fn, kt as pn, l as mn, ln as hn, lr as gn, lt as _n, m as vn, mn as yn, mr as bn, mt as xn, n as Sn, nn as Cn, nr as wn, nt as Tn, o as En, on as Dn, or as On, ot as kn, p as An, pn as jn, pr as Mn, pt as Nn, q as Pn, qn as Fn, qt as In, r as Ln, rn as Rn, rr as zn, rt as Bn, s as Vn, sn as S, sr as Hn, st as Un, t as Wn, tn as Gn, tr as Kn, tt as qn, u as Jn, un as Yn, ur as Xn, ut as Zn, v as Qn, vn as $n, vr as er, vt as tr, w as nr, wn as rr, wr as ir, wt as C, x as ar, xn as or, xr as sr, xt as cr, y as lr, yn as ur, yr as dr, yt as fr, z as pr, zn as mr, zr as hr, zt as gr } from "./replaceInProgress-CncEA_Sx.js";
2
+ import { a as _r, i as vr, n as yr, o as br, r as xr, s as Sr, t as Cr } from "./wire-B28cPjEp.js";
3
+ import { Cause as wr, Chunk as Tr, Data as Er, Effect as w, Exit as Dr, Metric as T, MetricBoundaries as Or, Option as E, Schedule as kr, Schema as D, Stream as Ar } from "effect";
4
+ import { createHash as jr } from "node:crypto";
5
+ import { AsyncLocalStorage as Mr } from "node:async_hooks";
6
+ import { TransactionConnection as Nr } from "@effect/sql/SqlClient";
7
+ import { ansi as O } from "@voltro/logger";
8
+ import { SqlClient as Pr } from "@effect/sql";
9
9
  //#region src/actorSnapshot.ts
10
- var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n) => {
10
+ var Fr = (e) => typeof e == "string" && e !== "" ? e : null, Ir = 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 jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
23
23
  }))[0];
24
24
  return r === void 0 ? void 0 : {
25
25
  id: t,
26
- type: jr(r.kind) ?? n,
27
- displayName: jr(r.displayName),
28
- email: jr(r.email)
26
+ type: Fr(r.kind) ?? n,
27
+ displayName: Fr(r.displayName),
28
+ email: Fr(r.email)
29
29
  };
30
30
  } catch {
31
31
  return;
32
32
  }
33
- }, Nr = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqlite", Pr = (e) => {
33
+ }, Lr = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqlite", Rr = (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
- }, Fr = (e, t, n) => {
38
- if (!Nr(n) || !t) return e;
39
- let r = Pr(t);
37
+ }, zr = (e, t, n) => {
38
+ if (!Lr(n) || !t) return e;
39
+ let r = Rr(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 jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
44
44
  Array.isArray(t) && (i[e] = JSON.stringify(t));
45
45
  }
46
46
  return i;
47
- }, Ir = (e, t, n) => {
48
- if (!Nr(n) || !t) return e;
49
- let r = Pr(t);
47
+ }, Br = (e, t, n) => {
48
+ if (!Lr(n) || !t) return e;
49
+ let r = Rr(t);
50
50
  return r.length === 0 ? e : e.map((e) => {
51
51
  let t;
52
52
  for (let n of r) {
@@ -58,13 +58,13 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
58
58
  }
59
59
  return t ?? e;
60
60
  });
61
- }, Lr = "enc:v1:", Rr = "enc:v2:", zr = (e, t, n) => {
61
+ }, Vr = "enc:v1:", Hr = "enc:v2:", Ur = (e, t, n) => {
62
62
  let r = `${e}:${t}`, i = n == null || n === "" ? void 0 : String(n);
63
63
  return i === void 0 ? { column: r } : {
64
64
  column: r,
65
65
  row: `${r}:${i}`
66
66
  };
67
- }, Br = (e) => typeof e == "string" && e.startsWith("enc:v2:"), Vr = class extends Error {
67
+ }, Wr = (e) => typeof e == "string" && e.startsWith("enc:v2:"), Gr = class extends Error {
68
68
  _tag = "FieldDecryptionError";
69
69
  table;
70
70
  column;
@@ -72,7 +72,7 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
72
72
  constructor(e) {
73
73
  super(`column "${e.table}.${e.column}" is .encrypted() but could not be decrypted (${e.reason}) — the stored value was most likely encrypted under a different key`), this.name = "FieldDecryptionError", this.table = e.table, this.column = e.column, this.reason = e.reason;
74
74
  }
75
- }, Hr = (e) => typeof e == "object" && !!e && e._tag === "FieldDecryptionError", Ur = (e) => typeof e == "string" && (e.startsWith("enc:v1:") || e.startsWith("enc:v2:")), Wr = (e, t, n) => e.encrypt(JSON.stringify(t), n), Gr = /* @__PURE__ */ new Set([
75
+ }, Kr = (e) => typeof e == "object" && !!e && e._tag === "FieldDecryptionError", qr = (e) => typeof e == "string" && (e.startsWith("enc:v1:") || e.startsWith("enc:v2:")), Jr = (e, t, n) => e.encrypt(JSON.stringify(t), n), Yr = /* @__PURE__ */ new Set([
76
76
  "text",
77
77
  "id",
78
78
  "reference",
@@ -80,51 +80,51 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
80
80
  "uuid",
81
81
  "email",
82
82
  "url"
83
- ]), Kr = (e, t, n, r) => {
83
+ ]), Xr = (e, t, n, r) => {
84
84
  let i = e.decrypt(t, r), a;
85
85
  try {
86
86
  a = JSON.parse(i);
87
87
  } catch {
88
88
  return i;
89
89
  }
90
- return typeof a == "string" ? a : n === void 0 || Gr.has(n) ? i : a;
91
- }, qr = (e, t, n, r) => {
90
+ return typeof a == "string" ? a : n === void 0 || Yr.has(n) ? i : a;
91
+ }, Zr = (e, t, n, r) => {
92
92
  let i = e.decrypt(t, r);
93
93
  try {
94
- return typeof JSON.parse(i) == "string" ? !1 : n === void 0 || Gr.has(n) ? !0 : void 0;
94
+ return typeof JSON.parse(i) == "string" ? !1 : n === void 0 || Yr.has(n) ? !0 : void 0;
95
95
  } catch {
96
96
  return !0;
97
97
  }
98
- }, Jr = (e, t) => e.fields[t]?.type, Yr = (e) => {
98
+ }, Qr = (e, t) => e.fields[t]?.type, $r = (e) => {
99
99
  let t = [];
100
100
  for (let [n, r] of Object.entries(e.fields)) r.encrypted === !0 && t.push(n);
101
101
  return t;
102
- }, Xr = "id", Zr = (e, t, n, r) => {
102
+ }, ei = "id", ti = (e, t, n, r) => {
103
103
  if (!t) return e;
104
- let i = Yr(t);
104
+ let i = $r(t);
105
105
  if (i.length === 0) return e;
106
- let a = t.tableName ?? "?", o = r ?? e[Xr], s = { ...e };
106
+ let a = t.tableName ?? "?", o = r ?? e[ei], s = { ...e };
107
107
  for (let e of i) {
108
108
  let t = s[e];
109
- if (!(t == null || Ur(t))) {
109
+ if (!(t == null || qr(t))) {
110
110
  if (!n) throw Error(`column "${a}.${e}" is .encrypted() but no field cipher is registered — set VOLTRO_FIELD_ENCRYPTION_KEY (\`voltro dev\` mints one; \`voltro serve\` refuses to boot without it); in a test, pass \`fieldEncryptionKey\` to makeTestContext`);
111
- s[e] = Wr(n, t, zr(a, e, o));
111
+ s[e] = Jr(n, t, Ur(a, e, o));
112
112
  }
113
113
  }
114
114
  return s;
115
- }, Qr = (e, t, n, r) => {
115
+ }, ni = (e, t, n, r) => {
116
116
  if (!t) return e;
117
- let i = Yr(t);
117
+ let i = $r(t);
118
118
  if (i.length === 0 || !n) return e;
119
119
  let a = r?.onError ?? "throw", o = t.tableName ?? "?";
120
120
  return e.map((e) => {
121
121
  let s;
122
122
  for (let c of i) {
123
123
  let i = e[c];
124
- if (Ur(i)) {
124
+ if (qr(i)) {
125
125
  s ??= { ...e };
126
126
  try {
127
- s[c] = Kr(n, i, Jr(t, c), zr(o, c, r?.rowId ?? e[Xr]));
127
+ s[c] = Xr(n, i, Qr(t, c), Ur(o, c, r?.rowId ?? e[ei]));
128
128
  } catch (e) {
129
129
  let t = String(e?.message ?? e);
130
130
  if (a === "null") {
@@ -135,7 +135,7 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
135
135
  });
136
136
  continue;
137
137
  }
138
- throw new Vr({
138
+ throw new Gr({
139
139
  table: o,
140
140
  column: c,
141
141
  reason: t
@@ -145,77 +145,77 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
145
145
  }
146
146
  return s ?? e;
147
147
  });
148
- }, $r = Symbol.for("@voltro/database/storeRefusal"), ei = (e) => {
148
+ }, ri = Symbol.for("@voltro/database/storeRefusal"), ii = (e) => {
149
149
  let t = x(e.detail);
150
- return Object.defineProperty(t, $r, {
150
+ return Object.defineProperty(t, ri, {
151
151
  value: e,
152
152
  enumerable: !1
153
153
  }), t;
154
- }, ti = (e) => {
155
- for (let t of ye(e)) {
154
+ }, ai = (e) => {
155
+ for (let t of yt(e)) {
156
156
  let e = t;
157
157
  for (let t = 0; e != null && t < 8; t += 1) {
158
- let t = e[$r];
158
+ let t = e[ri];
159
159
  if (t !== void 0) return t;
160
160
  e = e.cause;
161
161
  }
162
162
  }
163
- }, ni = (e) => {
163
+ }, oi = (e) => {
164
164
  let t = (() => {
165
165
  switch (e.type) {
166
- case "id": return e.idScheme?.kind === "numeric" ? E.Number : E.String;
166
+ case "id": return e.idScheme?.kind === "numeric" ? D.Number : D.String;
167
167
  case "text":
168
- case "enum": return E.String;
169
- case "reference": return e.referenceStorage === "numeric" ? E.Number : E.String;
168
+ case "enum": return D.String;
169
+ case "reference": return e.referenceStorage === "numeric" ? D.Number : D.String;
170
170
  case "integer":
171
171
  case "real":
172
- case "decimal": return E.Number;
173
- case "boolean": return E.Boolean;
172
+ case "decimal": return D.Number;
173
+ case "boolean": return D.Boolean;
174
174
  case "timestamp":
175
- case "date": return yr;
176
- case "bigint": return E.BigInt;
177
- case "bytes": return E.Uint8ArrayFromBase64;
178
- case "array": return E.Array(E.Unknown);
179
- case "interval": return E.String;
180
- default: return E.Unknown;
175
+ case "date": return Cr;
176
+ case "bigint": return D.BigInt;
177
+ case "bytes": return D.Uint8ArrayFromBase64;
178
+ case "array": return D.Array(D.Unknown);
179
+ case "interval": return D.String;
180
+ default: return D.Unknown;
181
181
  }
182
182
  })();
183
- return e.nullable === !0 ? E.NullOr(t) : t;
184
- }, ri = (e, t) => {
183
+ return e.nullable === !0 ? D.NullOr(t) : t;
184
+ }, si = (e, t) => {
185
185
  let n = new Set(t?.omit ?? []), r = {};
186
- for (let [t, i] of Object.entries(e.fields)) n.has(t) || (r[t] = ni(i));
187
- return E.Struct(r);
188
- }, ii = (e) => typeof e == "function" ? e : () => e, ai = (e, t) => ({
186
+ for (let [t, i] of Object.entries(e.fields)) n.has(t) || (r[t] = oi(i));
187
+ return D.Struct(r);
188
+ }, ci = (e) => typeof e == "function" ? e : () => e, li = (e, t) => ({
189
189
  kind: "one",
190
- target: ii(e),
190
+ target: ci(e),
191
191
  ...t?.foreignKey === void 0 ? {} : { foreignKey: t.foreignKey },
192
192
  ...t?.sourceKey === void 0 ? {} : { sourceKey: t.sourceKey }
193
- }), oi = (e, t) => ({
193
+ }), ui = (e, t) => ({
194
194
  kind: "many",
195
- target: ii(e),
195
+ target: ci(e),
196
196
  ...t?.foreignKey === void 0 ? {} : { foreignKey: t.foreignKey },
197
197
  ...t?.sourceKey === void 0 ? {} : { sourceKey: t.sourceKey }
198
- }), si = (e, t) => ({
198
+ }), di = (e, t) => ({
199
199
  kind: "manyToMany",
200
- target: ii(e),
201
- through: ii(t.through),
200
+ target: ci(e),
201
+ through: ci(t.through),
202
202
  sourceKey: t.sourceKey,
203
203
  targetKey: t.targetKey
204
- }), ci = {
205
- one: ai,
206
- many: oi,
207
- manyToMany: si
208
- }, li = (e, t) => {
204
+ }), fi = {
205
+ one: li,
206
+ many: ui,
207
+ manyToMany: di
208
+ }, pi = (e, t) => {
209
209
  let n = typeof e == "function" ? e : () => e;
210
210
  return {
211
211
  source: n,
212
- relations: t(ci, n())
212
+ relations: t(fi, n())
213
213
  };
214
- }, ui = (e) => {
214
+ }, mi = (e) => {
215
215
  if (typeof e != "object" || !e) return !1;
216
216
  let t = e;
217
217
  return typeof t.source != "function" || typeof t.relations != "object" || t.relations === null ? !1 : Object.keys(t.relations).length === 0;
218
- }, di = (e) => {
218
+ }, hi = (e) => {
219
219
  if (typeof e != "object" || !e) return !1;
220
220
  let t = e;
221
221
  if (typeof t.source != "function" || typeof t.relations != "object" || t.relations === null) return !1;
@@ -224,35 +224,35 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
224
224
  let t = e?.kind;
225
225
  return t === "one" || t === "many" || t === "manyToMany";
226
226
  });
227
- }, fi = ai, pi = oi, mi = si, hi = (e, t, n) => {
227
+ }, gi = li, _i = ui, vi = di, k = (e, t, n) => {
228
228
  let r = [];
229
229
  for (let [n, i] of Object.entries(e.fields)) i.type === "reference" && i.references?.()?.tableName === t && r.push(n);
230
230
  if (r.length === 0) throw x(`relation '${n}': no reference() column on '${e.tableName}' points at '${t}'. Either add one or pass an explicit { foreignKey: '<column>' }.`);
231
231
  if (r.length > 1) throw x(`relation '${n}': multiple reference() columns on '${e.tableName}' point at '${t}' (${r.join(", ")}). Pass an explicit { foreignKey: '<column>' } to disambiguate.`);
232
232
  return r[0];
233
- }, gi = (e) => Object.keys(e.fields), O = (e, t) => Object.prototype.hasOwnProperty.call(e.fields, t), _i = (e) => {
234
- let t = gi(e);
233
+ }, yi = (e) => Object.keys(e.fields), A = (e, t) => Object.prototype.hasOwnProperty.call(e.fields, t), bi = (e) => {
234
+ let t = yi(e);
235
235
  return t.length === 0 ? "<none>" : t.join(", ");
236
- }, vi = (e, t, n) => {
236
+ }, xi = (e, t, n) => {
237
237
  let r = `relation '${t}' on '${e.tableName}'`, i = n.target();
238
238
  if (n.kind === "manyToMany") {
239
239
  let t = n.through();
240
- for (let [a, o] of [["sourceKey", n.sourceKey], ["targetKey", n.targetKey]]) if (!O(t, o)) throw x(`${r}: manyToMany ${a} '${o}' is not a column on the junction table '${t.tableName}'. Both keys name columns on the JUNCTION — ${a === "sourceKey" ? `sourceKey points at '${e.tableName}'` : `targetKey points at '${i.tableName}'`}. Columns on '${t.tableName}': ${_i(t)}.`);
240
+ for (let [a, o] of [["sourceKey", n.sourceKey], ["targetKey", n.targetKey]]) if (!A(t, o)) throw x(`${r}: manyToMany ${a} '${o}' is not a column on the junction table '${t.tableName}'. Both keys name columns on the JUNCTION — ${a === "sourceKey" ? `sourceKey points at '${e.tableName}'` : `targetKey points at '${i.tableName}'`}. Columns on '${t.tableName}': ${bi(t)}.`);
241
241
  return;
242
242
  }
243
243
  if (n.sourceKey !== void 0 && n.foreignKey !== void 0) throw x(`${r}: pass EITHER sourceKey OR foreignKey, not both. sourceKey '${n.sourceKey}' names a column on the source ('${e.tableName}') holding the target's id; foreignKey '${n.foreignKey}' names a column on the target ('${i.tableName}') holding the source's id. With both, foreignKey is ignored.`);
244
- if (n.sourceKey !== void 0 && !O(e, n.sourceKey)) {
245
- let t = O(i, n.sourceKey);
246
- throw x(`${r}: sourceKey '${n.sourceKey}' is not a column on the source table '${e.tableName}'.` + (t ? ` It IS a column on the target '${i.tableName}' — you probably want { foreignKey: '${n.sourceKey}' }, which names the column on the TARGET that holds this table's id.` : ` Columns on '${e.tableName}': ${_i(e)}.`));
244
+ if (n.sourceKey !== void 0 && !A(e, n.sourceKey)) {
245
+ let t = A(i, n.sourceKey);
246
+ throw x(`${r}: sourceKey '${n.sourceKey}' is not a column on the source table '${e.tableName}'.` + (t ? ` It IS a column on the target '${i.tableName}' — you probably want { foreignKey: '${n.sourceKey}' }, which names the column on the TARGET that holds this table's id.` : ` Columns on '${e.tableName}': ${bi(e)}.`));
247
247
  }
248
- if (n.foreignKey !== void 0 && !O(i, n.foreignKey)) {
249
- let t = O(e, n.foreignKey);
250
- throw x(`${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}': ${_i(i)}.`));
248
+ if (n.foreignKey !== void 0 && !A(i, n.foreignKey)) {
249
+ let t = A(e, n.foreignKey);
250
+ throw x(`${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}': ${bi(i)}.`));
251
251
  }
252
- }, yi = Symbol.for("@voltro/database/relationsRegistry"), bi = globalThis, k = bi[yi] ?? (bi[yi] = /* @__PURE__ */ new Map()), xi = (e) => {
253
- let t = e.source(), n = k.get(t.tableName);
252
+ }, Si = Symbol.for("@voltro/database/relationsRegistry"), Ci = globalThis, j = Ci[Si] ?? (Ci[Si] = /* @__PURE__ */ new Map()), wi = (e) => {
253
+ let t = e.source(), n = j.get(t.tableName);
254
254
  if (n === void 0) {
255
- k.set(t.tableName, new Map(Object.entries(e.relations)));
255
+ j.set(t.tableName, new Map(Object.entries(e.relations)));
256
256
  return;
257
257
  }
258
258
  for (let [r, i] of Object.entries(e.relations)) {
@@ -262,33 +262,33 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
262
262
  n.set(r, i);
263
263
  }
264
264
  }
265
- }, Si = (e) => {
265
+ }, Ti = (e) => {
266
266
  let t = 0;
267
- for (let n of Object.values(e)) di(n) && (xi(n), t += 1);
267
+ for (let n of Object.values(e)) hi(n) && (wi(n), t += 1);
268
268
  return t;
269
- }, Ci = (e) => {
270
- let t = k.get(e);
269
+ }, Ei = (e) => {
270
+ let t = j.get(e);
271
271
  if (t !== void 0) return Object.fromEntries(t);
272
- }, wi = (e, t) => k.get(e)?.get(t), Ti = () => {
272
+ }, Di = (e, t) => j.get(e)?.get(t), Oi = () => {
273
273
  let e = [];
274
- for (let [t, n] of k) for (let [r, i] of n) e.push({
274
+ for (let [t, n] of j) for (let [r, i] of n) e.push({
275
275
  source: t,
276
276
  name: r,
277
277
  relation: i
278
278
  });
279
279
  return e;
280
- }, Ei = () => {
281
- for (let [e, t] of k) {
282
- let n = Wt(e);
283
- if (n !== void 0) for (let [e, r] of t) vi(n, e, r);
284
- }
285
- }, Di = () => {
286
- k.clear();
287
- }, Oi = 4, ki = (e) => Object.keys(e.fields), Ai = (e, t) => Object.prototype.hasOwnProperty.call(e.fields, t), ji = (e, t) => {
280
+ }, ki = () => {
281
+ for (let [e, t] of j) {
282
+ let n = or(e);
283
+ if (n !== void 0) for (let [e, r] of t) xi(n, e, r);
284
+ }
285
+ }, Ai = () => {
286
+ j.clear();
287
+ }, ji = 4, Mi = (e) => Object.keys(e.fields), Ni = (e, t) => Object.prototype.hasOwnProperty.call(e.fields, t), Pi = (e, t) => {
288
288
  let n = [];
289
289
  for (let [r, i] of Object.entries(e.fields)) i.type === "reference" && i.references?.()?.tableName === t && n.push(r);
290
290
  return n;
291
- }, Mi = (e, t) => {
291
+ }, Fi = (e, t) => {
292
292
  let n = [];
293
293
  for (let r of t) {
294
294
  if (r.source !== e) continue;
@@ -305,7 +305,7 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
305
305
  } catch {
306
306
  continue;
307
307
  }
308
- if (!Ai(e, t.sourceKey)) continue;
308
+ if (!Ni(e, t.sourceKey)) continue;
309
309
  n.push({
310
310
  table: e.tableName,
311
311
  foreignKey: t.sourceKey,
@@ -314,8 +314,8 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
314
314
  continue;
315
315
  }
316
316
  if (t.sourceKey !== void 0) continue;
317
- let a = ji(i, e), o = t.foreignKey ?? (a.length === 1 ? a[0] : void 0);
318
- if (o === void 0 || !Ai(i, o)) continue;
317
+ let a = Pi(i, e), o = t.foreignKey ?? (a.length === 1 ? a[0] : void 0);
318
+ if (o === void 0 || !Ni(i, o)) continue;
319
319
  let s = i.fields[o];
320
320
  n.push({
321
321
  table: i.tableName,
@@ -324,9 +324,9 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
324
324
  });
325
325
  }
326
326
  return n;
327
- }, Ni = (e, t) => {
327
+ }, Ii = (e, t) => {
328
328
  let n = [];
329
- for (let r of t) if (r.tableName !== e) for (let t of ji(r, e)) {
329
+ for (let r of t) if (r.tableName !== e) for (let t of Pi(r, e)) {
330
330
  let e = r.fields[t];
331
331
  n.push({
332
332
  table: r.tableName,
@@ -335,8 +335,8 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
335
335
  });
336
336
  }
337
337
  return n;
338
- }, Pi = (e) => `${e.table}\u0000${e.hops.map((e) => `${e.table}.${e.foreignKey}<-${e.parentKey}`).join("|")}`, Fi = (e) => {
339
- let t = e.tables ?? En(), n = e.relations ?? Ti(), r = e.maxDepth ?? 4, i = new Set(e.exclude ?? []), a = new Map(t.map((e) => [e.tableName, e])), o = [];
338
+ }, Li = (e) => `${e.table}\u0000${e.hops.map((e) => `${e.table}.${e.foreignKey}<-${e.parentKey}`).join("|")}`, Ri = (e) => {
339
+ let t = e.tables ?? $n(), n = e.relations ?? Oi(), r = e.maxDepth ?? 4, i = new Set(e.exclude ?? []), a = new Map(t.map((e) => [e.tableName, e])), o = [];
340
340
  if (!a.has(e.subjectTable)) return {
341
341
  subjectTable: e.subjectTable,
342
342
  paths: [],
@@ -351,11 +351,11 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
351
351
  hops: [],
352
352
  depth: 0,
353
353
  via: "relation"
354
- }, c = [s], l = /* @__PURE__ */ new Set([Pi(s)]), u = /* @__PURE__ */ new Set(), d = [s];
354
+ }, c = [s], l = /* @__PURE__ */ new Set([Li(s)]), u = /* @__PURE__ */ new Set(), d = [s];
355
355
  for (let e = 1; e <= r; e++) {
356
356
  let r = [];
357
357
  for (let a of d) {
358
- let s = Mi(a.table, n), d = Ni(a.table, t), f = [...s.map((e) => [e, "relation"]), ...d.map((e) => [e, "reference"])];
358
+ let s = Fi(a.table, n), d = Ii(a.table, t), f = [...s.map((e) => [e, "relation"]), ...d.map((e) => [e, "reference"])];
359
359
  for (let [t, n] of f) {
360
360
  if (i.has(t.table)) {
361
361
  o.push({
@@ -373,7 +373,7 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
373
373
  hops: [...a.hops, t],
374
374
  depth: e,
375
375
  via: n
376
- }, f = Pi(d);
376
+ }, f = Li(d);
377
377
  l.has(f) || (l.add(f), c.push(d), r.push(d));
378
378
  }
379
379
  }
@@ -383,7 +383,7 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
383
383
  }
384
384
  d = r;
385
385
  }
386
- for (let e of d) (Mi(e.table, n).length > 0 || Ni(e.table, t).length > 0) && o.push({
386
+ for (let e of d) (Fi(e.table, n).length > 0 || Ii(e.table, t).length > 0) && o.push({
387
387
  kind: "depth-truncated",
388
388
  table: e.table,
389
389
  detail: `stopped at maxDepth ${r}; tables linked FROM '${e.table}' were not explored`
@@ -392,14 +392,14 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
392
392
  for (let n of t) f.has(n.tableName) || i.has(n.tableName) || o.push({
393
393
  kind: "unreachable",
394
394
  table: n.tableName,
395
- detail: `no relation() and no reference() column links '${n.tableName}' to '${e.subjectTable}'. If it holds subject data through a plain column, a polymorphic (type,id) pair, JSON or free text, add an explicit subjectScopes entry — this derivation cannot see it. Columns: ${ki(n).join(", ")}`
395
+ detail: `no relation() and no reference() column links '${n.tableName}' to '${e.subjectTable}'. If it holds subject data through a plain column, a polymorphic (type,id) pair, JSON or free text, add an explicit subjectScopes entry — this derivation cannot see it. Columns: ${Mi(n).join(", ")}`
396
396
  });
397
397
  return {
398
398
  subjectTable: e.subjectTable,
399
399
  paths: c,
400
400
  limitations: o
401
401
  };
402
- }, Ii = (e) => {
402
+ }, zi = (e) => {
403
403
  let t = [`subject graph · ${e.subjectTable} · ${e.paths.length} table(s) reachable`];
404
404
  for (let n of e.paths) {
405
405
  let r = n.hops.length === 0 ? `${e.subjectTable} (the subject row itself)` : [e.subjectTable, ...n.hops.map((e) => `${e.table}.${e.foreignKey}`)].join(" → ");
@@ -407,12 +407,12 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
407
407
  }
408
408
  let n = e.limitations.filter((e) => e.kind === "depth-truncated"), r = e.limitations.filter((e) => e.kind === "unreachable"), i = e.limitations.filter((e) => e.kind === "excluded");
409
409
  return t.push(""), t.push(" WHAT THIS CANNOT SEE — a DSAR is only as complete as this list is short:"), n.length > 0 && t.push(` depth-truncated (${n.length}): ${n.map((e) => e.table).join(", ")}`), i.length > 0 && t.push(` excluded (${i.length}): ${[...new Set(i.map((e) => e.table))].join(", ")}`), t.push(r.length === 0 ? " unreachable: none — every registered table is linked to the subject." : ` unreachable (${r.length}): ${r.map((e) => e.table).join(", ")}`), t.push(" Always outside this graph: object storage / uploaded files, external processors,"), t.push(" log and metric sinks, backups, and any subject id embedded in JSON or free text."), t.join("\n");
410
- }, Li = (e) => Object.fromEntries(Object.entries(e.updateValues ?? {}).filter(([t, n]) => {
410
+ }, Bi = (e) => Object.fromEntries(Object.entries(e.updateValues ?? {}).filter(([t, n]) => {
411
411
  if (n === void 0) return !1;
412
412
  if (t === "id" || e.conflictColumns.includes(t)) throw x(`upsert: updateValues cannot rewrite row identity column '${t}'`);
413
413
  return !0;
414
- })), Ri = (e, t, n) => {
415
- let r = Li(n);
414
+ })), Vi = (e, t, n) => {
415
+ let r = Bi(n);
416
416
  if (typeof n.update == "function") return {
417
417
  ...n.update(t),
418
418
  ...r
@@ -422,21 +422,21 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
422
422
  ...Object.fromEntries(i.filter((t) => t in e).map((t) => [t, e[t]])),
423
423
  ...r
424
424
  };
425
- }, zi = (e) => typeof e == "string" ? [["id", e]] : Object.entries(e).map(([e, t]) => [e, t]), Bi = (e) => {
425
+ }, Hi = (e) => typeof e == "string" ? [["id", e]] : Object.entries(e).map(([e, t]) => [e, t]), Ui = (e) => {
426
426
  if (typeof e == "string") return e;
427
427
  let t = Object.entries(e);
428
428
  return t.length === 1 ? String(t[0][1]) : t.slice().sort(([e], [t]) => e < t ? -1 : +(e > t)).map(([e, t]) => `${e}=${String(t)}`).join("\0");
429
- }, Vi = (e) => typeof e != "string", Hi = (e, t, n) => {
430
- let r = new Set(zi(e).map(([e]) => e)), i = t.split(".")[0];
429
+ }, Wi = (e) => typeof e != "string", Gi = (e, t, n) => {
430
+ let r = new Set(Hi(e).map(([e]) => e)), i = t.split(".")[0];
431
431
  return Object.fromEntries(Object.entries(n ?? {}).filter(([e, t]) => {
432
432
  if (t === void 0) return !1;
433
433
  if (r.has(e) || e === i) throw x(`patchJson: additionalPatch cannot rewrite the primary key or patched JSON column '${e}'`);
434
434
  return !0;
435
435
  }));
436
- }, A = (e) => typeof e == "object" && !!e && !Array.isArray(e), Ui = (e) => JSON.parse(JSON.stringify(e ?? null)), Wi = (e, t, n) => {
437
- let [r, ...i] = t.split("."), a = Ui(n), o = e[r], s = (e, t) => {
436
+ }, M = (e) => typeof e == "object" && !!e && !Array.isArray(e), Ki = (e) => JSON.parse(JSON.stringify(e ?? null)), qi = (e, t, n) => {
437
+ let [r, ...i] = t.split("."), a = Ki(n), o = e[r], s = (e, t) => {
438
438
  if (t === i.length) return a;
439
- let n = A(e) ? e : {}, r = i[t], o = Object.hasOwn(n, r) ? n[r] : void 0;
439
+ let n = M(e) ? e : {}, r = i[t], o = Object.hasOwn(n, r) ? n[r] : void 0;
440
440
  return {
441
441
  ...n,
442
442
  [r]: s(o, t + 1)
@@ -444,14 +444,14 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
444
444
  };
445
445
  return {
446
446
  ...e,
447
- [r]: i.length === 0 ? A(o) && A(a) ? {
447
+ [r]: i.length === 0 ? M(o) && M(a) ? {
448
448
  ...o,
449
449
  ...a
450
450
  } : a : s(o, 0)
451
451
  };
452
- }, Gi = (e, t, n, r, i) => {
453
- let [a, ...o] = n.split("."), s = i ?? e`${e(a)}`, c = Ui(r), l = (e) => /["\\\u0000-\u001f]/.test(e);
454
- if ((t === "sqlite" || t === "turso") && (o.some(l) || o.length === 0 && A(c) && Object.keys(c).some(l))) {
452
+ }, Ji = (e, t, n, r, i) => {
453
+ let [a, ...o] = n.split("."), s = i ?? e`${e(a)}`, c = Ki(r), l = (e) => /["\\\u0000-\u001f]/.test(e);
454
+ if ((t === "sqlite" || t === "turso") && (o.some(l) || o.length === 0 && M(c) && Object.keys(c).some(l))) {
455
455
  let t = 0, n = (t) => e`CASE WHEN (SELECT _voltro_json_escape_probe.key FROM json_each(${String.raw`{"\u0061":0}`}) AS _voltro_json_escape_probe) = ${String.raw`\u0061`}
456
456
  THEN json_extract('"' || replace(${t}.key, '"', ${String.raw`\"`}) || '"', '$')
457
457
  ELSE ${t}.key END`, r = (r) => {
@@ -493,7 +493,7 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
493
493
  return t === "mysql" || t === "mariadb" ? e`JSON_SET(${n}, ${o}, JSON_EXTRACT(${i}, '$'))` : t === "mssql" ? a === null ? e`JSON_MODIFY(JSON_MODIFY(${n}, ${o}, 0), ${`strict ${o}`}, NULL)` : typeof a == "boolean" ? e`JSON_MODIFY(${n}, ${o}, CAST(${+!!a} AS bit))` : typeof a == "string" || typeof a == "number" ? e`JSON_MODIFY(${n}, ${o}, ${a})` : e`JSON_MODIFY(${n}, ${o}, JSON_QUERY(${i}))` : e`json_set(${n}, ${o}, json(${i}))`;
494
494
  }, v;
495
495
  if (o.length === 0) {
496
- if (!A(c)) v = g(c);
496
+ if (!M(c)) v = g(c);
497
497
  else {
498
498
  v = h([]);
499
499
  for (let [e, t] of Object.entries(c)) v = _(v, [e], g(t), t);
@@ -507,17 +507,17 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
507
507
  v = _(v, o, g(c), c);
508
508
  }
509
509
  return e`${e(a)} = ${v}`;
510
- }, Ki = class extends Error {
510
+ }, Yi = class extends Error {
511
511
  _tag = "EagerCardinalityError";
512
512
  constructor(e) {
513
513
  super(e), this.name = "EagerCardinalityError";
514
514
  }
515
- }, qi = (e) => {
515
+ }, Xi = (e) => {
516
516
  let { relationName: t, sourceTableName: n, targetTableName: r, foreignKey: i, sourceKey: a } = e, o = r === n;
517
517
  return `relation '${t}' on '${n}' is declared \`one\`, but ${r}.${i} matches MORE than one row for the same ${n}.${a} — so there is no single related row to return.` + (o ? ` Because this relation is self-referential, check which side the key is on: \`foreignKey: '${i}'\` means "rows whose ${i} points AT me" (my children — there can be many). If you meant "the row my ${i} points to" (my parent), that is \`sourceKey: '${i}'\`.` : " Use `many(...)` if several are expected, or narrow the key.");
518
- }, Ji = async (e, t, n, r) => {
518
+ }, Zi = async (e, t, n, r) => {
519
519
  if (e.length === 0) return e;
520
- let i = Ci(n.tableName);
520
+ let i = Ei(n.tableName);
521
521
  if (i === void 0) throw x(`cannot eager-load on '${n.tableName}': no relations registered. Did you forget to declare \`relations(${n.tableName}, ...)\` or import the file that does?`);
522
522
  let a = e.map((e) => ({ ...e }));
523
523
  for (let [e, o] of Object.entries(t)) {
@@ -526,36 +526,36 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
526
526
  let t = Object.keys(i).join(", ") || "<none>";
527
527
  throw x(`unknown relation '${e}' on '${n.tableName}'. Registered relations: ${t}.`);
528
528
  }
529
- vi(n, e, t), await Yi(a, e, t, o === !0 ? {} : o, n, r);
529
+ xi(n, e, t), await Qi(a, e, t, o === !0 ? {} : o, n, r);
530
530
  }
531
531
  return a;
532
- }, Yi = async (e, t, n, r, i, a) => {
532
+ }, Qi = async (e, t, n, r, i, a) => {
533
533
  switch (n.kind) {
534
534
  case "one":
535
- await Xi(e, t, n, r, i, a);
535
+ await $i(e, t, n, r, i, a);
536
536
  return;
537
537
  case "many":
538
- await Zi(e, t, n, r, i, a);
538
+ await ea(e, t, n, r, i, a);
539
539
  return;
540
540
  case "manyToMany":
541
- await $i(e, t, n, r, i, a);
541
+ await na(e, t, n, r, i, a);
542
542
  return;
543
543
  }
544
- }, Xi = async (e, t, n, r, i, a) => {
545
- let o = n.target(), s = n.sourceKey ?? ea(i, o.tableName);
544
+ }, $i = async (e, t, n, r, i, a) => {
545
+ let o = n.target(), s = n.sourceKey ?? ra(i, o.tableName);
546
546
  if (s !== void 0) {
547
- let n = j(e, s), i = n.length === 0 ? [] : await ta(o, "id", n, r, a), c = new Map(i.map((e) => [e.id, e]));
547
+ let n = N(e, s), i = n.length === 0 ? [] : await ia(o, "id", n, r, a), c = new Map(i.map((e) => [e.id, e]));
548
548
  for (let n of e) {
549
549
  let e = n[s];
550
550
  n[t] = e == null ? null : c.get(e) ?? null;
551
551
  }
552
- await na(i, r.with, o, a);
552
+ await aa(i, r.with, o, a);
553
553
  return;
554
554
  }
555
- let c = n.foreignKey ?? hi(o, i.tableName, t), l = n.sourceKey ?? "id", u = j(e, l), d = u.length === 0 ? [] : await ta(o, c, u, r, a), f = /* @__PURE__ */ new Map();
555
+ let c = n.foreignKey ?? k(o, i.tableName, t), l = n.sourceKey ?? "id", u = N(e, l), d = u.length === 0 ? [] : await ia(o, c, u, r, a), f = /* @__PURE__ */ new Map();
556
556
  for (let e of d) {
557
557
  let n = e[c];
558
- if (f.has(n)) throw new Ki(qi({
558
+ if (f.has(n)) throw new Yi(Xi({
559
559
  relationName: t,
560
560
  sourceTableName: i.tableName,
561
561
  targetTableName: o.tableName,
@@ -568,9 +568,9 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
568
568
  let e = n[l];
569
569
  n[t] = e == null ? null : f.get(e) ?? null;
570
570
  }
571
- await na(d, r.with, o, a);
572
- }, Zi = async (e, t, n, r, i, a) => {
573
- let o = n.target(), s = n.foreignKey ?? hi(o, i.tableName, t), c = n.sourceKey ?? "id", l = j(e, c), u = Qi(r), d = l.length === 0 ? [] : await ta(o, s, l, u, a), f = /* @__PURE__ */ new Map();
571
+ await aa(d, r.with, o, a);
572
+ }, ea = async (e, t, n, r, i, a) => {
573
+ let o = n.target(), s = n.foreignKey ?? k(o, i.tableName, t), c = n.sourceKey ?? "id", l = N(e, c), u = ta(r), d = l.length === 0 ? [] : await ia(o, s, l, u, a), f = /* @__PURE__ */ new Map();
574
574
  for (let e of d) {
575
575
  let t = e[s], n = f.get(t);
576
576
  n ? n.push(e) : f.set(t, [e]);
@@ -586,12 +586,12 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
586
586
  let e = n[c];
587
587
  n[t] = f.get(e) ?? [];
588
588
  }
589
- await na(d, r.with, o, a);
590
- }, Qi = (e) => {
589
+ await aa(d, r.with, o, a);
590
+ }, ta = (e) => {
591
591
  let { limit: t, offset: n, ...r } = e;
592
592
  return r;
593
- }, $i = async (e, t, n, r, i, a) => {
594
- let o = n.target(), s = n.through(), c = j(e, "id");
593
+ }, na = async (e, t, n, r, i, a) => {
594
+ let o = n.target(), s = n.through(), c = N(e, "id");
595
595
  if (c.length === 0) {
596
596
  for (let n of e) n[t] = [];
597
597
  return;
@@ -612,8 +612,8 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
612
612
  for (let n of e) n[t] = [];
613
613
  return;
614
614
  }
615
- let f = await ta(o, "id", j(d, n.targetKey), r, a), p = new Map(f.map((e) => [e.id, e]));
616
- await na(f, r.with, o, a);
615
+ let f = await ia(o, "id", N(d, n.targetKey), r, a), p = new Map(f.map((e) => [e.id, e]));
616
+ await aa(f, r.with, o, a);
617
617
  let m = r.junction === void 0 ? void 0 : r.junction === !0 ? Object.keys(s.fields) : r.junction, h = /* @__PURE__ */ new Map();
618
618
  for (let e of d) {
619
619
  let t = e[n.sourceKey], r = e[n.targetKey], i = p.get(r);
@@ -625,16 +625,16 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
625
625
  o ? o.push(a) : h.set(t, [a]);
626
626
  }
627
627
  for (let n of e) n[t] = h.get(n.id) ?? [];
628
- }, ea = (e, t) => {
628
+ }, ra = (e, t) => {
629
629
  for (let [n, r] of Object.entries(e.fields)) if (r.type === "reference" && r.references?.()?.tableName === t) return n;
630
- }, j = (e, t) => {
630
+ }, N = (e, t) => {
631
631
  let n = /* @__PURE__ */ new Set();
632
632
  for (let r of e) {
633
633
  let e = r[t];
634
634
  e != null && n.add(e);
635
635
  }
636
636
  return [...n];
637
- }, ta = (e, t, n, r, i) => {
637
+ }, ia = (e, t, n, r, i) => {
638
638
  let a = {
639
639
  column: t,
640
640
  op: "in",
@@ -648,34 +648,34 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
648
648
  skip: r.offset,
649
649
  projection: void 0
650
650
  });
651
- }, na = async (e, t, n, r) => {
652
- t !== void 0 && e.length !== 0 && (await Ji(e, t, n, r)).forEach((t, n) => {
651
+ }, aa = async (e, t, n, r) => {
652
+ t !== void 0 && e.length !== 0 && (await Zi(e, t, n, r)).forEach((t, n) => {
653
653
  let r = e[n];
654
654
  for (let [e, n] of Object.entries(t)) e in r || (r[e] = n);
655
655
  });
656
- }, ra = (e) => e.eager !== void 0 && Object.keys(e.eager).length > 0, ia = (e, t, n) => {
656
+ }, oa = (e) => e.eager !== void 0 && Object.keys(e.eager).length > 0, sa = (e, t, n) => {
657
657
  if (e.eager === void 0) return null;
658
- let r = oa(e.table, e.eager, e.sourceTable);
658
+ let r = ua(e.table, e.eager, e.sourceTable);
659
659
  if (r === null) return null;
660
- let i = pa(n, e, r, fa(t, n));
660
+ let i = _a(n, e, r, ga(t, n));
661
661
  return i === null ? null : {
662
662
  fragment: i,
663
- decode: ga(r, n)
663
+ decode: ba(r, n)
664
664
  };
665
- }, M = (e) => e.relation.kind === "one" && e.fkSide === "target", aa = (e) => ({
665
+ }, ca = (e) => e.relation.kind === "one" && e.fkSide === "target", la = (e) => ({
666
666
  ...e,
667
667
  branch: {
668
668
  ...e.branch,
669
669
  limit: 2
670
670
  }
671
- }), oa = (e, t, n) => {
672
- let r = n ?? sr(e), i = Ci(e);
671
+ }), ua = (e, t, n) => {
672
+ let r = n ?? rr(e), i = Ei(e);
673
673
  if (i === void 0) return null;
674
674
  let a = [];
675
675
  for (let [e, n] of Object.entries(t)) {
676
676
  let t = i[e];
677
677
  if (t === void 0) return null;
678
- let o = sa(e, t, r, n === !0 ? {} : n);
678
+ let o = da(e, t, r, n === !0 ? {} : n);
679
679
  if (o === null) return null;
680
680
  a.push(o);
681
681
  }
@@ -683,30 +683,30 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
683
683
  table: r,
684
684
  children: a
685
685
  };
686
- }, sa = (e, t, n, r) => {
686
+ }, da = (e, t, n, r) => {
687
687
  let i = t.target(), a = (t.kind === "manyToMany" ? void 0 : t.sourceKey) ?? "id", o, s;
688
688
  if (t.kind === "manyToMany") o = t.targetKey, s = "target";
689
689
  else if (t.kind === "one") {
690
- let r = t.sourceKey ?? da(n, i.tableName);
690
+ let r = t.sourceKey ?? ha(n, i.tableName);
691
691
  if (r !== void 0) o = r, s = "source";
692
692
  else try {
693
- o = t.foreignKey ?? hi(i, n.tableName, e), s = "target";
693
+ o = t.foreignKey ?? k(i, n.tableName, e), s = "target";
694
694
  } catch {
695
695
  return null;
696
696
  }
697
697
  } else try {
698
- o = t.foreignKey ?? hi(i, n.tableName, e), s = "target";
698
+ o = t.foreignKey ?? k(i, n.tableName, e), s = "target";
699
699
  } catch {
700
700
  return null;
701
701
  }
702
702
  let c = r.with === void 0 ? [] : (() => {
703
- let e = Ci(i.tableName);
703
+ let e = Ei(i.tableName);
704
704
  if (e === void 0 && Object.keys(r.with).length > 0) return null;
705
705
  let t = [];
706
706
  for (let [n, a] of Object.entries(r.with)) {
707
707
  let r = e?.[n];
708
708
  if (r === void 0) return null;
709
- let o = sa(n, r, i, a === !0 ? {} : a);
709
+ let o = da(n, r, i, a === !0 ? {} : a);
710
710
  if (o === null) return null;
711
711
  t.push(o);
712
712
  }
@@ -722,9 +722,9 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
722
722
  fkSide: s,
723
723
  branch: r,
724
724
  children: c,
725
- junction: ca(t, r)
725
+ junction: fa(t, r)
726
726
  };
727
- }, ca = (e, t) => {
727
+ }, fa = (e, t) => {
728
728
  if (e.kind !== "manyToMany" || t.junction === void 0) return;
729
729
  let n = e.through(), r = t.junction === !0 ? Object.keys(n.fields) : t.junction, i = r.filter((e) => e in n.fields);
730
730
  return {
@@ -736,35 +736,35 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
736
736
  return t !== void 0 && (t.type === "timestamp" || t.type === "date");
737
737
  })
738
738
  };
739
- }, la = (e) => `__j_${e}`, ua = "__j", da = (e, t) => {
739
+ }, pa = (e) => `__j_${e}`, ma = "__j", ha = (e, t) => {
740
740
  for (let [n, r] of Object.entries(e.fields)) if (r.type === "reference" && r.references?.()?.tableName === t) return n;
741
- }, fa = (e, t) => {
741
+ }, ga = (e, t) => {
742
742
  let n = 0;
743
743
  return {
744
744
  sql: e,
745
745
  dialect: t,
746
746
  nextAlias: () => `__a${n++}`
747
747
  };
748
- }, pa = (e, t, n, r) => {
748
+ }, _a = (e, t, n, r) => {
749
749
  switch (e) {
750
- case "postgres": return ya(t, n, r);
750
+ case "postgres": return Ca(t, n, r);
751
751
  case "sqlite":
752
- case "turso": return Da(t, n, r);
752
+ case "turso": return ja(t, n, r);
753
753
  case "mysql":
754
- case "mariadb": return La(t, n, r);
755
- case "mssql": return Wa(t, n, r);
754
+ case "mariadb": return Va(t, n, r);
755
+ case "mssql": return Ja(t, n, r);
756
756
  }
757
- }, ma = (e, t) => t === "mssql" && !ha.test(e) ? /* @__PURE__ */ new Date(`${e}Z`) : new Date(e), ha = /(?:Z|[+-]\d{2}:?\d{2})$/, ga = (e, t) => {
758
- let n = _a(e.table, e.children, t);
757
+ }, va = (e, t) => t === "mssql" && !ya.test(e) ? /* @__PURE__ */ new Date(`${e}Z`) : new Date(e), ya = /(?:Z|[+-]\d{2}:?\d{2})$/, ba = (e, t) => {
758
+ let n = xa(e.table, e.children, t);
759
759
  return (e) => e.map((e) => {
760
760
  let t = e.__row, r = typeof t == "string" ? JSON.parse(t) : t;
761
761
  return n(r);
762
762
  });
763
- }, _a = (e, t, n) => {
763
+ }, xa = (e, t, n) => {
764
764
  let r = [], i = [];
765
765
  for (let [t, n] of Object.entries(e.fields)) (n.type === "timestamp" || n.type === "date") && r.push(t), n.type === "vector" && i.push(t);
766
766
  let a = t.map((e) => {
767
- let t = _a(e.target, e.children, n), r = e.relation.kind === "one", i = M(e), a = i ? qi({
767
+ let t = xa(e.target, e.children, n), r = e.relation.kind === "one", i = ca(e), a = i ? Xi({
768
768
  relationName: e.relationName,
769
769
  sourceTableName: e.source.tableName,
770
770
  targetTableName: e.target.tableName,
@@ -777,15 +777,15 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
777
777
  isSingle: r,
778
778
  fromOverFetch: i,
779
779
  cardinalityMessage: a,
780
- junction: va(e.junction, n)
780
+ junction: Sa(e.junction, n)
781
781
  };
782
782
  });
783
783
  return (e) => {
784
784
  let t = { ...e };
785
- for (let e of i) e in t && (t[e] = ae(t[e], "vector", n));
785
+ for (let e of i) e in t && (t[e] = u(t[e], "vector", n));
786
786
  for (let e of r) {
787
787
  let r = t[e];
788
- typeof r == "string" && (t[e] = ma(r, n));
788
+ typeof r == "string" && (t[e] = va(r, n));
789
789
  }
790
790
  for (let e of a) {
791
791
  let n = t[e.name];
@@ -795,7 +795,7 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
795
795
  }
796
796
  if (e.fromOverFetch) {
797
797
  let r = n;
798
- if (r.length > 1) throw new Ki(e.cardinalityMessage);
798
+ if (r.length > 1) throw new Yi(e.cardinalityMessage);
799
799
  t[e.name] = r.length === 0 ? null : e.decode(r[0]);
800
800
  continue;
801
801
  }
@@ -807,204 +807,213 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
807
807
  }
808
808
  return t;
809
809
  };
810
- }, va = (e, t) => {
810
+ }, Sa = (e, t) => {
811
811
  if (e === void 0) return;
812
812
  let n = new Set(e.dateColumns), r = e.requested;
813
813
  return (e) => {
814
814
  let i = e._junction ?? {}, a = {};
815
815
  for (let e of r) {
816
816
  let r = i[e];
817
- a[e] = n.has(e) && typeof r == "string" ? ma(r, t) : r;
817
+ a[e] = n.has(e) && typeof r == "string" ? va(r, t) : r;
818
818
  }
819
819
  return {
820
820
  ...e,
821
821
  _junction: a
822
822
  };
823
823
  };
824
- }, ya = (e, t, n) => {
825
- let r = n.sql, i = n.nextAlias(), a = r(t.table.tableName), o = r(i), s = ba(i, t.children, n);
826
- return s === null ? null : r`SELECT ${s} AS "__row" FROM ${a} AS ${o}${e.predicate ? r` WHERE ${R(e.predicate, i, r)}` : r``}${S(e).length > 0 ? r` ORDER BY ${r.csv(S(e).map((e) => e.direction === "desc" ? r`${F(i, e.column, r)} DESC` : r`${F(i, e.column, r)} ASC`))}` : r``}${e.take === void 0 ? r`` : r` LIMIT ${L(e.take, r)}`}${e.skip === void 0 ? r`` : r` OFFSET ${L(e.skip, r)}`}`;
827
- }, ba = (e, t, n, r) => {
828
- let i = n.sql, a = r === void 0 ? i`to_jsonb(${i(e)}.*)` : i`(to_jsonb(${i(e)}.*) - ${I(ua, i)}::text)`;
824
+ }, Ca = (e, t, n) => {
825
+ let r = n.sql, i = n.nextAlias(), a = r(t.table.tableName), o = r(i), s = wa(i, t.children, n);
826
+ return s === null ? null : r`SELECT ${s} AS "__row" FROM ${a} AS ${o}${e.predicate ? r` WHERE ${z(e.predicate, i, r)}` : r``}${S(e).length > 0 ? r` ORDER BY ${r.csv(S(e).map((e) => e.direction === "desc" ? r`${I(i, e.column, r)} DESC` : r`${I(i, e.column, r)} ASC`))}` : r``}${e.take === void 0 ? r`` : r` LIMIT ${R(e.take, r)}`}${e.skip === void 0 ? r`` : r` OFFSET ${R(e.skip, r)}`}`;
827
+ }, wa = (e, t, n, r) => {
828
+ let i = n.sql, a = r === void 0 ? i`to_jsonb(${i(e)}.*)` : i`(to_jsonb(${i(e)}.*) - ${L(ma, i)}::text)`;
829
829
  if (t.length === 0 && r === void 0) return a;
830
830
  let o = [];
831
- r !== void 0 && o.push(i`${I("_junction", i)}, ${F(e, ua, i)}`);
831
+ r !== void 0 && o.push(i`${L("_junction", i)}, ${I(e, ma, i)}`);
832
832
  for (let r of t) {
833
- let t = xa(r, e, n);
833
+ let t = Ta(r, e, n);
834
834
  if (t === null) return null;
835
- o.push(i`${I(r.relationName, i)}, ${t}`);
835
+ o.push(i`${L(r.relationName, i)}, ${t}`);
836
836
  }
837
837
  return i`${a} || jsonb_build_object(${i.csv(o)})`;
838
- }, xa = (e, t, n) => {
838
+ }, Ta = (e, t, n) => {
839
839
  switch (e.relation.kind) {
840
- case "one": return M(e) ? Ca(aa(e), t, n) : Sa(e, t, n);
841
- case "many": return Ca(e, t, n);
842
- case "manyToMany": return wa(e, t, n);
840
+ case "one": return ca(e) ? Da(la(e), t, n) : Ea(e, t, n);
841
+ case "many": return Da(e, t, n);
842
+ case "manyToMany": return Oa(e, t, n);
843
843
  }
844
- }, Sa = (e, t, n) => {
845
- let r = n.sql, i = n.nextAlias(), a = ba(i, e.children, n);
844
+ }, Ea = (e, t, n) => {
845
+ let r = n.sql, i = n.nextAlias(), a = wa(i, e.children, n);
846
846
  if (a === null) return null;
847
- let o = e.fkSide === "source" ? r`${F(i, "id", r)} = ${F(t, e.foreignKey, r)}` : r`${F(i, e.foreignKey, r)} = ${F(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${R(e.branch.where, i, r)}`, c = N(i, e.branch.orderBy, r);
847
+ let o = e.fkSide === "source" ? r`${I(i, "id", r)} = ${I(t, e.foreignKey, r)}` : r`${I(i, e.foreignKey, r)} = ${I(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${z(e.branch.where, i, r)}`, c = P(i, e.branch.orderBy, r);
848
848
  return r`(SELECT ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o}${s}${c} LIMIT 1)`;
849
- }, Ca = (e, t, n) => {
850
- let r = n.sql, i = n.nextAlias(), a = ba(i, e.children, n);
849
+ }, Da = (e, t, n) => {
850
+ let r = n.sql, i = n.nextAlias(), a = wa(i, e.children, n);
851
851
  if (a === null) return null;
852
- let o = r`${F(void 0, e.foreignKey, r)} = ${F(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${p(e.branch.where, r)}`, c = Ea(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${L(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${L(e.branch.offset, r)}`;
852
+ let o = r`${I(void 0, e.foreignKey, r)} = ${I(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${C(e.branch.where, r)}`, c = Aa(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${R(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${R(e.branch.offset, r)}`;
853
853
  return r`COALESCE((SELECT jsonb_agg(${a}) FROM (SELECT * FROM ${r(e.target.tableName)} WHERE ${o}${s}${c}${l}${u}) AS ${r(i)}), '[]'::jsonb)`;
854
- }, wa = (e, t, n) => {
855
- let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = ba(o, e.children, n, e.junction);
854
+ }, Oa = (e, t, n) => {
855
+ let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = wa(o, e.children, n, e.junction);
856
856
  if (c === null) return null;
857
- let l = e.branch.where === void 0 ? r`` : r` AND ${p(e.branch.where, r)}`, u = z(e, s, r), d = N(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${L(e.branch.limit, r)}`, m = e.branch.offset === void 0 ? r`` : r` OFFSET ${L(e.branch.offset, r)}`, h = e.junction === void 0 ? r`` : r`, ${Ta(e.junction, s, r)} AS ${r(ua)}`;
858
- return r`COALESCE((SELECT jsonb_agg(${c}) FROM (SELECT ${r(o)}.*${h} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${F(o, "id", r)} = ${F(s, i.targetKey, r)} WHERE ${F(s, i.sourceKey, r)} = ${F(t, "id", r)}${u}${l}${d}${f}${m}) AS ${r(o)}), '[]'::jsonb)`;
859
- }, Ta = (e, t, n) => e.present.length === 0 ? n`jsonb_build_object()` : n`jsonb_build_object(${n.csv(e.present.map((e) => n`${I(e, n)}, ${F(t, e, n)}`))})`, N = (e, t, n) => t === void 0 || t.length === 0 ? n`` : n` ORDER BY ${n.csv(t.map((t) => t.direction === "desc" ? n`${F(e, t.column, n)} DESC` : n`${F(e, t.column, n)} ASC`))}`, Ea = (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`))}`, Da = (e, t, n) => {
860
- let r = n.sql, i = n.nextAlias(), a = Oa(i, t.table, t.children, n);
857
+ let l = e.branch.where === void 0 ? r`` : r` AND ${C(e.branch.where, r)}`, u = no(e, s, r), d = P(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${R(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${R(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : r`, ${ka(e.junction, s, r)} AS ${r(ma)}`;
858
+ 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 ${I(o, "id", r)} = ${I(s, i.targetKey, r)} WHERE ${I(s, i.sourceKey, r)} = ${I(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), '[]'::jsonb)`;
859
+ }, ka = (e, t, n) => e.present.length === 0 ? n`jsonb_build_object()` : n`jsonb_build_object(${n.csv(e.present.map((e) => n`${L(e, n)}, ${I(t, e, n)}`))})`, P = (e, t, n) => t === void 0 || t.length === 0 ? n`` : n` ORDER BY ${n.csv(t.map((t) => t.direction === "desc" ? n`${I(e, t.column, n)} DESC` : n`${I(e, t.column, n)} ASC`))}`, Aa = (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`))}`, ja = (e, t, n) => {
860
+ let r = n.sql, i = n.nextAlias(), a = Ma(i, t.table, t.children, n);
861
861
  if (a === null) return null;
862
- let o = e.predicate ? r` WHERE ${R(e.predicate, i, r)}` : r``, s = S(e).length > 0 ? r` ORDER BY ${r.csv(S(e).map((e) => e.direction === "desc" ? r`${F(i, e.column, r)} DESC` : r`${F(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${L(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${L(e.skip, r)}`;
862
+ let o = e.predicate ? r` WHERE ${z(e.predicate, i, r)}` : r``, s = S(e).length > 0 ? r` ORDER BY ${r.csv(S(e).map((e) => e.direction === "desc" ? r`${I(i, e.column, r)} DESC` : r`${I(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${R(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${R(e.skip, r)}`;
863
863
  return r`SELECT ${a} AS "__row" FROM ${r(t.table.tableName)} AS ${r(i)}${o}${s}${c}${l}`;
864
- }, Oa = (e, t, n, r, i) => {
864
+ }, Ma = (e, t, n, r, i) => {
865
865
  let a = r.sql, o = [];
866
- for (let n of Object.keys(t.fields)) o.push(a`${I(n, a)}, ${F(e, n, a)}`);
866
+ for (let n of Object.keys(t.fields)) {
867
+ let r = I(e, n, a), i = t.fields[n]?.type === "bigint" ? a`CAST(${r} AS TEXT)` : r;
868
+ o.push(a`${L(n, a)}, ${i}`);
869
+ }
867
870
  if (i !== void 0) {
868
- let e = ka(i.projection, i.source, a);
869
- o.push(a`${I("_junction", a)}, json_object(${e})`);
871
+ let e = Na(i.projection, i.source, a);
872
+ o.push(a`${L("_junction", a)}, json_object(${e})`);
870
873
  }
871
874
  for (let t of n) {
872
- let n = Na(t, e, r);
875
+ let n = La(t, e, r);
873
876
  if (n === null) return null;
874
- o.push(a`${I(t.relationName, a)}, ${n}`);
877
+ o.push(a`${L(t.relationName, a)}, ${n}`);
875
878
  }
876
879
  return a`json_object(${a.csv(o)})`;
877
- }, ka = (e, t, n) => e.present.length === 0 ? n`` : n.csv(e.present.map((e) => n`${I(e, n)}, ${F(t.alias, t.physical(e), n)}`)), Aa = (e, t, n) => e.present.length === 0 ? n`` : n`, ${n.csv(e.present.map((e) => n`${F(t, e, n)} AS ${n(la(e))}`))}`, ja = (e) => ({
880
+ }, Na = (e, t, n) => e.present.length === 0 ? n`` : n.csv(e.present.map((r) => {
881
+ let i = I(t.alias, t.physical(r), n), a = e.through.fields[r]?.type === "bigint" ? n.onDialectOrElse({
882
+ sqlite: () => n`CAST(${i} AS TEXT)`,
883
+ orElse: () => i
884
+ }) : i;
885
+ return n`${L(r, n)}, ${a}`;
886
+ })), Pa = (e, t, n) => e.present.length === 0 ? n`` : n`, ${n.csv(e.present.map((e) => n`${I(t, e, n)} AS ${n(pa(e))}`))}`, Fa = (e) => ({
878
887
  alias: e,
879
- physical: la
880
- }), Ma = (e) => ({
888
+ physical: pa
889
+ }), Ia = (e) => ({
881
890
  alias: e,
882
891
  physical: (e) => e
883
- }), Na = (e, t, n) => {
892
+ }), La = (e, t, n) => {
884
893
  switch (e.relation.kind) {
885
- case "one": return M(e) ? Fa(aa(e), t, n) : Pa(e, t, n);
886
- case "many": return Fa(e, t, n);
887
- case "manyToMany": return Ia(e, t, n);
894
+ case "one": return ca(e) ? za(la(e), t, n) : Ra(e, t, n);
895
+ case "many": return za(e, t, n);
896
+ case "manyToMany": return Ba(e, t, n);
888
897
  }
889
- }, Pa = (e, t, n) => {
890
- let r = n.sql, i = n.nextAlias(), a = Oa(i, e.target, e.children, n);
898
+ }, Ra = (e, t, n) => {
899
+ let r = n.sql, i = n.nextAlias(), a = Ma(i, e.target, e.children, n);
891
900
  if (a === null) return null;
892
- let o = e.fkSide === "source" ? r`${F(i, "id", r)} = ${F(t, e.foreignKey, r)}` : r`${F(i, e.foreignKey, r)} = ${F(t, e.sourceKey, r)}`;
901
+ let o = e.fkSide === "source" ? r`${I(i, "id", r)} = ${I(t, e.foreignKey, r)}` : r`${I(i, e.foreignKey, r)} = ${I(t, e.sourceKey, r)}`;
893
902
  return r`(SELECT ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o} LIMIT 1)`;
894
- }, Fa = (e, t, n) => {
895
- let r = n.sql, i = n.nextAlias(), a = Oa(i, e.target, e.children, n);
903
+ }, za = (e, t, n) => {
904
+ let r = n.sql, i = n.nextAlias(), a = Ma(i, e.target, e.children, n);
896
905
  if (a === null) return null;
897
- let o = r`${F(void 0, e.foreignKey, r)} = ${F(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${p(B(e.branch.where), r)}`, c = Ea(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${L(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${L(e.branch.offset, r)}`;
906
+ let o = r`${I(void 0, e.foreignKey, r)} = ${I(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${C(B(e.branch.where), r)}`, c = Aa(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${R(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${R(e.branch.offset, r)}`;
898
907
  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('[]'))`;
899
- }, Ia = (e, t, n) => {
900
- let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = Oa(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
908
+ }, Ba = (e, t, n) => {
909
+ let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = Ma(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
901
910
  projection: e.junction,
902
- source: ja(o)
911
+ source: Fa(o)
903
912
  });
904
913
  if (c === null) return null;
905
- let l = e.branch.where === void 0 ? r`` : r` AND ${p(B(e.branch.where), r)}`, u = z(e, s, r, !0), d = N(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${L(e.branch.limit, r)}`, m = e.branch.offset === void 0 ? r`` : r` OFFSET ${L(e.branch.offset, r)}`, h = e.junction === void 0 ? r`` : Aa(e.junction, s, r);
906
- return r`COALESCE((SELECT json_group_array(${c}) FROM (SELECT ${r(o)}.*${h} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${F(o, "id", r)} = ${F(s, i.targetKey, r)} WHERE ${F(s, i.sourceKey, r)} = ${F(t, "id", r)}${u}${l}${d}${f}${m}) AS ${r(o)}), json('[]'))`;
907
- }, La = (e, t, n) => {
908
- let r = n.sql, i = n.nextAlias(), a = P(i, t.table, t.children, n);
914
+ let l = e.branch.where === void 0 ? r`` : r` AND ${C(B(e.branch.where), r)}`, u = no(e, s, r, !0), d = P(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${R(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${R(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : Pa(e.junction, s, r);
915
+ 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 ${I(o, "id", r)} = ${I(s, i.targetKey, r)} WHERE ${I(s, i.sourceKey, r)} = ${I(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), json('[]'))`;
916
+ }, Va = (e, t, n) => {
917
+ let r = n.sql, i = n.nextAlias(), a = F(i, t.table, t.children, n);
909
918
  if (a === null) return null;
910
- let o = e.predicate ? r` WHERE ${R(e.predicate, i, r)}` : r``, s = S(e).length > 0 ? r` ORDER BY ${r.csv(S(e).map((e) => e.direction === "desc" ? r`${F(i, e.column, r)} DESC` : r`${F(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${L(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${L(e.skip, r)}`;
919
+ let o = e.predicate ? r` WHERE ${z(e.predicate, i, r)}` : r``, s = S(e).length > 0 ? r` ORDER BY ${r.csv(S(e).map((e) => e.direction === "desc" ? r`${I(i, e.column, r)} DESC` : r`${I(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${R(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${R(e.skip, r)}`;
911
920
  return r`SELECT ${a} AS \`__row\` FROM ${r(t.table.tableName)} AS ${r(i)}${o}${s}${c}${l}`;
912
- }, P = (e, t, n, r, i) => {
921
+ }, F = (e, t, n, r, i) => {
913
922
  let a = r.sql, o = [];
914
- for (let n of Object.keys(t.fields)) o.push(a`${I(n, a)}, ${F(e, n, a)}`);
923
+ for (let n of Object.keys(t.fields)) o.push(a`${L(n, a)}, ${I(e, n, a)}`);
915
924
  if (i !== void 0) {
916
- let e = ka(i.projection, i.source, a);
917
- o.push(a`${I("_junction", a)}, JSON_OBJECT(${e})`);
925
+ let e = Na(i.projection, i.source, a);
926
+ o.push(a`${L("_junction", a)}, JSON_OBJECT(${e})`);
918
927
  }
919
928
  for (let t of n) {
920
- let n = Ra(t, e, r);
929
+ let n = Ha(t, e, r);
921
930
  if (n === null) return null;
922
- o.push(a`${I(t.relationName, a)}, ${n}`);
931
+ o.push(a`${L(t.relationName, a)}, ${n}`);
923
932
  }
924
933
  return a`JSON_OBJECT(${a.csv(o)})`;
925
- }, Ra = (e, t, n) => {
934
+ }, Ha = (e, t, n) => {
926
935
  switch (e.relation.kind) {
927
936
  case "one":
928
- if (M(e)) {
929
- let r = aa(e);
930
- return n.dialect === "mariadb" ? Ha(r, t, n) : Ba(r, t, n);
937
+ if (ca(e)) {
938
+ let r = la(e);
939
+ return n.dialect === "mariadb" ? Ka(r, t, n) : Wa(r, t, n);
931
940
  }
932
- return za(e, t, n);
933
- case "many": return n.dialect === "mariadb" ? Ha(e, t, n) : Ba(e, t, n);
934
- case "manyToMany": return n.dialect === "mariadb" ? Ua(e, t, n) : Va(e, t, n);
941
+ return Ua(e, t, n);
942
+ case "many": return n.dialect === "mariadb" ? Ka(e, t, n) : Wa(e, t, n);
943
+ case "manyToMany": return n.dialect === "mariadb" ? qa(e, t, n) : Ga(e, t, n);
935
944
  }
936
- }, za = (e, t, n) => {
937
- let r = n.sql, i = n.nextAlias(), a = P(i, e.target, e.children, n);
945
+ }, Ua = (e, t, n) => {
946
+ let r = n.sql, i = n.nextAlias(), a = F(i, e.target, e.children, n);
938
947
  if (a === null) return null;
939
- let o = e.fkSide === "source" ? r`${F(i, "id", r)} = ${F(t, e.foreignKey, r)}` : r`${F(i, e.foreignKey, r)} = ${F(t, e.sourceKey, r)}`;
948
+ let o = e.fkSide === "source" ? r`${I(i, "id", r)} = ${I(t, e.foreignKey, r)}` : r`${I(i, e.foreignKey, r)} = ${I(t, e.sourceKey, r)}`;
940
949
  return r`(SELECT ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o} LIMIT 1)`;
941
- }, Ba = (e, t, n) => {
942
- let r = n.sql, i = n.nextAlias(), a = P(i, e.target, e.children, n);
950
+ }, Wa = (e, t, n) => {
951
+ let r = n.sql, i = n.nextAlias(), a = F(i, e.target, e.children, n);
943
952
  if (a === null) return null;
944
- let o = r`${F(void 0, e.foreignKey, r)} = ${F(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${p(B(e.branch.where), r)}`, c = Ea(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${L(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${L(e.branch.offset, r)}`;
953
+ let o = r`${I(void 0, e.foreignKey, r)} = ${I(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${C(B(e.branch.where), r)}`, c = Aa(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${R(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${R(e.branch.offset, r)}`;
945
954
  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())`;
946
- }, Va = (e, t, n) => {
947
- let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = P(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
955
+ }, Ga = (e, t, n) => {
956
+ let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = F(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
948
957
  projection: e.junction,
949
- source: ja(o)
958
+ source: Fa(o)
950
959
  });
951
960
  if (c === null) return null;
952
- let l = e.branch.where === void 0 ? r`` : r` AND ${p(B(e.branch.where), r)}`, u = z(e, s, r, !0), d = N(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${L(e.branch.limit, r)}`, m = e.branch.offset === void 0 ? r`` : r` OFFSET ${L(e.branch.offset, r)}`, h = e.junction === void 0 ? r`` : Aa(e.junction, s, r);
953
- return r`COALESCE((SELECT JSON_ARRAYAGG(${c}) FROM (SELECT ${r(o)}.*${h} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${F(o, "id", r)} = ${F(s, i.targetKey, r)} WHERE ${F(s, i.sourceKey, r)} = ${F(t, "id", r)}${u}${l}${d}${f}${m}) AS ${r(o)}), JSON_ARRAY())`;
954
- }, Ha = (e, t, n) => {
955
- let r = n.sql, i = n.nextAlias(), a = P(i, e.target, e.children, n);
961
+ let l = e.branch.where === void 0 ? r`` : r` AND ${C(B(e.branch.where), r)}`, u = no(e, s, r, !0), d = P(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${R(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${R(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : Pa(e.junction, s, r);
962
+ 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 ${I(o, "id", r)} = ${I(s, i.targetKey, r)} WHERE ${I(s, i.sourceKey, r)} = ${I(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), JSON_ARRAY())`;
963
+ }, Ka = (e, t, n) => {
964
+ let r = n.sql, i = n.nextAlias(), a = F(i, e.target, e.children, n);
956
965
  if (a === null) return null;
957
- let o = r`${F(i, e.foreignKey, r)} = ${F(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${p(B(e.branch.where), r)}`, c = e.branch.orderBy ?? [];
958
- 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`${F(i, e.column, r)} DESC` : r`${F(i, e.column, r)} ASC`))}` : r``}) FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o}${s}), JSON_ARRAY())`;
959
- 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 ${F(i, "rn", r)} > ${L(d, r)} AND ${F(i, "rn", r)} <= ${L(d + u, r)}` : u === void 0 ? r` AND ${F(i, "rn", r)} > ${L(d, r)}` : r` AND ${F(i, "rn", r)} <= ${L(u, r)}`;
960
- return r`COALESCE((SELECT JSON_ARRAYAGG(${a} ORDER BY ${F(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())`;
961
- }, Ua = (e, t, n) => {
966
+ let o = r`${I(i, e.foreignKey, r)} = ${I(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${C(B(e.branch.where), r)}`, c = e.branch.orderBy ?? [];
967
+ 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`${I(i, e.column, r)} DESC` : r`${I(i, e.column, r)} ASC`))}` : r``}) FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o}${s}), JSON_ARRAY())`;
968
+ 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 ${I(i, "rn", r)} > ${R(d, r)} AND ${I(i, "rn", r)} <= ${R(d + u, r)}` : u === void 0 ? r` AND ${I(i, "rn", r)} > ${R(d, r)}` : r` AND ${I(i, "rn", r)} <= ${R(u, r)}`;
969
+ return r`COALESCE((SELECT JSON_ARRAYAGG(${a} ORDER BY ${I(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())`;
970
+ }, qa = (e, t, n) => {
962
971
  let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = (t) => e.junction === void 0 ? void 0 : {
963
972
  projection: e.junction,
964
973
  source: t
965
- }, l = r`${F(s, i.sourceKey, r)} = ${F(t, "id", r)}`, u = r`${F(o, "id", r)} = ${F(s, i.targetKey, r)}`, d = e.branch.where === void 0 ? r`` : r` AND ${p(B(e.branch.where), r)}`, f = z(e, s, r, !0), m = e.branch.orderBy ?? [];
974
+ }, l = r`${I(s, i.sourceKey, r)} = ${I(t, "id", r)}`, u = r`${I(o, "id", r)} = ${I(s, i.targetKey, r)}`, d = e.branch.where === void 0 ? r`` : r` AND ${C(B(e.branch.where), r)}`, f = no(e, s, r, !0), p = e.branch.orderBy ?? [];
966
975
  if (e.branch.limit === void 0 && e.branch.offset === void 0) {
967
- let t = P(o, e.target, e.children, n, c(Ma(s)));
968
- return t === null ? null : r`COALESCE((SELECT JSON_ARRAYAGG(${t}${m.length > 0 ? r` ORDER BY ${r.csv(m.map((e) => e.direction === "desc" ? r`${F(o, e.column, r)} DESC` : r`${F(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())`;
976
+ let t = F(o, e.target, e.children, n, c(Ia(s)));
977
+ 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`${I(o, e.column, r)} DESC` : r`${I(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())`;
969
978
  }
970
- let h = m.length > 0 ? r` ORDER BY ${r.csv(m.map((e) => e.direction === "desc" ? r`${F(o, e.column, r)} DESC` : r`${F(o, e.column, r)} ASC`))}` : r` ORDER BY ${F(o, "id", r)}`, g = e.branch.limit, _ = e.branch.offset, v = g !== void 0 && _ !== void 0 ? r` AND ${F(o, "rn", r)} > ${L(_, r)} AND ${F(o, "rn", r)} <= ${L(_ + g, r)}` : g === void 0 ? r` AND ${F(o, "rn", r)} > ${L(_, r)}` : r` AND ${F(o, "rn", r)} <= ${L(g, r)}`, ee = e.branch.onJunction === void 0 ? r`` : r` WHERE ${R(B(e.branch.onJunction), s, r)}`, te = P(o, e.target, e.children, n, c(ja(o)));
971
- if (te === null) return null;
972
- let ne = e.junction === void 0 ? r`` : Aa(e.junction, s, r);
973
- return r`COALESCE((SELECT JSON_ARRAYAGG(${te} ORDER BY ${F(o, "rn", r)}) FROM (SELECT ${r(o)}.*${ne}, ${F(s, i.sourceKey, r)} AS ${r(`__src_${i.sourceKey}`)}, ROW_NUMBER() OVER (PARTITION BY ${F(s, i.sourceKey, r)}${h}) 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 ${F(o, `__src_${i.sourceKey}`, r)} = ${F(t, "id", r)}${d}${v}), JSON_ARRAY())`;
974
- }, Wa = (e, t, n) => {
975
- let r = n.sql, i = n.nextAlias(), a = Ga(i, t.table, t.children, n);
979
+ let m = p.length > 0 ? r` ORDER BY ${r.csv(p.map((e) => e.direction === "desc" ? r`${I(o, e.column, r)} DESC` : r`${I(o, e.column, r)} ASC`))}` : r` ORDER BY ${I(o, "id", r)}`, h = e.branch.limit, g = e.branch.offset, _ = h !== void 0 && g !== void 0 ? r` AND ${I(o, "rn", r)} > ${R(g, r)} AND ${I(o, "rn", r)} <= ${R(g + h, r)}` : h === void 0 ? r` AND ${I(o, "rn", r)} > ${R(g, r)}` : r` AND ${I(o, "rn", r)} <= ${R(h, r)}`, v = e.branch.onJunction === void 0 ? r`` : r` WHERE ${z(B(e.branch.onJunction), s, r)}`, ee = F(o, e.target, e.children, n, c(Fa(o)));
980
+ if (ee === null) return null;
981
+ let te = e.junction === void 0 ? r`` : Pa(e.junction, s, r);
982
+ return r`COALESCE((SELECT JSON_ARRAYAGG(${ee} ORDER BY ${I(o, "rn", r)}) FROM (SELECT ${r(o)}.*${te}, ${I(s, i.sourceKey, r)} AS ${r(`__src_${i.sourceKey}`)}, ROW_NUMBER() OVER (PARTITION BY ${I(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}${v}) AS ${r(o)} WHERE ${I(o, `__src_${i.sourceKey}`, r)} = ${I(t, "id", r)}${d}${_}), JSON_ARRAY())`;
983
+ }, Ja = (e, t, n) => {
984
+ let r = n.sql, i = n.nextAlias(), a = Ya(i, t.table, t.children, n);
976
985
  if (a === null) return null;
977
- let o = e.predicate ? r` WHERE ${R(e.predicate, i, r)}` : r``, s = S(e).length > 0 ? r` ORDER BY ${r.csv(S(e).map((e) => e.direction === "desc" ? r`${F(i, e.column, r)} DESC` : r`${F(i, e.column, r)} ASC`))}` : r``, c = r``, l = r``;
986
+ let o = e.predicate ? r` WHERE ${z(e.predicate, i, r)}` : r``, s = S(e).length > 0 ? r` ORDER BY ${r.csv(S(e).map((e) => e.direction === "desc" ? r`${I(i, e.column, r)} DESC` : r`${I(i, e.column, r)} ASC`))}` : r``, c = r``, l = r``;
978
987
  if (e.skip !== void 0) {
979
988
  let t = S(e).length > 0 ? s : r` ORDER BY (SELECT NULL)`;
980
- l = e.take === void 0 ? r`${t} OFFSET ${L(e.skip, r)} ROWS` : r`${t} OFFSET ${L(e.skip, r)} ROWS FETCH NEXT ${L(e.take, r)} ROWS ONLY`;
981
- } else e.take !== void 0 && (c = r`TOP ${L(e.take, r)} `);
989
+ l = e.take === void 0 ? r`${t} OFFSET ${R(e.skip, r)} ROWS` : r`${t} OFFSET ${R(e.skip, r)} ROWS FETCH NEXT ${R(e.take, r)} ROWS ONLY`;
990
+ } else e.take !== void 0 && (c = r`TOP ${R(e.take, r)} `);
982
991
  let u = e.skip === void 0 ? s : r``;
983
992
  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}`;
984
- }, Ga = (e, t, n, r, i) => {
993
+ }, Ya = (e, t, n, r, i) => {
985
994
  let a = r.sql, o = [];
986
- for (let n of Object.keys(t.fields)) o.push(a`${F(e, n, a)} AS ${a(n)}`);
987
- if (i !== void 0) for (let e of i.projection.present) o.push(a`${F(i.source.alias, i.source.physical(e), a)} AS ${Ka(`_junction.${e}`, a)}`);
995
+ for (let n of Object.keys(t.fields)) o.push(a`${I(e, n, a)} AS ${a(n)}`);
996
+ if (i !== void 0) for (let e of i.projection.present) o.push(a`${I(i.source.alias, i.source.physical(e), a)} AS ${Xa(`_junction.${e}`, a)}`);
988
997
  for (let t of n) {
989
- let n = qa(t, e, r);
998
+ let n = Za(t, e, r);
990
999
  if (n === null) return null;
991
1000
  o.push(n);
992
1001
  }
993
1002
  return a.csv(o);
994
- }, Ka = (e, t) => t.unsafe(`[${e.replace(/]/g, "]]")}]`), qa = (e, t, n) => {
1003
+ }, Xa = (e, t) => t.unsafe(`[${e.replace(/]/g, "]]")}]`), Za = (e, t, n) => {
995
1004
  switch (e.relation.kind) {
996
- case "one": return M(e) ? Xa(aa(e), t, n) : Ja(e, t, n);
997
- case "many": return Xa(e, t, n);
998
- case "manyToMany": return Za(e, t, n);
1005
+ case "one": return ca(e) ? eo(la(e), t, n) : Qa(e, t, n);
1006
+ case "many": return eo(e, t, n);
1007
+ case "manyToMany": return to(e, t, n);
999
1008
  }
1000
- }, Ja = (e, t, n) => {
1001
- let r = n.sql, i = n.nextAlias(), a = Ga(i, e.target, e.children, n);
1009
+ }, Qa = (e, t, n) => {
1010
+ let r = n.sql, i = n.nextAlias(), a = Ya(i, e.target, e.children, n);
1002
1011
  if (a === null) return null;
1003
- let o = e.fkSide === "source" ? r`${F(i, "id", r)} = ${F(t, e.foreignKey, r)}` : r`${F(i, e.foreignKey, r)} = ${F(t, e.sourceKey, r)}`;
1012
+ let o = e.fkSide === "source" ? r`${I(i, "id", r)} = ${I(t, e.foreignKey, r)}` : r`${I(i, e.foreignKey, r)} = ${I(t, e.sourceKey, r)}`;
1004
1013
  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)}`;
1005
- }, Ya = (e, t, n) => {
1014
+ }, $a = (e, t, n) => {
1006
1015
  if (e.offset !== void 0) {
1007
- let r = e.orderBy && e.orderBy.length > 0 ? t : n` ORDER BY (SELECT NULL)`, i = e.limit === void 0 ? n`${r} OFFSET ${L(e.offset, n)} ROWS` : n`${r} OFFSET ${L(e.offset, n)} ROWS FETCH NEXT ${L(e.limit, n)} ROWS ONLY`;
1016
+ let r = e.orderBy && e.orderBy.length > 0 ? t : n` ORDER BY (SELECT NULL)`, i = e.limit === void 0 ? n`${r} OFFSET ${R(e.offset, n)} ROWS` : n`${r} OFFSET ${R(e.offset, n)} ROWS FETCH NEXT ${R(e.limit, n)} ROWS ONLY`;
1008
1017
  return {
1009
1018
  top: n``,
1010
1019
  pagination: i,
@@ -1012,36 +1021,36 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
1012
1021
  };
1013
1022
  }
1014
1023
  return {
1015
- top: e.limit === void 0 ? n`` : n`TOP ${L(e.limit, n)} `,
1024
+ top: e.limit === void 0 ? n`` : n`TOP ${R(e.limit, n)} `,
1016
1025
  pagination: n``,
1017
1026
  finalOrder: t
1018
1027
  };
1019
- }, Xa = (e, t, n) => {
1020
- let r = n.sql, i = n.nextAlias(), a = Ga(i, e.target, e.children, n);
1028
+ }, eo = (e, t, n) => {
1029
+ let r = n.sql, i = n.nextAlias(), a = Ya(i, e.target, e.children, n);
1021
1030
  if (a === null) return null;
1022
- let o = e.branch.where === void 0 ? r`` : r` AND ${R(e.branch.where, i, r)}`, s = N(i, e.branch.orderBy, r), { top: c, pagination: l, finalOrder: u } = Ya(e.branch, s, r);
1023
- return r`ISNULL(JSON_QUERY((SELECT ${c}${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${F(i, e.foreignKey, r)} = ${F(t, e.sourceKey, r)}${o}${u}${l} FOR JSON PATH, INCLUDE_NULL_VALUES)), JSON_QUERY('[]')) AS ${r(e.relationName)}`;
1024
- }, Za = (e, t, n) => {
1025
- let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = Ga(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1031
+ let o = e.branch.where === void 0 ? r`` : r` AND ${z(e.branch.where, i, r)}`, s = P(i, e.branch.orderBy, r), { top: c, pagination: l, finalOrder: u } = $a(e.branch, s, r);
1032
+ return r`ISNULL(JSON_QUERY((SELECT ${c}${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${I(i, e.foreignKey, r)} = ${I(t, e.sourceKey, r)}${o}${u}${l} FOR JSON PATH, INCLUDE_NULL_VALUES)), JSON_QUERY('[]')) AS ${r(e.relationName)}`;
1033
+ }, to = (e, t, n) => {
1034
+ let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = Ya(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1026
1035
  projection: e.junction,
1027
- source: Ma(s)
1036
+ source: Ia(s)
1028
1037
  });
1029
1038
  if (c === null) return null;
1030
- let l = e.branch.where === void 0 ? r`` : r` AND ${R(e.branch.where, o, r)}`, u = z(e, s, r), d = N(o, e.branch.orderBy, r), { top: f, pagination: p, finalOrder: m } = Ya(e.branch, d, r);
1031
- 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 ${F(o, "id", r)} = ${F(s, i.targetKey, r)} WHERE ${F(s, i.sourceKey, r)} = ${F(t, "id", r)}${u}${l}${m}${p} FOR JSON PATH, INCLUDE_NULL_VALUES)), JSON_QUERY('[]')) AS ${r(e.relationName)}`;
1032
- }, F = (e, t, n) => e === void 0 ? n`${n(t)}` : n`${n(e)}.${n(t)}`, I = (e, t) => t.unsafe(`'${e.replace(/'/g, "''")}'`), L = (e, t) => {
1039
+ let l = e.branch.where === void 0 ? r`` : r` AND ${z(e.branch.where, o, r)}`, u = no(e, s, r), d = P(o, e.branch.orderBy, r), { top: f, pagination: p, finalOrder: m } = $a(e.branch, d, r);
1040
+ 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 ${I(o, "id", r)} = ${I(s, i.targetKey, r)} WHERE ${I(s, i.sourceKey, r)} = ${I(t, "id", r)}${u}${l}${m}${p} FOR JSON PATH, INCLUDE_NULL_VALUES)), JSON_QUERY('[]')) AS ${r(e.relationName)}`;
1041
+ }, I = (e, t, n) => e === void 0 ? n`${n(t)}` : n`${n(e)}.${n(t)}`, L = (e, t) => t.unsafe(`'${e.replace(/'/g, "''")}'`), R = (e, t) => {
1033
1042
  if (!Number.isFinite(e) || !Number.isInteger(e) || e < 0) throw x(`literalInt: expected non-negative integer, got ${e}`);
1034
1043
  return t.unsafe(String(e));
1035
- }, R = (e, t, n) => {
1036
- let r = Qa(e, t);
1037
- return p(r, n);
1038
- }, z = (e, t, n, r = !1) => {
1044
+ }, z = (e, t, n) => {
1045
+ let r = ro(e, t);
1046
+ return C(r, n);
1047
+ }, no = (e, t, n, r = !1) => {
1039
1048
  let i = e.branch.onJunction;
1040
- return i === void 0 ? n`` : n` AND ${R(r ? B(i) : i, t, n)}`;
1041
- }, Qa = (e, t) => {
1042
- if ("not" in e) return { not: Qa(e.not, t) };
1043
- if ("and" in e) return { and: e.and.map((e) => Qa(e, t)) };
1044
- if ("or" in e) return { or: e.or.map((e) => Qa(e, t)) };
1049
+ return i === void 0 ? n`` : n` AND ${z(r ? B(i) : i, t, n)}`;
1050
+ }, ro = (e, t) => {
1051
+ if ("not" in e) return { not: ro(e.not, t) };
1052
+ if ("and" in e) return { and: e.and.map((e) => ro(e, t)) };
1053
+ if ("or" in e) return { or: e.or.map((e) => ro(e, t)) };
1045
1054
  if (e.op === "subquery-in" || e.op === "subquery-not-in") {
1046
1055
  let n = e;
1047
1056
  return {
@@ -1053,7 +1062,8 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
1053
1062
  let n = e;
1054
1063
  return {
1055
1064
  ...n,
1056
- column: `${t}.${n.column}`
1065
+ column: `${t}.${n.column}`,
1066
+ ...gr(n.value) ? { value: Ye(`${t}.${n.value.column}`) } : {}
1057
1067
  };
1058
1068
  }, B = (e) => {
1059
1069
  if ("not" in e) return { not: B(e.not) };
@@ -1063,47 +1073,47 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
1063
1073
  let t = e;
1064
1074
  return {
1065
1075
  ...t,
1066
- value: $a(t.value)
1076
+ value: De(t.value)
1067
1077
  };
1068
- }, $a = (e) => e == null ? e : e instanceof Date ? e.toISOString() : typeof e == "boolean" ? +!!e : Array.isArray(e) ? e.map((e) => $a(e)) : e, eo = Symbol.for("@voltro/database/coreTablesRegistry"), to = globalThis, no = to[eo] ?? (to[eo] = {}), ro = (e) => {
1069
- e.actors !== void 0 && (no.actors = e.actors), e.tenants !== void 0 && (no.tenants = e.tenants);
1070
- }, io = (e, t) => () => {
1078
+ }, io = Symbol.for("@voltro/database/coreTablesRegistry"), ao = globalThis, oo = ao[io] ?? (ao[io] = {}), so = (e) => {
1079
+ e.actors !== void 0 && (oo.actors = e.actors), e.tenants !== void 0 && (oo.tenants = e.tenants);
1080
+ }, co = (e, t) => () => {
1071
1081
  let n = e();
1072
1082
  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`);
1073
1083
  return n();
1074
- }, ao = () => io(() => no.actors, "actors"), oo = () => io(() => no.tenants, "tenants"), so = h("actors", {
1075
- id: f(),
1076
- kind: y().oneOf([
1084
+ }, lo = () => co(() => oo.actors, "actors"), uo = () => co(() => oo.tenants, "tenants"), fo = ke("actors", {
1085
+ id: y(),
1086
+ kind: l().oneOf([
1077
1087
  "user",
1078
1088
  "serviceAccount",
1079
1089
  "apiKey",
1080
1090
  "system"
1081
1091
  ]).safe(),
1082
- displayName: y().nullable().sensitive("fullName"),
1092
+ displayName: l().nullable().sensitive("fullName"),
1083
1093
  createdAt: b().default("now")
1084
- }), co = (e, t) => ({
1094
+ }), po = (e, t) => ({
1085
1095
  ...t,
1086
1096
  ...e,
1087
1097
  origin: e.origin ?? "injected"
1088
- }), lo = (e, t, n = {}) => ({
1098
+ }), mo = (e, t, n = {}) => ({
1089
1099
  table: e,
1090
1100
  op: "insert",
1091
1101
  old: null,
1092
1102
  new: t,
1093
1103
  ...n
1094
- }), uo = (e, t, n, r = {}) => ({
1104
+ }), ho = (e, t, n, r = {}) => ({
1095
1105
  table: e,
1096
1106
  op: "update",
1097
1107
  old: t,
1098
1108
  new: n,
1099
1109
  ...r
1100
- }), fo = (e, t, n = {}) => ({
1110
+ }), go = (e, t, n = {}) => ({
1101
1111
  table: e,
1102
1112
  op: "delete",
1103
1113
  old: t,
1104
1114
  new: null,
1105
1115
  ...n
1106
- }), po = (e, t, n = {}) => {
1116
+ }), _o = (e, t, n = {}) => {
1107
1117
  let { at: r = "2026-01-01T00:00:00.000Z", column: i = "deletedAt", ...a } = n;
1108
1118
  return {
1109
1119
  table: e,
@@ -1118,13 +1128,13 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
1118
1128
  },
1119
1129
  ...a
1120
1130
  };
1121
- }, mo = (e) => e == null ? "null" : e instanceof Date ? JSON.stringify(e.toISOString()) : typeof e == "bigint" ? JSON.stringify(e.toString()) : Array.isArray(e) ? `[${e.map(mo).join(",")}]` : typeof e == "object" ? `{${Object.entries(e).filter(([, e]) => e !== void 0).sort(([e], [t]) => e < t ? -1 : +(e > t)).map(([e, t]) => `${JSON.stringify(e)}:${mo(t)}`).join(",")}}` : JSON.stringify(e) ?? "null", ho = (e) => Dr("sha256").update([
1131
+ }, vo = (e) => e == null ? "null" : e instanceof Date ? JSON.stringify(e.toISOString()) : typeof e == "bigint" ? JSON.stringify(e.toString()) : Array.isArray(e) ? `[${e.map(vo).join(",")}]` : typeof e == "object" ? `{${Object.entries(e).filter(([, e]) => e !== void 0).sort(([e], [t]) => e < t ? -1 : +(e > t)).map(([e, t]) => `${JSON.stringify(e)}:${vo(t)}`).join(",")}}` : JSON.stringify(e) ?? "null", yo = (e) => jr("sha256").update([
1122
1132
  e.pipe,
1123
1133
  e.op,
1124
1134
  e.key,
1125
- mo(e.next),
1126
- mo(e.prev)
1127
- ].join("\0")).digest("hex").slice(0, 32), go = (e, t) => `${e}:${t}`, _o = (e) => {
1135
+ vo(e.next),
1136
+ vo(e.prev)
1137
+ ].join("\0")).digest("hex").slice(0, 32), bo = (e, t) => `${e}:${t}`, xo = (e) => {
1128
1138
  let t = e.lastIndexOf(":");
1129
1139
  if (t <= 0) return null;
1130
1140
  let n = Number(e.slice(t + 1));
@@ -1132,7 +1142,7 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
1132
1142
  digest: e.slice(0, t),
1133
1143
  occurrence: n
1134
1144
  };
1135
- }, vo = class {
1145
+ }, So = class {
1136
1146
  #e = /* @__PURE__ */ new Map();
1137
1147
  #t;
1138
1148
  #n;
@@ -1154,7 +1164,7 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
1154
1164
  }
1155
1165
  seedFromChangeKeys(e, t) {
1156
1166
  for (let n of e) {
1157
- let e = _o(n);
1167
+ let e = xo(n);
1158
1168
  if (e === null) continue;
1159
1169
  let r = this.#e.get(e.digest), i = Math.max(r?.count ?? 0, e.occurrence + 1);
1160
1170
  this.#e.set(e.digest, {
@@ -1175,70 +1185,70 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
1175
1185
  this.#e.delete(e.value);
1176
1186
  }
1177
1187
  }
1178
- }, yo = "VOLTRO_CHANGE_CLAIMS_TTL_HOURS", bo = 1, xo = (e = process.env) => {
1179
- let t = Number(e[yo]);
1188
+ }, Co = "VOLTRO_CHANGE_CLAIMS_TTL_HOURS", wo = 1, To = (e = process.env) => {
1189
+ let t = Number(e[Co]);
1180
1190
  return (Number.isFinite(t) && t > 0 ? t : 1) * 2 * 36e5;
1181
- }, V = new Or(), So = (e, t) => V.run(e, t), Co = () => V.getStore(), wo = (e) => {
1182
- let t = e ?? V.getStore();
1191
+ }, Eo = new Mr(), Do = (e, t) => Eo.run(e, t), Oo = () => Eo.getStore(), ko = (e) => {
1192
+ let t = e ?? Eo.getStore();
1183
1193
  return t === void 0 ? {} : {
1184
1194
  ...t.traceId === void 0 ? {} : { traceId: t.traceId },
1185
1195
  ...t.subjectId === void 0 ? {} : { subjectId: t.subjectId },
1186
1196
  ...t.procedure === void 0 ? {} : { procedure: t.procedure },
1187
1197
  ...t.via === void 0 ? {} : { via: t.via }
1188
1198
  };
1189
- }, To = (e) => {
1190
- let t = V.getStore();
1191
- return t === void 0 ? e(void 0) : V.run(t, () => e(t));
1192
- }, Eo = 3e4, Do = 1e4, H = /* @__PURE__ */ new Map(), U = 0, Oo = (e, t, n) => `${e}\u0000${t}\u0000${String(n)}`, ko = (e) => {
1193
- for (let [t, n] of H) {
1194
- let r = n.filter((t) => e - t.at < Eo);
1195
- U -= n.length - r.length, r.length === 0 ? H.delete(t) : r.length !== n.length && H.set(t, r);
1196
- }
1197
- }, Ao = (e, t) => {
1199
+ }, Ao = (e) => {
1200
+ let t = Eo.getStore();
1201
+ return t === void 0 ? e(void 0) : Eo.run(t, () => e(t));
1202
+ }, jo = 3e4, Mo = 1e4, V = /* @__PURE__ */ new Map(), H = 0, No = (e, t, n) => `${e}\u0000${t}\u0000${String(n)}`, Po = (e) => {
1203
+ for (let [t, n] of V) {
1204
+ let r = n.filter((t) => e - t.at < jo);
1205
+ H -= n.length - r.length, r.length === 0 ? V.delete(t) : r.length !== n.length && V.set(t, r);
1206
+ }
1207
+ }, Fo = (e, t) => {
1198
1208
  if (t.traceId === void 0 && t.subjectId === void 0 && t.procedure === void 0) return;
1199
1209
  let n = Date.now();
1200
- if (U >= Do && ko(n), U >= Do) return;
1201
- let r = H.get(e);
1202
- r === void 0 ? H.set(e, [{
1210
+ if (H >= Mo && Po(n), H >= Mo) return;
1211
+ let r = V.get(e);
1212
+ r === void 0 ? V.set(e, [{
1203
1213
  attribution: t,
1204
1214
  at: n
1205
1215
  }]) : r.push({
1206
1216
  attribution: t,
1207
1217
  at: n
1208
- }), U += 1;
1209
- }, jo = (e) => {
1210
- let t = H.get(e);
1218
+ }), H += 1;
1219
+ }, Io = (e) => {
1220
+ let t = V.get(e);
1211
1221
  if (t === void 0 || t.length === 0) return;
1212
1222
  let n = t.shift();
1213
- if (--U, t.length === 0 && H.delete(e), !(Date.now() - n.at >= Eo)) return n.attribution;
1214
- }, Mo = (e) => (H.get(e)?.length ?? 0) > 0, W = /* @__PURE__ */ new Map(), G = /* @__PURE__ */ new Map(), K = /* @__PURE__ */ new Map(), No = 250, Po = (e) => {
1215
- let t = G.get(e);
1223
+ if (--H, t.length === 0 && V.delete(e), !(Date.now() - n.at >= jo)) return n.attribution;
1224
+ }, Lo = (e) => (V.get(e)?.length ?? 0) > 0, U = /* @__PURE__ */ new Map(), W = /* @__PURE__ */ new Map(), G = /* @__PURE__ */ new Map(), Ro = 250, zo = (e) => {
1225
+ let t = W.get(e);
1216
1226
  if (t === void 0) return;
1217
- G.delete(e);
1218
- let n = K.get(e);
1219
- n !== void 0 && (clearTimeout(n), K.delete(e));
1227
+ W.delete(e);
1228
+ let n = G.get(e);
1229
+ n !== void 0 && (clearTimeout(n), G.delete(e));
1220
1230
  for (let e of t) e();
1221
- }, Fo = (e) => {
1222
- W.set(e, (W.get(e) ?? 0) + 1);
1223
- }, Io = (e) => {
1224
- let t = (W.get(e) ?? 0) - 1;
1231
+ }, Bo = (e) => {
1232
+ U.set(e, (U.get(e) ?? 0) + 1);
1233
+ }, Vo = (e) => {
1234
+ let t = (U.get(e) ?? 0) - 1;
1225
1235
  if (t > 0) {
1226
- W.set(e, t);
1236
+ U.set(e, t);
1227
1237
  return;
1228
1238
  }
1229
- W.delete(e), Po(e);
1230
- }, Lo = (e, t, n, r) => {
1231
- let i = n == null ? void 0 : Oo(e, t, n), a = () => r(i === void 0 ? void 0 : jo(i));
1239
+ U.delete(e), zo(e);
1240
+ }, Ho = (e, t, n, r) => {
1241
+ let i = n == null ? void 0 : No(e, t, n), a = () => r(i === void 0 ? void 0 : Io(i));
1232
1242
  if (i === void 0) {
1233
1243
  a();
1234
1244
  return;
1235
1245
  }
1236
- if (Mo(i)) {
1246
+ if (Lo(i)) {
1237
1247
  a();
1238
1248
  return;
1239
1249
  }
1240
- let o = G.get(e);
1241
- if (o === void 0 && (W.get(e) ?? 0) === 0) {
1250
+ let o = W.get(e);
1251
+ if (o === void 0 && (U.get(e) ?? 0) === 0) {
1242
1252
  a();
1243
1253
  return;
1244
1254
  }
@@ -1246,91 +1256,91 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
1246
1256
  o.push(a);
1247
1257
  return;
1248
1258
  }
1249
- G.set(e, [a]);
1250
- let s = setTimeout(() => Po(e), No);
1251
- typeof s == "object" && typeof s.unref == "function" && s.unref(), K.set(e, s);
1252
- }, Ro = () => {
1253
- H.clear(), U = 0, W.clear();
1254
- for (let e of K.values()) clearTimeout(e);
1255
- K.clear(), G.clear();
1256
- }, zo = () => U, Bo = 64, Vo = "\0", Ho = 32, Uo = (e, ...t) => `${e}_${Dr("sha256").update(t.map(String).join(Vo)).digest("hex").slice(0, Ho)}`, Wo = (e) => e.length + 1 + Ho, q = /* @__PURE__ */ new Map(), Go = (e, t) => {
1257
- q.set(e, {
1259
+ W.set(e, [a]);
1260
+ let s = setTimeout(() => zo(e), Ro);
1261
+ typeof s == "object" && typeof s.unref == "function" && s.unref(), G.set(e, s);
1262
+ }, Uo = () => {
1263
+ V.clear(), H = 0, U.clear();
1264
+ for (let e of G.values()) clearTimeout(e);
1265
+ G.clear(), W.clear();
1266
+ }, Wo = () => H, Go = 64, Ko = "\0", qo = 32, Jo = (e, ...t) => `${e}_${jr("sha256").update(t.map(String).join(Ko)).digest("hex").slice(0, qo)}`, Yo = (e) => e.length + 1 + qo, K = /* @__PURE__ */ new Map(), Xo = (e, t) => {
1267
+ K.set(e, {
1258
1268
  recorder: t.recorder,
1259
1269
  tables: new Set(t.tables),
1260
1270
  ownTables: new Set(t.ownTables)
1261
1271
  });
1262
- }, Ko = (e) => {
1263
- q.delete(e);
1264
- }, qo = () => q.clear(), J = new Or(), Jo = (e) => J.run({ n: 1 }, e), Yo = (e) => C.suspend(() => {
1265
- let t = J.getStore();
1266
- if (t !== void 0) return t.n += 1, C.ensuring(e, C.sync(() => {
1272
+ }, Zo = (e) => {
1273
+ K.delete(e);
1274
+ }, Qo = () => K.clear(), q = new Mr(), $o = (e) => q.run({ n: 1 }, e), es = (e) => w.suspend(() => {
1275
+ let t = q.getStore();
1276
+ if (t !== void 0) return t.n += 1, w.ensuring(e, w.sync(() => {
1267
1277
  --t.n;
1268
1278
  }));
1269
1279
  let n = { n: 1 };
1270
- return J.enterWith(n), C.ensuring(e, C.sync(() => {
1280
+ return q.enterWith(n), w.ensuring(e, w.sync(() => {
1271
1281
  --n.n;
1272
1282
  }));
1273
- }), Xo = () => (J.getStore()?.n ?? 0) > 0, Zo = (e) => {
1274
- if (q.size === 0 || (J.getStore()?.n ?? 0) > 0) return !1;
1275
- for (let t of q.values()) if (!t.ownTables.has(e) && t.tables.has(e)) return !0;
1283
+ }), ts = () => (q.getStore()?.n ?? 0) > 0, ns = (e) => {
1284
+ if (K.size === 0 || (q.getStore()?.n ?? 0) > 0) return !1;
1285
+ for (let t of K.values()) if (!t.ownTables.has(e) && t.tables.has(e)) return !0;
1276
1286
  return !1;
1277
- }, Qo = async (e, t) => {
1278
- if (q.size !== 0) {
1279
- for (let [n, r] of q.entries()) if (!r.ownTables.has(t.table) && r.tables.has(t.table)) try {
1287
+ }, rs = async (e, t) => {
1288
+ if (K.size !== 0) {
1289
+ for (let [n, r] of K.entries()) if (!r.ownTables.has(t.table) && r.tables.has(t.table)) try {
1280
1290
  await r.recorder(e, t);
1281
1291
  } catch (e) {
1282
- let r = dt(e);
1292
+ let r = Ht(e);
1283
1293
  throw r === void 0 ? e : Error(`write recorder '${n}' failed while recording a ${t.op} on '${t.table}': ${r}`, { cause: e });
1284
1294
  }
1285
1295
  }
1286
- }, $o = wr.exponential({
1296
+ }, is = Or.exponential({
1287
1297
  start: 5e-4,
1288
1298
  factor: 2,
1289
1299
  count: 16
1290
- }), es = w.counter("voltro_db_queries_total", { description: "Database operations executed, by dialect and operation kind." }), ts = w.histogram("voltro_db_query_duration_seconds", $o, "Database operation duration in seconds, by dialect and operation kind."), ns = w.counter("voltro_db_errors_total", { description: "Database operations that threw, by dialect and operation kind." }), rs = w.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." }), is = w.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." }), as = [], os = /* @__PURE__ */ new Map(), ss = /* @__PURE__ */ new Map(), cs = /* @__PURE__ */ new Map(), ls = (e, t) => {
1291
- let n = `${e}\u0000${t}`, r = os.get(n);
1300
+ }), as = T.counter("voltro_db_queries_total", { description: "Database operations executed, by dialect and operation kind." }), os = T.histogram("voltro_db_query_duration_seconds", is, "Database operation duration in seconds, by dialect and operation kind."), ss = T.counter("voltro_db_errors_total", { description: "Database operations that threw, by dialect and operation kind." }), cs = T.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." }), ls = T.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." }), J = [], us = /* @__PURE__ */ new Map(), ds = /* @__PURE__ */ new Map(), fs = /* @__PURE__ */ new Map(), ps = (e, t) => {
1301
+ let n = `${e}\u0000${t}`, r = us.get(n);
1292
1302
  if (r !== void 0) return r;
1293
- let i = (n) => w.tagged(w.tagged(n, "dialect", e), "op", t), a = {
1294
- count: i(es),
1295
- duration: i(ts),
1296
- errors: i(ns)
1303
+ let i = (n) => T.tagged(T.tagged(n, "dialect", e), "op", t), a = {
1304
+ count: i(as),
1305
+ duration: i(os),
1306
+ errors: i(ss)
1297
1307
  };
1298
- return os.set(n, a), a;
1299
- }, us = () => {
1300
- os.clear(), ss.clear(), cs.clear();
1301
- }, ds = () => os.size + ss.size + cs.size, fs = /* @__PURE__ */ new Map(), ps = (e, t) => {
1302
- let n = Math.max(0, (fs.get(e) ?? 0) + t);
1303
- n === 0 ? fs.delete(e) : fs.set(e, n);
1304
- let r = ss.get(e);
1305
- r === void 0 && (r = w.tagged(rs, "dialect", e), ss.set(e, r)), r.unsafeUpdate(n, as);
1306
- }, ms = (e) => fs.get(e) ?? 0, hs = (e) => {
1307
- let t = ls(String(e.dialect), e.op);
1308
- t.count.unsafeUpdate(1, as), t.duration.unsafeUpdate(e.durationMs / 1e3, as), e.status === "error" && t.errors.unsafeUpdate(1, as);
1309
- }, gs = async (e, t, n) => {
1308
+ return us.set(n, a), a;
1309
+ }, ms = () => {
1310
+ us.clear(), ds.clear(), fs.clear();
1311
+ }, hs = () => us.size + ds.size + fs.size, gs = /* @__PURE__ */ new Map(), _s = (e, t) => {
1312
+ let n = Math.max(0, (gs.get(e) ?? 0) + t);
1313
+ n === 0 ? gs.delete(e) : gs.set(e, n);
1314
+ let r = ds.get(e);
1315
+ r === void 0 && (r = T.tagged(cs, "dialect", e), ds.set(e, r)), r.unsafeUpdate(n, J);
1316
+ }, vs = (e) => gs.get(e) ?? 0, ys = (e) => {
1317
+ let t = ps(String(e.dialect), e.op);
1318
+ t.count.unsafeUpdate(1, J), t.duration.unsafeUpdate(e.durationMs / 1e3, J), e.status === "error" && t.errors.unsafeUpdate(1, J);
1319
+ }, bs = async (e, t, n) => {
1310
1320
  let r = performance.now(), i = String(e);
1311
- ps(i, 1);
1321
+ _s(i, 1);
1312
1322
  let a = "ok";
1313
1323
  try {
1314
1324
  return await n();
1315
1325
  } catch (e) {
1316
1326
  throw a = "error", e;
1317
1327
  } finally {
1318
- ps(i, -1), hs({
1328
+ _s(i, -1), ys({
1319
1329
  dialect: e,
1320
1330
  op: t,
1321
1331
  durationMs: performance.now() - r,
1322
1332
  status: a
1323
1333
  });
1324
1334
  }
1325
- }, _s = 3e5, vs = (e) => {
1335
+ }, xs = 3e5, Ss = (e) => {
1326
1336
  if (e == null || e === "") return;
1327
1337
  let t = Number(e);
1328
1338
  return Number.isFinite(t) && t >= 0 ? Math.floor(t) : void 0;
1329
- }, ys = (e, t = process.env) => vs(t.VOLTRO_DB_EAGER_FALLBACK_WARN_INTERVAL_MS) ?? vs(e) ?? 3e5, bs = (e, t = {}) => {
1330
- let n = ys(t.warnIntervalMs), r = t.now ?? (() => Date.now()), i = /* @__PURE__ */ new Map();
1339
+ }, Cs = (e, t = process.env) => Ss(t.VOLTRO_DB_EAGER_FALLBACK_WARN_INTERVAL_MS) ?? Ss(e) ?? 3e5, ws = (e, t = {}) => {
1340
+ let n = Cs(t.warnIntervalMs), r = t.now ?? (() => Date.now()), i = /* @__PURE__ */ new Map();
1331
1341
  return (t) => {
1332
- let a = `${t.dialect} ${t.reason}`, o = cs.get(a);
1333
- o === void 0 && (o = w.tagged(w.tagged(is, "dialect", String(t.dialect)), "reason", t.reason), cs.set(a, o)), o.unsafeUpdate(1, as);
1342
+ let a = `${t.dialect} ${t.reason}`, o = fs.get(a);
1343
+ o === void 0 && (o = T.tagged(T.tagged(ls, "dialect", String(t.dialect)), "reason", t.reason), fs.set(a, o)), o.unsafeUpdate(1, J);
1334
1344
  let s = `${t.table}\u0000${t.reason}`, c = i.get(s), l = c === void 0 || n > 0 && r() - c >= n, u = {
1335
1345
  table: t.table,
1336
1346
  dialect: String(t.dialect),
@@ -1344,37 +1354,37 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
1344
1354
  }
1345
1355
  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);
1346
1356
  };
1347
- }, xs = (e) => {
1348
- if (Cr.isSuccess(e)) return e.value;
1349
- throw br.squash(e.cause);
1350
- }, Ss = "10 millis", Cs = 3, ws = (e) => Tr.exponential(Ss).pipe(Tr.compose(Tr.recurs(Cs)), Tr.whileInput(e)), Ts = async (e) => {
1351
- let t = 0, n = C.suspend(() => {
1357
+ }, Ts = (e) => {
1358
+ if (Dr.isSuccess(e)) return e.value;
1359
+ throw wr.squash(e.cause);
1360
+ }, Es = "10 millis", Ds = 3, Os = (e) => kr.exponential(Es).pipe(kr.compose(kr.recurs(Ds)), kr.whileInput(e)), ks = async (e) => {
1361
+ let t = 0, n = w.suspend(() => {
1352
1362
  let n = ++t;
1353
- return e.withTransaction(C.flatMap(C.serviceOption(kr), (t) => {
1354
- if (T.isNone(t)) return C.fail(/* @__PURE__ */ Error(`${e.label}: TransactionConnection unexpectedly missing inside withTransaction.`));
1355
- let r = t.value, i = C.tryPromise({
1363
+ return e.withTransaction(w.flatMap(w.serviceOption(Nr), (t) => {
1364
+ if (E.isNone(t)) return w.fail(/* @__PURE__ */ Error(`${e.label}: TransactionConnection unexpectedly missing inside withTransaction.`));
1365
+ let r = t.value, i = w.tryPromise({
1356
1366
  try: () => e.body(r, n),
1357
1367
  catch: (e) => e
1358
1368
  });
1359
- return e.prepare === void 0 ? i : C.flatMap(e.prepare(r), () => i);
1360
- })).pipe(C.catchAllDefect((t) => e.isRetryable(t) ? C.fail(t) : C.die(t)));
1361
- }).pipe(C.retry(ws(e.isRetryable)), C.withSpan(e.span.name, { attributes: { ...e.span.attributes } }));
1362
- return gs(e.dialect, "transaction", async () => xs(await e.runPromiseExit(e.wrapProgram === void 0 ? n : e.wrapProgram(n))));
1363
- }, Es = class extends Error {
1369
+ return e.prepare === void 0 ? i : w.flatMap(e.prepare(r), () => i);
1370
+ })).pipe(w.catchAllDefect((t) => e.isRetryable(t) ? w.fail(t) : w.die(t)));
1371
+ }).pipe(w.retry(Os(e.isRetryable)), w.withSpan(e.span.name, { attributes: { ...e.span.attributes } }));
1372
+ return bs(e.dialect, "transaction", async () => Ts(await e.runPromiseExit(e.wrapProgram === void 0 ? n : e.wrapProgram(n))));
1373
+ }, As = class extends Error {
1364
1374
  swallowed;
1365
1375
  _tag = "TransactionAborted";
1366
1376
  constructor(e, t) {
1367
1377
  super(`${e}: a statement failed inside this transaction and the error was caught, but the database had already aborted the transaction — every later statement was refused, and COMMIT would have rolled back ALL of its writes, including the ones that succeeded. Nothing was committed.
1368
- the caught failure: ${As(t)}\n to tolerate a failing statement and keep the rest, run it inside \`tx.savepoint(() => …)\` — only that statement is rolled back. To keep all-or-nothing, let the error propagate.`, { cause: t }), this.swallowed = t, this.name = "TransactionAbortedError";
1378
+ the caught failure: ${Ps(t)}\n to tolerate a failing statement and keep the rest, run it inside \`tx.savepoint(() => …)\` — only that statement is rolled back. To keep all-or-nothing, let the error propagate.`, { cause: t }), this.swallowed = t, this.name = "TransactionAbortedError";
1369
1379
  }
1370
- }, Ds = (e, t = "transactional()") => {
1380
+ }, js = (e, t = "transactional()") => {
1371
1381
  let n = 0, r, i = (e) => {
1372
1382
  r === void 0 && (r = { error: e });
1373
1383
  };
1374
1384
  return {
1375
1385
  track: (a) => r === void 0 ? n > 0 ? a() : a().catch((t) => {
1376
1386
  throw e(t) && i(t), t;
1377
- }) : Promise.reject(new Es(t, r.error)),
1387
+ }) : Promise.reject(new As(t, r.error)),
1378
1388
  inSavepoint: async (e) => {
1379
1389
  n++;
1380
1390
  try {
@@ -1386,7 +1396,7 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
1386
1396
  record: i,
1387
1397
  abortedBy: () => r
1388
1398
  };
1389
- }, Os = async (e, t) => {
1399
+ }, Ms = async (e, t) => {
1390
1400
  let { tracker: n, name: r, exec: i, spelling: a } = e;
1391
1401
  await n.track(() => i(a === "mssql" ? `SAVE TRANSACTION ${r}` : `SAVEPOINT ${r}`));
1392
1402
  try {
@@ -1395,8 +1405,8 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
1395
1405
  } catch (e) {
1396
1406
  throw await i(a === "mssql" ? `ROLLBACK TRANSACTION ${r}` : `ROLLBACK TO SAVEPOINT ${r}`).catch((e) => n.record(e)), a === "standard" && await i(`RELEASE SAVEPOINT ${r}`).catch(() => void 0), e;
1397
1407
  }
1398
- }, ks = (e) => e instanceof Es || typeof e == "object" && !!e && e._tag === "TransactionAborted", As = (e) => {
1399
- for (let t of ye(e)) {
1408
+ }, Ns = (e) => e instanceof As || typeof e == "object" && !!e && e._tag === "TransactionAborted", Ps = (e) => {
1409
+ for (let t of yt(e)) {
1400
1410
  let e = t;
1401
1411
  for (let t = 0; t < 5 && typeof e == "object" && e; t++) {
1402
1412
  let t = e.code, n = e.message;
@@ -1405,14 +1415,14 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
1405
1415
  }
1406
1416
  }
1407
1417
  return e instanceof Error ? e.message : String(e);
1408
- }, js = async (e) => {
1409
- let t = Co(), n = t === void 0 ? (e) => e() : (e) => So(t, e), r = await Ts({
1418
+ }, Fs = async (e) => {
1419
+ let t = Oo(), n = t === void 0 ? (e) => e() : (e) => Do(t, e), r = await ks({
1410
1420
  ...e,
1411
1421
  body: (r) => {
1412
1422
  let i = e.makeView(r, t);
1413
1423
  return n(() => e.work(i)).then((t) => {
1414
1424
  let n = i.abortedBy?.();
1415
- if (n !== void 0) throw e.isRetryable(n.error) ? n.error : new Es(e.label, n.error);
1425
+ if (n !== void 0) throw e.isRetryable(n.error) ? n.error : new As(e.label, n.error);
1416
1426
  return {
1417
1427
  result: t,
1418
1428
  view: i
@@ -1424,50 +1434,50 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
1424
1434
  }
1425
1435
  });
1426
1436
  return r.view.commitEvents(), r.result;
1427
- }, Ms = /* @__PURE__ */ new Set([
1437
+ }, Is = /* @__PURE__ */ new Set([
1428
1438
  "1213",
1429
1439
  "ER_LOCK_DEADLOCK",
1430
1440
  "1205",
1431
1441
  "ER_LOCK_WAIT_TIMEOUT",
1432
1442
  "1020",
1433
1443
  "ER_CHECKREAD"
1434
- ]), Ns = /* @__PURE__ */ new Set(["40001", "40P01"]), Ps = /* @__PURE__ */ new Set(["1205"]), Fs = /* @__PURE__ */ new Set([
1444
+ ]), Ls = /* @__PURE__ */ new Set(["40001", "40P01"]), Rs = /* @__PURE__ */ new Set(["1205"]), zs = /* @__PURE__ */ new Set([
1435
1445
  "SQLITE_BUSY",
1436
1446
  "5",
1437
1447
  "SQLITE_LOCKED",
1438
1448
  "6"
1439
- ]), Is = /write-write conflict|write-read conflict|database is locked|table is locked|database is busy/i, Ls = /* @__PURE__ */ new Set([
1449
+ ]), Bs = /write-write conflict|write-read conflict|database is locked|table is locked|database is busy/i, Vs = /* @__PURE__ */ new Set([
1440
1450
  1213,
1441
1451
  1205,
1442
1452
  1020
1443
- ]), Rs = /* @__PURE__ */ new Set([
1444
- ...Ms,
1445
- ...Ns,
1446
- ...Ps,
1447
- ...Fs
1448
- ]), zs = (e) => ye(e).some(Bs), Bs = (e) => {
1453
+ ]), Hs = /* @__PURE__ */ new Set([
1454
+ ...Is,
1455
+ ...Ls,
1456
+ ...Rs,
1457
+ ...zs
1458
+ ]), Us = (e) => yt(e).some(Ws), Ws = (e) => {
1449
1459
  let t = e;
1450
1460
  for (let e = 0; e < 6 && typeof t == "object" && t; e++) {
1451
1461
  let e = t;
1452
- if (typeof e.errno == "number" && Ls.has(e.errno) || typeof e.number == "number" && Ps.has(String(e.number)) || typeof e.code == "string" && Rs.has(e.code) || typeof e.sqlState == "string" && Ns.has(e.sqlState) || typeof e.message == "string" && Is.test(e.message)) return !0;
1462
+ if (typeof e.errno == "number" && Vs.has(e.errno) || typeof e.number == "number" && Rs.has(String(e.number)) || typeof e.code == "string" && Hs.has(e.code) || typeof e.sqlState == "string" && Ls.has(e.sqlState) || typeof e.message == "string" && Bs.test(e.message)) return !0;
1453
1463
  t = e.cause;
1454
1464
  }
1455
1465
  return !1;
1456
- }, Vs = "voltro/expires", Hs = () => sn({
1457
- id: Vs,
1466
+ }, Gs = "voltro/expires", Ks = () => Be({
1467
+ id: Gs,
1458
1468
  fields: { expiresAt: b().nullable() },
1459
1469
  behaviors: { defaultWhere: () => "expiresAt IS NULL OR expiresAt > now()" }
1460
- }), Us = "voltro/localFirst", Ws = () => sn({
1461
- id: Us,
1470
+ }), qs = "voltro/localFirst", Js = () => Be({
1471
+ id: qs,
1462
1472
  fields: {}
1463
- }), Gs = (e) => e.appliedMixins.some((e) => e.id === Us), Ks = (e) => {
1473
+ }), Ys = (e) => e.appliedMixins.some((e) => e.id === qs), Xs = (e) => {
1464
1474
  let t = [];
1465
- for (let n of Object.values(e)) Gs(n) && t.push(n.tableName);
1475
+ for (let n of Object.values(e)) Ys(n) && t.push(n.tableName);
1466
1476
  return t;
1467
- }, qs = class extends Sr.TaggedError("TableStreamError") {}, Js = 1e3, Ys = (e, t, n, r) => {
1468
- let i = T.match(r, {
1477
+ }, Zs = class extends Er.TaggedError("TableStreamError") {}, Qs = 1e3, $s = (e, t, n, r) => {
1478
+ let i = E.match(r, {
1469
1479
  onNone: () => e.where,
1470
- onSome: (n) => e.where ? ut(e.where, en(t, n)) : en(t, n)
1480
+ onSome: (n) => e.where ? pt(e.where, Ot(t, n)) : Ot(t, n)
1471
1481
  });
1472
1482
  return {
1473
1483
  table: e.table,
@@ -1482,19 +1492,19 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
1482
1492
  ...e.includeDeleted === void 0 ? {} : { includeDeleted: e.includeDeleted },
1483
1493
  ...e.crossTenant === void 0 ? {} : { crossTenant: e.crossTenant }
1484
1494
  };
1485
- }, Xs = (e, t) => {
1486
- let n = t.pk ?? "id", r = t.chunkSize ?? Js;
1487
- return Er.paginateChunkEffect(T.none(), (i) => {
1488
- let a = C.tryPromise({
1489
- try: () => e.query(Ys(t, n, r, i)),
1490
- catch: (e) => new qs({
1495
+ }, ec = (e, t) => {
1496
+ let n = t.pk ?? "id", r = t.chunkSize ?? Qs;
1497
+ return Ar.paginateChunkEffect(E.none(), (i) => {
1498
+ let a = w.tryPromise({
1499
+ try: () => e.query($s(t, n, r, i)),
1500
+ catch: (e) => new Zs({
1491
1501
  table: t.table,
1492
1502
  cause: e
1493
1503
  })
1494
1504
  });
1495
- return (t.retry ? a.pipe(C.retry(t.retry)) : a).pipe(C.map((e) => [xr.fromIterable(e), e.length === r && e.length > 0 ? T.some(T.some(e[e.length - 1][n])) : T.none()]));
1505
+ return (t.retry ? a.pipe(w.retry(t.retry)) : a).pipe(w.map((e) => [Tr.fromIterable(e), e.length === r && e.length > 0 ? E.some(E.some(e[e.length - 1][n])) : E.none()]));
1496
1506
  });
1497
- }, Zs = (e) => {
1507
+ }, tc = (e) => {
1498
1508
  let t = e.alpha ?? .5;
1499
1509
  if (t < 0 || t > 1) throw Error(`hybridSearch: alpha must be in [0, 1], got ${t}`);
1500
1510
  return (n) => {
@@ -1508,7 +1518,7 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
1508
1518
  queryText: e.vector.query,
1509
1519
  distance: e.vector.distance ?? "cosine",
1510
1520
  alpha: t
1511
- }, i = Ln(n.table, e.fts.indexName, n.fullTextIndexes);
1521
+ }, i = Gt(n.table, e.fts.indexName, n.fullTextIndexes);
1512
1522
  return {
1513
1523
  ...n,
1514
1524
  annClause: r,
@@ -1521,17 +1531,17 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
1521
1531
  }
1522
1532
  };
1523
1533
  };
1524
- }, Qs = async (e, t) => {
1534
+ }, nc = async (e, t) => {
1525
1535
  let n = e.as ?? "embedding", r = t.row[e.from];
1526
1536
  if (typeof r != "string" || r.length === 0) return {};
1527
1537
  let i = await t.embed(r);
1528
1538
  return { [n]: i };
1529
- }, $s = (e) => {
1539
+ }, rc = (e) => {
1530
1540
  if (!Number.isInteger(e.dimensions) || e.dimensions <= 0) throw Error(`vectorEmbedding: dimensions must be a positive integer, got ${String(e.dimensions)}.`);
1531
- let t = e.as ?? "embedding", n = (t) => Qs(e, t);
1532
- return sn({
1541
+ let t = e.as ?? "embedding", n = (t) => nc(e, t);
1542
+ return Be({
1533
1543
  id: "voltro/vectorEmbedding",
1534
- fields: { [t]: Ce(e.dimensions) },
1544
+ fields: { [t]: pe(e.dimensions) },
1535
1545
  ...e.index === !1 ? {} : { indexes: [{
1536
1546
  fields: [t],
1537
1547
  kind: "hnsw",
@@ -1546,19 +1556,19 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
1546
1556
  beforeUpdate: n
1547
1557
  }
1548
1558
  });
1549
- }, ec = 63, tc = "br_pr", Y = class extends Error {
1559
+ }, ic = 63, ac = "br_pr", Y = class extends Error {
1550
1560
  _tag = "BranchNameInvalid";
1551
1561
  constructor(e) {
1552
1562
  super(e), this.name = "BranchNameInvalid";
1553
1563
  }
1554
- }, nc = (e, t) => {
1564
+ }, oc = (e, t) => {
1555
1565
  if (!Number.isInteger(t) || t < 0) throw new Y(`prNumber must be a non-negative integer, got ${String(t)}`);
1556
- let n = Me(e);
1566
+ let n = se(e);
1557
1567
  if (n.replace(/_/g, "") === "") throw new Y(`app slug '${e}' has no usable identifier characters`);
1558
- let r = `${tc}${t}_${n}`;
1559
- if (r.length > ec) throw new Y(`branch namespace '${r}' exceeds the ${ec}-byte identifier limit — use a shorter app slug`);
1568
+ let r = `${ac}${t}_${n}`;
1569
+ if (r.length > ic) throw new Y(`branch namespace '${r}' exceeds the ${ic}-byte identifier limit — use a shorter app slug`);
1560
1570
  return r;
1561
- }, rc = (e) => e.startsWith(tc), ic = {
1571
+ }, sc = (e) => e.startsWith(ac), cc = {
1562
1572
  requested: {
1563
1573
  provision: "provisioning",
1564
1574
  destroy: "destroying"
@@ -1577,18 +1587,18 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
1577
1587
  fail: "failed"
1578
1588
  },
1579
1589
  destroyed: {}
1580
- }, ac = class extends Error {
1590
+ }, lc = class extends Error {
1581
1591
  from;
1582
1592
  event;
1583
1593
  _tag = "BranchTransitionInvalid";
1584
1594
  constructor(e, t) {
1585
1595
  super(`invalid branch transition: ${e} --${t}-->`), this.from = e, this.event = t, this.name = "BranchTransitionInvalid";
1586
1596
  }
1587
- }, oc = (e, t) => {
1588
- let n = ic[e][t];
1589
- if (n === void 0) throw new ac(e, t);
1597
+ }, uc = (e, t) => {
1598
+ let n = cc[e][t];
1599
+ if (n === void 0) throw new lc(e, t);
1590
1600
  return n;
1591
- }, sc = (e, t, n, r, i = [], a = []) => {
1601
+ }, dc = (e, t, n, r, i = [], a = []) => {
1592
1602
  if (n === "copy" && (r === void 0 || r === "")) throw new Y("seed 'copy' requires a parentNamespace to snapshot from");
1593
1603
  let o = [{
1594
1604
  kind: "create-namespace",
@@ -1618,13 +1628,13 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
1618
1628
  kind: "seed",
1619
1629
  detail: `run boot seeds into ${e}`
1620
1630
  }), o;
1621
- }, cc = (e) => {
1622
- if (!rc(e)) throw new Y(`refusing to plan teardown of '${e}' — not a branch namespace`);
1631
+ }, fc = (e) => {
1632
+ if (!sc(e)) throw new Y(`refusing to plan teardown of '${e}' — not a branch namespace`);
1623
1633
  return [{
1624
1634
  kind: "drop-namespace",
1625
1635
  detail: e
1626
1636
  }];
1627
- }, lc = (e) => {
1637
+ }, pc = (e) => {
1628
1638
  if (e === void 0 || e === "") return !1;
1629
1639
  try {
1630
1640
  let t = new URL(e).hostname.toLowerCase();
@@ -1632,27 +1642,27 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
1632
1642
  } catch {
1633
1643
  return /\bneon\.(tech|build)\b/i.test(e);
1634
1644
  }
1635
- }, uc = (e) => e.prefer === void 0 ? e.seed === "copy" && lc(e.dbUrl) ? "neon-cow" : "namespace" : e.prefer, dc = (e, t = {}) => [{
1645
+ }, mc = (e) => e.prefer === void 0 ? e.seed === "copy" && pc(e.dbUrl) ? "neon-cow" : "namespace" : e.prefer, hc = (e, t = {}) => [{
1636
1646
  kind: "neon-branch-create",
1637
1647
  detail: `${t.parentBranch ?? "main"} → ${e} (copy-on-write)`
1638
- }], fc = (e) => {
1639
- if (!rc(e)) throw new Y(`refusing to plan teardown of '${e}' — not a branch namespace`);
1648
+ }], gc = (e) => {
1649
+ if (!sc(e)) throw new Y(`refusing to plan teardown of '${e}' — not a branch namespace`);
1640
1650
  return [{
1641
1651
  kind: "neon-branch-delete",
1642
1652
  detail: e
1643
1653
  }];
1644
- }, pc = (e) => e.mechanism === "neon-cow" ? dc(e.branchId, e.neonParentBranch === void 0 ? {} : { parentBranch: e.neonParentBranch }) : sc(e.branchId, e.tableNames, e.seed, e.parentNamespace, e.foreignKeys, e.indexNames), mc = (e, t) => e === "neon-cow" ? fc(t) : cc(t), hc = (e, t, n) => {
1654
+ }, _c = (e) => e.mechanism === "neon-cow" ? hc(e.branchId, e.neonParentBranch === void 0 ? {} : { parentBranch: e.neonParentBranch }) : dc(e.branchId, e.tableNames, e.seed, e.parentNamespace, e.foreignKeys, e.indexNames), vc = (e, t) => e === "neon-cow" ? gc(t) : fc(t), yc = (e, t, n) => {
1645
1655
  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);
1646
1656
  return {
1647
1657
  evict: i,
1648
1658
  rejectNew: r.filter((e) => !a.has(e.namespace)).length >= t.maxBranches
1649
1659
  };
1650
- }, gc = async (e, t) => {
1651
- let n = nc(e.appSlug, e.prNumber), r = uc({
1660
+ }, bc = async (e, t) => {
1661
+ let n = oc(e.appSlug, e.prNumber), r = mc({
1652
1662
  seed: e.seed,
1653
1663
  ...e.dbUrl === void 0 ? {} : { dbUrl: e.dbUrl },
1654
1664
  ...e.prefer === void 0 ? {} : { prefer: e.prefer }
1655
- }), i = pc({
1665
+ }), i = _c({
1656
1666
  mechanism: r,
1657
1667
  branchId: n,
1658
1668
  tableNames: e.tableNames,
@@ -1681,15 +1691,15 @@ var jr = (e) => typeof e == "string" && e !== "" ? e : null, Mr = async (e, t, n
1681
1691
  mechanism: r,
1682
1692
  steps: i
1683
1693
  };
1684
- }, _c = async (e, t, n) => {
1685
- let r = mc(t, e);
1694
+ }, xc = async (e, t, n) => {
1695
+ let r = vc(t, e);
1686
1696
  return t === "neon-cow" ? await n.neonBranchDelete(e) : await n.dropNamespace(e), r;
1687
- }, vc = (e, t, n) => hc(e, t, n), X = (e) => `"${e.replace(/"/g, "\"\"")}"`, yc = {
1697
+ }, Sc = (e, t, n) => yc(e, t, n), X = (e) => `"${e.replace(/"/g, "\"\"")}"`, Cc = {
1688
1698
  cascade: "CASCADE",
1689
1699
  restrict: "RESTRICT",
1690
1700
  setNull: "SET NULL",
1691
1701
  noAction: "NO ACTION"
1692
- }, Z = (e) => `'${e.replace(/'/g, "''")}'`, bc = (e, t) => {
1702
+ }, Z = (e) => `'${e.replace(/'/g, "''")}'`, wc = (e, t) => {
1693
1703
  let n = t.columns.map(Z).join(", ");
1694
1704
  return `DO $voltro_branch$
1695
1705
  DECLARE derived name;
@@ -1716,10 +1726,10 @@ BEGIN
1716
1726
  END IF;
1717
1727
  END
1718
1728
  $voltro_branch$`;
1719
- }, xc = (e, t) => {
1720
- let n = t.onDelete === void 0 ? "" : ` ON DELETE ${yc[t.onDelete]}`, r = t.onUpdate === void 0 ? "" : ` ON UPDATE ${yc[t.onUpdate]}`;
1729
+ }, Tc = (e, t) => {
1730
+ let n = t.onDelete === void 0 ? "" : ` ON DELETE ${Cc[t.onDelete]}`, r = t.onUpdate === void 0 ? "" : ` ON UPDATE ${Cc[t.onUpdate]}`;
1721
1731
  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}`;
1722
- }, Sc = (e) => {
1732
+ }, Ec = (e) => {
1723
1733
  let t = () => {
1724
1734
  throw Error("namespace branch executor: Neon ops require a neon-cow executor (use a Neon connection for copy-on-write branches)");
1725
1735
  };
@@ -1727,24 +1737,24 @@ $voltro_branch$`;
1727
1737
  createNamespace: (t) => e.run(`CREATE SCHEMA IF NOT EXISTS ${X(t)}`),
1728
1738
  createTable: (t, n) => e.run(`CREATE TABLE IF NOT EXISTS ${X(t)}.${X(n)} (LIKE ${X(n)} INCLUDING ALL)`),
1729
1739
  copyTable: (t, n, r) => e.run(`INSERT INTO ${X(n)}.${X(r)} SELECT * FROM ${X(t)}.${X(r)}`),
1730
- addForeignKey: (t, n) => e.run(xc(t, n)),
1731
- restoreIndexName: (t, n) => e.run(bc(t, n)),
1740
+ addForeignKey: (t, n) => e.run(Tc(t, n)),
1741
+ restoreIndexName: (t, n) => e.run(wc(t, n)),
1732
1742
  dropNamespace: (t) => e.run(`DROP SCHEMA IF EXISTS ${X(t)} CASCADE`),
1733
1743
  neonBranchCreate: t,
1734
1744
  neonBranchDelete: t
1735
1745
  };
1736
- }, Cc = class extends Error {
1746
+ }, Dc = class extends Error {
1737
1747
  _tag = "TenantResidencyUnresolved";
1738
1748
  constructor(e) {
1739
1749
  super(e), this.name = "TenantResidencyUnresolved";
1740
1750
  }
1741
- }, wc = class extends Error {
1751
+ }, Oc = class extends Error {
1742
1752
  region;
1743
1753
  _tag = "TenantRegionUnavailable";
1744
1754
  constructor(e, t) {
1745
1755
  super(t), this.region = e, this.name = "TenantRegionUnavailable";
1746
1756
  }
1747
- }, Tc, Ec = (e) => {
1757
+ }, kc, Ac = (e) => {
1748
1758
  if (e.homes === void 0) throw Error("setResidencyConfig: `homes` is required");
1749
1759
  if (e.servableRegions === void 0 || e.servableRegions.length === 0) throw Error("setResidencyConfig: `servableRegions` must be non-empty (which regions this deployment serves)");
1750
1760
  let t = /* @__PURE__ */ new Map();
@@ -1753,55 +1763,55 @@ $voltro_branch$`;
1753
1763
  if (e !== void 0 && e !== n.region) throw Error(`residency: tenant '${n.tenantId}' is mapped to two regions ('${e}' and '${n.region}')`);
1754
1764
  t.set(n.tenantId, n.region);
1755
1765
  }
1756
- return Tc = e, e;
1757
- }, Dc = () => Tc, Oc = () => {
1758
- Tc = void 0;
1759
- }, kc = (e, t) => {
1760
- if (e == null || e === "") throw new Cc("residency is on but the request has no resolvable tenant — refusing to bind a store");
1766
+ return kc = e, e;
1767
+ }, jc = () => kc, Mc = () => {
1768
+ kc = void 0;
1769
+ }, Nc = (e, t) => {
1770
+ if (e == null || e === "") throw new Dc("residency is on but the request has no resolvable tenant — refusing to bind a store");
1761
1771
  let n = t.homes.find((t) => t.tenantId === e);
1762
- if (n === void 0) throw new Cc(`no residency home is mapped for tenant '${e}' — refusing to fall back to a default store (would be a residency violation)`);
1772
+ if (n === void 0) throw new Dc(`no residency home is mapped for tenant '${e}' — refusing to fall back to a default store (would be a residency violation)`);
1763
1773
  return n;
1764
- }, Ac = (e, t) => t.servableRegions.includes(e), jc = (e, t) => {
1765
- let n = kc(e.tenantId, t), r = Oe(n.tenantId);
1774
+ }, Pc = (e, t) => t.servableRegions.includes(e), Fc = (e, t) => {
1775
+ let n = Nc(e.tenantId, t), r = He(n.tenantId);
1766
1776
  return {
1767
1777
  region: n.region,
1768
1778
  namespace: r,
1769
1779
  ...n.connectionKey === void 0 ? {} : { connectionKey: n.connectionKey }
1770
1780
  };
1771
- }, Mc = (e, t, n) => {
1772
- let r = jc(e, t);
1773
- if (!Ac(r.region, t)) throw new wc(r.region, `tenant homed in region '${r.region}', which this deployment does not serve — route to the home region`);
1781
+ }, Ic = (e, t, n) => {
1782
+ let r = Fc(e, t);
1783
+ if (!Pc(r.region, t)) throw new Oc(r.region, `tenant homed in region '${r.region}', which this deployment does not serve — route to the home region`);
1774
1784
  let i = n.get(r.region);
1775
- if (i === void 0) throw new wc(r.region, `no store handle for home region '${r.region}' (declared servable but not wired) — failing closed`);
1785
+ if (i === void 0) throw new Oc(r.region, `no store handle for home region '${r.region}' (declared servable but not wired) — failing closed`);
1776
1786
  return {
1777
1787
  store: i,
1778
1788
  placement: r
1779
1789
  };
1780
- }, Nc = async (e, t, n, r) => {
1781
- let { store: i, placement: a } = Mc(e, t, n);
1790
+ }, Lc = async (e, t, n, r) => {
1791
+ let { store: i, placement: a } = Ic(e, t, n);
1782
1792
  return await r(i, a), a;
1783
- }, Pc = (e) => {
1793
+ }, Rc = (e) => {
1784
1794
  if (typeof e == "string") return e;
1785
1795
  if ("jsonPath" in e) {
1786
1796
  let { column: t, path: n, numeric: r } = e.jsonPath;
1787
1797
  return `(json:${t}->${n.join(".")}${r ? "::num" : ""})`;
1788
1798
  }
1789
1799
  return `(${e.expr})`;
1790
- }, Q = (e) => e.map(Pc), Fc = (e, t) => {
1800
+ }, Q = (e) => e.map(Rc), zc = (e, t) => {
1791
1801
  if (e.length !== t.length) return !1;
1792
- for (let n = 0; n < e.length; n++) if (Pc(e[n]) !== Pc(t[n])) return !1;
1802
+ for (let n = 0; n < e.length; n++) if (Rc(e[n]) !== Rc(t[n])) return !1;
1793
1803
  return !0;
1794
- }, Ic = (e, t) => {
1804
+ }, Bc = (e, t) => {
1795
1805
  if (e.length >= t.length) return !1;
1796
- for (let n = 0; n < e.length; n++) if (Pc(e[n]) !== Pc(t[n])) return !1;
1806
+ for (let n = 0; n < e.length; n++) if (Rc(e[n]) !== Rc(t[n])) return !1;
1797
1807
  return !0;
1798
- }, Lc = (e) => {
1808
+ }, Vc = (e) => {
1799
1809
  let t = [], n = e.appliedIndexes, r = e.tableName;
1800
1810
  for (let e = 0; e < n.length; e++) {
1801
1811
  let i = n[e];
1802
1812
  for (let a = e + 1; a < n.length; a++) {
1803
1813
  let e = n[a];
1804
- if (Fc(i.fields, e.fields)) {
1814
+ if (zc(i.fields, e.fields)) {
1805
1815
  let [n, a] = i.name < e.name ? [i, e] : [e, i];
1806
1816
  t.push({
1807
1817
  kind: "duplicate-fields",
@@ -1812,13 +1822,13 @@ $voltro_branch$`;
1812
1822
  });
1813
1823
  continue;
1814
1824
  }
1815
- Ic(i.fields, e.fields) ? t.push({
1825
+ Bc(i.fields, e.fields) ? t.push({
1816
1826
  kind: "redundant-prefix",
1817
1827
  table: r,
1818
1828
  redundant: i,
1819
1829
  coveredBy: e,
1820
1830
  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).`
1821
- }) : Ic(e.fields, i.fields) && t.push({
1831
+ }) : Bc(e.fields, i.fields) && t.push({
1822
1832
  kind: "redundant-prefix",
1823
1833
  table: r,
1824
1834
  redundant: e,
@@ -1828,23 +1838,23 @@ $voltro_branch$`;
1828
1838
  }
1829
1839
  }
1830
1840
  return t;
1831
- }, Rc = (e) => {
1841
+ }, Hc = (e) => {
1832
1842
  let t = [];
1833
- for (let n of e) t.push(...Lc(n));
1843
+ for (let n of e) t.push(...Vc(n));
1834
1844
  return t;
1835
- }, zc = "\x1B[", Bc = `${zc}38;2;245;158;11m`, Vc = `${zc}38;2;16;185;129m`, Hc = (e, t) => `${e}${t}${D.reset}`, $ = (e, t, n) => e ? typeof t == "function" ? t(n) : Hc(t, n) : n, Uc = (e, t = {}) => {
1836
- let n = t.color ?? !0, r = t.indent ?? " ", i = (e) => $(n, D.dim, e.padEnd(11)), a = (e) => $(n, (e) => D.bold(D.brand(e)), e), o = (e) => $(n, D.brightRed24, e), s = (e) => $(n, Vc, e), c = (e) => $(n, Bc, e), l = (e) => $(n, D.dim, e), u = `${c("index audit")} ${l("·")} ${$(n, D.bold, e.kind)}`, d = e.redundant.fields.length, f = Q(e.coveredBy.fields.slice(d)), p = (e, t) => {
1845
+ }, Uc = "\x1B[", Wc = `${Uc}38;2;245;158;11m`, Gc = `${Uc}38;2;16;185;129m`, Kc = (e, t) => `${e}${t}${O.reset}`, $ = (e, t, n) => e ? typeof t == "function" ? t(n) : Kc(t, n) : n, qc = (e, t = {}) => {
1846
+ let n = t.color ?? !0, r = t.indent ?? " ", i = (e) => $(n, O.dim, e.padEnd(11)), a = (e) => $(n, (e) => O.bold(O.brand(e)), e), o = (e) => $(n, O.brightRed24, e), s = (e) => $(n, Gc, e), c = (e) => $(n, Wc, e), l = (e) => $(n, O.dim, e), u = `${c("index audit")} ${l("·")} ${$(n, O.bold, e.kind)}`, d = e.redundant.fields.length, f = Q(e.coveredBy.fields.slice(d)), p = (e, t) => {
1837
1847
  let n = e.slice(0, t), r = e.slice(t), i = [];
1838
1848
  return n.length > 0 && i.push(s(`[${n.join(", ")}]`)), r.length > 0 && i.push(c(`+ [${r.join(", ")}]`)), i.join(" ");
1839
1849
  }, m = [];
1840
- 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, D.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");
1841
- }, Wc = (e, { apply: t, undo: n }) => ({
1850
+ 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, O.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");
1851
+ }, Jc = (e, { apply: t, undo: n }) => ({
1842
1852
  name: e,
1843
1853
  apply: t,
1844
1854
  undo: n
1845
- }), Gc = (e) => {
1855
+ }), Yc = (e) => {
1846
1856
  if (!/^\d{14}_/.test(e.id)) throw Error(`migration "${e.id}": id must start with a 14-digit timestamp followed by "_" (convention: <YYYYMMDDHHMMSS>_<slug>)`);
1847
- let t = e.steps({ step: Wc });
1857
+ let t = e.steps({ step: Jc });
1848
1858
  if (t.length === 0) throw Error(`migration "${e.id}": at least one step is required`);
1849
1859
  return {
1850
1860
  __migration: !0,
@@ -1852,42 +1862,42 @@ $voltro_branch$`;
1852
1862
  name: e.name,
1853
1863
  steps: t
1854
1864
  };
1855
- }, Kc = (e) => typeof e == "object" && !!e && "__migration" in e && e.__migration === !0, qc = Jn.tableName, Jc = (e) => Dr("sha256").update(`${e.type}\u0000${e.id}`, "utf8").digest("hex"), Yc = async (e, t) => {
1865
+ }, Xc = (e) => typeof e == "object" && !!e && "__migration" in e && e.__migration === !0, Zc = lr.tableName, Qc = (e) => jr("sha256").update(`${e.type}\u0000${e.id}`, "utf8").digest("hex"), $c = async (e, t) => {
1856
1866
  let [n] = await e.query({
1857
- table: qc,
1858
- predicate: Un("id", Jc(t)),
1867
+ table: Zc,
1868
+ predicate: Tn("id", Qc(t)),
1859
1869
  order: [],
1860
1870
  take: 1,
1861
1871
  skip: void 0,
1862
1872
  projection: void 0
1863
1873
  }), r = n?.tenantId;
1864
1874
  return typeof r == "string" ? r : null;
1865
- }, Xc = async (e, t, n) => {
1866
- await e.upsert(qc, {
1867
- id: Jc(t),
1875
+ }, el = async (e, t, n) => {
1876
+ await e.upsert(Zc, {
1877
+ id: Qc(t),
1868
1878
  subjectType: t.type,
1869
1879
  subjectId: t.id,
1870
1880
  tenantId: n,
1871
1881
  selectedAt: /* @__PURE__ */ new Date()
1872
1882
  }, { conflictColumns: ["id"] });
1873
- }, Zc = async (e, t) => {
1874
- await e.delete(qc, Jc(t));
1875
- }, Qc = "id", $c = (e, t) => {
1876
- let n = Wt(e);
1883
+ }, tl = async (e, t) => {
1884
+ await e.delete(Zc, Qc(t));
1885
+ }, nl = "id", rl = (e, t) => {
1886
+ let n = or(e);
1877
1887
  if (n === void 0) return t;
1878
- let r = n.fields[Qc]?.idScheme;
1879
- if (r === void 0 || t[Qc] != null) return t;
1888
+ let r = n.fields[nl]?.idScheme;
1889
+ if (r === void 0 || t[nl] != null) return t;
1880
1890
  if (r.kind === "numeric") {
1881
- if (!(Qc in t)) return t;
1891
+ if (!(nl in t)) return t;
1882
1892
  let e = { ...t };
1883
- return delete e[Qc], e;
1893
+ return delete e[nl], e;
1884
1894
  }
1885
- let i = Ae(r, e);
1895
+ let i = qe(r, e);
1886
1896
  return i === null ? t : {
1887
1897
  ...t,
1888
- [Qc]: i
1898
+ [nl]: i
1889
1899
  };
1890
- }, el = (e, t) => t.map((t) => $c(e, t)), tl = {
1900
+ }, il = (e, t) => t.map((t) => rl(e, t)), al = {
1891
1901
  postgres: { maxBindParameters: 65535 },
1892
1902
  mysql: { maxBindParameters: 65535 },
1893
1903
  mariadb: { maxBindParameters: 65535 },
@@ -1897,25 +1907,25 @@ $voltro_branch$`;
1897
1907
  },
1898
1908
  sqlite: { maxBindParameters: 32766 },
1899
1909
  turso: { maxBindParameters: 32766 }
1900
- }, nl = (e) => tl[e], rl = (e) => {
1910
+ }, ol = (e) => al[e], sl = (e) => {
1901
1911
  let t = /* @__PURE__ */ new Set();
1902
1912
  for (let n of e) for (let e of Object.keys(n)) t.add(e);
1903
1913
  return t.size;
1904
- }, il = (e, t) => {
1914
+ }, cl = (e, t) => {
1905
1915
  if (t === void 0 || e.length === 0) return [e];
1906
- let n = Math.max(1, rl(e)), r = Math.floor(t.maxBindParameters / n), i = t.maxRowsPerStatement ?? Infinity, a = Math.max(1, Math.min(r, i));
1916
+ let n = Math.max(1, sl(e)), r = Math.floor(t.maxBindParameters / n), i = t.maxRowsPerStatement ?? Infinity, a = Math.max(1, Math.min(r, i));
1907
1917
  if (e.length <= a) return [e];
1908
1918
  let o = [];
1909
1919
  for (let t = 0; t < e.length; t += a) o.push(e.slice(t, t + a));
1910
1920
  return o;
1911
- }, al = (e, t) => {
1921
+ }, ll = (e, t) => {
1912
1922
  let n = [], r = t;
1913
1923
  for (let [t, i] of Object.entries(e.fields)) {
1914
1924
  let e = i;
1915
1925
  e.nullable || e.hasDefault || e.idScheme !== void 0 || e.generatedAs !== void 0 || (r[t] === void 0 || r[t] === null) && n.push(t);
1916
1926
  }
1917
1927
  return n;
1918
- }, ol = (e, t, n) => {
1928
+ }, ul = (e, t, n) => {
1919
1929
  let r = n, i = new Set(e === void 0 ? [] : Object.entries(e.fields).filter(([, e]) => e.generatedAs !== void 0).map(([e]) => e)), a = [];
1920
1930
  for (let e of t) i.has(e) || (r[e] === void 0 ? a.push({
1921
1931
  column: e,
@@ -1925,36 +1935,36 @@ $voltro_branch$`;
1925
1935
  reason: "null"
1926
1936
  }));
1927
1937
  return a;
1928
- }, sl = (e, t, n) => e.insert(t.tableName, n), cl = (e, t, n) => e.insertMany(t.tableName, n), ll = (e, t, n, r) => e.upsert(t.tableName, n, {
1938
+ }, dl = (e, t, n) => e.insert(t.tableName, n), fl = (e, t, n) => e.insertMany(t.tableName, n), pl = (e, t, n, r) => e.upsert(t.tableName, n, {
1929
1939
  conflictColumns: r.conflictColumns,
1930
1940
  ...r.update === void 0 ? {} : { update: r.update },
1931
1941
  ...r.updateValues === void 0 ? {} : { updateValues: r.updateValues }
1932
- }), ul = async (e, t, n, r) => {
1942
+ }), ml = async (e, t, n, r) => {
1933
1943
  if (e.upsertWithOutcome === void 0) throw x("upsertRowOutcome: this store does not implement `upsertWithOutcome`. It is provided by the framework's store wrapper, so `ctx.store` has it; a hand-written DataStore must add it.");
1934
1944
  return e.upsertWithOutcome(t.tableName, n, {
1935
1945
  conflictColumns: r.conflictColumns,
1936
1946
  ...r.update === void 0 ? {} : { update: r.update },
1937
1947
  ...r.updateValues === void 0 ? {} : { updateValues: r.updateValues }
1938
1948
  });
1939
- }, dl = async (e, t, n, r) => e.insertIgnoreWithOutcome(t.tableName, n, { conflictColumns: r.conflictColumns }), fl = (e, t, n, r) => e.updateMany(t.tableName, n, { where: r.where }), pl = 512, ml = (e) => {
1949
+ }, hl = async (e, t, n, r) => e.insertIgnoreWithOutcome(t.tableName, n, { conflictColumns: r.conflictColumns }), gl = (e, t, n, r) => e.updateMany(t.tableName, n, { where: r.where }), _l = 512, vl = (e) => {
1940
1950
  e.setMaxListeners(512);
1941
- }, hl = (e, t, n) => ({
1951
+ }, yl = (e, t, n) => ({
1942
1952
  _tag: "PrimaryKeyConflictError",
1943
1953
  table: e,
1944
1954
  key: t,
1945
1955
  cause: n
1946
- }), gl = (e) => typeof e == "object" && !!e && e._tag === "PrimaryKeyConflictError", _l = {
1956
+ }), bl = (e) => typeof e == "object" && !!e && e._tag === "PrimaryKeyConflictError", xl = {
1947
1957
  postgres: 5432,
1948
1958
  mysql: 3306,
1949
1959
  mariadb: 3306,
1950
1960
  mssql: 1433
1951
- }, vl = /* @__PURE__ */ new Set([
1961
+ }, Sl = /* @__PURE__ */ new Set([
1952
1962
  "localhost",
1953
1963
  "127.0.0.1",
1954
1964
  "::1",
1955
1965
  "[::1]",
1956
1966
  "0.0.0.0"
1957
- ]), yl = (e) => {
1967
+ ]), Cl = (e) => {
1958
1968
  let t = e.host, n = e.port, r = e.database;
1959
1969
  if (e.url !== void 0 && e.url !== "") try {
1960
1970
  let i = new URL(e.url);
@@ -1963,29 +1973,29 @@ $voltro_branch$`;
1963
1973
  return;
1964
1974
  }
1965
1975
  if (t === void 0 || t === "" || r === void 0 || r === "") return;
1966
- let i = n ?? _l[(e.dialect ?? "").toLowerCase()];
1976
+ let i = n ?? xl[(e.dialect ?? "").toLowerCase()];
1967
1977
  if (i === void 0 || !Number.isFinite(i)) return;
1968
1978
  let a = t.toLowerCase();
1969
1979
  return {
1970
- host: vl.has(a) ? "localhost" : a,
1980
+ host: Sl.has(a) ? "localhost" : a,
1971
1981
  port: i,
1972
1982
  database: r.toLowerCase()
1973
1983
  };
1974
- }, bl = (e) => {
1975
- let t = yl(e);
1976
- if (t !== void 0) return Dr("sha256").update(`${t.host}\u0000${t.port}\u0000${t.database}`).digest("hex").slice(0, 32);
1977
- }, xl = (e, t) => e === void 0 || t === void 0 ? "unknown" : e === t ? "same" : "different", Sl = {
1984
+ }, wl = (e) => {
1985
+ let t = Cl(e);
1986
+ if (t !== void 0) return jr("sha256").update(`${t.host}\u0000${t.port}\u0000${t.database}`).digest("hex").slice(0, 32);
1987
+ }, Tl = (e, t) => e === void 0 || t === void 0 ? "unknown" : e === t ? "same" : "different", El = {
1978
1988
  app: 3,
1979
1989
  plugin: 2,
1980
1990
  framework: 1
1981
- }, Cl = /* @__PURE__ */ new Map(), wl = [], Tl = () => [...wl], El = (e) => {
1991
+ }, Dl = /* @__PURE__ */ new Map(), Ol = [], kl = () => [...Ol], Al = (e) => {
1982
1992
  if (!e.table || !e.timeColumn) throw Error("registerRetention: table + timeColumn are required");
1983
1993
  if (!Number.isFinite(e.ttlMs) || e.ttlMs <= 0) throw Error(`registerRetention(${e.table}): ttlMs must be a positive number`);
1984
- let t = e.source ?? "app", n = Cl.get(e.table);
1994
+ let t = e.source ?? "app", n = Dl.get(e.table);
1985
1995
  if (n !== void 0) {
1986
- let r = n.source ?? "app", i = n.ttlMs !== e.ttlMs || n.where !== void 0 != (e.where !== void 0);
1987
- if (Sl[t] < Sl[r]) {
1988
- i && wl.push({
1996
+ let r = n.source ?? "app", i = n.ttlMs !== e.ttlMs || n.timeColumn !== e.timeColumn || JSON.stringify(n.activityColumns ?? []) !== JSON.stringify(e.activityColumns ?? []) || JSON.stringify(n.where) !== JSON.stringify(e.where);
1997
+ if (El[t] < El[r]) {
1998
+ i && Ol.push({
1989
1999
  table: e.table,
1990
2000
  kept: {
1991
2001
  source: r,
@@ -1998,7 +2008,7 @@ $voltro_branch$`;
1998
2008
  });
1999
2009
  return;
2000
2010
  }
2001
- i && r !== t && wl.push({
2011
+ i && r !== t && Ol.push({
2002
2012
  table: e.table,
2003
2013
  kept: {
2004
2014
  source: t,
@@ -2010,59 +2020,59 @@ $voltro_branch$`;
2010
2020
  }
2011
2021
  });
2012
2022
  }
2013
- Cl.set(e.table, {
2023
+ Dl.set(e.table, {
2014
2024
  ...e,
2015
2025
  source: t
2016
2026
  });
2017
- }, Dl = () => [...Cl.values()], Ol = () => {
2018
- Cl.clear(), wl.length = 0;
2019
- }, kl = async (e, t, n, r = 2e4) => {
2020
- let i = new Date(t - e.ttlMs), a = 0;
2027
+ }, jl = () => [...Dl.values()], Ml = () => {
2028
+ Dl.clear(), Ol.length = 0;
2029
+ }, Nl = async (e, t, n, r = 2e4) => {
2030
+ let i = new Date(t - e.ttlMs), a = (e.activityColumns ?? []).map((e) => fr(Zn(e), qt(e, i))), o = a.length === 0 ? e.where : pt(...e.where === void 0 ? [] : [e.where], ...a), s = 0;
2021
2031
  try {
2022
2032
  for (;;) {
2023
- let t = await n(e.table, e.timeColumn, i, r, e.where);
2024
- if (a += t, t < r) break;
2033
+ let t = await n(e.table, e.timeColumn, i, r, o);
2034
+ if (s += t, t < r) break;
2025
2035
  }
2026
2036
  } catch (t) {
2027
- throw C.runSync(w.increment(w.tagged(jl, "table", e.table))), t;
2037
+ throw w.runSync(T.increment(T.tagged(Fl, "table", e.table))), t;
2028
2038
  }
2029
- return a > 0 && C.runSync(w.incrementBy(w.tagged(Al, "table", e.table), a)), a;
2030
- }, Al = w.counter("voltro_retention_swept_rows_total"), jl = w.counter("voltro_retention_sweep_errors_total"), Ml = (e, t) => {
2039
+ return s > 0 && w.runSync(T.incrementBy(T.tagged(Pl, "table", e.table), s)), s;
2040
+ }, Pl = T.counter("voltro_retention_swept_rows_total"), Fl = T.counter("voltro_retention_sweep_errors_total"), Il = (e, t) => {
2031
2041
  let n = Number(e ?? String(t));
2032
2042
  return (Number.isFinite(n) && n > 0 ? n : t) * 36e5;
2033
- }, Nl = "_voltro_cdc_offsets", Pl = h(Nl, {
2034
- id: f({ prefix: "cdcoff" }),
2035
- replicaId: y(),
2036
- streamName: y(),
2037
- binlogFile: y(),
2038
- binlogPosition: y(),
2043
+ }, Ll = "_voltro_cdc_offsets", Rl = ke(Ll, {
2044
+ id: y({ prefix: "cdcoff" }),
2045
+ replicaId: l(),
2046
+ streamName: l(),
2047
+ binlogFile: l(),
2048
+ binlogPosition: l(),
2039
2049
  updatedAt: b()
2040
- }).index(["replicaId"]), Fl = h(Nl, {
2041
- id: f({ prefix: "cdcoff" }),
2042
- replicaId: y(),
2043
- streamName: y(),
2044
- ctVersion: y(),
2050
+ }).index(["replicaId"]), zl = ke(Ll, {
2051
+ id: y({ prefix: "cdcoff" }),
2052
+ replicaId: l(),
2053
+ streamName: l(),
2054
+ ctVersion: l(),
2045
2055
  updatedAt: b()
2046
- }).index(["replicaId"]), Il = "_voltro_data_transfers", Ll = h(Il, {
2047
- id: f({ prefix: "dimp" }),
2056
+ }).index(["replicaId"]), Bl = "_voltro_data_transfers", Vl = ke(Bl, {
2057
+ id: y({ prefix: "dimp" }),
2048
2058
  startedAt: b().default("now"),
2049
2059
  finishedAt: b().nullable(),
2050
- direction: y().default("import"),
2051
- mode: y(),
2052
- via: y(),
2053
- bundle: y().nullable(),
2054
- sourceFingerprint: y().nullable(),
2055
- tablesWritten: er().default(0),
2056
- rowsWritten: er().default(0),
2057
- failure: y().nullable(),
2058
- staged: Pt().nullable()
2059
- }).renamedFrom("_voltro_data_imports").nonReactive(), Rl = (e) => {
2060
+ direction: l().default("import"),
2061
+ mode: l(),
2062
+ via: l(),
2063
+ bundle: l().nullable(),
2064
+ sourceFingerprint: l().nullable(),
2065
+ tablesWritten: fn().default(0),
2066
+ rowsWritten: fn().default(0),
2067
+ failure: l().nullable(),
2068
+ staged: Xt().nullable()
2069
+ }).renamedFrom("_voltro_data_imports").nonReactive(), Hl = (e) => {
2060
2070
  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)";
2061
2071
  return `${t} · ${r} · via ${e.via}${i}` + (e.bundle === null ? "" : ` · from ${e.bundle}`) + (e.sourceFingerprint === null ? "" : ` · source schema ${e.sourceFingerprint}`);
2062
- }, zl = 255, Bl = (e) => e == null ? "null" : typeof e == "string" || typeof e == "number" || typeof e == "boolean" ? JSON.stringify(e) : Array.isArray(e) ? `[${e.map(Bl).join(",")}]` : typeof e == "object" ? `{${Object.entries(e).filter(([, e]) => e !== void 0).sort(([e], [t]) => e < t ? -1 : +(e > t)).map(([e, t]) => `${JSON.stringify(e)}:${Bl(t)}`).join(",")}}` : JSON.stringify(String(e)), Vl = (e) => {
2072
+ }, Ul = 255, Wl = (e) => e == null ? "null" : typeof e == "string" || typeof e == "number" || typeof e == "boolean" ? JSON.stringify(e) : Array.isArray(e) ? `[${e.map(Wl).join(",")}]` : typeof e == "object" ? `{${Object.entries(e).filter(([, e]) => e !== void 0).sort(([e], [t]) => e < t ? -1 : +(e > t)).map(([e, t]) => `${JSON.stringify(e)}:${Wl(t)}`).join(",")}}` : JSON.stringify(String(e)), Gl = (e) => {
2063
2073
  if (e == null) return null;
2064
- let t = typeof e == "string" ? e : Bl(e);
2074
+ let t = typeof e == "string" ? e : Wl(e);
2065
2075
  return t.length > 255 ? t.slice(0, 255) : t;
2066
- }, Hl = "postgres";
2076
+ }, Kl = "postgres";
2067
2077
  //#endregion
2068
- export { Xe as AUTO_FILLED_COLUMNS, Rr as BOUND_ENCRYPTED_PREFIX, tl as BULK_INSERT_LIMITS, Y as BranchNameInvalid, ac as BranchTransitionInvalid, Nl as CDC_OFFSETS_TABLE, yo as CHANGE_CLAIM_TTL_ENV, pl as CHANGE_LISTENER_CEILING, Rn as ColumnBuilder, Il as DATA_TRANSFERS_TABLE, rr as DEFAULT_ACQUIRE_TIMEOUT_MS, bo as DEFAULT_CHANGE_CLAIM_TTL_HOURS, _s as DEFAULT_EAGER_FALLBACK_WARN_INTERVAL_MS, wt as DEFAULT_SOFT_DROP_RETENTION_DAYS, Oi as DEFAULT_SUBJECT_GRAPH_DEPTH, Lr as ENCRYPTED_PREFIX, Hl as ENGINE, Ki as EagerCardinalityError, r as FILE_MIGRATION_PATTERN, nr as FRAMEWORK_LIVE_TABLES, Vr as FieldDecryptionError, Bo as ID_COLUMN_MAX_LENGTH, _r as INITIAL_VERSION, tn as IrreversibleMigrationError, he as MATCHES_NO_ROWS, Se as MAX_IDENTIFIER_LENGTH, Te as MIGRATION_PHASES, Ps as MSSQL_TRANSIENT_NUMBERS, Ms as MYSQL_TRANSIENT_CODES, ke as MigrationExpectationFailed, Ie as MigrationNeedsSqlClient, re as MigrationSkipped, vo as OccurrenceCounter, Ns as POSTGRES_TRANSIENT_STATES, Bn as REPLACE_IN_PROGRESS_TABLE, fe as RewriteUnstableError, zl as SCOPE_KEY_MAX_LENGTH, At as SELF_REFERENCE_TARGET, Fs as SQLITE_TRANSIENT_CODES, vn as STAGING_STALE_MINUTES, Ge as STAGING_TABLE_PREFIX, Ar as SqlClient, qc as TENANT_SELECTIONS_TABLE, Is as TURSO_TRANSIENT_MESSAGE, qs as TableStreamError, ln as TenantNamespaceInvalid, o as TenantNamespaceUnresolved, wc as TenantRegionUnavailable, Cc as TenantResidencyUnresolved, Es as TransactionAbortedError, xe as TransactionBrokenByBodyError, Vs as VOLTRO_EXPIRES_MIXIN_ID, Us as VOLTRO_LOCAL_FIRST_MIXIN_ID, mr as VersionConflict, Ue as WARN_IDENTIFIER_LENGTH, un as _voltroApiKeysTable, Pl as _voltroCdcOffsetsTable, Ll as _voltroDataTransfersTable, Wn as _voltroDevicesTable, Mt as _voltroIdempotencyTable, zt as _voltroKvTable, Tn as _voltroMigrationPlansTable, mn as _voltroMigrationsTable, Fl as _voltroMssqlCdcOffsetsTable, Mn as _voltroReplaceInProgressTable, qt as _voltroReplicaObservationsTable, Ut as _voltroSchemaOwnerTable, gt as _voltroSeedsTable, Jn as _voltroTenantSelectionsTable, so as actorsTable, vc as admitBranch, u as agedSoftDropSnapshots, Hn as allEnumRenames, Ti as allRegisteredRelations, En as allRegisteredTables, ut as and, Wi as applyJsonPatch, fn as array, st as arrayContains, pt as arrayHas, ze as arrayOverlaps, Ji as attachEagerLoads, wo as attributionFields, Oo as attributionKey, Rc as auditAllTableIndexes, Lc as auditTableIndexes, x as authoredError, se as authoredMessageOf, tt as avg, ot as avgOver, Fo as beginLocalWrite, Kn as bigint, Mc as bindResidentStore, Pt as boolean, nc as branchNamespaceName, nl as bulkInsertLimitsFor, Vt as bytes, ye as causeBranches, fo as changeDelete, ho as changeDigest, lo as changeInsert, po as changeSoftDelete, uo as changeUpdate, il as chunkRowsForInsert, jo as claimPendingAttribution, An as classifyConstraintViolation, yn as clearEnumRenames, Ro as clearPendingAttribution, Di as clearRelationsRegistry, Oc as clearResidencyConfig, Ol as clearRetentions, hn as clearTableRegistry, qo as clearWriteRecorders, B as coercePredicateForSqlite, _ as coercePredicateValue, Fe as coercePredicateValues, $a as coerceValueForSqlite, e as collectSubqueries, ce as column, ni as columnSchema, rl as columnsPerRow, Je as compareDecimal, ia as compileEagerJson, Gi as compileJsonPatch, p as compilePredicate, tr as compileRawFragment, Qe as compileSelect, go as composeChangeKey, Qs as computeEmbedding, bl as connectionIdentity, Rt as contains, be as count, jn as countDistinct, Dn as crdtDoc, gn as crdtManagedColumns, Yt as crdtManagedColumnsOf, Gt as crdtText, Co as currentWriteAttribution, _e as databaseHandle, vt as date, Xn as dbEnum, ds as dbMetricTagCacheSizeForTests, ms as dbOperationsInFlight, cr as decimal, Pn as declareEnumRename, Kr as decodeFieldValue, me as decodeRowsForTable, we as decodeRowsFromSchema, Qr as decryptFieldsOnRead, Gc as defineMigration, sn as defineMixin, le as defineSeed, Zc as deleteTenantSelection, ft as denseRank, Fi as deriveSubjectGraph, Ee as deriveTypeIdPrefix, Uo as derivedRowId, Wo as derivedRowIdLength, Qn as describeAgedSoftDropSnapshots, ge as describeCharsetRefusal, dt as describeDriverError, ct as describeRowBindings, Rl as describeTransferRun, Ir as deserializeArraysOnRead, dr as drainIdentifierWarnings, Et as dropped, Wr as encodeFieldValue, We as encodeRowForSchema, Zr as encryptFieldsForWrite, Yr as encryptedColumnsOf, Io as endLocalWrite, hc as enforceBranchLimits, Jt as ensureTableRegistered, Un as eq, ne as escapeLike, bn as evaluatePredicate, lt as except, Fn as exists, Hs as expires, co as externalChangeEvent, mt as extractDbCause, zr as fieldBinding, $e as fireSchemaChangeSeeds, at as fireTenantCreateSeeds, Uc as formatIndexAuditIssue, Ii as formatSubjectGraph, or as frameworkTables, Ae as generateId, ie as generateSnowflake, ir as geography, qe as geometry, $t as getEnumRenames, wi as getRelation, Ci as getRelations, Dc as getResidencyConfig, Wt as getTable, en as gt, Ct as gte, ra as hasEagerLoads, Zs as hybridSearch, f as id, wn as inSet, zn as inSubquery, hi as inferForeignKey, dl as insertIgnoreRowOutcome, cl as insertManyRows, sl as insertRow, er as integer, Zt as interruptedReplaceRefusal, ht as intersect, Ze as interval, He as irreversible, ur as irreversibleReason, Br as isBoundCiphertext, rc as isBranchNamespace, Vi as isCompositeRowKey, ui as isEmptyRelationsSpec, Ur as isEncrypted, Hr as isFieldDecryptionError, s as isFileMigration, Be as isForeignKeyViolation, Ye as isFrameworkOwnedLiveTable, Gs as isLocalFirst, Kc as isMigrationDefinition, Ke as isMysqlFamily, lc as isNeonConnection, jt as isNotNull, pn as isNull, gl as isPrimaryKeyConflictError, t as isQueryTimeout, qr as isRawEncoding, Ac as isRegionServable, di as isRelationsSpec, oe as isSeedDefinition, v as isSoftDropSnapshotName, d as isSqliteFamily, m as isStagingTableName, _t as isTableReactive, ks as isTransactionAbortedError, zs as isTransientContention, fr as isView, te as json, qn as jsonField, ee as jsonIndex, Hi as jsonPatchAssignments, Ve as lag, n as lead, Tl as listRetentionConflicts, Dl as listRetentions, Ws as localFirst, Ks as localFirstTables, Ft as lt, Ht as lte, bs as makeEagerFallbackReporter, Sc as makeNamespaceBranchExecutor, Ds as makeTransactionAbortTracker, pi as many, mi as manyToMany, g as materializeFields, It as max, nt as migration, Vn as min, ol as missingConflictColumns, al as missingRequiredColumns, i as mixin, On as neq, oc as nextBranchState, yl as normaliseTarget, Ui as normalizeJsonPatchValue, _n as not, Xt as notExists, Kt as notInSet, yt as notInSubquery, Pe as numeric, gs as observeDbOp, xo as occurrenceWindowMs, fi as one, qi as oneCardinalityMessage, Zn as or, S as orderClausesOf, Nn as paginateBy, Qt as paginateById, _o as parseChangeKey, zo as pendingAttributionCount, pc as planBranch, sc as planBranchProvision, cc as planBranchTeardown, mc as planBranchTeardownFor, dc as planNeonBranchProvision, fc as planNeonBranchTeardown, pr as planVersionedUpdate, St as pluginRef, Cn as pluginRefSpecOf, hl as primaryKeyConflictError, gc as provisionBranch, Nc as provisionResidentTenant, an as qualifyTable, xt as queryFor, l as queryForView, $n as quoteIdent, ml as raiseChangeListenerCeiling, Sn as rank, cn as raw, Yc as readTenantSelection, a as readableByColumns, rn as real, hs as recordDbOp, Zo as recordsTable, De as reference, ei as refuseWrite, ro as registerCoreTables, Si as registerDiscoveredRelations, Ao as registerPendingAttribution, xi as registerRelations, El as registerRetention, Yn as registerTable, Go as registerWriteRecorder, li as relations, ao as requireActors, sr as requireTable, oo as requireTenants, us as resetDbMetricTagCacheForTests, pe as resetSnowflake, jc as residentPlacement, Mr as resolveActorSnapshot, uc as resolveBranchMechanism, ys as resolveEagerFallbackWarnIntervalMs, Lo as resolveEchoAttribution, Ln as resolveFullTextIndex, Le as resolveIdScheme, nn as resolveMixinGraph, kc as resolveTenantHome, Oe as resolveTenantNamespace, Ml as retentionTtlMsFromEnv, zi as rowKeyColumns, Bi as rowKeyIdentity, kt as rowNumber, ri as rowSchema, Ts as runRetryingTransaction, Os as runSavepoint, js as runStoreTransaction, So as runWithWriteAttribution, Qo as runWriteRecorders, xl as sameDatabase, Me as sanitizeIdentifierFragment, Vl as scopeKeyOf, je as selfReference, Fr as serializeArraysForWrite, Re as serverOnlyColumns, Ec as setResidencyConfig, ve as setSchemaChangeSeedHook, kn as setTenantCreateSeedHook, xs as settleTransactionExit, gr as settleVersionedUpdate, on as softDropSnapshotStamp, lr as spatialPredicate, bt as stagingLeftoverReport, xn as stagingLeftovers, In as stagingNamesOf, Ot as stagingStaleAfterMs, $c as stampGeneratedId, el as stampGeneratedIds, Dt as startsWith, ti as storeRefusalOf, Xs as streamTable, dn as sum, Gn as sumOver, Jo as suspendWriteRecorders, Yo as suspendWriteRecordersEffect, kl as sweepRetention, h as table, _c as teardownBranch, Jc as tenantSelectionId, y as text, b as timestamp, yr as timestampMs, hr as timestampMsOrNull, ws as transactionRetrySchedule, Nt as union, Bt as unionAll, Tt as unregisterTable, Ko as unregisterWriteRecorder, fl as updateManyRow, ll as upsertRow, ul as upsertRowOutcome, Ri as upsertUpdatePatch, Li as upsertUpdateValues, c as validateColumnName, rt as validateIndexName, Ei as validateRegisteredRelations, vi as validateRelationConfig, ue as validateTableName, et as validateTypeIdPrefix, Ce as vector, Ne as vectorDistanceToOpclass, $s as vectorEmbedding, vr as versionColumnOf, it as view, de as viewSql, ar as walkLeaves, Lt as wireSafeCause, To as withCapturedAttribution, Xo as writeRecordersSuspended, Xc as writeTenantSelection };
2078
+ export { i as AUTO_FILLED_COLUMNS, Hr as BOUND_ENCRYPTED_PREFIX, al as BULK_INSERT_LIMITS, Y as BranchNameInvalid, lc as BranchTransitionInvalid, Ll as CDC_OFFSETS_TABLE, Co as CHANGE_CLAIM_TTL_ENV, _l as CHANGE_LISTENER_CEILING, Kt as ColumnBuilder, Bl as DATA_TRANSFERS_TABLE, te as DEFAULT_ACQUIRE_TIMEOUT_MS, wo as DEFAULT_CHANGE_CLAIM_TTL_HOURS, xs as DEFAULT_EAGER_FALLBACK_WARN_INTERVAL_MS, ar as DEFAULT_SOFT_DROP_RETENTION_DAYS, ji as DEFAULT_SUBJECT_GRAPH_DEPTH, Vr as ENCRYPTED_PREFIX, Kl as ENGINE, Yi as EagerCardinalityError, sn as FILE_MIGRATION_PATTERN, Xe as FRAMEWORK_LIVE_TABLES, Gr as FieldDecryptionError, Go as ID_COLUMN_MAX_LENGTH, xr as INITIAL_VERSION, Oe as IrreversibleMigrationError, gt as MATCHES_NO_ROWS, fe as MAX_IDENTIFIER_LENGTH, Me as MIGRATION_PHASES, Rs as MSSQL_TRANSIENT_NUMBERS, Is as MYSQL_TRANSIENT_CODES, ze as MigrationExpectationFailed, ie as MigrationNeedsSqlClient, he as MigrationSkipped, So as OccurrenceCounter, Ls as POSTGRES_TRANSIENT_STATES, Wn as REPLACE_IN_PROGRESS_TABLE, we as RewriteUnstableError, Ul as SCOPE_KEY_MAX_LENGTH, Mn as SELF_REFERENCE_TARGET, zs as SQLITE_TRANSIENT_CODES, Sn as STAGING_STALE_MINUTES, d as STAGING_TABLE_PREFIX, Pr as SqlClient, Zc as TENANT_SELECTIONS_TABLE, Bs as TURSO_TRANSIENT_MESSAGE, Zs as TableStreamError, un as TenantNamespaceInvalid, je as TenantNamespaceUnresolved, Oc as TenantRegionUnavailable, Dc as TenantResidencyUnresolved, As as TransactionAbortedError, Ke as TransactionBrokenByBodyError, Gs as VOLTRO_EXPIRES_MIXIN_ID, qs as VOLTRO_LOCAL_FIRST_MIXIN_ID, vr as VersionConflict, at as WARN_IDENTIFIER_LENGTH, mn as _voltroApiKeysTable, Rl as _voltroCdcOffsetsTable, Vl as _voltroDataTransfersTable, Jn as _voltroDevicesTable, Lt as _voltroIdempotencyTable, Wt as _voltroKvTable, An as _voltroMigrationPlansTable, vn as _voltroMigrationsTable, zl as _voltroMssqlCdcOffsetsTable, Qt as _voltroPluginMigrationsTable, Ln as _voltroReplaceInProgressTable, Jt as _voltroReplicaObservationsTable, xt as _voltroSchemaOwnerTable, Qn as _voltroSeedsTable, lr as _voltroTenantSelectionsTable, fo as actorsTable, Sc as admitBranch, nr as agedSoftDropSnapshots, On as allEnumRenames, Oi as allRegisteredRelations, $n as allRegisteredTables, pt as and, qi as applyJsonPatch, bn as array, vt as arrayContains, Ue as arrayHas, e as arrayOverlaps, Zi as attachEagerLoads, ko as attributionFields, No as attributionKey, Hc as auditAllTableIndexes, Vc as auditTableIndexes, x as authoredError, mt as authoredMessageOf, be as avg, _t as avgOver, Bo as beginLocalWrite, en as bigint, Ic as bindResidentStore, Xt as boolean, oc as branchNamespaceName, ol as bulkInsertLimitsFor, Ct as bytes, yt as causeBranches, go as changeDelete, yo as changeDigest, mo as changeInsert, _o as changeSoftDelete, ho as changeUpdate, cl as chunkRowsForInsert, Io as claimPendingAttribution, We as classifyConstraintViolation, Hn as clearEnumRenames, Uo as clearPendingAttribution, Ai as clearRelationsRegistry, Mc as clearResidencyConfig, Ml as clearRetentions, ur as clearTableRegistry, Qo as clearWriteRecorders, B as coercePredicateForSqlite, pn as coercePredicateValue, o as coercePredicateValues, De as coerceValueForSqlite, Ut as collectSubqueries, ht as column, Ye as columnRef, oi as columnSchema, sl as columnsPerRow, m as compareDecimal, sa as compileEagerJson, Ji as compileJsonPatch, C as compilePredicate, rt as compileRawFragment, re as compileRowProjection, v as compileSelect, bo as composeChangeKey, nc as computeEmbedding, wl as connectionIdentity, qn as contains, bt as count, Ge as countDistinct, er as crdtDoc, dr as crdtManagedColumns, jt as crdtManagedColumnsOf, sr as crdtText, Oo as currentWriteAttribution, n as databaseHandle, Qe as date, p as dbEnum, hs as dbMetricTagCacheSizeForTests, vs as dbOperationsInFlight, ir as decimal, Ft as declareEnumRename, Xr as decodeFieldValue, lt as decodeRowsForTable, me as decodeRowsFromSchema, ni as decryptFieldsOnRead, Yc as defineMigration, Be as defineMixin, it as defineSeed, tl as deleteTenantSelection, Vt as denseRank, Ri as deriveSubjectGraph, Te as deriveTypeIdPrefix, Jo as derivedRowId, Yo as derivedRowIdLength, et as describeAgedSoftDropSnapshots, t as describeCharsetRefusal, Ht as describeDriverError, Kn as describeRowBindings, Hl as describeTransferRun, Br as deserializeArraysOnRead, dt as drainIdentifierWarnings, nt as dropped, Jr as encodeFieldValue, ot as encodeRowForSchema, ti as encryptFieldsForWrite, $r as encryptedColumnsOf, Vo as endLocalWrite, yc as enforceBranchLimits, At as ensureTableRegistered, Tn as eq, Re as escapeLike, Bn as evaluatePredicate, Gn as except, on as exists, Ks as expires, po as externalChangeEvent, wn as extractDbCause, Ur as fieldBinding, ut as fireSchemaChangeSeeds, ce as fireTenantCreateSeeds, qc as formatIndexAuditIssue, zi as formatSubjectGraph, kt as frameworkTables, qe as generateId, c as generateSnowflake, ne as geography, _ as geometry, gn as getEnumRenames, Di as getRelation, Ei as getRelations, jc as getResidencyConfig, or as getTable, Ot as gt, kn as gte, oa as hasEagerLoads, tc as hybridSearch, y as id, Un as inSet, It as inSubquery, k as inferForeignKey, hl as insertIgnoreRowOutcome, fl as insertManyRows, dl as insertRow, fn as integer, nn as interruptedReplaceRefusal, Cn as intersect, a as interval, pr as irreversible, s as irreversibleReason, Wr as isBoundCiphertext, sc as isBranchNamespace, gr as isColumnReference, Wi as isCompositeRowKey, mi as isEmptyRelationsSpec, qr as isEncrypted, Kr as isFieldDecryptionError, st as isFileMigration, zn as isForeignKeyViolation, ee as isFrameworkOwnedLiveTable, Ys as isLocalFirst, Xc as isMigrationDefinition, g as isMysqlFamily, pc as isNeonConnection, _n as isNotNull, Zn as isNull, bl as isPrimaryKeyConflictError, an as isQueryTimeout, Zr as isRawEncoding, Pc as isRegionServable, hi as isRelationsSpec, xe as isSeedDefinition, h as isSoftDropSnapshotName, Le as isSqliteFamily, Ie as isStagingTableName, Ze as isTableReactive, Ns as isTransactionAbortedError, Us as isTransientContention, ft as isView, ln as json, Bt as jsonField, cn as jsonIndex, Gi as jsonPatchAssignments, Rn as lag, rn as lead, kl as listRetentionConflicts, jl as listRetentions, Js as localFirst, Xs as localFirstTables, qt as lt, Nn as lte, ws as makeEagerFallbackReporter, Ec as makeNamespaceBranchExecutor, js as makeTransactionAbortTracker, _i as many, vi as manyToMany, Ae as materializeFields, Et as max, de as migration, Dn as min, ul as missingConflictColumns, ll as missingRequiredColumns, ae as mixin, xn as neq, uc as nextBranchState, Cl as normaliseTarget, Ki as normalizeJsonPatchValue, tn as not, Zt as notExists, wt as notInSet, tr as notInSubquery, Pe as numeric, bs as observeDbOp, To as occurrenceWindowMs, gi as one, Xi as oneCardinalityMessage, fr as or, S as orderClausesOf, Pt as paginateBy, hn as paginateById, xo as parseChangeKey, Wo as pendingAttributionCount, _c as planBranch, dc as planBranchProvision, fc as planBranchTeardown, vc as planBranchTeardownFor, hc as planNeonBranchProvision, gc as planNeonBranchTeardown, _r as planVersionedUpdate, Xn as pluginRef, zt as pluginRefSpecOf, yl as primaryKeyConflictError, bc as provisionBranch, Lc as provisionResidentTenant, Fe as qualifyTable, Yn as queryFor, ue as queryForView, dn as quoteIdent, vl as raiseChangeListenerCeiling, Rt as rank, Ve as raw, $c as readTenantSelection, oe as readableByColumns, _e as real, ys as recordDbOp, ns as recordsTable, Ee as reference, ii as refuseWrite, so as registerCoreTables, Ti as registerDiscoveredRelations, Fo as registerPendingAttribution, wi as registerRelations, Al as registerRetention, f as registerTable, Xo as registerWriteRecorder, pi as relations, lo as requireActors, rr as requireTable, uo as requireTenants, ms as resetDbMetricTagCacheForTests, ct as resetSnowflake, Fc as residentPlacement, Ir as resolveActorSnapshot, mc as resolveBranchMechanism, Cs as resolveEagerFallbackWarnIntervalMs, Ho as resolveEchoAttribution, Gt as resolveFullTextIndex, mr as resolveIdScheme, ge as resolveMixinGraph, Nc as resolveTenantHome, He as resolveTenantNamespace, Il as retentionTtlMsFromEnv, Hi as rowKeyColumns, Ui as rowKeyIdentity, jn as rowNumber, si as rowSchema, ks as runRetryingTransaction, Ms as runSavepoint, Fs as runStoreTransaction, Do as runWithWriteAttribution, rs as runWriteRecorders, Tl as sameDatabase, se as sanitizeIdentifierFragment, Gl as scopeKeyOf, Je as selfReference, zr as serializeArraysForWrite, hr as serverOnlyColumns, Ac as setResidencyConfig, Pn as setSchemaChangeSeedHook, ve as setTenantCreateSeedHook, Ts as settleTransactionExit, br as settleVersionedUpdate, r as softDropSnapshotStamp, Mt as spatialPredicate, Tt as stagingLeftoverReport, En as stagingLeftovers, Vn as stagingNamesOf, Nt as stagingStaleAfterMs, rl as stampGeneratedId, il as stampGeneratedIds, cr as startsWith, ai as storeRefusalOf, ec as streamTable, yn as sum, $t as sumOver, $o as suspendWriteRecorders, es as suspendWriteRecordersEffect, Nl as sweepRetention, ke as table, xc as teardownBranch, Qc as tenantSelectionId, l as text, b as timestamp, Cr as timestampMs, yr as timestampMsOrNull, Os as transactionRetrySchedule, Yt as union, St as unionAll, tt as unregisterTable, Zo as unregisterWriteRecorder, gl as updateManyRow, pl as upsertRow, ml as upsertRowOutcome, Vi as upsertUpdatePatch, Bi as upsertUpdateValues, le as validateColumnName, Se as validateIndexName, ki as validateRegisteredRelations, xi as validateRelationConfig, Fn as validateTableName, ye as validateTypeIdPrefix, pe as vector, Ne as vectorDistanceToOpclass, rc as vectorEmbedding, Sr as versionColumnOf, Ce as view, In as viewSql, $e as walkLeaves, Dt as wireSafeCause, Ao as withCapturedAttribution, ts as writeRecordersSuspended, el as writeTenantSelection };