@voltro/database 0.69.1 → 0.70.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,13 +1,13 @@
1
- import { $ as e, $t as t, A as n, At as r, B as i, Bt as a, C as o, Ct as s, D as c, Dt as l, E as u, Et as d, F as f, Ft as p, G as m, Gt as h, H as g, Ht as _, I as v, It as ee, J as te, Jt as y, K as ne, Kt as re, L as b, Lt as ie, M as x, Mt as ae, N as oe, Nt as se, O as ce, Ot as le, P as ue, Pt as de, Q as fe, Qt as pe, R as me, Rt as he, S as ge, St as _e, T as ve, Tt as ye, U as be, Ut as xe, V as Se, Vt as Ce, W as we, Wt as Te, X as Ee, Xt as S, Y as De, Yt as Oe, Z as C, Zt as ke, _ as Ae, _t as je, a as Me, an as w, at as Ne, b as Pe, bt as Fe, c as Ie, ct as T, d as Le, dt as Re, en as ze, et as Be, f as Ve, ft as He, g as Ue, gt as We, h as Ge, ht as Ke, i as qe, in as Je, it as Ye, j as Xe, jt as Ze, k as Qe, kt as $e, l as et, lt as tt, m as nt, mt as rt, n as it, nn as at, nt as ot, o as st, on as E, ot as ct, p as lt, pt as ut, q as dt, qt as D, r as ft, rn as pt, rt as mt, s as ht, sn as gt, st as _t, t as vt, tn as yt, tt as bt, u as xt, ut as St, v as Ct, vt as wt, w as Tt, wt as Et, x as Dt, xt as Ot, y as O, yt as kt, z as At, zt as jt } from "./frameworkLiveTables-CWbTSnjk.js";
2
- import { a as Mt, i as Nt, n as Pt, o as Ft, r as It, s as Lt, t as Rt } from "./wire-B28cPjEp.js";
3
- import { Cause as zt, Chunk as Bt, Data as Vt, Effect as k, Exit as Ht, Metric as A, MetricBoundaries as Ut, Option as j, Runtime as Wt, Schedule as Gt, Schema as M, Stream as Kt } from "effect";
4
- import { createHash as qt } from "node:crypto";
5
- import { AsyncLocalStorage as Jt } from "node:async_hooks";
6
- import { TransactionConnection as Yt } from "@effect/sql/SqlClient";
7
- import { ansi as N } from "@voltro/logger";
8
- import { SqlClient as Xt } from "@effect/sql";
1
+ import { $ as e, $t as t, A as n, At as r, B as i, Bt as a, C as o, Ct as s, D as c, Dt as l, E as u, Et as d, F as f, Ft as p, G as m, Gt as h, H as g, Ht as _, I as v, It as ee, J as te, Jt as y, K as ne, Kt as re, L as b, Lt as ie, M as x, Mt as ae, N as S, Nt as oe, O as se, Ot as ce, P as le, Pt as ue, Q as de, Qt as fe, R as pe, Rt as me, S as he, St as ge, T as _e, Tt as ve, U as ye, Ut as be, V as xe, Vt as Se, W as Ce, Wt as we, X as Te, Xt as C, Y as Ee, Yt as De, Z as w, Zt as Oe, _ as ke, _t as Ae, a as je, an as T, at as Me, b as Ne, bt as Pe, c as Fe, ct as E, d as Ie, dt as Le, en as Re, et as ze, f as Be, ft as Ve, g as He, gt as Ue, h as We, ht as Ge, i as Ke, in as qe, it as Je, j as Ye, jt as Xe, k as Ze, kt as Qe, l as $e, lt as et, m as tt, mt as nt, n as rt, nn as it, nt as at, o as ot, on as D, ot as st, p as ct, pt as lt, q as ut, qt as O, r as dt, rn as ft, rt as pt, s as mt, sn as ht, st as gt, t as _t, tn as vt, tt as yt, u as bt, ut as xt, v as St, vt as Ct, w as wt, wt as Tt, x as Et, xt as Dt, y as k, yt as Ot, z as kt, zt as At } from "./frameworkLiveTables-CWbTSnjk.js";
2
+ import { a as jt, i as Mt, n as Nt, o as Pt, r as Ft, s as It, t as Lt } from "./wire-B28cPjEp.js";
3
+ import { Cause as Rt, Chunk as zt, Data as Bt, Effect as A, Exit as Vt, Metric as j, MetricBoundaries as Ht, Option as M, Runtime as Ut, Schedule as Wt, Schema as N, Stream as Gt } from "effect";
4
+ import { createHash as Kt } from "node:crypto";
5
+ import { AsyncLocalStorage as qt } from "node:async_hooks";
6
+ import { TransactionConnection as Jt } from "@effect/sql/SqlClient";
7
+ import { ansi as P } from "@voltro/logger";
8
+ import { SqlClient as Yt } from "@effect/sql";
9
9
  //#region src/actorSnapshot.ts
10
- var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n) => {
10
+ var Xt = (e) => typeof e == "string" && e !== "" ? e : null, Zt = 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 Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
23
23
  }))[0];
24
24
  return r === void 0 ? void 0 : {
25
25
  id: t,
26
- type: Zt(r.kind) ?? n,
27
- displayName: Zt(r.displayName),
28
- email: Zt(r.email)
26
+ type: Xt(r.kind) ?? n,
27
+ displayName: Xt(r.displayName),
28
+ email: Xt(r.email)
29
29
  };
30
30
  } catch {
31
31
  return;
32
32
  }
