@voltro/database 0.45.0 → 0.47.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,13 +1,13 @@
1
- import { $ as e, A as t, At as n, B as r, Bt as i, C as a, Ct as o, D as s, Dt as c, E as l, Et as u, F as d, Ft as f, G as p, Gt as m, H as h, Ht as g, I as ee, It as te, J as _, Jt as v, K as ne, Kt as y, L as re, Lt as b, M as ie, Mt as ae, N as oe, Nt as se, O as ce, Ot as le, P as ue, Pt as de, Q as fe, R as pe, Rt as x, S as me, St as he, T as ge, Tt as _e, U as ve, Ut as ye, V as be, Vt as xe, W as Se, Wt as Ce, X as we, Xt as Te, Y as Ee, Yt as S, Z as De, _ as Oe, _t as ke, a as Ae, at as je, b as Me, bt as Ne, c as Pe, ct as Fe, d as Ie, dt as Le, et as Re, f as ze, ft as Be, g as Ve, gt as He, h as Ue, ht as We, i as Ge, it as Ke, j as C, jt as qe, k as Je, kt as Ye, l as Xe, lt as Ze, m as Qe, mt as $e, n as et, nt as tt, o as nt, ot as rt, p as w, pt as it, q as at, qt as ot, rt as st, s as ct, st as lt, t as ut, tt as T, u as dt, ut as ft, v as pt, vt as mt, w as ht, wt as gt, x as _t, xt as vt, y as yt, yt as bt, z as xt, zt as St } from "./frameworkLiveTables-XPFqj8n3.js";
2
- import { timestampMs as Ct, timestampMsOrNull as wt } from "./wire.js";
3
- import { Cause as Tt, Chunk as Et, Data as Dt, Effect as E, Exit as Ot, Metric as D, MetricBoundaries as kt, Option as O, Runtime as At, Schedule as jt, Schema as k, Stream as Mt } from "effect";
4
- import { AsyncLocalStorage as Nt } from "node:async_hooks";
5
- import { createHash as Pt } from "node:crypto";
6
- import { TransactionConnection as Ft } from "@effect/sql/SqlClient";
7
- import { ansi as A } from "@voltro/logger";
8
- import { SqlClient as It } from "@effect/sql";
1
+ import { $ as e, A as t, At as n, B as r, Bt as i, C as a, Ct as o, D as s, Dt as c, E as l, Et as u, F as d, Ft as f, G as p, Gt as m, H as h, Ht as g, I as _, It as ee, J as v, Jt as te, K as ne, Kt as y, L as re, Lt as b, M as ie, Mt as ae, N as oe, Nt as se, O as ce, Ot as le, P as ue, Pt as de, Q as fe, R as pe, Rt as x, S as me, St as he, T as ge, Tt as _e, U as ve, Ut as ye, V as be, Vt as S, W as xe, Wt as Se, X as Ce, Xt as C, Y as we, Yt as w, Z as Te, Zt as Ee, _ as De, _t as Oe, a as ke, at as Ae, b as je, bt as Me, c as Ne, ct as Pe, d as Fe, dt as Ie, et as Le, f as Re, ft as ze, g as Be, gt as Ve, h as He, ht as Ue, i as We, it as Ge, j as T, jt as Ke, k as qe, kt as Je, l as Ye, lt as Xe, m as Ze, mt as Qe, n as $e, nt as E, o as et, ot as tt, p as D, pt as nt, q as rt, qt as it, rt as at, s as ot, st, t as ct, tt as lt, u as ut, ut as dt, v as ft, vt as pt, w as mt, wt as ht, x as gt, xt as _t, y as vt, yt, z as bt, zt as O } from "./frameworkLiveTables-DNu6F6P8.js";
2
+ import { timestampMs as xt, timestampMsOrNull as St } from "./wire.js";
3
+ import { Cause as Ct, Chunk as wt, Data as Tt, Effect as k, Exit as Et, Metric as A, MetricBoundaries as Dt, Option as j, Runtime as Ot, Schedule as kt, Schema as M, Stream as At } from "effect";
4
+ import { AsyncLocalStorage as jt } from "node:async_hooks";
5
+ import { createHash as Mt } from "node:crypto";
6
+ import { TransactionConnection as Nt } from "@effect/sql/SqlClient";
7
+ import { ansi as N } from "@voltro/logger";
8
+ import { SqlClient as Pt } from "@effect/sql";
9
9
  //#region src/actorSnapshot.ts
10
- var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n) => {
10
+ var Ft = (e) => typeof e == "string" && e !== "" ? e : null, It = 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 Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
23
23
  }))[0];
24
24
  return r === void 0 ? void 0 : {
25
25
  id: t,
26
- type: Lt(r.kind) ?? n,
27
- displayName: Lt(r.displayName),
28
- email: Lt(r.email)
26
+ type: Ft(r.kind) ?? n,
27
+ displayName: Ft(r.displayName),
28
+ email: Ft(r.email)
29
29
  };
30
30
  } catch {
31
31
  return;
32
32
  }
