@voltro/database 0.34.0 → 0.36.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, A as t, At as n, B as r, Bt as i, C as a, Ct as o, D as s, Dt as c, E as l, Et as u, F as d, Ft as f, G as p, Gt as m, H as h, Ht as g, I as _, It as v, J as y, Jt as b, K as x, Kt as S, L as ee, Lt as C, M as te, Mt as ne, N as re, Nt as ie, O as ae, Ot as oe, P as se, Pt as ce, Q as le, R as ue, Rt as de, S as fe, St as pe, T as me, Tt as he, U as ge, Ut as _e, V as ve, Vt as ye, W as be, Wt as xe, X as Se, Y as Ce, Yt as we, Z as Te, _ as Ee, _t as De, a as Oe, at as ke, b as Ae, bt as je, c as Me, ct as Ne, d as Pe, dt as Fe, et as w, f as Ie, ft as Le, g as Re, gt as ze, h as Be, ht as Ve, i as He, it as Ue, j as T, jt as We, k as Ge, kt as Ke, l as qe, lt as Je, m as Ye, mt as Xe, n as Ze, nt as Qe, o as $e, ot as et, p as E, pt as tt, q as nt, qt as D, rt, s as it, st as at, t as ot, tt as st, u as ct, ut as lt, v as ut, vt as dt, w as ft, wt as pt, x as mt, xt as ht, y as gt, yt as _t, z as vt, zt as O } from "./frameworkLiveTables-CeuTYhWm.js";
2
- import { timestampMs as yt, timestampMsOrNull as bt } from "./wire.js";
3
- import { Cause as xt, Chunk as St, Data as Ct, Effect as k, Exit as wt, Metric as A, MetricBoundaries as Tt, Option as j, Schedule as Et, Schema as M, Stream as Dt } from "effect";
4
- import { AsyncLocalStorage as Ot } from "node:async_hooks";
5
- import { TransactionConnection as kt } from "@effect/sql/SqlClient";
6
- import { ansi as N } from "@voltro/logger";
7
- import { SqlClient as At } from "@effect/sql";
8
- import { createHash as jt } from "node:crypto";
1
+ import { $ as e, A as t, At as n, B as r, Bt as i, C as a, Ct as o, D as s, Dt as c, E as l, Et as u, F as d, Ft as f, G as p, Gt as m, H as h, Ht as g, I as _, It as v, J as y, Jt as b, K as ee, Kt as x, L as te, Lt as S, M as ne, Mt as re, N as ie, Nt as ae, O as oe, Ot as se, P as ce, Pt as le, Q as ue, R as de, Rt as fe, S as pe, St as me, T as he, Tt as ge, U as _e, Ut as ve, V as ye, Vt as be, W as xe, Wt as Se, X as Ce, Y as we, Yt as Te, Z as Ee, _ as De, _t as Oe, a as ke, at as Ae, b as je, bt as Me, c as Ne, ct as Pe, d as Fe, dt as Ie, et as C, f as Le, ft as Re, g as ze, gt as Be, h as Ve, ht as He, i as Ue, it as We, j as w, jt as Ge, k as Ke, kt as qe, l as Je, lt as Ye, m as Xe, mt as Ze, n as Qe, nt as $e, o as et, ot as tt, p as T, pt as nt, q as rt, qt as E, rt as it, s as at, st as ot, t as st, tt as ct, u as lt, ut, v as dt, vt as ft, w as pt, wt as mt, x as ht, xt as gt, y as _t, yt as vt, z as yt, zt as D } from "./frameworkLiveTables-CeuTYhWm.js";
2
+ import { timestampMs as bt, timestampMsOrNull as xt } from "./wire.js";
3
+ import { Cause as St, Chunk as Ct, Data as wt, Effect as O, Exit as Tt, Metric as k, MetricBoundaries as Et, Option as A, Schedule as Dt, Schema as j, Stream as Ot } from "effect";
4
+ import { AsyncLocalStorage as kt } from "node:async_hooks";
5
+ import { TransactionConnection as At } from "@effect/sql/SqlClient";
6
+ import { ansi as M } from "@voltro/logger";
7
+ import { SqlClient as jt } from "@effect/sql";
8
+ import { createHash as Mt } from "node:crypto";
9
9
  //#region src/actorSnapshot.ts
10
- var Mt = (e) => typeof e == "string" && e !== "" ? e : null, Nt = async (e, t, n) => {
10
+ var Nt = (e) => typeof e == "string" && e !== "" ? e : null, Pt = 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 Mt = (e) => typeof e == "string" && e !== "" ? e : null, Nt = async (e, t, n
23
23
  }))[0];
24
24
  return r === void 0 ? void 0 : {
25
25
  id: t,
26
- type: Mt(r.kind) ?? n,
27
- displayName: Mt(r.displayName),
28
- email: Mt(r.email)
26
+ type: Nt(r.kind) ?? n,
27
+ displayName: Nt(r.displayName),
28
+ email: Nt(r.email)
29
29
  };
30
30
  } catch {
31
31
  return;
32
32
  }