33
- }, $t = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqlite", en = (e) => {
33
+ }, Qt = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqlite", $t = (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
- }, tn = (e, t, n) => {
38
- if (!$t(n) || !t) return e;
39
- let r = en(t);
37
+ }, en = (e, t, n) => {
38
+ if (!Qt(n) || !t) return e;
39
+ let r = $t(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 Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
44
44
  Array.isArray(t) && (i[e] = JSON.stringify(t));
45
45
  }
46
46
  return i;
47
- }, nn = (e, t, n) => {
48
- if (!$t(n) || !t) return e;
49
- let r = en(t);
47
+ }, tn = (e, t, n) => {
48
+ if (!Qt(n) || !t) return e;
49
+ let r = $t(t);
50
50
  return r.length === 0 ? e : e.map((e) => {
51
51
  let t;
52
52
  for (let n of r) {
@@ -58,13 +58,13 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
58
58
  }
59
59
  return t ?? e;
60
60
  });
61
- }, rn = "enc:v1:", an = "enc:v2:", on = (e, t, n) => {
61
+ }, nn = "enc:v1:", rn = "enc:v2:", an = (e, t, n) => {
62
62
  let r = `${e}:${t}`, i = n == null || n === "" ? void 0 : String(n);
63
63
  return i === void 0 ? { column: r } : {
64
64
  column: r,
65
65
  row: `${r}:${i}`
66
66
  };
67
- }, sn = (e) => typeof e == "string" && e.startsWith("enc:v2:"), cn = class extends Error {
67
+ }, on = (e) => typeof e == "string" && e.startsWith("enc:v2:"), sn = class extends Error {
68
68
  _tag = "FieldDecryptionError";
69
69
  table;
70
70
  column;
@@ -72,7 +72,7 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
72
72
  constructor(e) {
73
73
  super(`column "${e.table}.${e.column}" is .encrypted() but could not be decrypted (${e.reason}) — the stored value was most likely encrypted under a different key`), this.name = "FieldDecryptionError", this.table = e.table, this.column = e.column, this.reason = e.reason;
74
74
  }
75
- }, ln = (e) => typeof e == "object" && !!e && e._tag === "FieldDecryptionError", un = (e) => typeof e == "string" && (e.startsWith("enc:v1:") || e.startsWith("enc:v2:")), dn = (e, t, n) => e.encrypt(JSON.stringify(t), n), fn = /* @__PURE__ */ new Set([
75
+ }, cn = (e) => typeof e == "object" && !!e && e._tag === "FieldDecryptionError", ln = (e) => typeof e == "string" && (e.startsWith("enc:v1:") || e.startsWith("enc:v2:")), un = (e, t, n) => e.encrypt(JSON.stringify(t), n), dn = /* @__PURE__ */ new Set([
76
76
  "text",
77
77
  "id",
78
78
  "reference",
@@ -80,51 +80,51 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
80
80
  "uuid",
81
81
  "email",
82
82
  "url"
83
- ]), pn = (e, t, n, r) => {
83
+ ]), fn = (e, t, n, r) => {
84
84
  let i = e.decrypt(t, r), a;
85
85
  try {
86
86
  a = JSON.parse(i);
87
87
  } catch {
88
88
  return i;
89
89
  }
90
- return typeof a == "string" ? a : n === void 0 || fn.has(n) ? i : a;
91
- }, mn = (e, t, n, r) => {
90
+ return typeof a == "string" ? a : n === void 0 || dn.has(n) ? i : a;
91
+ }, pn = (e, t, n, r) => {
92
92
  let i = e.decrypt(t, r);
93
93
  try {
94
- return typeof JSON.parse(i) == "string" ? !1 : n === void 0 || fn.has(n) ? !0 : void 0;
94
+ return typeof JSON.parse(i) == "string" ? !1 : n === void 0 || dn.has(n) ? !0 : void 0;
95
95
  } catch {
96
96
  return !0;
97
97
  }
98
- }, hn = (e, t) => e.fields[t]?.type, gn = (e) => {
98
+ }, mn = (e, t) => e.fields[t]?.type, hn = (e) => {
99
99
  let t = [];
100
100
  for (let [n, r] of Object.entries(e.fields)) r.encrypted === !0 && t.push(n);
101
101
  return t;
102
- }, _n = "id", vn = (e, t, n, r) => {
102
+ }, gn = "id", _n = (e, t, n, r) => {
103
103
  if (!t) return e;
104
- let i = gn(t);
104
+ let i = hn(t);
105
105
  if (i.length === 0) return e;
106
- let a = t.tableName ?? "?", o = r ?? e[_n], s = { ...e };
106
+ let a = t.tableName ?? "?", o = r ?? e[gn], s = { ...e };
107
107
  for (let e of i) {
108
108
  let t = s[e];
109
- if (!(t == null || un(t))) {
110
- if (!n) throw Error(`column "${a}.${e}" is .encrypted() but no field cipher is registered — set VOLTRO_FIELD_ENCRYPTION_KEY (\`voltro dev\` mints one; \`voltro serve\` refuses to boot without it)`);
111
- s[e] = dn(n, t, on(a, e, o));
109
+ if (!(t == null || ln(t))) {
110
+ if (!n) throw Error(`column "${a}.${e}" is .encrypted() but no field cipher is registered — set VOLTRO_FIELD_ENCRYPTION_KEY (\`voltro dev\` mints one; \`voltro serve\` refuses to boot without it); in a test, pass \`fieldEncryptionKey\` to makeTestContext`);
111
+ s[e] = un(n, t, an(a, e, o));
112
112
  }
113
113
  }
114
114
  return s;
115
- }, yn = (e, t, n, r) => {
115
+ }, vn = (e, t, n, r) => {
116
116
  if (!t) return e;
117
- let i = gn(t);
117
+ let i = hn(t);
118
118
  if (i.length === 0 || !n) return e;
119
119
  let a = r?.onError ?? "throw", o = t.tableName ?? "?";
120
120
  return e.map((e) => {
121
121
  let s;
122
122
  for (let c of i) {
123
123
  let i = e[c];
124
- if (un(i)) {
124
+ if (ln(i)) {
125
125
  s ??= { ...e };
126
126
  try {
127
- s[c] = pn(n, i, hn(t, c), on(o, c, r?.rowId ?? e[_n]));
127
+ s[c] = fn(n, i, mn(t, c), an(o, c, r?.rowId ?? e[gn]));
128
128
  } catch (e) {
129
129
  let t = String(e?.message ?? e);
130
130
  if (a === "null") {
@@ -135,7 +135,7 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
135
135
  });
136
136
  continue;
137
137
  }
138
- throw new cn({
138
+ throw new sn({
139
139
  table: o,
140
140
  column: c,
141
141
  reason: t
@@ -145,136 +145,136 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
145
145
  }
146
146
  return s ?? e;
147
147
  });
148
- }, bn = (e) => {
148
+ }, yn = (e) => {
149
149
  let t = e;
150
- for (let e = 0; e < 4 && Wt.isFiberFailure(t); e++) t = zt.squash(t[Wt.FiberFailureCauseId]);
150
+ for (let e = 0; e < 4 && Ut.isFiberFailure(t); e++) t = Rt.squash(t[Ut.FiberFailureCauseId]);
151
151
  return t;
152
- }, xn = (e, t = 0) => {
153
- if (t >= 4 || !Wt.isFiberFailure(e)) return [e];
154
- let n = e[Wt.FiberFailureCauseId], r = [...zt.failures(n), ...zt.defects(n)];
155
- if (r.length === 0) return [zt.squash(n)];
152
+ }, bn = (e, t = 0) => {
153
+ if (t >= 4 || !Ut.isFiberFailure(e)) return [e];
154
+ let n = e[Ut.FiberFailureCauseId], r = [...Rt.failures(n), ...Rt.defects(n)];
155
+ if (r.length === 0) return [Rt.squash(n)];
156
156
  let i = [];
157
- for (let e of r.slice(0, 8)) i.push(...xn(e, t + 1));
157
+ for (let e of r.slice(0, 8)) i.push(...bn(e, t + 1));
158
158
  return i;
159
- }, Sn = (e) => e.dbCode !== void 0 || e.dbErrno !== void 0 || e.dbNumber !== void 0 || e.dbSqlState !== void 0 || e.dbConstraint !== void 0, Cn = (e) => {
160
- let t = {}, n = [], r = bn(e);
159
+ }, xn = (e) => e.dbCode !== void 0 || e.dbErrno !== void 0 || e.dbNumber !== void 0 || e.dbSqlState !== void 0 || e.dbConstraint !== void 0, Sn = (e) => {
160
+ let t = {}, n = [], r = yn(e);
161
161
  for (let e = 0; e < 8 && typeof r == "object" && r; e++) {
162
162
  let e = r;
163
163
  t.dbCode === void 0 && (typeof e.code == "string" || typeof e.code == "number") && (t.dbCode = e.code), t.dbErrno === void 0 && typeof e.errno == "number" && (t.dbErrno = e.errno), t.dbNumber === void 0 && typeof e.number == "number" && (t.dbNumber = e.number), t.dbSqlState === void 0 && typeof e.sqlState == "string" && (t.dbSqlState = e.sqlState), t.dbBindings === void 0 && typeof e.voltroBindings == "string" && (t.dbBindings = e.voltroBindings), t.dbStatement === void 0 && typeof e.sql == "string" && e.sql.includes("?") && (t.dbStatement = e.sql, t.dbPlaceholders = (e.sql.match(/\?/g) ?? []).length), t.dbFatal === void 0 && typeof e.fatal == "boolean" && (t.dbFatal = e.fatal), t.dbConstraint === void 0 && typeof e.constraint == "string" && (t.dbConstraint = e.constraint), t.dbTable === void 0 && typeof e.table == "string" && (t.dbTable = e.table), t.dbColumn === void 0 && typeof e.column == "string" && (t.dbColumn = e.column), t.dbSchema === void 0 && typeof e.schema == "string" && (t.dbSchema = e.schema);
164
164
  let i = e.sqlMessage ?? e.detail;
165
165
  t.dbMessage === void 0 && typeof i == "string" && (t.dbMessage = i);
166
166
  let a = typeof e.constructor == "function" ? e.constructor.name : void 0, o = typeof e._tag == "string" && e._tag || typeof e.name == "string" && e.name || (typeof a == "string" && a !== "Object" ? a : void 0), s = typeof e.message == "string" ? e.message : void 0;
167
- (o || s) && n.push(`${o || "Error"}${s ? `: ${s.slice(0, 200)}` : ""}`), r = bn(e.cause);
167
+ (o || s) && n.push(`${o || "Error"}${s ? `: ${s.slice(0, 200)}` : ""}`), r = yn(e.cause);
168
168
  }
169
169
  return n.length > 0 && (t.dbCauseChain = n.join(" ← "), t.dbMessage === void 0 && (t.dbMessage = n[n.length - 1])), t;
170
- }, wn = (e) => {
171
- let t = xn(e).map(Cn);
170
+ }, Cn = (e) => {
171
+ let t = bn(e).map(Sn);
172
172
  if (t.length <= 1) return t[0] ?? {};
173
- let n = t.find(Sn) ?? t[0], r = t.filter((e) => e !== n).map((e) => e.dbCauseChain).filter((e) => typeof e == "string");
173
+ let n = t.find(xn) ?? t[0], r = t.filter((e) => e !== n).map((e) => e.dbCauseChain).filter((e) => typeof e == "string");
174
174
  if (r.length === 0) return n;
175
175
  let i = typeof n.dbCauseChain == "string" ? n.dbCauseChain : void 0;
176
176
  return {
177
177
  ...n,
178
178
  dbCauseChain: [i, ...r].filter(Boolean).join(" ‖ ")
179
179
  };
180
- }, Tn = (e, t) => {
181
- let n = wn(e), r = jn(n, t);
180
+ }, wn = (e, t) => {
181
+ let n = Cn(e), r = An(n, t);
182
182
  if (r !== void 0) {
183
183
  let e = r.constraint ?? r.column;
184
184
  return e === void 0 ? r.kind : `${r.kind}: ${e}`;
185
185
  }
186
- let i = n.dbCode ?? n.dbSqlState ?? n.dbErrno ?? n.dbNumber, a = On(e);
187
- return i !== void 0 && En.test(String(i)) ? `${a} (${String(i)})` : a;
188
- }, En = /^[A-Za-z0-9_]{1,32}$/, Dn = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/, On = (e) => {
186
+ let i = n.dbCode ?? n.dbSqlState ?? n.dbErrno ?? n.dbNumber, a = Dn(e);
187
+ return i !== void 0 && Tn.test(String(i)) ? `${a} (${String(i)})` : a;
188
+ }, Tn = /^[A-Za-z0-9_]{1,32}$/, En = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/, Dn = (e) => {
189
189
  let t = e?._tag, n = e?.name, r = (typeof t == "string" ? t : typeof n == "string" ? n : "").split(/[^A-Za-z0-9_]+/).filter(Boolean).pop();
190
- return r !== void 0 && Dn.test(r) ? r : "unknown";
191
- }, kn = /^[A-Za-z_][A-Za-z0-9_$]*$/, P = (e) => e !== void 0 && e.length <= 128 && kn.test(e) ? e : void 0, An = (e) => e === void 0 ? void 0 : e.split(".").pop() ?? e, F = (e, ...t) => {
190
+ return r !== void 0 && En.test(r) ? r : "unknown";
191
+ }, On = /^[A-Za-z_][A-Za-z0-9_$]*$/, F = (e) => e !== void 0 && e.length <= 128 && On.test(e) ? e : void 0, kn = (e) => e === void 0 ? void 0 : e.split(".").pop() ?? e, I = (e, ...t) => {
192
192
  for (let n of t) {
193
193
  let t = n.exec(e);
194
194
  if (t?.[1] !== void 0) return t[1];
195
195
  }
196
- }, jn = (e, t) => {
196
+ }, An = (e, t) => {
197
197
  let n = e.dbCode, r = e.dbErrno, i = e.dbNumber, a = typeof e.dbMessage == "string" ? e.dbMessage : "", o = `${typeof e.dbCauseChain == "string" ? e.dbCauseChain : ""} ${a}`;
198
198
  if (n === "23503") {
199
- let t = P(e.dbConstraint);
199
+ let t = F(e.dbConstraint);
200
200
  return {
201
201
  kind: /is still referenced from table/i.test(o) ? "foreignKeyInUse" : "foreignKey",
202
202
  ...t === void 0 ? {} : { constraint: t }
203
203
  };
204
204
  }
205
205
  if (n === "23505") {
206
- let t = P(e.dbConstraint);
206
+ let t = F(e.dbConstraint);
207
207
  return {
208
208
  kind: "unique",
209
209
  ...t === void 0 ? {} : { constraint: t }
210
210
  };
211
211
  }
212
212
  if (n === "23502") {
213
- let t = P(e.dbColumn);
213
+ let t = F(e.dbColumn);
214
214
  return {
215
215
  kind: "notNull",
216
216
  ...t === void 0 ? {} : { column: t }
217
217
  };
218
218
  }
219
219
  if (n === "23514") {
220
- let t = P(e.dbConstraint);
220
+ let t = F(e.dbConstraint);
221
221
  return {
222
222
  kind: "check",
223
223
  ...t === void 0 ? {} : { constraint: t }
224
224
  };
225
225
  }
226
226
  if (r === 1452 || r === 1451) {
227
- let e = P(F(o, /CONSTRAINT `([^`]+)`/));
227
+ let e = F(I(o, /CONSTRAINT `([^`]+)`/));
228
228
  return {
229
229
  kind: r === 1451 ? "foreignKeyInUse" : "foreignKey",
230
230
  ...e === void 0 ? {} : { constraint: e }
231
231
  };
232
232
  }
233
233
  if (r === 1062) {
234
- let e = P(An(F(o, /for key '([^']+)'/)));
234
+ let e = F(kn(I(o, /for key '([^']+)'/)));
235
235
  return {
236
236
  kind: "unique",
237
237
  ...e === void 0 ? {} : { constraint: e }
238
238
  };
239
239
  }
240
240
  if (r === 1048 || r === 1364) {
241
- let e = P(F(o, /Column '([^']+)' cannot be null/, /Field '([^']+)' doesn't have a default value/));
241
+ let e = F(I(o, /Column '([^']+)' cannot be null/, /Field '([^']+)' doesn't have a default value/));
242
242
  return {
243
243
  kind: "notNull",
244
244
  ...e === void 0 ? {} : { column: e }
245
245
  };
246
246
  }
247
247
  if (r === 3819 || r === 4025) {
248
- let e = P(F(o, /Check constraint '([^']+)'/, /CONSTRAINT `([^`]+)` failed/));
248
+ let e = F(I(o, /Check constraint '([^']+)'/, /CONSTRAINT `([^`]+)` failed/));
249
249
  return {
250
250
  kind: "check",
251
251
  ...e === void 0 ? {} : { constraint: e }
252
252
  };
253
253
  }
254
254
  if (i === 547) {
255
- let e = F(o, /(?:FOREIGN KEY|REFERENCE) constraint "([^"]+)"/), t = F(o, /CHECK constraint "([^"]+)"/);
255
+ let e = I(o, /(?:FOREIGN KEY|REFERENCE) constraint "([^"]+)"/), t = I(o, /CHECK constraint "([^"]+)"/);
256
256
  if (t !== void 0 && e === void 0) {
257
- let e = P(t);
257
+ let e = F(t);
258
258
  return {
259
259
  kind: "check",
260
260
  ...e === void 0 ? {} : { constraint: e }
261
261
  };
262
262
  }
263
- let n = /REFERENCE constraint/.test(o), r = P(e);
263
+ let n = /REFERENCE constraint/.test(o), r = F(e);
264
264
  return {
265
265
  kind: n ? "foreignKeyInUse" : "foreignKey",
266
266
  ...r === void 0 ? {} : { constraint: r }
267
267
  };
268
268
  }
269
269
  if (i === 2627 || i === 2601) {
270
- let e = P(F(o, /(?:UNIQUE KEY|PRIMARY KEY) constraint '([^']+)'/, /index '([^']+)'/));
270
+ let e = F(I(o, /(?:UNIQUE KEY|PRIMARY KEY) constraint '([^']+)'/, /index '([^']+)'/));
271
271
  return {
272
272
  kind: "unique",
273
273
  ...e === void 0 ? {} : { constraint: e }
274
274
  };
275
275
  }
276
276
  if (i === 515) {
277
- let e = P(F(o, /Cannot insert the value NULL into column '([^']+)'/));
277
+ let e = F(I(o, /Cannot insert the value NULL into column '([^']+)'/));
278
278
  return {
279
279
  kind: "notNull",
280
280
  ...e === void 0 ? {} : { column: e }
@@ -282,34 +282,34 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
282
282
  }
283
283
  if (n === "SQLITE_CONSTRAINT_FOREIGNKEY") return { kind: t === "delete" || t === "deleteMany" || t === "hardDelete" ? "foreignKeyInUse" : "foreignKey" };
284
284
  if (n === "SQLITE_CONSTRAINT_UNIQUE" || n === "SQLITE_CONSTRAINT_PRIMARYKEY") {
285
- let e = P(An(F(o, /UNIQUE constraint failed: ([^,\s]+)/)));
285
+ let e = F(kn(I(o, /UNIQUE constraint failed: ([^,\s]+)/)));
286
286
  return {
287
287
  kind: "unique",
288
288
  ...e === void 0 ? {} : { column: e }
289
289
  };
290
290
  }
291
291
  if (n === "SQLITE_CONSTRAINT_NOTNULL") {
292
- let e = P(An(F(o, /NOT NULL constraint failed: ([^,\s]+)/)));
292
+ let e = F(kn(I(o, /NOT NULL constraint failed: ([^,\s]+)/)));
293
293
  return {
294
294
  kind: "notNull",
295
295
  ...e === void 0 ? {} : { column: e }
296
296
  };
297
297
  }
298
298
  if (n === "SQLITE_CONSTRAINT_CHECK") {
299
- let e = P(F(a, /CHECK constraint failed: (.+)$/));
299
+ let e = F(I(a, /CHECK constraint failed: (.+)$/));
300
300
  return {
301
301
  kind: "check",
302
302
  ...e === void 0 ? {} : { constraint: e }
303
303
  };
304
304
  }
305
- }, Mn = (e) => {
306
- let t = jn(e)?.kind;
305
+ }, jn = (e) => {
306
+ let t = An(e)?.kind;
307
307
  return t === "foreignKey" || t === "foreignKeyInUse";
308
- }, Nn = (e) => {
308
+ }, Mn = (e) => {
309
309
  let t = e.dbCode, n = e.dbErrno;
310
310
  return t === "57014" || n === 3024 || n === 1969 || t === "ETIMEOUT" || t === "SQLITE_INTERRUPT";
311
- }, Pn = (e) => {
312
- let t = wn(e), n = [
311
+ }, Nn = (e) => {
312
+ let t = Cn(e), n = [
313
313
  t.dbCode === void 0 ? void 0 : `code=${String(t.dbCode)}`,
314
314
  t.dbErrno === void 0 ? void 0 : `errno=${String(t.dbErrno)}`,
315
315
  t.dbNumber === void 0 ? void 0 : `number=${String(t.dbNumber)}`,
@@ -318,7 +318,7 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
318
318
  t.dbPlaceholders === void 0 ? void 0 : `placeholders=${String(t.dbPlaceholders)}`
319
319
  ].filter((e) => e !== void 0), r = typeof e?.message == "string" ? e.message : void 0, i = typeof t.dbMessage == "string" ? t.dbMessage : void 0, a = i === void 0 ? void 0 : n.length > 0 || i !== r && i !== `Error: ${String(r)}` ? i : void 0, o = typeof t.dbBindings == "string" ? `\n bindings: ${t.dbBindings}` : "", s = typeof t.dbStatement == "string" ? `\n statement: ${t.dbStatement.length <= 400 ? t.dbStatement : `${t.dbStatement.slice(0, 400)}…`}` : "";
320
320
  if (a !== void 0 || n.length !== 0) return [a, n.length > 0 ? `[${n.join(" ")}]` : void 0].filter((e) => e !== void 0 && e !== "").join(" ") + s + o;
321
- }, Fn = (e) => Object.entries(e).map(([e, t]) => `${e}:${In(t)}`).join(" "), In = (e) => {
321
+ }, Pn = (e) => Object.entries(e).map(([e, t]) => `${e}:${Fn(t)}`).join(" "), Fn = (e) => {
322
322
  if (e === null) return "null";
323
323
  if (e === void 0) return "undefined";
324
324
  if (typeof e == "bigint") return "bigint";
@@ -328,77 +328,77 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
328
328
  if (globalThis.Buffer !== void 0 && globalThis.Buffer.isBuffer(e)) return "Buffer";
329
329
  let t = e.constructor?.name;
330
330
  return typeof t == "string" && t !== "" ? t : "Object";
331
- }, Ln = Symbol.for("@voltro/database/storeRefusal"), Rn = (e) => {
331
+ }, In = Symbol.for("@voltro/database/storeRefusal"), Ln = (e) => {
332
332
  let t = Error(e.detail);
333
- return Object.defineProperty(t, Ln, {
333
+ return Object.defineProperty(t, In, {
334
334
  value: e,
335
335
  enumerable: !1
336
336
  }), t;
337
- }, zn = (e) => {
338
- for (let t of xn(e)) {
337
+ }, Rn = (e) => {
338
+ for (let t of bn(e)) {
339
339
  let e = t;
340
340
  for (let t = 0; e != null && t < 8; t += 1) {
341
- let t = e[Ln];
341
+ let t = e[In];
342
342
  if (t !== void 0) return t;
343
343
  e = e.cause;
344
344
  }
345
345
  }
346
- }, Bn = (e) => {
346
+ }, zn = (e) => {
347
347
  let t = (() => {
348
348
  switch (e.type) {
349
- case "id": return e.idScheme?.kind === "numeric" ? M.Number : M.String;
349
+ case "id": return e.idScheme?.kind === "numeric" ? N.Number : N.String;
350
350
  case "text":
351
- case "enum": return M.String;
352
- case "reference": return e.referenceStorage === "numeric" ? M.Number : M.String;
351
+ case "enum": return N.String;
352
+ case "reference": return e.referenceStorage === "numeric" ? N.Number : N.String;
353
353
  case "integer":
354
354
  case "real":
355
- case "decimal": return M.Number;
356
- case "boolean": return M.Boolean;
355
+ case "decimal": return N.Number;
356
+ case "boolean": return N.Boolean;
357
357
  case "timestamp":
358
- case "date": return Rt;
359
- case "bigint": return M.BigInt;
360
- case "bytes": return M.Uint8ArrayFromBase64;
361
- case "array": return M.Array(M.Unknown);
362
- case "interval": return M.String;
363
- default: return M.Unknown;
358
+ case "date": return Lt;
359
+ case "bigint": return N.BigInt;
360
+ case "bytes": return N.Uint8ArrayFromBase64;
361
+ case "array": return N.Array(N.Unknown);
362
+ case "interval": return N.String;
363
+ default: return N.Unknown;
364
364
  }
365
365
  })();
366
- return e.nullable === !0 ? M.NullOr(t) : t;
367
- }, Vn = (e, t) => {
366
+ return e.nullable === !0 ? N.NullOr(t) : t;
367
+ }, Bn = (e, t) => {
368
368
  let n = new Set(t?.omit ?? []), r = {};
369
- for (let [t, i] of Object.entries(e.fields)) n.has(t) || (r[t] = Bn(i));
370
- return M.Struct(r);
371
- }, Hn = (e) => typeof e == "function" ? e : () => e, Un = (e, t) => ({
369
+ for (let [t, i] of Object.entries(e.fields)) n.has(t) || (r[t] = zn(i));
370
+ return N.Struct(r);
371
+ }, Vn = (e) => typeof e == "function" ? e : () => e, Hn = (e, t) => ({
372
372
  kind: "one",
373
- target: Hn(e),
373
+ target: Vn(e),
374
374
  ...t?.foreignKey === void 0 ? {} : { foreignKey: t.foreignKey },
375
375
  ...t?.sourceKey === void 0 ? {} : { sourceKey: t.sourceKey }
376
- }), Wn = (e, t) => ({
376
+ }), Un = (e, t) => ({
377
377
  kind: "many",
378
- target: Hn(e),
378
+ target: Vn(e),
379
379
  ...t?.foreignKey === void 0 ? {} : { foreignKey: t.foreignKey },
380
380
  ...t?.sourceKey === void 0 ? {} : { sourceKey: t.sourceKey }
381
- }), Gn = (e, t) => ({
381
+ }), Wn = (e, t) => ({
382
382
  kind: "manyToMany",
383
- target: Hn(e),
384
- through: Hn(t.through),
383
+ target: Vn(e),
384
+ through: Vn(t.through),
385
385
  sourceKey: t.sourceKey,
386
386
  targetKey: t.targetKey
387
- }), Kn = {
388
- one: Un,
389
- many: Wn,
390
- manyToMany: Gn
391
- }, qn = (e, t) => {
387
+ }), Gn = {
388
+ one: Hn,
389
+ many: Un,
390
+ manyToMany: Wn
391
+ }, Kn = (e, t) => {
392
392
  let n = typeof e == "function" ? e : () => e;
393
393
  return {
394
394
  source: n,
395
- relations: t(Kn, n())
395
+ relations: t(Gn, n())
396
396
  };
397
- }, Jn = (e) => {
397
+ }, qn = (e) => {
398
398
  if (typeof e != "object" || !e) return !1;
399
399
  let t = e;
400
400
  return typeof t.source != "function" || typeof t.relations != "object" || t.relations === null ? !1 : Object.keys(t.relations).length === 0;
401
- }, Yn = (e) => {
401
+ }, Jn = (e) => {
402
402
  if (typeof e != "object" || !e) return !1;
403
403
  let t = e;
404
404
  if (typeof t.source != "function" || typeof t.relations != "object" || t.relations === null) return !1;
@@ -407,35 +407,35 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
407
407
  let t = e?.kind;
408
408
  return t === "one" || t === "many" || t === "manyToMany";
409
409
  });
410
- }, Xn = Un, Zn = Wn, Qn = Gn, $n = (e, t, n) => {
410
+ }, Yn = Hn, Xn = Un, Zn = Wn, Qn = (e, t, n) => {
411
411
  let r = [];
412
412
  for (let [n, i] of Object.entries(e.fields)) i.type === "reference" && i.references?.()?.tableName === t && r.push(n);
413
413
  if (r.length === 0) throw Error(`relation '${n}': no reference() column on '${e.tableName}' points at '${t}'. Either add one or pass an explicit { foreignKey: '<column>' }.`);
414
414
  if (r.length > 1) throw Error(`relation '${n}': multiple reference() columns on '${e.tableName}' point at '${t}' (${r.join(", ")}). Pass an explicit { foreignKey: '<column>' } to disambiguate.`);
415
415
  return r[0];
416
- }, er = (e) => Object.keys(e.fields), tr = (e, t) => Object.prototype.hasOwnProperty.call(e.fields, t), nr = (e) => {
417
- let t = er(e);
416
+ }, $n = (e) => Object.keys(e.fields), er = (e, t) => Object.prototype.hasOwnProperty.call(e.fields, t), tr = (e) => {
417
+ let t = $n(e);
418
418
  return t.length === 0 ? "<none>" : t.join(", ");
419
- }, rr = (e, t, n) => {
419
+ }, nr = (e, t, n) => {
420
420
  let r = `relation '${t}' on '${e.tableName}'`, i = n.target();
421
421
  if (n.kind === "manyToMany") {
422
422
  let t = n.through();
423
- for (let [a, o] of [["sourceKey", n.sourceKey], ["targetKey", n.targetKey]]) if (!tr(t, o)) throw Error(`${r}: manyToMany ${a} '${o}' is not a column on the junction table '${t.tableName}'. Both keys name columns on the JUNCTION — ${a === "sourceKey" ? `sourceKey points at '${e.tableName}'` : `targetKey points at '${i.tableName}'`}. Columns on '${t.tableName}': ${nr(t)}.`);
423
+ for (let [a, o] of [["sourceKey", n.sourceKey], ["targetKey", n.targetKey]]) if (!er(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}': ${tr(t)}.`);
424
424
  return;
425
425
  }
426
426
  if (n.sourceKey !== void 0 && n.foreignKey !== void 0) throw Error(`${r}: pass EITHER sourceKey OR foreignKey, not both. sourceKey '${n.sourceKey}' names a column on the source ('${e.tableName}') holding the target's id; foreignKey '${n.foreignKey}' names a column on the target ('${i.tableName}') holding the source's id. With both, foreignKey is ignored.`);
427
- if (n.sourceKey !== void 0 && !tr(e, n.sourceKey)) {
428
- let t = tr(i, n.sourceKey);
429
- throw Error(`${r}: sourceKey '${n.sourceKey}' is not a column on the source table '${e.tableName}'.` + (t ? ` It IS a column on the target '${i.tableName}' — you probably want { foreignKey: '${n.sourceKey}' }, which names the column on the TARGET that holds this table's id.` : ` Columns on '${e.tableName}': ${nr(e)}.`));
427
+ if (n.sourceKey !== void 0 && !er(e, n.sourceKey)) {
428
+ let t = er(i, n.sourceKey);
429
+ throw Error(`${r}: sourceKey '${n.sourceKey}' is not a column on the source table '${e.tableName}'.` + (t ? ` It IS a column on the target '${i.tableName}' — you probably want { foreignKey: '${n.sourceKey}' }, which names the column on the TARGET that holds this table's id.` : ` Columns on '${e.tableName}': ${tr(e)}.`));
430
430
  }
431
- if (n.foreignKey !== void 0 && !tr(i, n.foreignKey)) {
432
- let t = tr(e, n.foreignKey);
433
- throw Error(`${r}: foreignKey '${n.foreignKey}' is not a column on the target table '${i.tableName}'.` + (t ? ` It IS a column on the source '${e.tableName}' — you want { sourceKey: '${n.foreignKey}' }. foreignKey names the column on the TARGET that points back at this table; sourceKey names the column on THIS table that holds the target's id.` : ` Columns on '${i.tableName}': ${nr(i)}.`));
431
+ if (n.foreignKey !== void 0 && !er(i, n.foreignKey)) {
432
+ let t = er(e, n.foreignKey);
433
+ throw Error(`${r}: foreignKey '${n.foreignKey}' is not a column on the target table '${i.tableName}'.` + (t ? ` It IS a column on the source '${e.tableName}' — you want { sourceKey: '${n.foreignKey}' }. foreignKey names the column on the TARGET that points back at this table; sourceKey names the column on THIS table that holds the target's id.` : ` Columns on '${i.tableName}': ${tr(i)}.`));
434
434
  }
435
- }, ir = Symbol.for("@voltro/database/relationsRegistry"), ar = globalThis, I = ar[ir] ?? (ar[ir] = /* @__PURE__ */ new Map()), or = (e) => {
436
- let t = e.source(), n = I.get(t.tableName);
435
+ }, rr = Symbol.for("@voltro/database/relationsRegistry"), ir = globalThis, L = ir[rr] ?? (ir[rr] = /* @__PURE__ */ new Map()), ar = (e) => {
436
+ let t = e.source(), n = L.get(t.tableName);
437
437
  if (n === void 0) {
438
- I.set(t.tableName, new Map(Object.entries(e.relations)));
438
+ L.set(t.tableName, new Map(Object.entries(e.relations)));
439
439
  return;
440
440
  }
441
441
  for (let [r, i] of Object.entries(e.relations)) {
@@ -445,33 +445,33 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
445
445
  n.set(r, i);
446
446
  }
447
447
  }
448
- }, sr = (e) => {
448
+ }, or = (e) => {
449
449
  let t = 0;
450
- for (let n of Object.values(e)) Yn(n) && (or(n), t += 1);
450
+ for (let n of Object.values(e)) Jn(n) && (ar(n), t += 1);
451
451
  return t;
452
- }, cr = (e) => {
453
- let t = I.get(e);
452
+ }, sr = (e) => {
453
+ let t = L.get(e);
454
454
  if (t !== void 0) return Object.fromEntries(t);
455
- }, lr = (e, t) => I.get(e)?.get(t), ur = () => {
455
+ }, cr = (e, t) => L.get(e)?.get(t), lr = () => {
456
456
  let e = [];
457
- for (let [t, n] of I) for (let [r, i] of n) e.push({
457
+ for (let [t, n] of L) for (let [r, i] of n) e.push({
458
458
  source: t,
459
459
  name: r,
460
460
  relation: i
461
461
  });
462
462
  return e;
463
- }, dr = () => {
464
- for (let [e, t] of I) {
465
- let n = C(e);
466
- if (n !== void 0) for (let [e, r] of t) rr(n, e, r);
463
+ }, ur = () => {
464
+ for (let [e, t] of L) {
465
+ let n = w(e);
466
+ if (n !== void 0) for (let [e, r] of t) nr(n, e, r);
467
467
  }
468
- }, fr = () => {
469
- I.clear();
470
- }, pr = 4, mr = (e) => Object.keys(e.fields), hr = (e, t) => Object.prototype.hasOwnProperty.call(e.fields, t), gr = (e, t) => {
468
+ }, dr = () => {
469
+ L.clear();
470
+ }, fr = 4, pr = (e) => Object.keys(e.fields), mr = (e, t) => Object.prototype.hasOwnProperty.call(e.fields, t), hr = (e, t) => {
471
471
  let n = [];
472
472
  for (let [r, i] of Object.entries(e.fields)) i.type === "reference" && i.references?.()?.tableName === t && n.push(r);
473
473
  return n;
474
- }, _r = (e, t) => {
474
+ }, gr = (e, t) => {
475
475
  let n = [];
476
476
  for (let r of t) {
477
477
  if (r.source !== e) continue;
@@ -488,7 +488,7 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
488
488
  } catch {
489
489
  continue;
490
490
  }
491
- if (!hr(e, t.sourceKey)) continue;
491
+ if (!mr(e, t.sourceKey)) continue;
492
492
  n.push({
493
493
  table: e.tableName,
494
494
  foreignKey: t.sourceKey,
@@ -497,8 +497,8 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
497
497
  continue;
498
498
  }
499
499
  if (t.sourceKey !== void 0) continue;
500
- let a = gr(i, e), o = t.foreignKey ?? (a.length === 1 ? a[0] : void 0);
501
- if (o === void 0 || !hr(i, o)) continue;
500
+ let a = hr(i, e), o = t.foreignKey ?? (a.length === 1 ? a[0] : void 0);
501
+ if (o === void 0 || !mr(i, o)) continue;
502
502
  let s = i.fields[o];
503
503
  n.push({
504
504
  table: i.tableName,
@@ -507,9 +507,9 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
507
507
  });
508
508
  }
509
509
  return n;
510
- }, vr = (e, t) => {
510
+ }, _r = (e, t) => {
511
511
  let n = [];
512
- for (let r of t) if (r.tableName !== e) for (let t of gr(r, e)) {
512
+ for (let r of t) if (r.tableName !== e) for (let t of hr(r, e)) {
513
513
  let e = r.fields[t];
514
514
  n.push({
515
515
  table: r.tableName,
@@ -518,8 +518,8 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
518
518
  });
519
519
  }
520
520
  return n;
521
- }, yr = (e) => `${e.table}\u0000${e.hops.map((e) => `${e.table}.${e.foreignKey}<-${e.parentKey}`).join("|")}`, br = (e) => {
522
- let t = e.tables ?? te(), n = e.relations ?? ur(), r = e.maxDepth ?? 4, i = new Set(e.exclude ?? []), a = new Map(t.map((e) => [e.tableName, e])), o = [];
521
+ }, vr = (e) => `${e.table}\u0000${e.hops.map((e) => `${e.table}.${e.foreignKey}<-${e.parentKey}`).join("|")}`, yr = (e) => {
522
+ let t = e.tables ?? te(), n = e.relations ?? lr(), r = e.maxDepth ?? 4, i = new Set(e.exclude ?? []), a = new Map(t.map((e) => [e.tableName, e])), o = [];
523
523
  if (!a.has(e.subjectTable)) return {
524
524
  subjectTable: e.subjectTable,
525
525
  paths: [],
@@ -534,11 +534,11 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
534
534
  hops: [],
535
535
  depth: 0,
536
536
  via: "relation"
537
- }, c = [s], l = /* @__PURE__ */ new Set([yr(s)]), u = /* @__PURE__ */ new Set(), d = [s];
537
+ }, c = [s], l = /* @__PURE__ */ new Set([vr(s)]), u = /* @__PURE__ */ new Set(), d = [s];
538
538
  for (let e = 1; e <= r; e++) {
539
539
  let r = [];
540
540
  for (let a of d) {
541
- let s = _r(a.table, n), d = vr(a.table, t), f = [...s.map((e) => [e, "relation"]), ...d.map((e) => [e, "reference"])];
541
+ let s = gr(a.table, n), d = _r(a.table, t), f = [...s.map((e) => [e, "relation"]), ...d.map((e) => [e, "reference"])];
542
542
  for (let [t, n] of f) {
543
543
  if (i.has(t.table)) {
544
544
  o.push({
@@ -556,7 +556,7 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
556
556
  hops: [...a.hops, t],
557
557
  depth: e,
558
558
  via: n
559
- }, f = yr(d);
559
+ }, f = vr(d);
560
560
  l.has(f) || (l.add(f), c.push(d), r.push(d));
561
561
  }
562
562
  }
@@ -566,7 +566,7 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
566
566
  }
567
567
  d = r;
568
568
  }
569
- for (let e of d) (_r(e.table, n).length > 0 || vr(e.table, t).length > 0) && o.push({
569
+ for (let e of d) (gr(e.table, n).length > 0 || _r(e.table, t).length > 0) && o.push({
570
570
  kind: "depth-truncated",
571
571
  table: e.table,
572
572
  detail: `stopped at maxDepth ${r}; tables linked FROM '${e.table}' were not explored`
@@ -575,14 +575,14 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
575
575
  for (let n of t) f.has(n.tableName) || i.has(n.tableName) || o.push({
576
576
  kind: "unreachable",
577
577
  table: n.tableName,
578
- detail: `no relation() and no reference() column links '${n.tableName}' to '${e.subjectTable}'. If it holds subject data through a plain column, a polymorphic (type,id) pair, JSON or free text, add an explicit subjectScopes entry — this derivation cannot see it. Columns: ${mr(n).join(", ")}`
578
+ detail: `no relation() and no reference() column links '${n.tableName}' to '${e.subjectTable}'. If it holds subject data through a plain column, a polymorphic (type,id) pair, JSON or free text, add an explicit subjectScopes entry — this derivation cannot see it. Columns: ${pr(n).join(", ")}`
579
579
  });
580
580
  return {
581
581
  subjectTable: e.subjectTable,
582
582
  paths: c,
583
583
  limitations: o
584
584
  };
585
- }, xr = (e) => {
585
+ }, br = (e) => {
586
586
  let t = [`subject graph · ${e.subjectTable} · ${e.paths.length} table(s) reachable`];
587
587
  for (let n of e.paths) {
588
588
  let r = n.hops.length === 0 ? `${e.subjectTable} (the subject row itself)` : [e.subjectTable, ...n.hops.map((e) => `${e.table}.${e.foreignKey}`)].join(" → ");
@@ -590,7 +590,7 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
590
590
  }
591
591
  let n = e.limitations.filter((e) => e.kind === "depth-truncated"), r = e.limitations.filter((e) => e.kind === "unreachable"), i = e.limitations.filter((e) => e.kind === "excluded");
592
592
  return t.push(""), t.push(" WHAT THIS CANNOT SEE — a DSAR is only as complete as this list is short:"), n.length > 0 && t.push(` depth-truncated (${n.length}): ${n.map((e) => e.table).join(", ")}`), i.length > 0 && t.push(` excluded (${i.length}): ${[...new Set(i.map((e) => e.table))].join(", ")}`), t.push(r.length === 0 ? " unreachable: none — every registered table is linked to the subject." : ` unreachable (${r.length}): ${r.map((e) => e.table).join(", ")}`), t.push(" Always outside this graph: object storage / uploaded files, external processors,"), t.push(" log and metric sinks, backups, and any subject id embedded in JSON or free text."), t.join("\n");
593
- }, Sr = (e) => e == null || typeof e == "boolean" ? e : typeof e == "number" ? e !== 0 : typeof e == "bigint" ? e !== 0n : typeof e == "string" ? e === "1" || e.toLowerCase() === "true" : e, Cr = (e) => {
593
+ }, xr = (e) => e == null || typeof e == "boolean" ? e : typeof e == "number" ? e !== 0 : typeof e == "bigint" ? e !== 0n : typeof e == "string" ? e === "1" || e.toLowerCase() === "true" : e, Sr = (e) => {
594
594
  if (e == null || typeof e != "string") return e;
595
595
  let t = e.trim();
596
596
  if (t.length === 0) return e;
@@ -601,7 +601,7 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
601
601
  } catch {
602
602
  return e;
603
603
  }
604
- }, wr = (e) => e == null || typeof e == "string" ? e : typeof e == "number" || typeof e == "bigint" ? String(e) : e, Tr = (e) => {
604
+ }, Cr = (e) => e == null || typeof e == "string" ? e : typeof e == "number" || typeof e == "bigint" ? String(e) : e, wr = (e) => {
605
605
  if (e == null || e instanceof Date) return e;
606
606
  if (typeof e == "string") {
607
607
  let t = new Date(e);
@@ -612,21 +612,21 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
612
612
  return isNaN(t.getTime()) ? e : t;
613
613
  }
614
614
  return e;
615
- }, Er = (e, t, n) => {
615
+ }, Tr = (e, t, n) => {
616
616
  if (e == null) return e;
617
617
  switch (t) {
618
- case "boolean": return n === "postgres" ? e : Sr(e);
618
+ case "boolean": return n === "postgres" ? e : xr(e);
619
619
  case "json":
620
- case "array": return n === "postgres" ? e : Cr(e);
620
+ case "array": return n === "postgres" ? e : Sr(e);
621
621
  case "timestamp":
622
- case "date": return n === "sqlite" || n === "turso" ? Tr(e) : e;
622
+ case "date": return n === "sqlite" || n === "turso" ? wr(e) : e;
623
623
  case "decimal":
624
- case "bigint": return wr(e);
624
+ case "bigint": return Cr(e);
625
625
  default: return e;
626
626
  }
627
- }, Dr = (e, t, n) => {
627
+ }, Er = (e, t, n) => {
628
628
  if (e.length === 0) return e;
629
- let r = C(t);
629
+ let r = w(t);
630
630
  if (r === void 0) return e;
631
631
  let i = r.fields, a = [];
632
632
  for (let [e, t] of Object.entries(i)) a.push({
@@ -635,31 +635,31 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
635
635
  });
636
636
  return e.map((e) => {
637
637
  let t = { ...e };
638
- for (let { key: e, type: r } of a) e in t && (t[e] = Er(t[e], r, n));
638
+ for (let { key: e, type: r } of a) e in t && (t[e] = Tr(t[e], r, n));
639
639
  return t;
640
640
  });
641
- }, Or = (e, t) => {
641
+ }, Dr = (e, t) => {
642
642
  if (e == null) return e;
643
643
  switch (t) {
644
644
  case "json":
645
645
  case "array": return typeof e == "string" ? e : JSON.stringify(e);
646
646
  default: return e;
647
647
  }
648
- }, kr = (e, t, n = ["json", "array"]) => {
649
- let r = C(t);
648
+ }, Or = (e, t, n = ["json", "array"]) => {
649
+ let r = w(t);
650
650
  if (r === void 0) return e;
651
651
  let i = r.fields, a = null;
652
652
  for (let [t, r] of Object.entries(i)) if (n.includes(r.type) && t in e) {
653
- let n = Or(e[t], r.type);
653
+ let n = Dr(e[t], r.type);
654
654
  n !== e[t] && (a === null && (a = { ...e }), a[t] = n);
655
655
  }
656
656
  return a ?? e;
657
- }, Ar = (e) => Object.fromEntries(Object.entries(e.updateValues ?? {}).filter(([t, n]) => {
657
+ }, kr = (e) => Object.fromEntries(Object.entries(e.updateValues ?? {}).filter(([t, n]) => {
658
658
  if (n === void 0) return !1;
659
659
  if (t === "id" || e.conflictColumns.includes(t)) throw Error(`upsert: updateValues cannot rewrite row identity column '${t}'`);
660
660
  return !0;
661
- })), jr = (e, t, n) => {
662
- let r = Ar(n);
661
+ })), Ar = (e, t, n) => {
662
+ let r = kr(n);
663
663
  if (typeof n.update == "function") return {
664
664
  ...n.update(t),
665
665
  ...r
@@ -669,21 +669,21 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
669
669
  ...Object.fromEntries(i.filter((t) => t in e).map((t) => [t, e[t]])),
670
670
  ...r
671
671
  };
672
- }, Mr = (e) => typeof e == "string" ? [["id", e]] : Object.entries(e).map(([e, t]) => [e, t]), Nr = (e) => {
672
+ }, jr = (e) => typeof e == "string" ? [["id", e]] : Object.entries(e).map(([e, t]) => [e, t]), Mr = (e) => {
673
673
  if (typeof e == "string") return e;
674
674
  let t = Object.entries(e);
675
675
  return t.length === 1 ? String(t[0][1]) : t.slice().sort(([e], [t]) => e < t ? -1 : +(e > t)).map(([e, t]) => `${e}=${String(t)}`).join("\0");
676
- }, Pr = (e) => typeof e != "string", Fr = (e, t, n) => {
677
- let r = new Set(Mr(e).map(([e]) => e)), i = t.split(".")[0];
676
+ }, Nr = (e) => typeof e != "string", Pr = (e, t, n) => {
677
+ let r = new Set(jr(e).map(([e]) => e)), i = t.split(".")[0];
678
678
  return Object.fromEntries(Object.entries(n ?? {}).filter(([e, t]) => {
679
679
  if (t === void 0) return !1;
680
680
  if (r.has(e) || e === i) throw Error(`patchJson: additionalPatch cannot rewrite the primary key or patched JSON column '${e}'`);
681
681
  return !0;
682
682
  }));
683
- }, Ir = (e) => typeof e == "object" && !!e && !Array.isArray(e), Lr = (e) => JSON.parse(JSON.stringify(e ?? null)), Rr = (e, t, n) => {
684
- let [r, ...i] = t.split("."), a = Lr(n), o = e[r], s = (e, t) => {
683
+ }, Fr = (e) => typeof e == "object" && !!e && !Array.isArray(e), Ir = (e) => JSON.parse(JSON.stringify(e ?? null)), Lr = (e, t, n) => {
684
+ let [r, ...i] = t.split("."), a = Ir(n), o = e[r], s = (e, t) => {
685
685
  if (t === i.length) return a;
686
- let n = Ir(e) ? e : {}, r = i[t], o = Object.hasOwn(n, r) ? n[r] : void 0;
686
+ let n = Fr(e) ? e : {}, r = i[t], o = Object.hasOwn(n, r) ? n[r] : void 0;
687
687
  return {
688
688
  ...n,
689
689
  [r]: s(o, t + 1)
@@ -691,14 +691,14 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
691
691
  };
692
692
  return {
693
693
  ...e,
694
- [r]: i.length === 0 ? Ir(o) && Ir(a) ? {
694
+ [r]: i.length === 0 ? Fr(o) && Fr(a) ? {
695
695
  ...o,
696
696
  ...a
697
697
  } : a : s(o, 0)
698
698
  };
699
- }, zr = (e, t, n, r, i) => {
700
- let [a, ...o] = n.split("."), s = i ?? e`${e(a)}`, c = Lr(r), l = (e) => /["\\\u0000-\u001f]/.test(e);
701
- if ((t === "sqlite" || t === "turso") && (o.some(l) || o.length === 0 && Ir(c) && Object.keys(c).some(l))) {
699
+ }, Rr = (e, t, n, r, i) => {
700
+ let [a, ...o] = n.split("."), s = i ?? e`${e(a)}`, c = Ir(r), l = (e) => /["\\\u0000-\u001f]/.test(e);
701
+ if ((t === "sqlite" || t === "turso") && (o.some(l) || o.length === 0 && Fr(c) && Object.keys(c).some(l))) {
702
702
  let t = 0, n = (t) => e`CASE WHEN (SELECT _voltro_json_escape_probe.key FROM json_each(${String.raw`{"\u0061":0}`}) AS _voltro_json_escape_probe) = ${String.raw`\u0061`}
703
703
  THEN json_extract('"' || replace(${t}.key, '"', ${String.raw`\"`}) || '"', '$')
704
704
  ELSE ${t}.key END`, r = (r) => {
@@ -740,7 +740,7 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
740
740
  return t === "mysql" || t === "mariadb" ? e`JSON_SET(${n}, ${o}, JSON_EXTRACT(${i}, '$'))` : t === "mssql" ? a === null ? e`JSON_MODIFY(JSON_MODIFY(${n}, ${o}, 0), ${`strict ${o}`}, NULL)` : typeof a == "boolean" ? e`JSON_MODIFY(${n}, ${o}, CAST(${+!!a} AS bit))` : typeof a == "string" || typeof a == "number" ? e`JSON_MODIFY(${n}, ${o}, ${a})` : e`JSON_MODIFY(${n}, ${o}, JSON_QUERY(${i}))` : e`json_set(${n}, ${o}, json(${i}))`;
741
741
  }, v;
742
742
  if (o.length === 0) {
743
- if (!Ir(c)) v = g(c);
743
+ if (!Fr(c)) v = g(c);
744
744
  else {
745
745
  v = h([]);
746
746
  for (let [e, t] of Object.entries(c)) v = _(v, [e], g(t), t);
@@ -754,17 +754,17 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
754
754
  v = _(v, o, g(c), c);
755
755
  }
756
756
  return e`${e(a)} = ${v}`;
757
- }, Br = class extends Error {
757
+ }, zr = class extends Error {
758
758
  _tag = "EagerCardinalityError";
759
759
  constructor(e) {
760
760
  super(e), this.name = "EagerCardinalityError";
761
761
  }
762
- }, Vr = (e) => {
762
+ }, Br = (e) => {
763
763
  let { relationName: t, sourceTableName: n, targetTableName: r, foreignKey: i, sourceKey: a } = e, o = r === n;
764
764
  return `relation '${t}' on '${n}' is declared \`one\`, but ${r}.${i} matches MORE than one row for the same ${n}.${a} — so there is no single related row to return.` + (o ? ` Because this relation is self-referential, check which side the key is on: \`foreignKey: '${i}'\` means "rows whose ${i} points AT me" (my children — there can be many). If you meant "the row my ${i} points to" (my parent), that is \`sourceKey: '${i}'\`.` : " Use `many(...)` if several are expected, or narrow the key.");
765
- }, Hr = async (e, t, n, r) => {
765
+ }, Vr = async (e, t, n, r) => {
766
766
  if (e.length === 0) return e;
767
- let i = cr(n.tableName);
767
+ let i = sr(n.tableName);
768
768
  if (i === void 0) throw Error(`cannot eager-load on '${n.tableName}': no relations registered. Did you forget to declare \`relations(${n.tableName}, ...)\` or import the file that does?`);
769
769
  let a = e.map((e) => ({ ...e }));
770
770
  for (let [e, o] of Object.entries(t)) {
@@ -773,36 +773,36 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
773
773
  let t = Object.keys(i).join(", ") || "<none>";
774
774
  throw Error(`unknown relation '${e}' on '${n.tableName}'. Registered relations: ${t}.`);
775
775
  }
776
- rr(n, e, t), await Ur(a, e, t, o === !0 ? {} : o, n, r);
776
+ nr(n, e, t), await Hr(a, e, t, o === !0 ? {} : o, n, r);
777
777
  }
778
778
  return a;
779
- }, Ur = async (e, t, n, r, i, a) => {
779
+ }, Hr = async (e, t, n, r, i, a) => {
780
780
  switch (n.kind) {
781
781
  case "one":
782
- await Wr(e, t, n, r, i, a);
782
+ await Ur(e, t, n, r, i, a);
783
783
  return;
784
784
  case "many":
785
- await Gr(e, t, n, r, i, a);
785
+ await Wr(e, t, n, r, i, a);
786
786
  return;
787
787
  case "manyToMany":
788
- await qr(e, t, n, r, i, a);
788
+ await Kr(e, t, n, r, i, a);
789
789
  return;
790
790
  }
791
- }, Wr = async (e, t, n, r, i, a) => {
792
- let o = n.target(), s = n.sourceKey ?? Jr(i, o.tableName);
791
+ }, Ur = async (e, t, n, r, i, a) => {
792
+ let o = n.target(), s = n.sourceKey ?? qr(i, o.tableName);
793
793
  if (s !== void 0) {
794
- let n = Yr(e, s), i = n.length === 0 ? [] : await Xr(o, "id", n, r, a), c = new Map(i.map((e) => [e.id, e]));
794
+ let n = Jr(e, s), i = n.length === 0 ? [] : await Yr(o, "id", n, r, a), c = new Map(i.map((e) => [e.id, e]));
795
795
  for (let n of e) {
796
796
  let e = n[s];
797
797
  n[t] = e == null ? null : c.get(e) ?? null;
798
798
  }
799
- await Zr(i, r.with, o, a);
799
+ await Xr(i, r.with, o, a);
800
800
  return;
801
801
  }
802
- let c = n.foreignKey ?? $n(o, i.tableName, t), l = n.sourceKey ?? "id", u = Yr(e, l), d = u.length === 0 ? [] : await Xr(o, c, u, r, a), f = /* @__PURE__ */ new Map();
802
+ let c = n.foreignKey ?? Qn(o, i.tableName, t), l = n.sourceKey ?? "id", u = Jr(e, l), d = u.length === 0 ? [] : await Yr(o, c, u, r, a), f = /* @__PURE__ */ new Map();
803
803
  for (let e of d) {
804
804
  let n = e[c];
805
- if (f.has(n)) throw new Br(Vr({
805
+ if (f.has(n)) throw new zr(Br({
806
806
  relationName: t,
807
807
  sourceTableName: i.tableName,
808
808
  targetTableName: o.tableName,
@@ -815,9 +815,9 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
815
815
  let e = n[l];
816
816
  n[t] = e == null ? null : f.get(e) ?? null;
817
817
  }
818
- await Zr(d, r.with, o, a);
819
- }, Gr = async (e, t, n, r, i, a) => {
820
- let o = n.target(), s = n.foreignKey ?? $n(o, i.tableName, t), c = n.sourceKey ?? "id", l = Yr(e, c), u = Kr(r), d = l.length === 0 ? [] : await Xr(o, s, l, u, a), f = /* @__PURE__ */ new Map();
818
+ await Xr(d, r.with, o, a);
819
+ }, Wr = async (e, t, n, r, i, a) => {
820
+ let o = n.target(), s = n.foreignKey ?? Qn(o, i.tableName, t), c = n.sourceKey ?? "id", l = Jr(e, c), u = Gr(r), d = l.length === 0 ? [] : await Yr(o, s, l, u, a), f = /* @__PURE__ */ new Map();
821
821
  for (let e of d) {
822
822
  let t = e[s], n = f.get(t);
823
823
  n ? n.push(e) : f.set(t, [e]);
@@ -833,12 +833,12 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
833
833
  let e = n[c];
834
834
  n[t] = f.get(e) ?? [];
835
835
  }
836
- await Zr(d, r.with, o, a);
837
- }, Kr = (e) => {
836
+ await Xr(d, r.with, o, a);
837
+ }, Gr = (e) => {
838
838
  let { limit: t, offset: n, ...r } = e;
839
839
  return r;
840
- }, qr = async (e, t, n, r, i, a) => {
841
- let o = n.target(), s = n.through(), c = Yr(e, "id");
840
+ }, Kr = async (e, t, n, r, i, a) => {
841
+ let o = n.target(), s = n.through(), c = Jr(e, "id");
842
842
  if (c.length === 0) {
843
843
  for (let n of e) n[t] = [];
844
844
  return;
@@ -859,8 +859,8 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
859
859
  for (let n of e) n[t] = [];
860
860
  return;
861
861
  }
862
- let f = await Xr(o, "id", Yr(d, n.targetKey), r, a), p = new Map(f.map((e) => [e.id, e]));
863
- await Zr(f, r.with, o, a);
862
+ let f = await Yr(o, "id", Jr(d, n.targetKey), r, a), p = new Map(f.map((e) => [e.id, e]));
863
+ await Xr(f, r.with, o, a);
864
864
  let m = r.junction === void 0 ? void 0 : r.junction === !0 ? Object.keys(s.fields) : r.junction, h = /* @__PURE__ */ new Map();
865
865
  for (let e of d) {
866
866
  let t = e[n.sourceKey], r = e[n.targetKey], i = p.get(r);
@@ -872,16 +872,16 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
872
872
  o ? o.push(a) : h.set(t, [a]);
873
873
  }
874
874
  for (let n of e) n[t] = h.get(n.id) ?? [];
875
- }, Jr = (e, t) => {
875
+ }, qr = (e, t) => {
876
876
  for (let [n, r] of Object.entries(e.fields)) if (r.type === "reference" && r.references?.()?.tableName === t) return n;
877
- }, Yr = (e, t) => {
877
+ }, Jr = (e, t) => {
878
878
  let n = /* @__PURE__ */ new Set();
879
879
  for (let r of e) {
880
880
  let e = r[t];
881
881
  e != null && n.add(e);
882
882
  }
883
883
  return [...n];
884
- }, Xr = (e, t, n, r, i) => {
884
+ }, Yr = (e, t, n, r, i) => {
885
885
  let a = {
886
886
  column: t,
887
887
  op: "in",
@@ -895,63 +895,63 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
895
895
  skip: r.offset,
896
896
  projection: void 0
897
897
  });
898
- }, Zr = async (e, t, n, r) => {
899
- t !== void 0 && e.length !== 0 && (await Hr(e, t, n, r)).forEach((t, n) => {
898
+ }, Xr = async (e, t, n, r) => {
899
+ t !== void 0 && e.length !== 0 && (await Vr(e, t, n, r)).forEach((t, n) => {
900
900
  let r = e[n];
901
901
  for (let [e, n] of Object.entries(t)) e in r || (r[e] = n);
902
902
  });
903
- }, Qr = (e) => e.eager !== void 0 && Object.keys(e.eager).length > 0, $r = class extends Error {
903
+ }, Zr = (e) => e.eager !== void 0 && Object.keys(e.eager).length > 0, Qr = class extends Error {
904
904
  _tag = "TenantNamespaceUnresolved";
905
905
  constructor(e) {
906
906
  super(e), this.name = "TenantNamespaceUnresolved";
907
907
  }
908
- }, ei = class extends Error {
908
+ }, $r = class extends Error {
909
909
  _tag = "TenantNamespaceInvalid";
910
910
  constructor(e) {
911
911
  super(e), this.name = "TenantNamespaceInvalid";
912
912
  }
913
- }, ti = 63, ni = "tenant_", ri = (e) => e.toLowerCase().replace(/[^a-z0-9_]/g, "_"), ii = (e) => {
914
- if (e == null || e === "") throw new $r("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.");
915
- let t = ri(e);
916
- if (t.replace(/_/g, "") === "") throw new ei(`tenant id '${e}' has no usable identifier characters after sanitisation — cannot derive a distinct namespace.`);
917
- let n = `${ni}${t}`;
918
- if (n.length > ti) throw new ei(`namespace '${n}' for tenant '${e}' exceeds the ${ti}-byte identifier limit. Use a shorter tenant id.`);
913
+ }, ei = 63, ti = "tenant_", ni = (e) => e.toLowerCase().replace(/[^a-z0-9_]/g, "_"), ri = (e) => {
914
+ if (e == null || e === "") throw new Qr("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.");
915
+ let t = ni(e);
916
+ if (t.replace(/_/g, "") === "") throw new $r(`tenant id '${e}' has no usable identifier characters after sanitisation — cannot derive a distinct namespace.`);
917
+ let n = `${ti}${t}`;
918
+ if (n.length > ei) throw new $r(`namespace '${n}' for tenant '${e}' exceeds the ${ei}-byte identifier limit. Use a shorter tenant id.`);
919
919
  return n;
920
- }, ai = (e, t) => e === null ? t : `${e}.${t}`, oi = /* @__PURE__ */ new Set(["timestamp", "date"]), si = /^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2})?/, ci = (e, t) => {
921
- if (e === void 0 || t == null || !oi.has(e) || t instanceof Date) return t;
920
+ }, ii = (e, t) => e === null ? t : `${e}.${t}`, ai = /* @__PURE__ */ new Set(["timestamp", "date"]), oi = /^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2})?/, si = (e, t) => {
921
+ if (e === void 0 || t == null || !ai.has(e) || t instanceof Date) return t;
922
922
  if (typeof t == "number" && Number.isFinite(t)) return new Date(t);
923
- if (typeof t == "string" && si.test(t)) {
923
+ if (typeof t == "string" && oi.test(t)) {
924
924
  let e = new Date(t);
925
925
  return Number.isNaN(e.getTime()) ? t : e;
926
926
  }
927
927
  return t;
928
- }, li = (e, t) => e === void 0 || !oi.has(e) ? t : t.map((t) => ci(e, t)), ui = (e, t) => {
928
+ }, ci = (e, t) => e === void 0 || !ai.has(e) ? t : t.map((t) => si(e, t)), li = (e, t) => {
929
929
  let { strings: n, values: r } = e, i = t.unsafe(n[0] ?? "");
930
930
  for (let e = 0; e < r.length; e++) i = t`${i}${r[e]}${t.unsafe(n[e + 1] ?? "")}`;
931
931
  return t`${i}`;
932
- }, di = (e) => e.replace(/[\\%_]/g, (e) => `\\${e}`), L = (e, t, n = null, r) => {
933
- if ("not" in e) return t`NOT (${L(e.not, t, n, r)})`;
934
- if ("and" in e) return e.and.length === 0 ? t`TRUE` : t.and(e.and.map((e) => L(e, t, n, r)));
935
- if ("or" in e) return e.or.length === 0 ? t`FALSE` : t.or(e.or.map((e) => L(e, t, n, r)));
932
+ }, ui = (e) => e.replace(/[\\%_]/g, (e) => `\\${e}`), R = (e, t, n = null, r) => {
933
+ if ("not" in e) return t`NOT (${R(e.not, t, n, r)})`;
934
+ if ("and" in e) return e.and.length === 0 ? t`TRUE` : t.and(e.and.map((e) => R(e, t, n, r)));
935
+ if ("or" in e) return e.or.length === 0 ? t`FALSE` : t.or(e.or.map((e) => R(e, t, n, r)));
936
936
  if (e.op === "subquery-in" || e.op === "subquery-not-in") {
937
- let r = e, i = Si(r.subquery, t, n);
937
+ let r = e, i = xi(r.subquery, t, n);
938
938
  return r.op === "subquery-in" ? t`${t(r.column)} IN (${i})` : t`${t(r.column)} NOT IN (${i})`;
939
939
  }
940
940
  if (e.op === "exists" || e.op === "not-exists") {
941
- let r = e, i = Si(r.subquery, t, n);
941
+ let r = e, i = xi(r.subquery, t, n);
942
942
  return r.op === "exists" ? t`EXISTS (${i})` : t`NOT EXISTS (${i})`;
943
943
  }
944
944
  let i = e, a = t(i.column), o = i.path, s = o !== void 0 && o.length > 0, c = () => t.onDialectOrElse({
945
- mysql: () => t.unsafe(O(i.column, o, "mysql")),
946
- mssql: () => t.unsafe(O(i.column, o, "mssql")),
947
- sqlite: () => t.unsafe(O(i.column, o, "sqlite")),
948
- orElse: () => t.unsafe(O(i.column, o, "postgres"))
945
+ mysql: () => t.unsafe(k(i.column, o, "mysql")),
946
+ mssql: () => t.unsafe(k(i.column, o, "mssql")),
947
+ sqlite: () => t.unsafe(k(i.column, o, "sqlite")),
948
+ orElse: () => t.unsafe(k(i.column, o, "postgres"))
949
949
  }), l = () => t.onDialectOrElse({
950
- mysql: () => t.unsafe(O(i.column, o, "mysql", { numeric: !0 })),
951
- mssql: () => t.unsafe(O(i.column, o, "mssql", { numeric: !0 })),
952
- sqlite: () => t.unsafe(O(i.column, o, "sqlite", { numeric: !0 })),
953
- orElse: () => t.unsafe(O(i.column, o, "postgres", { numeric: !0 }))
954
- }), u = s ? c() : a, d = s ? l() : a, f = (e) => s && e != null ? String(e) : e, p = (e) => s ? Number(e) : e, m = s || r === void 0 ? void 0 : C(r)?.fields?.[i.column]?.type, h = (e) => ci(m, e);
950
+ mysql: () => t.unsafe(k(i.column, o, "mysql", { numeric: !0 })),
951
+ mssql: () => t.unsafe(k(i.column, o, "mssql", { numeric: !0 })),
952
+ sqlite: () => t.unsafe(k(i.column, o, "sqlite", { numeric: !0 })),
953
+ orElse: () => t.unsafe(k(i.column, o, "postgres", { numeric: !0 }))
954
+ }), u = s ? c() : a, d = s ? l() : a, f = (e) => s && e != null ? String(e) : e, p = (e) => s ? Number(e) : e, m = s || r === void 0 ? void 0 : w(r)?.fields?.[i.column]?.type, h = (e) => si(m, e);
955
955
  switch (i.op) {
956
956
  case "eq": return t`${u} = ${f(h(i.value))}`;
957
957
  case "neq": return t`${u} <> ${f(h(i.value))}`;
@@ -968,7 +968,7 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
968
968
  return e.length === 0 ? t`TRUE` : t`${u} NOT IN ${t.in(s ? e.map((e) => f(e)) : e)}`;
969
969
  }
970
970
  case "contains": {
971
- let e = `%${di(typeof i.value == "string" ? i.value : String(i.value ?? ""))}%`;
971
+ let e = `%${ui(typeof i.value == "string" ? i.value : String(i.value ?? ""))}%`;
972
972
  return t.onDialectOrElse({
973
973
  mysql: () => t`LOWER(${u}) LIKE LOWER(${e})`,
974
974
  mssql: () => t`LOWER(${u}) LIKE LOWER(${e})`,
@@ -977,7 +977,7 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
977
977
  });
978
978
  }
979
979
  case "startsWith": {
980
- let e = `${di(typeof i.value == "string" ? i.value : String(i.value ?? ""))}%`;
980
+ let e = `${ui(typeof i.value == "string" ? i.value : String(i.value ?? ""))}%`;
981
981
  return t.onDialectOrElse({
982
982
  mysql: () => t`${u} LIKE ${e}`,
983
983
  orElse: () => t`${u} LIKE ${e} ESCAPE '\\'`
@@ -1025,13 +1025,13 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1025
1025
  });
1026
1026
  }
1027
1027
  }
1028
- }, fi = (e, t) => {
1028
+ }, di = (e, t) => {
1029
1029
  let n = [];
1030
1030
  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}`);
1031
- }, pi = (e, t) => t.csv(e.map((e) => {
1031
+ }, fi = (e, t) => t.csv(e.map((e) => {
1032
1032
  let n = e.column === void 0 ? t.unsafe("*") : t`${t(e.column)}`;
1033
1033
  if (e.op.startsWith("window-")) {
1034
- let r = fi(e.window ?? {}, t);
1034
+ let r = di(e.window ?? {}, t);
1035
1035
  switch (e.op) {
1036
1036
  case "window-row-number": return t`ROW_NUMBER() OVER (${r}) AS ${t(e.alias)}`;
1037
1037
  case "window-rank": return t`RANK() OVER (${r}) AS ${t(e.alias)}`;
@@ -1055,43 +1055,43 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1055
1055
  return t`${t(e.column)} AS ${t(e.alias)}`;
1056
1056
  default: throw Error(`compileAggregateProjection: unknown op '${e.op}'`);
1057
1057
  }
1058
- })), mi = (e) => `[${e.join(",")}]`, hi = (e, t) => {
1058
+ })), pi = (e) => `[${e.join(",")}]`, mi = (e, t) => {
1059
1059
  if (e.queryVector === void 0) return null;
1060
- let n = t(e.column), r = mi(e.queryVector), i = e.distance === "cosine" ? "<=>" : e.distance === "l2" ? "<->" : "<#>", a = e.distance === "cosine" ? "VEC_DISTANCE_COSINE" : "VEC_DISTANCE_EUCLIDEAN";
1060
+ let n = t(e.column), r = pi(e.queryVector), i = e.distance === "cosine" ? "<=>" : e.distance === "l2" ? "<->" : "<#>", a = e.distance === "cosine" ? "VEC_DISTANCE_COSINE" : "VEC_DISTANCE_EUCLIDEAN";
1061
1061
  return t.onDialectOrElse({
1062
1062
  mysql: () => t`${t.unsafe(a)}(${n}, ${r})`,
1063
1063
  mssql: () => t`NULL`,
1064
1064
  sqlite: () => t`NULL`,
1065
1065
  orElse: () => t`${n} ${t.unsafe(i)} ${r}::vector`
1066
1066
  });
1067
- }, gi = (e, t) => {
1067
+ }, hi = (e, t) => {
1068
1068
  let n = t.unsafe(e.useGeography ? "::geography" : "::geometry");
1069
1069
  return t`ST_Distance(${t(e.column)}${n}, ${e.geom}${n})`;
1070
- }, _i = (e, t) => t`${t(e.column)} <-> ${e.geom}::geometry`, vi = (e, t) => t`${t(`${e.indexName}_tsv`)}`, yi = (e, t) => `${t}_${e.indexName}_fts`, bi = (e, t, n) => {
1071
- let r = n.csv(e.columns.map((e) => n`${n(e)}`)), i = `%${di(e.query)}%`;
1070
+ }, gi = (e, t) => t`${t(e.column)} <-> ${e.geom}::geometry`, _i = (e, t) => t`${t(`${e.indexName}_tsv`)}`, vi = (e, t) => `${t}_${e.indexName}_fts`, yi = (e, t, n) => {
1071
+ let r = n.csv(e.columns.map((e) => n`${n(e)}`)), i = `%${ui(e.query)}%`;
1072
1072
  return n.onDialectOrElse({
1073
1073
  mysql: () => n`MATCH(${r}) AGAINST(${e.query} IN NATURAL LANGUAGE MODE)`,
1074
1074
  sqlite: () => {
1075
- let r = n(yi(e, t));
1075
+ let r = n(vi(e, t));
1076
1076
  return n`${n("id")} IN (SELECT ${n("row_id")} FROM ${r} WHERE ${r} MATCH ${e.query})`;
1077
1077
  },
1078
1078
  mssql: () => n.or(e.columns.map((e) => n`LOWER(${n(e)}) LIKE LOWER(${i}) ESCAPE '\\'`)),
1079
- orElse: () => n`${vi(e, n)} @@ plainto_tsquery(${e.config ?? "english"}, ${e.query})`
1079
+ orElse: () => n`${_i(e, n)} @@ plainto_tsquery(${e.config ?? "english"}, ${e.query})`
1080
1080
  });
1081
- }, xi = (e, t, n) => {
1082
- let r = `%${di(e.query)}%`;
1081
+ }, bi = (e, t, n) => {
1082
+ let r = `%${ui(e.query)}%`;
1083
1083
  return n.onDialectOrElse({
1084
1084
  mysql: () => n`MATCH(${n.csv(e.columns.map((e) => n`${n(e)}`))}) AGAINST(${e.query} IN NATURAL LANGUAGE MODE)`,
1085
1085
  sqlite: () => {
1086
- let r = n(yi(e, t));
1086
+ let r = n(vi(e, t));
1087
1087
  return n`COALESCE((SELECT -bm25(${r}) FROM ${r} WHERE ${r} MATCH ${e.query} AND ${r}.${n("row_id")} = ${n("id")}), 0)`;
1088
1088
  },
1089
1089
  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}`),
1090
- orElse: () => n`ts_rank(${vi(e, n)}, plainto_tsquery(${e.config ?? "english"}, ${e.query}))`
1090
+ orElse: () => n`ts_rank(${_i(e, n)}, plainto_tsquery(${e.config ?? "english"}, ${e.query}))`
1091
1091
  });
1092
- }, Si = (e, t, n = null) => {
1092
+ }, xi = (e, t, n = null) => {
1093
1093
  if (e.setOp && e.setOp.queries.length >= 2) {
1094
- 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`(${Si(e, t, n)})`).reduce((e, n, i) => i === 0 ? n : t`${e} ${t.unsafe(r)} ${n}`), a = [];
1094
+ 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`(${xi(e, t, n)})`).reduce((e, n, i) => i === 0 ? n : t`${e} ${t.unsafe(r)} ${n}`), a = [];
1095
1095
  if (b(e).length > 0 && a.push(t` ORDER BY ${t.csv(b(e).map((e) => e.direction === "desc" ? t`${t(e.column)} DESC` : t`${t(e.column)} ASC`))}`), e.take !== void 0) {
1096
1096
  if (!Number.isInteger(e.take) || e.take < 0) throw Error(`compileSelect: invalid take ${e.take}`);
1097
1097
  a.push(t` LIMIT ${t.unsafe(String(e.take))}`);
@@ -1102,7 +1102,7 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1102
1102
  }
1103
1103
  return t`${i}${a.reduce((e, n) => t`${e}${n}`, t``)}`;
1104
1104
  }
1105
- let r = e.annClause === void 0 ? null : hi(e.annClause, t);
1105
+ let r = e.annClause === void 0 ? null : mi(e.annClause, t);
1106
1106
  e.spatialClause !== void 0 && t.onDialectOrElse({
1107
1107
  mysql: () => {
1108
1108
  throw Error("@voltro/plugin-postgis: spatial distance / KNN ordering is postgres-only");
@@ -1115,7 +1115,7 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1115
1115
  },
1116
1116
  orElse: () => t``
1117
1117
  });
1118
- let i = e.spatialClause?.projectAs === void 0 ? null : gi(e.spatialClause, t), a = e.aggregations && e.aggregations.length > 0 ? pi(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 ? xi(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({
1118
+ let i = e.spatialClause?.projectAs === void 0 ? null : hi(e.spatialClause, t), a = e.aggregations && e.aggregations.length > 0 ? fi(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 ? bi(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({
1119
1119
  orElse: () => t`DISTINCT ON (${t.csv(e.distinctOn.map((e) => t`${t(e)}`))}) `,
1120
1120
  mysql: () => t`DISTINCT `,
1121
1121
  mssql: () => t`DISTINCT `,
@@ -1127,52 +1127,52 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1127
1127
  mssql: () => t``,
1128
1128
  sqlite: () => t``,
1129
1129
  orElse: () => t` FOR UPDATE`
1130
- }) : t``, g = e.alias === void 0 ? t`${t(ai(n, e.table))}${m}` : t`${t(ai(n, e.table))} AS ${t(e.alias)}${m}`, _ = (e.joins ?? []).map((e) => {
1130
+ }) : t``, g = e.alias === void 0 ? t`${t(ii(n, e.table))}${m}` : t`${t(ii(n, e.table))} AS ${t(e.alias)}${m}`, _ = (e.joins ?? []).map((e) => {
1131
1131
  let r = e.kind === "inner" ? "INNER" : "LEFT";
1132
- return t` ${t.unsafe(r)} JOIN ${t(ai(n, e.table))} AS ${t(e.alias)} ON ${L(e.on, t, n)}`;
1133
- }), v = _.length > 0 ? _.reduce((e, n) => t`${e}${n}`, g) : g, ee = c === void 0 ? null : bi(c, e.table, t), te = [e.predicate ? L(e.predicate, t, n, e.table) : null, ee].filter((e) => e !== null), y = te.length > 0 ? t` WHERE ${t.and(te)}` : t``, ne = e.groupBy && e.groupBy.length > 0 ? t` GROUP BY ${t.csv(e.groupBy.map((e) => t`${t(e)}`))}` : t``, re = e.having ? t` HAVING ${L(e.having, t, n, e.table)}` : t``, ie = e.skip !== void 0, x = [];
1134
- r !== null && x.push(t`${r} ASC`), e.spatialClause?.order !== void 0 && x.push(e.spatialClause.order === "desc" ? t`${_i(e.spatialClause, t)} DESC` : t`${_i(e.spatialClause, t)} ASC`), l !== null && c?.rank?.order === !0 && x.push(t`${l} DESC`);
1132
+ return t` ${t.unsafe(r)} JOIN ${t(ii(n, e.table))} AS ${t(e.alias)} ON ${R(e.on, t, n)}`;
1133
+ }), v = _.length > 0 ? _.reduce((e, n) => t`${e}${n}`, g) : g, ee = c === void 0 ? null : yi(c, e.table, t), te = [e.predicate ? R(e.predicate, t, n, e.table) : null, ee].filter((e) => e !== null), y = te.length > 0 ? t` WHERE ${t.and(te)}` : t``, ne = e.groupBy && e.groupBy.length > 0 ? t` GROUP BY ${t.csv(e.groupBy.map((e) => t`${t(e)}`))}` : t``, re = e.having ? t` HAVING ${R(e.having, t, n, e.table)}` : t``, ie = e.skip !== void 0, x = [];
1134
+ r !== null && x.push(t`${r} ASC`), e.spatialClause?.order !== void 0 && x.push(e.spatialClause.order === "desc" ? t`${gi(e.spatialClause, t)} DESC` : t`${gi(e.spatialClause, t)} ASC`), l !== null && c?.rank?.order === !0 && x.push(t`${l} DESC`);
1135
1135
  for (let n of b(e)) x.push(n.direction === "desc" ? t`${t(n.column)} DESC` : t`${t(n.column)} ASC`);
1136
1136
  let ae = x.length > 0 ? t` ORDER BY ${t.csv(x)}` : ie ? t.onDialectOrElse({
1137
1137
  mssql: () => t` ORDER BY (SELECT NULL)`,
1138
1138
  orElse: () => t``
1139
- }) : t``, oe = (e) => {
1139
+ }) : t``, S = (e) => {
1140
1140
  if (!Number.isFinite(e) || !Number.isInteger(e) || e < 0) throw Error(`compileSelect: expected non-negative integer take/skip, got ${e}`);
1141
1141
  return t.unsafe(String(e));
1142
- }, se = (e.ctes ?? []).map((e) => t`${t(e.name)} AS (${Si(e.descriptor, t, n)})`), ce = (e.ctes ?? []).some((e) => e.recursive === !0), le = se.length > 0 ? t`WITH ${t.unsafe(ce ? "RECURSIVE " : "")}${t.csv(se)} ` : t``;
1142
+ }, oe = (e.ctes ?? []).map((e) => t`${t(e.name)} AS (${xi(e.descriptor, t, n)})`), se = (e.ctes ?? []).some((e) => e.recursive === !0), ce = oe.length > 0 ? t`WITH ${t.unsafe(se ? "RECURSIVE " : "")}${t.csv(oe)} ` : t``;
1143
1143
  return t.onDialectOrElse({
1144
1144
  mssql: () => {
1145
- let n = e.take !== void 0 && !ie ? t`TOP ${oe(e.take)} ` : t``, r = ie ? t` OFFSET ${oe(e.skip)} ROWS FETCH NEXT ${oe(e.take ?? 2 ** 53 - 1)} ROWS ONLY` : t``;
1146
- return t`${le}SELECT ${n}${f}${d} FROM ${v}${y}${ne}${re}${ae}${r}`;
1145
+ let n = e.take !== void 0 && !ie ? t`TOP ${S(e.take)} ` : t``, r = ie ? t` OFFSET ${S(e.skip)} ROWS FETCH NEXT ${S(e.take ?? 2 ** 53 - 1)} ROWS ONLY` : t``;
1146
+ return t`${ce}SELECT ${n}${f}${d} FROM ${v}${y}${ne}${re}${ae}${r}`;
1147
1147
  },
1148
1148
  orElse: () => {
1149
- let n = e.take === void 0 ? t`` : t` LIMIT ${oe(e.take)}`, r = ie ? t` OFFSET ${oe(e.skip)}` : t``;
1150
- return t`${le}SELECT ${f}${d} FROM ${v}${y}${ne}${re}${ae}${n}${r}${h}`;
1149
+ let n = e.take === void 0 ? t`` : t` LIMIT ${S(e.take)}`, r = ie ? t` OFFSET ${S(e.skip)}` : t``;
1150
+ return t`${ce}SELECT ${f}${d} FROM ${v}${y}${ne}${re}${ae}${n}${r}${h}`;
1151
1151
  }
1152
1152
  });
1153
- }, Ci = (e, t, n) => {
1153
+ }, Si = (e, t, n) => {
1154
1154
  if (e.eager === void 0) return null;
1155
- let r = Ei(e.table, e.eager, e.sourceTable);
1155
+ let r = Ti(e.table, e.eager, e.sourceTable);
1156
1156
  if (r === null) return null;
1157
- let i = Ni(n, e, r, Mi(t, n));
1157
+ let i = Mi(n, e, r, ji(t, n));
1158
1158
  return i === null ? null : {
1159
1159
  fragment: i,
1160
- decode: Ii(r, n)
1160
+ decode: Fi(r, n)
1161
1161
  };
1162
- }, wi = (e) => e.relation.kind === "one" && e.fkSide === "target", Ti = (e) => ({
1162
+ }, Ci = (e) => e.relation.kind === "one" && e.fkSide === "target", wi = (e) => ({
1163
1163
  ...e,
1164
1164
  branch: {
1165
1165
  ...e.branch,
1166
1166
  limit: 2
1167
1167
  }
1168
- }), Ei = (e, t, n) => {
1169
- let r = n ?? Be(e), i = cr(e);
1168
+ }), Ti = (e, t, n) => {
1169
+ let r = n ?? ze(e), i = sr(e);
1170
1170
  if (i === void 0) return null;
1171
1171
  let a = [];
1172
1172
  for (let [e, n] of Object.entries(t)) {
1173
1173
  let t = i[e];
1174
1174
  if (t === void 0) return null;
1175
- let o = Di(e, t, r, n === !0 ? {} : n);
1175
+ let o = Ei(e, t, r, n === !0 ? {} : n);
1176
1176
  if (o === null) return null;
1177
1177
  a.push(o);
1178
1178
  }
@@ -1180,30 +1180,30 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1180
1180
  table: r,
1181
1181
  children: a
1182
1182
  };
1183
- }, Di = (e, t, n, r) => {
1183
+ }, Ei = (e, t, n, r) => {
1184
1184
  let i = t.target(), a = (t.kind === "manyToMany" ? void 0 : t.sourceKey) ?? "id", o, s;
1185
1185
  if (t.kind === "manyToMany") o = t.targetKey, s = "target";
1186
1186
  else if (t.kind === "one") {
1187
- let r = t.sourceKey ?? ji(n, i.tableName);
1187
+ let r = t.sourceKey ?? Ai(n, i.tableName);
1188
1188
  if (r !== void 0) o = r, s = "source";
1189
1189
  else try {
1190
- o = t.foreignKey ?? $n(i, n.tableName, e), s = "target";
1190
+ o = t.foreignKey ?? Qn(i, n.tableName, e), s = "target";
1191
1191
  } catch {
1192
1192
  return null;
1193
1193
  }
1194
1194
  } else try {
1195
- o = t.foreignKey ?? $n(i, n.tableName, e), s = "target";
1195
+ o = t.foreignKey ?? Qn(i, n.tableName, e), s = "target";
1196
1196
  } catch {
1197
1197
  return null;
1198
1198
  }
1199
1199
  let c = r.with === void 0 ? [] : (() => {
1200
- let e = cr(i.tableName);
1200
+ let e = sr(i.tableName);
1201
1201
  if (e === void 0 && Object.keys(r.with).length > 0) return null;
1202
1202
  let t = [];
1203
1203
  for (let [n, a] of Object.entries(r.with)) {
1204
1204
  let r = e?.[n];
1205
1205
  if (r === void 0) return null;
1206
- let o = Di(n, r, i, a === !0 ? {} : a);
1206
+ let o = Ei(n, r, i, a === !0 ? {} : a);
1207
1207
  if (o === null) return null;
1208
1208
  t.push(o);
1209
1209
  }
@@ -1219,9 +1219,9 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1219
1219
  fkSide: s,
1220
1220
  branch: r,
1221
1221
  children: c,
1222
- junction: Oi(t, r)
1222
+ junction: Di(t, r)
1223
1223
  };
1224
- }, Oi = (e, t) => {
1224
+ }, Di = (e, t) => {
1225
1225
  if (e.kind !== "manyToMany" || t.junction === void 0) return;
1226
1226
  let n = e.through(), r = t.junction === !0 ? Object.keys(n.fields) : t.junction, i = r.filter((e) => e in n.fields);
1227
1227
  return {
@@ -1233,35 +1233,35 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1233
1233
  return t !== void 0 && (t.type === "timestamp" || t.type === "date");
1234
1234
  })
1235
1235
  };
1236
- }, ki = (e) => `__j_${e}`, Ai = "__j", ji = (e, t) => {
1236
+ }, Oi = (e) => `__j_${e}`, ki = "__j", Ai = (e, t) => {
1237
1237
  for (let [n, r] of Object.entries(e.fields)) if (r.type === "reference" && r.references?.()?.tableName === t) return n;
1238
- }, Mi = (e, t) => {
1238
+ }, ji = (e, t) => {
1239
1239
  let n = 0;
1240
1240
  return {
1241
1241
  sql: e,
1242
1242
  dialect: t,
1243
1243
  nextAlias: () => `__a${n++}`
1244
1244
  };
1245
- }, Ni = (e, t, n, r) => {
1245
+ }, Mi = (e, t, n, r) => {
1246
1246
  switch (e) {
1247
- case "postgres": return zi(t, n, r);
1247
+ case "postgres": return Ri(t, n, r);
1248
1248
  case "sqlite":
1249
- case "turso": return qi(t, n, r);
1249
+ case "turso": return Ki(t, n, r);
1250
1250
  case "mysql":
1251
- case "mariadb": return ra(t, n, r);
1252
- case "mssql": return ua(t, n, r);
1251
+ case "mariadb": return na(t, n, r);
1252
+ case "mssql": return la(t, n, r);
1253
1253
  }
1254
- }, Pi = (e, t) => t === "mssql" && !Fi.test(e) ? /* @__PURE__ */ new Date(`${e}Z`) : new Date(e), Fi = /(?:Z|[+-]\d{2}:?\d{2})$/, Ii = (e, t) => {
1255
- let n = Li(e.table, e.children, t);
1254
+ }, Ni = (e, t) => t === "mssql" && !Pi.test(e) ? /* @__PURE__ */ new Date(`${e}Z`) : new Date(e), Pi = /(?:Z|[+-]\d{2}:?\d{2})$/, Fi = (e, t) => {
1255
+ let n = Ii(e.table, e.children, t);
1256
1256
  return (e) => e.map((e) => {
1257
1257
  let t = e.__row, r = typeof t == "string" ? JSON.parse(t) : t;
1258
1258
  return n(r);
1259
1259
  });
1260
- }, Li = (e, t, n) => {
1260
+ }, Ii = (e, t, n) => {
1261
1261
  let r = [];
1262
1262
  for (let [t, n] of Object.entries(e.fields)) (n.type === "timestamp" || n.type === "date") && r.push(t);
1263
1263
  let i = t.map((e) => {
1264
- let t = Li(e.target, e.children, n), r = e.relation.kind === "one", i = wi(e), a = i ? Vr({
1264
+ let t = Ii(e.target, e.children, n), r = e.relation.kind === "one", i = Ci(e), a = i ? Br({
1265
1265
  relationName: e.relationName,
1266
1266
  sourceTableName: e.source.tableName,
1267
1267
  targetTableName: e.target.tableName,
@@ -1274,14 +1274,14 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1274
1274
  isSingle: r,
1275
1275
  fromOverFetch: i,
1276
1276
  cardinalityMessage: a,
1277
- junction: Ri(e.junction, n)
1277
+ junction: Li(e.junction, n)
1278
1278
  };
1279
1279
  });
1280
1280
  return (e) => {
1281
1281
  let t = { ...e };
1282
1282
  for (let e of r) {
1283
1283
  let r = t[e];
1284
- typeof r == "string" && (t[e] = Pi(r, n));
1284
+ typeof r == "string" && (t[e] = Ni(r, n));
1285
1285
  }
1286
1286
  for (let e of i) {
1287
1287
  let n = t[e.name];
@@ -1291,7 +1291,7 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1291
1291
  }
1292
1292
  if (e.fromOverFetch) {
1293
1293
  let r = n;
1294
- if (r.length > 1) throw new Br(e.cardinalityMessage);
1294
+ if (r.length > 1) throw new zr(e.cardinalityMessage);
1295
1295
  t[e.name] = r.length === 0 ? null : e.decode(r[0]);
1296
1296
  continue;
1297
1297
  }
@@ -1303,204 +1303,204 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1303
1303
  }
1304
1304
  return t;
1305
1305
  };
1306
- }, Ri = (e, t) => {
1306
+ }, Li = (e, t) => {
1307
1307
  if (e === void 0) return;
1308
1308
  let n = new Set(e.dateColumns), r = e.requested;
1309
1309
  return (e) => {
1310
1310
  let i = e._junction ?? {}, a = {};
1311
1311
  for (let e of r) {
1312
1312
  let r = i[e];
1313
- a[e] = n.has(e) && typeof r == "string" ? Pi(r, t) : r;
1313
+ a[e] = n.has(e) && typeof r == "string" ? Ni(r, t) : r;
1314
1314
  }
1315
1315
  return {
1316
1316
  ...e,
1317
1317
  _junction: a
1318
1318
  };
1319
1319
  };
1320
- }, zi = (e, t, n) => {
1321
- let r = n.sql, i = n.nextAlias(), a = r(t.table.tableName), o = r(i), s = Bi(i, t.children, n);
1322
- return s === null ? null : r`SELECT ${s} AS "__row" FROM ${a} AS ${o}${e.predicate ? r` WHERE ${U(e.predicate, i, r)}` : r``}${b(e).length > 0 ? r` ORDER BY ${r.csv(b(e).map((e) => e.direction === "desc" ? r`${B(i, e.column, r)} DESC` : r`${B(i, e.column, r)} ASC`))}` : r``}${e.take === void 0 ? r`` : r` LIMIT ${H(e.take, r)}`}${e.skip === void 0 ? r`` : r` OFFSET ${H(e.skip, r)}`}`;
1323
- }, Bi = (e, t, n, r) => {
1324
- let i = n.sql, a = r === void 0 ? i`to_jsonb(${i(e)}.*)` : i`(to_jsonb(${i(e)}.*) - ${V(Ai, i)}::text)`;
1320
+ }, Ri = (e, t, n) => {
1321
+ let r = n.sql, i = n.nextAlias(), a = r(t.table.tableName), o = r(i), s = zi(i, t.children, n);
1322
+ return s === null ? null : r`SELECT ${s} AS "__row" FROM ${a} AS ${o}${e.predicate ? r` WHERE ${W(e.predicate, i, r)}` : r``}${b(e).length > 0 ? r` ORDER BY ${r.csv(b(e).map((e) => e.direction === "desc" ? r`${V(i, e.column, r)} DESC` : r`${V(i, e.column, r)} ASC`))}` : r``}${e.take === void 0 ? r`` : r` LIMIT ${U(e.take, r)}`}${e.skip === void 0 ? r`` : r` OFFSET ${U(e.skip, r)}`}`;
1323
+ }, zi = (e, t, n, r) => {
1324
+ let i = n.sql, a = r === void 0 ? i`to_jsonb(${i(e)}.*)` : i`(to_jsonb(${i(e)}.*) - ${H(ki, i)}::text)`;
1325
1325
  if (t.length === 0 && r === void 0) return a;
1326
1326
  let o = [];
1327
- r !== void 0 && o.push(i`${V("_junction", i)}, ${B(e, Ai, i)}`);
1327
+ r !== void 0 && o.push(i`${H("_junction", i)}, ${V(e, ki, i)}`);
1328
1328
  for (let r of t) {
1329
- let t = Vi(r, e, n);
1329
+ let t = Bi(r, e, n);
1330
1330
  if (t === null) return null;
1331
- o.push(i`${V(r.relationName, i)}, ${t}`);
1331
+ o.push(i`${H(r.relationName, i)}, ${t}`);
1332
1332
  }
1333
1333
  return i`${a} || jsonb_build_object(${i.csv(o)})`;
1334
- }, Vi = (e, t, n) => {
1334
+ }, Bi = (e, t, n) => {
1335
1335
  switch (e.relation.kind) {
1336
- case "one": return wi(e) ? Ui(Ti(e), t, n) : Hi(e, t, n);
1337
- case "many": return Ui(e, t, n);
1338
- case "manyToMany": return Wi(e, t, n);
1336
+ case "one": return Ci(e) ? Hi(wi(e), t, n) : Vi(e, t, n);
1337
+ case "many": return Hi(e, t, n);
1338
+ case "manyToMany": return Ui(e, t, n);
1339
1339
  }
1340
- }, Hi = (e, t, n) => {
1341
- let r = n.sql, i = n.nextAlias(), a = Bi(i, e.children, n);
1340
+ }, Vi = (e, t, n) => {
1341
+ let r = n.sql, i = n.nextAlias(), a = zi(i, e.children, n);
1342
1342
  if (a === null) return null;
1343
- let o = e.fkSide === "source" ? r`${B(i, "id", r)} = ${B(t, e.foreignKey, r)}` : r`${B(i, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${U(e.branch.where, i, r)}`, c = R(i, e.branch.orderBy, r);
1343
+ let o = e.fkSide === "source" ? r`${V(i, "id", r)} = ${V(t, e.foreignKey, r)}` : r`${V(i, e.foreignKey, r)} = ${V(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${W(e.branch.where, i, r)}`, c = z(i, e.branch.orderBy, r);
1344
1344
  return r`(SELECT ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o}${s}${c} LIMIT 1)`;
1345
- }, Ui = (e, t, n) => {
1346
- let r = n.sql, i = n.nextAlias(), a = Bi(i, e.children, n);
1345
+ }, Hi = (e, t, n) => {
1346
+ let r = n.sql, i = n.nextAlias(), a = zi(i, e.children, n);
1347
1347
  if (a === null) return null;
1348
- let o = r`${B(void 0, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${L(e.branch.where, r)}`, c = Ki(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`;
1348
+ let o = r`${V(void 0, e.foreignKey, r)} = ${V(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${R(e.branch.where, r)}`, c = Gi(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${U(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${U(e.branch.offset, r)}`;
1349
1349
  return r`COALESCE((SELECT jsonb_agg(${a}) FROM (SELECT * FROM ${r(e.target.tableName)} WHERE ${o}${s}${c}${l}${u}) AS ${r(i)}), '[]'::jsonb)`;
1350
- }, Wi = (e, t, n) => {
1351
- let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = Bi(o, e.children, n, e.junction);
1350
+ }, Ui = (e, t, n) => {
1351
+ let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = zi(o, e.children, n, e.junction);
1352
1352
  if (c === null) return null;
1353
- let l = e.branch.where === void 0 ? r`` : r` AND ${L(e.branch.where, r)}`, u = va(e, s, r), d = R(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : r`, ${Gi(e.junction, s, r)} AS ${r(Ai)}`;
1354
- return r`COALESCE((SELECT jsonb_agg(${c}) FROM (SELECT ${r(o)}.*${m} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${B(o, "id", r)} = ${B(s, i.targetKey, r)} WHERE ${B(s, i.sourceKey, r)} = ${B(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), '[]'::jsonb)`;
1355
- }, Gi = (e, t, n) => e.present.length === 0 ? n`jsonb_build_object()` : n`jsonb_build_object(${n.csv(e.present.map((e) => n`${V(e, n)}, ${B(t, e, n)}`))})`, R = (e, t, n) => t === void 0 || t.length === 0 ? n`` : n` ORDER BY ${n.csv(t.map((t) => t.direction === "desc" ? n`${B(e, t.column, n)} DESC` : n`${B(e, t.column, n)} ASC`))}`, Ki = (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`))}`, qi = (e, t, n) => {
1356
- let r = n.sql, i = n.nextAlias(), a = Ji(i, t.table, t.children, n);
1353
+ let l = e.branch.where === void 0 ? r`` : r` AND ${R(e.branch.where, r)}`, u = _a(e, s, r), d = z(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${U(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${U(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : r`, ${Wi(e.junction, s, r)} AS ${r(ki)}`;
1354
+ 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 ${V(o, "id", r)} = ${V(s, i.targetKey, r)} WHERE ${V(s, i.sourceKey, r)} = ${V(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), '[]'::jsonb)`;
1355
+ }, Wi = (e, t, n) => e.present.length === 0 ? n`jsonb_build_object()` : n`jsonb_build_object(${n.csv(e.present.map((e) => n`${H(e, n)}, ${V(t, e, n)}`))})`, z = (e, t, n) => t === void 0 || t.length === 0 ? n`` : n` ORDER BY ${n.csv(t.map((t) => t.direction === "desc" ? n`${V(e, t.column, n)} DESC` : n`${V(e, t.column, n)} ASC`))}`, Gi = (e, t) => e === void 0 || e.length === 0 ? t`` : t` ORDER BY ${t.csv(e.map((e) => e.direction === "desc" ? t`${t(e.column)} DESC` : t`${t(e.column)} ASC`))}`, Ki = (e, t, n) => {
1356
+ let r = n.sql, i = n.nextAlias(), a = qi(i, t.table, t.children, n);
1357
1357
  if (a === null) return null;
1358
- let o = e.predicate ? r` WHERE ${U(e.predicate, i, r)}` : r``, s = b(e).length > 0 ? r` ORDER BY ${r.csv(b(e).map((e) => e.direction === "desc" ? r`${B(i, e.column, r)} DESC` : r`${B(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${H(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${H(e.skip, r)}`;
1358
+ let o = e.predicate ? r` WHERE ${W(e.predicate, i, r)}` : r``, s = b(e).length > 0 ? r` ORDER BY ${r.csv(b(e).map((e) => e.direction === "desc" ? r`${V(i, e.column, r)} DESC` : r`${V(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${U(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${U(e.skip, r)}`;
1359
1359
  return r`SELECT ${a} AS "__row" FROM ${r(t.table.tableName)} AS ${r(i)}${o}${s}${c}${l}`;
1360
- }, Ji = (e, t, n, r, i) => {
1360
+ }, qi = (e, t, n, r, i) => {
1361
1361
  let a = r.sql, o = [];
1362
- for (let n of Object.keys(t.fields)) o.push(a`${V(n, a)}, ${B(e, n, a)}`);
1362
+ for (let n of Object.keys(t.fields)) o.push(a`${H(n, a)}, ${V(e, n, a)}`);
1363
1363
  if (i !== void 0) {
1364
- let e = Yi(i.projection, i.source, a);
1365
- o.push(a`${V("_junction", a)}, json_object(${e})`);
1364
+ let e = Ji(i.projection, i.source, a);
1365
+ o.push(a`${H("_junction", a)}, json_object(${e})`);
1366
1366
  }
1367
1367
  for (let t of n) {
1368
- let n = $i(t, e, r);
1368
+ let n = Qi(t, e, r);
1369
1369
  if (n === null) return null;
1370
- o.push(a`${V(t.relationName, a)}, ${n}`);
1370
+ o.push(a`${H(t.relationName, a)}, ${n}`);
1371
1371
  }
1372
1372
  return a`json_object(${a.csv(o)})`;
1373
- }, Yi = (e, t, n) => e.present.length === 0 ? n`` : n.csv(e.present.map((e) => n`${V(e, n)}, ${B(t.alias, t.physical(e), n)}`)), Xi = (e, t, n) => e.present.length === 0 ? n`` : n`, ${n.csv(e.present.map((e) => n`${B(t, e, n)} AS ${n(ki(e))}`))}`, Zi = (e) => ({
1373
+ }, Ji = (e, t, n) => e.present.length === 0 ? n`` : n.csv(e.present.map((e) => n`${H(e, n)}, ${V(t.alias, t.physical(e), n)}`)), Yi = (e, t, n) => e.present.length === 0 ? n`` : n`, ${n.csv(e.present.map((e) => n`${V(t, e, n)} AS ${n(Oi(e))}`))}`, Xi = (e) => ({
1374
1374
  alias: e,
1375
- physical: ki
1376
- }), Qi = (e) => ({
1375
+ physical: Oi
1376
+ }), Zi = (e) => ({
1377
1377
  alias: e,
1378
1378
  physical: (e) => e
1379
- }), $i = (e, t, n) => {
1379
+ }), Qi = (e, t, n) => {
1380
1380
  switch (e.relation.kind) {
1381
- case "one": return wi(e) ? ta(Ti(e), t, n) : ea(e, t, n);
1382
- case "many": return ta(e, t, n);
1383
- case "manyToMany": return na(e, t, n);
1381
+ case "one": return Ci(e) ? ea(wi(e), t, n) : $i(e, t, n);
1382
+ case "many": return ea(e, t, n);
1383
+ case "manyToMany": return ta(e, t, n);
1384
1384
  }
1385
- }, ea = (e, t, n) => {
1386
- let r = n.sql, i = n.nextAlias(), a = Ji(i, e.target, e.children, n);
1385
+ }, $i = (e, t, n) => {
1386
+ let r = n.sql, i = n.nextAlias(), a = qi(i, e.target, e.children, n);
1387
1387
  if (a === null) return null;
1388
- let o = e.fkSide === "source" ? r`${B(i, "id", r)} = ${B(t, e.foreignKey, r)}` : r`${B(i, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`;
1388
+ let o = e.fkSide === "source" ? r`${V(i, "id", r)} = ${V(t, e.foreignKey, r)}` : r`${V(i, e.foreignKey, r)} = ${V(t, e.sourceKey, r)}`;
1389
1389
  return r`(SELECT ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o} LIMIT 1)`;
1390
- }, ta = (e, t, n) => {
1391
- let r = n.sql, i = n.nextAlias(), a = Ji(i, e.target, e.children, n);
1390
+ }, ea = (e, t, n) => {
1391
+ let r = n.sql, i = n.nextAlias(), a = qi(i, e.target, e.children, n);
1392
1392
  if (a === null) return null;
1393
- let o = r`${B(void 0, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${L(W(e.branch.where), r)}`, c = Ki(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`;
1393
+ let o = r`${V(void 0, e.foreignKey, r)} = ${V(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${R(G(e.branch.where), r)}`, c = Gi(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${U(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${U(e.branch.offset, r)}`;
1394
1394
  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('[]'))`;
1395
- }, na = (e, t, n) => {
1396
- let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = Ji(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1395
+ }, ta = (e, t, n) => {
1396
+ let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = qi(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1397
1397
  projection: e.junction,
1398
- source: Zi(o)
1398
+ source: Xi(o)
1399
1399
  });
1400
1400
  if (c === null) return null;
1401
- let l = e.branch.where === void 0 ? r`` : r` AND ${L(W(e.branch.where), r)}`, u = va(e, s, r, !0), d = R(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : Xi(e.junction, s, r);
1402
- return r`COALESCE((SELECT json_group_array(${c}) FROM (SELECT ${r(o)}.*${m} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${B(o, "id", r)} = ${B(s, i.targetKey, r)} WHERE ${B(s, i.sourceKey, r)} = ${B(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), json('[]'))`;
1403
- }, ra = (e, t, n) => {
1404
- let r = n.sql, i = n.nextAlias(), a = z(i, t.table, t.children, n);
1401
+ let l = e.branch.where === void 0 ? r`` : r` AND ${R(G(e.branch.where), r)}`, u = _a(e, s, r, !0), d = z(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${U(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${U(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : Yi(e.junction, s, r);
1402
+ 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 ${V(o, "id", r)} = ${V(s, i.targetKey, r)} WHERE ${V(s, i.sourceKey, r)} = ${V(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), json('[]'))`;
1403
+ }, na = (e, t, n) => {
1404
+ let r = n.sql, i = n.nextAlias(), a = B(i, t.table, t.children, n);
1405
1405
  if (a === null) return null;
1406
- let o = e.predicate ? r` WHERE ${U(e.predicate, i, r)}` : r``, s = b(e).length > 0 ? r` ORDER BY ${r.csv(b(e).map((e) => e.direction === "desc" ? r`${B(i, e.column, r)} DESC` : r`${B(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${H(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${H(e.skip, r)}`;
1406
+ let o = e.predicate ? r` WHERE ${W(e.predicate, i, r)}` : r``, s = b(e).length > 0 ? r` ORDER BY ${r.csv(b(e).map((e) => e.direction === "desc" ? r`${V(i, e.column, r)} DESC` : r`${V(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${U(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${U(e.skip, r)}`;
1407
1407
  return r`SELECT ${a} AS \`__row\` FROM ${r(t.table.tableName)} AS ${r(i)}${o}${s}${c}${l}`;
1408
- }, z = (e, t, n, r, i) => {
1408
+ }, B = (e, t, n, r, i) => {
1409
1409
  let a = r.sql, o = [];
1410
- for (let n of Object.keys(t.fields)) o.push(a`${V(n, a)}, ${B(e, n, a)}`);
1410
+ for (let n of Object.keys(t.fields)) o.push(a`${H(n, a)}, ${V(e, n, a)}`);
1411
1411
  if (i !== void 0) {
1412
- let e = Yi(i.projection, i.source, a);
1413
- o.push(a`${V("_junction", a)}, JSON_OBJECT(${e})`);
1412
+ let e = Ji(i.projection, i.source, a);
1413
+ o.push(a`${H("_junction", a)}, JSON_OBJECT(${e})`);
1414
1414
  }
1415
1415
  for (let t of n) {
1416
- let n = ia(t, e, r);
1416
+ let n = ra(t, e, r);
1417
1417
  if (n === null) return null;
1418
- o.push(a`${V(t.relationName, a)}, ${n}`);
1418
+ o.push(a`${H(t.relationName, a)}, ${n}`);
1419
1419
  }
1420
1420
  return a`JSON_OBJECT(${a.csv(o)})`;
1421
- }, ia = (e, t, n) => {
1421
+ }, ra = (e, t, n) => {
1422
1422
  switch (e.relation.kind) {
1423
1423
  case "one":
1424
- if (wi(e)) {
1425
- let r = Ti(e);
1426
- return n.dialect === "mariadb" ? ca(r, t, n) : oa(r, t, n);
1424
+ if (Ci(e)) {
1425
+ let r = wi(e);
1426
+ return n.dialect === "mariadb" ? sa(r, t, n) : aa(r, t, n);
1427
1427
  }
1428
- return aa(e, t, n);
1429
- case "many": return n.dialect === "mariadb" ? ca(e, t, n) : oa(e, t, n);
1430
- case "manyToMany": return n.dialect === "mariadb" ? la(e, t, n) : sa(e, t, n);
1428
+ return ia(e, t, n);
1429
+ case "many": return n.dialect === "mariadb" ? sa(e, t, n) : aa(e, t, n);
1430
+ case "manyToMany": return n.dialect === "mariadb" ? ca(e, t, n) : oa(e, t, n);
1431
1431
  }
1432
- }, aa = (e, t, n) => {
1433
- let r = n.sql, i = n.nextAlias(), a = z(i, e.target, e.children, n);
1432
+ }, ia = (e, t, n) => {
1433
+ let r = n.sql, i = n.nextAlias(), a = B(i, e.target, e.children, n);
1434
1434
  if (a === null) return null;
1435
- let o = e.fkSide === "source" ? r`${B(i, "id", r)} = ${B(t, e.foreignKey, r)}` : r`${B(i, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`;
1435
+ let o = e.fkSide === "source" ? r`${V(i, "id", r)} = ${V(t, e.foreignKey, r)}` : r`${V(i, e.foreignKey, r)} = ${V(t, e.sourceKey, r)}`;
1436
1436
  return r`(SELECT ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o} LIMIT 1)`;
1437
- }, oa = (e, t, n) => {
1438
- let r = n.sql, i = n.nextAlias(), a = z(i, e.target, e.children, n);
1437
+ }, aa = (e, t, n) => {
1438
+ let r = n.sql, i = n.nextAlias(), a = B(i, e.target, e.children, n);
1439
1439
  if (a === null) return null;
1440
- let o = r`${B(void 0, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${L(W(e.branch.where), r)}`, c = Ki(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`;
1440
+ let o = r`${V(void 0, e.foreignKey, r)} = ${V(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${R(G(e.branch.where), r)}`, c = Gi(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${U(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${U(e.branch.offset, r)}`;
1441
1441
  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())`;
1442
- }, sa = (e, t, n) => {
1443
- let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = z(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1442
+ }, oa = (e, t, n) => {
1443
+ let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = B(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1444
1444
  projection: e.junction,
1445
- source: Zi(o)
1445
+ source: Xi(o)
1446
1446
  });
1447
1447
  if (c === null) return null;
1448
- let l = e.branch.where === void 0 ? r`` : r` AND ${L(W(e.branch.where), r)}`, u = va(e, s, r, !0), d = R(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : Xi(e.junction, s, r);
1449
- return r`COALESCE((SELECT JSON_ARRAYAGG(${c}) FROM (SELECT ${r(o)}.*${m} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${B(o, "id", r)} = ${B(s, i.targetKey, r)} WHERE ${B(s, i.sourceKey, r)} = ${B(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), JSON_ARRAY())`;
1450
- }, ca = (e, t, n) => {
1451
- let r = n.sql, i = n.nextAlias(), a = z(i, e.target, e.children, n);
1448
+ let l = e.branch.where === void 0 ? r`` : r` AND ${R(G(e.branch.where), r)}`, u = _a(e, s, r, !0), d = z(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${U(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${U(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : Yi(e.junction, s, r);
1449
+ 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 ${V(o, "id", r)} = ${V(s, i.targetKey, r)} WHERE ${V(s, i.sourceKey, r)} = ${V(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), JSON_ARRAY())`;
1450
+ }, sa = (e, t, n) => {
1451
+ let r = n.sql, i = n.nextAlias(), a = B(i, e.target, e.children, n);
1452
1452
  if (a === null) return null;
1453
- let o = r`${B(i, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${L(W(e.branch.where), r)}`, c = e.branch.orderBy ?? [];
1454
- if (e.branch.limit === void 0 && e.branch.offset === void 0) return r`COALESCE((SELECT JSON_ARRAYAGG(${a}${c.length > 0 ? r` ORDER BY ${r.csv(c.map((e) => e.direction === "desc" ? r`${B(i, e.column, r)} DESC` : r`${B(i, e.column, r)} ASC`))}` : r``}) FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o}${s}), JSON_ARRAY())`;
1455
- let l = c.length > 0 ? r` ORDER BY ${r.csv(c.map((e) => e.direction === "desc" ? r`${r(e.column)} DESC` : r`${r(e.column)} ASC`))}` : r` ORDER BY ${r("id")}`, u = e.branch.limit, d = e.branch.offset, f = u !== void 0 && d !== void 0 ? r` AND ${B(i, "rn", r)} > ${H(d, r)} AND ${B(i, "rn", r)} <= ${H(d + u, r)}` : u === void 0 ? r` AND ${B(i, "rn", r)} > ${H(d, r)}` : r` AND ${B(i, "rn", r)} <= ${H(u, r)}`;
1456
- return r`COALESCE((SELECT JSON_ARRAYAGG(${a} ORDER BY ${B(i, "rn", r)}) FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY ${r(e.foreignKey)}${l}) AS rn FROM ${r(e.target.tableName)}) AS ${r(i)} WHERE ${o}${s}${f}), JSON_ARRAY())`;
1457
- }, la = (e, t, n) => {
1453
+ let o = r`${V(i, e.foreignKey, r)} = ${V(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${R(G(e.branch.where), r)}`, c = e.branch.orderBy ?? [];
1454
+ 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`${V(i, e.column, r)} DESC` : r`${V(i, e.column, r)} ASC`))}` : r``}) FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o}${s}), JSON_ARRAY())`;
1455
+ 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 ${V(i, "rn", r)} > ${U(d, r)} AND ${V(i, "rn", r)} <= ${U(d + u, r)}` : u === void 0 ? r` AND ${V(i, "rn", r)} > ${U(d, r)}` : r` AND ${V(i, "rn", r)} <= ${U(u, r)}`;
1456
+ return r`COALESCE((SELECT JSON_ARRAYAGG(${a} ORDER BY ${V(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())`;
1457
+ }, ca = (e, t, n) => {
1458
1458
  let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = (t) => e.junction === void 0 ? void 0 : {
1459
1459
  projection: e.junction,
1460
1460
  source: t
1461
- }, l = r`${B(s, i.sourceKey, r)} = ${B(t, "id", r)}`, u = r`${B(o, "id", r)} = ${B(s, i.targetKey, r)}`, d = e.branch.where === void 0 ? r`` : r` AND ${L(W(e.branch.where), r)}`, f = va(e, s, r, !0), p = e.branch.orderBy ?? [];
1461
+ }, l = r`${V(s, i.sourceKey, r)} = ${V(t, "id", r)}`, u = r`${V(o, "id", r)} = ${V(s, i.targetKey, r)}`, d = e.branch.where === void 0 ? r`` : r` AND ${R(G(e.branch.where), r)}`, f = _a(e, s, r, !0), p = e.branch.orderBy ?? [];
1462
1462
  if (e.branch.limit === void 0 && e.branch.offset === void 0) {
1463
- let t = z(o, e.target, e.children, n, c(Qi(s)));
1464
- return t === null ? null : r`COALESCE((SELECT JSON_ARRAYAGG(${t}${p.length > 0 ? r` ORDER BY ${r.csv(p.map((e) => e.direction === "desc" ? r`${B(o, e.column, r)} DESC` : r`${B(o, e.column, r)} ASC`))}` : r``}) FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${u} WHERE ${l}${f}${d}), JSON_ARRAY())`;
1463
+ let t = B(o, e.target, e.children, n, c(Zi(s)));
1464
+ 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`${V(o, e.column, r)} DESC` : r`${V(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())`;
1465
1465
  }
1466
- let m = p.length > 0 ? r` ORDER BY ${r.csv(p.map((e) => e.direction === "desc" ? r`${B(o, e.column, r)} DESC` : r`${B(o, e.column, r)} ASC`))}` : r` ORDER BY ${B(o, "id", r)}`, h = e.branch.limit, g = e.branch.offset, _ = h !== void 0 && g !== void 0 ? r` AND ${B(o, "rn", r)} > ${H(g, r)} AND ${B(o, "rn", r)} <= ${H(g + h, r)}` : h === void 0 ? r` AND ${B(o, "rn", r)} > ${H(g, r)}` : r` AND ${B(o, "rn", r)} <= ${H(h, r)}`, v = e.branch.onJunction === void 0 ? r`` : r` WHERE ${U(W(e.branch.onJunction), s, r)}`, ee = z(o, e.target, e.children, n, c(Zi(o)));
1466
+ let m = p.length > 0 ? r` ORDER BY ${r.csv(p.map((e) => e.direction === "desc" ? r`${V(o, e.column, r)} DESC` : r`${V(o, e.column, r)} ASC`))}` : r` ORDER BY ${V(o, "id", r)}`, h = e.branch.limit, g = e.branch.offset, _ = h !== void 0 && g !== void 0 ? r` AND ${V(o, "rn", r)} > ${U(g, r)} AND ${V(o, "rn", r)} <= ${U(g + h, r)}` : h === void 0 ? r` AND ${V(o, "rn", r)} > ${U(g, r)}` : r` AND ${V(o, "rn", r)} <= ${U(h, r)}`, v = e.branch.onJunction === void 0 ? r`` : r` WHERE ${W(G(e.branch.onJunction), s, r)}`, ee = B(o, e.target, e.children, n, c(Xi(o)));
1467
1467
  if (ee === null) return null;
1468
- let te = e.junction === void 0 ? r`` : Xi(e.junction, s, r);
1469
- return r`COALESCE((SELECT JSON_ARRAYAGG(${ee} ORDER BY ${B(o, "rn", r)}) FROM (SELECT ${r(o)}.*${te}, ${B(s, i.sourceKey, r)} AS ${r(`__src_${i.sourceKey}`)}, ROW_NUMBER() OVER (PARTITION BY ${B(s, i.sourceKey, r)}${m}) AS rn FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${u}${v}) AS ${r(o)} WHERE ${B(o, `__src_${i.sourceKey}`, r)} = ${B(t, "id", r)}${d}${_}), JSON_ARRAY())`;
1470
- }, ua = (e, t, n) => {
1471
- let r = n.sql, i = n.nextAlias(), a = da(i, t.table, t.children, n);
1468
+ let te = e.junction === void 0 ? r`` : Yi(e.junction, s, r);
1469
+ return r`COALESCE((SELECT JSON_ARRAYAGG(${ee} ORDER BY ${V(o, "rn", r)}) FROM (SELECT ${r(o)}.*${te}, ${V(s, i.sourceKey, r)} AS ${r(`__src_${i.sourceKey}`)}, ROW_NUMBER() OVER (PARTITION BY ${V(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 ${V(o, `__src_${i.sourceKey}`, r)} = ${V(t, "id", r)}${d}${_}), JSON_ARRAY())`;
1470
+ }, la = (e, t, n) => {
1471
+ let r = n.sql, i = n.nextAlias(), a = ua(i, t.table, t.children, n);
1472
1472
  if (a === null) return null;
1473
- let o = e.predicate ? r` WHERE ${U(e.predicate, i, r)}` : r``, s = b(e).length > 0 ? r` ORDER BY ${r.csv(b(e).map((e) => e.direction === "desc" ? r`${B(i, e.column, r)} DESC` : r`${B(i, e.column, r)} ASC`))}` : r``, c = r``, l = r``;
1473
+ let o = e.predicate ? r` WHERE ${W(e.predicate, i, r)}` : r``, s = b(e).length > 0 ? r` ORDER BY ${r.csv(b(e).map((e) => e.direction === "desc" ? r`${V(i, e.column, r)} DESC` : r`${V(i, e.column, r)} ASC`))}` : r``, c = r``, l = r``;
1474
1474
  if (e.skip !== void 0) {
1475
1475
  let t = b(e).length > 0 ? s : r` ORDER BY (SELECT NULL)`;
1476
- l = e.take === void 0 ? r`${t} OFFSET ${H(e.skip, r)} ROWS` : r`${t} OFFSET ${H(e.skip, r)} ROWS FETCH NEXT ${H(e.take, r)} ROWS ONLY`;
1477
- } else e.take !== void 0 && (c = r`TOP ${H(e.take, r)} `);
1476
+ l = e.take === void 0 ? r`${t} OFFSET ${U(e.skip, r)} ROWS` : r`${t} OFFSET ${U(e.skip, r)} ROWS FETCH NEXT ${U(e.take, r)} ROWS ONLY`;
1477
+ } else e.take !== void 0 && (c = r`TOP ${U(e.take, r)} `);
1478
1478
  let u = e.skip === void 0 ? s : r``;
1479
1479
  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}`;
1480
- }, da = (e, t, n, r, i) => {
1480
+ }, ua = (e, t, n, r, i) => {
1481
1481
  let a = r.sql, o = [];
1482
- for (let n of Object.keys(t.fields)) o.push(a`${B(e, n, a)} AS ${a(n)}`);
1483
- if (i !== void 0) for (let e of i.projection.present) o.push(a`${B(i.source.alias, i.source.physical(e), a)} AS ${fa(`_junction.${e}`, a)}`);
1482
+ for (let n of Object.keys(t.fields)) o.push(a`${V(e, n, a)} AS ${a(n)}`);
1483
+ if (i !== void 0) for (let e of i.projection.present) o.push(a`${V(i.source.alias, i.source.physical(e), a)} AS ${da(`_junction.${e}`, a)}`);
1484
1484
  for (let t of n) {
1485
- let n = pa(t, e, r);
1485
+ let n = fa(t, e, r);
1486
1486
  if (n === null) return null;
1487
1487
  o.push(n);
1488
1488
  }
1489
1489
  return a.csv(o);
1490
- }, fa = (e, t) => t.unsafe(`[${e.replace(/]/g, "]]")}]`), pa = (e, t, n) => {
1490
+ }, da = (e, t) => t.unsafe(`[${e.replace(/]/g, "]]")}]`), fa = (e, t, n) => {
1491
1491
  switch (e.relation.kind) {
1492
- case "one": return wi(e) ? ga(Ti(e), t, n) : ma(e, t, n);
1493
- case "many": return ga(e, t, n);
1494
- case "manyToMany": return _a(e, t, n);
1492
+ case "one": return Ci(e) ? ha(wi(e), t, n) : pa(e, t, n);
1493
+ case "many": return ha(e, t, n);
1494
+ case "manyToMany": return ga(e, t, n);
1495
1495
  }
1496
- }, ma = (e, t, n) => {
1497
- let r = n.sql, i = n.nextAlias(), a = da(i, e.target, e.children, n);
1496
+ }, pa = (e, t, n) => {
1497
+ let r = n.sql, i = n.nextAlias(), a = ua(i, e.target, e.children, n);
1498
1498
  if (a === null) return null;
1499
- let o = e.fkSide === "source" ? r`${B(i, "id", r)} = ${B(t, e.foreignKey, r)}` : r`${B(i, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`;
1499
+ let o = e.fkSide === "source" ? r`${V(i, "id", r)} = ${V(t, e.foreignKey, r)}` : r`${V(i, e.foreignKey, r)} = ${V(t, e.sourceKey, r)}`;
1500
1500
  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)}`;
1501
- }, ha = (e, t, n) => {
1501
+ }, ma = (e, t, n) => {
1502
1502
  if (e.offset !== void 0) {
1503
- let r = e.orderBy && e.orderBy.length > 0 ? t : n` ORDER BY (SELECT NULL)`, i = e.limit === void 0 ? n`${r} OFFSET ${H(e.offset, n)} ROWS` : n`${r} OFFSET ${H(e.offset, n)} ROWS FETCH NEXT ${H(e.limit, n)} ROWS ONLY`;
1503
+ let r = e.orderBy && e.orderBy.length > 0 ? t : n` ORDER BY (SELECT NULL)`, i = e.limit === void 0 ? n`${r} OFFSET ${U(e.offset, n)} ROWS` : n`${r} OFFSET ${U(e.offset, n)} ROWS FETCH NEXT ${U(e.limit, n)} ROWS ONLY`;
1504
1504
  return {
1505
1505
  top: n``,
1506
1506
  pagination: i,
@@ -1508,33 +1508,33 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1508
1508
  };
1509
1509
  }
1510
1510
  return {
1511
- top: e.limit === void 0 ? n`` : n`TOP ${H(e.limit, n)} `,
1511
+ top: e.limit === void 0 ? n`` : n`TOP ${U(e.limit, n)} `,
1512
1512
  pagination: n``,
1513
1513
  finalOrder: t
1514
1514
  };
1515
- }, ga = (e, t, n) => {
1516
- let r = n.sql, i = n.nextAlias(), a = da(i, e.target, e.children, n);
1515
+ }, ha = (e, t, n) => {
1516
+ let r = n.sql, i = n.nextAlias(), a = ua(i, e.target, e.children, n);
1517
1517
  if (a === null) return null;
1518
- let o = e.branch.where === void 0 ? r`` : r` AND ${U(e.branch.where, i, r)}`, s = R(i, e.branch.orderBy, r), { top: c, pagination: l, finalOrder: u } = ha(e.branch, s, r);
1519
- return r`ISNULL(JSON_QUERY((SELECT ${c}${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${B(i, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}${o}${u}${l} FOR JSON PATH, INCLUDE_NULL_VALUES)), JSON_QUERY('[]')) AS ${r(e.relationName)}`;
1520
- }, _a = (e, t, n) => {
1521
- let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = da(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1518
+ let o = e.branch.where === void 0 ? r`` : r` AND ${W(e.branch.where, i, r)}`, s = z(i, e.branch.orderBy, r), { top: c, pagination: l, finalOrder: u } = ma(e.branch, s, r);
1519
+ return r`ISNULL(JSON_QUERY((SELECT ${c}${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${V(i, e.foreignKey, r)} = ${V(t, e.sourceKey, r)}${o}${u}${l} FOR JSON PATH, INCLUDE_NULL_VALUES)), JSON_QUERY('[]')) AS ${r(e.relationName)}`;
1520
+ }, ga = (e, t, n) => {
1521
+ let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = ua(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1522
1522
  projection: e.junction,
1523
- source: Qi(s)
1523
+ source: Zi(s)
1524
1524
  });
1525
1525
  if (c === null) return null;
1526
- let l = e.branch.where === void 0 ? r`` : r` AND ${U(e.branch.where, o, r)}`, u = va(e, s, r), d = R(o, e.branch.orderBy, r), { top: f, pagination: p, finalOrder: m } = ha(e.branch, d, r);
1527
- return r`ISNULL(JSON_QUERY((SELECT ${f}${c} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${B(o, "id", r)} = ${B(s, i.targetKey, r)} WHERE ${B(s, i.sourceKey, r)} = ${B(t, "id", r)}${u}${l}${m}${p} FOR JSON PATH, INCLUDE_NULL_VALUES)), JSON_QUERY('[]')) AS ${r(e.relationName)}`;
1528
- }, B = (e, t, n) => e === void 0 ? n`${n(t)}` : n`${n(e)}.${n(t)}`, V = (e, t) => t.unsafe(`'${e.replace(/'/g, "''")}'`), H = (e, t) => {
1526
+ let l = e.branch.where === void 0 ? r`` : r` AND ${W(e.branch.where, o, r)}`, u = _a(e, s, r), d = z(o, e.branch.orderBy, r), { top: f, pagination: p, finalOrder: m } = ma(e.branch, d, r);
1527
+ 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 ${V(o, "id", r)} = ${V(s, i.targetKey, r)} WHERE ${V(s, i.sourceKey, r)} = ${V(t, "id", r)}${u}${l}${m}${p} FOR JSON PATH, INCLUDE_NULL_VALUES)), JSON_QUERY('[]')) AS ${r(e.relationName)}`;
1528
+ }, V = (e, t, n) => e === void 0 ? n`${n(t)}` : n`${n(e)}.${n(t)}`, H = (e, t) => t.unsafe(`'${e.replace(/'/g, "''")}'`), U = (e, t) => {
1529
1529
  if (!Number.isFinite(e) || !Number.isInteger(e) || e < 0) throw Error(`literalInt: expected non-negative integer, got ${e}`);
1530
1530
  return t.unsafe(String(e));
1531
- }, U = (e, t, n) => L(ya(e, t), n), va = (e, t, n, r = !1) => {
1531
+ }, W = (e, t, n) => R(va(e, t), n), _a = (e, t, n, r = !1) => {
1532
1532
  let i = e.branch.onJunction;
1533
- return i === void 0 ? n`` : n` AND ${U(r ? W(i) : i, t, n)}`;
1534
- }, ya = (e, t) => {
1535
- if ("not" in e) return { not: ya(e.not, t) };
1536
- if ("and" in e) return { and: e.and.map((e) => ya(e, t)) };
1537
- if ("or" in e) return { or: e.or.map((e) => ya(e, t)) };
1533
+ return i === void 0 ? n`` : n` AND ${W(r ? G(i) : i, t, n)}`;
1534
+ }, va = (e, t) => {
1535
+ if ("not" in e) return { not: va(e.not, t) };
1536
+ if ("and" in e) return { and: e.and.map((e) => va(e, t)) };
1537
+ if ("or" in e) return { or: e.or.map((e) => va(e, t)) };
1538
1538
  if (e.op === "subquery-in" || e.op === "subquery-not-in") {
1539
1539
  let n = e;
1540
1540
  return {
@@ -1548,99 +1548,99 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1548
1548
  ...n,
1549
1549
  column: `${t}.${n.column}`
1550
1550
  };
1551
- }, W = (e) => {
1552
- if ("not" in e) return { not: W(e.not) };
1553
- if ("and" in e) return { and: e.and.map((e) => W(e)) };
1554
- if ("or" in e) return { or: e.or.map((e) => W(e)) };
1551
+ }, G = (e) => {
1552
+ if ("not" in e) return { not: G(e.not) };
1553
+ if ("and" in e) return { and: e.and.map((e) => G(e)) };
1554
+ if ("or" in e) return { or: e.or.map((e) => G(e)) };
1555
1555
  if (e.op === "subquery-in" || e.op === "subquery-not-in" || e.op === "exists" || e.op === "not-exists") return e;
1556
1556
  let t = e;
1557
1557
  return {
1558
1558
  ...t,
1559
- value: ba(t.value)
1559
+ value: ya(t.value)
1560
1560
  };
1561
- }, ba = (e) => e == null ? e : e instanceof Date ? e.toISOString() : typeof e == "boolean" ? +!!e : Array.isArray(e) ? e.map((e) => ba(e)) : e, xa = Symbol.for("@voltro/database/coreTablesRegistry"), Sa = globalThis, Ca = Sa[xa] ?? (Sa[xa] = {}), wa = (e) => {
1562
- e.actors !== void 0 && (Ca.actors = e.actors), e.tenants !== void 0 && (Ca.tenants = e.tenants);
1563
- }, Ta = (e, t) => () => {
1561
+ }, ya = (e) => e == null ? e : e instanceof Date ? e.toISOString() : typeof e == "boolean" ? +!!e : Array.isArray(e) ? e.map((e) => ya(e)) : e, ba = Symbol.for("@voltro/database/coreTablesRegistry"), xa = globalThis, Sa = xa[ba] ?? (xa[ba] = {}), Ca = (e) => {
1562
+ e.actors !== void 0 && (Sa.actors = e.actors), e.tenants !== void 0 && (Sa.tenants = e.tenants);
1563
+ }, wa = (e, t) => () => {
1564
1564
  let n = e();
1565
1565
  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`);
1566
1566
  return n();
1567
- }, Ea = () => Ta(() => Ca.actors, "actors"), Da = () => Ta(() => Ca.tenants, "tenants"), Oa = T("actors", {
1568
- id: D(),
1569
- kind: w().oneOf([
1567
+ }, Ta = () => wa(() => Sa.actors, "actors"), Ea = () => wa(() => Sa.tenants, "tenants"), Da = E("actors", {
1568
+ id: O(),
1569
+ kind: T().oneOf([
1570
1570
  "user",
1571
1571
  "serviceAccount",
1572
1572
  "apiKey",
1573
1573
  "system"
1574
1574
  ]),
1575
- displayName: w().nullable(),
1576
- createdAt: E().default("now")
1577
- }), ka = (e, t) => ({
1575
+ displayName: T().nullable(),
1576
+ createdAt: D().default("now")
1577
+ }), Oa = (e, t) => ({
1578
1578
  column: e,
1579
1579
  op: "eq",
1580
1580
  value: t
1581
- }), Aa = (e, t) => ({
1581
+ }), ka = (e, t) => ({
1582
1582
  column: e,
1583
1583
  op: "neq",
1584
1584
  value: t
1585
- }), ja = (e, t) => ({
1585
+ }), Aa = (e, t) => ({
1586
1586
  column: e,
1587
1587
  op: "gt",
1588
1588
  value: t
1589
- }), Ma = (e, t) => ({
1589
+ }), ja = (e, t) => ({
1590
1590
  column: e,
1591
1591
  op: "gte",
1592
1592
  value: t
1593
- }), Na = (e, t) => ({
1593
+ }), Ma = (e, t) => ({
1594
1594
  column: e,
1595
1595
  op: "lt",
1596
1596
  value: t
1597
- }), Pa = (e, t) => ({
1597
+ }), Na = (e, t) => ({
1598
1598
  column: e,
1599
1599
  op: "lte",
1600
1600
  value: t
1601
- }), Fa = (e, t) => ({
1601
+ }), Pa = (e, t) => ({
1602
1602
  column: e,
1603
1603
  op: "in",
1604
1604
  value: t
1605
- }), Ia = (e, t) => ({
1605
+ }), Fa = (e, t) => ({
1606
1606
  column: e,
1607
1607
  op: "notIn",
1608
1608
  value: t
1609
- }), La = (e, t) => ({
1609
+ }), Ia = (e, t) => ({
1610
1610
  column: e,
1611
1611
  op: "contains",
1612
1612
  value: t
1613
- }), Ra = (e, t) => ({
1613
+ }), La = (e, t) => ({
1614
1614
  column: e,
1615
1615
  op: "startsWith",
1616
1616
  value: t
1617
- }), za = (e, t) => ({
1617
+ }), Ra = (e, t) => ({
1618
1618
  column: e,
1619
1619
  op: "arrayContains",
1620
1620
  value: t
1621
- }), Ba = (e, t) => ({
1621
+ }), za = (e, t) => ({
1622
1622
  column: e,
1623
1623
  op: "arrayOverlaps",
1624
1624
  value: t
1625
- }), Va = (e, t) => ({
1625
+ }), Ba = (e, t) => ({
1626
1626
  column: e,
1627
1627
  op: "arrayHas",
1628
1628
  value: t
1629
- }), Ha = {
1629
+ }), Va = {
1630
1630
  column: "id",
1631
1631
  op: "in",
1632
1632
  value: []
1633
- }, Ua = (e) => ({
1633
+ }, Ha = (e) => ({
1634
1634
  column: e,
1635
1635
  op: "isNull"
1636
- }), Wa = (e) => ({
1636
+ }), Ua = (e) => ({
1637
1637
  column: e,
1638
1638
  op: "isNotNull"
1639
- }), Ga = (e, t) => ({
1639
+ }), Wa = (e, t) => ({
1640
1640
  column: e,
1641
1641
  op: "spatial",
1642
1642
  value: t
1643
- }), Ka = (...e) => ({ and: e }), qa = (...e) => ({ or: e }), Ja = (e) => ({ not: e }), Ya = (e, ...t) => {
1643
+ }), Ga = (...e) => ({ and: e }), Ka = (...e) => ({ or: e }), qa = (e) => ({ not: e }), Ja = (e, ...t) => {
1644
1644
  if (t.length === 0) throw Error(`jsonField("${e}"): at least one path segment is required`);
1645
1645
  let n = (n, r) => ({
1646
1646
  column: e,
@@ -1662,33 +1662,33 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1662
1662
  isNull: () => n("isNull"),
1663
1663
  isNotNull: () => n("isNotNull")
1664
1664
  };
1665
- }, Xa = (e) => "descriptor" in e ? e.descriptor : e, Za = (e, t) => ({
1665
+ }, Ya = (e) => "descriptor" in e ? e.descriptor : e, Xa = (e, t) => ({
1666
1666
  column: e,
1667
1667
  op: "subquery-in",
1668
- subquery: Xa(t)
1669
- }), Qa = (e, t) => ({
1668
+ subquery: Ya(t)
1669
+ }), Za = (e, t) => ({
1670
1670
  column: e,
1671
1671
  op: "subquery-not-in",
1672
- subquery: Xa(t)
1673
- }), $a = (e) => ({
1672
+ subquery: Ya(t)
1673
+ }), Qa = (e) => ({
1674
1674
  op: "exists",
1675
- subquery: Xa(e)
1676
- }), eo = (e) => ({
1675
+ subquery: Ya(e)
1676
+ }), $a = (e) => ({
1677
1677
  op: "not-exists",
1678
- subquery: Xa(e)
1679
- }), to = (e, t) => e === t || e instanceof Date && t instanceof Date && e.getTime() === t.getTime(), no = (e, t) => {
1678
+ subquery: Ya(e)
1679
+ }), eo = (e, t) => e === t || e instanceof Date && t instanceof Date && e.getTime() === t.getTime(), to = (e, t) => {
1680
1680
  if (e == null || t == null) return null;
1681
1681
  let n = e instanceof Date ? e.getTime() : e, r = t instanceof Date ? t.getTime() : t;
1682
1682
  return typeof n == typeof r ? n === r ? 0 : n > r ? 1 : -1 : null;
1683
- }, ro = (e, t, n = null) => {
1683
+ }, no = (e, t, n = null) => {
1684
1684
  if (!t) return !1;
1685
- if ("not" in e) return !ro(e.not, t, n);
1685
+ if ("not" in e) return !no(e.not, t, n);
1686
1686
  if ("and" in e) {
1687
- for (let r of e.and) if (!ro(r, t, n)) return !1;
1687
+ for (let r of e.and) if (!no(r, t, n)) return !1;
1688
1688
  return !0;
1689
1689
  }
1690
1690
  if ("or" in e) {
1691
- for (let r of e.or) if (ro(r, t, n)) return !0;
1691
+ for (let r of e.or) if (no(r, t, n)) return !0;
1692
1692
  return !1;
1693
1693
  }
1694
1694
  if (e.op === "subquery-in" || e.op === "subquery-not-in") {
@@ -1705,14 +1705,14 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1705
1705
  }
1706
1706
  let r = e, i = t[r.column];
1707
1707
  switch (r.op) {
1708
- case "eq": return to(i, r.value);
1709
- case "neq": return !to(i, r.value);
1710
- case "gt": return (no(i, r.value) ?? -1) > 0;
1711
- case "gte": return (no(i, r.value) ?? -1) >= 0;
1712
- case "lt": return (no(i, r.value) ?? 1) < 0;
1713
- case "lte": return (no(i, r.value) ?? 1) <= 0;
1714
- case "in": return Array.isArray(r.value) && r.value.some((e) => to(i, e));
1715
- case "notIn": return Array.isArray(r.value) && !r.value.some((e) => to(i, e));
1708
+ case "eq": return eo(i, r.value);
1709
+ case "neq": return !eo(i, r.value);
1710
+ case "gt": return (to(i, r.value) ?? -1) > 0;
1711
+ case "gte": return (to(i, r.value) ?? -1) >= 0;
1712
+ case "lt": return (to(i, r.value) ?? 1) < 0;
1713
+ case "lte": return (to(i, r.value) ?? 1) <= 0;
1714
+ case "in": return Array.isArray(r.value) && r.value.some((e) => eo(i, e));
1715
+ case "notIn": return Array.isArray(r.value) && !r.value.some((e) => eo(i, e));
1716
1716
  case "contains": return typeof i == "string" && typeof r.value == "string" && i.toLowerCase().includes(r.value.toLowerCase());
1717
1717
  case "startsWith": return typeof i == "string" && typeof r.value == "string" && i.startsWith(r.value);
1718
1718
  case "arrayContains": {
@@ -1728,17 +1728,17 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1728
1728
  case "isNotNull": return i != null;
1729
1729
  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.");
1730
1730
  }
1731
- }, io = function* (e) {
1731
+ }, ro = function* (e) {
1732
1732
  if ("not" in e) {
1733
- yield* io(e.not);
1733
+ yield* ro(e.not);
1734
1734
  return;
1735
1735
  }
1736
1736
  if ("and" in e) {
1737
- for (let t of e.and) yield* io(t);
1737
+ for (let t of e.and) yield* ro(t);
1738
1738
  return;
1739
1739
  }
1740
1740
  if ("or" in e) {
1741
- for (let t of e.or) yield* io(t);
1741
+ for (let t of e.or) yield* ro(t);
1742
1742
  return;
1743
1743
  }
1744
1744
  e.op === "subquery-in" || e.op === "subquery-not-in" ? yield {
@@ -1748,46 +1748,46 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1748
1748
  kind: "exists",
1749
1749
  descriptor: e.subquery
1750
1750
  });
1751
- }, ao = function* (e, t = !0) {
1751
+ }, io = function* (e, t = !0) {
1752
1752
  if ("not" in e) {
1753
- yield* ao(e.not, !1);
1753
+ yield* io(e.not, !1);
1754
1754
  return;
1755
1755
  }
1756
1756
  if ("and" in e) {
1757
- for (let n of e.and) yield* ao(n, t);
1757
+ for (let n of e.and) yield* io(n, t);
1758
1758
  return;
1759
1759
  }
1760
1760
  if ("or" in e) {
1761
- for (let t of e.or) yield* ao(t, !1);
1761
+ for (let t of e.or) yield* io(t, !1);
1762
1762
  return;
1763
1763
  }
1764
1764
  e.op !== "subquery-in" && e.op !== "subquery-not-in" && e.op !== "exists" && e.op !== "not-exists" && (yield {
1765
1765
  ...e,
1766
1766
  conjunctive: t
1767
1767
  });
1768
- }, oo = (e, t) => ({
1768
+ }, ao = (e, t) => ({
1769
1769
  ...t,
1770
1770
  ...e,
1771
1771
  origin: e.origin ?? "injected"
1772
- }), so = (e, t, n = {}) => ({
1772
+ }), oo = (e, t, n = {}) => ({
1773
1773
  table: e,
1774
1774
  op: "insert",
1775
1775
  old: null,
1776
1776
  new: t,
1777
1777
  ...n
1778
- }), co = (e, t, n, r = {}) => ({
1778
+ }), so = (e, t, n, r = {}) => ({
1779
1779
  table: e,
1780
1780
  op: "update",
1781
1781
  old: t,
1782
1782
  new: n,
1783
1783
  ...r
1784
- }), lo = (e, t, n = {}) => ({
1784
+ }), co = (e, t, n = {}) => ({
1785
1785
  table: e,
1786
1786
  op: "delete",
1787
1787
  old: t,
1788
1788
  new: null,
1789
1789
  ...n
1790
- }), uo = (e, t, n = {}) => {
1790
+ }), lo = (e, t, n = {}) => {
1791
1791
  let { at: r = "2026-01-01T00:00:00.000Z", column: i = "deletedAt", ...a } = n;
1792
1792
  return {
1793
1793
  table: e,
@@ -1802,13 +1802,13 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1802
1802
  },
1803
1803
  ...a
1804
1804
  };
1805
- }, fo = (e) => e == null ? "null" : e instanceof Date ? JSON.stringify(e.toISOString()) : typeof e == "bigint" ? JSON.stringify(e.toString()) : Array.isArray(e) ? `[${e.map(fo).join(",")}]` : typeof e == "object" ? `{${Object.entries(e).filter(([, e]) => e !== void 0).sort(([e], [t]) => e < t ? -1 : +(e > t)).map(([e, t]) => `${JSON.stringify(e)}:${fo(t)}`).join(",")}}` : JSON.stringify(e) ?? "null", po = (e) => qt("sha256").update([
1805
+ }, uo = (e) => e == null ? "null" : e instanceof Date ? JSON.stringify(e.toISOString()) : typeof e == "bigint" ? JSON.stringify(e.toString()) : Array.isArray(e) ? `[${e.map(uo).join(",")}]` : typeof e == "object" ? `{${Object.entries(e).filter(([, e]) => e !== void 0).sort(([e], [t]) => e < t ? -1 : +(e > t)).map(([e, t]) => `${JSON.stringify(e)}:${uo(t)}`).join(",")}}` : JSON.stringify(e) ?? "null", fo = (e) => Kt("sha256").update([
1806
1806
  e.pipe,
1807
1807
  e.op,
1808
1808
  e.key,
1809
- fo(e.next),
1810
- fo(e.prev)
1811
- ].join("\0")).digest("hex").slice(0, 32), mo = (e, t) => `${e}:${t}`, ho = (e) => {
1809
+ uo(e.next),
1810
+ uo(e.prev)
1811
+ ].join("\0")).digest("hex").slice(0, 32), po = (e, t) => `${e}:${t}`, mo = (e) => {
1812
1812
  let t = e.lastIndexOf(":");
1813
1813
  if (t <= 0) return null;
1814
1814
  let n = Number(e.slice(t + 1));
@@ -1816,7 +1816,7 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1816
1816
  digest: e.slice(0, t),
1817
1817
  occurrence: n
1818
1818
  };
1819
- }, go = class {
1819
+ }, ho = class {
1820
1820
  #e = /* @__PURE__ */ new Map();
1821
1821
  #t;
1822
1822
  #n;
@@ -1838,7 +1838,7 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1838
1838
  }
1839
1839
  seedFromChangeKeys(e, t) {
1840
1840
  for (let n of e) {
1841
- let e = ho(n);
1841
+ let e = mo(n);
1842
1842
  if (e === null) continue;
1843
1843
  let r = this.#e.get(e.digest), i = Math.max(r?.count ?? 0, e.occurrence + 1);
1844
1844
  this.#e.set(e.digest, {
@@ -1859,70 +1859,70 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1859
1859
  this.#e.delete(e.value);
1860
1860
  }
1861
1861
  }
1862
- }, _o = "VOLTRO_CHANGE_CLAIMS_TTL_HOURS", vo = 1, yo = (e = process.env) => {
1863
- let t = Number(e[_o]);
1862
+ }, go = "VOLTRO_CHANGE_CLAIMS_TTL_HOURS", _o = 1, vo = (e = process.env) => {
1863
+ let t = Number(e[go]);
1864
1864
  return (Number.isFinite(t) && t > 0 ? t : 1) * 2 * 36e5;
1865
- }, bo = new Jt(), xo = (e, t) => bo.run(e, t), So = () => bo.getStore(), Co = (e) => {
1866
- let t = e ?? bo.getStore();
1865
+ }, yo = new qt(), bo = (e, t) => yo.run(e, t), xo = () => yo.getStore(), So = (e) => {
1866
+ let t = e ?? yo.getStore();
1867
1867
  return t === void 0 ? {} : {
1868
1868
  ...t.traceId === void 0 ? {} : { traceId: t.traceId },
1869
1869
  ...t.subjectId === void 0 ? {} : { subjectId: t.subjectId },
1870
1870
  ...t.procedure === void 0 ? {} : { procedure: t.procedure },
1871
1871
  ...t.via === void 0 ? {} : { via: t.via }
1872
1872
  };
1873
- }, wo = (e) => {
1874
- let t = bo.getStore();
1875
- return t === void 0 ? e(void 0) : bo.run(t, () => e(t));
1876
- }, To = 3e4, Eo = 1e4, G = /* @__PURE__ */ new Map(), K = 0, Do = (e, t, n) => `${e}\u0000${t}\u0000${String(n)}`, Oo = (e) => {
1877
- for (let [t, n] of G) {
1878
- let r = n.filter((t) => e - t.at < To);
1879
- K -= n.length - r.length, r.length === 0 ? G.delete(t) : r.length !== n.length && G.set(t, r);
1880
- }
1881
- }, ko = (e, t) => {
1873
+ }, Co = (e) => {
1874
+ let t = yo.getStore();
1875
+ return t === void 0 ? e(void 0) : yo.run(t, () => e(t));
1876
+ }, wo = 3e4, To = 1e4, K = /* @__PURE__ */ new Map(), q = 0, Eo = (e, t, n) => `${e}\u0000${t}\u0000${String(n)}`, Do = (e) => {
1877
+ for (let [t, n] of K) {
1878
+ let r = n.filter((t) => e - t.at < wo);
1879
+ q -= n.length - r.length, r.length === 0 ? K.delete(t) : r.length !== n.length && K.set(t, r);
1880
+ }
1881
+ }, Oo = (e, t) => {
1882
1882
  if (t.traceId === void 0 && t.subjectId === void 0 && t.procedure === void 0) return;
1883
1883
  let n = Date.now();
1884
- if (K >= Eo && Oo(n), K >= Eo) return;
1885
- let r = G.get(e);
1886
- r === void 0 ? G.set(e, [{
1884
+ if (q >= To && Do(n), q >= To) return;
1885
+ let r = K.get(e);
1886
+ r === void 0 ? K.set(e, [{
1887
1887
  attribution: t,
1888
1888
  at: n
1889
1889
  }]) : r.push({
1890
1890
  attribution: t,
1891
1891
  at: n
1892
- }), K += 1;
1893
- }, Ao = (e) => {
1894
- let t = G.get(e);
1892
+ }), q += 1;
1893
+ }, ko = (e) => {
1894
+ let t = K.get(e);
1895
1895
  if (t === void 0 || t.length === 0) return;
1896
1896
  let n = t.shift();
1897
- if (--K, t.length === 0 && G.delete(e), !(Date.now() - n.at >= To)) return n.attribution;
1898
- }, jo = (e) => (G.get(e)?.length ?? 0) > 0, q = /* @__PURE__ */ new Map(), Mo = /* @__PURE__ */ new Map(), No = /* @__PURE__ */ new Map(), Po = 250, Fo = (e) => {
1899
- let t = Mo.get(e);
1897
+ if (--q, t.length === 0 && K.delete(e), !(Date.now() - n.at >= wo)) return n.attribution;
1898
+ }, Ao = (e) => (K.get(e)?.length ?? 0) > 0, J = /* @__PURE__ */ new Map(), jo = /* @__PURE__ */ new Map(), Mo = /* @__PURE__ */ new Map(), No = 250, Po = (e) => {
1899
+ let t = jo.get(e);
1900
1900
  if (t === void 0) return;
1901
- Mo.delete(e);
1902
- let n = No.get(e);
1903
- n !== void 0 && (clearTimeout(n), No.delete(e));
1901
+ jo.delete(e);
1902
+ let n = Mo.get(e);
1903
+ n !== void 0 && (clearTimeout(n), Mo.delete(e));
1904
1904
  for (let e of t) e();
1905
+ }, Fo = (e) => {
1906
+ J.set(e, (J.get(e) ?? 0) + 1);
1905
1907
  }, Io = (e) => {
1906
- q.set(e, (q.get(e) ?? 0) + 1);
1907
- }, Lo = (e) => {
1908
- let t = (q.get(e) ?? 0) - 1;
1908
+ let t = (J.get(e) ?? 0) - 1;
1909
1909
  if (t > 0) {
1910
- q.set(e, t);
1910
+ J.set(e, t);
1911
1911
  return;
1912
1912
  }
1913
- q.delete(e), Fo(e);
1914
- }, Ro = (e, t, n, r) => {
1915
- let i = n == null ? void 0 : Do(e, t, n), a = () => r(i === void 0 ? void 0 : Ao(i));
1913
+ J.delete(e), Po(e);
1914
+ }, Lo = (e, t, n, r) => {
1915
+ let i = n == null ? void 0 : Eo(e, t, n), a = () => r(i === void 0 ? void 0 : ko(i));
1916
1916
  if (i === void 0) {
1917
1917
  a();
1918
1918
  return;
1919
1919
  }
1920
- if (jo(i)) {
1920
+ if (Ao(i)) {
1921
1921
  a();
1922
1922
  return;
1923
1923
  }
1924
- let o = Mo.get(e);
1925
- if (o === void 0 && (q.get(e) ?? 0) === 0) {
1924
+ let o = jo.get(e);
1925
+ if (o === void 0 && (J.get(e) ?? 0) === 0) {
1926
1926
  a();
1927
1927
  return;
1928
1928
  }
@@ -1930,91 +1930,91 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1930
1930
  o.push(a);
1931
1931
  return;
1932
1932
  }
1933
- Mo.set(e, [a]);
1934
- let s = setTimeout(() => Fo(e), Po);
1935
- typeof s == "object" && typeof s.unref == "function" && s.unref(), No.set(e, s);
1936
- }, zo = () => {
1937
- G.clear(), K = 0, q.clear();
1938
- for (let e of No.values()) clearTimeout(e);
1939
- No.clear(), Mo.clear();
1940
- }, Bo = () => K, Vo = 64, Ho = "\0", Uo = 32, Wo = (e, ...t) => `${e}_${qt("sha256").update(t.map(String).join(Ho)).digest("hex").slice(0, Uo)}`, Go = (e) => e.length + 1 + Uo, J = /* @__PURE__ */ new Map(), Ko = (e, t) => {
1941
- J.set(e, {
1933
+ jo.set(e, [a]);
1934
+ let s = setTimeout(() => Po(e), No);
1935
+ typeof s == "object" && typeof s.unref == "function" && s.unref(), Mo.set(e, s);
1936
+ }, Ro = () => {
1937
+ K.clear(), q = 0, J.clear();
1938
+ for (let e of Mo.values()) clearTimeout(e);
1939
+ Mo.clear(), jo.clear();
1940
+ }, zo = () => q, Bo = 64, Vo = "\0", Ho = 32, Uo = (e, ...t) => `${e}_${Kt("sha256").update(t.map(String).join(Vo)).digest("hex").slice(0, Ho)}`, Wo = (e) => e.length + 1 + Ho, Y = /* @__PURE__ */ new Map(), Go = (e, t) => {
1941
+ Y.set(e, {
1942
1942
  recorder: t.recorder,
1943
1943
  tables: new Set(t.tables),
1944
1944
  ownTables: new Set(t.ownTables)
1945
1945
  });
1946
- }, qo = (e) => {
1947
- J.delete(e);
1948
- }, Jo = () => J.clear(), Yo = new Jt(), Xo = (e) => Yo.run({ n: 1 }, e), Zo = (e) => k.suspend(() => {
1949
- let t = Yo.getStore();
1950
- if (t !== void 0) return t.n += 1, k.ensuring(e, k.sync(() => {
1946
+ }, Ko = (e) => {
1947
+ Y.delete(e);
1948
+ }, qo = () => Y.clear(), Jo = new qt(), Yo = (e) => Jo.run({ n: 1 }, e), Xo = (e) => A.suspend(() => {
1949
+ let t = Jo.getStore();
1950
+ if (t !== void 0) return t.n += 1, A.ensuring(e, A.sync(() => {
1951
1951
  --t.n;
1952
1952
  }));
1953
1953
  let n = { n: 1 };
1954
- return Yo.enterWith(n), k.ensuring(e, k.sync(() => {
1954
+ return Jo.enterWith(n), A.ensuring(e, A.sync(() => {
1955
1955
  --n.n;
1956
1956
  }));
1957
- }), Qo = () => (Yo.getStore()?.n ?? 0) > 0, $o = (e) => {
1958
- if (J.size === 0 || (Yo.getStore()?.n ?? 0) > 0) return !1;
1959
- for (let t of J.values()) if (!t.ownTables.has(e) && t.tables.has(e)) return !0;
1957
+ }), Zo = () => (Jo.getStore()?.n ?? 0) > 0, Qo = (e) => {
1958
+ if (Y.size === 0 || (Jo.getStore()?.n ?? 0) > 0) return !1;
1959
+ for (let t of Y.values()) if (!t.ownTables.has(e) && t.tables.has(e)) return !0;
1960
1960
  return !1;
1961
- }, es = async (e, t) => {
1962
- if (J.size !== 0) {
1963
- for (let [n, r] of J.entries()) if (!r.ownTables.has(t.table) && r.tables.has(t.table)) try {
1961
+ }, $o = async (e, t) => {
1962
+ if (Y.size !== 0) {
1963
+ for (let [n, r] of Y.entries()) if (!r.ownTables.has(t.table) && r.tables.has(t.table)) try {
1964
1964
  await r.recorder(e, t);
1965
1965
  } catch (e) {
1966
- let r = Pn(e);
1966
+ let r = Nn(e);
1967
1967
  throw r === void 0 ? e : Error(`write recorder '${n}' failed while recording a ${t.op} on '${t.table}': ${r}`, { cause: e });
1968
1968
  }
1969
1969
  }
1970
- }, ts = Ut.exponential({
1970
+ }, es = Ht.exponential({
1971
1971
  start: 5e-4,
1972
1972
  factor: 2,
1973
1973
  count: 16
1974
- }), ns = A.counter("voltro_db_queries_total", { description: "Database operations executed, by dialect and operation kind." }), rs = A.histogram("voltro_db_query_duration_seconds", ts, "Database operation duration in seconds, by dialect and operation kind."), is = A.counter("voltro_db_errors_total", { description: "Database operations that threw, by dialect and operation kind." }), as = 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." }), os = 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." }), ss = [], cs = /* @__PURE__ */ new Map(), ls = /* @__PURE__ */ new Map(), us = /* @__PURE__ */ new Map(), ds = (e, t) => {
1975
- let n = `${e}\u0000${t}`, r = cs.get(n);
1974
+ }), ts = j.counter("voltro_db_queries_total", { description: "Database operations executed, by dialect and operation kind." }), ns = j.histogram("voltro_db_query_duration_seconds", es, "Database operation duration in seconds, by dialect and operation kind."), rs = j.counter("voltro_db_errors_total", { description: "Database operations that threw, by dialect and operation kind." }), is = j.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." }), as = j.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." }), os = [], ss = /* @__PURE__ */ new Map(), cs = /* @__PURE__ */ new Map(), ls = /* @__PURE__ */ new Map(), us = (e, t) => {
1975
+ let n = `${e}\u0000${t}`, r = ss.get(n);
1976
1976
  if (r !== void 0) return r;
1977
- let i = (n) => A.tagged(A.tagged(n, "dialect", e), "op", t), a = {
1978
- count: i(ns),
1979
- duration: i(rs),
1980
- errors: i(is)
1977
+ let i = (n) => j.tagged(j.tagged(n, "dialect", e), "op", t), a = {
1978
+ count: i(ts),
1979
+ duration: i(ns),
1980
+ errors: i(rs)
1981
1981
  };
1982
- return cs.set(n, a), a;
1983
- }, fs = () => {
1984
- cs.clear(), ls.clear(), us.clear();
1985
- }, ps = () => cs.size + ls.size + us.size, ms = /* @__PURE__ */ new Map(), hs = (e, t) => {
1986
- let n = Math.max(0, (ms.get(e) ?? 0) + t);
1987
- n === 0 ? ms.delete(e) : ms.set(e, n);
1988
- let r = ls.get(e);
1989
- r === void 0 && (r = A.tagged(as, "dialect", e), ls.set(e, r)), r.unsafeUpdate(n, ss);
1990
- }, gs = (e) => ms.get(e) ?? 0, _s = (e) => {
1991
- let t = ds(String(e.dialect), e.op);
1992
- t.count.unsafeUpdate(1, ss), t.duration.unsafeUpdate(e.durationMs / 1e3, ss), e.status === "error" && t.errors.unsafeUpdate(1, ss);
1993
- }, vs = async (e, t, n) => {
1982
+ return ss.set(n, a), a;
1983
+ }, ds = () => {
1984
+ ss.clear(), cs.clear(), ls.clear();
1985
+ }, fs = () => ss.size + cs.size + ls.size, ps = /* @__PURE__ */ new Map(), ms = (e, t) => {
1986
+ let n = Math.max(0, (ps.get(e) ?? 0) + t);
1987
+ n === 0 ? ps.delete(e) : ps.set(e, n);
1988
+ let r = cs.get(e);
1989
+ r === void 0 && (r = j.tagged(is, "dialect", e), cs.set(e, r)), r.unsafeUpdate(n, os);
1990
+ }, hs = (e) => ps.get(e) ?? 0, gs = (e) => {
1991
+ let t = us(String(e.dialect), e.op);
1992
+ t.count.unsafeUpdate(1, os), t.duration.unsafeUpdate(e.durationMs / 1e3, os), e.status === "error" && t.errors.unsafeUpdate(1, os);
1993
+ }, _s = async (e, t, n) => {
1994
1994
  let r = performance.now(), i = String(e);
1995
- hs(i, 1);
1995
+ ms(i, 1);
1996
1996
  let a = "ok";
1997
1997
  try {
1998
1998
  return await n();
1999
1999
  } catch (e) {
2000
2000
  throw a = "error", e;
2001
2001
  } finally {
2002
- hs(i, -1), _s({
2002
+ ms(i, -1), gs({
2003
2003
  dialect: e,
2004
2004
  op: t,
2005
2005
  durationMs: performance.now() - r,
2006
2006
  status: a
2007
2007
  });
2008
2008
  }
2009
- }, ys = 3e5, bs = (e) => {
2009
+ }, vs = 3e5, ys = (e) => {
2010
2010
  if (e == null || e === "") return;
2011
2011
  let t = Number(e);
2012
2012
  return Number.isFinite(t) && t >= 0 ? Math.floor(t) : void 0;
2013
- }, xs = (e, t = process.env) => bs(t.VOLTRO_DB_EAGER_FALLBACK_WARN_INTERVAL_MS) ?? bs(e) ?? 3e5, Ss = (e, t = {}) => {
2014
- let n = xs(t.warnIntervalMs), r = t.now ?? (() => Date.now()), i = /* @__PURE__ */ new Map();
2013
+ }, bs = (e, t = process.env) => ys(t.VOLTRO_DB_EAGER_FALLBACK_WARN_INTERVAL_MS) ?? ys(e) ?? 3e5, xs = (e, t = {}) => {
2014
+ let n = bs(t.warnIntervalMs), r = t.now ?? (() => Date.now()), i = /* @__PURE__ */ new Map();
2015
2015
  return (t) => {
2016
- let a = `${t.dialect} ${t.reason}`, o = us.get(a);
2017
- o === void 0 && (o = A.tagged(A.tagged(os, "dialect", String(t.dialect)), "reason", t.reason), us.set(a, o)), o.unsafeUpdate(1, ss);
2016
+ let a = `${t.dialect} ${t.reason}`, o = ls.get(a);
2017
+ o === void 0 && (o = j.tagged(j.tagged(as, "dialect", String(t.dialect)), "reason", t.reason), ls.set(a, o)), o.unsafeUpdate(1, os);
2018
2018
  let s = `${t.table}\u0000${t.reason}`, c = i.get(s), l = c === void 0 || n > 0 && r() - c >= n, u = {
2019
2019
  table: t.table,
2020
2020
  dialect: String(t.dialect),
@@ -2028,24 +2028,24 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
2028
2028
  }
2029
2029
  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);
2030
2030
  };
2031
- }, Cs = (e) => {
2032
- if (Ht.isSuccess(e)) return e.value;
2033
- throw zt.squash(e.cause);
2034
- }, ws = "10 millis", Ts = 3, Es = async (e) => {
2035
- let t = 0, n = k.suspend(() => {
2031
+ }, Ss = (e) => {
2032
+ if (Vt.isSuccess(e)) return e.value;
2033
+ throw Rt.squash(e.cause);
2034
+ }, Cs = "10 millis", ws = 3, Ts = async (e) => {
2035
+ let t = 0, n = A.suspend(() => {
2036
2036
  let n = ++t;
2037
- return e.withTransaction(k.flatMap(k.serviceOption(Yt), (t) => {
2038
- if (j.isNone(t)) return k.fail(/* @__PURE__ */ Error(`${e.label}: TransactionConnection unexpectedly missing inside withTransaction.`));
2039
- let r = t.value, i = k.tryPromise({
2037
+ return e.withTransaction(A.flatMap(A.serviceOption(Jt), (t) => {
2038
+ if (M.isNone(t)) return A.fail(/* @__PURE__ */ Error(`${e.label}: TransactionConnection unexpectedly missing inside withTransaction.`));
2039
+ let r = t.value, i = A.tryPromise({
2040
2040
  try: () => e.body(r, n),
2041
2041
  catch: (e) => e
2042
2042
  });
2043
- return e.prepare === void 0 ? i : k.flatMap(e.prepare(r), () => i);
2044
- })).pipe(k.catchAllDefect((t) => e.isRetryable(t) ? k.fail(t) : k.die(t)));
2045
- }), r = Gt.exponential(ws).pipe(Gt.compose(Gt.recurs(Ts)), Gt.whileInput(e.isRetryable)), i = n.pipe(k.retry(r), k.withSpan(e.span.name, { attributes: { ...e.span.attributes } }));
2046
- return vs(e.dialect, "transaction", async () => Cs(await e.runPromiseExit(e.wrapProgram === void 0 ? i : e.wrapProgram(i))));
2047
- }, Ds = async (e) => {
2048
- let t = So(), n = t === void 0 ? (e) => e() : (e) => xo(t, e), r = await Es({
2043
+ return e.prepare === void 0 ? i : A.flatMap(e.prepare(r), () => i);
2044
+ })).pipe(A.catchAllDefect((t) => e.isRetryable(t) ? A.fail(t) : A.die(t)));
2045
+ }), r = Wt.exponential(Cs).pipe(Wt.compose(Wt.recurs(ws)), Wt.whileInput(e.isRetryable)), i = n.pipe(A.retry(r), A.withSpan(e.span.name, { attributes: { ...e.span.attributes } }));
2046
+ return _s(e.dialect, "transaction", async () => Ss(await e.runPromiseExit(e.wrapProgram === void 0 ? i : e.wrapProgram(i))));
2047
+ }, Es = async (e) => {
2048
+ let t = xo(), n = t === void 0 ? (e) => e() : (e) => bo(t, e), r = await Ts({
2049
2049
  ...e,
2050
2050
  body: (r) => {
2051
2051
  let i = e.makeView(r, t);
@@ -2056,50 +2056,50 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
2056
2056
  }
2057
2057
  });
2058
2058
  return r.view.commitEvents(), r.result;
2059
- }, Os = /* @__PURE__ */ new Set([
2059
+ }, Ds = /* @__PURE__ */ new Set([
2060
2060
  "1213",
2061
2061
  "ER_LOCK_DEADLOCK",
2062
2062
  "1205",
2063
2063
  "ER_LOCK_WAIT_TIMEOUT",
2064
2064
  "1020",
2065
2065
  "ER_CHECKREAD"
2066
- ]), ks = /* @__PURE__ */ new Set(["40001", "40P01"]), As = /* @__PURE__ */ new Set(["1205"]), js = /* @__PURE__ */ new Set([
2066
+ ]), Os = /* @__PURE__ */ new Set(["40001", "40P01"]), ks = /* @__PURE__ */ new Set(["1205"]), As = /* @__PURE__ */ new Set([
2067
2067
  "SQLITE_BUSY",
2068
2068
  "5",
2069
2069
  "SQLITE_LOCKED",
2070
2070
  "6"
2071
- ]), Ms = /write-write conflict|write-read conflict|database is locked|table is locked|database is busy/i, Ns = /* @__PURE__ */ new Set([
2071
+ ]), js = /write-write conflict|write-read conflict|database is locked|table is locked|database is busy/i, Ms = /* @__PURE__ */ new Set([
2072
2072
  1213,
2073
2073
  1205,
2074
2074
  1020
2075
- ]), Ps = /* @__PURE__ */ new Set([
2075
+ ]), Ns = /* @__PURE__ */ new Set([
2076
+ ...Ds,
2076
2077
  ...Os,
2077
2078
  ...ks,
2078
- ...As,
2079
- ...js
2080
- ]), Fs = (e) => xn(e).some(Is), Is = (e) => {
2079
+ ...As
2080
+ ]), Ps = (e) => bn(e).some(Fs), Fs = (e) => {
2081
2081
  let t = e;
2082
2082
  for (let e = 0; e < 6 && typeof t == "object" && t; e++) {
2083
2083
  let e = t;
2084
- if (typeof e.errno == "number" && Ns.has(e.errno) || typeof e.number == "number" && As.has(String(e.number)) || typeof e.code == "string" && Ps.has(e.code) || typeof e.sqlState == "string" && ks.has(e.sqlState) || typeof e.message == "string" && Ms.test(e.message)) return !0;
2084
+ if (typeof e.errno == "number" && Ms.has(e.errno) || typeof e.number == "number" && ks.has(String(e.number)) || typeof e.code == "string" && Ns.has(e.code) || typeof e.sqlState == "string" && Os.has(e.sqlState) || typeof e.message == "string" && js.test(e.message)) return !0;
2085
2085
  t = e.cause;
2086
2086
  }
2087
2087
  return !1;
2088
- }, Ls = "voltro/expires", Rs = () => St({
2089
- id: Ls,
2090
- fields: { expiresAt: E().nullable() },
2088
+ }, Is = "voltro/expires", Ls = () => xt({
2089
+ id: Is,
2090
+ fields: { expiresAt: D().nullable() },
2091
2091
  behaviors: { defaultWhere: () => "expiresAt IS NULL OR expiresAt > now()" }
2092
- }), zs = "voltro/localFirst", Bs = () => St({
2093
- id: zs,
2092
+ }), Rs = "voltro/localFirst", zs = () => xt({
2093
+ id: Rs,
2094
2094
  fields: {}
2095
- }), Vs = (e) => e.appliedMixins.some((e) => e.id === zs), Hs = (e) => {
2095
+ }), Bs = (e) => e.appliedMixins.some((e) => e.id === Rs), Vs = (e) => {
2096
2096
  let t = [];
2097
- for (let n of Object.values(e)) Vs(n) && t.push(n.tableName);
2097
+ for (let n of Object.values(e)) Bs(n) && t.push(n.tableName);
2098
2098
  return t;
2099
- }, Us = class extends Vt.TaggedError("TableStreamError") {}, Ws = 1e3, Gs = (e, t, n, r) => {
2100
- let i = j.match(r, {
2099
+ }, Hs = class extends Bt.TaggedError("TableStreamError") {}, Us = 1e3, Ws = (e, t, n, r) => {
2100
+ let i = M.match(r, {
2101
2101
  onNone: () => e.where,
2102
- onSome: (n) => e.where ? Ka(e.where, ja(t, n)) : ja(t, n)
2102
+ onSome: (n) => e.where ? Ga(e.where, Aa(t, n)) : Aa(t, n)
2103
2103
  });
2104
2104
  return {
2105
2105
  table: e.table,
@@ -2114,19 +2114,19 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
2114
2114
  ...e.includeDeleted === void 0 ? {} : { includeDeleted: e.includeDeleted },
2115
2115
  ...e.crossTenant === void 0 ? {} : { crossTenant: e.crossTenant }
2116
2116
  };
2117
- }, Ks = (e, t) => {
2118
- let n = t.pk ?? "id", r = t.chunkSize ?? Ws;
2119
- return Kt.paginateChunkEffect(j.none(), (i) => {
2120
- let a = k.tryPromise({
2121
- try: () => e.query(Gs(t, n, r, i)),
2122
- catch: (e) => new Us({
2117
+ }, Gs = (e, t) => {
2118
+ let n = t.pk ?? "id", r = t.chunkSize ?? Us;
2119
+ return Gt.paginateChunkEffect(M.none(), (i) => {
2120
+ let a = A.tryPromise({
2121
+ try: () => e.query(Ws(t, n, r, i)),
2122
+ catch: (e) => new Hs({
2123
2123
  table: t.table,
2124
2124
  cause: e
2125
2125
  })
2126
2126
  });
2127
- return (t.retry ? a.pipe(k.retry(t.retry)) : a).pipe(k.map((e) => [Bt.fromIterable(e), e.length === r && e.length > 0 ? j.some(j.some(e[e.length - 1][n])) : j.none()]));
2127
+ return (t.retry ? a.pipe(A.retry(t.retry)) : a).pipe(A.map((e) => [zt.fromIterable(e), e.length === r && e.length > 0 ? M.some(M.some(e[e.length - 1][n])) : M.none()]));
2128
2128
  });
2129
- }, qs = (e) => {
2129
+ }, Ks = (e) => {
2130
2130
  let t = e.alpha ?? .5;
2131
2131
  if (t < 0 || t > 1) throw Error(`hybridSearch: alpha must be in [0, 1], got ${t}`);
2132
2132
  return (n) => {
@@ -2153,17 +2153,17 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
2153
2153
  }
2154
2154
  };
2155
2155
  };
2156
- }, Js = async (e, t) => {
2156
+ }, qs = async (e, t) => {
2157
2157
  let n = e.as ?? "embedding", r = t.row[e.from];
2158
2158
  if (typeof r != "string" || r.length === 0) return {};
2159
2159
  let i = await t.embed(r);
2160
2160
  return { [n]: i };
2161
- }, Ys = (e) => {
2161
+ }, Js = (e) => {
2162
2162
  if (!Number.isInteger(e.dimensions) || e.dimensions <= 0) throw Error(`vectorEmbedding: dimensions must be a positive integer, got ${String(e.dimensions)}.`);
2163
- let t = e.as ?? "embedding", n = (t) => Js(e, t);
2164
- return St({
2163
+ let t = e.as ?? "embedding", n = (t) => qs(e, t);
2164
+ return xt({
2165
2165
  id: "voltro/vectorEmbedding",
2166
- fields: { [t]: gt(e.dimensions) },
2166
+ fields: { [t]: ht(e.dimensions) },
2167
2167
  ...e.index === !1 ? {} : { indexes: [{
2168
2168
  fields: [t],
2169
2169
  kind: "hnsw",
@@ -2178,19 +2178,19 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
2178
2178
  beforeUpdate: n
2179
2179
  }
2180
2180
  });
2181
- }, Xs = 63, Zs = "br_pr", Y = class extends Error {
2181
+ }, Ys = 63, Xs = "br_pr", X = class extends Error {
2182
2182
  _tag = "BranchNameInvalid";
2183
2183
  constructor(e) {
2184
2184
  super(e), this.name = "BranchNameInvalid";
2185
2185
  }
2186
- }, Qs = (e, t) => {
2187
- if (!Number.isInteger(t) || t < 0) throw new Y(`prNumber must be a non-negative integer, got ${String(t)}`);
2188
- let n = ri(e);
2189
- if (n.replace(/_/g, "") === "") throw new Y(`app slug '${e}' has no usable identifier characters`);
2190
- let r = `${Zs}${t}_${n}`;
2191
- if (r.length > Xs) throw new Y(`branch namespace '${r}' exceeds the ${Xs}-byte identifier limit — use a shorter app slug`);
2186
+ }, Zs = (e, t) => {
2187
+ if (!Number.isInteger(t) || t < 0) throw new X(`prNumber must be a non-negative integer, got ${String(t)}`);
2188
+ let n = ni(e);
2189
+ if (n.replace(/_/g, "") === "") throw new X(`app slug '${e}' has no usable identifier characters`);
2190
+ let r = `${Xs}${t}_${n}`;
2191
+ if (r.length > Ys) throw new X(`branch namespace '${r}' exceeds the ${Ys}-byte identifier limit — use a shorter app slug`);
2192
2192
  return r;
2193
- }, $s = (e) => e.startsWith(Zs), ec = {
2193
+ }, Qs = (e) => e.startsWith(Xs), $s = {
2194
2194
  requested: {
2195
2195
  provision: "provisioning",
2196
2196
  destroy: "destroying"
@@ -2209,19 +2209,19 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
2209
2209
  fail: "failed"
2210
2210
  },
2211
2211
  destroyed: {}
2212
- }, tc = class extends Error {
2212
+ }, ec = class extends Error {
2213
2213
  from;
2214
2214
  event;
2215
2215
  _tag = "BranchTransitionInvalid";
2216
2216
  constructor(e, t) {
2217
2217
  super(`invalid branch transition: ${e} --${t}-->`), this.from = e, this.event = t, this.name = "BranchTransitionInvalid";
2218
2218
  }
2219
- }, nc = (e, t) => {
2220
- let n = ec[e][t];
2221
- if (n === void 0) throw new tc(e, t);
2219
+ }, tc = (e, t) => {
2220
+ let n = $s[e][t];
2221
+ if (n === void 0) throw new ec(e, t);
2222
2222
  return n;
2223
- }, rc = (e, t, n, r, i = [], a = []) => {
2224
- if (n === "copy" && (r === void 0 || r === "")) throw new Y("seed 'copy' requires a parentNamespace to snapshot from");
2223
+ }, nc = (e, t, n, r, i = [], a = []) => {
2224
+ if (n === "copy" && (r === void 0 || r === "")) throw new X("seed 'copy' requires a parentNamespace to snapshot from");
2225
2225
  let o = [{
2226
2226
  kind: "create-namespace",
2227
2227
  detail: e
@@ -2250,13 +2250,13 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
2250
2250
  kind: "seed",
2251
2251
  detail: `run boot seeds into ${e}`
2252
2252
  }), o;
2253
- }, ic = (e) => {
2254
- if (!$s(e)) throw new Y(`refusing to plan teardown of '${e}' — not a branch namespace`);
2253
+ }, rc = (e) => {
2254
+ if (!Qs(e)) throw new X(`refusing to plan teardown of '${e}' — not a branch namespace`);
2255
2255
  return [{
2256
2256
  kind: "drop-namespace",
2257
2257
  detail: e
2258
2258
  }];
2259
- }, ac = (e) => {
2259
+ }, ic = (e) => {
2260
2260
  if (e === void 0 || e === "") return !1;
2261
2261
  try {
2262
2262
  let t = new URL(e).hostname.toLowerCase();
@@ -2264,27 +2264,27 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
2264
2264
  } catch {
2265
2265
  return /\bneon\.(tech|build)\b/i.test(e);
2266
2266
  }
2267
- }, oc = (e) => e.prefer === void 0 ? e.seed === "copy" && ac(e.dbUrl) ? "neon-cow" : "namespace" : e.prefer, sc = (e, t = {}) => [{
2267
+ }, ac = (e) => e.prefer === void 0 ? e.seed === "copy" && ic(e.dbUrl) ? "neon-cow" : "namespace" : e.prefer, oc = (e, t = {}) => [{
2268
2268
  kind: "neon-branch-create",
2269
2269
  detail: `${t.parentBranch ?? "main"} → ${e} (copy-on-write)`
2270
- }], cc = (e) => {
2271
- if (!$s(e)) throw new Y(`refusing to plan teardown of '${e}' — not a branch namespace`);
2270
+ }], sc = (e) => {
2271
+ if (!Qs(e)) throw new X(`refusing to plan teardown of '${e}' — not a branch namespace`);
2272
2272
  return [{
2273
2273
  kind: "neon-branch-delete",
2274
2274
  detail: e
2275
2275
  }];
2276
- }, lc = (e) => e.mechanism === "neon-cow" ? sc(e.branchId, e.neonParentBranch === void 0 ? {} : { parentBranch: e.neonParentBranch }) : rc(e.branchId, e.tableNames, e.seed, e.parentNamespace, e.foreignKeys, e.indexNames), uc = (e, t) => e === "neon-cow" ? cc(t) : ic(t), dc = (e, t, n) => {
2276
+ }, cc = (e) => e.mechanism === "neon-cow" ? oc(e.branchId, e.neonParentBranch === void 0 ? {} : { parentBranch: e.neonParentBranch }) : nc(e.branchId, e.tableNames, e.seed, e.parentNamespace, e.foreignKeys, e.indexNames), lc = (e, t) => e === "neon-cow" ? sc(t) : rc(t), uc = (e, t, n) => {
2277
2277
  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);
2278
2278
  return {
2279
2279
  evict: i,
2280
2280
  rejectNew: r.filter((e) => !a.has(e.namespace)).length >= t.maxBranches
2281
2281
  };
2282
- }, fc = async (e, t) => {
2283
- let n = Qs(e.appSlug, e.prNumber), r = oc({
2282
+ }, dc = async (e, t) => {
2283
+ let n = Zs(e.appSlug, e.prNumber), r = ac({
2284
2284
  seed: e.seed,
2285
2285
  ...e.dbUrl === void 0 ? {} : { dbUrl: e.dbUrl },
2286
2286
  ...e.prefer === void 0 ? {} : { prefer: e.prefer }
2287
- }), i = lc({
2287
+ }), i = cc({
2288
2288
  mechanism: r,
2289
2289
  branchId: n,
2290
2290
  tableNames: e.tableNames,
@@ -2313,16 +2313,16 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
2313
2313
  mechanism: r,
2314
2314
  steps: i
2315
2315
  };
2316
- }, pc = async (e, t, n) => {
2317
- let r = uc(t, e);
2316
+ }, fc = async (e, t, n) => {
2317
+ let r = lc(t, e);
2318
2318
  return t === "neon-cow" ? await n.neonBranchDelete(e) : await n.dropNamespace(e), r;
2319
- }, mc = (e, t, n) => dc(e, t, n), X = (e) => `"${e.replace(/"/g, "\"\"")}"`, hc = {
2319
+ }, pc = (e, t, n) => uc(e, t, n), Z = (e) => `"${e.replace(/"/g, "\"\"")}"`, mc = {
2320
2320
  cascade: "CASCADE",
2321
2321
  restrict: "RESTRICT",
2322
2322
  setNull: "SET NULL",
2323
2323
  noAction: "NO ACTION"
2324
- }, Z = (e) => `'${e.replace(/'/g, "''")}'`, gc = (e, t) => {
2325
- let n = t.columns.map(Z).join(", ");
2324
+ }, hc = (e) => `'${e.replace(/'/g, "''")}'`, gc = (e, t) => {
2325
+ let n = t.columns.map(hc).join(", ");
2326
2326
  return `DO $voltro_branch$
2327
2327
  DECLARE derived name;
2328
2328
  BEGIN
@@ -2331,11 +2331,11 @@ BEGIN
2331
2331
  JOIN pg_class i ON i.oid = x.indexrelid
2332
2332
  JOIN pg_class c ON c.oid = x.indrelid
2333
2333
  JOIN pg_namespace nsp ON nsp.oid = c.relnamespace
2334
- WHERE nsp.nspname = ${Z(e)}
2335
- AND c.relname = ${Z(t.table)}
2334
+ WHERE nsp.nspname = ${hc(e)}
2335
+ AND c.relname = ${hc(t.table)}
2336
2336
  AND NOT x.indisprimary
2337
2337
  AND x.indisunique = ${t.unique ? "true" : "false"}
2338
- AND i.relname <> ${Z(t.name)}
2338
+ AND i.relname <> ${hc(t.name)}
2339
2339
  AND (
2340
2340
  SELECT array_agg(att.attname::text ORDER BY k.ord)
2341
2341
  FROM unnest(x.indkey::int2[]) WITH ORDINALITY AS k(attnum, ord)
@@ -2344,24 +2344,24 @@ BEGIN
2344
2344
  LIMIT 1;
2345
2345
  IF derived IS NOT NULL THEN
2346
2346
  EXECUTE format('ALTER INDEX %I.%I RENAME TO %I',
2347
- ${Z(e)}, derived, ${Z(t.name)});
2347
+ ${hc(e)}, derived, ${hc(t.name)});
2348
2348
  END IF;
2349
2349
  END
2350
2350
  $voltro_branch$`;
2351
2351
  }, _c = (e, t) => {
2352
- let n = t.onDelete === void 0 ? "" : ` ON DELETE ${hc[t.onDelete]}`, r = t.onUpdate === void 0 ? "" : ` ON UPDATE ${hc[t.onUpdate]}`;
2353
- return `ALTER TABLE ${X(e)}.${X(t.table)} ADD FOREIGN KEY (${X(t.column)}) REFERENCES ${X(e)}.${X(t.targetTable)} (${X(t.targetColumn)})${n}${r}`;
2352
+ let n = t.onDelete === void 0 ? "" : ` ON DELETE ${mc[t.onDelete]}`, r = t.onUpdate === void 0 ? "" : ` ON UPDATE ${mc[t.onUpdate]}`;
2353
+ return `ALTER TABLE ${Z(e)}.${Z(t.table)} ADD FOREIGN KEY (${Z(t.column)}) REFERENCES ${Z(e)}.${Z(t.targetTable)} (${Z(t.targetColumn)})${n}${r}`;
2354
2354
  }, vc = (e) => {
2355
2355
  let t = () => {
2356
2356
  throw Error("namespace branch executor: Neon ops require a neon-cow executor (use a Neon connection for copy-on-write branches)");
2357
2357
  };
2358
2358
  return {
2359
- createNamespace: (t) => e.run(`CREATE SCHEMA IF NOT EXISTS ${X(t)}`),
2360
- createTable: (t, n) => e.run(`CREATE TABLE IF NOT EXISTS ${X(t)}.${X(n)} (LIKE ${X(n)} INCLUDING ALL)`),
2361
- copyTable: (t, n, r) => e.run(`INSERT INTO ${X(n)}.${X(r)} SELECT * FROM ${X(t)}.${X(r)}`),
2359
+ createNamespace: (t) => e.run(`CREATE SCHEMA IF NOT EXISTS ${Z(t)}`),
2360
+ createTable: (t, n) => e.run(`CREATE TABLE IF NOT EXISTS ${Z(t)}.${Z(n)} (LIKE ${Z(n)} INCLUDING ALL)`),
2361
+ copyTable: (t, n, r) => e.run(`INSERT INTO ${Z(n)}.${Z(r)} SELECT * FROM ${Z(t)}.${Z(r)}`),
2362
2362
  addForeignKey: (t, n) => e.run(_c(t, n)),
2363
2363
  restoreIndexName: (t, n) => e.run(gc(t, n)),
2364
- dropNamespace: (t) => e.run(`DROP SCHEMA IF EXISTS ${X(t)} CASCADE`),
2364
+ dropNamespace: (t) => e.run(`DROP SCHEMA IF EXISTS ${Z(t)} CASCADE`),
2365
2365
  neonBranchCreate: t,
2366
2366
  neonBranchDelete: t
2367
2367
  };
@@ -2394,7 +2394,7 @@ $voltro_branch$`;
2394
2394
  if (n === void 0) throw new yc(`no residency home is mapped for tenant '${e}' — refusing to fall back to a default store (would be a residency violation)`);
2395
2395
  return n;
2396
2396
  }, Ec = (e, t) => t.servableRegions.includes(e), Dc = (e, t) => {
2397
- let n = Tc(e.tenantId, t), r = ii(n.tenantId);
2397
+ let n = Tc(e.tenantId, t), r = ri(n.tenantId);
2398
2398
  return {
2399
2399
  region: n.region,
2400
2400
  namespace: r,
@@ -2464,12 +2464,12 @@ $voltro_branch$`;
2464
2464
  let t = [];
2465
2465
  for (let n of e) t.push(...Nc(n));
2466
2466
  return t;
2467
- }, Fc = "\x1B[", Ic = `${Fc}38;2;245;158;11m`, Lc = `${Fc}38;2;16;185;129m`, Rc = (e, t) => `${e}${t}${N.reset}`, $ = (e, t, n) => e ? typeof t == "function" ? t(n) : Rc(t, n) : n, zc = (e, t = {}) => {
2468
- let n = t.color ?? !0, r = t.indent ?? " ", i = (e) => $(n, N.dim, e.padEnd(11)), a = (e) => $(n, (e) => N.bold(N.brand(e)), e), o = (e) => $(n, N.brightRed24, e), s = (e) => $(n, Lc, e), c = (e) => $(n, Ic, e), l = (e) => $(n, N.dim, e), u = `${c("index audit")} ${l("·")} ${$(n, N.bold, e.kind)}`, d = e.redundant.fields.length, f = Q(e.coveredBy.fields.slice(d)), p = (e, t) => {
2467
+ }, Fc = "\x1B[", Ic = `${Fc}38;2;245;158;11m`, Lc = `${Fc}38;2;16;185;129m`, Rc = (e, t) => `${e}${t}${P.reset}`, $ = (e, t, n) => e ? typeof t == "function" ? t(n) : Rc(t, n) : n, zc = (e, t = {}) => {
2468
+ let n = t.color ?? !0, r = t.indent ?? " ", i = (e) => $(n, P.dim, e.padEnd(11)), a = (e) => $(n, (e) => P.bold(P.brand(e)), e), o = (e) => $(n, P.brightRed24, e), s = (e) => $(n, Lc, e), c = (e) => $(n, Ic, e), l = (e) => $(n, P.dim, e), u = `${c("index audit")} ${l("·")} ${$(n, P.bold, e.kind)}`, d = e.redundant.fields.length, f = Q(e.coveredBy.fields.slice(d)), p = (e, t) => {
2469
2469
  let n = e.slice(0, t), r = e.slice(t), i = [];
2470
2470
  return n.length > 0 && i.push(s(`[${n.join(", ")}]`)), r.length > 0 && i.push(c(`+ [${r.join(", ")}]`)), i.join(" ");
2471
2471
  }, m = [];
2472
- return m.push(u), m.push(""), m.push(`${i("table")}${a(e.table)}`), m.push(""), m.push(`${i("redundant")}${o(e.redundant.name)}`), m.push(`${i("")}${p(Q(e.redundant.fields), d)}`), m.push(""), m.push(`${i("covered by")}${s(e.coveredBy.name)}`), m.push(`${i("")}${p(Q(e.coveredBy.fields), d)}`), f.length > 0 && m.push(`${i("")}${l(`└ extra columns: ${f.join(", ")}`)}`), m.push(""), e.kind === "redundant-prefix" ? (m.push(`${i("why")}B-tree indexes serve queries that filter on a LEADING PREFIX of`), m.push(`${i("")}their column list. The wider index already covers every`), m.push(`${i("")}query the narrower one can serve.`), m.push(`${i("")}${l("Same rule on Postgres / MySQL / MariaDB / MSSQL / SQLite.")}`)) : (m.push(`${i("why")}Two indexes on the same columns under different names.`), m.push(`${i("")}The B-tree engine builds both — same coverage, double cost.`), m.push(`${i("")}${l("Same rule on Postgres / MySQL / MariaDB / MSSQL / SQLite.")}`)), m.push(""), m.push(`${i("cost")}Every ${a("INSERT")} / ${a("UPDATE")} / ${a("DELETE")} on this table writes`), m.push(`${i("")}to ${$(n, N.bold, "both")} B-trees. Pure write overhead, zero read benefit.`), m.push(""), m.push(`${i("fix")}Drop ${o(e.redundant.name)}`), m.push(`${i("")}${l("Keep only if profiling shows the smaller index gives a")}`), m.push(`${i("")}${l("measurable cache-locality boost on a write-heavy hot path.")}`), m.push(`${i("")}${l("Silence with VOLTRO_INDEX_AUDIT=off if intentional.")}`), m.map((e) => `${r}${e}`).join("\n");
2472
+ 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, P.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");
2473
2473
  }, Bc = (e, { apply: t, undo: n }) => ({
2474
2474
  name: e,
2475
2475
  apply: t,
@@ -2484,101 +2484,101 @@ $voltro_branch$`;
2484
2484
  name: e.name,
2485
2485
  steps: t
2486
2486
  };
2487
- }, Hc = (e) => typeof e == "object" && !!e && "__migration" in e && e.__migration === !0, Uc = T("_voltro_migrations", {
2488
- id: D({ prefix: "mig" }),
2489
- name: w(),
2490
- hash: w(),
2491
- status: w(),
2492
- appliedAt: E().nullable(),
2487
+ }, Hc = (e) => typeof e == "object" && !!e && "__migration" in e && e.__migration === !0, Uc = E("_voltro_migrations", {
2488
+ id: O({ prefix: "mig" }),
2489
+ name: T(),
2490
+ hash: T(),
2491
+ status: T(),
2492
+ appliedAt: D().nullable(),
2493
2493
  durationMs: y().nullable(),
2494
- errorMessage: w().nullable(),
2495
- errorStack: w().nullable(),
2496
- workflowRunId: w().nullable(),
2497
- createdAt: E().default("now"),
2498
- updatedAt: E().default("now").onUpdate("now")
2499
- }).index(["status"]), Wc = T("_voltro_seeds", {
2500
- id: D({ prefix: "seed" }),
2501
- name: w(),
2502
- lifecycle: w(),
2503
- fingerprint: w(),
2504
- cronSchedule: w().nullable(),
2505
- watchedTables: S().nullable(),
2506
- nextRunAt: E().nullable(),
2507
- lastRunStatus: w().nullable(),
2508
- lastRunAt: E().nullable(),
2494
+ errorMessage: T().nullable(),
2495
+ errorStack: T().nullable(),
2496
+ workflowRunId: T().nullable(),
2497
+ createdAt: D().default("now"),
2498
+ updatedAt: D().default("now").onUpdate("now")
2499
+ }).index(["status"]), Wc = E("_voltro_seeds", {
2500
+ id: O({ prefix: "seed" }),
2501
+ name: T(),
2502
+ lifecycle: T(),
2503
+ fingerprint: T(),
2504
+ cronSchedule: T().nullable(),
2505
+ watchedTables: C().nullable(),
2506
+ nextRunAt: D().nullable(),
2507
+ lastRunStatus: T().nullable(),
2508
+ lastRunAt: D().nullable(),
2509
2509
  lastRunDurationMs: y().nullable(),
2510
2510
  lastRunRowsTouched: y().nullable(),
2511
- lastError: w().nullable(),
2512
- workflowRunId: w().nullable(),
2513
- createdAt: E().default("now"),
2514
- updatedAt: E().default("now").onUpdate("now")
2515
- }).index(["lifecycle"]).index(["nextRunAt"]), Gc = T("_voltro_migration_plans", {
2516
- id: D({ prefix: "plan" }),
2517
- fingerprint: w(),
2518
- liveFingerprint: w().nullable(),
2519
- operations: S(),
2520
- rollbackPlan: S().nullable(),
2521
- appliedBy: w(),
2522
- environment: w(),
2523
- source: w(),
2524
- onlineStrategy: w().nullable(),
2511
+ lastError: T().nullable(),
2512
+ workflowRunId: T().nullable(),
2513
+ createdAt: D().default("now"),
2514
+ updatedAt: D().default("now").onUpdate("now")
2515
+ }).index(["lifecycle"]).index(["nextRunAt"]), Gc = E("_voltro_migration_plans", {
2516
+ id: O({ prefix: "plan" }),
2517
+ fingerprint: T(),
2518
+ liveFingerprint: T().nullable(),
2519
+ operations: C(),
2520
+ rollbackPlan: C().nullable(),
2521
+ appliedBy: T(),
2522
+ environment: T(),
2523
+ source: T(),
2524
+ onlineStrategy: T().nullable(),
2525
2525
  durationMs: y(),
2526
- notes: w().nullable(),
2527
- squashedAt: E().nullable(),
2528
- appliedAt: E().default("now"),
2529
- createdAt: E().default("now"),
2530
- updatedAt: E().default("now").onUpdate("now")
2531
- }).index(["fingerprint"]).index(["environment"]), Kc = T("_voltro_idempotency", {
2532
- id: D({ prefix: "idem" }),
2533
- scope: w(),
2534
- key: w(),
2535
- status: w(),
2536
- response: S().nullable(),
2537
- createdAt: E().default("now")
2538
- }).unique(["scope", "key"]).index(["createdAt"]), qc = T("_voltro_kv", {
2539
- id: D({ prefix: "kv" }),
2540
- key: w().unique(),
2541
- value: w().nullable(),
2542
- expiresAt: E().nullable(),
2543
- createdAt: E().default("now"),
2544
- updatedAt: E().default("now").onUpdate("now")
2545
- }).index(["expiresAt"]), Jc = T("_voltro_api_keys", {
2546
- id: D({ prefix: "apikey" }),
2547
- tenantId: w().nullable(),
2548
- name: w(),
2549
- hashedKey: w().maxLength(64).unique(),
2550
- keyPrefix: w(),
2551
- scopes: S().nullable(),
2552
- lastUsedAt: E().nullable(),
2526
+ notes: T().nullable(),
2527
+ squashedAt: D().nullable(),
2528
+ appliedAt: D().default("now"),
2529
+ createdAt: D().default("now"),
2530
+ updatedAt: D().default("now").onUpdate("now")
2531
+ }).index(["fingerprint"]).index(["environment"]), Kc = E("_voltro_idempotency", {
2532
+ id: O({ prefix: "idem" }),
2533
+ scope: T(),
2534
+ key: T(),
2535
+ status: T(),
2536
+ response: C().nullable(),
2537
+ createdAt: D().default("now")
2538
+ }).unique(["scope", "key"]).index(["createdAt"]), qc = E("_voltro_kv", {
2539
+ id: O({ prefix: "kv" }),
2540
+ key: T().unique(),
2541
+ value: T().nullable(),
2542
+ expiresAt: D().nullable(),
2543
+ createdAt: D().default("now"),
2544
+ updatedAt: D().default("now").onUpdate("now")
2545
+ }).index(["expiresAt"]), Jc = E("_voltro_api_keys", {
2546
+ id: O({ prefix: "apikey" }),
2547
+ tenantId: T().nullable(),
2548
+ name: T(),
2549
+ hashedKey: T().maxLength(64).unique(),
2550
+ keyPrefix: T(),
2551
+ scopes: C().nullable(),
2552
+ lastUsedAt: D().nullable(),
2553
2553
  requestCount: y().default(0),
2554
- expiresAt: E().nullable(),
2555
- revokedAt: E().nullable(),
2556
- createdBy: w().nullable(),
2557
- onBehalfOf: w().nullable(),
2558
- metadata: S().nullable(),
2559
- createdAt: E().default("now")
2560
- }).index("byApiKeyTenant", ["tenantId"]), Yc = T("_voltro_replica_observations", {
2561
- id: D({ prefix: "robs" }),
2562
- replicaId: w().maxLength(191),
2563
- startedAt: E(),
2564
- version: w().maxLength(64).nullable(),
2565
- kind: w().maxLength(64),
2566
- payload: w().nullable(),
2567
- reachableAt: w().maxLength(255).nullable(),
2568
- writtenAt: E().default("now").onUpdate("now")
2554
+ expiresAt: D().nullable(),
2555
+ revokedAt: D().nullable(),
2556
+ createdBy: T().nullable(),
2557
+ onBehalfOf: T().nullable(),
2558
+ metadata: C().nullable(),
2559
+ createdAt: D().default("now")
2560
+ }).index("byApiKeyTenant", ["tenantId"]), Yc = E("_voltro_replica_observations", {
2561
+ id: O({ prefix: "robs" }),
2562
+ replicaId: T().maxLength(191),
2563
+ startedAt: D(),
2564
+ version: T().maxLength(64).nullable(),
2565
+ kind: T().maxLength(64),
2566
+ payload: T().nullable(),
2567
+ reachableAt: T().maxLength(255).nullable(),
2568
+ writtenAt: D().default("now").onUpdate("now")
2569
2569
  }).unique(["replicaId", "kind"]).index(["kind"]), Xc = [
2570
2570
  Uc,
2571
2571
  Wc,
2572
2572
  Gc
2573
- ], Zc = "_voltro_replace_in_progress", Qc = T(Zc, {
2574
- id: D({ prefix: "repl" }),
2575
- startedAt: E().default("now"),
2576
- kind: w().default("replace"),
2577
- tables: w().nullable(),
2578
- capture: w().nullable(),
2579
- via: w(),
2580
- staging: w().nullable(),
2581
- heartbeatAt: E().nullable(),
2573
+ ], Zc = "_voltro_replace_in_progress", Qc = E(Zc, {
2574
+ id: O({ prefix: "repl" }),
2575
+ startedAt: D().default("now"),
2576
+ kind: T().default("replace"),
2577
+ tables: T().nullable(),
2578
+ capture: T().nullable(),
2579
+ via: T(),
2580
+ staging: T().nullable(),
2581
+ heartbeatAt: D().nullable(),
2582
2582
  resumable: p().nullable()
2583
2583
  }), $c = 30, el = (e, t) => {
2584
2584
  let n = typeof t == "number" && Number.isFinite(t) && t > 0 ? t : 30, r = Number(e.VOLTRO_STAGING_STALE_MINUTES);
@@ -2618,7 +2618,7 @@ ${e.all.map((e) => {
2618
2618
  }).join("\n")}\n The target of a staged \`replace\` is untouched until one short swap at the end, so none of this is
2619
2619
  a reason to refuse the boot — it is a reason to know the disk is holding a copy of a bundle.`;
2620
2620
  }, al = "id", ol = (e, t) => {
2621
- let n = C(e);
2621
+ let n = w(e);
2622
2622
  if (n === void 0) return t;
2623
2623
  let r = n.fields[al]?.idScheme;
2624
2624
  if (r === void 0 || t[al] != null) return t;
@@ -2627,7 +2627,7 @@ ${e.all.map((e) => {
2627
2627
  let e = { ...t };
2628
2628
  return delete e[al], e;
2629
2629
  }
2630
- let i = rt(r, e);
2630
+ let i = nt(r, e);
2631
2631
  return i === null ? t : {
2632
2632
  ...t,
2633
2633
  [al]: i
@@ -2681,25 +2681,28 @@ ${e.all.map((e) => {
2681
2681
  ...r.update === void 0 ? {} : { update: r.update },
2682
2682
  ...r.updateValues === void 0 ? {} : { updateValues: r.updateValues }
2683
2683
  });
2684
- }, vl = (e, t, n, r) => e.updateMany(t.tableName, n, { where: r.where }), yl = 512, bl = (e) => {
2684
+ }, vl = async (e, t, n, r) => {
2685
+ if (e.insertIgnoreWithOutcome === void 0) throw Error("insertIgnoreRowOutcome: this store does not implement `insertIgnoreWithOutcome`. It is provided by the framework's store wrapper, so `ctx.store` has it; a hand-written DataStore must add it.");
2686
+ return e.insertIgnoreWithOutcome(t.tableName, n, { conflictColumns: r.conflictColumns });
2687
+ }, yl = (e, t, n, r) => e.updateMany(t.tableName, n, { where: r.where }), bl = 512, xl = (e) => {
2685
2688
  e.setMaxListeners(512);
2686
- }, xl = (e, t, n) => ({
2689
+ }, Sl = (e, t, n) => ({
2687
2690
  _tag: "PrimaryKeyConflictError",
2688
2691
  table: e,
2689
2692
  key: t,
2690
2693
  cause: n
2691
- }), Sl = (e) => typeof e == "object" && !!e && e._tag === "PrimaryKeyConflictError", Cl = {
2694
+ }), Cl = (e) => typeof e == "object" && !!e && e._tag === "PrimaryKeyConflictError", wl = {
2692
2695
  postgres: 5432,
2693
2696
  mysql: 3306,
2694
2697
  mariadb: 3306,
2695
2698
  mssql: 1433
2696
- }, wl = /* @__PURE__ */ new Set([
2699
+ }, Tl = /* @__PURE__ */ new Set([
2697
2700
  "localhost",
2698
2701
  "127.0.0.1",
2699
2702
  "::1",
2700
2703
  "[::1]",
2701
2704
  "0.0.0.0"
2702
- ]), Tl = (e) => {
2705
+ ]), El = (e) => {
2703
2706
  let t = e.host, n = e.port, r = e.database;
2704
2707
  if (e.url !== void 0 && e.url !== "") try {
2705
2708
  let i = new URL(e.url);
@@ -2708,29 +2711,29 @@ ${e.all.map((e) => {
2708
2711
  return;
2709
2712
  }
2710
2713
  if (t === void 0 || t === "" || r === void 0 || r === "") return;
2711
- let i = n ?? Cl[(e.dialect ?? "").toLowerCase()];
2714
+ let i = n ?? wl[(e.dialect ?? "").toLowerCase()];
2712
2715
  if (i === void 0 || !Number.isFinite(i)) return;
2713
2716
  let a = t.toLowerCase();
2714
2717
  return {
2715
- host: wl.has(a) ? "localhost" : a,
2718
+ host: Tl.has(a) ? "localhost" : a,
2716
2719
  port: i,
2717
2720
  database: r.toLowerCase()
2718
2721
  };
2719
- }, El = (e) => {
2720
- let t = Tl(e);
2721
- if (t !== void 0) return qt("sha256").update(`${t.host}\u0000${t.port}\u0000${t.database}`).digest("hex").slice(0, 32);
2722
- }, Dl = (e, t) => e === void 0 || t === void 0 ? "unknown" : e === t ? "same" : "different", Ol = {
2722
+ }, Dl = (e) => {
2723
+ let t = El(e);
2724
+ if (t !== void 0) return Kt("sha256").update(`${t.host}\u0000${t.port}\u0000${t.database}`).digest("hex").slice(0, 32);
2725
+ }, Ol = (e, t) => e === void 0 || t === void 0 ? "unknown" : e === t ? "same" : "different", kl = {
2723
2726
  app: 3,
2724
2727
  plugin: 2,
2725
2728
  framework: 1
2726
- }, kl = /* @__PURE__ */ new Map(), Al = [], jl = () => [...Al], Ml = (e) => {
2729
+ }, Al = /* @__PURE__ */ new Map(), jl = [], Ml = () => [...jl], Nl = (e) => {
2727
2730
  if (!e.table || !e.timeColumn) throw Error("registerRetention: table + timeColumn are required");
2728
2731
  if (!Number.isFinite(e.ttlMs) || e.ttlMs <= 0) throw Error(`registerRetention(${e.table}): ttlMs must be a positive number`);
2729
- let t = e.source ?? "app", n = kl.get(e.table);
2732
+ let t = e.source ?? "app", n = Al.get(e.table);
2730
2733
  if (n !== void 0) {
2731
2734
  let r = n.source ?? "app", i = n.ttlMs !== e.ttlMs || n.where !== void 0 != (e.where !== void 0);
2732
- if (Ol[t] < Ol[r]) {
2733
- i && Al.push({
2735
+ if (kl[t] < kl[r]) {
2736
+ i && jl.push({
2734
2737
  table: e.table,
2735
2738
  kept: {
2736
2739
  source: r,
@@ -2743,7 +2746,7 @@ ${e.all.map((e) => {
2743
2746
  });
2744
2747
  return;
2745
2748
  }
2746
- i && r !== t && Al.push({
2749
+ i && r !== t && jl.push({
2747
2750
  table: e.table,
2748
2751
  kept: {
2749
2752
  source: t,
@@ -2755,13 +2758,13 @@ ${e.all.map((e) => {
2755
2758
  }
2756
2759
  });
2757
2760
  }
2758
- kl.set(e.table, {
2761
+ Al.set(e.table, {
2759
2762
  ...e,
2760
2763
  source: t
2761
2764
  });
2762
- }, Nl = () => [...kl.values()], Pl = () => {
2763
- kl.clear(), Al.length = 0;
2764
- }, Fl = async (e, t, n, r = 2e4) => {
2765
+ }, Pl = () => [...Al.values()], Fl = () => {
2766
+ Al.clear(), jl.length = 0;
2767
+ }, Il = async (e, t, n, r = 2e4) => {
2765
2768
  let i = new Date(t - e.ttlMs), a = 0;
2766
2769
  try {
2767
2770
  for (;;) {
@@ -2769,45 +2772,45 @@ ${e.all.map((e) => {
2769
2772
  if (a += t, t < r) break;
2770
2773
  }
2771
2774
  } catch (t) {
2772
- throw k.runSync(A.increment(A.tagged(Ll, "table", e.table))), t;
2775
+ throw A.runSync(j.increment(j.tagged(Rl, "table", e.table))), t;
2773
2776
  }
2774
- return a > 0 && k.runSync(A.incrementBy(A.tagged(Il, "table", e.table), a)), a;
2775
- }, Il = A.counter("voltro_retention_swept_rows_total"), Ll = A.counter("voltro_retention_sweep_errors_total"), Rl = (e, t) => {
2777
+ return a > 0 && A.runSync(j.incrementBy(j.tagged(Ll, "table", e.table), a)), a;
2778
+ }, Ll = j.counter("voltro_retention_swept_rows_total"), Rl = j.counter("voltro_retention_sweep_errors_total"), zl = (e, t) => {
2776
2779
  let n = Number(e ?? String(t));
2777
2780
  return (Number.isFinite(n) && n > 0 ? n : t) * 36e5;
2778
- }, zl = "_voltro_cdc_offsets", Bl = T(zl, {
2779
- id: D({ prefix: "cdcoff" }),
2780
- replicaId: w(),
2781
- streamName: w(),
2782
- binlogFile: w(),
2783
- binlogPosition: w(),
2784
- updatedAt: E()
2785
- }).index(["replicaId"]), Vl = T(zl, {
2786
- id: D({ prefix: "cdcoff" }),
2787
- replicaId: w(),
2788
- streamName: w(),
2789
- ctVersion: w(),
2790
- updatedAt: E()
2791
- }).index(["replicaId"]), Hl = "_voltro_data_transfers", Ul = T(Hl, {
2792
- id: D({ prefix: "dimp" }),
2793
- startedAt: E().default("now"),
2794
- finishedAt: E().nullable(),
2795
- direction: w().default("import"),
2796
- mode: w(),
2797
- via: w(),
2798
- bundle: w().nullable(),
2799
- sourceFingerprint: w().nullable(),
2781
+ }, Bl = "_voltro_cdc_offsets", Vl = E(Bl, {
2782
+ id: O({ prefix: "cdcoff" }),
2783
+ replicaId: T(),
2784
+ streamName: T(),
2785
+ binlogFile: T(),
2786
+ binlogPosition: T(),
2787
+ updatedAt: D()
2788
+ }).index(["replicaId"]), Hl = E(Bl, {
2789
+ id: O({ prefix: "cdcoff" }),
2790
+ replicaId: T(),
2791
+ streamName: T(),
2792
+ ctVersion: T(),
2793
+ updatedAt: D()
2794
+ }).index(["replicaId"]), Ul = "_voltro_data_transfers", Wl = E(Ul, {
2795
+ id: O({ prefix: "dimp" }),
2796
+ startedAt: D().default("now"),
2797
+ finishedAt: D().nullable(),
2798
+ direction: T().default("import"),
2799
+ mode: T(),
2800
+ via: T(),
2801
+ bundle: T().nullable(),
2802
+ sourceFingerprint: T().nullable(),
2800
2803
  tablesWritten: y().default(0),
2801
2804
  rowsWritten: y().default(0),
2802
- failure: w().nullable(),
2805
+ failure: T().nullable(),
2803
2806
  staged: p().nullable()
2804
- }).renamedFrom("_voltro_data_imports").nonReactive(), Wl = (e) => {
2807
+ }).renamedFrom("_voltro_data_imports").nonReactive(), Gl = (e) => {
2805
2808
  let t = Number.isFinite(e.startedAt.getTime()) ? e.startedAt.toISOString() : "an unknown time", n = e.direction === "import" ? e.mode : `${e.direction} ${e.mode}`, r = e.failure === null ? e.finishedAt === null ? `${n} — started and never reported finishing` : e.direction === "backup" || e.direction === "restore" ? `${n} — finished${e.rowsWritten > 0 ? ` (${e.rowsWritten} blob(s))` : ""}` : `${n} — ${e.rowsWritten} row(s) across ${e.tablesWritten} table(s)` : `FAILED ${n} — ${e.failure}`, i = e.staged === null ? "" : e.staged ? " · staged (target untouched until the swap)" : " · NOT staged (target emptied first)";
2806
2809
  return `${t} · ${r} · via ${e.via}${i}` + (e.bundle === null ? "" : ` · from ${e.bundle}`) + (e.sourceFingerprint === null ? "" : ` · source schema ${e.sourceFingerprint}`);
2807
- }, Gl = 255, Kl = (e) => e == null ? "null" : typeof e == "string" || typeof e == "number" || typeof e == "boolean" ? JSON.stringify(e) : Array.isArray(e) ? `[${e.map(Kl).join(",")}]` : typeof e == "object" ? `{${Object.entries(e).filter(([, e]) => e !== void 0).sort(([e], [t]) => e < t ? -1 : +(e > t)).map(([e, t]) => `${JSON.stringify(e)}:${Kl(t)}`).join(",")}}` : JSON.stringify(String(e)), ql = (e) => {
2810
+ }, Kl = 255, ql = (e) => e == null ? "null" : typeof e == "string" || typeof e == "number" || typeof e == "boolean" ? JSON.stringify(e) : Array.isArray(e) ? `[${e.map(ql).join(",")}]` : typeof e == "object" ? `{${Object.entries(e).filter(([, e]) => e !== void 0).sort(([e], [t]) => e < t ? -1 : +(e > t)).map(([e, t]) => `${JSON.stringify(e)}:${ql(t)}`).join(",")}}` : JSON.stringify(String(e)), Jl = (e) => {
2808
2811
  if (e == null) return null;
2809
- let t = typeof e == "string" ? e : Kl(e);
2812
+ let t = typeof e == "string" ? e : ql(e);
2810
2813
  return t.length > 255 ? t.slice(0, 255) : t;
2811
- }, Jl = "postgres";
2814
+ }, Yl = "postgres";
2812
2815
  //#endregion
2813
- export { ct as AUTO_FILLED_COLUMNS, an as BOUND_ENCRYPTED_PREFIX, cl as BULK_INSERT_LIMITS, Y as BranchNameInvalid, tc as BranchTransitionInvalid, zl as CDC_OFFSETS_TABLE, _o as CHANGE_CLAIM_TTL_ENV, yl as CHANGE_LISTENER_CEILING, Ze as ColumnBuilder, Hl as DATA_TRANSFERS_TABLE, ot as DEFAULT_ACQUIRE_TIMEOUT_MS, vo as DEFAULT_CHANGE_CLAIM_TTL_HOURS, ys as DEFAULT_EAGER_FALLBACK_WARN_INTERVAL_MS, vt as DEFAULT_SOFT_DROP_RETENTION_DAYS, pr as DEFAULT_SUBJECT_GRAPH_DEPTH, rn as ENCRYPTED_PREFIX, Jl as ENGINE, Br as EagerCardinalityError, xt as FILE_MIGRATION_PATTERN, it as FRAMEWORK_LIVE_TABLES, cn as FieldDecryptionError, Vo as ID_COLUMN_MAX_LENGTH, It as INITIAL_VERSION, Ha as MATCHES_NO_ROWS, wt as MAX_IDENTIFIER_LENGTH, As as MSSQL_TRANSIENT_NUMBERS, Os as MYSQL_TRANSIENT_CODES, go as OccurrenceCounter, ks as POSTGRES_TRANSIENT_STATES, Zc as REPLACE_IN_PROGRESS_TABLE, Gl as SCOPE_KEY_MAX_LENGTH, ae as SELF_REFERENCE_TARGET, js as SQLITE_TRANSIENT_CODES, $c as STAGING_STALE_MINUTES, ft as STAGING_TABLE_PREFIX, Xt as SqlClient, Ms as TURSO_TRANSIENT_MESSAGE, Us as TableStreamError, ei as TenantNamespaceInvalid, $r as TenantNamespaceUnresolved, bc as TenantRegionUnavailable, yc as TenantResidencyUnresolved, Ls as VOLTRO_EXPIRES_MIXIN_ID, zs as VOLTRO_LOCAL_FIRST_MIXIN_ID, Nt as VersionConflict, kt as WARN_IDENTIFIER_LENGTH, Jc as _voltroApiKeysTable, Bl as _voltroCdcOffsetsTable, Ul as _voltroDataTransfersTable, Kc as _voltroIdempotencyTable, qc as _voltroKvTable, Gc as _voltroMigrationPlansTable, Uc as _voltroMigrationsTable, Vl as _voltroMssqlCdcOffsetsTable, Qc as _voltroReplaceInProgressTable, Yc as _voltroReplicaObservationsTable, Wc as _voltroSeedsTable, Oa as actorsTable, mc as admitBranch, qe as agedSoftDropSnapshots, ye as allEnumRenames, ur as allRegisteredRelations, te as allRegisteredTables, Ka as and, Rr as applyJsonPatch, se as array, za as arrayContains, Va as arrayHas, Ba as arrayOverlaps, Hr as attachEagerLoads, Co as attributionFields, Do as attributionKey, Pc as auditAllTableIndexes, Nc as auditTableIndexes, Tt as avg, ve as avgOver, Io as beginLocalWrite, de as bigint, Oc as bindResidentStore, p as boolean, Qs as branchNamespaceName, ll as bulkInsertLimitsFor, ee as bytes, xn as causeBranches, lo as changeDelete, po as changeDigest, so as changeInsert, uo as changeSoftDelete, co as changeUpdate, dl as chunkRowsForInsert, Ao as claimPendingAttribution, jn as classifyConstraintViolation, d as clearEnumRenames, zo as clearPendingAttribution, fr as clearRelationsRegistry, wc as clearResidencyConfig, Pl as clearRetentions, De as clearTableRegistry, Jo as clearWriteRecorders, W as coercePredicateForSqlite, ci as coercePredicateValue, li as coercePredicateValues, ba as coerceValueForSqlite, io as collectSubqueries, u as column, Bn as columnSchema, ul as columnsPerRow, Ci as compileEagerJson, zr as compileJsonPatch, L as compilePredicate, ui as compileRawFragment, Si as compileSelect, mo as composeChangeKey, Js as computeEmbedding, El as connectionIdentity, La as contains, c as count, ce as countDistinct, ie as crdtDoc, he as crdtManagedColumns, jt as crdtManagedColumnsOf, a as crdtText, So as currentWriteAttribution, Qe as databaseHandle, Ce as date, _ as dbEnum, ps as dbMetricTagCacheSizeForTests, gs as dbOperationsInFlight, xe as decimal, l as declareEnumRename, pn as decodeFieldValue, Dr as decodeRowsFromSchema, yn as decryptFieldsOnRead, Vc as defineMigration, St as defineMixin, lt as defineSeed, n as denseRank, br as deriveSubjectGraph, ut as deriveTypeIdPrefix, Wo as derivedRowId, Go as derivedRowIdLength, Me as describeAgedSoftDropSnapshots, Pn as describeDriverError, Fn as describeRowBindings, Wl as describeTransferRun, nn as deserializeArraysOnRead, Fe as drainIdentifierWarnings, Te as dropped, dn as encodeFieldValue, kr as encodeRowForSchema, vn as encryptFieldsForWrite, gn as encryptedColumnsOf, Lo as endLocalWrite, dc as enforceBranchLimits, Ee as ensureTableRegistered, ka as eq, di as escapeLike, ro as evaluatePredicate, Xe as except, $a as exists, Rs as expires, oo as externalChangeEvent, wn as extractDbCause, on as fieldBinding, nt as fireSchemaChangeSeeds, Ge as fireTenantCreateSeeds, zc as formatIndexAuditIssue, xr as formatSubjectGraph, Xc as frameworkTables, rt as generateId, We as generateSnowflake, h as geography, re as geometry, le as getEnumRenames, lr as getRelation, cr as getRelations, Cc as getResidencyConfig, C as getTable, ja as gt, Ma as gte, Qr as hasEagerLoads, qs as hybridSearch, D as id, Fa as inSet, Za as inSubquery, $n as inferForeignKey, hl as insertManyRows, ml as insertRow, y as integer, nl as interruptedReplaceRefusal, x as intersect, Oe as interval, sn as isBoundCiphertext, $s as isBranchNamespace, Pr as isCompositeRowKey, Jn as isEmptyRelationsSpec, un as isEncrypted, ln as isFieldDecryptionError, Le as isFileMigration, Mn as isForeignKeyViolation, st as isFrameworkOwnedLiveTable, Vs as isLocalFirst, Hc as isMigrationDefinition, mt as isMysqlFamily, ac as isNeonConnection, Wa as isNotNull, Ua as isNull, Sl as isPrimaryKeyConflictError, Nn as isQueryTimeout, mn as isRawEncoding, Ec as isRegionServable, Yn as isRelationsSpec, Ue as isSeedDefinition, ht as isSoftDropSnapshotName, Ye as isSqliteFamily, Ie as isStagingTableName, fe as isTableReactive, Fs as isTransientContention, Pe as isView, S as json, Ya as jsonField, _t as jsonIndex, Fr as jsonPatchAssignments, oe as lag, ue as lead, jl as listRetentionConflicts, Nl as listRetentions, Bs as localFirst, Hs as localFirstTables, Na as lt, Pa as lte, Ss as makeEagerFallbackReporter, vc as makeNamespaceBranchExecutor, Zn as many, Qn as manyToMany, ke as materializeFields, f as max, Ve as migration, v as min, pl as missingConflictColumns, fl as missingRequiredColumns, Re as mixin, Aa as neq, nc as nextBranchState, Tl as normaliseTarget, Lr as normalizeJsonPatchValue, Ja as not, eo as notExists, Ia as notInSet, Qa as notInSubquery, pe as numeric, vs as observeDbOp, yo as occurrenceWindowMs, Xn as one, Vr as oneCardinalityMessage, qa as or, b as orderClausesOf, me as paginateBy, At as paginateById, ho as parseChangeKey, Bo as pendingAttributionCount, lc as planBranch, rc as planBranchProvision, ic as planBranchTeardown, uc as planBranchTeardownFor, sc as planNeonBranchProvision, cc as planNeonBranchTeardown, Mt as planVersionedUpdate, $e as pluginRef, r as pluginRefSpecOf, xl as primaryKeyConflictError, fc as provisionBranch, kc as provisionResidentTenant, ai as qualifyTable, i as queryFor, Dt as queryForView, Ne as quoteIdent, bl as raiseChangeListenerCeiling, Se as rank, t as raw, ze as readableByColumns, yt as real, _s as recordDbOp, $o as recordsTable, at as reference, Rn as refuseWrite, wa as registerCoreTables, sr as registerDiscoveredRelations, ko as registerPendingAttribution, or as registerRelations, Ml as registerRetention, e as registerTable, Ko as registerWriteRecorder, qn as relations, Ea as requireActors, Be as requireTable, Da as requireTenants, fs as resetDbMetricTagCacheForTests, je as resetSnowflake, Dc as residentPlacement, Qt as resolveActorSnapshot, oc as resolveBranchMechanism, xs as resolveEagerFallbackWarnIntervalMs, Ro as resolveEchoAttribution, g as resolveFullTextIndex, Ke as resolveIdScheme, He as resolveMixinGraph, Tc as resolveTenantHome, ii as resolveTenantNamespace, Rl as retentionTtlMsFromEnv, Mr as rowKeyColumns, Nr as rowKeyIdentity, be as rowNumber, Vn as rowSchema, Es as runRetryingTransaction, Ds as runStoreTransaction, xo as runWithWriteAttribution, es as runWriteRecorders, Dl as sameDatabase, ri as sanitizeIdentifierFragment, ql as scopeKeyOf, pt as selfReference, tn as serializeArraysForWrite, Je as serverOnlyColumns, Sc as setResidencyConfig, Ae as setSchemaChangeSeedHook, Ct as setTenantCreateSeedHook, Cs as settleTransactionExit, Ft as settleVersionedUpdate, et as softDropSnapshotStamp, Ga as spatialPredicate, il as stagingLeftoverReport, rl as stagingLeftovers, tl as stagingNamesOf, el as stagingStaleAfterMs, ol as stampGeneratedId, sl as stampGeneratedIds, Ra as startsWith, zn as storeRefusalOf, Ks as streamTable, we as sum, m as sumOver, Xo as suspendWriteRecorders, Zo as suspendWriteRecordersEffect, Fl as sweepRetention, T as table, pc as teardownBranch, w as text, E as timestamp, Rt as timestampMs, Pt as timestampMsOrNull, ne as union, dt as unionAll, bt as unregisterTable, qo as unregisterWriteRecorder, vl as updateManyRow, gl as upsertRow, _l as upsertRowOutcome, jr as upsertUpdatePatch, Ar as upsertUpdateValues, Ot as validateColumnName, _e as validateIndexName, dr as validateRegisteredRelations, rr as validateRelationConfig, s as validateTableName, Et as validateTypeIdPrefix, gt as vector, tt as vectorDistanceToOpclass, Ys as vectorEmbedding, Lt as versionColumnOf, ge as view, o as viewSql, ao as walkLeaves, Tn as wireSafeCause, wo as withCapturedAttribution, Qo as writeRecordersSuspended };
2816
+ export { st as AUTO_FILLED_COLUMNS, rn as BOUND_ENCRYPTED_PREFIX, cl as BULK_INSERT_LIMITS, X as BranchNameInvalid, ec as BranchTransitionInvalid, Bl as CDC_OFFSETS_TABLE, go as CHANGE_CLAIM_TTL_ENV, bl as CHANGE_LISTENER_CEILING, Xe as ColumnBuilder, Ul as DATA_TRANSFERS_TABLE, at as DEFAULT_ACQUIRE_TIMEOUT_MS, _o as DEFAULT_CHANGE_CLAIM_TTL_HOURS, vs as DEFAULT_EAGER_FALLBACK_WARN_INTERVAL_MS, _t as DEFAULT_SOFT_DROP_RETENTION_DAYS, fr as DEFAULT_SUBJECT_GRAPH_DEPTH, nn as ENCRYPTED_PREFIX, Yl as ENGINE, zr as EagerCardinalityError, bt as FILE_MIGRATION_PATTERN, rt as FRAMEWORK_LIVE_TABLES, sn as FieldDecryptionError, Bo as ID_COLUMN_MAX_LENGTH, Ft as INITIAL_VERSION, Va as MATCHES_NO_ROWS, Ct as MAX_IDENTIFIER_LENGTH, ks as MSSQL_TRANSIENT_NUMBERS, Ds as MYSQL_TRANSIENT_CODES, ho as OccurrenceCounter, Os as POSTGRES_TRANSIENT_STATES, Zc as REPLACE_IN_PROGRESS_TABLE, Kl as SCOPE_KEY_MAX_LENGTH, ae as SELF_REFERENCE_TARGET, As as SQLITE_TRANSIENT_CODES, $c as STAGING_STALE_MINUTES, dt as STAGING_TABLE_PREFIX, Yt as SqlClient, js as TURSO_TRANSIENT_MESSAGE, Hs as TableStreamError, $r as TenantNamespaceInvalid, Qr as TenantNamespaceUnresolved, bc as TenantRegionUnavailable, yc as TenantResidencyUnresolved, Is as VOLTRO_EXPIRES_MIXIN_ID, Rs as VOLTRO_LOCAL_FIRST_MIXIN_ID, Mt as VersionConflict, Ot as WARN_IDENTIFIER_LENGTH, Jc as _voltroApiKeysTable, Vl as _voltroCdcOffsetsTable, Wl as _voltroDataTransfersTable, Kc as _voltroIdempotencyTable, qc as _voltroKvTable, Gc as _voltroMigrationPlansTable, Uc as _voltroMigrationsTable, Hl as _voltroMssqlCdcOffsetsTable, Qc as _voltroReplaceInProgressTable, Yc as _voltroReplicaObservationsTable, Wc as _voltroSeedsTable, Da as actorsTable, pc as admitBranch, Ke as agedSoftDropSnapshots, ve as allEnumRenames, lr as allRegisteredRelations, te as allRegisteredTables, Ga as and, Lr as applyJsonPatch, oe as array, Ra as arrayContains, Ba as arrayHas, za as arrayOverlaps, Vr as attachEagerLoads, So as attributionFields, Eo as attributionKey, Pc as auditAllTableIndexes, Nc as auditTableIndexes, wt as avg, _e as avgOver, Fo as beginLocalWrite, ue as bigint, Oc as bindResidentStore, p as boolean, Zs as branchNamespaceName, ll as bulkInsertLimitsFor, ee as bytes, bn as causeBranches, co as changeDelete, fo as changeDigest, oo as changeInsert, lo as changeSoftDelete, so as changeUpdate, dl as chunkRowsForInsert, ko as claimPendingAttribution, An as classifyConstraintViolation, d as clearEnumRenames, Ro as clearPendingAttribution, dr as clearRelationsRegistry, wc as clearResidencyConfig, Fl as clearRetentions, Ee as clearTableRegistry, qo as clearWriteRecorders, G as coercePredicateForSqlite, si as coercePredicateValue, ci as coercePredicateValues, ya as coerceValueForSqlite, ro as collectSubqueries, u as column, zn as columnSchema, ul as columnsPerRow, Si as compileEagerJson, Rr as compileJsonPatch, R as compilePredicate, li as compileRawFragment, xi as compileSelect, po as composeChangeKey, qs as computeEmbedding, Dl as connectionIdentity, Ia as contains, c as count, se as countDistinct, ie as crdtDoc, me as crdtManagedColumns, At as crdtManagedColumnsOf, a as crdtText, xo as currentWriteAttribution, Ze as databaseHandle, Se as date, _ as dbEnum, fs as dbMetricTagCacheSizeForTests, hs as dbOperationsInFlight, be as decimal, l as declareEnumRename, fn as decodeFieldValue, Er as decodeRowsFromSchema, vn as decryptFieldsOnRead, Vc as defineMigration, xt as defineMixin, ct as defineSeed, n as denseRank, yr as deriveSubjectGraph, lt as deriveTypeIdPrefix, Uo as derivedRowId, Wo as derivedRowIdLength, je as describeAgedSoftDropSnapshots, Nn as describeDriverError, Pn as describeRowBindings, Gl as describeTransferRun, tn as deserializeArraysOnRead, Pe as drainIdentifierWarnings, we as dropped, un as encodeFieldValue, Or as encodeRowForSchema, _n as encryptFieldsForWrite, hn as encryptedColumnsOf, Io as endLocalWrite, uc as enforceBranchLimits, Te as ensureTableRegistered, Oa as eq, ui as escapeLike, no as evaluatePredicate, Ye as except, Qa as exists, Ls as expires, ao as externalChangeEvent, Cn as extractDbCause, an as fieldBinding, tt as fireSchemaChangeSeeds, We as fireTenantCreateSeeds, zc as formatIndexAuditIssue, br as formatSubjectGraph, Xc as frameworkTables, nt as generateId, Ue as generateSnowflake, h as geography, re as geometry, ce as getEnumRenames, cr as getRelation, sr as getRelations, Cc as getResidencyConfig, w as getTable, Aa as gt, ja as gte, Zr as hasEagerLoads, Ks as hybridSearch, O as id, Pa as inSet, Xa as inSubquery, Qn as inferForeignKey, vl as insertIgnoreRowOutcome, hl as insertManyRows, ml as insertRow, y as integer, nl as interruptedReplaceRefusal, x as intersect, De as interval, on as isBoundCiphertext, Qs as isBranchNamespace, Nr as isCompositeRowKey, qn as isEmptyRelationsSpec, ln as isEncrypted, cn as isFieldDecryptionError, Ie as isFileMigration, jn as isForeignKeyViolation, ot as isFrameworkOwnedLiveTable, Bs as isLocalFirst, Hc as isMigrationDefinition, pt as isMysqlFamily, ic as isNeonConnection, Ua as isNotNull, Ha as isNull, Cl as isPrimaryKeyConflictError, Mn as isQueryTimeout, pn as isRawEncoding, Ec as isRegionServable, Jn as isRelationsSpec, He as isSeedDefinition, mt as isSoftDropSnapshotName, Je as isSqliteFamily, Fe as isStagingTableName, de as isTableReactive, Ps as isTransientContention, Ne as isView, C as json, Ja as jsonField, gt as jsonIndex, Pr as jsonPatchAssignments, S as lag, le as lead, Ml as listRetentionConflicts, Pl as listRetentions, zs as localFirst, Vs as localFirstTables, Ma as lt, Na as lte, xs as makeEagerFallbackReporter, vc as makeNamespaceBranchExecutor, Xn as many, Zn as manyToMany, Oe as materializeFields, f as max, Be as migration, v as min, pl as missingConflictColumns, fl as missingRequiredColumns, Le as mixin, ka as neq, tc as nextBranchState, El as normaliseTarget, Ir as normalizeJsonPatchValue, qa as not, $a as notExists, Fa as notInSet, Za as notInSubquery, fe as numeric, _s as observeDbOp, vo as occurrenceWindowMs, Yn as one, Br as oneCardinalityMessage, Ka as or, b as orderClausesOf, pe as paginateBy, kt as paginateById, mo as parseChangeKey, zo as pendingAttributionCount, cc as planBranch, nc as planBranchProvision, rc as planBranchTeardown, lc as planBranchTeardownFor, oc as planNeonBranchProvision, sc as planNeonBranchTeardown, jt as planVersionedUpdate, Qe as pluginRef, r as pluginRefSpecOf, Sl as primaryKeyConflictError, dc as provisionBranch, kc as provisionResidentTenant, ii as qualifyTable, i as queryFor, Et as queryForView, Me as quoteIdent, xl as raiseChangeListenerCeiling, xe as rank, t as raw, Re as readableByColumns, vt as real, gs as recordDbOp, Qo as recordsTable, it as reference, Ln as refuseWrite, Ca as registerCoreTables, or as registerDiscoveredRelations, Oo as registerPendingAttribution, ar as registerRelations, Nl as registerRetention, e as registerTable, Go as registerWriteRecorder, Kn as relations, Ta as requireActors, ze as requireTable, Ea as requireTenants, ds as resetDbMetricTagCacheForTests, Ae as resetSnowflake, Dc as residentPlacement, Zt as resolveActorSnapshot, ac as resolveBranchMechanism, bs as resolveEagerFallbackWarnIntervalMs, Lo as resolveEchoAttribution, g as resolveFullTextIndex, Ge as resolveIdScheme, Ve as resolveMixinGraph, Tc as resolveTenantHome, ri as resolveTenantNamespace, zl as retentionTtlMsFromEnv, jr as rowKeyColumns, Mr as rowKeyIdentity, ye as rowNumber, Bn as rowSchema, Ts as runRetryingTransaction, Es as runStoreTransaction, bo as runWithWriteAttribution, $o as runWriteRecorders, Ol as sameDatabase, ni as sanitizeIdentifierFragment, Jl as scopeKeyOf, ft as selfReference, en as serializeArraysForWrite, qe as serverOnlyColumns, Sc as setResidencyConfig, ke as setSchemaChangeSeedHook, St as setTenantCreateSeedHook, Ss as settleTransactionExit, Pt as settleVersionedUpdate, $e as softDropSnapshotStamp, Wa as spatialPredicate, il as stagingLeftoverReport, rl as stagingLeftovers, tl as stagingNamesOf, el as stagingStaleAfterMs, ol as stampGeneratedId, sl as stampGeneratedIds, La as startsWith, Rn as storeRefusalOf, Gs as streamTable, Ce as sum, m as sumOver, Yo as suspendWriteRecorders, Xo as suspendWriteRecordersEffect, Il as sweepRetention, E as table, fc as teardownBranch, T as text, D as timestamp, Lt as timestampMs, Nt as timestampMsOrNull, ne as union, ut as unionAll, yt as unregisterTable, Ko as unregisterWriteRecorder, yl as updateManyRow, gl as upsertRow, _l as upsertRowOutcome, Ar as upsertUpdatePatch, kr as upsertUpdateValues, Dt as validateColumnName, ge as validateIndexName, ur as validateRegisteredRelations, nr as validateRelationConfig, s as validateTableName, Tt as validateTypeIdPrefix, ht as vector, et as vectorDistanceToOpclass, Js as vectorEmbedding, It as versionColumnOf, he as view, o as viewSql, io as walkLeaves, wn as wireSafeCause, Co as withCapturedAttribution, Zo as writeRecordersSuspended };