33
- }, zt = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqlite", Bt = (e) => {
33
+ }, Lt = (e) => e === "mysql" || e === "mariadb" || e === "mssql" || e === "sqlite", Rt = (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
- }, Vt = (e, t, n) => {
38
- if (!zt(n) || !t) return e;
39
- let r = Bt(t);
37
+ }, zt = (e, t, n) => {
38
+ if (!Lt(n) || !t) return e;
39
+ let r = Rt(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 Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
44
44
  Array.isArray(t) && (i[e] = JSON.stringify(t));
45
45
  }
46
46
  return i;
47
- }, Ht = (e, t, n) => {
48
- if (!zt(n) || !t) return e;
49
- let r = Bt(t);
47
+ }, Bt = (e, t, n) => {
48
+ if (!Lt(n) || !t) return e;
49
+ let r = Rt(t);
50
50
  return r.length === 0 ? e : e.map((e) => {
51
51
  let t;
52
52
  for (let n of r) {
@@ -58,7 +58,7 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
58
58
  }
59
59
  return t ?? e;
60
60
  });
61
- }, Ut = "enc:v1:", Wt = class extends Error {
61
+ }, Vt = "enc:v1:", Ht = class extends Error {
62
62
  _tag = "FieldDecryptionError";
63
63
  table;
64
64
  column;
@@ -66,7 +66,7 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
66
66
  constructor(e) {
67
67
  super(`column "${e.table}.${e.column}" is .encrypted() but could not be decrypted (${e.reason}) — the stored value was most likely encrypted under a different key`), this.name = "FieldDecryptionError", this.table = e.table, this.column = e.column, this.reason = e.reason;
68
68
  }
69
- }, Gt = (e) => typeof e == "object" && !!e && e._tag === "FieldDecryptionError", Kt = (e) => typeof e == "string" && e.startsWith("enc:v1:"), qt = (e, t) => e.encrypt(JSON.stringify(t)), Jt = /* @__PURE__ */ new Set([
69
+ }, Ut = (e) => typeof e == "object" && !!e && e._tag === "FieldDecryptionError", Wt = (e) => typeof e == "string" && e.startsWith("enc:v1:"), Gt = (e, t) => e.encrypt(JSON.stringify(t)), Kt = /* @__PURE__ */ new Set([
70
70
  "text",
71
71
  "id",
72
72
  "reference",
@@ -74,51 +74,51 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
74
74
  "uuid",
75
75
  "email",
76
76
  "url"
77
- ]), Yt = (e, t, n) => {
77
+ ]), qt = (e, t, n) => {
78
78
  let r = e.decrypt(t), i;
79
79
  try {
80
80
  i = JSON.parse(r);
81
81
  } catch {
82
82
  return r;
83
83
  }
84
- return typeof i == "string" ? i : n === void 0 || Jt.has(n) ? r : i;
85
- }, Xt = (e, t, n) => {
84
+ return typeof i == "string" ? i : n === void 0 || Kt.has(n) ? r : i;
85
+ }, Jt = (e, t, n) => {
86
86
  let r = e.decrypt(t);
87
87
  try {
88
- return typeof JSON.parse(r) == "string" ? !1 : n === void 0 || Jt.has(n) ? !0 : void 0;
88
+ return typeof JSON.parse(r) == "string" ? !1 : n === void 0 || Kt.has(n) ? !0 : void 0;
89
89
  } catch {
90
90
  return !0;
91
91
  }
92
- }, Zt = (e, t) => e.fields[t]?.type, Qt = (e) => {
92
+ }, Yt = (e, t) => e.fields[t]?.type, Xt = (e) => {
93
93
  let t = [];
94
94
  for (let [n, r] of Object.entries(e.fields)) r.encrypted === !0 && t.push(n);
95
95
  return t;
96
- }, $t = (e, t, n) => {
96
+ }, Zt = (e, t, n) => {
97
97
  if (!t) return e;
98
- let r = Qt(t);
98
+ let r = Xt(t);
99
99
  if (r.length === 0) return e;
100
100
  let i = { ...e };
101
101
  for (let e of r) {
102
102
  let r = i[e];
103
- if (!(r == null || Kt(r))) {
103
+ if (!(r == null || Wt(r))) {
104
104
  if (!n) throw Error(`column "${t.tableName ?? "?"}.${e}" is .encrypted() but no field cipher is registered — wire @voltro/plugin-governance's fieldEncryption (key via the Secrets-Resolver)`);
105
- i[e] = qt(n, r);
105
+ i[e] = Gt(n, r);
106
106
  }
107
107
  }
108
108
  return i;
109
- }, en = (e, t, n, r) => {
109
+ }, Qt = (e, t, n, r) => {
110
110
  if (!t) return e;
111
- let i = Qt(t);
111
+ let i = Xt(t);
112
112
  if (i.length === 0 || !n) return e;
113
113
  let a = r?.onError ?? "throw", o = t.tableName ?? "?";
114
114
  return e.map((e) => {
115
115
  let s;
116
116
  for (let c of i) {
117
117
  let i = e[c];
118
- if (Kt(i)) {
118
+ if (Wt(i)) {
119
119
  s ??= { ...e };
120
120
  try {
121
- s[c] = Yt(n, i, Zt(t, c));
121
+ s[c] = qt(n, i, Yt(t, c));
122
122
  } catch (e) {
123
123
  let t = String(e?.message ?? e);
124
124
  if (a === "null") {
@@ -129,7 +129,7 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
129
129
  });
130
130
  continue;
131
131
  }
132
- throw new Wt({
132
+ throw new Ht({
133
133
  table: o,
134
134
  column: c,
135
135
  reason: t
@@ -139,125 +139,125 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
139
139
  }
140
140
  return s ?? e;
141
141
  });
142
- }, tn = (e) => {
142
+ }, $t = (e) => {
143
143
  let t = e;
144
- for (let e = 0; e < 4 && At.isFiberFailure(t); e++) t = Tt.squash(t[At.FiberFailureCauseId]);
144
+ for (let e = 0; e < 4 && Ot.isFiberFailure(t); e++) t = Ct.squash(t[Ot.FiberFailureCauseId]);
145
145
  return t;
146
- }, nn = (e, t = 0) => {
147
- if (t >= 4 || !At.isFiberFailure(e)) return [e];
148
- let n = e[At.FiberFailureCauseId], r = [...Tt.failures(n), ...Tt.defects(n)];
149
- if (r.length === 0) return [Tt.squash(n)];
146
+ }, en = (e, t = 0) => {
147
+ if (t >= 4 || !Ot.isFiberFailure(e)) return [e];
148
+ let n = e[Ot.FiberFailureCauseId], r = [...Ct.failures(n), ...Ct.defects(n)];
149
+ if (r.length === 0) return [Ct.squash(n)];
150
150
  let i = [];
151
- for (let e of r.slice(0, 8)) i.push(...nn(e, t + 1));
151
+ for (let e of r.slice(0, 8)) i.push(...en(e, t + 1));
152
152
  return i;
153
- }, rn = (e) => e.dbCode !== void 0 || e.dbErrno !== void 0 || e.dbNumber !== void 0 || e.dbSqlState !== void 0 || e.dbConstraint !== void 0, an = (e) => {
154
- let t = {}, n = [], r = tn(e);
153
+ }, tn = (e) => e.dbCode !== void 0 || e.dbErrno !== void 0 || e.dbNumber !== void 0 || e.dbSqlState !== void 0 || e.dbConstraint !== void 0, nn = (e) => {
154
+ let t = {}, n = [], r = $t(e);
155
155
  for (let e = 0; e < 8 && typeof r == "object" && r; e++) {
156
156
  let e = r;
157
157
  t.dbCode === void 0 && (typeof e.code == "string" || typeof e.code == "number") && (t.dbCode = e.code), t.dbErrno === void 0 && typeof e.errno == "number" && (t.dbErrno = e.errno), t.dbNumber === void 0 && typeof e.number == "number" && (t.dbNumber = e.number), t.dbSqlState === void 0 && typeof e.sqlState == "string" && (t.dbSqlState = e.sqlState), t.dbBindings === void 0 && typeof e.voltroBindings == "string" && (t.dbBindings = e.voltroBindings), t.dbStatement === void 0 && typeof e.sql == "string" && e.sql.includes("?") && (t.dbStatement = e.sql, t.dbPlaceholders = (e.sql.match(/\?/g) ?? []).length), t.dbFatal === void 0 && typeof e.fatal == "boolean" && (t.dbFatal = e.fatal), t.dbConstraint === void 0 && typeof e.constraint == "string" && (t.dbConstraint = e.constraint), t.dbTable === void 0 && typeof e.table == "string" && (t.dbTable = e.table), t.dbColumn === void 0 && typeof e.column == "string" && (t.dbColumn = e.column), t.dbSchema === void 0 && typeof e.schema == "string" && (t.dbSchema = e.schema);
158
158
  let i = e.sqlMessage ?? e.detail;
159
159
  t.dbMessage === void 0 && typeof i == "string" && (t.dbMessage = i);
160
160
  let a = typeof e.constructor == "function" ? e.constructor.name : void 0, o = typeof e._tag == "string" && e._tag || typeof e.name == "string" && e.name || (typeof a == "string" && a !== "Object" ? a : void 0), s = typeof e.message == "string" ? e.message : void 0;
161
- (o || s) && n.push(`${o || "Error"}${s ? `: ${s.slice(0, 200)}` : ""}`), r = tn(e.cause);
161
+ (o || s) && n.push(`${o || "Error"}${s ? `: ${s.slice(0, 200)}` : ""}`), r = $t(e.cause);
162
162
  }
163
163
  return n.length > 0 && (t.dbCauseChain = n.join(" ← "), t.dbMessage === void 0 && (t.dbMessage = n[n.length - 1])), t;
164
- }, on = (e) => {
165
- let t = nn(e).map(an);
164
+ }, rn = (e) => {
165
+ let t = en(e).map(nn);
166
166
  if (t.length <= 1) return t[0] ?? {};
167
- let n = t.find(rn) ?? t[0], r = t.filter((e) => e !== n).map((e) => e.dbCauseChain).filter((e) => typeof e == "string");
167
+ let n = t.find(tn) ?? t[0], r = t.filter((e) => e !== n).map((e) => e.dbCauseChain).filter((e) => typeof e == "string");
168
168
  if (r.length === 0) return n;
169
169
  let i = typeof n.dbCauseChain == "string" ? n.dbCauseChain : void 0;
170
170
  return {
171
171
  ...n,
172
172
  dbCauseChain: [i, ...r].filter(Boolean).join(" ‖ ")
173
173
  };
174
- }, sn = /^[A-Za-z_][A-Za-z0-9_$]*$/, j = (e) => e !== void 0 && e.length <= 128 && sn.test(e) ? e : void 0, cn = (e) => e === void 0 ? void 0 : e.split(".").pop() ?? e, M = (e, ...t) => {
174
+ }, an = /^[A-Za-z_][A-Za-z0-9_$]*$/, P = (e) => e !== void 0 && e.length <= 128 && an.test(e) ? e : void 0, on = (e) => e === void 0 ? void 0 : e.split(".").pop() ?? e, F = (e, ...t) => {
175
175
  for (let n of t) {
176
176
  let t = n.exec(e);
177
177
  if (t?.[1] !== void 0) return t[1];
178
178
  }
179
- }, ln = (e, t) => {
179
+ }, sn = (e, t) => {
180
180
  let n = e.dbCode, r = e.dbErrno, i = e.dbNumber, a = typeof e.dbMessage == "string" ? e.dbMessage : "", o = `${typeof e.dbCauseChain == "string" ? e.dbCauseChain : ""} ${a}`;
181
181
  if (n === "23503") {
182
- let t = j(e.dbConstraint);
182
+ let t = P(e.dbConstraint);
183
183
  return {
184
184
  kind: /is still referenced from table/i.test(o) ? "foreignKeyInUse" : "foreignKey",
185
185
  ...t === void 0 ? {} : { constraint: t }
186
186
  };
187
187
  }
188
188
  if (n === "23505") {
189
- let t = j(e.dbConstraint);
189
+ let t = P(e.dbConstraint);
190
190
  return {
191
191
  kind: "unique",
192
192
  ...t === void 0 ? {} : { constraint: t }
193
193
  };
194
194
  }
195
195
  if (n === "23502") {
196
- let t = j(e.dbColumn);
196
+ let t = P(e.dbColumn);
197
197
  return {
198
198
  kind: "notNull",
199
199
  ...t === void 0 ? {} : { column: t }
200
200
  };
201
201
  }
202
202
  if (n === "23514") {
203
- let t = j(e.dbConstraint);
203
+ let t = P(e.dbConstraint);
204
204
  return {
205
205
  kind: "check",
206
206
  ...t === void 0 ? {} : { constraint: t }
207
207
  };
208
208
  }
209
209
  if (r === 1452 || r === 1451) {
210
- let e = j(M(o, /CONSTRAINT `([^`]+)`/));
210
+ let e = P(F(o, /CONSTRAINT `([^`]+)`/));
211
211
  return {
212
212
  kind: r === 1451 ? "foreignKeyInUse" : "foreignKey",
213
213
  ...e === void 0 ? {} : { constraint: e }
214
214
  };
215
215
  }
216
216
  if (r === 1062) {
217
- let e = j(cn(M(o, /for key '([^']+)'/)));
217
+ let e = P(on(F(o, /for key '([^']+)'/)));
218
218
  return {
219
219
  kind: "unique",
220
220
  ...e === void 0 ? {} : { constraint: e }
221
221
  };
222
222
  }
223
223
  if (r === 1048 || r === 1364) {
224
- let e = j(M(o, /Column '([^']+)' cannot be null/, /Field '([^']+)' doesn't have a default value/));
224
+ let e = P(F(o, /Column '([^']+)' cannot be null/, /Field '([^']+)' doesn't have a default value/));
225
225
  return {
226
226
  kind: "notNull",
227
227
  ...e === void 0 ? {} : { column: e }
228
228
  };
229
229
  }
230
230
  if (r === 3819 || r === 4025) {
231
- let e = j(M(o, /Check constraint '([^']+)'/, /CONSTRAINT `([^`]+)` failed/));
231
+ let e = P(F(o, /Check constraint '([^']+)'/, /CONSTRAINT `([^`]+)` failed/));
232
232
  return {
233
233
  kind: "check",
234
234
  ...e === void 0 ? {} : { constraint: e }
235
235
  };
236
236
  }
237
237
  if (i === 547) {
238
- let e = M(o, /(?:FOREIGN KEY|REFERENCE) constraint "([^"]+)"/), t = M(o, /CHECK constraint "([^"]+)"/);
238
+ let e = F(o, /(?:FOREIGN KEY|REFERENCE) constraint "([^"]+)"/), t = F(o, /CHECK constraint "([^"]+)"/);
239
239
  if (t !== void 0 && e === void 0) {
240
- let e = j(t);
240
+ let e = P(t);
241
241
  return {
242
242
  kind: "check",
243
243
  ...e === void 0 ? {} : { constraint: e }
244
244
  };
245
245
  }
246
- let n = /REFERENCE constraint/.test(o), r = j(e);
246
+ let n = /REFERENCE constraint/.test(o), r = P(e);
247
247
  return {
248
248
  kind: n ? "foreignKeyInUse" : "foreignKey",
249
249
  ...r === void 0 ? {} : { constraint: r }
250
250
  };
251
251
  }
252
252
  if (i === 2627 || i === 2601) {
253
- let e = j(M(o, /(?:UNIQUE KEY|PRIMARY KEY) constraint '([^']+)'/, /index '([^']+)'/));
253
+ let e = P(F(o, /(?:UNIQUE KEY|PRIMARY KEY) constraint '([^']+)'/, /index '([^']+)'/));
254
254
  return {
255
255
  kind: "unique",
256
256
  ...e === void 0 ? {} : { constraint: e }
257
257
  };
258
258
  }
259
259
  if (i === 515) {
260
- let e = j(M(o, /Cannot insert the value NULL into column '([^']+)'/));
260
+ let e = P(F(o, /Cannot insert the value NULL into column '([^']+)'/));
261
261
  return {
262
262
  kind: "notNull",
263
263
  ...e === void 0 ? {} : { column: e }
@@ -265,34 +265,34 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
265
265
  }
266
266
  if (n === "SQLITE_CONSTRAINT_FOREIGNKEY") return { kind: t === "delete" || t === "deleteMany" || t === "hardDelete" ? "foreignKeyInUse" : "foreignKey" };
267
267
  if (n === "SQLITE_CONSTRAINT_UNIQUE" || n === "SQLITE_CONSTRAINT_PRIMARYKEY") {
268
- let e = j(cn(M(o, /UNIQUE constraint failed: ([^,\s]+)/)));
268
+ let e = P(on(F(o, /UNIQUE constraint failed: ([^,\s]+)/)));
269
269
  return {
270
270
  kind: "unique",
271
271
  ...e === void 0 ? {} : { column: e }
272
272
  };
273
273
  }
274
274
  if (n === "SQLITE_CONSTRAINT_NOTNULL") {
275
- let e = j(cn(M(o, /NOT NULL constraint failed: ([^,\s]+)/)));
275
+ let e = P(on(F(o, /NOT NULL constraint failed: ([^,\s]+)/)));
276
276
  return {
277
277
  kind: "notNull",
278
278
  ...e === void 0 ? {} : { column: e }
279
279
  };
280
280
  }
281
281
  if (n === "SQLITE_CONSTRAINT_CHECK") {
282
- let e = j(M(a, /CHECK constraint failed: (.+)$/));
282
+ let e = P(F(a, /CHECK constraint failed: (.+)$/));
283
283
  return {
284
284
  kind: "check",
285
285
  ...e === void 0 ? {} : { constraint: e }
286
286
  };
287
287
  }
288
- }, un = (e) => {
289
- let t = ln(e)?.kind;
288
+ }, cn = (e) => {
289
+ let t = sn(e)?.kind;
290
290
  return t === "foreignKey" || t === "foreignKeyInUse";
291
- }, dn = (e) => {
291
+ }, ln = (e) => {
292
292
  let t = e.dbCode, n = e.dbErrno;
293
293
  return t === "57014" || n === 3024 || n === 1969 || t === "ETIMEOUT" || t === "SQLITE_INTERRUPT";
294
- }, fn = (e) => {
295
- let t = on(e), n = [
294
+ }, un = (e) => {
295
+ let t = rn(e), n = [
296
296
  t.dbCode === void 0 ? void 0 : `code=${String(t.dbCode)}`,
297
297
  t.dbErrno === void 0 ? void 0 : `errno=${String(t.dbErrno)}`,
298
298
  t.dbNumber === void 0 ? void 0 : `number=${String(t.dbNumber)}`,
@@ -301,7 +301,7 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
301
301
  t.dbPlaceholders === void 0 ? void 0 : `placeholders=${String(t.dbPlaceholders)}`
302
302
  ].filter((e) => e !== void 0), r = typeof e?.message == "string" ? e.message : void 0, i = typeof t.dbMessage == "string" ? t.dbMessage : void 0, a = i === void 0 ? void 0 : n.length > 0 || i !== r && i !== `Error: ${String(r)}` ? i : void 0, o = typeof t.dbBindings == "string" ? `\n bindings: ${t.dbBindings}` : "", s = typeof t.dbStatement == "string" ? `\n statement: ${t.dbStatement.length <= 400 ? t.dbStatement : `${t.dbStatement.slice(0, 400)}…`}` : "";
303
303
  if (a !== void 0 || n.length !== 0) return [a, n.length > 0 ? `[${n.join(" ")}]` : void 0].filter((e) => e !== void 0 && e !== "").join(" ") + s + o;
304
- }, pn = (e) => Object.entries(e).map(([e, t]) => `${e}:${mn(t)}`).join(" "), mn = (e) => {
304
+ }, dn = (e) => Object.entries(e).map(([e, t]) => `${e}:${fn(t)}`).join(" "), fn = (e) => {
305
305
  if (e === null) return "null";
306
306
  if (e === void 0) return "undefined";
307
307
  if (typeof e == "bigint") return "bigint";
@@ -311,62 +311,62 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
311
311
  if (globalThis.Buffer !== void 0 && globalThis.Buffer.isBuffer(e)) return "Buffer";
312
312
  let t = e.constructor?.name;
313
313
  return typeof t == "string" && t !== "" ? t : "Object";
314
- }, hn = (e) => {
314
+ }, pn = (e) => {
315
315
  let t = (() => {
316
316
  switch (e.type) {
317
317
  case "id":
318
318
  case "reference":
319
319
  case "text":
320
- case "enum": return k.String;
320
+ case "enum": return M.String;
321
321
  case "integer":
322
322
  case "real":
323
- case "decimal": return k.Number;
324
- case "boolean": return k.Boolean;
323
+ case "decimal": return M.Number;
324
+ case "boolean": return M.Boolean;
325
325
  case "timestamp":
326
- case "date": return Ct;
327
- case "bigint": return k.BigInt;
328
- case "bytes": return k.Uint8ArrayFromBase64;
329
- case "array": return k.Array(k.Unknown);
330
- case "interval": return k.String;
331
- default: return k.Unknown;
326
+ case "date": return xt;
327
+ case "bigint": return M.BigInt;
328
+ case "bytes": return M.Uint8ArrayFromBase64;
329
+ case "array": return M.Array(M.Unknown);
330
+ case "interval": return M.String;
331
+ default: return M.Unknown;
332
332
  }
333
333
  })();
334
- return e.nullable === !0 ? k.NullOr(t) : t;
335
- }, gn = (e, t) => {
334
+ return e.nullable === !0 ? M.NullOr(t) : t;
335
+ }, mn = (e, t) => {
336
336
  let n = new Set(t?.omit ?? []), r = {};
337
- for (let [t, i] of Object.entries(e.fields)) n.has(t) || (r[t] = hn(i));
338
- return k.Struct(r);
339
- }, _n = (e) => typeof e == "function" ? e : () => e, vn = (e, t) => ({
337
+ for (let [t, i] of Object.entries(e.fields)) n.has(t) || (r[t] = pn(i));
338
+ return M.Struct(r);
339
+ }, hn = (e) => typeof e == "function" ? e : () => e, gn = (e, t) => ({
340
340
  kind: "one",
341
- target: _n(e),
341
+ target: hn(e),
342
342
  ...t?.foreignKey === void 0 ? {} : { foreignKey: t.foreignKey },
343
343
  ...t?.sourceKey === void 0 ? {} : { sourceKey: t.sourceKey }
344
- }), yn = (e, t) => ({
344
+ }), _n = (e, t) => ({
345
345
  kind: "many",
346
- target: _n(e),
346
+ target: hn(e),
347
347
  ...t?.foreignKey === void 0 ? {} : { foreignKey: t.foreignKey },
348
348
  ...t?.sourceKey === void 0 ? {} : { sourceKey: t.sourceKey }
349
- }), bn = (e, t) => ({
349
+ }), vn = (e, t) => ({
350
350
  kind: "manyToMany",
351
- target: _n(e),
352
- through: _n(t.through),
351
+ target: hn(e),
352
+ through: hn(t.through),
353
353
  sourceKey: t.sourceKey,
354
354
  targetKey: t.targetKey
355
- }), xn = {
356
- one: vn,
357
- many: yn,
358
- manyToMany: bn
359
- }, Sn = (e, t) => {
355
+ }), yn = {
356
+ one: gn,
357
+ many: _n,
358
+ manyToMany: vn
359
+ }, bn = (e, t) => {
360
360
  let n = typeof e == "function" ? e : () => e;
361
361
  return {
362
362
  source: n,
363
- relations: t(xn, n())
363
+ relations: t(yn, n())
364
364
  };
365
- }, Cn = (e) => {
365
+ }, xn = (e) => {
366
366
  if (typeof e != "object" || !e) return !1;
367
367
  let t = e;
368
368
  return typeof t.source != "function" || typeof t.relations != "object" || t.relations === null ? !1 : Object.keys(t.relations).length === 0;
369
- }, wn = (e) => {
369
+ }, Sn = (e) => {
370
370
  if (typeof e != "object" || !e) return !1;
371
371
  let t = e;
372
372
  if (typeof t.source != "function" || typeof t.relations != "object" || t.relations === null) return !1;
@@ -375,35 +375,35 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
375
375
  let t = e?.kind;
376
376
  return t === "one" || t === "many" || t === "manyToMany";
377
377
  });
378
- }, Tn = vn, En = yn, Dn = bn, N = (e, t, n) => {
378
+ }, Cn = gn, wn = _n, Tn = vn, En = (e, t, n) => {
379
379
  let r = [];
380
380
  for (let [n, i] of Object.entries(e.fields)) i.type === "reference" && i.references?.()?.tableName === t && r.push(n);
381
381
  if (r.length === 0) throw Error(`relation '${n}': no reference() column on '${e.tableName}' points at '${t}'. Either add one or pass an explicit { foreignKey: '<column>' }.`);
382
382
  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.`);
383
383
  return r[0];
384
- }, On = (e) => Object.keys(e.fields), P = (e, t) => Object.prototype.hasOwnProperty.call(e.fields, t), kn = (e) => {
385
- let t = On(e);
384
+ }, Dn = (e) => Object.keys(e.fields), On = (e, t) => Object.prototype.hasOwnProperty.call(e.fields, t), kn = (e) => {
385
+ let t = Dn(e);
386
386
  return t.length === 0 ? "<none>" : t.join(", ");
387
387
  }, An = (e, t, n) => {
388
388
  let r = `relation '${t}' on '${e.tableName}'`, i = n.target();
389
389
  if (n.kind === "manyToMany") {
390
390
  let t = n.through();
391
- for (let [a, o] of [["sourceKey", n.sourceKey], ["targetKey", n.targetKey]]) if (!P(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}': ${kn(t)}.`);
391
+ for (let [a, o] of [["sourceKey", n.sourceKey], ["targetKey", n.targetKey]]) if (!On(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}': ${kn(t)}.`);
392
392
  return;
393
393
  }
394
394
  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.`);
395
- if (n.sourceKey !== void 0 && !P(e, n.sourceKey)) {
396
- let t = P(i, n.sourceKey);
395
+ if (n.sourceKey !== void 0 && !On(e, n.sourceKey)) {
396
+ let t = On(i, n.sourceKey);
397
397
  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}': ${kn(e)}.`));
398
398
  }
399
- if (n.foreignKey !== void 0 && !P(i, n.foreignKey)) {
400
- let t = P(e, n.foreignKey);
399
+ if (n.foreignKey !== void 0 && !On(i, n.foreignKey)) {
400
+ let t = On(e, n.foreignKey);
401
401
  throw Error(`${r}: foreignKey '${n.foreignKey}' is not a column on the target table '${i.tableName}'.` + (t ? ` It IS a column on the source '${e.tableName}' — you want { sourceKey: '${n.foreignKey}' }. foreignKey names the column on the TARGET that points back at this table; sourceKey names the column on THIS table that holds the target's id.` : ` Columns on '${i.tableName}': ${kn(i)}.`));
402
402
  }
403
- }, jn = Symbol.for("@voltro/database/relationsRegistry"), Mn = globalThis, F = Mn[jn] ?? (Mn[jn] = /* @__PURE__ */ new Map()), Nn = (e) => {
404
- let t = e.source(), n = F.get(t.tableName);
403
+ }, jn = Symbol.for("@voltro/database/relationsRegistry"), Mn = globalThis, I = Mn[jn] ?? (Mn[jn] = /* @__PURE__ */ new Map()), Nn = (e) => {
404
+ let t = e.source(), n = I.get(t.tableName);
405
405
  if (n === void 0) {
406
- F.set(t.tableName, new Map(Object.entries(e.relations)));
406
+ I.set(t.tableName, new Map(Object.entries(e.relations)));
407
407
  return;
408
408
  }
409
409
  for (let [r, i] of Object.entries(e.relations)) {
@@ -415,26 +415,26 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
415
415
  }
416
416
  }, Pn = (e) => {
417
417
  let t = 0;
418
- for (let n of Object.values(e)) wn(n) && (Nn(n), t += 1);
418
+ for (let n of Object.values(e)) Sn(n) && (Nn(n), t += 1);
419
419
  return t;
420
420
  }, Fn = (e) => {
421
- let t = F.get(e);
421
+ let t = I.get(e);
422
422
  if (t !== void 0) return Object.fromEntries(t);
423
- }, In = (e, t) => F.get(e)?.get(t), Ln = () => {
423
+ }, In = (e, t) => I.get(e)?.get(t), Ln = () => {
424
424
  let e = [];
425
- for (let [t, n] of F) for (let [r, i] of n) e.push({
425
+ for (let [t, n] of I) for (let [r, i] of n) e.push({
426
426
  source: t,
427
427
  name: r,
428
428
  relation: i
429
429
  });
430
430
  return e;
431
431
  }, Rn = () => {
432
- for (let [e, t] of F) {
432
+ for (let [e, t] of I) {
433
433
  let n = p(e);
434
434
  if (n !== void 0) for (let [e, r] of t) An(n, e, r);
435
435
  }
436
436
  }, zn = () => {
437
- F.clear();
437
+ I.clear();
438
438
  }, Bn = 4, Vn = (e) => Object.keys(e.fields), Hn = (e, t) => Object.prototype.hasOwnProperty.call(e.fields, t), Un = (e, t) => {
439
439
  let n = [];
440
440
  for (let [r, i] of Object.entries(e.fields)) i.type === "reference" && i.references?.()?.tableName === t && n.push(r);
@@ -662,7 +662,7 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
662
662
  await mr(i, r.with, o, a);
663
663
  return;
664
664
  }
665
- let c = n.foreignKey ?? N(o, i.tableName, t), l = n.sourceKey ?? "id", u = fr(e, l), d = u.length === 0 ? [] : await pr(o, c, u, r, a), f = /* @__PURE__ */ new Map();
665
+ let c = n.foreignKey ?? En(o, i.tableName, t), l = n.sourceKey ?? "id", u = fr(e, l), d = u.length === 0 ? [] : await pr(o, c, u, r, a), f = /* @__PURE__ */ new Map();
666
666
  for (let e of d) {
667
667
  let n = e[c];
668
668
  if (f.has(n)) throw new rr(ir({
@@ -680,7 +680,7 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
680
680
  }
681
681
  await mr(d, r.with, o, a);
682
682
  }, cr = async (e, t, n, r, i, a) => {
683
- let o = n.target(), s = n.foreignKey ?? N(o, i.tableName, t), c = n.sourceKey ?? "id", l = fr(e, c), u = lr(r), d = l.length === 0 ? [] : await pr(o, s, l, u, a), f = /* @__PURE__ */ new Map();
683
+ let o = n.target(), s = n.foreignKey ?? En(o, i.tableName, t), c = n.sourceKey ?? "id", l = fr(e, c), u = lr(r), d = l.length === 0 ? [] : await pr(o, s, l, u, a), f = /* @__PURE__ */ new Map();
684
684
  for (let e of d) {
685
685
  let t = e[s], n = f.get(t);
686
686
  n ? n.push(e) : f.set(t, [e]);
@@ -792,10 +792,10 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
792
792
  let { strings: n, values: r } = e, i = t.unsafe(n[0] ?? "");
793
793
  for (let e = 0; e < r.length; e++) i = t`${i}${r[e]}${t.unsafe(n[e + 1] ?? "")}`;
794
794
  return t`${i}`;
795
- }, Or = (e) => e.replace(/[\\%_]/g, (e) => `\\${e}`), I = (e, t, n = null, r) => {
796
- if ("not" in e) return t`NOT (${I(e.not, t, n, r)})`;
797
- if ("and" in e) return e.and.length === 0 ? t`TRUE` : t.and(e.and.map((e) => I(e, t, n, r)));
798
- if ("or" in e) return e.or.length === 0 ? t`FALSE` : t.or(e.or.map((e) => I(e, t, n, r)));
795
+ }, Or = (e) => e.replace(/[\\%_]/g, (e) => `\\${e}`), L = (e, t, n = null, r) => {
796
+ if ("not" in e) return t`NOT (${L(e.not, t, n, r)})`;
797
+ if ("and" in e) return e.and.length === 0 ? t`TRUE` : t.and(e.and.map((e) => L(e, t, n, r)));
798
+ if ("or" in e) return e.or.length === 0 ? t`FALSE` : t.or(e.or.map((e) => L(e, t, n, r)));
799
799
  if (e.op === "subquery-in" || e.op === "subquery-not-in") {
800
800
  let r = e, i = zr(r.subquery, t, n);
801
801
  return r.op === "subquery-in" ? t`${t(r.column)} IN (${i})` : t`${t(r.column)} NOT IN (${i})`;
@@ -805,15 +805,15 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
805
805
  return r.op === "exists" ? t`EXISTS (${i})` : t`NOT EXISTS (${i})`;
806
806
  }
807
807
  let i = e, a = t(i.column), o = i.path, s = o !== void 0 && o.length > 0, c = () => t.onDialectOrElse({
808
- mysql: () => t.unsafe(w(i.column, o, "mysql")),
809
- mssql: () => t.unsafe(w(i.column, o, "mssql")),
810
- sqlite: () => t.unsafe(w(i.column, o, "sqlite")),
811
- orElse: () => t.unsafe(w(i.column, o, "postgres"))
808
+ mysql: () => t.unsafe(D(i.column, o, "mysql")),
809
+ mssql: () => t.unsafe(D(i.column, o, "mssql")),
810
+ sqlite: () => t.unsafe(D(i.column, o, "sqlite")),
811
+ orElse: () => t.unsafe(D(i.column, o, "postgres"))
812
812
  }), l = () => t.onDialectOrElse({
813
- mysql: () => t.unsafe(w(i.column, o, "mysql", { numeric: !0 })),
814
- mssql: () => t.unsafe(w(i.column, o, "mssql", { numeric: !0 })),
815
- sqlite: () => t.unsafe(w(i.column, o, "sqlite", { numeric: !0 })),
816
- orElse: () => t.unsafe(w(i.column, o, "postgres", { numeric: !0 }))
813
+ mysql: () => t.unsafe(D(i.column, o, "mysql", { numeric: !0 })),
814
+ mssql: () => t.unsafe(D(i.column, o, "mssql", { numeric: !0 })),
815
+ sqlite: () => t.unsafe(D(i.column, o, "sqlite", { numeric: !0 })),
816
+ orElse: () => t.unsafe(D(i.column, o, "postgres", { numeric: !0 }))
817
817
  }), u = s ? c() : a, d = s ? l() : a, f = (e) => s && e != null ? String(e) : e, m = (e) => s ? Number(e) : e, h = s || r === void 0 ? void 0 : p(r)?.fields?.[i.column]?.type, g = (e) => Tr(h, e);
818
818
  switch (i.op) {
819
819
  case "eq": return t`${u} = ${f(g(i.value))}`;
@@ -955,7 +955,7 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
955
955
  }, zr = (e, t, n = null) => {
956
956
  if (e.setOp && e.setOp.queries.length >= 2) {
957
957
  let r = e.setOp.kind === "union" ? "UNION" : e.setOp.kind === "union-all" ? "UNION ALL" : e.setOp.kind === "intersect" ? "INTERSECT" : "EXCEPT", i = e.setOp.queries.map((e) => t`(${zr(e, t, n)})`).reduce((e, n, i) => i === 0 ? n : t`${e} ${t.unsafe(r)} ${n}`), a = [];
958
- if (C(e).length > 0 && a.push(t` ORDER BY ${t.csv(C(e).map((e) => e.direction === "desc" ? t`${t(e.column)} DESC` : t`${t(e.column)} ASC`))}`), e.take !== void 0) {
958
+ if (T(e).length > 0 && a.push(t` ORDER BY ${t.csv(T(e).map((e) => e.direction === "desc" ? t`${t(e.column)} DESC` : t`${t(e.column)} ASC`))}`), e.take !== void 0) {
959
959
  if (!Number.isInteger(e.take) || e.take < 0) throw Error(`compileSelect: invalid take ${e.take}`);
960
960
  a.push(t` LIMIT ${t.unsafe(String(e.take))}`);
961
961
  }
@@ -985,10 +985,10 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
985
985
  sqlite: () => t`DISTINCT `
986
986
  }) : e.distinct ? t`DISTINCT ` : t``, p = e.alias === void 0 ? t`${t(Sr(n, e.table))}` : t`${t(Sr(n, e.table))} AS ${t(e.alias)}`, m = (e.joins ?? []).map((e) => {
987
987
  let r = e.kind === "inner" ? "INNER" : "LEFT";
988
- return t` ${t.unsafe(r)} JOIN ${t(Sr(n, e.table))} AS ${t(e.alias)} ON ${I(e.on, t, n)}`;
989
- }), h = m.length > 0 ? m.reduce((e, n) => t`${e}${n}`, p) : p, g = c === void 0 ? null : Lr(c, e.table, t), ee = [e.predicate ? I(e.predicate, t, n, e.table) : null, g].filter((e) => e !== null), te = ee.length > 0 ? t` WHERE ${t.and(ee)}` : t``, _ = e.groupBy && e.groupBy.length > 0 ? t` GROUP BY ${t.csv(e.groupBy.map((e) => t`${t(e)}`))}` : t``, v = e.having ? t` HAVING ${I(e.having, t, n, e.table)}` : t``, ne = e.skip !== void 0, y = [];
988
+ return t` ${t.unsafe(r)} JOIN ${t(Sr(n, e.table))} AS ${t(e.alias)} ON ${L(e.on, t, n)}`;
989
+ }), h = m.length > 0 ? m.reduce((e, n) => t`${e}${n}`, p) : p, g = c === void 0 ? null : Lr(c, e.table, t), _ = [e.predicate ? L(e.predicate, t, n, e.table) : null, g].filter((e) => e !== null), ee = _.length > 0 ? t` WHERE ${t.and(_)}` : t``, v = e.groupBy && e.groupBy.length > 0 ? t` GROUP BY ${t.csv(e.groupBy.map((e) => t`${t(e)}`))}` : t``, te = e.having ? t` HAVING ${L(e.having, t, n, e.table)}` : t``, ne = e.skip !== void 0, y = [];
990
990
  r !== null && y.push(t`${r} ASC`), e.spatialClause?.order !== void 0 && y.push(e.spatialClause.order === "desc" ? t`${Pr(e.spatialClause, t)} DESC` : t`${Pr(e.spatialClause, t)} ASC`), l !== null && c?.rank?.order === !0 && y.push(t`${l} DESC`);
991
- for (let n of C(e)) y.push(n.direction === "desc" ? t`${t(n.column)} DESC` : t`${t(n.column)} ASC`);
991
+ for (let n of T(e)) y.push(n.direction === "desc" ? t`${t(n.column)} DESC` : t`${t(n.column)} ASC`);
992
992
  let re = y.length > 0 ? t` ORDER BY ${t.csv(y)}` : ne ? t.onDialectOrElse({
993
993
  mssql: () => t` ORDER BY (SELECT NULL)`,
994
994
  orElse: () => t``
@@ -999,11 +999,11 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
999
999
  return t.onDialectOrElse({
1000
1000
  mssql: () => {
1001
1001
  let n = e.take !== void 0 && !ne ? t`TOP ${b(e.take)} ` : t``, r = ne ? t` OFFSET ${b(e.skip)} ROWS FETCH NEXT ${b(e.take ?? 2 ** 53 - 1)} ROWS ONLY` : t``;
1002
- return t`${oe}SELECT ${n}${f}${d} FROM ${h}${te}${_}${v}${re}${r}`;
1002
+ return t`${oe}SELECT ${n}${f}${d} FROM ${h}${ee}${v}${te}${re}${r}`;
1003
1003
  },
1004
1004
  orElse: () => {
1005
1005
  let n = e.take === void 0 ? t`` : t` LIMIT ${b(e.take)}`, r = ne ? t` OFFSET ${b(e.skip)}` : t``;
1006
- return t`${oe}SELECT ${f}${d} FROM ${h}${te}${_}${v}${re}${n}${r}`;
1006
+ return t`${oe}SELECT ${f}${d} FROM ${h}${ee}${v}${te}${re}${n}${r}`;
1007
1007
  }
1008
1008
  });
1009
1009
  }, Br = (e, t, n) => {
@@ -1022,7 +1022,7 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
1022
1022
  limit: 2
1023
1023
  }
1024
1024
  }), Ur = (e, t, n) => {
1025
- let r = n ?? _(e), i = Fn(e);
1025
+ let r = n ?? v(e), i = Fn(e);
1026
1026
  if (i === void 0) return null;
1027
1027
  let a = [];
1028
1028
  for (let [e, n] of Object.entries(t)) {
@@ -1043,12 +1043,12 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
1043
1043
  let r = t.sourceKey ?? Jr(n, i.tableName);
1044
1044
  if (r !== void 0) o = r, s = "source";
1045
1045
  else try {
1046
- o = t.foreignKey ?? N(i, n.tableName, e), s = "target";
1046
+ o = t.foreignKey ?? En(i, n.tableName, e), s = "target";
1047
1047
  } catch {
1048
1048
  return null;
1049
1049
  }
1050
1050
  } else try {
1051
- o = t.foreignKey ?? N(i, n.tableName, e), s = "target";
1051
+ o = t.foreignKey ?? En(i, n.tableName, e), s = "target";
1052
1052
  } catch {
1053
1053
  return null;
1054
1054
  }
@@ -1175,16 +1175,16 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
1175
1175
  };
1176
1176
  }, ni = (e, t, n) => {
1177
1177
  let r = n.sql, i = n.nextAlias(), a = r(t.table.tableName), o = r(i), s = ri(i, t.children, n);
1178
- return s === null ? null : r`SELECT ${s} AS "__row" FROM ${a} AS ${o}${e.predicate ? r` WHERE ${H(e.predicate, i, r)}` : r``}${C(e).length > 0 ? r` ORDER BY ${r.csv(C(e).map((e) => e.direction === "desc" ? r`${z(i, e.column, r)} DESC` : r`${z(i, e.column, r)} ASC`))}` : r``}${e.take === void 0 ? r`` : r` LIMIT ${V(e.take, r)}`}${e.skip === void 0 ? r`` : r` OFFSET ${V(e.skip, r)}`}`;
1178
+ return s === null ? null : r`SELECT ${s} AS "__row" FROM ${a} AS ${o}${e.predicate ? r` WHERE ${U(e.predicate, i, r)}` : r``}${T(e).length > 0 ? r` ORDER BY ${r.csv(T(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)}`}`;
1179
1179
  }, ri = (e, t, n, r) => {
1180
- let i = n.sql, a = r === void 0 ? i`to_jsonb(${i(e)}.*)` : i`(to_jsonb(${i(e)}.*) - ${B(qr, i)}::text)`;
1180
+ let i = n.sql, a = r === void 0 ? i`to_jsonb(${i(e)}.*)` : i`(to_jsonb(${i(e)}.*) - ${V(qr, i)}::text)`;
1181
1181
  if (t.length === 0 && r === void 0) return a;
1182
1182
  let o = [];
1183
- r !== void 0 && o.push(i`${B("_junction", i)}, ${z(e, qr, i)}`);
1183
+ r !== void 0 && o.push(i`${V("_junction", i)}, ${B(e, qr, i)}`);
1184
1184
  for (let r of t) {
1185
1185
  let t = ii(r, e, n);
1186
1186
  if (t === null) return null;
1187
- o.push(i`${B(r.relationName, i)}, ${t}`);
1187
+ o.push(i`${V(r.relationName, i)}, ${t}`);
1188
1188
  }
1189
1189
  return i`${a} || jsonb_build_object(${i.csv(o)})`;
1190
1190
  }, ii = (e, t, n) => {
@@ -1196,37 +1196,37 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
1196
1196
  }, ai = (e, t, n) => {
1197
1197
  let r = n.sql, i = n.nextAlias(), a = ri(i, e.children, n);
1198
1198
  if (a === null) return null;
1199
- let o = e.fkSide === "source" ? r`${z(i, "id", r)} = ${z(t, e.foreignKey, r)}` : r`${z(i, e.foreignKey, r)} = ${z(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${H(e.branch.where, i, r)}`, c = L(i, e.branch.orderBy, r);
1199
+ 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);
1200
1200
  return r`(SELECT ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o}${s}${c} LIMIT 1)`;
1201
1201
  }, oi = (e, t, n) => {
1202
1202
  let r = n.sql, i = n.nextAlias(), a = ri(i, e.children, n);
1203
1203
  if (a === null) return null;
1204
- let o = r`${z(void 0, e.foreignKey, r)} = ${z(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${I(e.branch.where, r)}`, c = li(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${V(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${V(e.branch.offset, r)}`;
1204
+ let o = r`${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 = li(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)}`;
1205
1205
  return r`COALESCE((SELECT jsonb_agg(${a}) FROM (SELECT * FROM ${r(e.target.tableName)} WHERE ${o}${s}${c}${l}${u}) AS ${r(i)}), '[]'::jsonb)`;
1206
1206
  }, si = (e, t, n) => {
1207
1207
  let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = ri(o, e.children, n, e.junction);
1208
1208
  if (c === null) return null;
1209
- let l = e.branch.where === void 0 ? r`` : r` AND ${I(e.branch.where, r)}`, u = Fi(e, s, r), d = L(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${V(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${V(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : r`, ${ci(e.junction, s, r)} AS ${r(qr)}`;
1210
- return r`COALESCE((SELECT jsonb_agg(${c}) FROM (SELECT ${r(o)}.*${m} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${z(o, "id", r)} = ${z(s, i.targetKey, r)} WHERE ${z(s, i.sourceKey, r)} = ${z(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), '[]'::jsonb)`;
1211
- }, ci = (e, t, n) => e.present.length === 0 ? n`jsonb_build_object()` : n`jsonb_build_object(${n.csv(e.present.map((e) => n`${B(e, n)}, ${z(t, e, n)}`))})`, L = (e, t, n) => t === void 0 || t.length === 0 ? n`` : n` ORDER BY ${n.csv(t.map((t) => t.direction === "desc" ? n`${z(e, t.column, n)} DESC` : n`${z(e, t.column, n)} ASC`))}`, li = (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`))}`, ui = (e, t, n) => {
1209
+ let l = e.branch.where === void 0 ? r`` : r` AND ${L(e.branch.where, r)}`, u = Fi(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`, ${ci(e.junction, s, r)} AS ${r(qr)}`;
1210
+ return r`COALESCE((SELECT jsonb_agg(${c}) FROM (SELECT ${r(o)}.*${m} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${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)`;
1211
+ }, ci = (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`))}`, li = (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`))}`, ui = (e, t, n) => {
1212
1212
  let r = n.sql, i = n.nextAlias(), a = di(i, t.table, t.children, n);
1213
1213
  if (a === null) return null;
1214
- let o = e.predicate ? r` WHERE ${H(e.predicate, i, r)}` : r``, s = C(e).length > 0 ? r` ORDER BY ${r.csv(C(e).map((e) => e.direction === "desc" ? r`${z(i, e.column, r)} DESC` : r`${z(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${V(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${V(e.skip, r)}`;
1214
+ let o = e.predicate ? r` WHERE ${U(e.predicate, i, r)}` : r``, s = T(e).length > 0 ? r` ORDER BY ${r.csv(T(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)}`;
1215
1215
  return r`SELECT ${a} AS "__row" FROM ${r(t.table.tableName)} AS ${r(i)}${o}${s}${c}${l}`;
1216
1216
  }, di = (e, t, n, r, i) => {
1217
1217
  let a = r.sql, o = [];
1218
- for (let n of Object.keys(t.fields)) o.push(a`${B(n, a)}, ${z(e, n, a)}`);
1218
+ for (let n of Object.keys(t.fields)) o.push(a`${V(n, a)}, ${B(e, n, a)}`);
1219
1219
  if (i !== void 0) {
1220
1220
  let e = fi(i.projection, i.source, a);
1221
- o.push(a`${B("_junction", a)}, json_object(${e})`);
1221
+ o.push(a`${V("_junction", a)}, json_object(${e})`);
1222
1222
  }
1223
1223
  for (let t of n) {
1224
1224
  let n = gi(t, e, r);
1225
1225
  if (n === null) return null;
1226
- o.push(a`${B(t.relationName, a)}, ${n}`);
1226
+ o.push(a`${V(t.relationName, a)}, ${n}`);
1227
1227
  }
1228
1228
  return a`json_object(${a.csv(o)})`;
1229
- }, fi = (e, t, n) => e.present.length === 0 ? n`` : n.csv(e.present.map((e) => n`${B(e, n)}, ${z(t.alias, t.physical(e), n)}`)), pi = (e, t, n) => e.present.length === 0 ? n`` : n`, ${n.csv(e.present.map((e) => n`${z(t, e, n)} AS ${n(Kr(e))}`))}`, mi = (e) => ({
1229
+ }, fi = (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)}`)), pi = (e, t, n) => e.present.length === 0 ? n`` : n`, ${n.csv(e.present.map((e) => n`${B(t, e, n)} AS ${n(Kr(e))}`))}`, mi = (e) => ({
1230
1230
  alias: e,
1231
1231
  physical: Kr
1232
1232
  }), hi = (e) => ({
@@ -1241,12 +1241,12 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
1241
1241
  }, _i = (e, t, n) => {
1242
1242
  let r = n.sql, i = n.nextAlias(), a = di(i, e.target, e.children, n);
1243
1243
  if (a === null) return null;
1244
- let o = e.fkSide === "source" ? r`${z(i, "id", r)} = ${z(t, e.foreignKey, r)}` : r`${z(i, e.foreignKey, r)} = ${z(t, e.sourceKey, r)}`;
1244
+ 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)}`;
1245
1245
  return r`(SELECT ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o} LIMIT 1)`;
1246
1246
  }, vi = (e, t, n) => {
1247
1247
  let r = n.sql, i = n.nextAlias(), a = di(i, e.target, e.children, n);
1248
1248
  if (a === null) return null;
1249
- let o = r`${z(void 0, e.foreignKey, r)} = ${z(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${I(U(e.branch.where), r)}`, c = li(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${V(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${V(e.branch.offset, r)}`;
1249
+ let o = r`${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 = li(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)}`;
1250
1250
  return r`COALESCE((SELECT json_group_array(${a}) FROM (SELECT * FROM ${r(e.target.tableName)} WHERE ${o}${s}${c}${l}${u}) AS ${r(i)}), json('[]'))`;
1251
1251
  }, yi = (e, t, n) => {
1252
1252
  let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = di(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
@@ -1254,24 +1254,24 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
1254
1254
  source: mi(o)
1255
1255
  });
1256
1256
  if (c === null) return null;
1257
- let l = e.branch.where === void 0 ? r`` : r` AND ${I(U(e.branch.where), r)}`, u = Fi(e, s, r, !0), d = L(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${V(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${V(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : pi(e.junction, s, r);
1258
- return r`COALESCE((SELECT json_group_array(${c}) FROM (SELECT ${r(o)}.*${m} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${z(o, "id", r)} = ${z(s, i.targetKey, r)} WHERE ${z(s, i.sourceKey, r)} = ${z(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), json('[]'))`;
1257
+ let l = e.branch.where === void 0 ? r`` : r` AND ${L(W(e.branch.where), r)}`, u = Fi(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`` : pi(e.junction, s, r);
1258
+ return r`COALESCE((SELECT json_group_array(${c}) FROM (SELECT ${r(o)}.*${m} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${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('[]'))`;
1259
1259
  }, bi = (e, t, n) => {
1260
- let r = n.sql, i = n.nextAlias(), a = R(i, t.table, t.children, n);
1260
+ let r = n.sql, i = n.nextAlias(), a = z(i, t.table, t.children, n);
1261
1261
  if (a === null) return null;
1262
- let o = e.predicate ? r` WHERE ${H(e.predicate, i, r)}` : r``, s = C(e).length > 0 ? r` ORDER BY ${r.csv(C(e).map((e) => e.direction === "desc" ? r`${z(i, e.column, r)} DESC` : r`${z(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${V(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${V(e.skip, r)}`;
1262
+ let o = e.predicate ? r` WHERE ${U(e.predicate, i, r)}` : r``, s = T(e).length > 0 ? r` ORDER BY ${r.csv(T(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)}`;
1263
1263
  return r`SELECT ${a} AS \`__row\` FROM ${r(t.table.tableName)} AS ${r(i)}${o}${s}${c}${l}`;
1264
- }, R = (e, t, n, r, i) => {
1264
+ }, z = (e, t, n, r, i) => {
1265
1265
  let a = r.sql, o = [];
1266
- for (let n of Object.keys(t.fields)) o.push(a`${B(n, a)}, ${z(e, n, a)}`);
1266
+ for (let n of Object.keys(t.fields)) o.push(a`${V(n, a)}, ${B(e, n, a)}`);
1267
1267
  if (i !== void 0) {
1268
1268
  let e = fi(i.projection, i.source, a);
1269
- o.push(a`${B("_junction", a)}, JSON_OBJECT(${e})`);
1269
+ o.push(a`${V("_junction", a)}, JSON_OBJECT(${e})`);
1270
1270
  }
1271
1271
  for (let t of n) {
1272
1272
  let n = xi(t, e, r);
1273
1273
  if (n === null) return null;
1274
- o.push(a`${B(t.relationName, a)}, ${n}`);
1274
+ o.push(a`${V(t.relationName, a)}, ${n}`);
1275
1275
  }
1276
1276
  return a`JSON_OBJECT(${a.csv(o)})`;
1277
1277
  }, xi = (e, t, n) => {
@@ -1286,57 +1286,57 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
1286
1286
  case "manyToMany": return n.dialect === "mariadb" ? Ei(e, t, n) : wi(e, t, n);
1287
1287
  }
1288
1288
  }, Si = (e, t, n) => {
1289
- let r = n.sql, i = n.nextAlias(), a = R(i, e.target, e.children, n);
1289
+ let r = n.sql, i = n.nextAlias(), a = z(i, e.target, e.children, n);
1290
1290
  if (a === null) return null;
1291
- let o = e.fkSide === "source" ? r`${z(i, "id", r)} = ${z(t, e.foreignKey, r)}` : r`${z(i, e.foreignKey, r)} = ${z(t, e.sourceKey, r)}`;
1291
+ 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)}`;
1292
1292
  return r`(SELECT ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o} LIMIT 1)`;
1293
1293
  }, Ci = (e, t, n) => {
1294
- let r = n.sql, i = n.nextAlias(), a = R(i, e.target, e.children, n);
1294
+ let r = n.sql, i = n.nextAlias(), a = z(i, e.target, e.children, n);
1295
1295
  if (a === null) return null;
1296
- let o = r`${z(void 0, e.foreignKey, r)} = ${z(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${I(U(e.branch.where), r)}`, c = li(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${V(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${V(e.branch.offset, r)}`;
1296
+ let o = r`${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 = li(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)}`;
1297
1297
  return r`COALESCE((SELECT JSON_ARRAYAGG(${a}) FROM (SELECT * FROM ${r(e.target.tableName)} WHERE ${o}${s}${c}${l}${u}) AS ${r(i)}), JSON_ARRAY())`;
1298
1298
  }, wi = (e, t, n) => {
1299
- let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = R(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1299
+ 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 : {
1300
1300
  projection: e.junction,
1301
1301
  source: mi(o)
1302
1302
  });
1303
1303
  if (c === null) return null;
1304
- let l = e.branch.where === void 0 ? r`` : r` AND ${I(U(e.branch.where), r)}`, u = Fi(e, s, r, !0), d = L(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${V(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${V(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : pi(e.junction, s, r);
1305
- return r`COALESCE((SELECT JSON_ARRAYAGG(${c}) FROM (SELECT ${r(o)}.*${m} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${z(o, "id", r)} = ${z(s, i.targetKey, r)} WHERE ${z(s, i.sourceKey, r)} = ${z(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), JSON_ARRAY())`;
1304
+ let l = e.branch.where === void 0 ? r`` : r` AND ${L(W(e.branch.where), r)}`, u = Fi(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`` : pi(e.junction, s, r);
1305
+ return r`COALESCE((SELECT JSON_ARRAYAGG(${c}) FROM (SELECT ${r(o)}.*${m} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${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())`;
1306
1306
  }, Ti = (e, t, n) => {
1307
- let r = n.sql, i = n.nextAlias(), a = R(i, e.target, e.children, n);
1307
+ let r = n.sql, i = n.nextAlias(), a = z(i, e.target, e.children, n);
1308
1308
  if (a === null) return null;
1309
- let o = r`${z(i, e.foreignKey, r)} = ${z(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${I(U(e.branch.where), r)}`, c = e.branch.orderBy ?? [];
1310
- if (e.branch.limit === void 0 && e.branch.offset === void 0) return r`COALESCE((SELECT JSON_ARRAYAGG(${a}${c.length > 0 ? r` ORDER BY ${r.csv(c.map((e) => e.direction === "desc" ? r`${z(i, e.column, r)} DESC` : r`${z(i, e.column, r)} ASC`))}` : r``}) FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o}${s}), JSON_ARRAY())`;
1311
- let l = c.length > 0 ? r` ORDER BY ${r.csv(c.map((e) => e.direction === "desc" ? r`${r(e.column)} DESC` : r`${r(e.column)} ASC`))}` : r` ORDER BY ${r("id")}`, u = e.branch.limit, d = e.branch.offset, f = u !== void 0 && d !== void 0 ? r` AND ${z(i, "rn", r)} > ${V(d, r)} AND ${z(i, "rn", r)} <= ${V(d + u, r)}` : u === void 0 ? r` AND ${z(i, "rn", r)} > ${V(d, r)}` : r` AND ${z(i, "rn", r)} <= ${V(u, r)}`;
1312
- return r`COALESCE((SELECT JSON_ARRAYAGG(${a} ORDER BY ${z(i, "rn", r)}) FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY ${r(e.foreignKey)}${l}) AS rn FROM ${r(e.target.tableName)}) AS ${r(i)} WHERE ${o}${s}${f}), JSON_ARRAY())`;
1309
+ 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 ?? [];
1310
+ if (e.branch.limit === void 0 && e.branch.offset === void 0) return r`COALESCE((SELECT JSON_ARRAYAGG(${a}${c.length > 0 ? r` ORDER BY ${r.csv(c.map((e) => e.direction === "desc" ? r`${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())`;
1311
+ let l = c.length > 0 ? r` ORDER BY ${r.csv(c.map((e) => e.direction === "desc" ? r`${r(e.column)} DESC` : r`${r(e.column)} ASC`))}` : r` ORDER BY ${r("id")}`, u = e.branch.limit, d = e.branch.offset, f = u !== void 0 && d !== void 0 ? r` AND ${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)}`;
1312
+ 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())`;
1313
1313
  }, Ei = (e, t, n) => {
1314
1314
  let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = (t) => e.junction === void 0 ? void 0 : {
1315
1315
  projection: e.junction,
1316
1316
  source: t
1317
- }, l = r`${z(s, i.sourceKey, r)} = ${z(t, "id", r)}`, u = r`${z(o, "id", r)} = ${z(s, i.targetKey, r)}`, d = e.branch.where === void 0 ? r`` : r` AND ${I(U(e.branch.where), r)}`, f = Fi(e, s, r, !0), p = e.branch.orderBy ?? [];
1317
+ }, 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 = Fi(e, s, r, !0), p = e.branch.orderBy ?? [];
1318
1318
  if (e.branch.limit === void 0 && e.branch.offset === void 0) {
1319
- let t = R(o, e.target, e.children, n, c(hi(s)));
1320
- return t === null ? null : r`COALESCE((SELECT JSON_ARRAYAGG(${t}${p.length > 0 ? r` ORDER BY ${r.csv(p.map((e) => e.direction === "desc" ? r`${z(o, e.column, r)} DESC` : r`${z(o, e.column, r)} ASC`))}` : r``}) FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${u} WHERE ${l}${f}${d}), JSON_ARRAY())`;
1319
+ let t = z(o, e.target, e.children, n, c(hi(s)));
1320
+ return t === null ? null : r`COALESCE((SELECT JSON_ARRAYAGG(${t}${p.length > 0 ? r` ORDER BY ${r.csv(p.map((e) => e.direction === "desc" ? r`${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())`;
1321
1321
  }
1322
- let m = p.length > 0 ? r` ORDER BY ${r.csv(p.map((e) => e.direction === "desc" ? r`${z(o, e.column, r)} DESC` : r`${z(o, e.column, r)} ASC`))}` : r` ORDER BY ${z(o, "id", r)}`, h = e.branch.limit, g = e.branch.offset, ee = h !== void 0 && g !== void 0 ? r` AND ${z(o, "rn", r)} > ${V(g, r)} AND ${z(o, "rn", r)} <= ${V(g + h, r)}` : h === void 0 ? r` AND ${z(o, "rn", r)} > ${V(g, r)}` : r` AND ${z(o, "rn", r)} <= ${V(h, r)}`, te = e.branch.onJunction === void 0 ? r`` : r` WHERE ${H(U(e.branch.onJunction), s, r)}`, _ = R(o, e.target, e.children, n, c(mi(o)));
1323
- if (_ === null) return null;
1324
- let v = e.junction === void 0 ? r`` : pi(e.junction, s, r);
1325
- return r`COALESCE((SELECT JSON_ARRAYAGG(${_} ORDER BY ${z(o, "rn", r)}) FROM (SELECT ${r(o)}.*${v}, ${z(s, i.sourceKey, r)} AS ${r(`__src_${i.sourceKey}`)}, ROW_NUMBER() OVER (PARTITION BY ${z(s, i.sourceKey, r)}${m}) AS rn FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${u}${te}) AS ${r(o)} WHERE ${z(o, `__src_${i.sourceKey}`, r)} = ${z(t, "id", r)}${d}${ee}), JSON_ARRAY())`;
1322
+ let m = p.length > 0 ? r` ORDER BY ${r.csv(p.map((e) => e.direction === "desc" ? r`${B(o, e.column, r)} DESC` : r`${B(o, e.column, r)} ASC`))}` : r` ORDER BY ${B(o, "id", r)}`, h = e.branch.limit, g = e.branch.offset, _ = h !== void 0 && g !== void 0 ? r` AND ${B(o, "rn", r)} > ${H(g, r)} AND ${B(o, "rn", r)} <= ${H(g + h, r)}` : h === void 0 ? r` AND ${B(o, "rn", r)} > ${H(g, r)}` : r` AND ${B(o, "rn", r)} <= ${H(h, r)}`, ee = e.branch.onJunction === void 0 ? r`` : r` WHERE ${U(W(e.branch.onJunction), s, r)}`, v = z(o, e.target, e.children, n, c(mi(o)));
1323
+ if (v === null) return null;
1324
+ let te = e.junction === void 0 ? r`` : pi(e.junction, s, r);
1325
+ return r`COALESCE((SELECT JSON_ARRAYAGG(${v} 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}${ee}) AS ${r(o)} WHERE ${B(o, `__src_${i.sourceKey}`, r)} = ${B(t, "id", r)}${d}${_}), JSON_ARRAY())`;
1326
1326
  }, Di = (e, t, n) => {
1327
1327
  let r = n.sql, i = n.nextAlias(), a = Oi(i, t.table, t.children, n);
1328
1328
  if (a === null) return null;
1329
- let o = e.predicate ? r` WHERE ${H(e.predicate, i, r)}` : r``, s = C(e).length > 0 ? r` ORDER BY ${r.csv(C(e).map((e) => e.direction === "desc" ? r`${z(i, e.column, r)} DESC` : r`${z(i, e.column, r)} ASC`))}` : r``, c = r``, l = r``;
1329
+ let o = e.predicate ? r` WHERE ${U(e.predicate, i, r)}` : r``, s = T(e).length > 0 ? r` ORDER BY ${r.csv(T(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``;
1330
1330
  if (e.skip !== void 0) {
1331
- let t = C(e).length > 0 ? s : r` ORDER BY (SELECT NULL)`;
1332
- l = e.take === void 0 ? r`${t} OFFSET ${V(e.skip, r)} ROWS` : r`${t} OFFSET ${V(e.skip, r)} ROWS FETCH NEXT ${V(e.take, r)} ROWS ONLY`;
1333
- } else e.take !== void 0 && (c = r`TOP ${V(e.take, r)} `);
1331
+ let t = T(e).length > 0 ? s : r` ORDER BY (SELECT NULL)`;
1332
+ 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`;
1333
+ } else e.take !== void 0 && (c = r`TOP ${H(e.take, r)} `);
1334
1334
  let u = e.skip === void 0 ? s : r``;
1335
1335
  return r`SELECT ${c}(SELECT ${a} FOR JSON PATH, INCLUDE_NULL_VALUES, WITHOUT_ARRAY_WRAPPER) AS ${r("__row")} FROM ${r(t.table.tableName)} AS ${r(i)}${o}${u}${l}`;
1336
1336
  }, Oi = (e, t, n, r, i) => {
1337
1337
  let a = r.sql, o = [];
1338
- for (let n of Object.keys(t.fields)) o.push(a`${z(e, n, a)} AS ${a(n)}`);
1339
- if (i !== void 0) for (let e of i.projection.present) o.push(a`${z(i.source.alias, i.source.physical(e), a)} AS ${ki(`_junction.${e}`, a)}`);
1338
+ for (let n of Object.keys(t.fields)) o.push(a`${B(e, n, a)} AS ${a(n)}`);
1339
+ if (i !== void 0) for (let e of i.projection.present) o.push(a`${B(i.source.alias, i.source.physical(e), a)} AS ${ki(`_junction.${e}`, a)}`);
1340
1340
  for (let t of n) {
1341
1341
  let n = Ai(t, e, r);
1342
1342
  if (n === null) return null;
@@ -1352,11 +1352,11 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
1352
1352
  }, ji = (e, t, n) => {
1353
1353
  let r = n.sql, i = n.nextAlias(), a = Oi(i, e.target, e.children, n);
1354
1354
  if (a === null) return null;
1355
- let o = e.fkSide === "source" ? r`${z(i, "id", r)} = ${z(t, e.foreignKey, r)}` : r`${z(i, e.foreignKey, r)} = ${z(t, e.sourceKey, r)}`;
1355
+ 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)}`;
1356
1356
  return r`JSON_QUERY((SELECT TOP 1 ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o} FOR JSON PATH, INCLUDE_NULL_VALUES, WITHOUT_ARRAY_WRAPPER)) AS ${r(e.relationName)}`;
1357
1357
  }, Mi = (e, t, n) => {
1358
1358
  if (e.offset !== void 0) {
1359
- let r = e.orderBy && e.orderBy.length > 0 ? t : n` ORDER BY (SELECT NULL)`, i = e.limit === void 0 ? n`${r} OFFSET ${V(e.offset, n)} ROWS` : n`${r} OFFSET ${V(e.offset, n)} ROWS FETCH NEXT ${V(e.limit, n)} ROWS ONLY`;
1359
+ 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`;
1360
1360
  return {
1361
1361
  top: n``,
1362
1362
  pagination: i,
@@ -1364,29 +1364,29 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
1364
1364
  };
1365
1365
  }
1366
1366
  return {
1367
- top: e.limit === void 0 ? n`` : n`TOP ${V(e.limit, n)} `,
1367
+ top: e.limit === void 0 ? n`` : n`TOP ${H(e.limit, n)} `,
1368
1368
  pagination: n``,
1369
1369
  finalOrder: t
1370
1370
  };
1371
1371
  }, Ni = (e, t, n) => {
1372
1372
  let r = n.sql, i = n.nextAlias(), a = Oi(i, e.target, e.children, n);
1373
1373
  if (a === null) return null;
1374
- let o = e.branch.where === void 0 ? r`` : r` AND ${H(e.branch.where, i, r)}`, s = L(i, e.branch.orderBy, r), { top: c, pagination: l, finalOrder: u } = Mi(e.branch, s, r);
1375
- return r`ISNULL(JSON_QUERY((SELECT ${c}${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${z(i, e.foreignKey, r)} = ${z(t, e.sourceKey, r)}${o}${u}${l} FOR JSON PATH, INCLUDE_NULL_VALUES)), JSON_QUERY('[]')) AS ${r(e.relationName)}`;
1374
+ 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 } = Mi(e.branch, s, r);
1375
+ 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)}`;
1376
1376
  }, Pi = (e, t, n) => {
1377
1377
  let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = Oi(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1378
1378
  projection: e.junction,
1379
1379
  source: hi(s)
1380
1380
  });
1381
1381
  if (c === null) return null;
1382
- let l = e.branch.where === void 0 ? r`` : r` AND ${H(e.branch.where, o, r)}`, u = Fi(e, s, r), d = L(o, e.branch.orderBy, r), { top: f, pagination: p, finalOrder: m } = Mi(e.branch, d, r);
1383
- return r`ISNULL(JSON_QUERY((SELECT ${f}${c} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${z(o, "id", r)} = ${z(s, i.targetKey, r)} WHERE ${z(s, i.sourceKey, r)} = ${z(t, "id", r)}${u}${l}${m}${p} FOR JSON PATH, INCLUDE_NULL_VALUES)), JSON_QUERY('[]')) AS ${r(e.relationName)}`;
1384
- }, z = (e, t, n) => e === void 0 ? n`${n(t)}` : n`${n(e)}.${n(t)}`, B = (e, t) => t.unsafe(`'${e.replace(/'/g, "''")}'`), V = (e, t) => {
1382
+ let l = e.branch.where === void 0 ? r`` : r` AND ${U(e.branch.where, o, r)}`, u = Fi(e, s, r), d = R(o, e.branch.orderBy, r), { top: f, pagination: p, finalOrder: m } = Mi(e.branch, d, r);
1383
+ return r`ISNULL(JSON_QUERY((SELECT ${f}${c} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${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)}`;
1384
+ }, 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) => {
1385
1385
  if (!Number.isFinite(e) || !Number.isInteger(e) || e < 0) throw Error(`literalInt: expected non-negative integer, got ${e}`);
1386
1386
  return t.unsafe(String(e));
1387
- }, H = (e, t, n) => I(Ii(e, t), n), Fi = (e, t, n, r = !1) => {
1387
+ }, U = (e, t, n) => L(Ii(e, t), n), Fi = (e, t, n, r = !1) => {
1388
1388
  let i = e.branch.onJunction;
1389
- return i === void 0 ? n`` : n` AND ${H(r ? U(i) : i, t, n)}`;
1389
+ return i === void 0 ? n`` : n` AND ${U(r ? W(i) : i, t, n)}`;
1390
1390
  }, Ii = (e, t) => {
1391
1391
  if ("not" in e) return { not: Ii(e.not, t) };
1392
1392
  if ("and" in e) return { and: e.and.map((e) => Ii(e, t)) };
@@ -1404,10 +1404,10 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
1404
1404
  ...n,
1405
1405
  column: `${t}.${n.column}`
1406
1406
  };
1407
- }, U = (e) => {
1408
- if ("not" in e) return { not: U(e.not) };
1409
- if ("and" in e) return { and: e.and.map((e) => U(e)) };
1410
- if ("or" in e) return { or: e.or.map((e) => U(e)) };
1407
+ }, W = (e) => {
1408
+ if ("not" in e) return { not: W(e.not) };
1409
+ if ("and" in e) return { and: e.and.map((e) => W(e)) };
1410
+ if ("or" in e) return { or: e.or.map((e) => W(e)) };
1411
1411
  if (e.op === "subquery-in" || e.op === "subquery-not-in" || e.op === "exists" || e.op === "not-exists") return e;
1412
1412
  let t = e;
1413
1413
  return {
@@ -1420,16 +1420,16 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
1420
1420
  let n = e();
1421
1421
  if (n === void 0) throw Error(`core '${t}' table not registered; expected the framework CLI or your migrate step to call registerCoreTables({ ${t}: () => ${t}Table }) before the database handle is constructed`);
1422
1422
  return n();
1423
- }, Ui = () => Hi(() => Bi.actors, "actors"), Wi = () => Hi(() => Bi.tenants, "tenants"), Gi = T("actors", {
1424
- id: b(),
1425
- kind: v().oneOf([
1423
+ }, Ui = () => Hi(() => Bi.actors, "actors"), Wi = () => Hi(() => Bi.tenants, "tenants"), Gi = E("actors", {
1424
+ id: x(),
1425
+ kind: w().oneOf([
1426
1426
  "user",
1427
1427
  "serviceAccount",
1428
1428
  "apiKey",
1429
1429
  "system"
1430
1430
  ]),
1431
- displayName: v().nullable(),
1432
- createdAt: S().default("now")
1431
+ displayName: w().nullable(),
1432
+ createdAt: C().default("now")
1433
1433
  }), Ki = (e, t) => ({
1434
1434
  column: e,
1435
1435
  op: "eq",
@@ -1658,7 +1658,7 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
1658
1658
  },
1659
1659
  ...a
1660
1660
  };
1661
- }, Oa = new Nt(), ka = (e, t) => Oa.run(e, t), Aa = () => Oa.getStore(), ja = (e) => {
1661
+ }, Oa = new jt(), ka = (e, t) => Oa.run(e, t), Aa = () => Oa.getStore(), ja = (e) => {
1662
1662
  let t = e ?? Oa.getStore();
1663
1663
  return t === void 0 ? {} : {
1664
1664
  ...t.traceId === void 0 ? {} : { traceId: t.traceId },
@@ -1669,29 +1669,29 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
1669
1669
  }, Ma = (e) => {
1670
1670
  let t = Oa.getStore();
1671
1671
  return t === void 0 ? e(void 0) : Oa.run(t, () => e(t));
1672
- }, Na = 3e4, Pa = 1e4, W = /* @__PURE__ */ new Map(), G = 0, Fa = (e, t, n) => `${e}\u0000${t}\u0000${String(n)}`, Ia = (e) => {
1673
- for (let [t, n] of W) {
1672
+ }, Na = 3e4, Pa = 1e4, G = /* @__PURE__ */ new Map(), K = 0, Fa = (e, t, n) => `${e}\u0000${t}\u0000${String(n)}`, Ia = (e) => {
1673
+ for (let [t, n] of G) {
1674
1674
  let r = n.filter((t) => e - t.at < Na);
1675
- G -= n.length - r.length, r.length === 0 ? W.delete(t) : r.length !== n.length && W.set(t, r);
1675
+ K -= n.length - r.length, r.length === 0 ? G.delete(t) : r.length !== n.length && G.set(t, r);
1676
1676
  }
1677
1677
  }, La = (e, t) => {
1678
1678
  if (t.traceId === void 0 && t.subjectId === void 0 && t.procedure === void 0) return;
1679
1679
  let n = Date.now();
1680
- if (G >= Pa && Ia(n), G >= Pa) return;
1681
- let r = W.get(e);
1682
- r === void 0 ? W.set(e, [{
1680
+ if (K >= Pa && Ia(n), K >= Pa) return;
1681
+ let r = G.get(e);
1682
+ r === void 0 ? G.set(e, [{
1683
1683
  attribution: t,
1684
1684
  at: n
1685
1685
  }]) : r.push({
1686
1686
  attribution: t,
1687
1687
  at: n
1688
- }), G += 1;
1688
+ }), K += 1;
1689
1689
  }, Ra = (e) => {
1690
- let t = W.get(e);
1690
+ let t = G.get(e);
1691
1691
  if (t === void 0 || t.length === 0) return;
1692
1692
  let n = t.shift();
1693
- if (--G, t.length === 0 && W.delete(e), !(Date.now() - n.at >= Na)) return n.attribution;
1694
- }, za = (e) => (W.get(e)?.length ?? 0) > 0, K = /* @__PURE__ */ new Map(), Ba = /* @__PURE__ */ new Map(), Va = /* @__PURE__ */ new Map(), Ha = 250, Ua = (e) => {
1693
+ if (--K, t.length === 0 && G.delete(e), !(Date.now() - n.at >= Na)) return n.attribution;
1694
+ }, za = (e) => (G.get(e)?.length ?? 0) > 0, q = /* @__PURE__ */ new Map(), Ba = /* @__PURE__ */ new Map(), Va = /* @__PURE__ */ new Map(), Ha = 250, Ua = (e) => {
1695
1695
  let t = Ba.get(e);
1696
1696
  if (t === void 0) return;
1697
1697
  Ba.delete(e);
@@ -1699,14 +1699,14 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
1699
1699
  n !== void 0 && (clearTimeout(n), Va.delete(e));
1700
1700
  for (let e of t) e();
1701
1701
  }, Wa = (e) => {
1702
- K.set(e, (K.get(e) ?? 0) + 1);
1702
+ q.set(e, (q.get(e) ?? 0) + 1);
1703
1703
  }, Ga = (e) => {
1704
- let t = (K.get(e) ?? 0) - 1;
1704
+ let t = (q.get(e) ?? 0) - 1;
1705
1705
  if (t > 0) {
1706
- K.set(e, t);
1706
+ q.set(e, t);
1707
1707
  return;
1708
1708
  }
1709
- K.delete(e), Ua(e);
1709
+ q.delete(e), Ua(e);
1710
1710
  }, Ka = (e, t, n, r) => {
1711
1711
  let i = n == null ? void 0 : Fa(e, t, n), a = () => r(i === void 0 ? void 0 : Ra(i));
1712
1712
  if (i === void 0) {
@@ -1718,7 +1718,7 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
1718
1718
  return;
1719
1719
  }
1720
1720
  let o = Ba.get(e);
1721
- if (o === void 0 && (K.get(e) ?? 0) === 0) {
1721
+ if (o === void 0 && (q.get(e) ?? 0) === 0) {
1722
1722
  a();
1723
1723
  return;
1724
1724
  }
@@ -1730,78 +1730,87 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
1730
1730
  let s = setTimeout(() => Ua(e), Ha);
1731
1731
  typeof s == "object" && typeof s.unref == "function" && s.unref(), Va.set(e, s);
1732
1732
  }, qa = () => {
1733
- W.clear(), G = 0, K.clear();
1733
+ G.clear(), K = 0, q.clear();
1734
1734
  for (let e of Va.values()) clearTimeout(e);
1735
1735
  Va.clear(), Ba.clear();
1736
- }, Ja = () => G, Ya = 64, Xa = "\0", Za = 32, Qa = (e, ...t) => `${e}_${Pt("sha256").update(t.map(String).join(Xa)).digest("hex").slice(0, Za)}`, $a = (e) => e.length + 1 + Za, q = /* @__PURE__ */ new Map(), eo = (e, t) => {
1737
- q.set(e, {
1736
+ }, Ja = () => K, Ya = 64, Xa = "\0", Za = 32, Qa = (e, ...t) => `${e}_${Mt("sha256").update(t.map(String).join(Xa)).digest("hex").slice(0, Za)}`, $a = (e) => e.length + 1 + Za, J = /* @__PURE__ */ new Map(), eo = (e, t) => {
1737
+ J.set(e, {
1738
1738
  recorder: t.recorder,
1739
1739
  tables: new Set(t.tables),
1740
1740
  ownTables: new Set(t.ownTables)
1741
1741
  });
1742
1742
  }, to = (e) => {
1743
- q.delete(e);
1744
- }, no = () => q.clear(), ro = (e) => {
1745
- if (q.size === 0) return !1;
1746
- for (let t of q.values()) if (!t.ownTables.has(e) && t.tables.has(e)) return !0;
1743
+ J.delete(e);
1744
+ }, no = () => J.clear(), ro = new jt(), io = (e) => ro.run({ n: 1 }, e), ao = (e) => k.suspend(() => {
1745
+ let t = ro.getStore();
1746
+ if (t !== void 0) return t.n += 1, k.ensuring(e, k.sync(() => {
1747
+ --t.n;
1748
+ }));
1749
+ let n = { n: 1 };
1750
+ return ro.enterWith(n), k.ensuring(e, k.sync(() => {
1751
+ --n.n;
1752
+ }));
1753
+ }), oo = () => (ro.getStore()?.n ?? 0) > 0, so = (e) => {
1754
+ if (J.size === 0 || (ro.getStore()?.n ?? 0) > 0) return !1;
1755
+ for (let t of J.values()) if (!t.ownTables.has(e) && t.tables.has(e)) return !0;
1747
1756
  return !1;
1748
- }, io = async (e, t) => {
1749
- if (q.size !== 0) {
1750
- for (let [n, r] of q.entries()) if (!r.ownTables.has(t.table) && r.tables.has(t.table)) try {
1757
+ }, co = async (e, t) => {
1758
+ if (J.size !== 0) {
1759
+ for (let [n, r] of J.entries()) if (!r.ownTables.has(t.table) && r.tables.has(t.table)) try {
1751
1760
  await r.recorder(e, t);
1752
1761
  } catch (e) {
1753
- let r = fn(e);
1762
+ let r = un(e);
1754
1763
  throw r === void 0 ? e : Error(`write recorder '${n}' failed while recording a ${t.op} on '${t.table}': ${r}`, { cause: e });
1755
1764
  }
1756
1765
  }
1757
- }, ao = kt.exponential({
1766
+ }, lo = Dt.exponential({
1758
1767
  start: 5e-4,
1759
1768
  factor: 2,
1760
1769
  count: 16
1761
- }), oo = D.counter("voltro_db_queries_total", { description: "Database operations executed, by dialect and operation kind." }), so = D.histogram("voltro_db_query_duration_seconds", ao, "Database operation duration in seconds, by dialect and operation kind."), co = D.counter("voltro_db_errors_total", { description: "Database operations that threw, by dialect and operation kind." }), lo = D.gauge("voltro_db_operations_in_flight", { description: "Database operations currently executing, by dialect. An upper bound on connections the framework holds; NOT the driver pool's waiting count." }), uo = D.counter("voltro_db_eager_fallback_total", { description: "Eager-load queries that degraded from the single-roundtrip JSON-agg path to the multi-query walker, by dialect and reason." }), fo = [], po = /* @__PURE__ */ new Map(), mo = /* @__PURE__ */ new Map(), ho = /* @__PURE__ */ new Map(), go = (e, t) => {
1762
- let n = `${e}\u0000${t}`, r = po.get(n);
1770
+ }), uo = A.counter("voltro_db_queries_total", { description: "Database operations executed, by dialect and operation kind." }), fo = A.histogram("voltro_db_query_duration_seconds", lo, "Database operation duration in seconds, by dialect and operation kind."), po = A.counter("voltro_db_errors_total", { description: "Database operations that threw, by dialect and operation kind." }), mo = 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." }), ho = 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." }), go = [], _o = /* @__PURE__ */ new Map(), vo = /* @__PURE__ */ new Map(), yo = /* @__PURE__ */ new Map(), bo = (e, t) => {
1771
+ let n = `${e}\u0000${t}`, r = _o.get(n);
1763
1772
  if (r !== void 0) return r;
1764
- let i = (n) => D.tagged(D.tagged(n, "dialect", e), "op", t), a = {
1765
- count: i(oo),
1766
- duration: i(so),
1767
- errors: i(co)
1773
+ let i = (n) => A.tagged(A.tagged(n, "dialect", e), "op", t), a = {
1774
+ count: i(uo),
1775
+ duration: i(fo),
1776
+ errors: i(po)
1768
1777
  };
1769
- return po.set(n, a), a;
1770
- }, _o = () => {
1771
- po.clear(), mo.clear(), ho.clear();
1772
- }, vo = () => po.size + mo.size + ho.size, yo = /* @__PURE__ */ new Map(), bo = (e, t) => {
1773
- let n = Math.max(0, (yo.get(e) ?? 0) + t);
1774
- n === 0 ? yo.delete(e) : yo.set(e, n);
1775
- let r = mo.get(e);
1776
- r === void 0 && (r = D.tagged(lo, "dialect", e), mo.set(e, r)), r.unsafeUpdate(n, fo);
1777
- }, xo = (e) => yo.get(e) ?? 0, So = (e) => {
1778
- let t = go(String(e.dialect), e.op);
1779
- t.count.unsafeUpdate(1, fo), t.duration.unsafeUpdate(e.durationMs / 1e3, fo), e.status === "error" && t.errors.unsafeUpdate(1, fo);
1780
- }, Co = async (e, t, n) => {
1778
+ return _o.set(n, a), a;
1779
+ }, xo = () => {
1780
+ _o.clear(), vo.clear(), yo.clear();
1781
+ }, So = () => _o.size + vo.size + yo.size, Co = /* @__PURE__ */ new Map(), wo = (e, t) => {
1782
+ let n = Math.max(0, (Co.get(e) ?? 0) + t);
1783
+ n === 0 ? Co.delete(e) : Co.set(e, n);
1784
+ let r = vo.get(e);
1785
+ r === void 0 && (r = A.tagged(mo, "dialect", e), vo.set(e, r)), r.unsafeUpdate(n, go);
1786
+ }, To = (e) => Co.get(e) ?? 0, Eo = (e) => {
1787
+ let t = bo(String(e.dialect), e.op);
1788
+ t.count.unsafeUpdate(1, go), t.duration.unsafeUpdate(e.durationMs / 1e3, go), e.status === "error" && t.errors.unsafeUpdate(1, go);
1789
+ }, Do = async (e, t, n) => {
1781
1790
  let r = performance.now(), i = String(e);
1782
- bo(i, 1);
1791
+ wo(i, 1);
1783
1792
  let a = "ok";
1784
1793
  try {
1785
1794
  return await n();
1786
1795
  } catch (e) {
1787
1796
  throw a = "error", e;
1788
1797
  } finally {
1789
- bo(i, -1), So({
1798
+ wo(i, -1), Eo({
1790
1799
  dialect: e,
1791
1800
  op: t,
1792
1801
  durationMs: performance.now() - r,
1793
1802
  status: a
1794
1803
  });
1795
1804
  }
1796
- }, wo = 3e5, To = (e) => {
1805
+ }, Oo = 3e5, ko = (e) => {
1797
1806
  if (e == null || e === "") return;
1798
1807
  let t = Number(e);
1799
1808
  return Number.isFinite(t) && t >= 0 ? Math.floor(t) : void 0;
1800
- }, Eo = (e, t = process.env) => To(t.VOLTRO_DB_EAGER_FALLBACK_WARN_INTERVAL_MS) ?? To(e) ?? 3e5, Do = (e, t = {}) => {
1801
- let n = Eo(t.warnIntervalMs), r = t.now ?? (() => Date.now()), i = /* @__PURE__ */ new Map();
1809
+ }, Ao = (e, t = process.env) => ko(t.VOLTRO_DB_EAGER_FALLBACK_WARN_INTERVAL_MS) ?? ko(e) ?? 3e5, jo = (e, t = {}) => {
1810
+ let n = Ao(t.warnIntervalMs), r = t.now ?? (() => Date.now()), i = /* @__PURE__ */ new Map();
1802
1811
  return (t) => {
1803
- let a = `${t.dialect} ${t.reason}`, o = ho.get(a);
1804
- o === void 0 && (o = D.tagged(D.tagged(uo, "dialect", String(t.dialect)), "reason", t.reason), ho.set(a, o)), o.unsafeUpdate(1, fo);
1812
+ let a = `${t.dialect} ${t.reason}`, o = yo.get(a);
1813
+ o === void 0 && (o = A.tagged(A.tagged(ho, "dialect", String(t.dialect)), "reason", t.reason), yo.set(a, o)), o.unsafeUpdate(1, go);
1805
1814
  let s = `${t.table}\u0000${t.reason}`, c = i.get(s), l = c === void 0 || n > 0 && r() - c >= n, u = {
1806
1815
  table: t.table,
1807
1816
  dialect: String(t.dialect),
@@ -1815,24 +1824,24 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
1815
1824
  }
1816
1825
  i.set(s, r()), e.warn(t.reason === "execute-failed" ? "eager-load JSON-agg statement FAILED and was re-run on the multi-query walker — this query pays both paths on every call. Counted as voltro_db_eager_fallback_total{reason=\"execute-failed\"}." : "eager-load could not be compiled to a single JSON-agg roundtrip and is running on the multi-query walker — one round trip per relation level, on every call. Counted as voltro_db_eager_fallback_total{reason=\"not-compilable\"}.", u);
1817
1826
  };
1818
- }, Oo = (e) => {
1819
- if (Ot.isSuccess(e)) return e.value;
1820
- throw Tt.squash(e.cause);
1821
- }, ko = "10 millis", Ao = 3, jo = async (e) => {
1822
- let t = 0, n = E.suspend(() => {
1827
+ }, Mo = (e) => {
1828
+ if (Et.isSuccess(e)) return e.value;
1829
+ throw Ct.squash(e.cause);
1830
+ }, No = "10 millis", Po = 3, Fo = async (e) => {
1831
+ let t = 0, n = k.suspend(() => {
1823
1832
  let n = ++t;
1824
- return e.withTransaction(E.flatMap(E.serviceOption(Ft), (t) => {
1825
- if (O.isNone(t)) return E.fail(/* @__PURE__ */ Error(`${e.label}: TransactionConnection unexpectedly missing inside withTransaction.`));
1826
- let r = t.value, i = E.tryPromise({
1833
+ return e.withTransaction(k.flatMap(k.serviceOption(Nt), (t) => {
1834
+ if (j.isNone(t)) return k.fail(/* @__PURE__ */ Error(`${e.label}: TransactionConnection unexpectedly missing inside withTransaction.`));
1835
+ let r = t.value, i = k.tryPromise({
1827
1836
  try: () => e.body(r, n),
1828
1837
  catch: (e) => e
1829
1838
  });
1830
- return e.prepare === void 0 ? i : E.flatMap(e.prepare(r), () => i);
1831
- })).pipe(E.catchAllDefect((t) => e.isRetryable(t) ? E.fail(t) : E.die(t)));
1832
- }), r = jt.exponential(ko).pipe(jt.compose(jt.recurs(Ao)), jt.whileInput(e.isRetryable)), i = n.pipe(E.retry(r), E.withSpan(e.span.name, { attributes: { ...e.span.attributes } }));
1833
- return Co(e.dialect, "transaction", async () => Oo(await e.runPromiseExit(e.wrapProgram === void 0 ? i : e.wrapProgram(i))));
1834
- }, Mo = async (e) => {
1835
- let t = Aa(), n = t === void 0 ? (e) => e() : (e) => ka(t, e), r = await jo({
1839
+ return e.prepare === void 0 ? i : k.flatMap(e.prepare(r), () => i);
1840
+ })).pipe(k.catchAllDefect((t) => e.isRetryable(t) ? k.fail(t) : k.die(t)));
1841
+ }), r = kt.exponential(No).pipe(kt.compose(kt.recurs(Po)), kt.whileInput(e.isRetryable)), i = n.pipe(k.retry(r), k.withSpan(e.span.name, { attributes: { ...e.span.attributes } }));
1842
+ return Do(e.dialect, "transaction", async () => Mo(await e.runPromiseExit(e.wrapProgram === void 0 ? i : e.wrapProgram(i))));
1843
+ }, Io = async (e) => {
1844
+ let t = Aa(), n = t === void 0 ? (e) => e() : (e) => ka(t, e), r = await Fo({
1836
1845
  ...e,
1837
1846
  body: (r) => {
1838
1847
  let i = e.makeView(r, t);
@@ -1843,14 +1852,14 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
1843
1852
  }
1844
1853
  });
1845
1854
  return r.view.commitEvents(), r.result;
1846
- }, No = class extends k.TaggedError()("VersionConflict", {
1847
- table: k.String,
1848
- id: k.String,
1849
- expected: k.Number,
1850
- actual: k.NullOr(k.Number)
1851
- }) {}, Po = (e) => {
1855
+ }, Lo = class extends M.TaggedError()("VersionConflict", {
1856
+ table: M.String,
1857
+ id: M.String,
1858
+ expected: M.Number,
1859
+ actual: M.NullOr(M.Number)
1860
+ }) {}, Ro = (e) => {
1852
1861
  for (let [t, n] of Object.entries(e)) if (n?.definition?.versionColumn === !0) return t;
1853
- }, Fo = (e) => {
1862
+ }, zo = (e) => {
1854
1863
  let { versionColumn: t, patch: n } = e;
1855
1864
  if (t === void 0) return {
1856
1865
  nextVersion: void 0,
@@ -1863,26 +1872,26 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
1863
1872
  expected: i,
1864
1873
  patch: a
1865
1874
  };
1866
- }, Io = (e) => {
1867
- if (e.expected !== void 0 && (e.current === null || e.current !== e.expected)) return new No({
1875
+ }, Bo = (e) => {
1876
+ if (e.expected !== void 0 && (e.current === null || e.current !== e.expected)) return new Lo({
1868
1877
  table: e.table,
1869
1878
  id: e.id,
1870
1879
  expected: e.expected,
1871
1880
  actual: e.current
1872
1881
  });
1873
- }, Lo = 1, Ro = "voltro/expires", zo = () => st({
1874
- id: Ro,
1875
- fields: { expiresAt: S().nullable() },
1882
+ }, Vo = 1, Ho = "voltro/expires", Uo = () => Ge({
1883
+ id: Ho,
1884
+ fields: { expiresAt: C().nullable() },
1876
1885
  behaviors: { defaultWhere: () => "expiresAt IS NULL OR expiresAt > now()" }
1877
- }), Bo = "voltro/localFirst", Vo = () => st({
1878
- id: Bo,
1886
+ }), Wo = "voltro/localFirst", Go = () => Ge({
1887
+ id: Wo,
1879
1888
  fields: {}
1880
- }), Ho = (e) => e.appliedMixins.some((e) => e.id === Bo), Uo = (e) => {
1889
+ }), Ko = (e) => e.appliedMixins.some((e) => e.id === Wo), qo = (e) => {
1881
1890
  let t = [];
1882
- for (let n of Object.values(e)) Ho(n) && t.push(n.tableName);
1891
+ for (let n of Object.values(e)) Ko(n) && t.push(n.tableName);
1883
1892
  return t;
1884
- }, Wo = class extends Dt.TaggedError("TableStreamError") {}, Go = 1e3, Ko = (e, t, n, r) => {
1885
- let i = O.match(r, {
1893
+ }, Jo = class extends Tt.TaggedError("TableStreamError") {}, Yo = 1e3, Xo = (e, t, n, r) => {
1894
+ let i = j.match(r, {
1886
1895
  onNone: () => e.where,
1887
1896
  onSome: (n) => e.where ? la(e.where, Ji(t, n)) : Ji(t, n)
1888
1897
  });
@@ -1899,19 +1908,19 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
1899
1908
  ...e.includeDeleted === void 0 ? {} : { includeDeleted: e.includeDeleted },
1900
1909
  ...e.crossTenant === void 0 ? {} : { crossTenant: e.crossTenant }
1901
1910
  };
1902
- }, qo = (e, t) => {
1903
- let n = t.pk ?? "id", r = t.chunkSize ?? Go;
1904
- return Mt.paginateChunkEffect(O.none(), (i) => {
1905
- let a = E.tryPromise({
1906
- try: () => e.query(Ko(t, n, r, i)),
1907
- catch: (e) => new Wo({
1911
+ }, Zo = (e, t) => {
1912
+ let n = t.pk ?? "id", r = t.chunkSize ?? Yo;
1913
+ return At.paginateChunkEffect(j.none(), (i) => {
1914
+ let a = k.tryPromise({
1915
+ try: () => e.query(Xo(t, n, r, i)),
1916
+ catch: (e) => new Jo({
1908
1917
  table: t.table,
1909
1918
  cause: e
1910
1919
  })
1911
1920
  });
1912
- return (t.retry ? a.pipe(E.retry(t.retry)) : a).pipe(E.map((e) => [Et.fromIterable(e), e.length === r && e.length > 0 ? O.some(O.some(e[e.length - 1][n])) : O.none()]));
1921
+ return (t.retry ? a.pipe(k.retry(t.retry)) : a).pipe(k.map((e) => [wt.fromIterable(e), e.length === r && e.length > 0 ? j.some(j.some(e[e.length - 1][n])) : j.none()]));
1913
1922
  });
1914
- }, Jo = (e) => {
1923
+ }, Qo = (e) => {
1915
1924
  let t = e.alpha ?? .5;
1916
1925
  if (t < 0 || t > 1) throw Error(`hybridSearch: alpha must be in [0, 1], got ${t}`);
1917
1926
  return (n) => {
@@ -1925,7 +1934,7 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
1925
1934
  queryText: e.vector.query,
1926
1935
  distance: e.vector.distance ?? "cosine",
1927
1936
  alpha: t
1928
- }, i = ee(n.table, e.fts.indexName, n.fullTextIndexes);
1937
+ }, i = _(n.table, e.fts.indexName, n.fullTextIndexes);
1929
1938
  return {
1930
1939
  ...n,
1931
1940
  annClause: r,
@@ -1938,17 +1947,17 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
1938
1947
  }
1939
1948
  };
1940
1949
  };
1941
- }, Yo = async (e, t) => {
1950
+ }, $o = async (e, t) => {
1942
1951
  let n = e.as ?? "embedding", r = t.row[e.from];
1943
1952
  if (typeof r != "string" || r.length === 0) return {};
1944
1953
  let i = await t.embed(r);
1945
1954
  return { [n]: i };
1946
- }, Xo = (e) => {
1955
+ }, es = (e) => {
1947
1956
  if (!Number.isInteger(e.dimensions) || e.dimensions <= 0) throw Error(`vectorEmbedding: dimensions must be a positive integer, got ${String(e.dimensions)}.`);
1948
- let t = e.as ?? "embedding", n = (t) => Yo(e, t);
1949
- return st({
1957
+ let t = e.as ?? "embedding", n = (t) => $o(e, t);
1958
+ return Ge({
1950
1959
  id: "voltro/vectorEmbedding",
1951
- fields: { [t]: Te(e.dimensions) },
1960
+ fields: { [t]: Ee(e.dimensions) },
1952
1961
  ...e.index === !1 ? {} : { indexes: [{
1953
1962
  fields: [t],
1954
1963
  kind: "hnsw",
@@ -1963,19 +1972,19 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
1963
1972
  beforeUpdate: n
1964
1973
  }
1965
1974
  });
1966
- }, Zo = 63, Qo = "br_pr", J = class extends Error {
1975
+ }, ts = 63, ns = "br_pr", Y = class extends Error {
1967
1976
  _tag = "BranchNameInvalid";
1968
1977
  constructor(e) {
1969
1978
  super(e), this.name = "BranchNameInvalid";
1970
1979
  }
1971
- }, $o = (e, t) => {
1972
- if (!Number.isInteger(t) || t < 0) throw new J(`prNumber must be a non-negative integer, got ${String(t)}`);
1980
+ }, rs = (e, t) => {
1981
+ if (!Number.isInteger(t) || t < 0) throw new Y(`prNumber must be a non-negative integer, got ${String(t)}`);
1973
1982
  let n = br(e);
1974
- if (n.replace(/_/g, "") === "") throw new J(`app slug '${e}' has no usable identifier characters`);
1975
- let r = `${Qo}${t}_${n}`;
1976
- if (r.length > Zo) throw new J(`branch namespace '${r}' exceeds the ${Zo}-byte identifier limit — use a shorter app slug`);
1983
+ if (n.replace(/_/g, "") === "") throw new Y(`app slug '${e}' has no usable identifier characters`);
1984
+ let r = `${ns}${t}_${n}`;
1985
+ if (r.length > ts) throw new Y(`branch namespace '${r}' exceeds the ${ts}-byte identifier limit — use a shorter app slug`);
1977
1986
  return r;
1978
- }, es = (e) => e.startsWith(Qo), ts = {
1987
+ }, is = (e) => e.startsWith(ns), as = {
1979
1988
  requested: {
1980
1989
  provision: "provisioning",
1981
1990
  destroy: "destroying"
@@ -1994,19 +2003,19 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
1994
2003
  fail: "failed"
1995
2004
  },
1996
2005
  destroyed: {}
1997
- }, ns = class extends Error {
2006
+ }, os = class extends Error {
1998
2007
  from;
1999
2008
  event;
2000
2009
  _tag = "BranchTransitionInvalid";
2001
2010
  constructor(e, t) {
2002
2011
  super(`invalid branch transition: ${e} --${t}-->`), this.from = e, this.event = t, this.name = "BranchTransitionInvalid";
2003
2012
  }
2004
- }, rs = (e, t) => {
2005
- let n = ts[e][t];
2006
- if (n === void 0) throw new ns(e, t);
2013
+ }, ss = (e, t) => {
2014
+ let n = as[e][t];
2015
+ if (n === void 0) throw new os(e, t);
2007
2016
  return n;
2008
- }, is = (e, t, n, r, i = [], a = []) => {
2009
- if (n === "copy" && (r === void 0 || r === "")) throw new J("seed 'copy' requires a parentNamespace to snapshot from");
2017
+ }, cs = (e, t, n, r, i = [], a = []) => {
2018
+ if (n === "copy" && (r === void 0 || r === "")) throw new Y("seed 'copy' requires a parentNamespace to snapshot from");
2010
2019
  let o = [{
2011
2020
  kind: "create-namespace",
2012
2021
  detail: e
@@ -2035,13 +2044,13 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
2035
2044
  kind: "seed",
2036
2045
  detail: `run boot seeds into ${e}`
2037
2046
  }), o;
2038
- }, as = (e) => {
2039
- if (!es(e)) throw new J(`refusing to plan teardown of '${e}' — not a branch namespace`);
2047
+ }, ls = (e) => {
2048
+ if (!is(e)) throw new Y(`refusing to plan teardown of '${e}' — not a branch namespace`);
2040
2049
  return [{
2041
2050
  kind: "drop-namespace",
2042
2051
  detail: e
2043
2052
  }];
2044
- }, os = (e) => {
2053
+ }, us = (e) => {
2045
2054
  if (e === void 0 || e === "") return !1;
2046
2055
  try {
2047
2056
  let t = new URL(e).hostname.toLowerCase();
@@ -2049,27 +2058,27 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
2049
2058
  } catch {
2050
2059
  return /\bneon\.(tech|build)\b/i.test(e);
2051
2060
  }
2052
- }, ss = (e) => e.prefer === void 0 ? e.seed === "copy" && os(e.dbUrl) ? "neon-cow" : "namespace" : e.prefer, cs = (e, t = {}) => [{
2061
+ }, ds = (e) => e.prefer === void 0 ? e.seed === "copy" && us(e.dbUrl) ? "neon-cow" : "namespace" : e.prefer, fs = (e, t = {}) => [{
2053
2062
  kind: "neon-branch-create",
2054
2063
  detail: `${t.parentBranch ?? "main"} → ${e} (copy-on-write)`
2055
- }], ls = (e) => {
2056
- if (!es(e)) throw new J(`refusing to plan teardown of '${e}' — not a branch namespace`);
2064
+ }], ps = (e) => {
2065
+ if (!is(e)) throw new Y(`refusing to plan teardown of '${e}' — not a branch namespace`);
2057
2066
  return [{
2058
2067
  kind: "neon-branch-delete",
2059
2068
  detail: e
2060
2069
  }];
2061
- }, us = (e) => e.mechanism === "neon-cow" ? cs(e.branchId, e.neonParentBranch === void 0 ? {} : { parentBranch: e.neonParentBranch }) : is(e.branchId, e.tableNames, e.seed, e.parentNamespace, e.foreignKeys, e.indexNames), ds = (e, t) => e === "neon-cow" ? ls(t) : as(t), fs = (e, t, n) => {
2070
+ }, ms = (e) => e.mechanism === "neon-cow" ? fs(e.branchId, e.neonParentBranch === void 0 ? {} : { parentBranch: e.neonParentBranch }) : cs(e.branchId, e.tableNames, e.seed, e.parentNamespace, e.foreignKeys, e.indexNames), hs = (e, t) => e === "neon-cow" ? ps(t) : ls(t), gs = (e, t, n) => {
2062
2071
  let r = e.filter((e) => e.state !== "destroyed" && e.state !== "destroying"), i = r.filter((e) => n - e.createdAtMs > t.ttlMs).map((e) => e.namespace), a = new Set(i);
2063
2072
  return {
2064
2073
  evict: i,
2065
2074
  rejectNew: r.filter((e) => !a.has(e.namespace)).length >= t.maxBranches
2066
2075
  };
2067
- }, ps = async (e, t) => {
2068
- let n = $o(e.appSlug, e.prNumber), r = ss({
2076
+ }, _s = async (e, t) => {
2077
+ let n = rs(e.appSlug, e.prNumber), r = ds({
2069
2078
  seed: e.seed,
2070
2079
  ...e.dbUrl === void 0 ? {} : { dbUrl: e.dbUrl },
2071
2080
  ...e.prefer === void 0 ? {} : { prefer: e.prefer }
2072
- }), i = us({
2081
+ }), i = ms({
2073
2082
  mechanism: r,
2074
2083
  branchId: n,
2075
2084
  tableNames: e.tableNames,
@@ -2098,16 +2107,16 @@ var Lt = (e) => typeof e == "string" && e !== "" ? e : null, Rt = async (e, t, n
2098
2107
  mechanism: r,
2099
2108
  steps: i
2100
2109
  };
2101
- }, ms = async (e, t, n) => {
2102
- let r = ds(t, e);
2110
+ }, vs = async (e, t, n) => {
2111
+ let r = hs(t, e);
2103
2112
  return t === "neon-cow" ? await n.neonBranchDelete(e) : await n.dropNamespace(e), r;
2104
- }, hs = (e, t, n) => fs(e, t, n), Y = (e) => `"${e.replace(/"/g, "\"\"")}"`, gs = {
2113
+ }, ys = (e, t, n) => gs(e, t, n), X = (e) => `"${e.replace(/"/g, "\"\"")}"`, bs = {
2105
2114
  cascade: "CASCADE",
2106
2115
  restrict: "RESTRICT",
2107
2116
  setNull: "SET NULL",
2108
2117
  noAction: "NO ACTION"
2109
- }, X = (e) => `'${e.replace(/'/g, "''")}'`, _s = (e, t) => {
2110
- let n = t.columns.map(X).join(", ");
2118
+ }, Z = (e) => `'${e.replace(/'/g, "''")}'`, xs = (e, t) => {
2119
+ let n = t.columns.map(Z).join(", ");
2111
2120
  return `DO $voltro_branch$
2112
2121
  DECLARE derived name;
2113
2122
  BEGIN
@@ -2116,11 +2125,11 @@ BEGIN
2116
2125
  JOIN pg_class i ON i.oid = x.indexrelid
2117
2126
  JOIN pg_class c ON c.oid = x.indrelid
2118
2127
  JOIN pg_namespace nsp ON nsp.oid = c.relnamespace
2119
- WHERE nsp.nspname = ${X(e)}
2120
- AND c.relname = ${X(t.table)}
2128
+ WHERE nsp.nspname = ${Z(e)}
2129
+ AND c.relname = ${Z(t.table)}
2121
2130
  AND NOT x.indisprimary
2122
2131
  AND x.indisunique = ${t.unique ? "true" : "false"}
2123
- AND i.relname <> ${X(t.name)}
2132
+ AND i.relname <> ${Z(t.name)}
2124
2133
  AND (
2125
2134
  SELECT array_agg(att.attname::text ORDER BY k.ord)
2126
2135
  FROM unnest(x.indkey::int2[]) WITH ORDINALITY AS k(attnum, ord)
@@ -2129,39 +2138,39 @@ BEGIN
2129
2138
  LIMIT 1;
2130
2139
  IF derived IS NOT NULL THEN
2131
2140
  EXECUTE format('ALTER INDEX %I.%I RENAME TO %I',
2132
- ${X(e)}, derived, ${X(t.name)});
2141
+ ${Z(e)}, derived, ${Z(t.name)});
2133
2142
  END IF;
2134
2143
  END
2135
2144
  $voltro_branch$`;
2136
- }, vs = (e, t) => {
2137
- let n = t.onDelete === void 0 ? "" : ` ON DELETE ${gs[t.onDelete]}`, r = t.onUpdate === void 0 ? "" : ` ON UPDATE ${gs[t.onUpdate]}`;
2138
- return `ALTER TABLE ${Y(e)}.${Y(t.table)} ADD FOREIGN KEY (${Y(t.column)}) REFERENCES ${Y(e)}.${Y(t.targetTable)} (${Y(t.targetColumn)})${n}${r}`;
2139
- }, ys = (e) => {
2145
+ }, Ss = (e, t) => {
2146
+ let n = t.onDelete === void 0 ? "" : ` ON DELETE ${bs[t.onDelete]}`, r = t.onUpdate === void 0 ? "" : ` ON UPDATE ${bs[t.onUpdate]}`;
2147
+ return `ALTER TABLE ${X(e)}.${X(t.table)} ADD FOREIGN KEY (${X(t.column)}) REFERENCES ${X(e)}.${X(t.targetTable)} (${X(t.targetColumn)})${n}${r}`;
2148
+ }, Cs = (e) => {
2140
2149
  let t = () => {
2141
2150
  throw Error("namespace branch executor: Neon ops require a neon-cow executor (use a Neon connection for copy-on-write branches)");
2142
2151
  };
2143
2152
  return {
2144
- createNamespace: (t) => e.run(`CREATE SCHEMA IF NOT EXISTS ${Y(t)}`),
2145
- createTable: (t, n) => e.run(`CREATE TABLE IF NOT EXISTS ${Y(t)}.${Y(n)} (LIKE ${Y(n)} INCLUDING ALL)`),
2146
- copyTable: (t, n, r) => e.run(`INSERT INTO ${Y(n)}.${Y(r)} SELECT * FROM ${Y(t)}.${Y(r)}`),
2147
- addForeignKey: (t, n) => e.run(vs(t, n)),
2148
- restoreIndexName: (t, n) => e.run(_s(t, n)),
2149
- dropNamespace: (t) => e.run(`DROP SCHEMA IF EXISTS ${Y(t)} CASCADE`),
2153
+ createNamespace: (t) => e.run(`CREATE SCHEMA IF NOT EXISTS ${X(t)}`),
2154
+ createTable: (t, n) => e.run(`CREATE TABLE IF NOT EXISTS ${X(t)}.${X(n)} (LIKE ${X(n)} INCLUDING ALL)`),
2155
+ copyTable: (t, n, r) => e.run(`INSERT INTO ${X(n)}.${X(r)} SELECT * FROM ${X(t)}.${X(r)}`),
2156
+ addForeignKey: (t, n) => e.run(Ss(t, n)),
2157
+ restoreIndexName: (t, n) => e.run(xs(t, n)),
2158
+ dropNamespace: (t) => e.run(`DROP SCHEMA IF EXISTS ${X(t)} CASCADE`),
2150
2159
  neonBranchCreate: t,
2151
2160
  neonBranchDelete: t
2152
2161
  };
2153
- }, bs = class extends Error {
2162
+ }, ws = class extends Error {
2154
2163
  _tag = "TenantResidencyUnresolved";
2155
2164
  constructor(e) {
2156
2165
  super(e), this.name = "TenantResidencyUnresolved";
2157
2166
  }
2158
- }, xs = class extends Error {
2167
+ }, Ts = class extends Error {
2159
2168
  region;
2160
2169
  _tag = "TenantRegionUnavailable";
2161
2170
  constructor(e, t) {
2162
2171
  super(t), this.region = e, this.name = "TenantRegionUnavailable";
2163
2172
  }
2164
- }, Ss, Cs = (e) => {
2173
+ }, Es, Ds = (e) => {
2165
2174
  if (e.homes === void 0) throw Error("setResidencyConfig: `homes` is required");
2166
2175
  if (e.servableRegions === void 0 || e.servableRegions.length === 0) throw Error("setResidencyConfig: `servableRegions` must be non-empty (which regions this deployment serves)");
2167
2176
  let t = /* @__PURE__ */ new Map();
@@ -2170,98 +2179,98 @@ $voltro_branch$`;
2170
2179
  if (e !== void 0 && e !== n.region) throw Error(`residency: tenant '${n.tenantId}' is mapped to two regions ('${e}' and '${n.region}')`);
2171
2180
  t.set(n.tenantId, n.region);
2172
2181
  }
2173
- return Ss = e, e;
2174
- }, ws = () => Ss, Ts = () => {
2175
- Ss = void 0;
2176
- }, Es = (e, t) => {
2177
- if (e == null || e === "") throw new bs("residency is on but the request has no resolvable tenant — refusing to bind a store");
2182
+ return Es = e, e;
2183
+ }, Os = () => Es, ks = () => {
2184
+ Es = void 0;
2185
+ }, As = (e, t) => {
2186
+ if (e == null || e === "") throw new ws("residency is on but the request has no resolvable tenant — refusing to bind a store");
2178
2187
  let n = t.homes.find((t) => t.tenantId === e);
2179
- if (n === void 0) throw new bs(`no residency home is mapped for tenant '${e}' — refusing to fall back to a default store (would be a residency violation)`);
2188
+ if (n === void 0) throw new ws(`no residency home is mapped for tenant '${e}' — refusing to fall back to a default store (would be a residency violation)`);
2180
2189
  return n;
2181
- }, Ds = (e, t) => t.servableRegions.includes(e), Os = (e, t) => {
2182
- let n = Es(e.tenantId, t), r = xr(n.tenantId);
2190
+ }, js = (e, t) => t.servableRegions.includes(e), Ms = (e, t) => {
2191
+ let n = As(e.tenantId, t), r = xr(n.tenantId);
2183
2192
  return {
2184
2193
  region: n.region,
2185
2194
  namespace: r,
2186
2195
  ...n.connectionKey === void 0 ? {} : { connectionKey: n.connectionKey }
2187
2196
  };
2188
- }, ks = (e, t, n) => {
2189
- let r = Os(e, t);
2190
- if (!Ds(r.region, t)) throw new xs(r.region, `tenant homed in region '${r.region}', which this deployment does not serve — route to the home region`);
2197
+ }, Ns = (e, t, n) => {
2198
+ let r = Ms(e, t);
2199
+ if (!js(r.region, t)) throw new Ts(r.region, `tenant homed in region '${r.region}', which this deployment does not serve — route to the home region`);
2191
2200
  let i = n.get(r.region);
2192
- if (i === void 0) throw new xs(r.region, `no store handle for home region '${r.region}' (declared servable but not wired) — failing closed`);
2201
+ if (i === void 0) throw new Ts(r.region, `no store handle for home region '${r.region}' (declared servable but not wired) — failing closed`);
2193
2202
  return {
2194
2203
  store: i,
2195
2204
  placement: r
2196
2205
  };
2197
- }, As = async (e, t, n, r) => {
2198
- let { store: i, placement: a } = ks(e, t, n);
2206
+ }, Ps = async (e, t, n, r) => {
2207
+ let { store: i, placement: a } = Ns(e, t, n);
2199
2208
  return await r(i, a), a;
2200
- }, js = (e) => {
2209
+ }, Fs = (e) => {
2201
2210
  if (typeof e == "string") return e;
2202
2211
  if ("jsonPath" in e) {
2203
2212
  let { column: t, path: n, numeric: r } = e.jsonPath;
2204
2213
  return `(json:${t}->${n.join(".")}${r ? "::num" : ""})`;
2205
2214
  }
2206
2215
  return `(${e.expr})`;
2207
- }, Z = (e) => e.map(js), Ms = (e, t) => {
2216
+ }, Q = (e) => e.map(Fs), Is = (e, t) => {
2208
2217
  if (e.length !== t.length) return !1;
2209
- for (let n = 0; n < e.length; n++) if (js(e[n]) !== js(t[n])) return !1;
2218
+ for (let n = 0; n < e.length; n++) if (Fs(e[n]) !== Fs(t[n])) return !1;
2210
2219
  return !0;
2211
- }, Ns = (e, t) => {
2220
+ }, Ls = (e, t) => {
2212
2221
  if (e.length >= t.length) return !1;
2213
- for (let n = 0; n < e.length; n++) if (js(e[n]) !== js(t[n])) return !1;
2222
+ for (let n = 0; n < e.length; n++) if (Fs(e[n]) !== Fs(t[n])) return !1;
2214
2223
  return !0;
2215
- }, Ps = (e) => {
2224
+ }, Rs = (e) => {
2216
2225
  let t = [], n = e.appliedIndexes, r = e.tableName;
2217
2226
  for (let e = 0; e < n.length; e++) {
2218
2227
  let i = n[e];
2219
2228
  for (let a = e + 1; a < n.length; a++) {
2220
2229
  let e = n[a];
2221
- if (Ms(i.fields, e.fields)) {
2230
+ if (Is(i.fields, e.fields)) {
2222
2231
  let [n, a] = i.name < e.name ? [i, e] : [e, i];
2223
2232
  t.push({
2224
2233
  kind: "duplicate-fields",
2225
2234
  table: r,
2226
2235
  redundant: n,
2227
2236
  coveredBy: a,
2228
- message: `'${r}' has two indexes on the same fields [${Z(i.fields).join(", ")}]: '${i.name}' and '${e.name}'. The B-tree engine builds both, costing write throughput + disk space for no read benefit. Drop '${n.name}' (or '${a.name}' if you prefer the other name). Applies to every supported dialect (Postgres / MySQL / MariaDB / MSSQL / SQLite).`
2237
+ message: `'${r}' has two indexes on the same fields [${Q(i.fields).join(", ")}]: '${i.name}' and '${e.name}'. The B-tree engine builds both, costing write throughput + disk space for no read benefit. Drop '${n.name}' (or '${a.name}' if you prefer the other name). Applies to every supported dialect (Postgres / MySQL / MariaDB / MSSQL / SQLite).`
2229
2238
  });
2230
2239
  continue;
2231
2240
  }
2232
- Ns(i.fields, e.fields) ? t.push({
2241
+ Ls(i.fields, e.fields) ? t.push({
2233
2242
  kind: "redundant-prefix",
2234
2243
  table: r,
2235
2244
  redundant: i,
2236
2245
  coveredBy: e,
2237
- message: `'${r}' index '${i.name}' on [${Z(i.fields).join(", ")}] is a leading prefix of '${e.name}' on [${Z(e.fields).join(", ")}]. Every B-tree dialect we support (Postgres / MySQL / MariaDB / MSSQL / SQLite) can serve a [${Z(i.fields).join(", ")}] query from '${e.name}' too via the leading-prefix rule, so '${i.name}' adds write cost without read benefit. Drop '${i.name}' — unless you specifically need a smaller index for cache locality on a write-heavy table (rare; profile first).`
2238
- }) : Ns(e.fields, i.fields) && t.push({
2246
+ message: `'${r}' index '${i.name}' on [${Q(i.fields).join(", ")}] is a leading prefix of '${e.name}' on [${Q(e.fields).join(", ")}]. Every B-tree dialect we support (Postgres / MySQL / MariaDB / MSSQL / SQLite) can serve a [${Q(i.fields).join(", ")}] query from '${e.name}' too via the leading-prefix rule, so '${i.name}' adds write cost without read benefit. Drop '${i.name}' — unless you specifically need a smaller index for cache locality on a write-heavy table (rare; profile first).`
2247
+ }) : Ls(e.fields, i.fields) && t.push({
2239
2248
  kind: "redundant-prefix",
2240
2249
  table: r,
2241
2250
  redundant: e,
2242
2251
  coveredBy: i,
2243
- message: `'${r}' index '${e.name}' on [${Z(e.fields).join(", ")}] is a leading prefix of '${i.name}' on [${Z(i.fields).join(", ")}]. Every B-tree dialect we support (Postgres / MySQL / MariaDB / MSSQL / SQLite) can serve a [${Z(e.fields).join(", ")}] query from '${i.name}' too via the leading-prefix rule, so '${e.name}' adds write cost without read benefit. Drop '${e.name}' — unless you specifically need a smaller index for cache locality on a write-heavy table (rare; profile first).`
2252
+ message: `'${r}' index '${e.name}' on [${Q(e.fields).join(", ")}] is a leading prefix of '${i.name}' on [${Q(i.fields).join(", ")}]. Every B-tree dialect we support (Postgres / MySQL / MariaDB / MSSQL / SQLite) can serve a [${Q(e.fields).join(", ")}] query from '${i.name}' too via the leading-prefix rule, so '${e.name}' adds write cost without read benefit. Drop '${e.name}' — unless you specifically need a smaller index for cache locality on a write-heavy table (rare; profile first).`
2244
2253
  });
2245
2254
  }
2246
2255
  }
2247
2256
  return t;
2248
- }, Fs = (e) => {
2257
+ }, zs = (e) => {
2249
2258
  let t = [];
2250
- for (let n of e) t.push(...Ps(n));
2259
+ for (let n of e) t.push(...Rs(n));
2251
2260
  return t;
2252
- }, Is = "\x1B[", Ls = `${Is}38;2;245;158;11m`, Rs = `${Is}38;2;16;185;129m`, zs = (e, t) => `${e}${t}${A.reset}`, Q = (e, t, n) => e ? typeof t == "function" ? t(n) : zs(t, n) : n, Bs = (e, t = {}) => {
2253
- let n = t.color ?? !0, r = t.indent ?? " ", i = (e) => Q(n, A.dim, e.padEnd(11)), a = (e) => Q(n, (e) => A.bold(A.brand(e)), e), o = (e) => Q(n, A.brightRed24, e), s = (e) => Q(n, Rs, e), c = (e) => Q(n, Ls, e), l = (e) => Q(n, A.dim, e), u = `${c("index audit")} ${l("·")} ${Q(n, A.bold, e.kind)}`, d = e.redundant.fields.length, f = Z(e.coveredBy.fields.slice(d)), p = (e, t) => {
2261
+ }, Bs = "\x1B[", Vs = `${Bs}38;2;245;158;11m`, Hs = `${Bs}38;2;16;185;129m`, Us = (e, t) => `${e}${t}${N.reset}`, $ = (e, t, n) => e ? typeof t == "function" ? t(n) : Us(t, n) : n, Ws = (e, t = {}) => {
2262
+ 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, Hs, e), c = (e) => $(n, Vs, 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) => {
2254
2263
  let n = e.slice(0, t), r = e.slice(t), i = [];
2255
2264
  return n.length > 0 && i.push(s(`[${n.join(", ")}]`)), r.length > 0 && i.push(c(`+ [${r.join(", ")}]`)), i.join(" ");
2256
2265
  }, m = [];
2257
- return m.push(u), m.push(""), m.push(`${i("table")}${a(e.table)}`), m.push(""), m.push(`${i("redundant")}${o(e.redundant.name)}`), m.push(`${i("")}${p(Z(e.redundant.fields), d)}`), m.push(""), m.push(`${i("covered by")}${s(e.coveredBy.name)}`), m.push(`${i("")}${p(Z(e.coveredBy.fields), d)}`), f.length > 0 && m.push(`${i("")}${l(`└ extra columns: ${f.join(", ")}`)}`), m.push(""), e.kind === "redundant-prefix" ? (m.push(`${i("why")}B-tree indexes serve queries that filter on a LEADING PREFIX of`), m.push(`${i("")}their column list. The wider index already covers every`), m.push(`${i("")}query the narrower one can serve.`), m.push(`${i("")}${l("Same rule on Postgres / MySQL / MariaDB / MSSQL / SQLite.")}`)) : (m.push(`${i("why")}Two indexes on the same columns under different names.`), m.push(`${i("")}The B-tree engine builds both — same coverage, double cost.`), m.push(`${i("")}${l("Same rule on Postgres / MySQL / MariaDB / MSSQL / SQLite.")}`)), m.push(""), m.push(`${i("cost")}Every ${a("INSERT")} / ${a("UPDATE")} / ${a("DELETE")} on this table writes`), m.push(`${i("")}to ${Q(n, A.bold, "both")} B-trees. Pure write overhead, zero read benefit.`), m.push(""), m.push(`${i("fix")}Drop ${o(e.redundant.name)}`), m.push(`${i("")}${l("Keep only if profiling shows the smaller index gives a")}`), m.push(`${i("")}${l("measurable cache-locality boost on a write-heavy hot path.")}`), m.push(`${i("")}${l("Silence with VOLTRO_INDEX_AUDIT=off if intentional.")}`), m.map((e) => `${r}${e}`).join("\n");
2258
- }, Vs = (e, { apply: t, undo: n }) => ({
2266
+ return m.push(u), m.push(""), m.push(`${i("table")}${a(e.table)}`), m.push(""), m.push(`${i("redundant")}${o(e.redundant.name)}`), m.push(`${i("")}${p(Q(e.redundant.fields), d)}`), m.push(""), m.push(`${i("covered by")}${s(e.coveredBy.name)}`), m.push(`${i("")}${p(Q(e.coveredBy.fields), d)}`), f.length > 0 && m.push(`${i("")}${l(`└ extra columns: ${f.join(", ")}`)}`), m.push(""), e.kind === "redundant-prefix" ? (m.push(`${i("why")}B-tree indexes serve queries that filter on a LEADING PREFIX of`), m.push(`${i("")}their column list. The wider index already covers every`), m.push(`${i("")}query the narrower one can serve.`), m.push(`${i("")}${l("Same rule on Postgres / MySQL / MariaDB / MSSQL / SQLite.")}`)) : (m.push(`${i("why")}Two indexes on the same columns under different names.`), m.push(`${i("")}The B-tree engine builds both — same coverage, double cost.`), m.push(`${i("")}${l("Same rule on Postgres / MySQL / MariaDB / MSSQL / SQLite.")}`)), m.push(""), m.push(`${i("cost")}Every ${a("INSERT")} / ${a("UPDATE")} / ${a("DELETE")} on this table writes`), m.push(`${i("")}to ${$(n, 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");
2267
+ }, Gs = (e, { apply: t, undo: n }) => ({
2259
2268
  name: e,
2260
2269
  apply: t,
2261
2270
  undo: n
2262
- }), Hs = (e) => {
2271
+ }), Ks = (e) => {
2263
2272
  if (!/^\d{14}_/.test(e.id)) throw Error(`migration "${e.id}": id must start with a 14-digit timestamp followed by "_" (convention: <YYYYMMDDHHMMSS>_<slug>)`);
2264
- let t = e.steps({ step: Vs });
2273
+ let t = e.steps({ step: Gs });
2265
2274
  if (t.length === 0) throw Error(`migration "${e.id}": at least one step is required`);
2266
2275
  return {
2267
2276
  __migration: !0,
@@ -2269,99 +2278,117 @@ $voltro_branch$`;
2269
2278
  name: e.name,
2270
2279
  steps: t
2271
2280
  };
2272
- }, Us = (e) => typeof e == "object" && !!e && "__migration" in e && e.__migration === !0, Ws = T("_voltro_migrations", {
2273
- id: b({ prefix: "mig" }),
2274
- name: v(),
2275
- hash: v(),
2276
- status: v(),
2277
- appliedAt: S().nullable(),
2278
- durationMs: x().nullable(),
2279
- errorMessage: v().nullable(),
2280
- errorStack: v().nullable(),
2281
- workflowRunId: v().nullable(),
2282
- createdAt: S().default("now"),
2283
- updatedAt: S().default("now").onUpdate("now")
2284
- }).index(["status"]), Gs = T("_voltro_seeds", {
2285
- id: b({ prefix: "seed" }),
2286
- name: v(),
2287
- lifecycle: v(),
2288
- fingerprint: v(),
2289
- cronSchedule: v().nullable(),
2290
- watchedTables: i().nullable(),
2291
- nextRunAt: S().nullable(),
2292
- lastRunStatus: v().nullable(),
2293
- lastRunAt: S().nullable(),
2294
- lastRunDurationMs: x().nullable(),
2295
- lastRunRowsTouched: x().nullable(),
2296
- lastError: v().nullable(),
2297
- workflowRunId: v().nullable(),
2298
- createdAt: S().default("now"),
2299
- updatedAt: S().default("now").onUpdate("now")
2300
- }).index(["lifecycle"]).index(["nextRunAt"]), Ks = T("_voltro_migration_plans", {
2301
- id: b({ prefix: "plan" }),
2302
- fingerprint: v(),
2303
- liveFingerprint: v().nullable(),
2304
- operations: i(),
2305
- rollbackPlan: i().nullable(),
2306
- appliedBy: v(),
2307
- environment: v(),
2308
- source: v(),
2309
- onlineStrategy: v().nullable(),
2310
- durationMs: x(),
2311
- notes: v().nullable(),
2312
- squashedAt: S().nullable(),
2313
- appliedAt: S().default("now"),
2314
- createdAt: S().default("now"),
2315
- updatedAt: S().default("now").onUpdate("now")
2316
- }).index(["fingerprint"]).index(["environment"]), qs = T("_voltro_idempotency", {
2317
- id: b({ prefix: "idem" }),
2318
- scope: v(),
2319
- key: v(),
2320
- status: v(),
2321
- response: i().nullable(),
2322
- createdAt: S().default("now")
2323
- }).unique(["scope", "key"]).index(["createdAt"]), Js = T("_voltro_kv", {
2324
- id: b({ prefix: "kv" }),
2325
- key: v().unique(),
2326
- value: v().nullable(),
2327
- expiresAt: S().nullable(),
2328
- createdAt: S().default("now"),
2329
- updatedAt: S().default("now").onUpdate("now")
2330
- }).index(["expiresAt"]), Ys = T("_voltro_api_keys", {
2331
- id: b({ prefix: "apikey" }),
2332
- tenantId: v().nullable(),
2333
- name: v(),
2334
- hashedKey: v().maxLength(64).unique(),
2335
- keyPrefix: v(),
2336
- scopes: i().nullable(),
2337
- lastUsedAt: S().nullable(),
2338
- requestCount: x().default(0),
2339
- expiresAt: S().nullable(),
2340
- revokedAt: S().nullable(),
2341
- createdBy: v().nullable(),
2342
- onBehalfOf: v().nullable(),
2343
- metadata: i().nullable(),
2344
- createdAt: S().default("now")
2345
- }).index("byApiKeyTenant", ["tenantId"]), Xs = [
2346
- Ws,
2347
- Gs,
2348
- Ks
2349
- ], $ = "id", Zs = (e, t) => {
2281
+ }, qs = (e) => typeof e == "object" && !!e && "__migration" in e && e.__migration === !0, Js = E("_voltro_migrations", {
2282
+ id: x({ prefix: "mig" }),
2283
+ name: w(),
2284
+ hash: w(),
2285
+ status: w(),
2286
+ appliedAt: C().nullable(),
2287
+ durationMs: O().nullable(),
2288
+ errorMessage: w().nullable(),
2289
+ errorStack: w().nullable(),
2290
+ workflowRunId: w().nullable(),
2291
+ createdAt: C().default("now"),
2292
+ updatedAt: C().default("now").onUpdate("now")
2293
+ }).index(["status"]), Ys = E("_voltro_seeds", {
2294
+ id: x({ prefix: "seed" }),
2295
+ name: w(),
2296
+ lifecycle: w(),
2297
+ fingerprint: w(),
2298
+ cronSchedule: w().nullable(),
2299
+ watchedTables: S().nullable(),
2300
+ nextRunAt: C().nullable(),
2301
+ lastRunStatus: w().nullable(),
2302
+ lastRunAt: C().nullable(),
2303
+ lastRunDurationMs: O().nullable(),
2304
+ lastRunRowsTouched: O().nullable(),
2305
+ lastError: w().nullable(),
2306
+ workflowRunId: w().nullable(),
2307
+ createdAt: C().default("now"),
2308
+ updatedAt: C().default("now").onUpdate("now")
2309
+ }).index(["lifecycle"]).index(["nextRunAt"]), Xs = E("_voltro_migration_plans", {
2310
+ id: x({ prefix: "plan" }),
2311
+ fingerprint: w(),
2312
+ liveFingerprint: w().nullable(),
2313
+ operations: S(),
2314
+ rollbackPlan: S().nullable(),
2315
+ appliedBy: w(),
2316
+ environment: w(),
2317
+ source: w(),
2318
+ onlineStrategy: w().nullable(),
2319
+ durationMs: O(),
2320
+ notes: w().nullable(),
2321
+ squashedAt: C().nullable(),
2322
+ appliedAt: C().default("now"),
2323
+ createdAt: C().default("now"),
2324
+ updatedAt: C().default("now").onUpdate("now")
2325
+ }).index(["fingerprint"]).index(["environment"]), Zs = E("_voltro_idempotency", {
2326
+ id: x({ prefix: "idem" }),
2327
+ scope: w(),
2328
+ key: w(),
2329
+ status: w(),
2330
+ response: S().nullable(),
2331
+ createdAt: C().default("now")
2332
+ }).unique(["scope", "key"]).index(["createdAt"]), Qs = E("_voltro_kv", {
2333
+ id: x({ prefix: "kv" }),
2334
+ key: w().unique(),
2335
+ value: w().nullable(),
2336
+ expiresAt: C().nullable(),
2337
+ createdAt: C().default("now"),
2338
+ updatedAt: C().default("now").onUpdate("now")
2339
+ }).index(["expiresAt"]), $s = E("_voltro_api_keys", {
2340
+ id: x({ prefix: "apikey" }),
2341
+ tenantId: w().nullable(),
2342
+ name: w(),
2343
+ hashedKey: w().maxLength(64).unique(),
2344
+ keyPrefix: w(),
2345
+ scopes: S().nullable(),
2346
+ lastUsedAt: C().nullable(),
2347
+ requestCount: O().default(0),
2348
+ expiresAt: C().nullable(),
2349
+ revokedAt: C().nullable(),
2350
+ createdBy: w().nullable(),
2351
+ onBehalfOf: w().nullable(),
2352
+ metadata: S().nullable(),
2353
+ createdAt: C().default("now")
2354
+ }).index("byApiKeyTenant", ["tenantId"]), ec = [
2355
+ Js,
2356
+ Ys,
2357
+ Xs
2358
+ ], tc = "_voltro_replace_in_progress", nc = E(tc, {
2359
+ id: x({ prefix: "repl" }),
2360
+ startedAt: C().default("now"),
2361
+ tables: w(),
2362
+ capture: w().nullable(),
2363
+ via: w()
2364
+ }), rc = (e) => {
2365
+ if (e.length !== 0) return `refusing to start: a destructive import did not finish.
2366
+ ${e.map((e) => {
2367
+ let t = Number.isFinite(e.startedAt.getTime()) ? `${Math.max(0, Math.round((Date.now() - e.startedAt.getTime()) / 6e4))} minute(s) ago` : "at an unknown time";
2368
+ return ` - a \`replace\` over ${e.via} began emptying ${e.tables} table(s) ${t} and never reported finishing.\n` + (e.capture === null ? " NO capture was taken for that run, so the previous rows are not recoverable from here.\n Restore from your own backup." : ` The target's previous rows were captured first:\n ${e.capture}\n Restore them with: voltro data import ${e.capture} --mode replace`);
2369
+ }).join("\n")}\n
2370
+ A half-replaced database is indistinguishable from an empty one from the inside — every table
2371
+ exists, every constraint holds, and every query returns nothing without erroring. That is why
2372
+ this is a refusal and not a warning.
2373
+
2374
+ When the data is back, or you have decided the current state is correct, clear the marker:
2375
+ voltro data clear-replace-marker --yes`;
2376
+ }, ic = "id", ac = (e, t) => {
2350
2377
  let n = p(e);
2351
2378
  if (n === void 0) return t;
2352
- let r = n.fields[$]?.idScheme;
2353
- if (r === void 0 || t[$] != null) return t;
2379
+ let r = n.fields[ic]?.idScheme;
2380
+ if (r === void 0 || t[ic] != null) return t;
2354
2381
  if (r.kind === "numeric") {
2355
- if (!($ in t)) return t;
2382
+ if (!(ic in t)) return t;
2356
2383
  let e = { ...t };
2357
- return delete e[$], e;
2384
+ return delete e[ic], e;
2358
2385
  }
2359
- let i = lt(r, e);
2386
+ let i = Pe(r, e);
2360
2387
  return i === null ? t : {
2361
2388
  ...t,
2362
- [$]: i
2389
+ [ic]: i
2363
2390
  };
2364
- }, Qs = (e, t) => t.map((t) => Zs(e, t)), $s = {
2391
+ }, oc = (e, t) => t.map((t) => ac(e, t)), sc = {
2365
2392
  postgres: { maxBindParameters: 65535 },
2366
2393
  mysql: { maxBindParameters: 65535 },
2367
2394
  mariadb: { maxBindParameters: 65535 },
@@ -2371,49 +2398,49 @@ $voltro_branch$`;
2371
2398
  },
2372
2399
  sqlite: { maxBindParameters: 32766 },
2373
2400
  turso: { maxBindParameters: 32766 }
2374
- }, ec = (e) => $s[e], tc = (e) => {
2401
+ }, cc = (e) => sc[e], lc = (e) => {
2375
2402
  let t = /* @__PURE__ */ new Set();
2376
2403
  for (let n of e) for (let e of Object.keys(n)) t.add(e);
2377
2404
  return t.size;
2378
- }, nc = (e, t) => {
2405
+ }, uc = (e, t) => {
2379
2406
  if (t === void 0 || e.length === 0) return [e];
2380
- let n = Math.max(1, tc(e)), r = Math.floor(t.maxBindParameters / n), i = t.maxRowsPerStatement ?? Infinity, a = Math.max(1, Math.min(r, i));
2407
+ let n = Math.max(1, lc(e)), r = Math.floor(t.maxBindParameters / n), i = t.maxRowsPerStatement ?? Infinity, a = Math.max(1, Math.min(r, i));
2381
2408
  if (e.length <= a) return [e];
2382
2409
  let o = [];
2383
2410
  for (let t = 0; t < e.length; t += a) o.push(e.slice(t, t + a));
2384
2411
  return o;
2385
- }, rc = (e, t) => {
2412
+ }, dc = (e, t) => {
2386
2413
  let n = [], r = t;
2387
2414
  for (let [t, i] of Object.entries(e.fields)) {
2388
2415
  let e = i;
2389
2416
  e.nullable || e.hasDefault || e.idScheme !== void 0 || e.generatedAs !== void 0 || (r[t] === void 0 || r[t] === null) && n.push(t);
2390
2417
  }
2391
2418
  return n;
2392
- }, ic = (e, t) => {
2419
+ }, fc = (e, t) => {
2393
2420
  let n = t;
2394
2421
  return e.filter((e) => n[e] === void 0 || n[e] === null);
2395
- }, ac = (e, t, n) => e.insert(t.tableName, n), oc = (e, t, n, r) => e.upsert(t.tableName, n, {
2422
+ }, pc = (e, t, n) => e.insert(t.tableName, n), mc = (e, t, n, r) => e.upsert(t.tableName, n, {
2396
2423
  conflictColumns: r.conflictColumns,
2397
2424
  ...r.update === void 0 ? {} : { update: r.update }
2398
- }), sc = (e, t, n, r) => e.updateMany(t.tableName, n, { where: r.where }), cc = 512, lc = (e) => {
2425
+ }), hc = (e, t, n, r) => e.updateMany(t.tableName, n, { where: r.where }), gc = 512, _c = (e) => {
2399
2426
  e.setMaxListeners(512);
2400
- }, uc = (e, t, n) => ({
2427
+ }, vc = (e, t, n) => ({
2401
2428
  _tag: "PrimaryKeyConflictError",
2402
2429
  table: e,
2403
2430
  key: t,
2404
2431
  cause: n
2405
- }), dc = (e) => typeof e == "object" && !!e && e._tag === "PrimaryKeyConflictError", fc = {
2432
+ }), yc = (e) => typeof e == "object" && !!e && e._tag === "PrimaryKeyConflictError", bc = {
2406
2433
  postgres: 5432,
2407
2434
  mysql: 3306,
2408
2435
  mariadb: 3306,
2409
2436
  mssql: 1433
2410
- }, pc = /* @__PURE__ */ new Set([
2437
+ }, xc = /* @__PURE__ */ new Set([
2411
2438
  "localhost",
2412
2439
  "127.0.0.1",
2413
2440
  "::1",
2414
2441
  "[::1]",
2415
2442
  "0.0.0.0"
2416
- ]), mc = (e) => {
2443
+ ]), Sc = (e) => {
2417
2444
  let t = e.host, n = e.port, r = e.database;
2418
2445
  if (e.url !== void 0 && e.url !== "") try {
2419
2446
  let i = new URL(e.url);
@@ -2422,29 +2449,29 @@ $voltro_branch$`;
2422
2449
  return;
2423
2450
  }
2424
2451
  if (t === void 0 || t === "" || r === void 0 || r === "") return;
2425
- let i = n ?? fc[(e.dialect ?? "").toLowerCase()];
2452
+ let i = n ?? bc[(e.dialect ?? "").toLowerCase()];
2426
2453
  if (i === void 0 || !Number.isFinite(i)) return;
2427
2454
  let a = t.toLowerCase();
2428
2455
  return {
2429
- host: pc.has(a) ? "localhost" : a,
2456
+ host: xc.has(a) ? "localhost" : a,
2430
2457
  port: i,
2431
2458
  database: r.toLowerCase()
2432
2459
  };
2433
- }, hc = (e) => {
2434
- let t = mc(e);
2435
- if (t !== void 0) return Pt("sha256").update(`${t.host}\u0000${t.port}\u0000${t.database}`).digest("hex").slice(0, 32);
2436
- }, gc = (e, t) => e === void 0 || t === void 0 ? "unknown" : e === t ? "same" : "different", _c = {
2460
+ }, Cc = (e) => {
2461
+ let t = Sc(e);
2462
+ if (t !== void 0) return Mt("sha256").update(`${t.host}\u0000${t.port}\u0000${t.database}`).digest("hex").slice(0, 32);
2463
+ }, wc = (e, t) => e === void 0 || t === void 0 ? "unknown" : e === t ? "same" : "different", Tc = {
2437
2464
  app: 3,
2438
2465
  plugin: 2,
2439
2466
  framework: 1
2440
- }, vc = /* @__PURE__ */ new Map(), yc = [], bc = () => [...yc], xc = (e) => {
2467
+ }, Ec = /* @__PURE__ */ new Map(), Dc = [], Oc = () => [...Dc], kc = (e) => {
2441
2468
  if (!e.table || !e.timeColumn) throw Error("registerRetention: table + timeColumn are required");
2442
2469
  if (!Number.isFinite(e.ttlMs) || e.ttlMs <= 0) throw Error(`registerRetention(${e.table}): ttlMs must be a positive number`);
2443
- let t = e.source ?? "app", n = vc.get(e.table);
2470
+ let t = e.source ?? "app", n = Ec.get(e.table);
2444
2471
  if (n !== void 0) {
2445
2472
  let r = n.source ?? "app", i = n.ttlMs !== e.ttlMs || n.where !== void 0 != (e.where !== void 0);
2446
- if (_c[t] < _c[r]) {
2447
- i && yc.push({
2473
+ if (Tc[t] < Tc[r]) {
2474
+ i && Dc.push({
2448
2475
  table: e.table,
2449
2476
  kept: {
2450
2477
  source: r,
@@ -2457,7 +2484,7 @@ $voltro_branch$`;
2457
2484
  });
2458
2485
  return;
2459
2486
  }
2460
- i && r !== t && yc.push({
2487
+ i && r !== t && Dc.push({
2461
2488
  table: e.table,
2462
2489
  kept: {
2463
2490
  source: t,
@@ -2469,35 +2496,46 @@ $voltro_branch$`;
2469
2496
  }
2470
2497
  });
2471
2498
  }
2472
- vc.set(e.table, {
2499
+ Ec.set(e.table, {
2473
2500
  ...e,
2474
2501
  source: t
2475
2502
  });
2476
- }, Sc = () => [...vc.values()], Cc = () => {
2477
- vc.clear(), yc.length = 0;
2478
- }, wc = async (e, t, n, r = 2e4) => {
2503
+ }, Ac = () => [...Ec.values()], jc = () => {
2504
+ Ec.clear(), Dc.length = 0;
2505
+ }, Mc = async (e, t, n, r = 2e4) => {
2479
2506
  let i = new Date(t - e.ttlMs), a = 0;
2480
2507
  for (;;) {
2481
2508
  let t = await n(e.table, e.timeColumn, i, r, e.where);
2482
2509
  if (a += t, t < r) break;
2483
2510
  }
2484
2511
  return a;
2485
- }, Tc = (e, t) => {
2512
+ }, Nc = (e, t) => {
2486
2513
  let n = Number(e ?? String(t));
2487
2514
  return (Number.isFinite(n) && n > 0 ? n : t) * 36e5;
2488
- }, Ec = "_voltro_cdc_offsets", Dc = T(Ec, {
2489
- id: b({ prefix: "cdcoff" }),
2490
- replicaId: v(),
2491
- streamName: v(),
2492
- binlogFile: v(),
2493
- binlogPosition: v(),
2494
- updatedAt: S()
2495
- }).index(["replicaId"]), Oc = T(Ec, {
2496
- id: b({ prefix: "cdcoff" }),
2497
- replicaId: v(),
2498
- streamName: v(),
2499
- ctVersion: v(),
2500
- updatedAt: S()
2501
- }).index(["replicaId"]), kc = "postgres";
2515
+ }, Pc = "_voltro_cdc_offsets", Fc = E(Pc, {
2516
+ id: x({ prefix: "cdcoff" }),
2517
+ replicaId: w(),
2518
+ streamName: w(),
2519
+ binlogFile: w(),
2520
+ binlogPosition: w(),
2521
+ updatedAt: C()
2522
+ }).index(["replicaId"]), Ic = E(Pc, {
2523
+ id: x({ prefix: "cdcoff" }),
2524
+ replicaId: w(),
2525
+ streamName: w(),
2526
+ ctVersion: w(),
2527
+ updatedAt: C()
2528
+ }).index(["replicaId"]), Lc = "_voltro_data_imports", Rc = E(Lc, {
2529
+ id: x({ prefix: "dimp" }),
2530
+ startedAt: C().default("now"),
2531
+ finishedAt: C().nullable(),
2532
+ mode: w(),
2533
+ via: w(),
2534
+ bundle: w().nullable(),
2535
+ sourceFingerprint: w().nullable(),
2536
+ tablesWritten: O().default(0),
2537
+ rowsWritten: O().default(0),
2538
+ failure: w().nullable()
2539
+ }).nonReactive(), zc = (e) => `${Number.isFinite(e.startedAt.getTime()) ? e.startedAt.toISOString() : "an unknown time"} · ${e.failure === null ? e.finishedAt === null ? `${e.mode} — started and never reported finishing` : `${e.mode} — ${e.rowsWritten} row(s) across ${e.tablesWritten} table(s)` : `FAILED ${e.mode} — ${e.failure}`} · via ${e.via}` + (e.bundle === null ? "" : ` · from ${e.bundle}`) + (e.sourceFingerprint === null ? "" : ` · source schema ${e.sourceFingerprint}`), Bc = "postgres";
2502
2540
  //#endregion
2503
- export { e as AUTO_FILLED_COLUMNS, $s as BULK_INSERT_LIMITS, J as BranchNameInvalid, ns as BranchTransitionInvalid, Ec as CDC_OFFSETS_TABLE, cc as CHANGE_LISTENER_CEILING, gt as ColumnBuilder, Ee as DEFAULT_ACQUIRE_TIMEOUT_MS, wo as DEFAULT_EAGER_FALLBACK_WARN_INTERVAL_MS, Bn as DEFAULT_SUBJECT_GRAPH_DEPTH, Ut as ENCRYPTED_PREFIX, kc as ENGINE, rr as EagerCardinalityError, Ge as FILE_MIGRATION_PATTERN, ut as FRAMEWORK_LIVE_TABLES, Wt as FieldDecryptionError, Ya as ID_COLUMN_MAX_LENGTH, Lo as INITIAL_VERSION, aa as MATCHES_NO_ROWS, Le as MAX_IDENTIFIER_LENGTH, It as SqlClient, Wo as TableStreamError, _r as TenantNamespaceInvalid, gr as TenantNamespaceUnresolved, xs as TenantRegionUnavailable, bs as TenantResidencyUnresolved, Ro as VOLTRO_EXPIRES_MIXIN_ID, Bo as VOLTRO_LOCAL_FIRST_MIXIN_ID, No as VersionConflict, Be as WARN_IDENTIFIER_LENGTH, Ys as _voltroApiKeysTable, Dc as _voltroCdcOffsetsTable, qs as _voltroIdempotencyTable, Js as _voltroKvTable, Ks as _voltroMigrationPlansTable, Ws as _voltroMigrationsTable, Oc as _voltroMssqlCdcOffsetsTable, Gs as _voltroSeedsTable, Gi as actorsTable, hs as admitBranch, mt as allEnumRenames, Ln as allRegisteredRelations, h as allRegisteredTables, la as and, _e as array, na as arrayContains, ia as arrayHas, ra as arrayOverlaps, ar as attachEagerLoads, ja as attributionFields, Fa as attributionKey, Fs as auditAllTableIndexes, Ps as auditTableIndexes, pt as avg, yt as avgOver, Wa as beginLocalWrite, u as bigint, ks as bindResidentStore, c as boolean, $o as branchNamespaceName, ec as bulkInsertLimitsFor, le as bytes, Ea as changeDelete, wa as changeInsert, Da as changeSoftDelete, Ta as changeUpdate, nc as chunkRowsForInsert, Ra as claimPendingAttribution, ln as classifyConstraintViolation, bt as clearEnumRenames, qa as clearPendingAttribution, zn as clearRelationsRegistry, Ts as clearResidencyConfig, Cc as clearRetentions, ve as clearTableRegistry, no as clearWriteRecorders, Tr as coercePredicateValue, Er as coercePredicateValues, xa as collectSubqueries, Me as column, hn as columnSchema, tc as columnsPerRow, Br as compileEagerJson, I as compilePredicate, Dr as compileRawFragment, zr as compileSelect, Yo as computeEmbedding, hc as connectionIdentity, ea as contains, _t as count, me as countDistinct, Ye as crdtManagedColumns, n as crdtText, Aa as currentWriteAttribution, a as databaseHandle, qe as date, ae as dbEnum, vo as dbMetricTagCacheSizeForTests, xo as dbOperationsInFlight, se as decimal, Ne as declareEnumRename, Yt as decodeFieldValue, er as decodeRowsFromSchema, en as decryptFieldsOnRead, Hs as defineMigration, st as defineMixin, ct as defineSeed, ht as denseRank, qn as deriveSubjectGraph, rt as deriveTypeIdPrefix, Qa as derivedRowId, $a as derivedRowIdLength, fn as describeDriverError, pn as describeRowBindings, Ht as deserializeArraysOnRead, it as drainIdentifierWarnings, de as dropped, qt as encodeFieldValue, nr as encodeRowForSchema, $t as encryptFieldsForWrite, Qt as encryptedColumnsOf, Ga as endLocalWrite, fs as enforceBranchLimits, Se as ensureTableRegistered, Ki as eq, Or as escapeLike, ba as evaluatePredicate, ge as except, ga as exists, zo as expires, Ca as externalChangeEvent, on as extractDbCause, Pe as fireSchemaChangeSeeds, Xe as fireTenantCreateSeeds, Bs as formatIndexAuditIssue, Jn as formatSubjectGraph, Xs as frameworkTables, lt as generateId, Ze as generateSnowflake, f as geography, te as geometry, vt as getEnumRenames, In as getRelation, Fn as getRelations, ws as getResidencyConfig, p as getTable, Ji as gt, Yi as gte, hr as hasEagerLoads, Jo as hybridSearch, b as id, Qi as inSet, ma as inSubquery, N as inferForeignKey, ac as insertRow, x as integer, l as intersect, St as interval, es as isBranchNamespace, Cn as isEmptyRelationsSpec, Kt as isEncrypted, Gt as isFieldDecryptionError, Ae as isFileMigration, un as isForeignKeyViolation, et as isFrameworkOwnedLiveTable, Ho as isLocalFirst, Us as isMigrationDefinition, we as isMysqlFamily, os as isNeonConnection, sa as isNotNull, oa as isNull, dc as isPrimaryKeyConflictError, dn as isQueryTimeout, Xt as isRawEncoding, Ds as isRegionServable, wn as isRelationsSpec, dt as isSeedDefinition, De as isSqliteFamily, ne as isTableReactive, Qe as isView, i as json, fa as jsonField, Re as jsonIndex, s as lag, ce as lead, bc as listRetentionConflicts, Sc as listRetentions, Vo as localFirst, Uo as localFirstTables, Xi as lt, Zi as lte, Do as makeEagerFallbackReporter, ys as makeNamespaceBranchExecutor, En as many, Dn as manyToMany, xe as materializeFields, Je as max, nt as migration, t as min, ic as missingConflictColumns, rc as missingRequiredColumns, Ke as mixin, qi as neq, rs as nextBranchState, mc as normaliseTarget, da as not, _a as notExists, $i as notInSet, ha as notInSubquery, g as numeric, Co as observeDbOp, Tn as one, ir as oneCardinalityMessage, ua as or, C as orderClausesOf, ie as paginateBy, oe as paginateById, Ja as pendingAttributionCount, us as planBranch, is as planBranchProvision, as as planBranchTeardown, ds as planBranchTeardownFor, cs as planNeonBranchProvision, ls as planNeonBranchTeardown, Fo as planVersionedUpdate, he as pluginRef, o as pluginRefSpecOf, uc as primaryKeyConflictError, ps as provisionBranch, As as provisionResidentTenant, Sr as qualifyTable, ue as queryFor, Ue as queryForView, fe as quoteIdent, lc as raiseChangeListenerCeiling, d as rank, ye as raw, Ce as readableByColumns, m as real, So as recordDbOp, ro as recordsTable, y as reference, Vi as registerCoreTables, Pn as registerDiscoveredRelations, La as registerPendingAttribution, Nn as registerRelations, xc as registerRetention, at as registerTable, eo as registerWriteRecorder, Sn as relations, Ui as requireActors, _ as requireTable, Wi as requireTenants, _o as resetDbMetricTagCacheForTests, ft as resetSnowflake, Os as residentPlacement, Rt as resolveActorSnapshot, ss as resolveBranchMechanism, Eo as resolveEagerFallbackWarnIntervalMs, Ka as resolveEchoAttribution, ee as resolveFullTextIndex, Fe as resolveIdScheme, je as resolveMixinGraph, Es as resolveTenantHome, xr as resolveTenantNamespace, Tc as retentionTtlMsFromEnv, re as rowNumber, gn as rowSchema, jo as runRetryingTransaction, Mo as runStoreTransaction, ka as runWithWriteAttribution, io as runWriteRecorders, gc as sameDatabase, br as sanitizeIdentifierFragment, Vt as serializeArraysForWrite, ot as serverOnlyColumns, Cs as setResidencyConfig, Ie as setSchemaChangeSeedHook, ze as setTenantCreateSeedHook, Oo as settleTransactionExit, Io as settleVersionedUpdate, ca as spatialPredicate, Zs as stampGeneratedId, Qs as stampGeneratedIds, ta as startsWith, qo as streamTable, pe as sum, xt as sumOver, wc as sweepRetention, T as table, ms as teardownBranch, v as text, S as timestamp, Ct as timestampMs, wt as timestampMsOrNull, r as union, be as unionAll, to as unregisterWriteRecorder, sc as updateManyRow, oc as upsertRow, $e as validateColumnName, We as validateIndexName, Rn as validateRegisteredRelations, An as validateRelationConfig, He as validateTableName, ke as validateTypeIdPrefix, Te as vector, tt as vectorDistanceToOpclass, Xo as vectorEmbedding, Po as versionColumnOf, Ve as view, Oe as viewSql, Sa as walkLeaves, Ma as withCapturedAttribution };
2541
+ export { Le as AUTO_FILLED_COLUMNS, sc as BULK_INSERT_LIMITS, Y as BranchNameInvalid, os as BranchTransitionInvalid, Pc as CDC_OFFSETS_TABLE, gc as CHANGE_LISTENER_CEILING, _e as ColumnBuilder, Ce as DEFAULT_ACQUIRE_TIMEOUT_MS, Oo as DEFAULT_EAGER_FALLBACK_WARN_INTERVAL_MS, Bn as DEFAULT_SUBJECT_GRAPH_DEPTH, Vt as ENCRYPTED_PREFIX, Bc as ENGINE, rr as EagerCardinalityError, We as FILE_MIGRATION_PATTERN, ct as FRAMEWORK_LIVE_TABLES, Ht as FieldDecryptionError, Ya as ID_COLUMN_MAX_LENGTH, Lc as IMPORT_RUNS_TABLE, Vo as INITIAL_VERSION, aa as MATCHES_NO_ROWS, ze as MAX_IDENTIFIER_LENGTH, tc as REPLACE_IN_PROGRESS_TABLE, Pt as SqlClient, Jo as TableStreamError, _r as TenantNamespaceInvalid, gr as TenantNamespaceUnresolved, Ts as TenantRegionUnavailable, ws as TenantResidencyUnresolved, Ho as VOLTRO_EXPIRES_MIXIN_ID, Wo as VOLTRO_LOCAL_FIRST_MIXIN_ID, Lo as VersionConflict, nt as WARN_IDENTIFIER_LENGTH, $s as _voltroApiKeysTable, Fc as _voltroCdcOffsetsTable, Zs as _voltroIdempotencyTable, Rc as _voltroImportRunsTable, Qs as _voltroKvTable, Xs as _voltroMigrationPlansTable, Js as _voltroMigrationsTable, Ic as _voltroMssqlCdcOffsetsTable, nc as _voltroReplaceInProgressTable, Ys as _voltroSeedsTable, Gi as actorsTable, ys as admitBranch, yt as allEnumRenames, Ln as allRegisteredRelations, h as allRegisteredTables, la as and, u as array, na as arrayContains, ia as arrayHas, ra as arrayOverlaps, ar as attachEagerLoads, ja as attributionFields, Fa as attributionKey, zs as auditAllTableIndexes, Rs as auditTableIndexes, ft as avg, vt as avgOver, Wa as beginLocalWrite, c as bigint, Ns as bindResidentStore, le as boolean, rs as branchNamespaceName, cc as bulkInsertLimitsFor, Je as bytes, Ea as changeDelete, wa as changeInsert, Da as changeSoftDelete, Ta as changeUpdate, uc as chunkRowsForInsert, Ra as claimPendingAttribution, sn as classifyConstraintViolation, Me as clearEnumRenames, qa as clearPendingAttribution, zn as clearRelationsRegistry, ks as clearResidencyConfig, jc as clearRetentions, ve as clearTableRegistry, no as clearWriteRecorders, Tr as coercePredicateValue, Er as coercePredicateValues, xa as collectSubqueries, je as column, pn as columnSchema, lc as columnsPerRow, Br as compileEagerJson, L as compilePredicate, Dr as compileRawFragment, zr as compileSelect, $o as computeEmbedding, Cc as connectionIdentity, ea as contains, gt as count, me as countDistinct, n as crdtManagedColumns, Ke as crdtText, Aa as currentWriteAttribution, a as databaseHandle, ae as date, se as dbEnum, So as dbMetricTagCacheSizeForTests, To as dbOperationsInFlight, de as decimal, _t as declareEnumRename, qt as decodeFieldValue, er as decodeRowsFromSchema, Qt as decryptFieldsOnRead, Ks as defineMigration, Ge as defineMixin, ot as defineSeed, mt as denseRank, qn as deriveSubjectGraph, st as deriveTypeIdPrefix, Qa as derivedRowId, $a as derivedRowIdLength, un as describeDriverError, zc as describeImportRun, dn as describeRowBindings, Bt as deserializeArraysOnRead, Qe as drainIdentifierWarnings, f as dropped, Gt as encodeFieldValue, nr as encodeRowForSchema, Zt as encryptFieldsForWrite, Xt as encryptedColumnsOf, Ga as endLocalWrite, gs as enforceBranchLimits, xe as ensureTableRegistered, Ki as eq, Or as escapeLike, ba as evaluatePredicate, ge as except, ga as exists, Uo as expires, Ca as externalChangeEvent, rn as extractDbCause, Ne as fireSchemaChangeSeeds, Ye as fireTenantCreateSeeds, Ws as formatIndexAuditIssue, Jn as formatSubjectGraph, ec as frameworkTables, Pe as generateId, dt as generateSnowflake, ee as geography, b as geometry, he as getEnumRenames, In as getRelation, Fn as getRelations, Os as getResidencyConfig, p as getTable, Ji as gt, Yi as gte, hr as hasEagerLoads, Qo as hybridSearch, x as id, Qi as inSet, ma as inSubquery, En as inferForeignKey, pc as insertRow, O as integer, rc as interruptedReplaceRefusal, l as intersect, i as interval, is as isBranchNamespace, xn as isEmptyRelationsSpec, Wt as isEncrypted, Ut as isFieldDecryptionError, ke as isFileMigration, cn as isForeignKeyViolation, $e as isFrameworkOwnedLiveTable, Ko as isLocalFirst, qs as isMigrationDefinition, Te as isMysqlFamily, us as isNeonConnection, sa as isNotNull, oa as isNull, yc as isPrimaryKeyConflictError, ln as isQueryTimeout, Jt as isRawEncoding, js as isRegionServable, Sn as isRelationsSpec, ut as isSeedDefinition, fe as isSqliteFamily, ne as isTableReactive, Ze as isView, S as json, fa as jsonField, lt as jsonIndex, s as lag, ce as lead, Oc as listRetentionConflicts, Ac as listRetentions, Go as localFirst, qo as localFirstTables, Xi as lt, Zi as lte, jo as makeEagerFallbackReporter, Cs as makeNamespaceBranchExecutor, wn as many, Tn as manyToMany, g as materializeFields, qe as max, et as migration, t as min, fc as missingConflictColumns, dc as missingRequiredColumns, Ae as mixin, qi as neq, ss as nextBranchState, Sc as normaliseTarget, da as not, _a as notExists, $i as notInSet, ha as notInSubquery, ye as numeric, Do as observeDbOp, Cn as one, ir as oneCardinalityMessage, ua as or, T as orderClausesOf, ie as paginateBy, oe as paginateById, Ja as pendingAttributionCount, ms as planBranch, cs as planBranchProvision, ls as planBranchTeardown, hs as planBranchTeardownFor, fs as planNeonBranchProvision, ps as planNeonBranchTeardown, zo as planVersionedUpdate, o as pluginRef, ht as pluginRefSpecOf, vc as primaryKeyConflictError, _s as provisionBranch, Ps as provisionResidentTenant, Sr as qualifyTable, ue as queryFor, He as queryForView, e as quoteIdent, _c as raiseChangeListenerCeiling, d as rank, Se as raw, m as readableByColumns, y as real, Eo as recordDbOp, so as recordsTable, it as reference, Vi as registerCoreTables, Pn as registerDiscoveredRelations, La as registerPendingAttribution, Nn as registerRelations, kc as registerRetention, rt as registerTable, eo as registerWriteRecorder, bn as relations, Ui as requireActors, v as requireTable, Wi as requireTenants, xo as resetDbMetricTagCacheForTests, Ie as resetSnowflake, Ms as residentPlacement, It as resolveActorSnapshot, ds as resolveBranchMechanism, Ao as resolveEagerFallbackWarnIntervalMs, Ka as resolveEchoAttribution, _ as resolveFullTextIndex, Xe as resolveIdScheme, tt as resolveMixinGraph, As as resolveTenantHome, xr as resolveTenantNamespace, Nc as retentionTtlMsFromEnv, re as rowNumber, mn as rowSchema, Fo as runRetryingTransaction, Io as runStoreTransaction, ka as runWithWriteAttribution, co as runWriteRecorders, wc as sameDatabase, br as sanitizeIdentifierFragment, zt as serializeArraysForWrite, te as serverOnlyColumns, Ds as setResidencyConfig, Fe as setSchemaChangeSeedHook, Re as setTenantCreateSeedHook, Mo as settleTransactionExit, Bo as settleVersionedUpdate, ca as spatialPredicate, ac as stampGeneratedId, oc as stampGeneratedIds, ta as startsWith, Zo as streamTable, pe as sum, bt as sumOver, io as suspendWriteRecorders, ao as suspendWriteRecordersEffect, Mc as sweepRetention, E as table, vs as teardownBranch, w as text, C as timestamp, xt as timestampMs, St as timestampMsOrNull, r as union, be as unionAll, we as unregisterTable, to as unregisterWriteRecorder, hc as updateManyRow, mc as upsertRow, Ue as validateColumnName, Ve as validateIndexName, Rn as validateRegisteredRelations, An as validateRelationConfig, Oe as validateTableName, pt as validateTypeIdPrefix, Ee as vector, at as vectorDistanceToOpclass, es as vectorEmbedding, Ro as versionColumnOf, Be as view, De as viewSql, Sa as walkLeaves, Ma as withCapturedAttribution, oo as writeRecordersSuspended };