33
- }, Pt = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqlite", Ft = (e) => {
33
+ }, Ft = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqlite", It = (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
- }, It = (e, t, n) => {
38
- if (!Pt(n) || !t) return e;
39
- let r = Ft(t);
37
+ }, Lt = (e, t, n) => {
38
+ if (!Ft(n) || !t) return e;
39
+ let r = It(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 Mt = (e) => typeof e == "string" && e !== "" ? e : null, Nt = async (e, t, n
44
44
  Array.isArray(t) && (i[e] = JSON.stringify(t));
45
45
  }
46
46
  return i;
47
- }, Lt = (e, t, n) => {
48
- if (!Pt(n) || !t) return e;
49
- let r = Ft(t);
47
+ }, Rt = (e, t, n) => {
48
+ if (!Ft(n) || !t) return e;
49
+ let r = It(t);
50
50
  return r.length === 0 ? e : e.map((e) => {
51
51
  let t;
52
52
  for (let n of r) {
@@ -58,7 +58,7 @@ var Mt = (e) => typeof e == "string" && e !== "" ? e : null, Nt = async (e, t, n
58
58
  }
59
59
  return t ?? e;
60
60
  });
61
- }, Rt = "enc:v1:", zt = class extends Error {
61
+ }, zt = "enc:v1:", Bt = class extends Error {
62
62
  _tag = "FieldDecryptionError";
63
63
  table;
64
64
  column;
@@ -66,33 +66,33 @@ var Mt = (e) => typeof e == "string" && e !== "" ? e : null, Nt = async (e, t, n
66
66
  constructor(e) {
67
67
  super(`column "${e.table}.${e.column}" is .encrypted() but could not be decrypted (${e.reason}) — the stored value was most likely encrypted under a different key`), this.name = "FieldDecryptionError", this.table = e.table, this.column = e.column, this.reason = e.reason;
68
68
  }
69
- }, Bt = (e) => typeof e == "object" && !!e && e._tag === "FieldDecryptionError", Vt = (e) => typeof e == "string" && e.startsWith("enc:v1:"), Ht = (e) => {
69
+ }, Vt = (e) => typeof e == "object" && !!e && e._tag === "FieldDecryptionError", Ht = (e) => typeof e == "string" && e.startsWith("enc:v1:"), Ut = (e) => {
70
70
  let t = [];
71
71
  for (let [n, r] of Object.entries(e.fields)) r.encrypted === !0 && t.push(n);
72
72
  return t;
73
- }, Ut = (e, t, n) => {
73
+ }, Wt = (e, t, n) => {
74
74
  if (!t) return e;
75
- let r = Ht(t);
75
+ let r = Ut(t);
76
76
  if (r.length === 0) return e;
77
77
  let i = { ...e };
78
78
  for (let e of r) {
79
79
  let r = i[e];
80
- if (!(r == null || Vt(r))) {
80
+ if (!(r == null || Ht(r))) {
81
81
  if (!n) throw Error(`column "${t.tableName ?? "?"}.${e}" is .encrypted() but no field cipher is registered — wire @voltro/plugin-governance's fieldEncryption (key via the Secrets-Resolver)`);
82
82
  i[e] = n.encrypt(JSON.stringify(r));
83
83
  }
84
84
  }
85
85
  return i;
86
- }, Wt = (e, t, n, r) => {
86
+ }, Gt = (e, t, n, r) => {
87
87
  if (!t) return e;
88
- let i = Ht(t);
88
+ let i = Ut(t);
89
89
  if (i.length === 0 || !n) return e;
90
90
  let a = r?.onError ?? "throw", o = t.tableName ?? "?";
91
91
  return e.map((e) => {
92
92
  let t;
93
93
  for (let s of i) {
94
94
  let i = e[s];
95
- if (Vt(i)) {
95
+ if (Ht(i)) {
96
96
  t ??= { ...e };
97
97
  try {
98
98
  t[s] = JSON.parse(n.decrypt(i));
@@ -106,7 +106,7 @@ var Mt = (e) => typeof e == "string" && e !== "" ? e : null, Nt = async (e, t, n
106
106
  });
107
107
  continue;
108
108
  }
109
- throw new zt({
109
+ throw new Bt({
110
110
  table: o,
111
111
  column: s,
112
112
  reason: n
@@ -116,62 +116,62 @@ var Mt = (e) => typeof e == "string" && e !== "" ? e : null, Nt = async (e, t, n
116
116
  }
117
117
  return t ?? e;
118
118
  });
119
- }, Gt = (e) => {
119
+ }, Kt = (e) => {
120
120
  let t = (() => {
121
121
  switch (e.type) {
122
122
  case "id":
123
123
  case "reference":
124
124
  case "text":
125
- case "enum": return M.String;
125
+ case "enum": return j.String;
126
126
  case "integer":
127
127
  case "real":
128
- case "decimal": return M.Number;
129
- case "boolean": return M.Boolean;
128
+ case "decimal": return j.Number;
129
+ case "boolean": return j.Boolean;
130
130
  case "timestamp":
131
- case "date": return yt;
132
- case "bigint": return M.BigInt;
133
- case "bytes": return M.Uint8ArrayFromBase64;
134
- case "array": return M.Array(M.Unknown);
135
- case "interval": return M.String;
136
- default: return M.Unknown;
131
+ case "date": return bt;
132
+ case "bigint": return j.BigInt;
133
+ case "bytes": return j.Uint8ArrayFromBase64;
134
+ case "array": return j.Array(j.Unknown);
135
+ case "interval": return j.String;
136
+ default: return j.Unknown;
137
137
  }
138
138
  })();
139
- return e.nullable === !0 ? M.NullOr(t) : t;
140
- }, Kt = (e, t) => {
139
+ return e.nullable === !0 ? j.NullOr(t) : t;
140
+ }, qt = (e, t) => {
141
141
  let n = new Set(t?.omit ?? []), r = {};
142
- for (let [t, i] of Object.entries(e.fields)) n.has(t) || (r[t] = Gt(i));
143
- return M.Struct(r);
144
- }, qt = (e) => typeof e == "function" ? e : () => e, Jt = (e, t) => ({
142
+ for (let [t, i] of Object.entries(e.fields)) n.has(t) || (r[t] = Kt(i));
143
+ return j.Struct(r);
144
+ }, Jt = (e) => typeof e == "function" ? e : () => e, Yt = (e, t) => ({
145
145
  kind: "one",
146
- target: qt(e),
146
+ target: Jt(e),
147
147
  ...t?.foreignKey === void 0 ? {} : { foreignKey: t.foreignKey },
148
148
  ...t?.sourceKey === void 0 ? {} : { sourceKey: t.sourceKey }
149
- }), Yt = (e, t) => ({
149
+ }), Xt = (e, t) => ({
150
150
  kind: "many",
151
- target: qt(e),
151
+ target: Jt(e),
152
152
  ...t?.foreignKey === void 0 ? {} : { foreignKey: t.foreignKey },
153
153
  ...t?.sourceKey === void 0 ? {} : { sourceKey: t.sourceKey }
154
- }), Xt = (e, t) => ({
154
+ }), Zt = (e, t) => ({
155
155
  kind: "manyToMany",
156
- target: qt(e),
157
- through: qt(t.through),
156
+ target: Jt(e),
157
+ through: Jt(t.through),
158
158
  sourceKey: t.sourceKey,
159
159
  targetKey: t.targetKey
160
- }), Zt = {
161
- one: Jt,
162
- many: Yt,
163
- manyToMany: Xt
164
- }, Qt = (e, t) => {
160
+ }), Qt = {
161
+ one: Yt,
162
+ many: Xt,
163
+ manyToMany: Zt
164
+ }, $t = (e, t) => {
165
165
  let n = typeof e == "function" ? e : () => e;
166
166
  return {
167
167
  source: n,
168
- relations: t(Zt, n())
168
+ relations: t(Qt, n())
169
169
  };
170
- }, $t = (e) => {
170
+ }, en = (e) => {
171
171
  if (typeof e != "object" || !e) return !1;
172
172
  let t = e;
173
173
  return typeof t.source != "function" || typeof t.relations != "object" || t.relations === null ? !1 : Object.keys(t.relations).length === 0;
174
- }, en = (e) => {
174
+ }, tn = (e) => {
175
175
  if (typeof e != "object" || !e) return !1;
176
176
  let t = e;
177
177
  if (typeof t.source != "function" || typeof t.relations != "object" || t.relations === null) return !1;
@@ -180,29 +180,29 @@ var Mt = (e) => typeof e == "string" && e !== "" ? e : null, Nt = async (e, t, n
180
180
  let t = e?.kind;
181
181
  return t === "one" || t === "many" || t === "manyToMany";
182
182
  });
183
- }, tn = Jt, nn = Yt, rn = Xt, an = (e, t, n) => {
183
+ }, nn = Yt, rn = Xt, an = Zt, on = (e, t, n) => {
184
184
  let r = [];
185
185
  for (let [n, i] of Object.entries(e.fields)) i.type === "reference" && i.references?.()?.tableName === t && r.push(n);
186
186
  if (r.length === 0) throw Error(`relation '${n}': no reference() column on '${e.tableName}' points at '${t}'. Either add one or pass an explicit { foreignKey: '<column>' }.`);
187
187
  if (r.length > 1) throw Error(`relation '${n}': multiple reference() columns on '${e.tableName}' point at '${t}' (${r.join(", ")}). Pass an explicit { foreignKey: '<column>' } to disambiguate.`);
188
188
  return r[0];
189
- }, on = (e) => Object.keys(e.fields), sn = (e, t) => Object.prototype.hasOwnProperty.call(e.fields, t), cn = (e) => {
190
- let t = on(e);
189
+ }, sn = (e) => Object.keys(e.fields), N = (e, t) => Object.prototype.hasOwnProperty.call(e.fields, t), cn = (e) => {
190
+ let t = sn(e);
191
191
  return t.length === 0 ? "<none>" : t.join(", ");
192
192
  }, ln = (e, t, n) => {
193
193
  let r = `relation '${t}' on '${e.tableName}'`, i = n.target();
194
194
  if (n.kind === "manyToMany") {
195
195
  let t = n.through();
196
- for (let [a, o] of [["sourceKey", n.sourceKey], ["targetKey", n.targetKey]]) if (!sn(t, o)) throw Error(`${r}: manyToMany ${a} '${o}' is not a column on the junction table '${t.tableName}'. Both keys name columns on the JUNCTION — ${a === "sourceKey" ? `sourceKey points at '${e.tableName}'` : `targetKey points at '${i.tableName}'`}. Columns on '${t.tableName}': ${cn(t)}.`);
196
+ for (let [a, o] of [["sourceKey", n.sourceKey], ["targetKey", n.targetKey]]) if (!N(t, o)) throw Error(`${r}: manyToMany ${a} '${o}' is not a column on the junction table '${t.tableName}'. Both keys name columns on the JUNCTION — ${a === "sourceKey" ? `sourceKey points at '${e.tableName}'` : `targetKey points at '${i.tableName}'`}. Columns on '${t.tableName}': ${cn(t)}.`);
197
197
  return;
198
198
  }
199
199
  if (n.sourceKey !== void 0 && n.foreignKey !== void 0) throw Error(`${r}: pass EITHER sourceKey OR foreignKey, not both. sourceKey '${n.sourceKey}' names a column on the source ('${e.tableName}') holding the target's id; foreignKey '${n.foreignKey}' names a column on the target ('${i.tableName}') holding the source's id. With both, foreignKey is ignored.`);
200
- if (n.sourceKey !== void 0 && !sn(e, n.sourceKey)) {
201
- let t = sn(i, n.sourceKey);
200
+ if (n.sourceKey !== void 0 && !N(e, n.sourceKey)) {
201
+ let t = N(i, n.sourceKey);
202
202
  throw Error(`${r}: sourceKey '${n.sourceKey}' is not a column on the source table '${e.tableName}'.` + (t ? ` It IS a column on the target '${i.tableName}' — you probably want { foreignKey: '${n.sourceKey}' }, which names the column on the TARGET that holds this table's id.` : ` Columns on '${e.tableName}': ${cn(e)}.`));
203
203
  }
204
- if (n.foreignKey !== void 0 && !sn(i, n.foreignKey)) {
205
- let t = sn(e, n.foreignKey);
204
+ if (n.foreignKey !== void 0 && !N(i, n.foreignKey)) {
205
+ let t = N(e, n.foreignKey);
206
206
  throw Error(`${r}: foreignKey '${n.foreignKey}' is not a column on the target table '${i.tableName}'.` + (t ? ` It IS a column on the source '${e.tableName}' — you want { sourceKey: '${n.foreignKey}' }. foreignKey names the column on the TARGET that points back at this table; sourceKey names the column on THIS table that holds the target's id.` : ` Columns on '${i.tableName}': ${cn(i)}.`));
207
207
  }
208
208
  }, un = Symbol.for("@voltro/database/relationsRegistry"), dn = globalThis, P = dn[un] ?? (dn[un] = /* @__PURE__ */ new Map()), fn = (e) => {
@@ -220,7 +220,7 @@ var Mt = (e) => typeof e == "string" && e !== "" ? e : null, Nt = async (e, t, n
220
220
  }
221
221
  }, pn = (e) => {
222
222
  let t = 0;
223
- for (let n of Object.values(e)) en(n) && (fn(n), t += 1);
223
+ for (let n of Object.values(e)) tn(n) && (fn(n), t += 1);
224
224
  return t;
225
225
  }, mn = (e) => {
226
226
  let t = P.get(e);
@@ -459,15 +459,15 @@ var Mt = (e) => typeof e == "string" && e !== "" ? e : null, Nt = async (e, t, n
459
459
  }, Bn = async (e, t, n, r, i, a) => {
460
460
  let o = n.target(), s = n.sourceKey ?? Wn(i, o.tableName);
461
461
  if (s !== void 0) {
462
- let n = F(e, s), i = n.length === 0 ? [] : await Gn(o, "id", n, r, a), c = new Map(i.map((e) => [e.id, e]));
462
+ let n = Gn(e, s), i = n.length === 0 ? [] : await Kn(o, "id", n, r, a), c = new Map(i.map((e) => [e.id, e]));
463
463
  for (let n of e) {
464
464
  let e = n[s];
465
465
  n[t] = e == null ? null : c.get(e) ?? null;
466
466
  }
467
- await Kn(i, r.with, o, a);
467
+ await qn(i, r.with, o, a);
468
468
  return;
469
469
  }
470
- let c = n.foreignKey ?? an(o, i.tableName, t), l = n.sourceKey ?? "id", u = F(e, l), d = u.length === 0 ? [] : await Gn(o, c, u, r, a), f = /* @__PURE__ */ new Map();
470
+ let c = n.foreignKey ?? on(o, i.tableName, t), l = n.sourceKey ?? "id", u = Gn(e, l), d = u.length === 0 ? [] : await Kn(o, c, u, r, a), f = /* @__PURE__ */ new Map();
471
471
  for (let e of d) {
472
472
  let n = e[c];
473
473
  if (f.has(n)) throw new In(Ln({
@@ -483,9 +483,9 @@ var Mt = (e) => typeof e == "string" && e !== "" ? e : null, Nt = async (e, t, n
483
483
  let e = n[l];
484
484
  n[t] = e == null ? null : f.get(e) ?? null;
485
485
  }
486
- await Kn(d, r.with, o, a);
486
+ await qn(d, r.with, o, a);
487
487
  }, Vn = async (e, t, n, r, i, a) => {
488
- let o = n.target(), s = n.foreignKey ?? an(o, i.tableName, t), c = n.sourceKey ?? "id", l = F(e, c), u = Hn(r), d = l.length === 0 ? [] : await Gn(o, s, l, u, a), f = /* @__PURE__ */ new Map();
488
+ let o = n.target(), s = n.foreignKey ?? on(o, i.tableName, t), c = n.sourceKey ?? "id", l = Gn(e, c), u = Hn(r), d = l.length === 0 ? [] : await Kn(o, s, l, u, a), f = /* @__PURE__ */ new Map();
489
489
  for (let e of d) {
490
490
  let t = e[s], n = f.get(t);
491
491
  n ? n.push(e) : f.set(t, [e]);
@@ -501,12 +501,12 @@ var Mt = (e) => typeof e == "string" && e !== "" ? e : null, Nt = async (e, t, n
501
501
  let e = n[c];
502
502
  n[t] = f.get(e) ?? [];
503
503
  }
504
- await Kn(d, r.with, o, a);
504
+ await qn(d, r.with, o, a);
505
505
  }, Hn = (e) => {
506
506
  let { limit: t, offset: n, ...r } = e;
507
507
  return r;
508
508
  }, Un = async (e, t, n, r, i, a) => {
509
- let o = n.target(), s = n.through(), c = F(e, "id");
509
+ let o = n.target(), s = n.through(), c = Gn(e, "id");
510
510
  if (c.length === 0) {
511
511
  for (let n of e) n[t] = [];
512
512
  return;
@@ -527,8 +527,8 @@ var Mt = (e) => typeof e == "string" && e !== "" ? e : null, Nt = async (e, t, n
527
527
  for (let n of e) n[t] = [];
528
528
  return;
529
529
  }
530
- let f = await Gn(o, "id", F(d, n.targetKey), r, a), p = new Map(f.map((e) => [e.id, e]));
531
- await Kn(f, r.with, o, a);
530
+ let f = await Kn(o, "id", Gn(d, n.targetKey), r, a), p = new Map(f.map((e) => [e.id, e]));
531
+ await qn(f, r.with, o, a);
532
532
  let m = r.junction === void 0 ? void 0 : r.junction === !0 ? Object.keys(s.fields) : r.junction, h = /* @__PURE__ */ new Map();
533
533
  for (let e of d) {
534
534
  let t = e[n.sourceKey], r = e[n.targetKey], i = p.get(r);
@@ -542,14 +542,14 @@ var Mt = (e) => typeof e == "string" && e !== "" ? e : null, Nt = async (e, t, n
542
542
  for (let n of e) n[t] = h.get(n.id) ?? [];
543
543
  }, Wn = (e, t) => {
544
544
  for (let [n, r] of Object.entries(e.fields)) if (r.type === "reference" && r.references?.()?.tableName === t) return n;
545
- }, F = (e, t) => {
545
+ }, Gn = (e, t) => {
546
546
  let n = /* @__PURE__ */ new Set();
547
547
  for (let r of e) {
548
548
  let e = r[t];
549
549
  e != null && n.add(e);
550
550
  }
551
551
  return [...n];
552
- }, Gn = (e, t, n, r, i) => {
552
+ }, Kn = (e, t, n, r, i) => {
553
553
  let a = {
554
554
  column: t,
555
555
  op: "in",
@@ -563,63 +563,63 @@ var Mt = (e) => typeof e == "string" && e !== "" ? e : null, Nt = async (e, t, n
563
563
  skip: r.offset,
564
564
  projection: void 0
565
565
  });
566
- }, Kn = async (e, t, n, r) => {
566
+ }, qn = async (e, t, n, r) => {
567
567
  t !== void 0 && e.length !== 0 && (await Rn(e, t, n, r)).forEach((t, n) => {
568
568
  let r = e[n];
569
569
  for (let [e, n] of Object.entries(t)) e in r || (r[e] = n);
570
570
  });
571
- }, qn = (e) => e.eager !== void 0 && Object.keys(e.eager).length > 0, Jn = class extends Error {
571
+ }, Jn = (e) => e.eager !== void 0 && Object.keys(e.eager).length > 0, Yn = class extends Error {
572
572
  _tag = "TenantNamespaceUnresolved";
573
573
  constructor(e) {
574
574
  super(e), this.name = "TenantNamespaceUnresolved";
575
575
  }
576
- }, Yn = class extends Error {
576
+ }, Xn = class extends Error {
577
577
  _tag = "TenantNamespaceInvalid";
578
578
  constructor(e) {
579
579
  super(e), this.name = "TenantNamespaceInvalid";
580
580
  }
581
- }, Xn = 63, Zn = "tenant_", Qn = (e) => e.toLowerCase().replace(/[^a-z0-9_]/g, "_"), $n = (e) => {
582
- if (e == null || e === "") throw new Jn("namespace isolation is on but the request has no resolvable tenant (subject.tenantId is null/empty). Refusing to run against a shared/default namespace — this would be a cross-tenant read. Authenticate with a tenant-scoped subject, or disable namespace isolation for this surface.");
583
- let t = Qn(e);
584
- if (t.replace(/_/g, "") === "") throw new Yn(`tenant id '${e}' has no usable identifier characters after sanitisation — cannot derive a distinct namespace.`);
585
- let n = `${Zn}${t}`;
586
- if (n.length > Xn) throw new Yn(`namespace '${n}' for tenant '${e}' exceeds the ${Xn}-byte identifier limit. Use a shorter tenant id.`);
581
+ }, Zn = 63, Qn = "tenant_", $n = (e) => e.toLowerCase().replace(/[^a-z0-9_]/g, "_"), er = (e) => {
582
+ if (e == null || e === "") throw new Yn("namespace isolation is on but the request has no resolvable tenant (subject.tenantId is null/empty). Refusing to run against a shared/default namespace — this would be a cross-tenant read. Authenticate with a tenant-scoped subject, or disable namespace isolation for this surface.");
583
+ let t = $n(e);
584
+ if (t.replace(/_/g, "") === "") throw new Xn(`tenant id '${e}' has no usable identifier characters after sanitisation — cannot derive a distinct namespace.`);
585
+ let n = `${Qn}${t}`;
586
+ if (n.length > Zn) throw new Xn(`namespace '${n}' for tenant '${e}' exceeds the ${Zn}-byte identifier limit. Use a shorter tenant id.`);
587
587
  return n;
588
- }, er = (e, t) => e === null ? t : `${e}.${t}`, tr = /* @__PURE__ */ new Set(["timestamp", "date"]), nr = /^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2})?/, rr = (e, t) => {
589
- if (e === void 0 || t == null || !tr.has(e) || t instanceof Date) return t;
588
+ }, tr = (e, t) => e === null ? t : `${e}.${t}`, nr = /* @__PURE__ */ new Set(["timestamp", "date"]), rr = /^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2})?/, ir = (e, t) => {
589
+ if (e === void 0 || t == null || !nr.has(e) || t instanceof Date) return t;
590
590
  if (typeof t == "number" && Number.isFinite(t)) return new Date(t);
591
- if (typeof t == "string" && nr.test(t)) {
591
+ if (typeof t == "string" && rr.test(t)) {
592
592
  let e = new Date(t);
593
593
  return Number.isNaN(e.getTime()) ? t : e;
594
594
  }
595
595
  return t;
596
- }, ir = (e, t) => e === void 0 || !tr.has(e) ? t : t.map((t) => rr(e, t)), ar = (e, t) => {
596
+ }, ar = (e, t) => e === void 0 || !nr.has(e) ? t : t.map((t) => ir(e, t)), or = (e, t) => {
597
597
  let { strings: n, values: r } = e, i = t.unsafe(n[0] ?? "");
598
598
  for (let e = 0; e < r.length; e++) i = t`${i}${r[e]}${t.unsafe(n[e + 1] ?? "")}`;
599
599
  return t`${i}`;
600
- }, or = (e) => e.replace(/[\\%_]/g, (e) => `\\${e}`), I = (e, t, n = null, r) => {
601
- if ("not" in e) return t`NOT (${I(e.not, t, n, r)})`;
602
- if ("and" in e) return e.and.length === 0 ? t`TRUE` : t.and(e.and.map((e) => I(e, t, n, r)));
603
- if ("or" in e) return e.or.length === 0 ? t`FALSE` : t.or(e.or.map((e) => I(e, t, n, r)));
600
+ }, sr = (e) => e.replace(/[\\%_]/g, (e) => `\\${e}`), F = (e, t, n = null, r) => {
601
+ if ("not" in e) return t`NOT (${F(e.not, t, n, r)})`;
602
+ if ("and" in e) return e.and.length === 0 ? t`TRUE` : t.and(e.and.map((e) => F(e, t, n, r)));
603
+ if ("or" in e) return e.or.length === 0 ? t`FALSE` : t.or(e.or.map((e) => F(e, t, n, r)));
604
604
  if (e.op === "subquery-in" || e.op === "subquery-not-in") {
605
- let r = e, i = _r(r.subquery, t, n);
605
+ let r = e, i = vr(r.subquery, t, n);
606
606
  return r.op === "subquery-in" ? t`${t(r.column)} IN (${i})` : t`${t(r.column)} NOT IN (${i})`;
607
607
  }
608
608
  if (e.op === "exists" || e.op === "not-exists") {
609
- let r = e, i = _r(r.subquery, t, n);
609
+ let r = e, i = vr(r.subquery, t, n);
610
610
  return r.op === "exists" ? t`EXISTS (${i})` : t`NOT EXISTS (${i})`;
611
611
  }
612
612
  let i = e, a = t(i.column), o = i.path, s = o !== void 0 && o.length > 0, c = () => t.onDialectOrElse({
613
- mysql: () => t.unsafe(E(i.column, o, "mysql")),
614
- mssql: () => t.unsafe(E(i.column, o, "mssql")),
615
- sqlite: () => t.unsafe(E(i.column, o, "sqlite")),
616
- orElse: () => t.unsafe(E(i.column, o, "postgres"))
613
+ mysql: () => t.unsafe(T(i.column, o, "mysql")),
614
+ mssql: () => t.unsafe(T(i.column, o, "mssql")),
615
+ sqlite: () => t.unsafe(T(i.column, o, "sqlite")),
616
+ orElse: () => t.unsafe(T(i.column, o, "postgres"))
617
617
  }), l = () => t.onDialectOrElse({
618
- mysql: () => t.unsafe(E(i.column, o, "mysql", { numeric: !0 })),
619
- mssql: () => t.unsafe(E(i.column, o, "mssql", { numeric: !0 })),
620
- sqlite: () => t.unsafe(E(i.column, o, "sqlite", { numeric: !0 })),
621
- orElse: () => t.unsafe(E(i.column, o, "postgres", { numeric: !0 }))
622
- }), u = s ? c() : a, d = s ? l() : a, f = (e) => s && e != null ? String(e) : e, m = (e) => s ? Number(e) : e, h = s || r === void 0 ? void 0 : p(r)?.fields?.[i.column]?.type, g = (e) => rr(h, e);
618
+ mysql: () => t.unsafe(T(i.column, o, "mysql", { numeric: !0 })),
619
+ mssql: () => t.unsafe(T(i.column, o, "mssql", { numeric: !0 })),
620
+ sqlite: () => t.unsafe(T(i.column, o, "sqlite", { numeric: !0 })),
621
+ orElse: () => t.unsafe(T(i.column, o, "postgres", { numeric: !0 }))
622
+ }), u = s ? c() : a, d = s ? l() : a, f = (e) => s && e != null ? String(e) : e, m = (e) => s ? Number(e) : e, h = s || r === void 0 ? void 0 : p(r)?.fields?.[i.column]?.type, g = (e) => ir(h, e);
623
623
  switch (i.op) {
624
624
  case "eq": return t`${u} = ${f(g(i.value))}`;
625
625
  case "neq": return t`${u} <> ${f(g(i.value))}`;
@@ -636,7 +636,7 @@ var Mt = (e) => typeof e == "string" && e !== "" ? e : null, Nt = async (e, t, n
636
636
  return e.length === 0 ? t`TRUE` : t`${u} NOT IN ${t.in(s ? e.map((e) => f(e)) : e)}`;
637
637
  }
638
638
  case "contains": {
639
- let e = `%${or(typeof i.value == "string" ? i.value : String(i.value ?? ""))}%`;
639
+ let e = `%${sr(typeof i.value == "string" ? i.value : String(i.value ?? ""))}%`;
640
640
  return t.onDialectOrElse({
641
641
  mysql: () => t`LOWER(${u}) LIKE LOWER(${e})`,
642
642
  mssql: () => t`LOWER(${u}) LIKE LOWER(${e})`,
@@ -645,7 +645,7 @@ var Mt = (e) => typeof e == "string" && e !== "" ? e : null, Nt = async (e, t, n
645
645
  });
646
646
  }
647
647
  case "startsWith": {
648
- let e = `${or(typeof i.value == "string" ? i.value : String(i.value ?? ""))}%`;
648
+ let e = `${sr(typeof i.value == "string" ? i.value : String(i.value ?? ""))}%`;
649
649
  return t.onDialectOrElse({
650
650
  mysql: () => t`${u} LIKE ${e}`,
651
651
  orElse: () => t`${u} LIKE ${e} ESCAPE '\\'`
@@ -693,13 +693,13 @@ var Mt = (e) => typeof e == "string" && e !== "" ? e : null, Nt = async (e, t, n
693
693
  });
694
694
  }
695
695
  }
696
- }, sr = (e, t) => {
696
+ }, cr = (e, t) => {
697
697
  let n = [];
698
698
  return e.partitionBy && e.partitionBy.length > 0 && n.push(t`PARTITION BY ${t.csv(e.partitionBy.map((e) => t`${t(e)}`))}`), e.orderBy && e.orderBy.length > 0 && n.push(t`ORDER BY ${t.csv(e.orderBy.map((e) => e.direction === "desc" ? t`${t(e.column)} DESC` : t`${t(e.column)} ASC`))}`), n.length === 0 ? t`` : n.length === 1 ? n[0] : n.reduce((e, n, r) => r === 0 ? n : t`${e} ${n}`);
699
- }, cr = (e, t) => t.csv(e.map((e) => {
699
+ }, lr = (e, t) => t.csv(e.map((e) => {
700
700
  let n = e.column === void 0 ? t.unsafe("*") : t`${t(e.column)}`;
701
701
  if (e.op.startsWith("window-")) {
702
- let r = sr(e.window ?? {}, t);
702
+ let r = cr(e.window ?? {}, t);
703
703
  switch (e.op) {
704
704
  case "window-row-number": return t`ROW_NUMBER() OVER (${r}) AS ${t(e.alias)}`;
705
705
  case "window-rank": return t`RANK() OVER (${r}) AS ${t(e.alias)}`;
@@ -723,44 +723,44 @@ var Mt = (e) => typeof e == "string" && e !== "" ? e : null, Nt = async (e, t, n
723
723
  return t`${t(e.column)} AS ${t(e.alias)}`;
724
724
  default: throw Error(`compileAggregateProjection: unknown op '${e.op}'`);
725
725
  }
726
- })), lr = (e) => `[${e.join(",")}]`, ur = (e, t) => {
726
+ })), ur = (e) => `[${e.join(",")}]`, dr = (e, t) => {
727
727
  if (e.queryVector === void 0) return null;
728
- let n = t(e.column), r = lr(e.queryVector), i = e.distance === "cosine" ? "<=>" : e.distance === "l2" ? "<->" : "<#>", a = e.distance === "cosine" ? "VEC_DISTANCE_COSINE" : "VEC_DISTANCE_EUCLIDEAN";
728
+ let n = t(e.column), r = ur(e.queryVector), i = e.distance === "cosine" ? "<=>" : e.distance === "l2" ? "<->" : "<#>", a = e.distance === "cosine" ? "VEC_DISTANCE_COSINE" : "VEC_DISTANCE_EUCLIDEAN";
729
729
  return t.onDialectOrElse({
730
730
  mysql: () => t`${t.unsafe(a)}(${n}, ${r})`,
731
731
  mssql: () => t`NULL`,
732
732
  sqlite: () => t`NULL`,
733
733
  orElse: () => t`${n} ${t.unsafe(i)} ${r}::vector`
734
734
  });
735
- }, dr = (e, t) => {
735
+ }, fr = (e, t) => {
736
736
  let n = t.unsafe(e.useGeography ? "::geography" : "::geometry");
737
737
  return t`ST_Distance(${t(e.column)}${n}, ${e.geom}${n})`;
738
- }, fr = (e, t) => t`${t(e.column)} <-> ${e.geom}::geometry`, pr = (e, t) => t`${t(`${e.indexName}_tsv`)}`, mr = (e, t) => `${t}_${e.indexName}_fts`, hr = (e, t, n) => {
739
- let r = n.csv(e.columns.map((e) => n`${n(e)}`)), i = `%${or(e.query)}%`;
738
+ }, pr = (e, t) => t`${t(e.column)} <-> ${e.geom}::geometry`, mr = (e, t) => t`${t(`${e.indexName}_tsv`)}`, hr = (e, t) => `${t}_${e.indexName}_fts`, gr = (e, t, n) => {
739
+ let r = n.csv(e.columns.map((e) => n`${n(e)}`)), i = `%${sr(e.query)}%`;
740
740
  return n.onDialectOrElse({
741
741
  mysql: () => n`MATCH(${r}) AGAINST(${e.query} IN NATURAL LANGUAGE MODE)`,
742
742
  sqlite: () => {
743
- let r = n(mr(e, t));
743
+ let r = n(hr(e, t));
744
744
  return n`${n("id")} IN (SELECT ${n("row_id")} FROM ${r} WHERE ${r} MATCH ${e.query})`;
745
745
  },
746
746
  mssql: () => n.or(e.columns.map((e) => n`LOWER(${n(e)}) LIKE LOWER(${i}) ESCAPE '\\'`)),
747
- orElse: () => n`${pr(e, n)} @@ plainto_tsquery(${e.config ?? "english"}, ${e.query})`
747
+ orElse: () => n`${mr(e, n)} @@ plainto_tsquery(${e.config ?? "english"}, ${e.query})`
748
748
  });
749
- }, gr = (e, t, n) => {
750
- let r = `%${or(e.query)}%`;
749
+ }, _r = (e, t, n) => {
750
+ let r = `%${sr(e.query)}%`;
751
751
  return n.onDialectOrElse({
752
752
  mysql: () => n`MATCH(${n.csv(e.columns.map((e) => n`${n(e)}`))}) AGAINST(${e.query} IN NATURAL LANGUAGE MODE)`,
753
753
  sqlite: () => {
754
- let r = n(mr(e, t));
754
+ let r = n(hr(e, t));
755
755
  return n`COALESCE((SELECT -bm25(${r}) FROM ${r} WHERE ${r} MATCH ${e.query} AND ${r}.${n("row_id")} = ${n("id")}), 0)`;
756
756
  },
757
757
  mssql: () => e.columns.map((e) => n`(CASE WHEN LOWER(${n(e)}) LIKE LOWER(${r}) ESCAPE '\\' THEN 1 ELSE 0 END)`).reduce((e, t, r) => r === 0 ? t : n`${e} + ${t}`),
758
- orElse: () => n`ts_rank(${pr(e, n)}, plainto_tsquery(${e.config ?? "english"}, ${e.query}))`
758
+ orElse: () => n`ts_rank(${mr(e, n)}, plainto_tsquery(${e.config ?? "english"}, ${e.query}))`
759
759
  });
760
- }, _r = (e, t, n = null) => {
760
+ }, vr = (e, t, n = null) => {
761
761
  if (e.setOp && e.setOp.queries.length >= 2) {
762
- let r = e.setOp.kind === "union" ? "UNION" : e.setOp.kind === "union-all" ? "UNION ALL" : e.setOp.kind === "intersect" ? "INTERSECT" : "EXCEPT", i = e.setOp.queries.map((e) => t`(${_r(e, t, n)})`).reduce((e, n, i) => i === 0 ? n : t`${e} ${t.unsafe(r)} ${n}`), a = [];
763
- if (T(e).length > 0 && a.push(t` ORDER BY ${t.csv(T(e).map((e) => e.direction === "desc" ? t`${t(e.column)} DESC` : t`${t(e.column)} ASC`))}`), e.take !== void 0) {
762
+ let r = e.setOp.kind === "union" ? "UNION" : e.setOp.kind === "union-all" ? "UNION ALL" : e.setOp.kind === "intersect" ? "INTERSECT" : "EXCEPT", i = e.setOp.queries.map((e) => t`(${vr(e, t, n)})`).reduce((e, n, i) => i === 0 ? n : t`${e} ${t.unsafe(r)} ${n}`), a = [];
763
+ if (w(e).length > 0 && a.push(t` ORDER BY ${t.csv(w(e).map((e) => e.direction === "desc" ? t`${t(e.column)} DESC` : t`${t(e.column)} ASC`))}`), e.take !== void 0) {
764
764
  if (!Number.isInteger(e.take) || e.take < 0) throw Error(`compileSelect: invalid take ${e.take}`);
765
765
  a.push(t` LIMIT ${t.unsafe(String(e.take))}`);
766
766
  }
@@ -770,7 +770,7 @@ var Mt = (e) => typeof e == "string" && e !== "" ? e : null, Nt = async (e, t, n
770
770
  }
771
771
  return t`${i}${a.reduce((e, n) => t`${e}${n}`, t``)}`;
772
772
  }
773
- let r = e.annClause === void 0 ? null : ur(e.annClause, t);
773
+ let r = e.annClause === void 0 ? null : dr(e.annClause, t);
774
774
  e.spatialClause !== void 0 && t.onDialectOrElse({
775
775
  mysql: () => {
776
776
  throw Error("@voltro/plugin-postgis: spatial distance / KNN ordering is postgres-only");
@@ -783,57 +783,57 @@ var Mt = (e) => typeof e == "string" && e !== "" ? e : null, Nt = async (e, t, n
783
783
  },
784
784
  orElse: () => t``
785
785
  });
786
- let i = e.spatialClause?.projectAs === void 0 ? null : dr(e.spatialClause, t), a = e.aggregations && e.aggregations.length > 0 ? cr(e.aggregations, t) : e.joinedProjection && e.joinedProjection.length > 0 ? t.csv(e.joinedProjection.map((e) => t`${t(e.source)} AS ${t(e.outputKey)}`)) : e.projection && e.projection.length > 0 ? t.csv(e.projection.map((e) => t`${t(e)}`)) : t`*`, o = (e.aggregations && e.aggregations.length > 0) === !0, s = r !== null && !o ? t`${a}, ${r} AS ${t("distance")}` : a, c = e.fullTextSearch, l = c?.rank !== void 0 && !o ? gr(c, e.table, t) : null, u = l !== null && c?.rank !== void 0 ? t`${s}, ${l} AS ${t(c.rank.alias)}` : s, d = i !== null && !o && e.spatialClause?.projectAs !== void 0 ? t`${u}, ${i} AS ${t(e.spatialClause.projectAs)}` : u, f = e.distinctOn && e.distinctOn.length > 0 ? t.onDialectOrElse({
786
+ let i = e.spatialClause?.projectAs === void 0 ? null : fr(e.spatialClause, t), a = e.aggregations && e.aggregations.length > 0 ? lr(e.aggregations, t) : e.joinedProjection && e.joinedProjection.length > 0 ? t.csv(e.joinedProjection.map((e) => t`${t(e.source)} AS ${t(e.outputKey)}`)) : e.projection && e.projection.length > 0 ? t.csv(e.projection.map((e) => t`${t(e)}`)) : t`*`, o = (e.aggregations && e.aggregations.length > 0) === !0, s = r !== null && !o ? t`${a}, ${r} AS ${t("distance")}` : a, c = e.fullTextSearch, l = c?.rank !== void 0 && !o ? _r(c, e.table, t) : null, u = l !== null && c?.rank !== void 0 ? t`${s}, ${l} AS ${t(c.rank.alias)}` : s, d = i !== null && !o && e.spatialClause?.projectAs !== void 0 ? t`${u}, ${i} AS ${t(e.spatialClause.projectAs)}` : u, f = e.distinctOn && e.distinctOn.length > 0 ? t.onDialectOrElse({
787
787
  orElse: () => t`DISTINCT ON (${t.csv(e.distinctOn.map((e) => t`${t(e)}`))}) `,
788
788
  mysql: () => t`DISTINCT `,
789
789
  mssql: () => t`DISTINCT `,
790
790
  sqlite: () => t`DISTINCT `
791
- }) : e.distinct ? t`DISTINCT ` : t``, p = e.alias === void 0 ? t`${t(er(n, e.table))}` : t`${t(er(n, e.table))} AS ${t(e.alias)}`, m = (e.joins ?? []).map((e) => {
791
+ }) : e.distinct ? t`DISTINCT ` : t``, p = e.alias === void 0 ? t`${t(tr(n, e.table))}` : t`${t(tr(n, e.table))} AS ${t(e.alias)}`, m = (e.joins ?? []).map((e) => {
792
792
  let r = e.kind === "inner" ? "INNER" : "LEFT";
793
- return t` ${t.unsafe(r)} JOIN ${t(er(n, e.table))} AS ${t(e.alias)} ON ${I(e.on, t, n)}`;
794
- }), h = m.length > 0 ? m.reduce((e, n) => t`${e}${n}`, p) : p, g = c === void 0 ? null : hr(c, e.table, t), _ = [e.predicate ? I(e.predicate, t, n, e.table) : null, g].filter((e) => e !== null), v = _.length > 0 ? t` WHERE ${t.and(_)}` : t``, y = e.groupBy && e.groupBy.length > 0 ? t` GROUP BY ${t.csv(e.groupBy.map((e) => t`${t(e)}`))}` : t``, b = e.having ? t` HAVING ${I(e.having, t, n, e.table)}` : t``, x = e.skip !== void 0, S = [];
795
- r !== null && S.push(t`${r} ASC`), e.spatialClause?.order !== void 0 && S.push(e.spatialClause.order === "desc" ? t`${fr(e.spatialClause, t)} DESC` : t`${fr(e.spatialClause, t)} ASC`), l !== null && c?.rank?.order === !0 && S.push(t`${l} DESC`);
796
- for (let n of T(e)) S.push(n.direction === "desc" ? t`${t(n.column)} DESC` : t`${t(n.column)} ASC`);
797
- let ee = S.length > 0 ? t` ORDER BY ${t.csv(S)}` : x ? t.onDialectOrElse({
793
+ return t` ${t.unsafe(r)} JOIN ${t(tr(n, e.table))} AS ${t(e.alias)} ON ${F(e.on, t, n)}`;
794
+ }), h = m.length > 0 ? m.reduce((e, n) => t`${e}${n}`, p) : p, g = c === void 0 ? null : gr(c, e.table, t), _ = [e.predicate ? F(e.predicate, t, n, e.table) : null, g].filter((e) => e !== null), v = _.length > 0 ? t` WHERE ${t.and(_)}` : t``, y = e.groupBy && e.groupBy.length > 0 ? t` GROUP BY ${t.csv(e.groupBy.map((e) => t`${t(e)}`))}` : t``, b = e.having ? t` HAVING ${F(e.having, t, n, e.table)}` : t``, ee = e.skip !== void 0, x = [];
795
+ r !== null && x.push(t`${r} ASC`), e.spatialClause?.order !== void 0 && x.push(e.spatialClause.order === "desc" ? t`${pr(e.spatialClause, t)} DESC` : t`${pr(e.spatialClause, t)} ASC`), l !== null && c?.rank?.order === !0 && x.push(t`${l} DESC`);
796
+ for (let n of w(e)) x.push(n.direction === "desc" ? t`${t(n.column)} DESC` : t`${t(n.column)} ASC`);
797
+ let te = x.length > 0 ? t` ORDER BY ${t.csv(x)}` : ee ? t.onDialectOrElse({
798
798
  mssql: () => t` ORDER BY (SELECT NULL)`,
799
799
  orElse: () => t``
800
- }) : t``, C = (e) => {
800
+ }) : t``, S = (e) => {
801
801
  if (!Number.isFinite(e) || !Number.isInteger(e) || e < 0) throw Error(`compileSelect: expected non-negative integer take/skip, got ${e}`);
802
802
  return t.unsafe(String(e));
803
- }, te = (e.ctes ?? []).map((e) => t`${t(e.name)} AS (${_r(e.descriptor, t, n)})`), ne = (e.ctes ?? []).some((e) => e.recursive === !0), re = te.length > 0 ? t`WITH ${t.unsafe(ne ? "RECURSIVE " : "")}${t.csv(te)} ` : t``;
803
+ }, ne = (e.ctes ?? []).map((e) => t`${t(e.name)} AS (${vr(e.descriptor, t, n)})`), re = (e.ctes ?? []).some((e) => e.recursive === !0), ie = ne.length > 0 ? t`WITH ${t.unsafe(re ? "RECURSIVE " : "")}${t.csv(ne)} ` : t``;
804
804
  return t.onDialectOrElse({
805
805
  mssql: () => {
806
- let n = e.take !== void 0 && !x ? t`TOP ${C(e.take)} ` : t``, r = x ? t` OFFSET ${C(e.skip)} ROWS FETCH NEXT ${C(e.take ?? 2 ** 53 - 1)} ROWS ONLY` : t``;
807
- return t`${re}SELECT ${n}${f}${d} FROM ${h}${v}${y}${b}${ee}${r}`;
806
+ let n = e.take !== void 0 && !ee ? t`TOP ${S(e.take)} ` : t``, r = ee ? t` OFFSET ${S(e.skip)} ROWS FETCH NEXT ${S(e.take ?? 2 ** 53 - 1)} ROWS ONLY` : t``;
807
+ return t`${ie}SELECT ${n}${f}${d} FROM ${h}${v}${y}${b}${te}${r}`;
808
808
  },
809
809
  orElse: () => {
810
- let n = e.take === void 0 ? t`` : t` LIMIT ${C(e.take)}`, r = x ? t` OFFSET ${C(e.skip)}` : t``;
811
- return t`${re}SELECT ${f}${d} FROM ${h}${v}${y}${b}${ee}${n}${r}`;
810
+ let n = e.take === void 0 ? t`` : t` LIMIT ${S(e.take)}`, r = ee ? t` OFFSET ${S(e.skip)}` : t``;
811
+ return t`${ie}SELECT ${f}${d} FROM ${h}${v}${y}${b}${te}${n}${r}`;
812
812
  }
813
813
  });
814
- }, vr = (e, t, n) => {
814
+ }, yr = (e, t, n) => {
815
815
  if (e.eager === void 0) return null;
816
- let r = xr(e.table, e.eager, e.sourceTable);
816
+ let r = Sr(e.table, e.eager, e.sourceTable);
817
817
  if (r === null) return null;
818
- let i = Or(n, e, r, Dr(t, n));
818
+ let i = kr(n, e, r, Or(t, n));
819
819
  return i === null ? null : {
820
820
  fragment: i,
821
- decode: jr(r, n)
821
+ decode: Mr(r, n)
822
822
  };
823
- }, yr = (e) => e.relation.kind === "one" && e.fkSide === "target", br = (e) => ({
823
+ }, br = (e) => e.relation.kind === "one" && e.fkSide === "target", xr = (e) => ({
824
824
  ...e,
825
825
  branch: {
826
826
  ...e.branch,
827
827
  limit: 2
828
828
  }
829
- }), xr = (e, t, n) => {
829
+ }), Sr = (e, t, n) => {
830
830
  let r = n ?? y(e), i = mn(e);
831
831
  if (i === void 0) return null;
832
832
  let a = [];
833
833
  for (let [e, n] of Object.entries(t)) {
834
834
  let t = i[e];
835
835
  if (t === void 0) return null;
836
- let o = Sr(e, t, r, n === !0 ? {} : n);
836
+ let o = Cr(e, t, r, n === !0 ? {} : n);
837
837
  if (o === null) return null;
838
838
  a.push(o);
839
839
  }
@@ -841,19 +841,19 @@ var Mt = (e) => typeof e == "string" && e !== "" ? e : null, Nt = async (e, t, n
841
841
  table: r,
842
842
  children: a
843
843
  };
844
- }, Sr = (e, t, n, r) => {
844
+ }, Cr = (e, t, n, r) => {
845
845
  let i = t.target(), a = (t.kind === "manyToMany" ? void 0 : t.sourceKey) ?? "id", o, s;
846
846
  if (t.kind === "manyToMany") o = t.targetKey, s = "target";
847
847
  else if (t.kind === "one") {
848
- let r = t.sourceKey ?? Er(n, i.tableName);
848
+ let r = t.sourceKey ?? Dr(n, i.tableName);
849
849
  if (r !== void 0) o = r, s = "source";
850
850
  else try {
851
- o = t.foreignKey ?? an(i, n.tableName, e), s = "target";
851
+ o = t.foreignKey ?? on(i, n.tableName, e), s = "target";
852
852
  } catch {
853
853
  return null;
854
854
  }
855
855
  } else try {
856
- o = t.foreignKey ?? an(i, n.tableName, e), s = "target";
856
+ o = t.foreignKey ?? on(i, n.tableName, e), s = "target";
857
857
  } catch {
858
858
  return null;
859
859
  }
@@ -864,7 +864,7 @@ var Mt = (e) => typeof e == "string" && e !== "" ? e : null, Nt = async (e, t, n
864
864
  for (let [n, a] of Object.entries(r.with)) {
865
865
  let r = e?.[n];
866
866
  if (r === void 0) return null;
867
- let o = Sr(n, r, i, a === !0 ? {} : a);
867
+ let o = Cr(n, r, i, a === !0 ? {} : a);
868
868
  if (o === null) return null;
869
869
  t.push(o);
870
870
  }
@@ -880,9 +880,9 @@ var Mt = (e) => typeof e == "string" && e !== "" ? e : null, Nt = async (e, t, n
880
880
  fkSide: s,
881
881
  branch: r,
882
882
  children: c,
883
- junction: Cr(t, r)
883
+ junction: wr(t, r)
884
884
  };
885
- }, Cr = (e, t) => {
885
+ }, wr = (e, t) => {
886
886
  if (e.kind !== "manyToMany" || t.junction === void 0) return;
887
887
  let n = e.through(), r = t.junction === !0 ? Object.keys(n.fields) : t.junction, i = r.filter((e) => e in n.fields);
888
888
  return {
@@ -894,35 +894,35 @@ var Mt = (e) => typeof e == "string" && e !== "" ? e : null, Nt = async (e, t, n
894
894
  return t !== void 0 && (t.type === "timestamp" || t.type === "date");
895
895
  })
896
896
  };
897
- }, wr = (e) => `__j_${e}`, Tr = "__j", Er = (e, t) => {
897
+ }, Tr = (e) => `__j_${e}`, Er = "__j", Dr = (e, t) => {
898
898
  for (let [n, r] of Object.entries(e.fields)) if (r.type === "reference" && r.references?.()?.tableName === t) return n;
899
- }, Dr = (e, t) => {
899
+ }, Or = (e, t) => {
900
900
  let n = 0;
901
901
  return {
902
902
  sql: e,
903
903
  dialect: t,
904
904
  nextAlias: () => `__a${n++}`
905
905
  };
906
- }, Or = (e, t, n, r) => {
906
+ }, kr = (e, t, n, r) => {
907
907
  switch (e) {
908
- case "postgres": return Pr(t, n, r);
908
+ case "postgres": return Fr(t, n, r);
909
909
  case "sqlite":
910
- case "turso": return Hr(t, n, r);
910
+ case "turso": return Ur(t, n, r);
911
911
  case "mysql":
912
- case "mariadb": return Qr(t, n, r);
913
- case "mssql": return ai(t, n, r);
912
+ case "mariadb": return $r(t, n, r);
913
+ case "mssql": return oi(t, n, r);
914
914
  }
915
- }, kr = (e, t) => t === "mssql" && !Ar.test(e) ? /* @__PURE__ */ new Date(`${e}Z`) : new Date(e), Ar = /(?:Z|[+-]\d{2}:?\d{2})$/, jr = (e, t) => {
916
- let n = Mr(e.table, e.children, t);
915
+ }, Ar = (e, t) => t === "mssql" && !jr.test(e) ? /* @__PURE__ */ new Date(`${e}Z`) : new Date(e), jr = /(?:Z|[+-]\d{2}:?\d{2})$/, Mr = (e, t) => {
916
+ let n = Nr(e.table, e.children, t);
917
917
  return (e) => e.map((e) => {
918
918
  let t = e.__row, r = typeof t == "string" ? JSON.parse(t) : t;
919
919
  return n(r);
920
920
  });
921
- }, Mr = (e, t, n) => {
921
+ }, Nr = (e, t, n) => {
922
922
  let r = [];
923
923
  for (let [t, n] of Object.entries(e.fields)) (n.type === "timestamp" || n.type === "date") && r.push(t);
924
924
  let i = t.map((e) => {
925
- let t = Mr(e.target, e.children, n), r = e.relation.kind === "one", i = yr(e), a = i ? Ln({
925
+ let t = Nr(e.target, e.children, n), r = e.relation.kind === "one", i = br(e), a = i ? Ln({
926
926
  relationName: e.relationName,
927
927
  sourceTableName: e.source.tableName,
928
928
  targetTableName: e.target.tableName,
@@ -935,14 +935,14 @@ var Mt = (e) => typeof e == "string" && e !== "" ? e : null, Nt = async (e, t, n
935
935
  isSingle: r,
936
936
  fromOverFetch: i,
937
937
  cardinalityMessage: a,
938
- junction: Nr(e.junction, n)
938
+ junction: Pr(e.junction, n)
939
939
  };
940
940
  });
941
941
  return (e) => {
942
942
  let t = { ...e };
943
943
  for (let e of r) {
944
944
  let r = t[e];
945
- typeof r == "string" && (t[e] = kr(r, n));
945
+ typeof r == "string" && (t[e] = Ar(r, n));
946
946
  }
947
947
  for (let e of i) {
948
948
  let n = t[e.name];
@@ -964,204 +964,204 @@ var Mt = (e) => typeof e == "string" && e !== "" ? e : null, Nt = async (e, t, n
964
964
  }
965
965
  return t;
966
966
  };
967
- }, Nr = (e, t) => {
967
+ }, Pr = (e, t) => {
968
968
  if (e === void 0) return;
969
969
  let n = new Set(e.dateColumns), r = e.requested;
970
970
  return (e) => {
971
971
  let i = e._junction ?? {}, a = {};
972
972
  for (let e of r) {
973
973
  let r = i[e];
974
- a[e] = n.has(e) && typeof r == "string" ? kr(r, t) : r;
974
+ a[e] = n.has(e) && typeof r == "string" ? Ar(r, t) : r;
975
975
  }
976
976
  return {
977
977
  ...e,
978
978
  _junction: a
979
979
  };
980
980
  };
981
- }, Pr = (e, t, n) => {
982
- let r = n.sql, i = n.nextAlias(), a = r(t.table.tableName), o = r(i), s = Fr(i, t.children, n);
983
- return s === null ? null : r`SELECT ${s} AS "__row" FROM ${a} AS ${o}${e.predicate ? r` WHERE ${H(e.predicate, i, r)}` : r``}${T(e).length > 0 ? r` ORDER BY ${r.csv(T(e).map((e) => e.direction === "desc" ? r`${z(i, e.column, r)} DESC` : r`${z(i, e.column, r)} ASC`))}` : r``}${e.take === void 0 ? r`` : r` LIMIT ${V(e.take, r)}`}${e.skip === void 0 ? r`` : r` OFFSET ${V(e.skip, r)}`}`;
984
- }, Fr = (e, t, n, r) => {
985
- let i = n.sql, a = r === void 0 ? i`to_jsonb(${i(e)}.*)` : i`(to_jsonb(${i(e)}.*) - ${B(Tr, i)}::text)`;
981
+ }, Fr = (e, t, n) => {
982
+ let r = n.sql, i = n.nextAlias(), a = r(t.table.tableName), o = r(i), s = Ir(i, t.children, n);
983
+ return s === null ? null : r`SELECT ${s} AS "__row" FROM ${a} AS ${o}${e.predicate ? r` WHERE ${V(e.predicate, i, r)}` : r``}${w(e).length > 0 ? r` ORDER BY ${r.csv(w(e).map((e) => e.direction === "desc" ? r`${R(i, e.column, r)} DESC` : r`${R(i, e.column, r)} ASC`))}` : r``}${e.take === void 0 ? r`` : r` LIMIT ${B(e.take, r)}`}${e.skip === void 0 ? r`` : r` OFFSET ${B(e.skip, r)}`}`;
984
+ }, Ir = (e, t, n, r) => {
985
+ let i = n.sql, a = r === void 0 ? i`to_jsonb(${i(e)}.*)` : i`(to_jsonb(${i(e)}.*) - ${z(Er, i)}::text)`;
986
986
  if (t.length === 0 && r === void 0) return a;
987
987
  let o = [];
988
- r !== void 0 && o.push(i`${B("_junction", i)}, ${z(e, Tr, i)}`);
988
+ r !== void 0 && o.push(i`${z("_junction", i)}, ${R(e, Er, i)}`);
989
989
  for (let r of t) {
990
- let t = Ir(r, e, n);
990
+ let t = Lr(r, e, n);
991
991
  if (t === null) return null;
992
- o.push(i`${B(r.relationName, i)}, ${t}`);
992
+ o.push(i`${z(r.relationName, i)}, ${t}`);
993
993
  }
994
994
  return i`${a} || jsonb_build_object(${i.csv(o)})`;
995
- }, Ir = (e, t, n) => {
995
+ }, Lr = (e, t, n) => {
996
996
  switch (e.relation.kind) {
997
- case "one": return yr(e) ? Rr(br(e), t, n) : Lr(e, t, n);
998
- case "many": return Rr(e, t, n);
999
- case "manyToMany": return zr(e, t, n);
997
+ case "one": return br(e) ? zr(xr(e), t, n) : Rr(e, t, n);
998
+ case "many": return zr(e, t, n);
999
+ case "manyToMany": return Br(e, t, n);
1000
1000
  }
1001
- }, Lr = (e, t, n) => {
1002
- let r = n.sql, i = n.nextAlias(), a = Fr(i, e.children, n);
1001
+ }, Rr = (e, t, n) => {
1002
+ let r = n.sql, i = n.nextAlias(), a = Ir(i, e.children, n);
1003
1003
  if (a === null) return null;
1004
- let o = e.fkSide === "source" ? r`${z(i, "id", r)} = ${z(t, e.foreignKey, r)}` : r`${z(i, e.foreignKey, r)} = ${z(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${H(e.branch.where, i, r)}`, c = L(i, e.branch.orderBy, r);
1004
+ let o = e.fkSide === "source" ? r`${R(i, "id", r)} = ${R(t, e.foreignKey, r)}` : r`${R(i, e.foreignKey, r)} = ${R(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${V(e.branch.where, i, r)}`, c = I(i, e.branch.orderBy, r);
1005
1005
  return r`(SELECT ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o}${s}${c} LIMIT 1)`;
1006
- }, Rr = (e, t, n) => {
1007
- let r = n.sql, i = n.nextAlias(), a = Fr(i, e.children, n);
1006
+ }, zr = (e, t, n) => {
1007
+ let r = n.sql, i = n.nextAlias(), a = Ir(i, e.children, n);
1008
1008
  if (a === null) return null;
1009
- let o = r`${z(void 0, e.foreignKey, r)} = ${z(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${I(e.branch.where, r)}`, c = Vr(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${V(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${V(e.branch.offset, r)}`;
1009
+ let o = r`${R(void 0, e.foreignKey, r)} = ${R(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${F(e.branch.where, r)}`, c = Hr(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${B(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${B(e.branch.offset, r)}`;
1010
1010
  return r`COALESCE((SELECT jsonb_agg(${a}) FROM (SELECT * FROM ${r(e.target.tableName)} WHERE ${o}${s}${c}${l}${u}) AS ${r(i)}), '[]'::jsonb)`;
1011
- }, zr = (e, t, n) => {
1012
- let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = Fr(o, e.children, n, e.junction);
1011
+ }, Br = (e, t, n) => {
1012
+ let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = Ir(o, e.children, n, e.junction);
1013
1013
  if (c === null) return null;
1014
- let l = e.branch.where === void 0 ? r`` : r` AND ${I(e.branch.where, r)}`, u = pi(e, s, r), d = L(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${V(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${V(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : r`, ${Br(e.junction, s, r)} AS ${r(Tr)}`;
1015
- return r`COALESCE((SELECT jsonb_agg(${c}) FROM (SELECT ${r(o)}.*${m} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${z(o, "id", r)} = ${z(s, i.targetKey, r)} WHERE ${z(s, i.sourceKey, r)} = ${z(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), '[]'::jsonb)`;
1016
- }, Br = (e, t, n) => e.present.length === 0 ? n`jsonb_build_object()` : n`jsonb_build_object(${n.csv(e.present.map((e) => n`${B(e, n)}, ${z(t, e, n)}`))})`, L = (e, t, n) => t === void 0 || t.length === 0 ? n`` : n` ORDER BY ${n.csv(t.map((t) => t.direction === "desc" ? n`${z(e, t.column, n)} DESC` : n`${z(e, t.column, n)} ASC`))}`, Vr = (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`))}`, Hr = (e, t, n) => {
1017
- let r = n.sql, i = n.nextAlias(), a = Ur(i, t.table, t.children, n);
1014
+ let l = e.branch.where === void 0 ? r`` : r` AND ${F(e.branch.where, r)}`, u = mi(e, s, r), d = I(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${B(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${B(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : r`, ${Vr(e.junction, s, r)} AS ${r(Er)}`;
1015
+ 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 ${R(o, "id", r)} = ${R(s, i.targetKey, r)} WHERE ${R(s, i.sourceKey, r)} = ${R(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), '[]'::jsonb)`;
1016
+ }, Vr = (e, t, n) => e.present.length === 0 ? n`jsonb_build_object()` : n`jsonb_build_object(${n.csv(e.present.map((e) => n`${z(e, n)}, ${R(t, e, n)}`))})`, I = (e, t, n) => t === void 0 || t.length === 0 ? n`` : n` ORDER BY ${n.csv(t.map((t) => t.direction === "desc" ? n`${R(e, t.column, n)} DESC` : n`${R(e, t.column, n)} ASC`))}`, Hr = (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`))}`, Ur = (e, t, n) => {
1017
+ let r = n.sql, i = n.nextAlias(), a = Wr(i, t.table, t.children, n);
1018
1018
  if (a === null) return null;
1019
- let o = e.predicate ? r` WHERE ${H(e.predicate, i, r)}` : r``, s = T(e).length > 0 ? r` ORDER BY ${r.csv(T(e).map((e) => e.direction === "desc" ? r`${z(i, e.column, r)} DESC` : r`${z(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${V(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${V(e.skip, r)}`;
1019
+ let o = e.predicate ? r` WHERE ${V(e.predicate, i, r)}` : r``, s = w(e).length > 0 ? r` ORDER BY ${r.csv(w(e).map((e) => e.direction === "desc" ? r`${R(i, e.column, r)} DESC` : r`${R(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${B(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${B(e.skip, r)}`;
1020
1020
  return r`SELECT ${a} AS "__row" FROM ${r(t.table.tableName)} AS ${r(i)}${o}${s}${c}${l}`;
1021
- }, Ur = (e, t, n, r, i) => {
1021
+ }, Wr = (e, t, n, r, i) => {
1022
1022
  let a = r.sql, o = [];
1023
- for (let n of Object.keys(t.fields)) o.push(a`${B(n, a)}, ${z(e, n, a)}`);
1023
+ for (let n of Object.keys(t.fields)) o.push(a`${z(n, a)}, ${R(e, n, a)}`);
1024
1024
  if (i !== void 0) {
1025
- let e = Wr(i.projection, i.source, a);
1026
- o.push(a`${B("_junction", a)}, json_object(${e})`);
1025
+ let e = Gr(i.projection, i.source, a);
1026
+ o.push(a`${z("_junction", a)}, json_object(${e})`);
1027
1027
  }
1028
1028
  for (let t of n) {
1029
- let n = Jr(t, e, r);
1029
+ let n = Yr(t, e, r);
1030
1030
  if (n === null) return null;
1031
- o.push(a`${B(t.relationName, a)}, ${n}`);
1031
+ o.push(a`${z(t.relationName, a)}, ${n}`);
1032
1032
  }
1033
1033
  return a`json_object(${a.csv(o)})`;
1034
- }, Wr = (e, t, n) => e.present.length === 0 ? n`` : n.csv(e.present.map((e) => n`${B(e, n)}, ${z(t.alias, t.physical(e), n)}`)), Gr = (e, t, n) => e.present.length === 0 ? n`` : n`, ${n.csv(e.present.map((e) => n`${z(t, e, n)} AS ${n(wr(e))}`))}`, Kr = (e) => ({
1034
+ }, Gr = (e, t, n) => e.present.length === 0 ? n`` : n.csv(e.present.map((e) => n`${z(e, n)}, ${R(t.alias, t.physical(e), n)}`)), Kr = (e, t, n) => e.present.length === 0 ? n`` : n`, ${n.csv(e.present.map((e) => n`${R(t, e, n)} AS ${n(Tr(e))}`))}`, qr = (e) => ({
1035
1035
  alias: e,
1036
- physical: wr
1037
- }), qr = (e) => ({
1036
+ physical: Tr
1037
+ }), Jr = (e) => ({
1038
1038
  alias: e,
1039
1039
  physical: (e) => e
1040
- }), Jr = (e, t, n) => {
1040
+ }), Yr = (e, t, n) => {
1041
1041
  switch (e.relation.kind) {
1042
- case "one": return yr(e) ? Xr(br(e), t, n) : Yr(e, t, n);
1043
- case "many": return Xr(e, t, n);
1044
- case "manyToMany": return Zr(e, t, n);
1042
+ case "one": return br(e) ? Zr(xr(e), t, n) : Xr(e, t, n);
1043
+ case "many": return Zr(e, t, n);
1044
+ case "manyToMany": return Qr(e, t, n);
1045
1045
  }
1046
- }, Yr = (e, t, n) => {
1047
- let r = n.sql, i = n.nextAlias(), a = Ur(i, e.target, e.children, n);
1046
+ }, Xr = (e, t, n) => {
1047
+ let r = n.sql, i = n.nextAlias(), a = Wr(i, e.target, e.children, n);
1048
1048
  if (a === null) return null;
1049
- let o = e.fkSide === "source" ? r`${z(i, "id", r)} = ${z(t, e.foreignKey, r)}` : r`${z(i, e.foreignKey, r)} = ${z(t, e.sourceKey, r)}`;
1049
+ let o = e.fkSide === "source" ? r`${R(i, "id", r)} = ${R(t, e.foreignKey, r)}` : r`${R(i, e.foreignKey, r)} = ${R(t, e.sourceKey, r)}`;
1050
1050
  return r`(SELECT ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o} LIMIT 1)`;
1051
- }, Xr = (e, t, n) => {
1052
- let r = n.sql, i = n.nextAlias(), a = Ur(i, e.target, e.children, n);
1051
+ }, Zr = (e, t, n) => {
1052
+ let r = n.sql, i = n.nextAlias(), a = Wr(i, e.target, e.children, n);
1053
1053
  if (a === null) return null;
1054
- let o = r`${z(void 0, e.foreignKey, r)} = ${z(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${I(U(e.branch.where), r)}`, c = Vr(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${V(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${V(e.branch.offset, r)}`;
1054
+ let o = r`${R(void 0, e.foreignKey, r)} = ${R(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${F(H(e.branch.where), r)}`, c = Hr(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${B(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${B(e.branch.offset, r)}`;
1055
1055
  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('[]'))`;
1056
- }, Zr = (e, t, n) => {
1057
- let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = Ur(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1056
+ }, Qr = (e, t, n) => {
1057
+ let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = Wr(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1058
1058
  projection: e.junction,
1059
- source: Kr(o)
1059
+ source: qr(o)
1060
1060
  });
1061
1061
  if (c === null) return null;
1062
- let l = e.branch.where === void 0 ? r`` : r` AND ${I(U(e.branch.where), r)}`, u = pi(e, s, r, !0), d = L(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${V(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${V(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : Gr(e.junction, s, r);
1063
- return r`COALESCE((SELECT json_group_array(${c}) FROM (SELECT ${r(o)}.*${m} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${z(o, "id", r)} = ${z(s, i.targetKey, r)} WHERE ${z(s, i.sourceKey, r)} = ${z(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), json('[]'))`;
1064
- }, Qr = (e, t, n) => {
1065
- let r = n.sql, i = n.nextAlias(), a = R(i, t.table, t.children, n);
1062
+ let l = e.branch.where === void 0 ? r`` : r` AND ${F(H(e.branch.where), r)}`, u = mi(e, s, r, !0), d = I(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${B(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${B(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : Kr(e.junction, s, r);
1063
+ 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 ${R(o, "id", r)} = ${R(s, i.targetKey, r)} WHERE ${R(s, i.sourceKey, r)} = ${R(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), json('[]'))`;
1064
+ }, $r = (e, t, n) => {
1065
+ let r = n.sql, i = n.nextAlias(), a = L(i, t.table, t.children, n);
1066
1066
  if (a === null) return null;
1067
- let o = e.predicate ? r` WHERE ${H(e.predicate, i, r)}` : r``, s = T(e).length > 0 ? r` ORDER BY ${r.csv(T(e).map((e) => e.direction === "desc" ? r`${z(i, e.column, r)} DESC` : r`${z(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${V(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${V(e.skip, r)}`;
1067
+ let o = e.predicate ? r` WHERE ${V(e.predicate, i, r)}` : r``, s = w(e).length > 0 ? r` ORDER BY ${r.csv(w(e).map((e) => e.direction === "desc" ? r`${R(i, e.column, r)} DESC` : r`${R(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${B(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${B(e.skip, r)}`;
1068
1068
  return r`SELECT ${a} AS \`__row\` FROM ${r(t.table.tableName)} AS ${r(i)}${o}${s}${c}${l}`;
1069
- }, R = (e, t, n, r, i) => {
1069
+ }, L = (e, t, n, r, i) => {
1070
1070
  let a = r.sql, o = [];
1071
- for (let n of Object.keys(t.fields)) o.push(a`${B(n, a)}, ${z(e, n, a)}`);
1071
+ for (let n of Object.keys(t.fields)) o.push(a`${z(n, a)}, ${R(e, n, a)}`);
1072
1072
  if (i !== void 0) {
1073
- let e = Wr(i.projection, i.source, a);
1074
- o.push(a`${B("_junction", a)}, JSON_OBJECT(${e})`);
1073
+ let e = Gr(i.projection, i.source, a);
1074
+ o.push(a`${z("_junction", a)}, JSON_OBJECT(${e})`);
1075
1075
  }
1076
1076
  for (let t of n) {
1077
- let n = $r(t, e, r);
1077
+ let n = ei(t, e, r);
1078
1078
  if (n === null) return null;
1079
- o.push(a`${B(t.relationName, a)}, ${n}`);
1079
+ o.push(a`${z(t.relationName, a)}, ${n}`);
1080
1080
  }
1081
1081
  return a`JSON_OBJECT(${a.csv(o)})`;
1082
- }, $r = (e, t, n) => {
1082
+ }, ei = (e, t, n) => {
1083
1083
  switch (e.relation.kind) {
1084
1084
  case "one":
1085
- if (yr(e)) {
1086
- let r = br(e);
1087
- return n.dialect === "mariadb" ? ri(r, t, n) : ti(r, t, n);
1085
+ if (br(e)) {
1086
+ let r = xr(e);
1087
+ return n.dialect === "mariadb" ? ii(r, t, n) : ni(r, t, n);
1088
1088
  }
1089
- return ei(e, t, n);
1090
- case "many": return n.dialect === "mariadb" ? ri(e, t, n) : ti(e, t, n);
1091
- case "manyToMany": return n.dialect === "mariadb" ? ii(e, t, n) : ni(e, t, n);
1089
+ return ti(e, t, n);
1090
+ case "many": return n.dialect === "mariadb" ? ii(e, t, n) : ni(e, t, n);
1091
+ case "manyToMany": return n.dialect === "mariadb" ? ai(e, t, n) : ri(e, t, n);
1092
1092
  }
1093
- }, ei = (e, t, n) => {
1094
- let r = n.sql, i = n.nextAlias(), a = R(i, e.target, e.children, n);
1093
+ }, ti = (e, t, n) => {
1094
+ let r = n.sql, i = n.nextAlias(), a = L(i, e.target, e.children, n);
1095
1095
  if (a === null) return null;
1096
- let o = e.fkSide === "source" ? r`${z(i, "id", r)} = ${z(t, e.foreignKey, r)}` : r`${z(i, e.foreignKey, r)} = ${z(t, e.sourceKey, r)}`;
1096
+ let o = e.fkSide === "source" ? r`${R(i, "id", r)} = ${R(t, e.foreignKey, r)}` : r`${R(i, e.foreignKey, r)} = ${R(t, e.sourceKey, r)}`;
1097
1097
  return r`(SELECT ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o} LIMIT 1)`;
1098
- }, ti = (e, t, n) => {
1099
- let r = n.sql, i = n.nextAlias(), a = R(i, e.target, e.children, n);
1098
+ }, ni = (e, t, n) => {
1099
+ let r = n.sql, i = n.nextAlias(), a = L(i, e.target, e.children, n);
1100
1100
  if (a === null) return null;
1101
- let o = r`${z(void 0, e.foreignKey, r)} = ${z(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${I(U(e.branch.where), r)}`, c = Vr(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${V(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${V(e.branch.offset, r)}`;
1101
+ let o = r`${R(void 0, e.foreignKey, r)} = ${R(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${F(H(e.branch.where), r)}`, c = Hr(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${B(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${B(e.branch.offset, r)}`;
1102
1102
  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())`;
1103
- }, ni = (e, t, n) => {
1104
- let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = R(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1103
+ }, ri = (e, t, n) => {
1104
+ let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = L(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1105
1105
  projection: e.junction,
1106
- source: Kr(o)
1106
+ source: qr(o)
1107
1107
  });
1108
1108
  if (c === null) return null;
1109
- let l = e.branch.where === void 0 ? r`` : r` AND ${I(U(e.branch.where), r)}`, u = pi(e, s, r, !0), d = L(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${V(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${V(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : Gr(e.junction, s, r);
1110
- return r`COALESCE((SELECT JSON_ARRAYAGG(${c}) FROM (SELECT ${r(o)}.*${m} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${z(o, "id", r)} = ${z(s, i.targetKey, r)} WHERE ${z(s, i.sourceKey, r)} = ${z(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), JSON_ARRAY())`;
1111
- }, ri = (e, t, n) => {
1112
- let r = n.sql, i = n.nextAlias(), a = R(i, e.target, e.children, n);
1113
- if (a === null) return null;
1114
- let o = r`${z(i, e.foreignKey, r)} = ${z(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${I(U(e.branch.where), r)}`, c = e.branch.orderBy ?? [];
1115
- if (!(e.branch.limit !== void 0 || e.branch.offset !== void 0)) return r`COALESCE((SELECT JSON_ARRAYAGG(${a}${c.length > 0 ? r` ORDER BY ${r.csv(c.map((e) => e.direction === "desc" ? r`${z(i, e.column, r)} DESC` : r`${z(i, e.column, r)} ASC`))}` : r``}) FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o}${s}), JSON_ARRAY())`;
1116
- let l = c.length > 0 ? r` ORDER BY ${r.csv(c.map((e) => e.direction === "desc" ? r`${r(e.column)} DESC` : r`${r(e.column)} ASC`))}` : r` ORDER BY ${r("id")}`, u = e.branch.limit, d = e.branch.offset, f = u !== void 0 && d !== void 0 ? r` AND ${z(i, "rn", r)} > ${V(d, r)} AND ${z(i, "rn", r)} <= ${V(d + u, r)}` : u === void 0 ? r` AND ${z(i, "rn", r)} > ${V(d, r)}` : r` AND ${z(i, "rn", r)} <= ${V(u, r)}`;
1117
- return r`COALESCE((SELECT JSON_ARRAYAGG(${a} ORDER BY ${z(i, "rn", r)}) FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY ${r(e.foreignKey)}${l}) AS rn FROM ${r(e.target.tableName)}) AS ${r(i)} WHERE ${o}${s}${f}), JSON_ARRAY())`;
1109
+ let l = e.branch.where === void 0 ? r`` : r` AND ${F(H(e.branch.where), r)}`, u = mi(e, s, r, !0), d = I(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${B(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${B(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : Kr(e.junction, s, r);
1110
+ 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 ${R(o, "id", r)} = ${R(s, i.targetKey, r)} WHERE ${R(s, i.sourceKey, r)} = ${R(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), JSON_ARRAY())`;
1118
1111
  }, ii = (e, t, n) => {
1112
+ let r = n.sql, i = n.nextAlias(), a = L(i, e.target, e.children, n);
1113
+ if (a === null) return null;
1114
+ let o = r`${R(i, e.foreignKey, r)} = ${R(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${F(H(e.branch.where), r)}`, c = e.branch.orderBy ?? [];
1115
+ 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`${R(i, e.column, r)} DESC` : r`${R(i, e.column, r)} ASC`))}` : r``}) FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o}${s}), JSON_ARRAY())`;
1116
+ 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 ${R(i, "rn", r)} > ${B(d, r)} AND ${R(i, "rn", r)} <= ${B(d + u, r)}` : u === void 0 ? r` AND ${R(i, "rn", r)} > ${B(d, r)}` : r` AND ${R(i, "rn", r)} <= ${B(u, r)}`;
1117
+ return r`COALESCE((SELECT JSON_ARRAYAGG(${a} ORDER BY ${R(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())`;
1118
+ }, ai = (e, t, n) => {
1119
1119
  let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = (t) => e.junction === void 0 ? void 0 : {
1120
1120
  projection: e.junction,
1121
1121
  source: t
1122
- }, l = r`${z(s, i.sourceKey, r)} = ${z(t, "id", r)}`, u = r`${z(o, "id", r)} = ${z(s, i.targetKey, r)}`, d = e.branch.where === void 0 ? r`` : r` AND ${I(U(e.branch.where), r)}`, f = pi(e, s, r, !0), p = e.branch.orderBy ?? [];
1122
+ }, l = r`${R(s, i.sourceKey, r)} = ${R(t, "id", r)}`, u = r`${R(o, "id", r)} = ${R(s, i.targetKey, r)}`, d = e.branch.where === void 0 ? r`` : r` AND ${F(H(e.branch.where), r)}`, f = mi(e, s, r, !0), p = e.branch.orderBy ?? [];
1123
1123
  if (!(e.branch.limit !== void 0 || e.branch.offset !== void 0)) {
1124
- let t = R(o, e.target, e.children, n, c(qr(s)));
1125
- return t === null ? null : r`COALESCE((SELECT JSON_ARRAYAGG(${t}${p.length > 0 ? r` ORDER BY ${r.csv(p.map((e) => e.direction === "desc" ? r`${z(o, e.column, r)} DESC` : r`${z(o, e.column, r)} ASC`))}` : r``}) FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${u} WHERE ${l}${f}${d}), JSON_ARRAY())`;
1124
+ let t = L(o, e.target, e.children, n, c(Jr(s)));
1125
+ 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`${R(o, e.column, r)} DESC` : r`${R(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())`;
1126
1126
  }
1127
- let m = p.length > 0 ? r` ORDER BY ${r.csv(p.map((e) => e.direction === "desc" ? r`${z(o, e.column, r)} DESC` : r`${z(o, e.column, r)} ASC`))}` : r` ORDER BY ${z(o, "id", r)}`, h = e.branch.limit, g = e.branch.offset, _ = h !== void 0 && g !== void 0 ? r` AND ${z(o, "rn", r)} > ${V(g, r)} AND ${z(o, "rn", r)} <= ${V(g + h, r)}` : h === void 0 ? r` AND ${z(o, "rn", r)} > ${V(g, r)}` : r` AND ${z(o, "rn", r)} <= ${V(h, r)}`, v = e.branch.onJunction === void 0 ? r`` : r` WHERE ${H(U(e.branch.onJunction), s, r)}`, y = R(o, e.target, e.children, n, c(Kr(o)));
1127
+ let m = p.length > 0 ? r` ORDER BY ${r.csv(p.map((e) => e.direction === "desc" ? r`${R(o, e.column, r)} DESC` : r`${R(o, e.column, r)} ASC`))}` : r` ORDER BY ${R(o, "id", r)}`, h = e.branch.limit, g = e.branch.offset, _ = h !== void 0 && g !== void 0 ? r` AND ${R(o, "rn", r)} > ${B(g, r)} AND ${R(o, "rn", r)} <= ${B(g + h, r)}` : h === void 0 ? r` AND ${R(o, "rn", r)} > ${B(g, r)}` : r` AND ${R(o, "rn", r)} <= ${B(h, r)}`, v = e.branch.onJunction === void 0 ? r`` : r` WHERE ${V(H(e.branch.onJunction), s, r)}`, y = L(o, e.target, e.children, n, c(qr(o)));
1128
1128
  if (y === null) return null;
1129
- let b = e.junction === void 0 ? r`` : Gr(e.junction, s, r);
1130
- return r`COALESCE((SELECT JSON_ARRAYAGG(${y} ORDER BY ${z(o, "rn", r)}) FROM (SELECT ${r(o)}.*${b}, ${z(s, i.sourceKey, r)} AS ${r(`__src_${i.sourceKey}`)}, ROW_NUMBER() OVER (PARTITION BY ${z(s, i.sourceKey, r)}${m}) AS rn FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${u}${v}) AS ${r(o)} WHERE ${z(o, `__src_${i.sourceKey}`, r)} = ${z(t, "id", r)}${d}${_}), JSON_ARRAY())`;
1131
- }, ai = (e, t, n) => {
1132
- let r = n.sql, i = n.nextAlias(), a = oi(i, t.table, t.children, n);
1129
+ let b = e.junction === void 0 ? r`` : Kr(e.junction, s, r);
1130
+ return r`COALESCE((SELECT JSON_ARRAYAGG(${y} ORDER BY ${R(o, "rn", r)}) FROM (SELECT ${r(o)}.*${b}, ${R(s, i.sourceKey, r)} AS ${r(`__src_${i.sourceKey}`)}, ROW_NUMBER() OVER (PARTITION BY ${R(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 ${R(o, `__src_${i.sourceKey}`, r)} = ${R(t, "id", r)}${d}${_}), JSON_ARRAY())`;
1131
+ }, oi = (e, t, n) => {
1132
+ let r = n.sql, i = n.nextAlias(), a = si(i, t.table, t.children, n);
1133
1133
  if (a === null) return null;
1134
- let o = e.predicate ? r` WHERE ${H(e.predicate, i, r)}` : r``, s = T(e).length > 0 ? r` ORDER BY ${r.csv(T(e).map((e) => e.direction === "desc" ? r`${z(i, e.column, r)} DESC` : r`${z(i, e.column, r)} ASC`))}` : r``, c = r``, l = r``;
1134
+ let o = e.predicate ? r` WHERE ${V(e.predicate, i, r)}` : r``, s = w(e).length > 0 ? r` ORDER BY ${r.csv(w(e).map((e) => e.direction === "desc" ? r`${R(i, e.column, r)} DESC` : r`${R(i, e.column, r)} ASC`))}` : r``, c = r``, l = r``;
1135
1135
  if (e.skip !== void 0) {
1136
- let t = T(e).length > 0 ? s : r` ORDER BY (SELECT NULL)`;
1137
- l = e.take === void 0 ? r`${t} OFFSET ${V(e.skip, r)} ROWS` : r`${t} OFFSET ${V(e.skip, r)} ROWS FETCH NEXT ${V(e.take, r)} ROWS ONLY`;
1138
- } else e.take !== void 0 && (c = r`TOP ${V(e.take, r)} `);
1136
+ let t = w(e).length > 0 ? s : r` ORDER BY (SELECT NULL)`;
1137
+ l = e.take === void 0 ? r`${t} OFFSET ${B(e.skip, r)} ROWS` : r`${t} OFFSET ${B(e.skip, r)} ROWS FETCH NEXT ${B(e.take, r)} ROWS ONLY`;
1138
+ } else e.take !== void 0 && (c = r`TOP ${B(e.take, r)} `);
1139
1139
  let u = e.skip === void 0 ? s : r``;
1140
1140
  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}`;
1141
- }, oi = (e, t, n, r, i) => {
1141
+ }, si = (e, t, n, r, i) => {
1142
1142
  let a = r.sql, o = [];
1143
- for (let n of Object.keys(t.fields)) o.push(a`${z(e, n, a)} AS ${a(n)}`);
1144
- if (i !== void 0) for (let e of i.projection.present) o.push(a`${z(i.source.alias, i.source.physical(e), a)} AS ${si(`_junction.${e}`, a)}`);
1143
+ for (let n of Object.keys(t.fields)) o.push(a`${R(e, n, a)} AS ${a(n)}`);
1144
+ if (i !== void 0) for (let e of i.projection.present) o.push(a`${R(i.source.alias, i.source.physical(e), a)} AS ${ci(`_junction.${e}`, a)}`);
1145
1145
  for (let t of n) {
1146
- let n = ci(t, e, r);
1146
+ let n = li(t, e, r);
1147
1147
  if (n === null) return null;
1148
1148
  o.push(n);
1149
1149
  }
1150
1150
  return a.csv(o);
1151
- }, si = (e, t) => t.unsafe(`[${e.replace(/]/g, "]]")}]`), ci = (e, t, n) => {
1151
+ }, ci = (e, t) => t.unsafe(`[${e.replace(/]/g, "]]")}]`), li = (e, t, n) => {
1152
1152
  switch (e.relation.kind) {
1153
- case "one": return yr(e) ? di(br(e), t, n) : li(e, t, n);
1154
- case "many": return di(e, t, n);
1155
- case "manyToMany": return fi(e, t, n);
1153
+ case "one": return br(e) ? fi(xr(e), t, n) : ui(e, t, n);
1154
+ case "many": return fi(e, t, n);
1155
+ case "manyToMany": return pi(e, t, n);
1156
1156
  }
1157
- }, li = (e, t, n) => {
1158
- let r = n.sql, i = n.nextAlias(), a = oi(i, e.target, e.children, n);
1157
+ }, ui = (e, t, n) => {
1158
+ let r = n.sql, i = n.nextAlias(), a = si(i, e.target, e.children, n);
1159
1159
  if (a === null) return null;
1160
- let o = e.fkSide === "source" ? r`${z(i, "id", r)} = ${z(t, e.foreignKey, r)}` : r`${z(i, e.foreignKey, r)} = ${z(t, e.sourceKey, r)}`;
1160
+ let o = e.fkSide === "source" ? r`${R(i, "id", r)} = ${R(t, e.foreignKey, r)}` : r`${R(i, e.foreignKey, r)} = ${R(t, e.sourceKey, r)}`;
1161
1161
  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)}`;
1162
- }, ui = (e, t, n) => {
1162
+ }, di = (e, t, n) => {
1163
1163
  if (e.offset !== void 0) {
1164
- let r = e.orderBy && e.orderBy.length > 0 ? t : n` ORDER BY (SELECT NULL)`, i = e.limit === void 0 ? n`${r} OFFSET ${V(e.offset, n)} ROWS` : n`${r} OFFSET ${V(e.offset, n)} ROWS FETCH NEXT ${V(e.limit, n)} ROWS ONLY`;
1164
+ let r = e.orderBy && e.orderBy.length > 0 ? t : n` ORDER BY (SELECT NULL)`, i = e.limit === void 0 ? n`${r} OFFSET ${B(e.offset, n)} ROWS` : n`${r} OFFSET ${B(e.offset, n)} ROWS FETCH NEXT ${B(e.limit, n)} ROWS ONLY`;
1165
1165
  return {
1166
1166
  top: n``,
1167
1167
  pagination: i,
@@ -1169,33 +1169,33 @@ var Mt = (e) => typeof e == "string" && e !== "" ? e : null, Nt = async (e, t, n
1169
1169
  };
1170
1170
  }
1171
1171
  return {
1172
- top: e.limit === void 0 ? n`` : n`TOP ${V(e.limit, n)} `,
1172
+ top: e.limit === void 0 ? n`` : n`TOP ${B(e.limit, n)} `,
1173
1173
  pagination: n``,
1174
1174
  finalOrder: t
1175
1175
  };
1176
- }, di = (e, t, n) => {
1177
- let r = n.sql, i = n.nextAlias(), a = oi(i, e.target, e.children, n);
1178
- if (a === null) return null;
1179
- let o = e.branch.where === void 0 ? r`` : r` AND ${H(e.branch.where, i, r)}`, s = L(i, e.branch.orderBy, r), { top: c, pagination: l, finalOrder: u } = ui(e.branch, s, r);
1180
- return r`ISNULL(JSON_QUERY((SELECT ${c}${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${z(i, e.foreignKey, r)} = ${z(t, e.sourceKey, r)}${o}${u}${l} FOR JSON PATH, INCLUDE_NULL_VALUES)), JSON_QUERY('[]')) AS ${r(e.relationName)}`;
1181
1176
  }, fi = (e, t, n) => {
1182
- let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = oi(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1177
+ let r = n.sql, i = n.nextAlias(), a = si(i, e.target, e.children, n);
1178
+ if (a === null) return null;
1179
+ let o = e.branch.where === void 0 ? r`` : r` AND ${V(e.branch.where, i, r)}`, s = I(i, e.branch.orderBy, r), { top: c, pagination: l, finalOrder: u } = di(e.branch, s, r);
1180
+ return r`ISNULL(JSON_QUERY((SELECT ${c}${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${R(i, e.foreignKey, r)} = ${R(t, e.sourceKey, r)}${o}${u}${l} FOR JSON PATH, INCLUDE_NULL_VALUES)), JSON_QUERY('[]')) AS ${r(e.relationName)}`;
1181
+ }, pi = (e, t, n) => {
1182
+ let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = si(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1183
1183
  projection: e.junction,
1184
- source: qr(s)
1184
+ source: Jr(s)
1185
1185
  });
1186
1186
  if (c === null) return null;
1187
- let l = e.branch.where === void 0 ? r`` : r` AND ${H(e.branch.where, o, r)}`, u = pi(e, s, r), d = L(o, e.branch.orderBy, r), { top: f, pagination: p, finalOrder: m } = ui(e.branch, d, r);
1188
- return r`ISNULL(JSON_QUERY((SELECT ${f}${c} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${z(o, "id", r)} = ${z(s, i.targetKey, r)} WHERE ${z(s, i.sourceKey, r)} = ${z(t, "id", r)}${u}${l}${m}${p} FOR JSON PATH, INCLUDE_NULL_VALUES)), JSON_QUERY('[]')) AS ${r(e.relationName)}`;
1189
- }, z = (e, t, n) => e === void 0 ? n`${n(t)}` : n`${n(e)}.${n(t)}`, B = (e, t) => t.unsafe(`'${e.replace(/'/g, "''")}'`), V = (e, t) => {
1187
+ let l = e.branch.where === void 0 ? r`` : r` AND ${V(e.branch.where, o, r)}`, u = mi(e, s, r), d = I(o, e.branch.orderBy, r), { top: f, pagination: p, finalOrder: m } = di(e.branch, d, r);
1188
+ 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 ${R(o, "id", r)} = ${R(s, i.targetKey, r)} WHERE ${R(s, i.sourceKey, r)} = ${R(t, "id", r)}${u}${l}${m}${p} FOR JSON PATH, INCLUDE_NULL_VALUES)), JSON_QUERY('[]')) AS ${r(e.relationName)}`;
1189
+ }, R = (e, t, n) => e === void 0 ? n`${n(t)}` : n`${n(e)}.${n(t)}`, z = (e, t) => t.unsafe(`'${e.replace(/'/g, "''")}'`), B = (e, t) => {
1190
1190
  if (!Number.isFinite(e) || !Number.isInteger(e) || e < 0) throw Error(`literalInt: expected non-negative integer, got ${e}`);
1191
1191
  return t.unsafe(String(e));
1192
- }, H = (e, t, n) => I(mi(e, t), n), pi = (e, t, n, r = !1) => {
1192
+ }, V = (e, t, n) => F(hi(e, t), n), mi = (e, t, n, r = !1) => {
1193
1193
  let i = e.branch.onJunction;
1194
- return i === void 0 ? n`` : n` AND ${H(r ? U(i) : i, t, n)}`;
1195
- }, mi = (e, t) => {
1196
- if ("not" in e) return { not: mi(e.not, t) };
1197
- if ("and" in e) return { and: e.and.map((e) => mi(e, t)) };
1198
- if ("or" in e) return { or: e.or.map((e) => mi(e, t)) };
1194
+ return i === void 0 ? n`` : n` AND ${V(r ? H(i) : i, t, n)}`;
1195
+ }, hi = (e, t) => {
1196
+ if ("not" in e) return { not: hi(e.not, t) };
1197
+ if ("and" in e) return { and: e.and.map((e) => hi(e, t)) };
1198
+ if ("or" in e) return { or: e.or.map((e) => hi(e, t)) };
1199
1199
  if (e.op === "subquery-in" || e.op === "subquery-not-in") {
1200
1200
  let n = e;
1201
1201
  return {
@@ -1209,99 +1209,99 @@ var Mt = (e) => typeof e == "string" && e !== "" ? e : null, Nt = async (e, t, n
1209
1209
  ...n,
1210
1210
  column: `${t}.${n.column}`
1211
1211
  };
1212
- }, U = (e) => {
1213
- if ("not" in e) return { not: U(e.not) };
1214
- if ("and" in e) return { and: e.and.map((e) => U(e)) };
1215
- if ("or" in e) return { or: e.or.map((e) => U(e)) };
1212
+ }, H = (e) => {
1213
+ if ("not" in e) return { not: H(e.not) };
1214
+ if ("and" in e) return { and: e.and.map((e) => H(e)) };
1215
+ if ("or" in e) return { or: e.or.map((e) => H(e)) };
1216
1216
  if (e.op === "subquery-in" || e.op === "subquery-not-in" || e.op === "exists" || e.op === "not-exists") return e;
1217
1217
  let t = e;
1218
1218
  return {
1219
1219
  ...t,
1220
- value: hi(t.value)
1220
+ value: gi(t.value)
1221
1221
  };
1222
- }, hi = (e) => e == null ? e : e instanceof Date ? e.toISOString() : typeof e == "boolean" ? +!!e : Array.isArray(e) ? e.map((e) => hi(e)) : e, gi = Symbol.for("@voltro/database/coreTablesRegistry"), _i = globalThis, vi = _i[gi] ?? (_i[gi] = {}), yi = (e) => {
1223
- e.actors !== void 0 && (vi.actors = e.actors), e.tenants !== void 0 && (vi.tenants = e.tenants);
1224
- }, bi = (e, t) => () => {
1222
+ }, gi = (e) => e == null ? e : e instanceof Date ? e.toISOString() : typeof e == "boolean" ? +!!e : Array.isArray(e) ? e.map((e) => gi(e)) : e, _i = Symbol.for("@voltro/database/coreTablesRegistry"), vi = globalThis, yi = vi[_i] ?? (vi[_i] = {}), bi = (e) => {
1223
+ e.actors !== void 0 && (yi.actors = e.actors), e.tenants !== void 0 && (yi.tenants = e.tenants);
1224
+ }, xi = (e, t) => () => {
1225
1225
  let n = e();
1226
1226
  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`);
1227
1227
  return n();
1228
- }, xi = () => bi(() => vi.actors, "actors"), Si = () => bi(() => vi.tenants, "tenants"), Ci = w("actors", {
1228
+ }, Si = () => xi(() => yi.actors, "actors"), Ci = () => xi(() => yi.tenants, "tenants"), wi = C("actors", {
1229
1229
  id: v(),
1230
- kind: D().oneOf([
1230
+ kind: E().oneOf([
1231
1231
  "user",
1232
1232
  "serviceAccount",
1233
1233
  "apiKey",
1234
1234
  "system"
1235
1235
  ]),
1236
- displayName: D().nullable(),
1236
+ displayName: E().nullable(),
1237
1237
  createdAt: b().default("now")
1238
- }), wi = (e, t) => ({
1238
+ }), Ti = (e, t) => ({
1239
1239
  column: e,
1240
1240
  op: "eq",
1241
1241
  value: t
1242
- }), Ti = (e, t) => ({
1242
+ }), Ei = (e, t) => ({
1243
1243
  column: e,
1244
1244
  op: "neq",
1245
1245
  value: t
1246
- }), Ei = (e, t) => ({
1246
+ }), Di = (e, t) => ({
1247
1247
  column: e,
1248
1248
  op: "gt",
1249
1249
  value: t
1250
- }), Di = (e, t) => ({
1250
+ }), Oi = (e, t) => ({
1251
1251
  column: e,
1252
1252
  op: "gte",
1253
1253
  value: t
1254
- }), Oi = (e, t) => ({
1254
+ }), ki = (e, t) => ({
1255
1255
  column: e,
1256
1256
  op: "lt",
1257
1257
  value: t
1258
- }), ki = (e, t) => ({
1258
+ }), Ai = (e, t) => ({
1259
1259
  column: e,
1260
1260
  op: "lte",
1261
1261
  value: t
1262
- }), Ai = (e, t) => ({
1262
+ }), ji = (e, t) => ({
1263
1263
  column: e,
1264
1264
  op: "in",
1265
1265
  value: t
1266
- }), ji = (e, t) => ({
1266
+ }), Mi = (e, t) => ({
1267
1267
  column: e,
1268
1268
  op: "notIn",
1269
1269
  value: t
1270
- }), Mi = (e, t) => ({
1270
+ }), Ni = (e, t) => ({
1271
1271
  column: e,
1272
1272
  op: "contains",
1273
1273
  value: t
1274
- }), Ni = (e, t) => ({
1274
+ }), Pi = (e, t) => ({
1275
1275
  column: e,
1276
1276
  op: "startsWith",
1277
1277
  value: t
1278
- }), Pi = (e, t) => ({
1278
+ }), Fi = (e, t) => ({
1279
1279
  column: e,
1280
1280
  op: "arrayContains",
1281
1281
  value: t
1282
- }), Fi = (e, t) => ({
1282
+ }), Ii = (e, t) => ({
1283
1283
  column: e,
1284
1284
  op: "arrayOverlaps",
1285
1285
  value: t
1286
- }), Ii = (e, t) => ({
1286
+ }), Li = (e, t) => ({
1287
1287
  column: e,
1288
1288
  op: "arrayHas",
1289
1289
  value: t
1290
- }), Li = {
1290
+ }), Ri = {
1291
1291
  column: "id",
1292
1292
  op: "in",
1293
1293
  value: []
1294
- }, Ri = (e) => ({
1294
+ }, zi = (e) => ({
1295
1295
  column: e,
1296
1296
  op: "isNull"
1297
- }), zi = (e) => ({
1297
+ }), Bi = (e) => ({
1298
1298
  column: e,
1299
1299
  op: "isNotNull"
1300
- }), Bi = (e, t) => ({
1300
+ }), Vi = (e, t) => ({
1301
1301
  column: e,
1302
1302
  op: "spatial",
1303
1303
  value: t
1304
- }), Vi = (...e) => ({ and: e }), Hi = (...e) => ({ or: e }), Ui = (e) => ({ not: e }), Wi = (e, ...t) => {
1304
+ }), Hi = (...e) => ({ and: e }), Ui = (...e) => ({ or: e }), Wi = (e) => ({ not: e }), Gi = (e, ...t) => {
1305
1305
  if (t.length === 0) throw Error(`jsonField("${e}"): at least one path segment is required`);
1306
1306
  let n = (n, r) => ({
1307
1307
  column: e,
@@ -1323,33 +1323,33 @@ var Mt = (e) => typeof e == "string" && e !== "" ? e : null, Nt = async (e, t, n
1323
1323
  isNull: () => n("isNull"),
1324
1324
  isNotNull: () => n("isNotNull")
1325
1325
  };
1326
- }, Gi = (e) => "descriptor" in e ? e.descriptor : e, Ki = (e, t) => ({
1326
+ }, Ki = (e) => "descriptor" in e ? e.descriptor : e, qi = (e, t) => ({
1327
1327
  column: e,
1328
1328
  op: "subquery-in",
1329
- subquery: Gi(t)
1330
- }), qi = (e, t) => ({
1329
+ subquery: Ki(t)
1330
+ }), Ji = (e, t) => ({
1331
1331
  column: e,
1332
1332
  op: "subquery-not-in",
1333
- subquery: Gi(t)
1334
- }), Ji = (e) => ({
1335
- op: "exists",
1336
- subquery: Gi(e)
1333
+ subquery: Ki(t)
1337
1334
  }), Yi = (e) => ({
1335
+ op: "exists",
1336
+ subquery: Ki(e)
1337
+ }), Xi = (e) => ({
1338
1338
  op: "not-exists",
1339
- subquery: Gi(e)
1340
- }), Xi = (e, t) => e === t || e instanceof Date && t instanceof Date && e.getTime() === t.getTime(), Zi = (e, t) => {
1339
+ subquery: Ki(e)
1340
+ }), Zi = (e, t) => e === t || e instanceof Date && t instanceof Date && e.getTime() === t.getTime(), Qi = (e, t) => {
1341
1341
  if (e == null || t == null) return null;
1342
1342
  let n = e instanceof Date ? e.getTime() : e, r = t instanceof Date ? t.getTime() : t;
1343
1343
  return typeof n == typeof r ? n === r ? 0 : n > r ? 1 : -1 : null;
1344
- }, Qi = (e, t, n = null) => {
1344
+ }, $i = (e, t, n = null) => {
1345
1345
  if (!t) return !1;
1346
- if ("not" in e) return !Qi(e.not, t, n);
1346
+ if ("not" in e) return !$i(e.not, t, n);
1347
1347
  if ("and" in e) {
1348
- for (let r of e.and) if (!Qi(r, t, n)) return !1;
1348
+ for (let r of e.and) if (!$i(r, t, n)) return !1;
1349
1349
  return !0;
1350
1350
  }
1351
1351
  if ("or" in e) {
1352
- for (let r of e.or) if (Qi(r, t, n)) return !0;
1352
+ for (let r of e.or) if ($i(r, t, n)) return !0;
1353
1353
  return !1;
1354
1354
  }
1355
1355
  if (e.op === "subquery-in" || e.op === "subquery-not-in") {
@@ -1366,14 +1366,14 @@ var Mt = (e) => typeof e == "string" && e !== "" ? e : null, Nt = async (e, t, n
1366
1366
  }
1367
1367
  let r = e, i = t[r.column];
1368
1368
  switch (r.op) {
1369
- case "eq": return Xi(i, r.value);
1370
- case "neq": return !Xi(i, r.value);
1371
- case "gt": return (Zi(i, r.value) ?? -1) > 0;
1372
- case "gte": return (Zi(i, r.value) ?? -1) >= 0;
1373
- case "lt": return (Zi(i, r.value) ?? 1) < 0;
1374
- case "lte": return (Zi(i, r.value) ?? 1) <= 0;
1375
- case "in": return Array.isArray(r.value) && r.value.some((e) => Xi(i, e));
1376
- case "notIn": return Array.isArray(r.value) && !r.value.some((e) => Xi(i, e));
1369
+ case "eq": return Zi(i, r.value);
1370
+ case "neq": return !Zi(i, r.value);
1371
+ case "gt": return (Qi(i, r.value) ?? -1) > 0;
1372
+ case "gte": return (Qi(i, r.value) ?? -1) >= 0;
1373
+ case "lt": return (Qi(i, r.value) ?? 1) < 0;
1374
+ case "lte": return (Qi(i, r.value) ?? 1) <= 0;
1375
+ case "in": return Array.isArray(r.value) && r.value.some((e) => Zi(i, e));
1376
+ case "notIn": return Array.isArray(r.value) && !r.value.some((e) => Zi(i, e));
1377
1377
  case "contains": return typeof i == "string" && typeof r.value == "string" && i.toLowerCase().includes(r.value.toLowerCase());
1378
1378
  case "startsWith": return typeof i == "string" && typeof r.value == "string" && i.startsWith(r.value);
1379
1379
  case "arrayContains": {
@@ -1389,17 +1389,17 @@ var Mt = (e) => typeof e == "string" && e !== "" ? e : null, Nt = async (e, t, n
1389
1389
  case "isNotNull": return i != null;
1390
1390
  case "spatial": throw Error("@voltro/plugin-postgis: spatial predicates (ST_DWithin / ST_Contains / ST_Within / ST_Intersects / bbox &&) are not evaluable in-memory — use them in one-shot ctx.store.query reads, not reactive subscriptions.");
1391
1391
  }
1392
- }, $i = function* (e) {
1392
+ }, ea = function* (e) {
1393
1393
  if ("not" in e) {
1394
- yield* $i(e.not);
1394
+ yield* ea(e.not);
1395
1395
  return;
1396
1396
  }
1397
1397
  if ("and" in e) {
1398
- for (let t of e.and) yield* $i(t);
1398
+ for (let t of e.and) yield* ea(t);
1399
1399
  return;
1400
1400
  }
1401
1401
  if ("or" in e) {
1402
- for (let t of e.or) yield* $i(t);
1402
+ for (let t of e.or) yield* ea(t);
1403
1403
  return;
1404
1404
  }
1405
1405
  e.op === "subquery-in" || e.op === "subquery-not-in" ? yield {
@@ -1409,42 +1409,46 @@ var Mt = (e) => typeof e == "string" && e !== "" ? e : null, Nt = async (e, t, n
1409
1409
  kind: "exists",
1410
1410
  descriptor: e.subquery
1411
1411
  });
1412
- }, ea = function* (e, t = !0) {
1412
+ }, ta = function* (e, t = !0) {
1413
1413
  if ("not" in e) {
1414
- yield* ea(e.not, !1);
1414
+ yield* ta(e.not, !1);
1415
1415
  return;
1416
1416
  }
1417
1417
  if ("and" in e) {
1418
- for (let n of e.and) yield* ea(n, t);
1418
+ for (let n of e.and) yield* ta(n, t);
1419
1419
  return;
1420
1420
  }
1421
1421
  if ("or" in e) {
1422
- for (let t of e.or) yield* ea(t, !1);
1422
+ for (let t of e.or) yield* ta(t, !1);
1423
1423
  return;
1424
1424
  }
1425
1425
  e.op === "subquery-in" || e.op === "subquery-not-in" || e.op === "exists" || e.op === "not-exists" || (yield {
1426
1426
  ...e,
1427
1427
  conjunctive: t
1428
1428
  });
1429
- }, ta = (e, t, n = {}) => ({
1429
+ }, na = (e, t) => ({
1430
+ ...t,
1431
+ ...e,
1432
+ origin: e.origin ?? "injected"
1433
+ }), ra = (e, t, n = {}) => ({
1430
1434
  table: e,
1431
1435
  op: "insert",
1432
1436
  old: null,
1433
1437
  new: t,
1434
1438
  ...n
1435
- }), na = (e, t, n, r = {}) => ({
1439
+ }), ia = (e, t, n, r = {}) => ({
1436
1440
  table: e,
1437
1441
  op: "update",
1438
1442
  old: t,
1439
1443
  new: n,
1440
1444
  ...r
1441
- }), ra = (e, t, n = {}) => ({
1445
+ }), aa = (e, t, n = {}) => ({
1442
1446
  table: e,
1443
1447
  op: "delete",
1444
1448
  old: t,
1445
1449
  new: null,
1446
1450
  ...n
1447
- }), ia = (e, t, n = {}) => {
1451
+ }), oa = (e, t, n = {}) => {
1448
1452
  let { at: r = "2026-01-01T00:00:00.000Z", column: i = "deletedAt", ...a } = n;
1449
1453
  return {
1450
1454
  table: e,
@@ -1459,67 +1463,67 @@ var Mt = (e) => typeof e == "string" && e !== "" ? e : null, Nt = async (e, t, n
1459
1463
  },
1460
1464
  ...a
1461
1465
  };
1462
- }, aa = new Ot(), oa = (e, t) => aa.run(e, t), sa = () => aa.getStore(), ca = (e) => {
1463
- let t = e ?? aa.getStore();
1466
+ }, sa = new kt(), ca = (e, t) => sa.run(e, t), la = () => sa.getStore(), ua = (e) => {
1467
+ let t = e ?? sa.getStore();
1464
1468
  return t === void 0 ? {} : {
1465
1469
  ...t.traceId === void 0 ? {} : { traceId: t.traceId },
1466
1470
  ...t.subjectId === void 0 ? {} : { subjectId: t.subjectId },
1467
1471
  ...t.procedure === void 0 ? {} : { procedure: t.procedure },
1468
1472
  ...t.via === void 0 ? {} : { via: t.via }
1469
1473
  };
1470
- }, la = (e) => {
1471
- let t = aa.getStore();
1472
- return t === void 0 ? e(void 0) : aa.run(t, () => e(t));
1473
- }, ua = 3e4, da = 1e4, W = /* @__PURE__ */ new Map(), G = 0, fa = (e, t, n) => `${e}\u0000${t}\u0000${String(n)}`, pa = (e) => {
1474
- for (let [t, n] of W) {
1475
- let r = n.filter((t) => e - t.at < ua);
1476
- G -= n.length - r.length, r.length === 0 ? W.delete(t) : r.length !== n.length && W.set(t, r);
1477
- }
1478
- }, ma = (e, t) => {
1474
+ }, da = (e) => {
1475
+ let t = sa.getStore();
1476
+ return t === void 0 ? e(void 0) : sa.run(t, () => e(t));
1477
+ }, fa = 3e4, pa = 1e4, U = /* @__PURE__ */ new Map(), W = 0, ma = (e, t, n) => `${e}\u0000${t}\u0000${String(n)}`, ha = (e) => {
1478
+ for (let [t, n] of U) {
1479
+ let r = n.filter((t) => e - t.at < fa);
1480
+ W -= n.length - r.length, r.length === 0 ? U.delete(t) : r.length !== n.length && U.set(t, r);
1481
+ }
1482
+ }, ga = (e, t) => {
1479
1483
  if (t.traceId === void 0 && t.subjectId === void 0 && t.procedure === void 0) return;
1480
1484
  let n = Date.now();
1481
- if (G >= da && pa(n), G >= da) return;
1482
- let r = W.get(e);
1483
- r === void 0 ? W.set(e, [{
1485
+ if (W >= pa && ha(n), W >= pa) return;
1486
+ let r = U.get(e);
1487
+ r === void 0 ? U.set(e, [{
1484
1488
  attribution: t,
1485
1489
  at: n
1486
1490
  }]) : r.push({
1487
1491
  attribution: t,
1488
1492
  at: n
1489
- }), G += 1;
1490
- }, ha = (e) => {
1491
- let t = W.get(e);
1493
+ }), W += 1;
1494
+ }, _a = (e) => {
1495
+ let t = U.get(e);
1492
1496
  if (t === void 0 || t.length === 0) return;
1493
1497
  let n = t.shift();
1494
- if (--G, t.length === 0 && W.delete(e), !(Date.now() - n.at >= ua)) return n.attribution;
1495
- }, ga = (e) => (W.get(e)?.length ?? 0) > 0, K = /* @__PURE__ */ new Map(), _a = /* @__PURE__ */ new Map(), va = /* @__PURE__ */ new Map(), ya = 250, ba = (e) => {
1496
- let t = _a.get(e);
1498
+ if (--W, t.length === 0 && U.delete(e), !(Date.now() - n.at >= fa)) return n.attribution;
1499
+ }, va = (e) => (U.get(e)?.length ?? 0) > 0, G = /* @__PURE__ */ new Map(), K = /* @__PURE__ */ new Map(), ya = /* @__PURE__ */ new Map(), ba = 250, xa = (e) => {
1500
+ let t = K.get(e);
1497
1501
  if (t === void 0) return;
1498
- _a.delete(e);
1499
- let n = va.get(e);
1500
- n !== void 0 && (clearTimeout(n), va.delete(e));
1502
+ K.delete(e);
1503
+ let n = ya.get(e);
1504
+ n !== void 0 && (clearTimeout(n), ya.delete(e));
1501
1505
  for (let e of t) e();
1502
- }, xa = (e) => {
1503
- K.set(e, (K.get(e) ?? 0) + 1);
1504
1506
  }, Sa = (e) => {
1505
- let t = (K.get(e) ?? 0) - 1;
1507
+ G.set(e, (G.get(e) ?? 0) + 1);
1508
+ }, Ca = (e) => {
1509
+ let t = (G.get(e) ?? 0) - 1;
1506
1510
  if (t > 0) {
1507
- K.set(e, t);
1511
+ G.set(e, t);
1508
1512
  return;
1509
1513
  }
1510
- K.delete(e), ba(e);
1511
- }, Ca = (e, t, n, r) => {
1512
- let i = n == null ? void 0 : fa(e, t, n), a = () => r(i === void 0 ? void 0 : ha(i));
1514
+ G.delete(e), xa(e);
1515
+ }, wa = (e, t, n, r) => {
1516
+ let i = n == null ? void 0 : ma(e, t, n), a = () => r(i === void 0 ? void 0 : _a(i));
1513
1517
  if (i === void 0) {
1514
1518
  a();
1515
1519
  return;
1516
1520
  }
1517
- if (ga(i)) {
1521
+ if (va(i)) {
1518
1522
  a();
1519
1523
  return;
1520
1524
  }
1521
- let o = _a.get(e);
1522
- if (o === void 0 && (K.get(e) ?? 0) === 0) {
1525
+ let o = K.get(e);
1526
+ if (o === void 0 && (G.get(e) ?? 0) === 0) {
1523
1527
  a();
1524
1528
  return;
1525
1529
  }
@@ -1527,75 +1531,75 @@ var Mt = (e) => typeof e == "string" && e !== "" ? e : null, Nt = async (e, t, n
1527
1531
  o.push(a);
1528
1532
  return;
1529
1533
  }
1530
- _a.set(e, [a]);
1531
- let s = setTimeout(() => ba(e), ya);
1532
- typeof s == "object" && typeof s.unref == "function" && s.unref(), va.set(e, s);
1533
- }, wa = () => {
1534
- W.clear(), G = 0, K.clear();
1535
- for (let e of va.values()) clearTimeout(e);
1536
- va.clear(), _a.clear();
1537
- }, Ta = () => G, q = /* @__PURE__ */ new Map(), Ea = (e, t) => {
1534
+ K.set(e, [a]);
1535
+ let s = setTimeout(() => xa(e), ba);
1536
+ typeof s == "object" && typeof s.unref == "function" && s.unref(), ya.set(e, s);
1537
+ }, Ta = () => {
1538
+ U.clear(), W = 0, G.clear();
1539
+ for (let e of ya.values()) clearTimeout(e);
1540
+ ya.clear(), K.clear();
1541
+ }, Ea = () => W, q = /* @__PURE__ */ new Map(), Da = (e, t) => {
1538
1542
  q.set(e, {
1539
1543
  recorder: t.recorder,
1540
1544
  tables: new Set(t.tables),
1541
1545
  ownTables: new Set(t.ownTables)
1542
1546
  });
1543
- }, Da = (e) => {
1547
+ }, Oa = (e) => {
1544
1548
  q.delete(e);
1545
- }, Oa = () => q.clear(), ka = (e) => {
1549
+ }, ka = () => q.clear(), Aa = (e) => {
1546
1550
  if (q.size === 0) return !1;
1547
1551
  for (let t of q.values()) if (!t.ownTables.has(e) && t.tables.has(e)) return !0;
1548
1552
  return !1;
1549
- }, Aa = async (e, t) => {
1553
+ }, ja = async (e, t) => {
1550
1554
  if (q.size !== 0) for (let n of q.values()) n.ownTables.has(t.table) || n.tables.has(t.table) && await n.recorder(e, t);
1551
- }, ja = Tt.exponential({
1555
+ }, Ma = Et.exponential({
1552
1556
  start: 5e-4,
1553
1557
  factor: 2,
1554
1558
  count: 16
1555
- }), Ma = A.counter("voltro_db_queries_total", { description: "Database operations executed, by dialect and operation kind." }), Na = A.histogram("voltro_db_query_duration_seconds", ja, "Database operation duration in seconds, by dialect and operation kind."), Pa = A.counter("voltro_db_errors_total", { description: "Database operations that threw, by dialect and operation kind." }), Fa = A.gauge("voltro_db_operations_in_flight", { description: "Database operations currently executing, by dialect. An upper bound on connections the framework holds; NOT the driver pool's waiting count." }), Ia = A.counter("voltro_db_eager_fallback_total", { description: "Eager-load queries that degraded from the single-roundtrip JSON-agg path to the multi-query walker, by dialect and reason." }), La = [], Ra = /* @__PURE__ */ new Map(), za = /* @__PURE__ */ new Map(), Ba = /* @__PURE__ */ new Map(), Va = (e, t) => {
1556
- let n = `${e}\u0000${t}`, r = Ra.get(n);
1559
+ }), Na = k.counter("voltro_db_queries_total", { description: "Database operations executed, by dialect and operation kind." }), Pa = k.histogram("voltro_db_query_duration_seconds", Ma, "Database operation duration in seconds, by dialect and operation kind."), Fa = k.counter("voltro_db_errors_total", { description: "Database operations that threw, by dialect and operation kind." }), Ia = k.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." }), La = k.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." }), Ra = [], za = /* @__PURE__ */ new Map(), Ba = /* @__PURE__ */ new Map(), Va = /* @__PURE__ */ new Map(), Ha = (e, t) => {
1560
+ let n = `${e}\u0000${t}`, r = za.get(n);
1557
1561
  if (r !== void 0) return r;
1558
- let i = (n) => A.tagged(A.tagged(n, "dialect", e), "op", t), a = {
1559
- count: i(Ma),
1560
- duration: i(Na),
1561
- errors: i(Pa)
1562
+ let i = (n) => k.tagged(k.tagged(n, "dialect", e), "op", t), a = {
1563
+ count: i(Na),
1564
+ duration: i(Pa),
1565
+ errors: i(Fa)
1562
1566
  };
1563
- return Ra.set(n, a), a;
1564
- }, Ha = () => {
1565
- Ra.clear(), za.clear(), Ba.clear();
1566
- }, Ua = () => Ra.size + za.size + Ba.size, Wa = /* @__PURE__ */ new Map(), Ga = (e, t) => {
1567
- let n = Math.max(0, (Wa.get(e) ?? 0) + t);
1568
- n === 0 ? Wa.delete(e) : Wa.set(e, n);
1569
- let r = za.get(e);
1570
- r === void 0 && (r = A.tagged(Fa, "dialect", e), za.set(e, r)), r.unsafeUpdate(n, La);
1571
- }, Ka = (e) => Wa.get(e) ?? 0, qa = (e) => {
1572
- let t = Va(String(e.dialect), e.op);
1573
- t.count.unsafeUpdate(1, La), t.duration.unsafeUpdate(e.durationMs / 1e3, La), e.status === "error" && t.errors.unsafeUpdate(1, La);
1574
- }, Ja = async (e, t, n) => {
1567
+ return za.set(n, a), a;
1568
+ }, Ua = () => {
1569
+ za.clear(), Ba.clear(), Va.clear();
1570
+ }, Wa = () => za.size + Ba.size + Va.size, Ga = /* @__PURE__ */ new Map(), Ka = (e, t) => {
1571
+ let n = Math.max(0, (Ga.get(e) ?? 0) + t);
1572
+ n === 0 ? Ga.delete(e) : Ga.set(e, n);
1573
+ let r = Ba.get(e);
1574
+ r === void 0 && (r = k.tagged(Ia, "dialect", e), Ba.set(e, r)), r.unsafeUpdate(n, Ra);
1575
+ }, qa = (e) => Ga.get(e) ?? 0, Ja = (e) => {
1576
+ let t = Ha(String(e.dialect), e.op);
1577
+ t.count.unsafeUpdate(1, Ra), t.duration.unsafeUpdate(e.durationMs / 1e3, Ra), e.status === "error" && t.errors.unsafeUpdate(1, Ra);
1578
+ }, Ya = async (e, t, n) => {
1575
1579
  let r = performance.now(), i = String(e);
1576
- Ga(i, 1);
1580
+ Ka(i, 1);
1577
1581
  let a = "ok";
1578
1582
  try {
1579
1583
  return await n();
1580
1584
  } catch (e) {
1581
1585
  throw a = "error", e;
1582
1586
  } finally {
1583
- Ga(i, -1), qa({
1587
+ Ka(i, -1), Ja({
1584
1588
  dialect: e,
1585
1589
  op: t,
1586
1590
  durationMs: performance.now() - r,
1587
1591
  status: a
1588
1592
  });
1589
1593
  }
1590
- }, Ya = 3e5, Xa = (e) => {
1594
+ }, Xa = 3e5, Za = (e) => {
1591
1595
  if (e == null || e === "") return;
1592
1596
  let t = Number(e);
1593
1597
  return Number.isFinite(t) && t >= 0 ? Math.floor(t) : void 0;
1594
- }, Za = (e, t = process.env) => Xa(t.VOLTRO_DB_EAGER_FALLBACK_WARN_INTERVAL_MS) ?? Xa(e) ?? 3e5, Qa = (e, t = {}) => {
1595
- let n = Za(t.warnIntervalMs), r = t.now ?? (() => Date.now()), i = /* @__PURE__ */ new Map();
1598
+ }, Qa = (e, t = process.env) => Za(t.VOLTRO_DB_EAGER_FALLBACK_WARN_INTERVAL_MS) ?? Za(e) ?? 3e5, $a = (e, t = {}) => {
1599
+ let n = Qa(t.warnIntervalMs), r = t.now ?? (() => Date.now()), i = /* @__PURE__ */ new Map();
1596
1600
  return (t) => {
1597
- let a = `${t.dialect} ${t.reason}`, o = Ba.get(a);
1598
- o === void 0 && (o = A.tagged(A.tagged(Ia, "dialect", String(t.dialect)), "reason", t.reason), Ba.set(a, o)), o.unsafeUpdate(1, La);
1601
+ let a = `${t.dialect} ${t.reason}`, o = Va.get(a);
1602
+ o === void 0 && (o = k.tagged(k.tagged(La, "dialect", String(t.dialect)), "reason", t.reason), Va.set(a, o)), o.unsafeUpdate(1, Ra);
1599
1603
  let s = `${t.table}\u0000${t.reason}`, c = i.get(s), l = c === void 0 || n > 0 && r() - c >= n, u = {
1600
1604
  table: t.table,
1601
1605
  dialect: String(t.dialect),
@@ -1609,24 +1613,24 @@ var Mt = (e) => typeof e == "string" && e !== "" ? e : null, Nt = async (e, t, n
1609
1613
  }
1610
1614
  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);
1611
1615
  };
1612
- }, $a = (e) => {
1613
- if (wt.isSuccess(e)) return e.value;
1614
- throw xt.squash(e.cause);
1615
- }, eo = "10 millis", to = 3, no = async (e) => {
1616
- let t = 0, n = k.suspend(() => {
1616
+ }, eo = (e) => {
1617
+ if (Tt.isSuccess(e)) return e.value;
1618
+ throw St.squash(e.cause);
1619
+ }, to = "10 millis", no = 3, ro = async (e) => {
1620
+ let t = 0, n = O.suspend(() => {
1617
1621
  let n = ++t;
1618
- return e.withTransaction(k.flatMap(k.serviceOption(kt), (t) => {
1619
- if (j.isNone(t)) return k.fail(/* @__PURE__ */ Error(`${e.label}: TransactionConnection unexpectedly missing inside withTransaction.`));
1620
- let r = t.value, i = k.tryPromise({
1622
+ return e.withTransaction(O.flatMap(O.serviceOption(At), (t) => {
1623
+ if (A.isNone(t)) return O.fail(/* @__PURE__ */ Error(`${e.label}: TransactionConnection unexpectedly missing inside withTransaction.`));
1624
+ let r = t.value, i = O.tryPromise({
1621
1625
  try: () => e.body(r, n),
1622
1626
  catch: (e) => e
1623
1627
  });
1624
- return e.prepare === void 0 ? i : k.flatMap(e.prepare(r), () => i);
1625
- })).pipe(k.catchAllDefect((t) => e.isRetryable(t) ? k.fail(t) : k.die(t)));
1626
- }), r = Et.exponential(eo).pipe(Et.compose(Et.recurs(to)), Et.whileInput(e.isRetryable)), i = n.pipe(k.retry(r), k.withSpan(e.span.name, { attributes: { ...e.span.attributes } }));
1627
- return Ja(e.dialect, "transaction", async () => $a(await e.runPromiseExit(e.wrapProgram === void 0 ? i : e.wrapProgram(i))));
1628
- }, ro = async (e) => {
1629
- let t = sa(), n = t === void 0 ? (e) => e() : (e) => oa(t, e), r = await no({
1628
+ return e.prepare === void 0 ? i : O.flatMap(e.prepare(r), () => i);
1629
+ })).pipe(O.catchAllDefect((t) => e.isRetryable(t) ? O.fail(t) : O.die(t)));
1630
+ }), r = Dt.exponential(to).pipe(Dt.compose(Dt.recurs(no)), Dt.whileInput(e.isRetryable)), i = n.pipe(O.retry(r), O.withSpan(e.span.name, { attributes: { ...e.span.attributes } }));
1631
+ return Ya(e.dialect, "transaction", async () => eo(await e.runPromiseExit(e.wrapProgram === void 0 ? i : e.wrapProgram(i))));
1632
+ }, io = async (e) => {
1633
+ let t = la(), n = t === void 0 ? (e) => e() : (e) => ca(t, e), r = await ro({
1630
1634
  ...e,
1631
1635
  body: (r) => {
1632
1636
  let i = e.makeView(r, t);
@@ -1637,14 +1641,14 @@ var Mt = (e) => typeof e == "string" && e !== "" ? e : null, Nt = async (e, t, n
1637
1641
  }
1638
1642
  });
1639
1643
  return r.view.commitEvents(), r.result;
1640
- }, io = class extends M.TaggedError()("VersionConflict", {
1641
- table: M.String,
1642
- id: M.String,
1643
- expected: M.Number,
1644
- actual: M.NullOr(M.Number)
1645
- }) {}, ao = (e) => {
1644
+ }, ao = class extends j.TaggedError()("VersionConflict", {
1645
+ table: j.String,
1646
+ id: j.String,
1647
+ expected: j.Number,
1648
+ actual: j.NullOr(j.Number)
1649
+ }) {}, oo = (e) => {
1646
1650
  for (let [t, n] of Object.entries(e)) if (n?.definition?.versionColumn === !0) return t;
1647
- }, oo = (e) => {
1651
+ }, so = (e) => {
1648
1652
  let { versionColumn: t, patch: n } = e;
1649
1653
  if (t === void 0) return {
1650
1654
  nextVersion: void 0,
@@ -1657,28 +1661,28 @@ var Mt = (e) => typeof e == "string" && e !== "" ? e : null, Nt = async (e, t, n
1657
1661
  expected: i,
1658
1662
  patch: a
1659
1663
  };
1660
- }, so = (e) => {
1661
- if (e.expected !== void 0 && !(e.current !== null && e.current === e.expected)) return new io({
1664
+ }, co = (e) => {
1665
+ if (e.expected !== void 0 && !(e.current !== null && e.current === e.expected)) return new ao({
1662
1666
  table: e.table,
1663
1667
  id: e.id,
1664
1668
  expected: e.expected,
1665
1669
  actual: e.current
1666
1670
  });
1667
- }, co = 1, lo = "voltro/expires", uo = () => Qe({
1668
- id: lo,
1671
+ }, lo = 1, uo = "voltro/expires", fo = () => $e({
1672
+ id: uo,
1669
1673
  fields: { expiresAt: b().nullable() },
1670
1674
  behaviors: { defaultWhere: () => "expiresAt IS NULL OR expiresAt > now()" }
1671
- }), fo = "voltro/localFirst", po = () => Qe({
1672
- id: fo,
1675
+ }), po = "voltro/localFirst", mo = () => $e({
1676
+ id: po,
1673
1677
  fields: {}
1674
- }), mo = (e) => e.appliedMixins.some((e) => e.id === fo), ho = (e) => {
1678
+ }), ho = (e) => e.appliedMixins.some((e) => e.id === po), go = (e) => {
1675
1679
  let t = [];
1676
- for (let n of Object.values(e)) mo(n) && t.push(n.tableName);
1680
+ for (let n of Object.values(e)) ho(n) && t.push(n.tableName);
1677
1681
  return t;
1678
- }, go = class extends Ct.TaggedError("TableStreamError") {}, _o = 1e3, vo = (e, t, n, r) => {
1679
- let i = j.match(r, {
1682
+ }, _o = class extends wt.TaggedError("TableStreamError") {}, vo = 1e3, yo = (e, t, n, r) => {
1683
+ let i = A.match(r, {
1680
1684
  onNone: () => e.where,
1681
- onSome: (n) => e.where ? Vi(e.where, Ei(t, n)) : Ei(t, n)
1685
+ onSome: (n) => e.where ? Hi(e.where, Di(t, n)) : Di(t, n)
1682
1686
  });
1683
1687
  return {
1684
1688
  table: e.table,
@@ -1693,19 +1697,19 @@ var Mt = (e) => typeof e == "string" && e !== "" ? e : null, Nt = async (e, t, n
1693
1697
  ...e.includeDeleted === void 0 ? {} : { includeDeleted: e.includeDeleted },
1694
1698
  ...e.crossTenant === void 0 ? {} : { crossTenant: e.crossTenant }
1695
1699
  };
1696
- }, yo = (e, t) => {
1697
- let n = t.pk ?? "id", r = t.chunkSize ?? _o;
1698
- return Dt.paginateChunkEffect(j.none(), (i) => {
1699
- let a = k.tryPromise({
1700
- try: () => e.query(vo(t, n, r, i)),
1701
- catch: (e) => new go({
1700
+ }, bo = (e, t) => {
1701
+ let n = t.pk ?? "id", r = t.chunkSize ?? vo;
1702
+ return Ot.paginateChunkEffect(A.none(), (i) => {
1703
+ let a = O.tryPromise({
1704
+ try: () => e.query(yo(t, n, r, i)),
1705
+ catch: (e) => new _o({
1702
1706
  table: t.table,
1703
1707
  cause: e
1704
1708
  })
1705
1709
  });
1706
- return (t.retry ? a.pipe(k.retry(t.retry)) : a).pipe(k.map((e) => [St.fromIterable(e), e.length === r && e.length > 0 ? j.some(j.some(e[e.length - 1][n])) : j.none()]));
1710
+ return (t.retry ? a.pipe(O.retry(t.retry)) : a).pipe(O.map((e) => [Ct.fromIterable(e), e.length === r && e.length > 0 ? A.some(A.some(e[e.length - 1][n])) : A.none()]));
1707
1711
  });
1708
- }, bo = (e) => {
1712
+ }, xo = (e) => {
1709
1713
  let t = e.alpha ?? .5;
1710
1714
  if (t < 0 || t > 1) throw Error(`hybridSearch: alpha must be in [0, 1], got ${t}`);
1711
1715
  return (n) => {
@@ -1732,17 +1736,17 @@ var Mt = (e) => typeof e == "string" && e !== "" ? e : null, Nt = async (e, t, n
1732
1736
  }
1733
1737
  };
1734
1738
  };
1735
- }, xo = async (e, t) => {
1739
+ }, So = async (e, t) => {
1736
1740
  let n = e.as ?? "embedding", r = t.row[e.from];
1737
1741
  if (typeof r != "string" || r.length === 0) return {};
1738
1742
  let i = await t.embed(r);
1739
1743
  return { [n]: i };
1740
- }, So = (e) => {
1744
+ }, Co = (e) => {
1741
1745
  if (!Number.isInteger(e.dimensions) || e.dimensions <= 0) throw Error(`vectorEmbedding: dimensions must be a positive integer, got ${String(e.dimensions)}.`);
1742
- let t = e.as ?? "embedding", n = (t) => xo(e, t);
1743
- return Qe({
1746
+ let t = e.as ?? "embedding", n = (t) => So(e, t);
1747
+ return $e({
1744
1748
  id: "voltro/vectorEmbedding",
1745
- fields: { [t]: we(e.dimensions) },
1749
+ fields: { [t]: Te(e.dimensions) },
1746
1750
  ...e.index === !1 ? {} : { indexes: [{
1747
1751
  fields: [t],
1748
1752
  kind: "hnsw",
@@ -1757,19 +1761,19 @@ var Mt = (e) => typeof e == "string" && e !== "" ? e : null, Nt = async (e, t, n
1757
1761
  beforeUpdate: n
1758
1762
  }
1759
1763
  });
1760
- }, Co = 63, wo = "br_pr", J = class extends Error {
1764
+ }, wo = 63, To = "br_pr", J = class extends Error {
1761
1765
  _tag = "BranchNameInvalid";
1762
1766
  constructor(e) {
1763
1767
  super(e), this.name = "BranchNameInvalid";
1764
1768
  }
1765
- }, To = (e, t) => {
1769
+ }, Eo = (e, t) => {
1766
1770
  if (!Number.isInteger(t) || t < 0) throw new J(`prNumber must be a non-negative integer, got ${String(t)}`);
1767
- let n = Qn(e);
1771
+ let n = $n(e);
1768
1772
  if (n.replace(/_/g, "") === "") throw new J(`app slug '${e}' has no usable identifier characters`);
1769
- let r = `${wo}${t}_${n}`;
1770
- if (r.length > Co) throw new J(`branch namespace '${r}' exceeds the ${Co}-byte identifier limit — use a shorter app slug`);
1773
+ let r = `${To}${t}_${n}`;
1774
+ if (r.length > wo) throw new J(`branch namespace '${r}' exceeds the ${wo}-byte identifier limit — use a shorter app slug`);
1771
1775
  return r;
1772
- }, Eo = (e) => e.startsWith(wo), Do = {
1776
+ }, Do = (e) => e.startsWith(To), Oo = {
1773
1777
  requested: {
1774
1778
  provision: "provisioning",
1775
1779
  destroy: "destroying"
@@ -1788,18 +1792,18 @@ var Mt = (e) => typeof e == "string" && e !== "" ? e : null, Nt = async (e, t, n
1788
1792
  fail: "failed"
1789
1793
  },
1790
1794
  destroyed: {}
1791
- }, Oo = class extends Error {
1795
+ }, ko = class extends Error {
1792
1796
  from;
1793
1797
  event;
1794
1798
  _tag = "BranchTransitionInvalid";
1795
1799
  constructor(e, t) {
1796
1800
  super(`invalid branch transition: ${e} --${t}-->`), this.from = e, this.event = t, this.name = "BranchTransitionInvalid";
1797
1801
  }
1798
- }, ko = (e, t) => {
1799
- let n = Do[e][t];
1800
- if (n === void 0) throw new Oo(e, t);
1802
+ }, Ao = (e, t) => {
1803
+ let n = Oo[e][t];
1804
+ if (n === void 0) throw new ko(e, t);
1801
1805
  return n;
1802
- }, Ao = (e, t, n, r, i = [], a = []) => {
1806
+ }, jo = (e, t, n, r, i = [], a = []) => {
1803
1807
  if (n === "copy" && (r === void 0 || r === "")) throw new J("seed 'copy' requires a parentNamespace to snapshot from");
1804
1808
  let o = [{
1805
1809
  kind: "create-namespace",
@@ -1829,13 +1833,13 @@ var Mt = (e) => typeof e == "string" && e !== "" ? e : null, Nt = async (e, t, n
1829
1833
  kind: "seed",
1830
1834
  detail: `run boot seeds into ${e}`
1831
1835
  }), o;
1832
- }, jo = (e) => {
1833
- if (!Eo(e)) throw new J(`refusing to plan teardown of '${e}' — not a branch namespace`);
1836
+ }, Mo = (e) => {
1837
+ if (!Do(e)) throw new J(`refusing to plan teardown of '${e}' — not a branch namespace`);
1834
1838
  return [{
1835
1839
  kind: "drop-namespace",
1836
1840
  detail: e
1837
1841
  }];
1838
- }, Mo = (e) => {
1842
+ }, No = (e) => {
1839
1843
  if (e === void 0 || e === "") return !1;
1840
1844
  try {
1841
1845
  let t = new URL(e).hostname.toLowerCase();
@@ -1843,27 +1847,27 @@ var Mt = (e) => typeof e == "string" && e !== "" ? e : null, Nt = async (e, t, n
1843
1847
  } catch {
1844
1848
  return /\bneon\.(tech|build)\b/i.test(e);
1845
1849
  }
1846
- }, No = (e) => e.prefer === void 0 ? e.seed === "copy" && Mo(e.dbUrl) ? "neon-cow" : "namespace" : e.prefer, Po = (e, t = {}) => [{
1850
+ }, Po = (e) => e.prefer === void 0 ? e.seed === "copy" && No(e.dbUrl) ? "neon-cow" : "namespace" : e.prefer, Fo = (e, t = {}) => [{
1847
1851
  kind: "neon-branch-create",
1848
1852
  detail: `${t.parentBranch ?? "main"} → ${e} (copy-on-write)`
1849
- }], Fo = (e) => {
1850
- if (!Eo(e)) throw new J(`refusing to plan teardown of '${e}' — not a branch namespace`);
1853
+ }], Io = (e) => {
1854
+ if (!Do(e)) throw new J(`refusing to plan teardown of '${e}' — not a branch namespace`);
1851
1855
  return [{
1852
1856
  kind: "neon-branch-delete",
1853
1857
  detail: e
1854
1858
  }];
1855
- }, Io = (e) => e.mechanism === "neon-cow" ? Po(e.branchId, e.neonParentBranch === void 0 ? {} : { parentBranch: e.neonParentBranch }) : Ao(e.branchId, e.tableNames, e.seed, e.parentNamespace, e.foreignKeys, e.indexNames), Lo = (e, t) => e === "neon-cow" ? Fo(t) : jo(t), Ro = (e, t, n) => {
1859
+ }, Lo = (e) => e.mechanism === "neon-cow" ? Fo(e.branchId, e.neonParentBranch === void 0 ? {} : { parentBranch: e.neonParentBranch }) : jo(e.branchId, e.tableNames, e.seed, e.parentNamespace, e.foreignKeys, e.indexNames), Ro = (e, t) => e === "neon-cow" ? Io(t) : Mo(t), zo = (e, t, n) => {
1856
1860
  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);
1857
1861
  return {
1858
1862
  evict: i,
1859
1863
  rejectNew: r.filter((e) => !a.has(e.namespace)).length >= t.maxBranches
1860
1864
  };
1861
- }, zo = async (e, t) => {
1862
- let n = To(e.appSlug, e.prNumber), r = No({
1865
+ }, Bo = async (e, t) => {
1866
+ let n = Eo(e.appSlug, e.prNumber), r = Po({
1863
1867
  seed: e.seed,
1864
1868
  ...e.dbUrl === void 0 ? {} : { dbUrl: e.dbUrl },
1865
1869
  ...e.prefer === void 0 ? {} : { prefer: e.prefer }
1866
- }), i = Io({
1870
+ }), i = Lo({
1867
1871
  mechanism: r,
1868
1872
  branchId: n,
1869
1873
  tableNames: e.tableNames,
@@ -1892,15 +1896,15 @@ var Mt = (e) => typeof e == "string" && e !== "" ? e : null, Nt = async (e, t, n
1892
1896
  mechanism: r,
1893
1897
  steps: i
1894
1898
  };
1895
- }, Bo = async (e, t, n) => {
1896
- let r = Lo(t, e);
1899
+ }, Vo = async (e, t, n) => {
1900
+ let r = Ro(t, e);
1897
1901
  return t === "neon-cow" ? await n.neonBranchDelete(e) : await n.dropNamespace(e), r;
1898
- }, Vo = (e, t, n) => Ro(e, t, n), Y = (e) => `"${e.replace(/"/g, "\"\"")}"`, Ho = {
1902
+ }, Ho = (e, t, n) => zo(e, t, n), Y = (e) => `"${e.replace(/"/g, "\"\"")}"`, Uo = {
1899
1903
  cascade: "CASCADE",
1900
1904
  restrict: "RESTRICT",
1901
1905
  setNull: "SET NULL",
1902
1906
  noAction: "NO ACTION"
1903
- }, X = (e) => `'${e.replace(/'/g, "''")}'`, Uo = (e, t) => {
1907
+ }, X = (e) => `'${e.replace(/'/g, "''")}'`, Wo = (e, t) => {
1904
1908
  let n = t.columns.map(X).join(", ");
1905
1909
  return `DO $voltro_branch$
1906
1910
  DECLARE derived name;
@@ -1927,10 +1931,10 @@ BEGIN
1927
1931
  END IF;
1928
1932
  END
1929
1933
  $voltro_branch$`;
1930
- }, Wo = (e, t) => {
1931
- let n = t.onDelete === void 0 ? "" : ` ON DELETE ${Ho[t.onDelete]}`, r = t.onUpdate === void 0 ? "" : ` ON UPDATE ${Ho[t.onUpdate]}`;
1934
+ }, Go = (e, t) => {
1935
+ let n = t.onDelete === void 0 ? "" : ` ON DELETE ${Uo[t.onDelete]}`, r = t.onUpdate === void 0 ? "" : ` ON UPDATE ${Uo[t.onUpdate]}`;
1932
1936
  return `ALTER TABLE ${Y(e)}.${Y(t.table)} ADD FOREIGN KEY (${Y(t.column)}) REFERENCES ${Y(e)}.${Y(t.targetTable)} (${Y(t.targetColumn)})${n}${r}`;
1933
- }, Go = (e) => {
1937
+ }, Ko = (e) => {
1934
1938
  let t = () => {
1935
1939
  throw Error("namespace branch executor: Neon ops require a neon-cow executor (use a Neon connection for copy-on-write branches)");
1936
1940
  };
@@ -1938,24 +1942,24 @@ $voltro_branch$`;
1938
1942
  createNamespace: (t) => e.run(`CREATE SCHEMA IF NOT EXISTS ${Y(t)}`),
1939
1943
  createTable: (t, n) => e.run(`CREATE TABLE IF NOT EXISTS ${Y(t)}.${Y(n)} (LIKE ${Y(n)} INCLUDING ALL)`),
1940
1944
  copyTable: (t, n, r) => e.run(`INSERT INTO ${Y(n)}.${Y(r)} SELECT * FROM ${Y(t)}.${Y(r)}`),
1941
- addForeignKey: (t, n) => e.run(Wo(t, n)),
1942
- restoreIndexName: (t, n) => e.run(Uo(t, n)),
1945
+ addForeignKey: (t, n) => e.run(Go(t, n)),
1946
+ restoreIndexName: (t, n) => e.run(Wo(t, n)),
1943
1947
  dropNamespace: (t) => e.run(`DROP SCHEMA IF EXISTS ${Y(t)} CASCADE`),
1944
1948
  neonBranchCreate: t,
1945
1949
  neonBranchDelete: t
1946
1950
  };
1947
- }, Ko = class extends Error {
1951
+ }, qo = class extends Error {
1948
1952
  _tag = "TenantResidencyUnresolved";
1949
1953
  constructor(e) {
1950
1954
  super(e), this.name = "TenantResidencyUnresolved";
1951
1955
  }
1952
- }, qo = class extends Error {
1956
+ }, Jo = class extends Error {
1953
1957
  region;
1954
1958
  _tag = "TenantRegionUnavailable";
1955
1959
  constructor(e, t) {
1956
1960
  super(t), this.region = e, this.name = "TenantRegionUnavailable";
1957
1961
  }
1958
- }, Jo, Yo = (e) => {
1962
+ }, Yo, Xo = (e) => {
1959
1963
  if (e.homes === void 0) throw Error("setResidencyConfig: `homes` is required");
1960
1964
  if (e.servableRegions === void 0 || e.servableRegions.length === 0) throw Error("setResidencyConfig: `servableRegions` must be non-empty (which regions this deployment serves)");
1961
1965
  let t = /* @__PURE__ */ new Map();
@@ -1964,47 +1968,47 @@ $voltro_branch$`;
1964
1968
  if (e !== void 0 && e !== n.region) throw Error(`residency: tenant '${n.tenantId}' is mapped to two regions ('${e}' and '${n.region}')`);
1965
1969
  t.set(n.tenantId, n.region);
1966
1970
  }
1967
- return Jo = e, e;
1968
- }, Xo = () => Jo, Zo = () => {
1969
- Jo = void 0;
1970
- }, Qo = (e, t) => {
1971
- if (e == null || e === "") throw new Ko("residency is on but the request has no resolvable tenant — refusing to bind a store");
1971
+ return Yo = e, e;
1972
+ }, Zo = () => Yo, Qo = () => {
1973
+ Yo = void 0;
1974
+ }, $o = (e, t) => {
1975
+ if (e == null || e === "") throw new qo("residency is on but the request has no resolvable tenant — refusing to bind a store");
1972
1976
  let n = t.homes.find((t) => t.tenantId === e);
1973
- if (n === void 0) throw new Ko(`no residency home is mapped for tenant '${e}' — refusing to fall back to a default store (would be a residency violation)`);
1977
+ if (n === void 0) throw new qo(`no residency home is mapped for tenant '${e}' — refusing to fall back to a default store (would be a residency violation)`);
1974
1978
  return n;
1975
- }, $o = (e, t) => t.servableRegions.includes(e), es = (e, t) => {
1976
- let n = Qo(e.tenantId, t), r = $n(n.tenantId);
1979
+ }, es = (e, t) => t.servableRegions.includes(e), ts = (e, t) => {
1980
+ let n = $o(e.tenantId, t), r = er(n.tenantId);
1977
1981
  return {
1978
1982
  region: n.region,
1979
1983
  namespace: r,
1980
1984
  ...n.connectionKey === void 0 ? {} : { connectionKey: n.connectionKey }
1981
1985
  };
1982
- }, ts = (e, t, n) => {
1983
- let r = es(e, t);
1984
- if (!$o(r.region, t)) throw new qo(r.region, `tenant homed in region '${r.region}', which this deployment does not serve — route to the home region`);
1986
+ }, ns = (e, t, n) => {
1987
+ let r = ts(e, t);
1988
+ if (!es(r.region, t)) throw new Jo(r.region, `tenant homed in region '${r.region}', which this deployment does not serve — route to the home region`);
1985
1989
  let i = n.get(r.region);
1986
- if (i === void 0) throw new qo(r.region, `no store handle for home region '${r.region}' (declared servable but not wired) — failing closed`);
1990
+ if (i === void 0) throw new Jo(r.region, `no store handle for home region '${r.region}' (declared servable but not wired) — failing closed`);
1987
1991
  return {
1988
1992
  store: i,
1989
1993
  placement: r
1990
1994
  };
1991
- }, ns = async (e, t, n, r) => {
1992
- let { store: i, placement: a } = ts(e, t, n);
1995
+ }, rs = async (e, t, n, r) => {
1996
+ let { store: i, placement: a } = ns(e, t, n);
1993
1997
  return await r(i, a), a;
1994
- }, rs = (e) => {
1998
+ }, Z = (e) => {
1995
1999
  if (typeof e == "string") return e;
1996
2000
  if ("jsonPath" in e) {
1997
2001
  let { column: t, path: n, numeric: r } = e.jsonPath;
1998
2002
  return `(json:${t}->${n.join(".")}${r ? "::num" : ""})`;
1999
2003
  }
2000
2004
  return `(${e.expr})`;
2001
- }, Z = (e) => e.map(rs), is = (e, t) => {
2005
+ }, Q = (e) => e.map(Z), is = (e, t) => {
2002
2006
  if (e.length !== t.length) return !1;
2003
- for (let n = 0; n < e.length; n++) if (rs(e[n]) !== rs(t[n])) return !1;
2007
+ for (let n = 0; n < e.length; n++) if (Z(e[n]) !== Z(t[n])) return !1;
2004
2008
  return !0;
2005
2009
  }, as = (e, t) => {
2006
2010
  if (e.length >= t.length) return !1;
2007
- for (let n = 0; n < e.length; n++) if (rs(e[n]) !== rs(t[n])) return !1;
2011
+ for (let n = 0; n < e.length; n++) if (Z(e[n]) !== Z(t[n])) return !1;
2008
2012
  return !0;
2009
2013
  }, os = (e) => {
2010
2014
  let t = [], n = e.appliedIndexes, r = e.tableName;
@@ -2019,7 +2023,7 @@ $voltro_branch$`;
2019
2023
  table: r,
2020
2024
  redundant: n,
2021
2025
  coveredBy: a,
2022
- message: `'${r}' has two indexes on the same fields [${Z(i.fields).join(", ")}]: '${i.name}' and '${e.name}'. The B-tree engine builds both, costing write throughput + disk space for no read benefit. Drop '${n.name}' (or '${a.name}' if you prefer the other name). Applies to every supported dialect (Postgres / MySQL / MariaDB / MSSQL / SQLite).`
2026
+ message: `'${r}' has two indexes on the same fields [${Q(i.fields).join(", ")}]: '${i.name}' and '${e.name}'. The B-tree engine builds both, costing write throughput + disk space for no read benefit. Drop '${n.name}' (or '${a.name}' if you prefer the other name). Applies to every supported dialect (Postgres / MySQL / MariaDB / MSSQL / SQLite).`
2023
2027
  });
2024
2028
  continue;
2025
2029
  }
@@ -2028,13 +2032,13 @@ $voltro_branch$`;
2028
2032
  table: r,
2029
2033
  redundant: i,
2030
2034
  coveredBy: e,
2031
- message: `'${r}' index '${i.name}' on [${Z(i.fields).join(", ")}] is a leading prefix of '${e.name}' on [${Z(e.fields).join(", ")}]. Every B-tree dialect we support (Postgres / MySQL / MariaDB / MSSQL / SQLite) can serve a [${Z(i.fields).join(", ")}] query from '${e.name}' too via the leading-prefix rule, so '${i.name}' adds write cost without read benefit. Drop '${i.name}' — unless you specifically need a smaller index for cache locality on a write-heavy table (rare; profile first).`
2035
+ 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).`
2032
2036
  }) : as(e.fields, i.fields) && t.push({
2033
2037
  kind: "redundant-prefix",
2034
2038
  table: r,
2035
2039
  redundant: e,
2036
2040
  coveredBy: i,
2037
- message: `'${r}' index '${e.name}' on [${Z(e.fields).join(", ")}] is a leading prefix of '${i.name}' on [${Z(i.fields).join(", ")}]. Every B-tree dialect we support (Postgres / MySQL / MariaDB / MSSQL / SQLite) can serve a [${Z(e.fields).join(", ")}] query from '${i.name}' too via the leading-prefix rule, so '${e.name}' adds write cost without read benefit. Drop '${e.name}' — unless you specifically need a smaller index for cache locality on a write-heavy table (rare; profile first).`
2041
+ message: `'${r}' index '${e.name}' on [${Q(e.fields).join(", ")}] is a leading prefix of '${i.name}' on [${Q(i.fields).join(", ")}]. Every B-tree dialect we support (Postgres / MySQL / MariaDB / MSSQL / SQLite) can serve a [${Q(e.fields).join(", ")}] query from '${i.name}' too via the leading-prefix rule, so '${e.name}' adds write cost without read benefit. Drop '${e.name}' — unless you specifically need a smaller index for cache locality on a write-heavy table (rare; profile first).`
2038
2042
  });
2039
2043
  }
2040
2044
  }
@@ -2043,12 +2047,12 @@ $voltro_branch$`;
2043
2047
  let t = [];
2044
2048
  for (let n of e) t.push(...os(n));
2045
2049
  return t;
2046
- }, cs = "\x1B[", ls = `${cs}38;2;245;158;11m`, us = `${cs}38;2;16;185;129m`, ds = (e, t) => `${e}${t}${N.reset}`, Q = (e, t, n) => e ? typeof t == "function" ? t(n) : ds(t, n) : n, fs = (e, t = {}) => {
2047
- let n = t.color ?? !0, r = t.indent ?? " ", i = (e) => Q(n, N.dim, e.padEnd(11)), a = (e) => Q(n, (e) => N.bold(N.brand(e)), e), o = (e) => Q(n, N.brightRed24, e), s = (e) => Q(n, us, e), c = (e) => Q(n, ls, e), l = (e) => Q(n, N.dim, e), u = `${c("index audit")} ${l("·")} ${Q(n, N.bold, e.kind)}`, d = e.redundant.fields.length, f = Z(e.coveredBy.fields.slice(d)), p = (e, t) => {
2050
+ }, cs = "\x1B[", ls = `${cs}38;2;245;158;11m`, us = `${cs}38;2;16;185;129m`, ds = (e, t) => `${e}${t}${M.reset}`, $ = (e, t, n) => e ? typeof t == "function" ? t(n) : ds(t, n) : n, fs = (e, t = {}) => {
2051
+ let n = t.color ?? !0, r = t.indent ?? " ", i = (e) => $(n, M.dim, e.padEnd(11)), a = (e) => $(n, (e) => M.bold(M.brand(e)), e), o = (e) => $(n, M.brightRed24, e), s = (e) => $(n, us, e), c = (e) => $(n, ls, e), l = (e) => $(n, M.dim, e), u = `${c("index audit")} ${l("·")} ${$(n, M.bold, e.kind)}`, d = e.redundant.fields.length, f = Q(e.coveredBy.fields.slice(d)), p = (e, t) => {
2048
2052
  let n = e.slice(0, t), r = e.slice(t), i = [];
2049
2053
  return n.length > 0 && i.push(s(`[${n.join(", ")}]`)), r.length > 0 && i.push(c(`+ [${r.join(", ")}]`)), i.join(" ");
2050
2054
  }, m = [];
2051
- return m.push(u), m.push(""), m.push(`${i("table")}${a(e.table)}`), m.push(""), m.push(`${i("redundant")}${o(e.redundant.name)}`), m.push(`${i("")}${p(Z(e.redundant.fields), d)}`), m.push(""), m.push(`${i("covered by")}${s(e.coveredBy.name)}`), m.push(`${i("")}${p(Z(e.coveredBy.fields), d)}`), f.length > 0 && m.push(`${i("")}${l(`└ extra columns: ${f.join(", ")}`)}`), m.push(""), e.kind === "redundant-prefix" ? (m.push(`${i("why")}B-tree indexes serve queries that filter on a LEADING PREFIX of`), m.push(`${i("")}their column list. The wider index already covers every`), m.push(`${i("")}query the narrower one can serve.`), m.push(`${i("")}${l("Same rule on Postgres / MySQL / MariaDB / MSSQL / SQLite.")}`)) : (m.push(`${i("why")}Two indexes on the same columns under different names.`), m.push(`${i("")}The B-tree engine builds both — same coverage, double cost.`), m.push(`${i("")}${l("Same rule on Postgres / MySQL / MariaDB / MSSQL / SQLite.")}`)), m.push(""), m.push(`${i("cost")}Every ${a("INSERT")} / ${a("UPDATE")} / ${a("DELETE")} on this table writes`), m.push(`${i("")}to ${Q(n, N.bold, "both")} B-trees. Pure write overhead, zero read benefit.`), m.push(""), m.push(`${i("fix")}Drop ${o(e.redundant.name)}`), m.push(`${i("")}${l("Keep only if profiling shows the smaller index gives a")}`), m.push(`${i("")}${l("measurable cache-locality boost on a write-heavy hot path.")}`), m.push(`${i("")}${l("Silence with VOLTRO_INDEX_AUDIT=off if intentional.")}`), m.map((e) => `${r}${e}`).join("\n");
2055
+ 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, M.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");
2052
2056
  }, ps = (e, { apply: t, undo: n }) => ({
2053
2057
  name: e,
2054
2058
  apply: t,
@@ -2063,99 +2067,99 @@ $voltro_branch$`;
2063
2067
  name: e.name,
2064
2068
  steps: t
2065
2069
  };
2066
- }, hs = (e) => typeof e == "object" && !!e && "__migration" in e && e.__migration === !0, gs = w("_voltro_migrations", {
2070
+ }, hs = (e) => typeof e == "object" && !!e && "__migration" in e && e.__migration === !0, gs = C("_voltro_migrations", {
2067
2071
  id: v({ prefix: "mig" }),
2068
- name: D(),
2069
- hash: D(),
2070
- status: D(),
2072
+ name: E(),
2073
+ hash: E(),
2074
+ status: E(),
2071
2075
  appliedAt: b().nullable(),
2072
- durationMs: C().nullable(),
2073
- errorMessage: D().nullable(),
2074
- errorStack: D().nullable(),
2075
- workflowRunId: D().nullable(),
2076
+ durationMs: S().nullable(),
2077
+ errorMessage: E().nullable(),
2078
+ errorStack: E().nullable(),
2079
+ workflowRunId: E().nullable(),
2076
2080
  createdAt: b().default("now"),
2077
2081
  updatedAt: b().default("now").onUpdate("now")
2078
- }).index(["status"]), _s = w("_voltro_seeds", {
2082
+ }).index(["status"]), _s = C("_voltro_seeds", {
2079
2083
  id: v({ prefix: "seed" }),
2080
- name: D(),
2081
- lifecycle: D(),
2082
- fingerprint: D(),
2083
- cronSchedule: D().nullable(),
2084
- watchedTables: O().nullable(),
2084
+ name: E(),
2085
+ lifecycle: E(),
2086
+ fingerprint: E(),
2087
+ cronSchedule: E().nullable(),
2088
+ watchedTables: D().nullable(),
2085
2089
  nextRunAt: b().nullable(),
2086
- lastRunStatus: D().nullable(),
2090
+ lastRunStatus: E().nullable(),
2087
2091
  lastRunAt: b().nullable(),
2088
- lastRunDurationMs: C().nullable(),
2089
- lastRunRowsTouched: C().nullable(),
2090
- lastError: D().nullable(),
2091
- workflowRunId: D().nullable(),
2092
+ lastRunDurationMs: S().nullable(),
2093
+ lastRunRowsTouched: S().nullable(),
2094
+ lastError: E().nullable(),
2095
+ workflowRunId: E().nullable(),
2092
2096
  createdAt: b().default("now"),
2093
2097
  updatedAt: b().default("now").onUpdate("now")
2094
- }).index(["lifecycle"]).index(["nextRunAt"]), vs = w("_voltro_migration_plans", {
2098
+ }).index(["lifecycle"]).index(["nextRunAt"]), vs = C("_voltro_migration_plans", {
2095
2099
  id: v({ prefix: "plan" }),
2096
- fingerprint: D(),
2097
- liveFingerprint: D().nullable(),
2098
- operations: O(),
2099
- rollbackPlan: O().nullable(),
2100
- appliedBy: D(),
2101
- environment: D(),
2102
- source: D(),
2103
- onlineStrategy: D().nullable(),
2104
- durationMs: C(),
2105
- notes: D().nullable(),
2100
+ fingerprint: E(),
2101
+ liveFingerprint: E().nullable(),
2102
+ operations: D(),
2103
+ rollbackPlan: D().nullable(),
2104
+ appliedBy: E(),
2105
+ environment: E(),
2106
+ source: E(),
2107
+ onlineStrategy: E().nullable(),
2108
+ durationMs: S(),
2109
+ notes: E().nullable(),
2106
2110
  squashedAt: b().nullable(),
2107
2111
  appliedAt: b().default("now"),
2108
2112
  createdAt: b().default("now"),
2109
2113
  updatedAt: b().default("now").onUpdate("now")
2110
- }).index(["fingerprint"]).index(["environment"]), ys = w("_voltro_idempotency", {
2114
+ }).index(["fingerprint"]).index(["environment"]), ys = C("_voltro_idempotency", {
2111
2115
  id: v({ prefix: "idem" }),
2112
- scope: D(),
2113
- key: D(),
2114
- status: D(),
2115
- response: O().nullable(),
2116
+ scope: E(),
2117
+ key: E(),
2118
+ status: E(),
2119
+ response: D().nullable(),
2116
2120
  createdAt: b().default("now")
2117
- }).unique(["scope", "key"]).index(["createdAt"]), bs = w("_voltro_kv", {
2121
+ }).unique(["scope", "key"]).index(["createdAt"]), bs = C("_voltro_kv", {
2118
2122
  id: v({ prefix: "kv" }),
2119
- key: D().unique(),
2120
- value: D().nullable(),
2123
+ key: E().unique(),
2124
+ value: E().nullable(),
2121
2125
  expiresAt: b().nullable(),
2122
2126
  createdAt: b().default("now"),
2123
2127
  updatedAt: b().default("now").onUpdate("now")
2124
- }).index(["expiresAt"]), xs = w("_voltro_api_keys", {
2128
+ }).index(["expiresAt"]), xs = C("_voltro_api_keys", {
2125
2129
  id: v({ prefix: "apikey" }),
2126
- tenantId: D().nullable(),
2127
- name: D(),
2128
- hashedKey: D().maxLength(64).unique(),
2129
- keyPrefix: D(),
2130
- scopes: O().nullable(),
2130
+ tenantId: E().nullable(),
2131
+ name: E(),
2132
+ hashedKey: E().maxLength(64).unique(),
2133
+ keyPrefix: E(),
2134
+ scopes: D().nullable(),
2131
2135
  lastUsedAt: b().nullable(),
2132
- requestCount: C().default(0),
2136
+ requestCount: S().default(0),
2133
2137
  expiresAt: b().nullable(),
2134
2138
  revokedAt: b().nullable(),
2135
- createdBy: D().nullable(),
2136
- onBehalfOf: D().nullable(),
2137
- metadata: O().nullable(),
2139
+ createdBy: E().nullable(),
2140
+ onBehalfOf: E().nullable(),
2141
+ metadata: D().nullable(),
2138
2142
  createdAt: b().default("now")
2139
2143
  }).index("byApiKeyTenant", ["tenantId"]), Ss = [
2140
2144
  gs,
2141
2145
  _s,
2142
2146
  vs
2143
- ], $ = "id", Cs = (e, t) => {
2147
+ ], Cs = "id", ws = (e, t) => {
2144
2148
  let n = p(e);
2145
2149
  if (n === void 0) return t;
2146
- let r = n.fields[$]?.idScheme;
2147
- if (r === void 0 || t[$] != null) return t;
2150
+ let r = n.fields[Cs]?.idScheme;
2151
+ if (r === void 0 || t[Cs] != null) return t;
2148
2152
  if (r.kind === "numeric") {
2149
- if (!($ in t)) return t;
2153
+ if (!(Cs in t)) return t;
2150
2154
  let e = { ...t };
2151
- return delete e[$], e;
2155
+ return delete e[Cs], e;
2152
2156
  }
2153
- let i = et(r, e);
2157
+ let i = tt(r, e);
2154
2158
  return i === null ? t : {
2155
2159
  ...t,
2156
- [$]: i
2160
+ [Cs]: i
2157
2161
  };
2158
- }, ws = (e, t) => t.map((t) => Cs(e, t)), Ts = {
2162
+ }, Ts = (e, t) => t.map((t) => ws(e, t)), Es = {
2159
2163
  postgres: { maxBindParameters: 65535 },
2160
2164
  mysql: { maxBindParameters: 65535 },
2161
2165
  mariadb: { maxBindParameters: 65535 },
@@ -2165,49 +2169,49 @@ $voltro_branch$`;
2165
2169
  },
2166
2170
  sqlite: { maxBindParameters: 32766 },
2167
2171
  turso: { maxBindParameters: 32766 }
2168
- }, Es = (e) => Ts[e], Ds = (e) => {
2172
+ }, Ds = (e) => Es[e], Os = (e) => {
2169
2173
  let t = /* @__PURE__ */ new Set();
2170
2174
  for (let n of e) for (let e of Object.keys(n)) t.add(e);
2171
2175
  return t.size;
2172
- }, Os = (e, t) => {
2176
+ }, ks = (e, t) => {
2173
2177
  if (t === void 0 || e.length === 0) return [e];
2174
- let n = Math.max(1, Ds(e)), r = Math.floor(t.maxBindParameters / n), i = t.maxRowsPerStatement ?? Infinity, a = Math.max(1, Math.min(r, i));
2178
+ let n = Math.max(1, Os(e)), r = Math.floor(t.maxBindParameters / n), i = t.maxRowsPerStatement ?? Infinity, a = Math.max(1, Math.min(r, i));
2175
2179
  if (e.length <= a) return [e];
2176
2180
  let o = [];
2177
2181
  for (let t = 0; t < e.length; t += a) o.push(e.slice(t, t + a));
2178
2182
  return o;
2179
- }, ks = (e, t) => {
2183
+ }, As = (e, t) => {
2180
2184
  let n = [], r = t;
2181
2185
  for (let [t, i] of Object.entries(e.fields)) {
2182
2186
  let e = i;
2183
2187
  e.nullable || e.hasDefault || e.idScheme !== void 0 || e.generatedAs !== void 0 || (r[t] === void 0 || r[t] === null) && n.push(t);
2184
2188
  }
2185
2189
  return n;
2186
- }, As = (e, t) => {
2190
+ }, js = (e, t) => {
2187
2191
  let n = t;
2188
2192
  return e.filter((e) => n[e] === void 0 || n[e] === null);
2189
- }, js = (e, t, n) => e.insert(t.tableName, n), Ms = (e, t, n, r) => e.upsert(t.tableName, n, {
2193
+ }, Ms = (e, t, n) => e.insert(t.tableName, n), Ns = (e, t, n, r) => e.upsert(t.tableName, n, {
2190
2194
  conflictColumns: r.conflictColumns,
2191
2195
  ...r.update === void 0 ? {} : { update: r.update }
2192
- }), Ns = (e, t, n, r) => e.updateMany(t.tableName, n, { where: r.where }), Ps = 512, Fs = (e) => {
2196
+ }), Ps = (e, t, n, r) => e.updateMany(t.tableName, n, { where: r.where }), Fs = 512, Is = (e) => {
2193
2197
  e.setMaxListeners(512);
2194
- }, Is = (e, t, n) => ({
2198
+ }, Ls = (e, t, n) => ({
2195
2199
  _tag: "PrimaryKeyConflictError",
2196
2200
  table: e,
2197
2201
  key: t,
2198
2202
  cause: n
2199
- }), Ls = (e) => typeof e == "object" && !!e && e._tag === "PrimaryKeyConflictError", Rs = {
2203
+ }), Rs = (e) => typeof e == "object" && !!e && e._tag === "PrimaryKeyConflictError", zs = {
2200
2204
  postgres: 5432,
2201
2205
  mysql: 3306,
2202
2206
  mariadb: 3306,
2203
2207
  mssql: 1433
2204
- }, zs = /* @__PURE__ */ new Set([
2208
+ }, Bs = /* @__PURE__ */ new Set([
2205
2209
  "localhost",
2206
2210
  "127.0.0.1",
2207
2211
  "::1",
2208
2212
  "[::1]",
2209
2213
  "0.0.0.0"
2210
- ]), Bs = (e) => {
2214
+ ]), Vs = (e) => {
2211
2215
  let t = e.host, n = e.port, r = e.database;
2212
2216
  if (e.url !== void 0 && e.url !== "") try {
2213
2217
  let i = new URL(e.url);
@@ -2216,29 +2220,29 @@ $voltro_branch$`;
2216
2220
  return;
2217
2221
  }
2218
2222
  if (t === void 0 || t === "" || r === void 0 || r === "") return;
2219
- let i = n ?? Rs[(e.dialect ?? "").toLowerCase()];
2223
+ let i = n ?? zs[(e.dialect ?? "").toLowerCase()];
2220
2224
  if (i === void 0 || !Number.isFinite(i)) return;
2221
2225
  let a = t.toLowerCase();
2222
2226
  return {
2223
- host: zs.has(a) ? "localhost" : a,
2227
+ host: Bs.has(a) ? "localhost" : a,
2224
2228
  port: i,
2225
2229
  database: r.toLowerCase()
2226
2230
  };
2227
- }, Vs = (e) => {
2228
- let t = Bs(e);
2229
- if (t !== void 0) return jt("sha256").update(`${t.host}\u0000${t.port}\u0000${t.database}`).digest("hex").slice(0, 32);
2230
- }, Hs = (e, t) => e === void 0 || t === void 0 ? "unknown" : e === t ? "same" : "different", Us = {
2231
+ }, Hs = (e) => {
2232
+ let t = Vs(e);
2233
+ if (t !== void 0) return Mt("sha256").update(`${t.host}\u0000${t.port}\u0000${t.database}`).digest("hex").slice(0, 32);
2234
+ }, Us = (e, t) => e === void 0 || t === void 0 ? "unknown" : e === t ? "same" : "different", Ws = {
2231
2235
  app: 3,
2232
2236
  plugin: 2,
2233
2237
  framework: 1
2234
- }, Ws = /* @__PURE__ */ new Map(), Gs = [], Ks = () => [...Gs], qs = (e) => {
2238
+ }, Gs = /* @__PURE__ */ new Map(), Ks = [], qs = () => [...Ks], Js = (e) => {
2235
2239
  if (!e.table || !e.timeColumn) throw Error("registerRetention: table + timeColumn are required");
2236
2240
  if (!Number.isFinite(e.ttlMs) || e.ttlMs <= 0) throw Error(`registerRetention(${e.table}): ttlMs must be a positive number`);
2237
- let t = e.source ?? "app", n = Ws.get(e.table);
2241
+ let t = e.source ?? "app", n = Gs.get(e.table);
2238
2242
  if (n !== void 0) {
2239
2243
  let r = n.source ?? "app", i = n.ttlMs !== e.ttlMs || n.where !== void 0 != (e.where !== void 0);
2240
- if (Us[t] < Us[r]) {
2241
- i && Gs.push({
2244
+ if (Ws[t] < Ws[r]) {
2245
+ i && Ks.push({
2242
2246
  table: e.table,
2243
2247
  kept: {
2244
2248
  source: r,
@@ -2251,7 +2255,7 @@ $voltro_branch$`;
2251
2255
  });
2252
2256
  return;
2253
2257
  }
2254
- i && r !== t && Gs.push({
2258
+ i && r !== t && Ks.push({
2255
2259
  table: e.table,
2256
2260
  kept: {
2257
2261
  source: t,
@@ -2263,35 +2267,35 @@ $voltro_branch$`;
2263
2267
  }
2264
2268
  });
2265
2269
  }
2266
- Ws.set(e.table, {
2270
+ Gs.set(e.table, {
2267
2271
  ...e,
2268
2272
  source: t
2269
2273
  });
2270
- }, Js = () => [...Ws.values()], Ys = () => {
2271
- Ws.clear(), Gs.length = 0;
2272
- }, Xs = async (e, t, n, r = 2e4) => {
2274
+ }, Ys = () => [...Gs.values()], Xs = () => {
2275
+ Gs.clear(), Ks.length = 0;
2276
+ }, Zs = async (e, t, n, r = 2e4) => {
2273
2277
  let i = new Date(t - e.ttlMs), a = 0;
2274
2278
  for (;;) {
2275
2279
  let t = await n(e.table, e.timeColumn, i, r, e.where);
2276
2280
  if (a += t, t < r) break;
2277
2281
  }
2278
2282
  return a;
2279
- }, Zs = (e, t) => {
2283
+ }, Qs = (e, t) => {
2280
2284
  let n = Number(e ?? String(t));
2281
2285
  return (Number.isFinite(n) && n > 0 ? n : t) * 36e5;
2282
- }, Qs = "_voltro_cdc_offsets", $s = w(Qs, {
2286
+ }, $s = "_voltro_cdc_offsets", ec = C($s, {
2283
2287
  id: v({ prefix: "cdcoff" }),
2284
- replicaId: D(),
2285
- streamName: D(),
2286
- binlogFile: D(),
2287
- binlogPosition: D(),
2288
+ replicaId: E(),
2289
+ streamName: E(),
2290
+ binlogFile: E(),
2291
+ binlogPosition: E(),
2288
2292
  updatedAt: b()
2289
- }).index(["replicaId"]), ec = w(Qs, {
2293
+ }).index(["replicaId"]), tc = C($s, {
2290
2294
  id: v({ prefix: "cdcoff" }),
2291
- replicaId: D(),
2292
- streamName: D(),
2293
- ctVersion: D(),
2295
+ replicaId: E(),
2296
+ streamName: E(),
2297
+ ctVersion: E(),
2294
2298
  updatedAt: b()
2295
- }).index(["replicaId"]), tc = "postgres";
2299
+ }).index(["replicaId"]), nc = "postgres";
2296
2300
  //#endregion
2297
- export { le as AUTO_FILLED_COLUMNS, Ts as BULK_INSERT_LIMITS, J as BranchNameInvalid, Oo as BranchTransitionInvalid, Qs as CDC_OFFSETS_TABLE, Ps as CHANGE_LISTENER_CEILING, o as ColumnBuilder, Ce as DEFAULT_ACQUIRE_TIMEOUT_MS, Ya as DEFAULT_EAGER_FALLBACK_WARN_INTERVAL_MS, yn as DEFAULT_SUBJECT_GRAPH_DEPTH, Rt as ENCRYPTED_PREFIX, tc as ENGINE, In as EagerCardinalityError, He as FILE_MIGRATION_PATTERN, ot as FRAMEWORK_LIVE_TABLES, zt as FieldDecryptionError, co as INITIAL_VERSION, Li as MATCHES_NO_ROWS, lt as MAX_IDENTIFIER_LENGTH, At as SqlClient, go as TableStreamError, Yn as TenantNamespaceInvalid, Jn as TenantNamespaceUnresolved, qo as TenantRegionUnavailable, Ko as TenantResidencyUnresolved, lo as VOLTRO_EXPIRES_MIXIN_ID, fo as VOLTRO_LOCAL_FIRST_MIXIN_ID, io as VersionConflict, Fe as WARN_IDENTIFIER_LENGTH, xs as _voltroApiKeysTable, $s as _voltroCdcOffsetsTable, ys as _voltroIdempotencyTable, bs as _voltroKvTable, vs as _voltroMigrationPlansTable, gs as _voltroMigrationsTable, ec as _voltroMssqlCdcOffsetsTable, _s as _voltroSeedsTable, Ci as actorsTable, Vo as admitBranch, De as allEnumRenames, gn as allRegisteredRelations, h as allRegisteredTables, Vi as and, pt as array, Pi as arrayContains, Ii as arrayHas, Fi as arrayOverlaps, Rn as attachEagerLoads, ca as attributionFields, fa as attributionKey, ss as auditAllTableIndexes, os as auditTableIndexes, ut as avg, gt as avgOver, xa as beginLocalWrite, he as bigint, ts as bindResidentStore, u as boolean, To as branchNamespaceName, Es as bulkInsertLimitsFor, c as bytes, ra as changeDelete, ta as changeInsert, ia as changeSoftDelete, na as changeUpdate, Os as chunkRowsForInsert, ha as claimPendingAttribution, dt as clearEnumRenames, wa as clearPendingAttribution, vn as clearRelationsRegistry, Zo as clearResidencyConfig, Ys as clearRetentions, ge as clearTableRegistry, Oa as clearWriteRecorders, rr as coercePredicateValue, ir as coercePredicateValues, $i as collectSubqueries, Ae as column, Gt as columnSchema, Ds as columnsPerRow, vr as compileEagerJson, I as compilePredicate, ar as compileRawFragment, _r as compileSelect, xo as computeEmbedding, Vs as connectionIdentity, Mi as contains, mt as count, fe as countDistinct, oe as crdtManagedColumns, Ke as crdtText, sa as currentWriteAttribution, a as databaseHandle, n as date, We as dbEnum, Ua as dbMetricTagCacheSizeForTests, Ka as dbOperationsInFlight, ne as decimal, _t as declareEnumRename, Nn as decodeRowsFromSchema, Wt as decryptFieldsOnRead, ms as defineMigration, Qe as defineMixin, it as defineSeed, ft as denseRank, En as deriveSubjectGraph, ke as deriveTypeIdPrefix, Lt as deserializeArraysOnRead, Le as drainIdentifierWarnings, ie as dropped, Fn as encodeRowForSchema, Ut as encryptFieldsForWrite, Ht as encryptedColumnsOf, Sa as endLocalWrite, Ro as enforceBranchLimits, be as ensureTableRegistered, wi as eq, or as escapeLike, Qi as evaluatePredicate, me as except, Ji as exists, uo as expires, Me as fireSchemaChangeSeeds, qe as fireTenantCreateSeeds, fs as formatIndexAuditIssue, Dn as formatSubjectGraph, Ss as frameworkTables, et as generateId, Ne as generateSnowflake, ce as geography, f as geometry, je as getEnumRenames, hn as getRelation, mn as getRelations, Xo as getResidencyConfig, p as getTable, Ei as gt, Di as gte, qn as hasEagerLoads, bo as hybridSearch, v as id, Ai as inSet, Ki as inSubquery, an as inferForeignKey, js as insertRow, C as integer, l as intersect, de as interval, Eo as isBranchNamespace, $t as isEmptyRelationsSpec, Vt as isEncrypted, Bt as isFieldDecryptionError, Oe as isFileMigration, Ze as isFrameworkOwnedLiveTable, mo as isLocalFirst, hs as isMigrationDefinition, Mo as isNeonConnection, zi as isNotNull, Ri as isNull, Ls as isPrimaryKeyConflictError, $o as isRegionServable, en as isRelationsSpec, ct as isSeedDefinition, Se as isSqliteFamily, x as isTableReactive, Ye as isView, O as json, Wi as jsonField, e as jsonIndex, s as lag, ae as lead, Ks as listRetentionConflicts, Js as listRetentions, po as localFirst, ho as localFirstTables, Oi as lt, ki as lte, Qa as makeEagerFallbackReporter, Go as makeNamespaceBranchExecutor, nn as many, rn as manyToMany, i as materializeFields, Ge as max, $e as migration, t as min, As as missingConflictColumns, ks as missingRequiredColumns, rt as mixin, Ti as neq, ko as nextBranchState, Bs as normaliseTarget, Ui as not, Yi as notExists, ji as notInSet, qi as notInSubquery, ye as numeric, Ja as observeDbOp, tn as one, Ln as oneCardinalityMessage, Hi as or, T as orderClausesOf, te as paginateBy, re as paginateById, Ta as pendingAttributionCount, Io as planBranch, Ao as planBranchProvision, jo as planBranchTeardown, Lo as planBranchTeardownFor, Po as planNeonBranchProvision, Fo as planNeonBranchTeardown, oo as planVersionedUpdate, ht as pluginRef, pe as pluginRefSpecOf, Is as primaryKeyConflictError, zo as provisionBranch, ns as provisionResidentTenant, er as qualifyTable, se as queryFor, Be as queryForView, Te as quoteIdent, Fs as raiseChangeListenerCeiling, d as rank, g as raw, _e as readableByColumns, xe as real, qa as recordDbOp, ka as recordsTable, m as reference, yi as registerCoreTables, pn as registerDiscoveredRelations, ma as registerPendingAttribution, fn as registerRelations, qs as registerRetention, nt as registerTable, Ea as registerWriteRecorder, Qt as relations, xi as requireActors, y as requireTable, Si as requireTenants, Ha as resetDbMetricTagCacheForTests, Je as resetSnowflake, es as residentPlacement, Nt as resolveActorSnapshot, No as resolveBranchMechanism, Za as resolveEagerFallbackWarnIntervalMs, Ca as resolveEchoAttribution, _ as resolveFullTextIndex, at as resolveIdScheme, Ue as resolveMixinGraph, Qo as resolveTenantHome, $n as resolveTenantNamespace, Zs as retentionTtlMsFromEnv, ee as rowNumber, Kt as rowSchema, no as runRetryingTransaction, ro as runStoreTransaction, oa as runWithWriteAttribution, Aa as runWriteRecorders, Hs as sameDatabase, Qn as sanitizeIdentifierFragment, It as serializeArraysForWrite, S as serverOnlyColumns, Yo as setResidencyConfig, Pe as setSchemaChangeSeedHook, Ie as setTenantCreateSeedHook, $a as settleTransactionExit, so as settleVersionedUpdate, Bi as spatialPredicate, Cs as stampGeneratedId, ws as stampGeneratedIds, Ni as startsWith, yo as streamTable, ue as sum, vt as sumOver, Xs as sweepRetention, w as table, Bo as teardownBranch, D as text, b as timestamp, yt as timestampMs, bt as timestampMsOrNull, r as union, ve as unionAll, Da as unregisterWriteRecorder, Ns as updateManyRow, Ms as upsertRow, tt as validateColumnName, Xe as validateIndexName, _n as validateRegisteredRelations, ln as validateRelationConfig, Ve as validateTableName, ze as validateTypeIdPrefix, we as vector, st as vectorDistanceToOpclass, So as vectorEmbedding, ao as versionColumnOf, Re as view, Ee as viewSql, ea as walkLeaves, la as withCapturedAttribution };
2301
+ export { ue as AUTO_FILLED_COLUMNS, Es as BULK_INSERT_LIMITS, J as BranchNameInvalid, ko as BranchTransitionInvalid, $s as CDC_OFFSETS_TABLE, Fs as CHANGE_LISTENER_CEILING, o as ColumnBuilder, we as DEFAULT_ACQUIRE_TIMEOUT_MS, Xa as DEFAULT_EAGER_FALLBACK_WARN_INTERVAL_MS, yn as DEFAULT_SUBJECT_GRAPH_DEPTH, zt as ENCRYPTED_PREFIX, nc as ENGINE, In as EagerCardinalityError, Ue as FILE_MIGRATION_PATTERN, st as FRAMEWORK_LIVE_TABLES, Bt as FieldDecryptionError, lo as INITIAL_VERSION, Ri as MATCHES_NO_ROWS, ut as MAX_IDENTIFIER_LENGTH, jt as SqlClient, _o as TableStreamError, Xn as TenantNamespaceInvalid, Yn as TenantNamespaceUnresolved, Jo as TenantRegionUnavailable, qo as TenantResidencyUnresolved, uo as VOLTRO_EXPIRES_MIXIN_ID, po as VOLTRO_LOCAL_FIRST_MIXIN_ID, ao as VersionConflict, Ie as WARN_IDENTIFIER_LENGTH, xs as _voltroApiKeysTable, ec as _voltroCdcOffsetsTable, ys as _voltroIdempotencyTable, bs as _voltroKvTable, vs as _voltroMigrationPlansTable, gs as _voltroMigrationsTable, tc as _voltroMssqlCdcOffsetsTable, _s as _voltroSeedsTable, wi as actorsTable, Ho as admitBranch, Oe as allEnumRenames, gn as allRegisteredRelations, h as allRegisteredTables, Hi as and, mt as array, Fi as arrayContains, Li as arrayHas, Ii as arrayOverlaps, Rn as attachEagerLoads, ua as attributionFields, ma as attributionKey, ss as auditAllTableIndexes, os as auditTableIndexes, dt as avg, _t as avgOver, Sa as beginLocalWrite, ge as bigint, ns as bindResidentStore, u as boolean, Eo as branchNamespaceName, Ds as bulkInsertLimitsFor, c as bytes, aa as changeDelete, ra as changeInsert, oa as changeSoftDelete, ia as changeUpdate, ks as chunkRowsForInsert, _a as claimPendingAttribution, ft as clearEnumRenames, Ta as clearPendingAttribution, vn as clearRelationsRegistry, Qo as clearResidencyConfig, Xs as clearRetentions, _e as clearTableRegistry, ka as clearWriteRecorders, ir as coercePredicateValue, ar as coercePredicateValues, ea as collectSubqueries, je as column, Kt as columnSchema, Os as columnsPerRow, yr as compileEagerJson, F as compilePredicate, or as compileRawFragment, vr as compileSelect, So as computeEmbedding, Hs as connectionIdentity, Ni as contains, ht as count, pe as countDistinct, se as crdtManagedColumns, qe as crdtText, la as currentWriteAttribution, a as databaseHandle, n as date, Ge as dbEnum, Wa as dbMetricTagCacheSizeForTests, qa as dbOperationsInFlight, re as decimal, vt as declareEnumRename, Nn as decodeRowsFromSchema, Gt as decryptFieldsOnRead, ms as defineMigration, $e as defineMixin, at as defineSeed, pt as denseRank, En as deriveSubjectGraph, Ae as deriveTypeIdPrefix, Rt as deserializeArraysOnRead, Re as drainIdentifierWarnings, ae as dropped, Fn as encodeRowForSchema, Wt as encryptFieldsForWrite, Ut as encryptedColumnsOf, Ca as endLocalWrite, zo as enforceBranchLimits, xe as ensureTableRegistered, Ti as eq, sr as escapeLike, $i as evaluatePredicate, he as except, Yi as exists, fo as expires, na as externalChangeEvent, Ne as fireSchemaChangeSeeds, Je as fireTenantCreateSeeds, fs as formatIndexAuditIssue, Dn as formatSubjectGraph, Ss as frameworkTables, tt as generateId, Pe as generateSnowflake, le as geography, f as geometry, Me as getEnumRenames, hn as getRelation, mn as getRelations, Zo as getResidencyConfig, p as getTable, Di as gt, Oi as gte, Jn as hasEagerLoads, xo as hybridSearch, v as id, ji as inSet, qi as inSubquery, on as inferForeignKey, Ms as insertRow, S as integer, l as intersect, fe as interval, Do as isBranchNamespace, en as isEmptyRelationsSpec, Ht as isEncrypted, Vt as isFieldDecryptionError, ke as isFileMigration, Qe as isFrameworkOwnedLiveTable, ho as isLocalFirst, hs as isMigrationDefinition, No as isNeonConnection, Bi as isNotNull, zi as isNull, Rs as isPrimaryKeyConflictError, es as isRegionServable, tn as isRelationsSpec, lt as isSeedDefinition, Ce as isSqliteFamily, ee as isTableReactive, Xe as isView, D as json, Gi as jsonField, e as jsonIndex, s as lag, oe as lead, qs as listRetentionConflicts, Ys as listRetentions, mo as localFirst, go as localFirstTables, ki as lt, Ai as lte, $a as makeEagerFallbackReporter, Ko as makeNamespaceBranchExecutor, rn as many, an as manyToMany, i as materializeFields, Ke as max, et as migration, t as min, js as missingConflictColumns, As as missingRequiredColumns, it as mixin, Ei as neq, Ao as nextBranchState, Vs as normaliseTarget, Wi as not, Xi as notExists, Mi as notInSet, Ji as notInSubquery, be as numeric, Ya as observeDbOp, nn as one, Ln as oneCardinalityMessage, Ui as or, w as orderClausesOf, ne as paginateBy, ie as paginateById, Ea as pendingAttributionCount, Lo as planBranch, jo as planBranchProvision, Mo as planBranchTeardown, Ro as planBranchTeardownFor, Fo as planNeonBranchProvision, Io as planNeonBranchTeardown, so as planVersionedUpdate, gt as pluginRef, me as pluginRefSpecOf, Ls as primaryKeyConflictError, Bo as provisionBranch, rs as provisionResidentTenant, tr as qualifyTable, ce as queryFor, Ve as queryForView, Ee as quoteIdent, Is as raiseChangeListenerCeiling, d as rank, g as raw, ve as readableByColumns, Se as real, Ja as recordDbOp, Aa as recordsTable, m as reference, bi as registerCoreTables, pn as registerDiscoveredRelations, ga as registerPendingAttribution, fn as registerRelations, Js as registerRetention, rt as registerTable, Da as registerWriteRecorder, $t as relations, Si as requireActors, y as requireTable, Ci as requireTenants, Ua as resetDbMetricTagCacheForTests, Ye as resetSnowflake, ts as residentPlacement, Pt as resolveActorSnapshot, Po as resolveBranchMechanism, Qa as resolveEagerFallbackWarnIntervalMs, wa as resolveEchoAttribution, _ as resolveFullTextIndex, ot as resolveIdScheme, We as resolveMixinGraph, $o as resolveTenantHome, er as resolveTenantNamespace, Qs as retentionTtlMsFromEnv, te as rowNumber, qt as rowSchema, ro as runRetryingTransaction, io as runStoreTransaction, ca as runWithWriteAttribution, ja as runWriteRecorders, Us as sameDatabase, $n as sanitizeIdentifierFragment, Lt as serializeArraysForWrite, x as serverOnlyColumns, Xo as setResidencyConfig, Fe as setSchemaChangeSeedHook, Le as setTenantCreateSeedHook, eo as settleTransactionExit, co as settleVersionedUpdate, Vi as spatialPredicate, ws as stampGeneratedId, Ts as stampGeneratedIds, Pi as startsWith, bo as streamTable, de as sum, yt as sumOver, Zs as sweepRetention, C as table, Vo as teardownBranch, E as text, b as timestamp, bt as timestampMs, xt as timestampMsOrNull, r as union, ye as unionAll, Oa as unregisterWriteRecorder, Ps as updateManyRow, Ns as upsertRow, nt as validateColumnName, Ze as validateIndexName, _n as validateRegisteredRelations, ln as validateRelationConfig, He as validateTableName, Be as validateTypeIdPrefix, Te as vector, ct as vectorDistanceToOpclass, Co as vectorEmbedding, oo as versionColumnOf, ze as view, De as viewSql, ta as walkLeaves, da as withCapturedAttribution };