@voltro/database 0.65.0 → 0.66.1

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,6 +1,6 @@
1
- import { $ as e, $t as t, A as n, At as r, B as i, Bt as a, C as o, Ct as s, D as c, Dt as l, E as u, Et as d, F as f, Ft as p, G as m, Gt as h, H as g, Ht as ee, I as te, It as ne, J as re, Jt as _, K as ie, Kt as ae, L as v, Lt as oe, M as y, Mt as se, N as b, Nt as ce, O as le, Ot as ue, P as de, Pt as fe, Q as pe, Qt as me, R as he, Rt as ge, S as _e, St as ve, T as ye, Tt as be, U as xe, Ut as Se, V as Ce, Vt as we, W as Te, Wt as Ee, X as De, Xt as x, Y as Oe, Yt as ke, Z as S, Zt as Ae, _ as je, _t as Me, a as Ne, an as C, at as Pe, b as Fe, bt as Ie, c as Le, ct as w, d as Re, dt as ze, en as Be, et as Ve, f as He, ft as Ue, g as We, gt as Ge, h as Ke, ht as qe, i as Je, in as Ye, it as Xe, j as Ze, jt as Qe, k as $e, kt as et, l as tt, lt as nt, m as rt, mt as it, n as at, nn as ot, nt as st, o as ct, on as T, ot as lt, p as ut, pt as dt, q as ft, qt as E, r as pt, rn as mt, rt as ht, s as gt, sn as _t, st as vt, t as yt, tn as bt, tt as xt, u as St, ut as Ct, v as wt, vt as Tt, w as Et, wt as Dt, x as Ot, xt as kt, y as D, yt as At, z as jt, zt as Mt } from "./frameworkLiveTables-BURogL9N.js";
2
- import { a as Nt, i as Pt, n as Ft, o as It, r as Lt, s as Rt, t as zt } from "./wire-B28cPjEp.js";
3
- import { Cause as O, Chunk as Bt, Data as Vt, Effect as k, Exit as Ht, Metric as A, MetricBoundaries as Ut, Option as j, Runtime as Wt, Schedule as Gt, Schema as M, Stream as Kt } from "effect";
1
+ import { $ as e, $t as t, A as n, At as r, B as i, Bt as a, C as o, Ct as s, D as c, Dt as l, E as u, Et as d, F as f, Ft as p, G as m, Gt as h, H as g, Ht as _, I as v, It as ee, J as te, Jt as y, K as ne, Kt as re, L as b, Lt as ie, M as x, Mt as ae, N as oe, Nt as se, O as ce, Ot as le, P as ue, Pt as de, Q as fe, Qt as pe, R as me, Rt as he, S as ge, St as _e, T as ve, Tt as ye, U as be, Ut as xe, V as Se, Vt as Ce, W as we, Wt as Te, X as Ee, Xt as S, Y as De, Yt as Oe, Z as C, Zt as ke, _ as Ae, _t as je, a as Me, an as w, at as Ne, b as Pe, bt as Fe, c as Ie, ct as T, d as Le, dt as Re, en as ze, et as Be, f as Ve, ft as He, g as Ue, gt as We, h as Ge, ht as Ke, i as qe, in as Je, it as Ye, j as Xe, jt as Ze, k as Qe, kt as $e, l as et, lt as tt, m as nt, mt as rt, n as it, nn as at, nt as ot, o as st, on as E, ot as ct, p as lt, pt as ut, q as dt, qt as D, r as ft, rn as pt, rt as mt, s as ht, sn as gt, st as _t, t as vt, tn as yt, tt as bt, u as xt, ut as St, v as Ct, vt as wt, w as Tt, wt as Et, x as Dt, xt as Ot, y as O, yt as kt, z as At, zt as jt } from "./frameworkLiveTables-CWbTSnjk.js";
2
+ import { a as Mt, i as Nt, n as Pt, o as Ft, r as It, s as Lt, t as Rt } from "./wire-B28cPjEp.js";
3
+ import { Cause as zt, Chunk as Bt, Data as Vt, Effect as k, Exit as Ht, Metric as A, MetricBoundaries as Ut, Option as j, Runtime as Wt, Schedule as Gt, Schema as M, Stream as Kt } from "effect";
4
4
  import { createHash as qt } from "node:crypto";
5
5
  import { AsyncLocalStorage as Jt } from "node:async_hooks";
6
6
  import { TransactionConnection as Yt } from "@effect/sql/SqlClient";
@@ -147,12 +147,12 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
147
147
  });
148
148
  }, bn = (e) => {
149
149
  let t = e;
150
- for (let e = 0; e < 4 && Wt.isFiberFailure(t); e++) t = O.squash(t[Wt.FiberFailureCauseId]);
150
+ for (let e = 0; e < 4 && Wt.isFiberFailure(t); e++) t = zt.squash(t[Wt.FiberFailureCauseId]);
151
151
  return t;
152
152
  }, xn = (e, t = 0) => {
153
153
  if (t >= 4 || !Wt.isFiberFailure(e)) return [e];
154
- let n = e[Wt.FiberFailureCauseId], r = [...O.failures(n), ...O.defects(n)];
155
- if (r.length === 0) return [O.squash(n)];
154
+ let n = e[Wt.FiberFailureCauseId], r = [...zt.failures(n), ...zt.defects(n)];
155
+ if (r.length === 0) return [zt.squash(n)];
156
156
  let i = [];
157
157
  for (let e of r.slice(0, 8)) i.push(...xn(e, t + 1));
158
158
  return i;
@@ -346,16 +346,16 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
346
346
  }, Bn = (e) => {
347
347
  let t = (() => {
348
348
  switch (e.type) {
349
- case "id":
350
- case "reference":
349
+ case "id": return e.idScheme?.kind === "numeric" ? M.Number : M.String;
351
350
  case "text":
352
351
  case "enum": return M.String;
352
+ case "reference": return e.referenceStorage === "numeric" ? M.Number : M.String;
353
353
  case "integer":
354
354
  case "real":
355
355
  case "decimal": return M.Number;
356
356
  case "boolean": return M.Boolean;
357
357
  case "timestamp":
358
- case "date": return zt;
358
+ case "date": return Rt;
359
359
  case "bigint": return M.BigInt;
360
360
  case "bytes": return M.Uint8ArrayFromBase64;
361
361
  case "array": return M.Array(M.Unknown);
@@ -462,7 +462,7 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
462
462
  return e;
463
463
  }, dr = () => {
464
464
  for (let [e, t] of I) {
465
- let n = S(e);
465
+ let n = C(e);
466
466
  if (n !== void 0) for (let [e, r] of t) rr(n, e, r);
467
467
  }
468
468
  }, fr = () => {
@@ -498,23 +498,28 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
498
498
  }
499
499
  if (t.sourceKey !== void 0) continue;
500
500
  let a = gr(i, e), o = t.foreignKey ?? (a.length === 1 ? a[0] : void 0);
501
- o === void 0 || !hr(i, o) || n.push({
501
+ if (o === void 0 || !hr(i, o)) continue;
502
+ let s = i.fields[o];
503
+ n.push({
502
504
  table: i.tableName,
503
505
  foreignKey: o,
504
- parentKey: "id"
506
+ parentKey: s?.referenceColumn ?? "id"
505
507
  });
506
508
  }
507
509
  return n;
508
510
  }, vr = (e, t) => {
509
511
  let n = [];
510
- for (let r of t) if (r.tableName !== e) for (let t of gr(r, e)) n.push({
511
- table: r.tableName,
512
- foreignKey: t,
513
- parentKey: "id"
514
- });
512
+ for (let r of t) if (r.tableName !== e) for (let t of gr(r, e)) {
513
+ let e = r.fields[t];
514
+ n.push({
515
+ table: r.tableName,
516
+ foreignKey: t,
517
+ parentKey: e?.referenceColumn ?? "id"
518
+ });
519
+ }
515
520
  return n;
516
521
  }, yr = (e) => `${e.table}\u0000${e.hops.map((e) => `${e.table}.${e.foreignKey}<-${e.parentKey}`).join("|")}`, br = (e) => {
517
- let t = e.tables ?? re(), n = e.relations ?? ur(), r = e.maxDepth ?? 4, i = new Set(e.exclude ?? []), a = new Map(t.map((e) => [e.tableName, e])), o = [];
522
+ let t = e.tables ?? te(), n = e.relations ?? ur(), r = e.maxDepth ?? 4, i = new Set(e.exclude ?? []), a = new Map(t.map((e) => [e.tableName, e])), o = [];
518
523
  if (!a.has(e.subjectTable)) return {
519
524
  subjectTable: e.subjectTable,
520
525
  paths: [],
@@ -621,7 +626,7 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
621
626
  }
622
627
  }, Dr = (e, t, n) => {
623
628
  if (e.length === 0) return e;
624
- let r = S(t);
629
+ let r = C(t);
625
630
  if (r === void 0) return e;
626
631
  let i = r.fields, a = [];
627
632
  for (let [e, t] of Object.entries(i)) a.push({
@@ -641,7 +646,7 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
641
646
  default: return e;
642
647
  }
643
648
  }, kr = (e, t, n = ["json", "array"]) => {
644
- let r = S(t);
649
+ let r = C(t);
645
650
  if (r === void 0) return e;
646
651
  let i = r.fields, a = null;
647
652
  for (let [t, r] of Object.entries(i)) if (n.includes(r.type) && t in e) {
@@ -649,15 +654,115 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
649
654
  n !== e[t] && (a === null && (a = { ...e }), a[t] = n);
650
655
  }
651
656
  return a ?? e;
652
- }, Ar = class extends Error {
657
+ }, Ar = (e) => Object.fromEntries(Object.entries(e.updateValues ?? {}).filter(([t, n]) => {
658
+ if (n === void 0) return !1;
659
+ if (t === "id" || e.conflictColumns.includes(t)) throw Error(`upsert: updateValues cannot rewrite row identity column '${t}'`);
660
+ return !0;
661
+ })), jr = (e, t, n) => {
662
+ let r = Ar(n);
663
+ if (typeof n.update == "function") return {
664
+ ...n.update(t),
665
+ ...r
666
+ };
667
+ let i = n.update ?? Object.keys(e).filter((e) => e !== "id" && !n.conflictColumns.includes(e));
668
+ return {
669
+ ...Object.fromEntries(i.filter((t) => t in e).map((t) => [t, e[t]])),
670
+ ...r
671
+ };
672
+ }, Mr = (e) => typeof e == "string" ? [["id", e]] : Object.entries(e).map(([e, t]) => [e, t]), Nr = (e) => {
673
+ if (typeof e == "string") return e;
674
+ let t = Object.entries(e);
675
+ return t.length === 1 ? String(t[0][1]) : t.slice().sort(([e], [t]) => e < t ? -1 : +(e > t)).map(([e, t]) => `${e}=${String(t)}`).join("\0");
676
+ }, Pr = (e) => typeof e != "string", Fr = (e, t, n) => {
677
+ let r = new Set(Mr(e).map(([e]) => e)), i = t.split(".")[0];
678
+ return Object.fromEntries(Object.entries(n ?? {}).filter(([e, t]) => {
679
+ if (t === void 0) return !1;
680
+ if (r.has(e) || e === i) throw Error(`patchJson: additionalPatch cannot rewrite the primary key or patched JSON column '${e}'`);
681
+ return !0;
682
+ }));
683
+ }, Ir = (e) => typeof e == "object" && !!e && !Array.isArray(e), Lr = (e) => JSON.parse(JSON.stringify(e ?? null)), Rr = (e, t, n) => {
684
+ let [r, ...i] = t.split("."), a = Lr(n), o = e[r], s = (e, t) => {
685
+ if (t === i.length) return a;
686
+ let n = Ir(e) ? e : {}, r = i[t], o = Object.hasOwn(n, r) ? n[r] : void 0;
687
+ return {
688
+ ...n,
689
+ [r]: s(o, t + 1)
690
+ };
691
+ };
692
+ return {
693
+ ...e,
694
+ [r]: i.length === 0 ? Ir(o) && Ir(a) ? {
695
+ ...o,
696
+ ...a
697
+ } : a : s(o, 0)
698
+ };
699
+ }, zr = (e, t, n, r, i) => {
700
+ let [a, ...o] = n.split("."), s = i ?? e`${e(a)}`, c = Lr(r), l = (e) => /["\\\u0000-\u001f]/.test(e);
701
+ if ((t === "sqlite" || t === "turso") && (o.some(l) || o.length === 0 && Ir(c) && Object.keys(c).some(l))) {
702
+ let t = 0, n = (t) => e`CASE WHEN (SELECT _voltro_json_escape_probe.key FROM json_each(${String.raw`{"\u0061":0}`}) AS _voltro_json_escape_probe) = ${String.raw`\u0061`}
703
+ THEN json_extract('"' || replace(${t}.key, '"', ${String.raw`\"`}) || '"', '$')
704
+ ELSE ${t}.key END`, r = (r) => {
705
+ let i = e`CASE WHEN json_type(${s}) = 'object' THEN ${s} ELSE '{}' END`;
706
+ for (let a of r) {
707
+ let r = e(`_voltro_json_${t++}`);
708
+ i = e`COALESCE((SELECT ${r}.value FROM json_each(${i}) AS ${r} WHERE ${n(r)} = ${a} AND ${r}.type = 'object'), '{}')`;
709
+ }
710
+ return i;
711
+ }, i = (r, i, a) => {
712
+ let o = e(`_voltro_json_${t++}`), s = e(`_voltro_json_${t++}`);
713
+ return e`(SELECT json_group_object(${s}.k, json(${s}.v)) FROM (
714
+ SELECT ${n(o)} AS k, CASE ${o}.type
715
+ WHEN 'true' THEN 'true' WHEN 'false' THEN 'false'
716
+ WHEN 'object' THEN ${o}.value WHEN 'array' THEN ${o}.value
717
+ ELSE json_quote(${o}.value) END AS v
718
+ FROM json_each(${r}) AS ${o} WHERE ${n(o)} <> ${i}
719
+ UNION ALL SELECT ${i}, ${a}
720
+ ) AS ${s})`;
721
+ }, l;
722
+ if (o.length === 0) {
723
+ l = r([]);
724
+ for (let [t, n] of Object.entries(c)) l = i(l, t, e`${JSON.stringify(n)}`);
725
+ } else {
726
+ l = e`${JSON.stringify(c)}`;
727
+ for (let e = o.length - 1; e >= 0; e--) l = i(r(o.slice(0, e)), o[e], l);
728
+ }
729
+ return e`${e(a)} = ${l}`;
730
+ }
731
+ let u = (e) => "$" + e.map((e) => `.${JSON.stringify(e)}`).join(""), d = (t) => e`ARRAY[${e.csv(t.map((t) => e`${t}`))}]::text[]`, f = (n) => n.length === 0 ? s : t === "postgres" ? e`${s} #> ${d(n)}` : t === "mssql" ? e`JSON_QUERY(${s}, ${u(n)})` : t === "mysql" || t === "mariadb" ? e`JSON_EXTRACT(${s}, ${u(n)})` : e`json_extract(${s}, ${u(n)})`, p = (n) => t === "postgres" ? e`jsonb_typeof(${f(n)}) = 'object'` : t === "mssql" ? e`LEFT(LTRIM(${f(n)}), 1) = '{'` : t === "mysql" || t === "mariadb" ? e`JSON_TYPE(${f(n)}) = 'OBJECT'` : e`json_type(${s}, ${u(n)}) = 'object'`, m = t === "postgres" ? e`'{}'::jsonb` : e`'{}'`, h = (t) => {
732
+ let n = Array.from({ length: t.length + 1 }, (e, n) => p(t.slice(0, n)));
733
+ return e`CASE WHEN ${e.and(n)} THEN ${f(t)} ELSE ${m} END`;
734
+ }, g = (n) => {
735
+ let r = JSON.stringify(n);
736
+ return t === "postgres" ? e`${r}::jsonb` : e`${r}`;
737
+ }, _ = (n, r, i, a) => {
738
+ if (t === "postgres") return e`jsonb_set(${n}, ${d(r)}, ${i}, true)`;
739
+ let o = u(r);
740
+ return t === "mysql" || t === "mariadb" ? e`JSON_SET(${n}, ${o}, JSON_EXTRACT(${i}, '$'))` : t === "mssql" ? a === null ? e`JSON_MODIFY(JSON_MODIFY(${n}, ${o}, 0), ${`strict ${o}`}, NULL)` : typeof a == "boolean" ? e`JSON_MODIFY(${n}, ${o}, CAST(${+!!a} AS bit))` : typeof a == "string" || typeof a == "number" ? e`JSON_MODIFY(${n}, ${o}, ${a})` : e`JSON_MODIFY(${n}, ${o}, JSON_QUERY(${i}))` : e`json_set(${n}, ${o}, json(${i}))`;
741
+ }, v;
742
+ if (o.length === 0) {
743
+ if (!Ir(c)) v = g(c);
744
+ else {
745
+ v = h([]);
746
+ for (let [e, t] of Object.entries(c)) v = _(v, [e], g(t), t);
747
+ }
748
+ } else {
749
+ v = h([]);
750
+ for (let e = 1; e < o.length; e++) {
751
+ let t = o.slice(0, e);
752
+ v = _(v, t, h(t));
753
+ }
754
+ v = _(v, o, g(c), c);
755
+ }
756
+ return e`${e(a)} = ${v}`;
757
+ }, Br = class extends Error {
653
758
  _tag = "EagerCardinalityError";
654
759
  constructor(e) {
655
760
  super(e), this.name = "EagerCardinalityError";
656
761
  }
657
- }, jr = (e) => {
762
+ }, Vr = (e) => {
658
763
  let { relationName: t, sourceTableName: n, targetTableName: r, foreignKey: i, sourceKey: a } = e, o = r === n;
659
764
  return `relation '${t}' on '${n}' is declared \`one\`, but ${r}.${i} matches MORE than one row for the same ${n}.${a} — so there is no single related row to return.` + (o ? ` Because this relation is self-referential, check which side the key is on: \`foreignKey: '${i}'\` means "rows whose ${i} points AT me" (my children — there can be many). If you meant "the row my ${i} points to" (my parent), that is \`sourceKey: '${i}'\`.` : " Use `many(...)` if several are expected, or narrow the key.");
660
- }, Mr = async (e, t, n, r) => {
765
+ }, Hr = async (e, t, n, r) => {
661
766
  if (e.length === 0) return e;
662
767
  let i = cr(n.tableName);
663
768
  if (i === void 0) throw Error(`cannot eager-load on '${n.tableName}': no relations registered. Did you forget to declare \`relations(${n.tableName}, ...)\` or import the file that does?`);
@@ -668,36 +773,36 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
668
773
  let t = Object.keys(i).join(", ") || "<none>";
669
774
  throw Error(`unknown relation '${e}' on '${n.tableName}'. Registered relations: ${t}.`);
670
775
  }
671
- rr(n, e, t), await Nr(a, e, t, o === !0 ? {} : o, n, r);
776
+ rr(n, e, t), await Ur(a, e, t, o === !0 ? {} : o, n, r);
672
777
  }
673
778
  return a;
674
- }, Nr = async (e, t, n, r, i, a) => {
779
+ }, Ur = async (e, t, n, r, i, a) => {
675
780
  switch (n.kind) {
676
781
  case "one":
677
- await Pr(e, t, n, r, i, a);
782
+ await Wr(e, t, n, r, i, a);
678
783
  return;
679
784
  case "many":
680
- await Fr(e, t, n, r, i, a);
785
+ await Gr(e, t, n, r, i, a);
681
786
  return;
682
787
  case "manyToMany":
683
- await Lr(e, t, n, r, i, a);
788
+ await qr(e, t, n, r, i, a);
684
789
  return;
685
790
  }
686
- }, Pr = async (e, t, n, r, i, a) => {
687
- let o = n.target(), s = n.sourceKey ?? Rr(i, o.tableName);
791
+ }, Wr = async (e, t, n, r, i, a) => {
792
+ let o = n.target(), s = n.sourceKey ?? Jr(i, o.tableName);
688
793
  if (s !== void 0) {
689
- let n = zr(e, s), i = n.length === 0 ? [] : await Br(o, "id", n, r, a), c = new Map(i.map((e) => [e.id, e]));
794
+ let n = Yr(e, s), i = n.length === 0 ? [] : await Xr(o, "id", n, r, a), c = new Map(i.map((e) => [e.id, e]));
690
795
  for (let n of e) {
691
796
  let e = n[s];
692
797
  n[t] = e == null ? null : c.get(e) ?? null;
693
798
  }
694
- await Vr(i, r.with, o, a);
799
+ await Zr(i, r.with, o, a);
695
800
  return;
696
801
  }
697
- let c = n.foreignKey ?? $n(o, i.tableName, t), l = n.sourceKey ?? "id", u = zr(e, l), d = u.length === 0 ? [] : await Br(o, c, u, r, a), f = /* @__PURE__ */ new Map();
802
+ let c = n.foreignKey ?? $n(o, i.tableName, t), l = n.sourceKey ?? "id", u = Yr(e, l), d = u.length === 0 ? [] : await Xr(o, c, u, r, a), f = /* @__PURE__ */ new Map();
698
803
  for (let e of d) {
699
804
  let n = e[c];
700
- if (f.has(n)) throw new Ar(jr({
805
+ if (f.has(n)) throw new Br(Vr({
701
806
  relationName: t,
702
807
  sourceTableName: i.tableName,
703
808
  targetTableName: o.tableName,
@@ -710,9 +815,9 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
710
815
  let e = n[l];
711
816
  n[t] = e == null ? null : f.get(e) ?? null;
712
817
  }
713
- await Vr(d, r.with, o, a);
714
- }, Fr = async (e, t, n, r, i, a) => {
715
- let o = n.target(), s = n.foreignKey ?? $n(o, i.tableName, t), c = n.sourceKey ?? "id", l = zr(e, c), u = Ir(r), d = l.length === 0 ? [] : await Br(o, s, l, u, a), f = /* @__PURE__ */ new Map();
818
+ await Zr(d, r.with, o, a);
819
+ }, Gr = async (e, t, n, r, i, a) => {
820
+ let o = n.target(), s = n.foreignKey ?? $n(o, i.tableName, t), c = n.sourceKey ?? "id", l = Yr(e, c), u = Kr(r), d = l.length === 0 ? [] : await Xr(o, s, l, u, a), f = /* @__PURE__ */ new Map();
716
821
  for (let e of d) {
717
822
  let t = e[s], n = f.get(t);
718
823
  n ? n.push(e) : f.set(t, [e]);
@@ -728,12 +833,12 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
728
833
  let e = n[c];
729
834
  n[t] = f.get(e) ?? [];
730
835
  }
731
- await Vr(d, r.with, o, a);
732
- }, Ir = (e) => {
836
+ await Zr(d, r.with, o, a);
837
+ }, Kr = (e) => {
733
838
  let { limit: t, offset: n, ...r } = e;
734
839
  return r;
735
- }, Lr = async (e, t, n, r, i, a) => {
736
- let o = n.target(), s = n.through(), c = zr(e, "id");
840
+ }, qr = async (e, t, n, r, i, a) => {
841
+ let o = n.target(), s = n.through(), c = Yr(e, "id");
737
842
  if (c.length === 0) {
738
843
  for (let n of e) n[t] = [];
739
844
  return;
@@ -754,8 +859,8 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
754
859
  for (let n of e) n[t] = [];
755
860
  return;
756
861
  }
757
- let f = await Br(o, "id", zr(d, n.targetKey), r, a), p = new Map(f.map((e) => [e.id, e]));
758
- await Vr(f, r.with, o, a);
862
+ let f = await Xr(o, "id", Yr(d, n.targetKey), r, a), p = new Map(f.map((e) => [e.id, e]));
863
+ await Zr(f, r.with, o, a);
759
864
  let m = r.junction === void 0 ? void 0 : r.junction === !0 ? Object.keys(s.fields) : r.junction, h = /* @__PURE__ */ new Map();
760
865
  for (let e of d) {
761
866
  let t = e[n.sourceKey], r = e[n.targetKey], i = p.get(r);
@@ -767,16 +872,16 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
767
872
  o ? o.push(a) : h.set(t, [a]);
768
873
  }
769
874
  for (let n of e) n[t] = h.get(n.id) ?? [];
770
- }, Rr = (e, t) => {
875
+ }, Jr = (e, t) => {
771
876
  for (let [n, r] of Object.entries(e.fields)) if (r.type === "reference" && r.references?.()?.tableName === t) return n;
772
- }, zr = (e, t) => {
877
+ }, Yr = (e, t) => {
773
878
  let n = /* @__PURE__ */ new Set();
774
879
  for (let r of e) {
775
880
  let e = r[t];
776
881
  e != null && n.add(e);
777
882
  }
778
883
  return [...n];
779
- }, Br = (e, t, n, r, i) => {
884
+ }, Xr = (e, t, n, r, i) => {
780
885
  let a = {
781
886
  column: t,
782
887
  op: "in",
@@ -790,63 +895,63 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
790
895
  skip: r.offset,
791
896
  projection: void 0
792
897
  });
793
- }, Vr = async (e, t, n, r) => {
794
- t !== void 0 && e.length !== 0 && (await Mr(e, t, n, r)).forEach((t, n) => {
898
+ }, Zr = async (e, t, n, r) => {
899
+ t !== void 0 && e.length !== 0 && (await Hr(e, t, n, r)).forEach((t, n) => {
795
900
  let r = e[n];
796
901
  for (let [e, n] of Object.entries(t)) e in r || (r[e] = n);
797
902
  });
798
- }, Hr = (e) => e.eager !== void 0 && Object.keys(e.eager).length > 0, Ur = class extends Error {
903
+ }, Qr = (e) => e.eager !== void 0 && Object.keys(e.eager).length > 0, $r = class extends Error {
799
904
  _tag = "TenantNamespaceUnresolved";
800
905
  constructor(e) {
801
906
  super(e), this.name = "TenantNamespaceUnresolved";
802
907
  }
803
- }, Wr = class extends Error {
908
+ }, ei = class extends Error {
804
909
  _tag = "TenantNamespaceInvalid";
805
910
  constructor(e) {
806
911
  super(e), this.name = "TenantNamespaceInvalid";
807
912
  }
808
- }, Gr = 63, Kr = "tenant_", qr = (e) => e.toLowerCase().replace(/[^a-z0-9_]/g, "_"), Jr = (e) => {
809
- if (e == null || e === "") throw new Ur("namespace isolation is on but the request has no resolvable tenant (subject.tenantId is null/empty). Refusing to run against a shared/default namespace — this would be a cross-tenant read. Authenticate with a tenant-scoped subject, or disable namespace isolation for this surface.");
810
- let t = qr(e);
811
- if (t.replace(/_/g, "") === "") throw new Wr(`tenant id '${e}' has no usable identifier characters after sanitisation — cannot derive a distinct namespace.`);
812
- let n = `${Kr}${t}`;
813
- if (n.length > Gr) throw new Wr(`namespace '${n}' for tenant '${e}' exceeds the ${Gr}-byte identifier limit. Use a shorter tenant id.`);
913
+ }, ti = 63, ni = "tenant_", ri = (e) => e.toLowerCase().replace(/[^a-z0-9_]/g, "_"), ii = (e) => {
914
+ if (e == null || e === "") throw new $r("namespace isolation is on but the request has no resolvable tenant (subject.tenantId is null/empty). Refusing to run against a shared/default namespace — this would be a cross-tenant read. Authenticate with a tenant-scoped subject, or disable namespace isolation for this surface.");
915
+ let t = ri(e);
916
+ if (t.replace(/_/g, "") === "") throw new ei(`tenant id '${e}' has no usable identifier characters after sanitisation — cannot derive a distinct namespace.`);
917
+ let n = `${ni}${t}`;
918
+ if (n.length > ti) throw new ei(`namespace '${n}' for tenant '${e}' exceeds the ${ti}-byte identifier limit. Use a shorter tenant id.`);
814
919
  return n;
815
- }, Yr = (e, t) => e === null ? t : `${e}.${t}`, Xr = /* @__PURE__ */ new Set(["timestamp", "date"]), Zr = /^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2})?/, Qr = (e, t) => {
816
- if (e === void 0 || t == null || !Xr.has(e) || t instanceof Date) return t;
920
+ }, ai = (e, t) => e === null ? t : `${e}.${t}`, oi = /* @__PURE__ */ new Set(["timestamp", "date"]), si = /^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2})?/, ci = (e, t) => {
921
+ if (e === void 0 || t == null || !oi.has(e) || t instanceof Date) return t;
817
922
  if (typeof t == "number" && Number.isFinite(t)) return new Date(t);
818
- if (typeof t == "string" && Zr.test(t)) {
923
+ if (typeof t == "string" && si.test(t)) {
819
924
  let e = new Date(t);
820
925
  return Number.isNaN(e.getTime()) ? t : e;
821
926
  }
822
927
  return t;
823
- }, $r = (e, t) => e === void 0 || !Xr.has(e) ? t : t.map((t) => Qr(e, t)), ei = (e, t) => {
928
+ }, li = (e, t) => e === void 0 || !oi.has(e) ? t : t.map((t) => ci(e, t)), ui = (e, t) => {
824
929
  let { strings: n, values: r } = e, i = t.unsafe(n[0] ?? "");
825
930
  for (let e = 0; e < r.length; e++) i = t`${i}${r[e]}${t.unsafe(n[e + 1] ?? "")}`;
826
931
  return t`${i}`;
827
- }, ti = (e) => e.replace(/[\\%_]/g, (e) => `\\${e}`), L = (e, t, n = null, r) => {
932
+ }, di = (e) => e.replace(/[\\%_]/g, (e) => `\\${e}`), L = (e, t, n = null, r) => {
828
933
  if ("not" in e) return t`NOT (${L(e.not, t, n, r)})`;
829
934
  if ("and" in e) return e.and.length === 0 ? t`TRUE` : t.and(e.and.map((e) => L(e, t, n, r)));
830
935
  if ("or" in e) return e.or.length === 0 ? t`FALSE` : t.or(e.or.map((e) => L(e, t, n, r)));
831
936
  if (e.op === "subquery-in" || e.op === "subquery-not-in") {
832
- let r = e, i = fi(r.subquery, t, n);
937
+ let r = e, i = Si(r.subquery, t, n);
833
938
  return r.op === "subquery-in" ? t`${t(r.column)} IN (${i})` : t`${t(r.column)} NOT IN (${i})`;
834
939
  }
835
940
  if (e.op === "exists" || e.op === "not-exists") {
836
- let r = e, i = fi(r.subquery, t, n);
941
+ let r = e, i = Si(r.subquery, t, n);
837
942
  return r.op === "exists" ? t`EXISTS (${i})` : t`NOT EXISTS (${i})`;
838
943
  }
839
944
  let i = e, a = t(i.column), o = i.path, s = o !== void 0 && o.length > 0, c = () => t.onDialectOrElse({
840
- mysql: () => t.unsafe(D(i.column, o, "mysql")),
841
- mssql: () => t.unsafe(D(i.column, o, "mssql")),
842
- sqlite: () => t.unsafe(D(i.column, o, "sqlite")),
843
- orElse: () => t.unsafe(D(i.column, o, "postgres"))
945
+ mysql: () => t.unsafe(O(i.column, o, "mysql")),
946
+ mssql: () => t.unsafe(O(i.column, o, "mssql")),
947
+ sqlite: () => t.unsafe(O(i.column, o, "sqlite")),
948
+ orElse: () => t.unsafe(O(i.column, o, "postgres"))
844
949
  }), l = () => t.onDialectOrElse({
845
- mysql: () => t.unsafe(D(i.column, o, "mysql", { numeric: !0 })),
846
- mssql: () => t.unsafe(D(i.column, o, "mssql", { numeric: !0 })),
847
- sqlite: () => t.unsafe(D(i.column, o, "sqlite", { numeric: !0 })),
848
- orElse: () => t.unsafe(D(i.column, o, "postgres", { numeric: !0 }))
849
- }), u = s ? c() : a, d = s ? l() : a, f = (e) => s && e != null ? String(e) : e, p = (e) => s ? Number(e) : e, m = s || r === void 0 ? void 0 : S(r)?.fields?.[i.column]?.type, h = (e) => Qr(m, e);
950
+ mysql: () => t.unsafe(O(i.column, o, "mysql", { numeric: !0 })),
951
+ mssql: () => t.unsafe(O(i.column, o, "mssql", { numeric: !0 })),
952
+ sqlite: () => t.unsafe(O(i.column, o, "sqlite", { numeric: !0 })),
953
+ orElse: () => t.unsafe(O(i.column, o, "postgres", { numeric: !0 }))
954
+ }), u = s ? c() : a, d = s ? l() : a, f = (e) => s && e != null ? String(e) : e, p = (e) => s ? Number(e) : e, m = s || r === void 0 ? void 0 : C(r)?.fields?.[i.column]?.type, h = (e) => ci(m, e);
850
955
  switch (i.op) {
851
956
  case "eq": return t`${u} = ${f(h(i.value))}`;
852
957
  case "neq": return t`${u} <> ${f(h(i.value))}`;
@@ -863,7 +968,7 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
863
968
  return e.length === 0 ? t`TRUE` : t`${u} NOT IN ${t.in(s ? e.map((e) => f(e)) : e)}`;
864
969
  }
865
970
  case "contains": {
866
- let e = `%${ti(typeof i.value == "string" ? i.value : String(i.value ?? ""))}%`;
971
+ let e = `%${di(typeof i.value == "string" ? i.value : String(i.value ?? ""))}%`;
867
972
  return t.onDialectOrElse({
868
973
  mysql: () => t`LOWER(${u}) LIKE LOWER(${e})`,
869
974
  mssql: () => t`LOWER(${u}) LIKE LOWER(${e})`,
@@ -872,7 +977,7 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
872
977
  });
873
978
  }
874
979
  case "startsWith": {
875
- let e = `${ti(typeof i.value == "string" ? i.value : String(i.value ?? ""))}%`;
980
+ let e = `${di(typeof i.value == "string" ? i.value : String(i.value ?? ""))}%`;
876
981
  return t.onDialectOrElse({
877
982
  mysql: () => t`${u} LIKE ${e}`,
878
983
  orElse: () => t`${u} LIKE ${e} ESCAPE '\\'`
@@ -920,13 +1025,13 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
920
1025
  });
921
1026
  }
922
1027
  }
923
- }, ni = (e, t) => {
1028
+ }, fi = (e, t) => {
924
1029
  let n = [];
925
1030
  return e.partitionBy && e.partitionBy.length > 0 && n.push(t`PARTITION BY ${t.csv(e.partitionBy.map((e) => t`${t(e)}`))}`), e.orderBy && e.orderBy.length > 0 && n.push(t`ORDER BY ${t.csv(e.orderBy.map((e) => e.direction === "desc" ? t`${t(e.column)} DESC` : t`${t(e.column)} ASC`))}`), n.length === 0 ? t`` : n.length === 1 ? n[0] : n.reduce((e, n, r) => r === 0 ? n : t`${e} ${n}`);
926
- }, ri = (e, t) => t.csv(e.map((e) => {
1031
+ }, pi = (e, t) => t.csv(e.map((e) => {
927
1032
  let n = e.column === void 0 ? t.unsafe("*") : t`${t(e.column)}`;
928
1033
  if (e.op.startsWith("window-")) {
929
- let r = ni(e.window ?? {}, t);
1034
+ let r = fi(e.window ?? {}, t);
930
1035
  switch (e.op) {
931
1036
  case "window-row-number": return t`ROW_NUMBER() OVER (${r}) AS ${t(e.alias)}`;
932
1037
  case "window-rank": return t`RANK() OVER (${r}) AS ${t(e.alias)}`;
@@ -950,44 +1055,44 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
950
1055
  return t`${t(e.column)} AS ${t(e.alias)}`;
951
1056
  default: throw Error(`compileAggregateProjection: unknown op '${e.op}'`);
952
1057
  }
953
- })), ii = (e) => `[${e.join(",")}]`, ai = (e, t) => {
1058
+ })), mi = (e) => `[${e.join(",")}]`, hi = (e, t) => {
954
1059
  if (e.queryVector === void 0) return null;
955
- let n = t(e.column), r = ii(e.queryVector), i = e.distance === "cosine" ? "<=>" : e.distance === "l2" ? "<->" : "<#>", a = e.distance === "cosine" ? "VEC_DISTANCE_COSINE" : "VEC_DISTANCE_EUCLIDEAN";
1060
+ let n = t(e.column), r = mi(e.queryVector), i = e.distance === "cosine" ? "<=>" : e.distance === "l2" ? "<->" : "<#>", a = e.distance === "cosine" ? "VEC_DISTANCE_COSINE" : "VEC_DISTANCE_EUCLIDEAN";
956
1061
  return t.onDialectOrElse({
957
1062
  mysql: () => t`${t.unsafe(a)}(${n}, ${r})`,
958
1063
  mssql: () => t`NULL`,
959
1064
  sqlite: () => t`NULL`,
960
1065
  orElse: () => t`${n} ${t.unsafe(i)} ${r}::vector`
961
1066
  });
962
- }, oi = (e, t) => {
1067
+ }, gi = (e, t) => {
963
1068
  let n = t.unsafe(e.useGeography ? "::geography" : "::geometry");
964
1069
  return t`ST_Distance(${t(e.column)}${n}, ${e.geom}${n})`;
965
- }, si = (e, t) => t`${t(e.column)} <-> ${e.geom}::geometry`, ci = (e, t) => t`${t(`${e.indexName}_tsv`)}`, li = (e, t) => `${t}_${e.indexName}_fts`, ui = (e, t, n) => {
966
- let r = n.csv(e.columns.map((e) => n`${n(e)}`)), i = `%${ti(e.query)}%`;
1070
+ }, _i = (e, t) => t`${t(e.column)} <-> ${e.geom}::geometry`, vi = (e, t) => t`${t(`${e.indexName}_tsv`)}`, yi = (e, t) => `${t}_${e.indexName}_fts`, bi = (e, t, n) => {
1071
+ let r = n.csv(e.columns.map((e) => n`${n(e)}`)), i = `%${di(e.query)}%`;
967
1072
  return n.onDialectOrElse({
968
1073
  mysql: () => n`MATCH(${r}) AGAINST(${e.query} IN NATURAL LANGUAGE MODE)`,
969
1074
  sqlite: () => {
970
- let r = n(li(e, t));
1075
+ let r = n(yi(e, t));
971
1076
  return n`${n("id")} IN (SELECT ${n("row_id")} FROM ${r} WHERE ${r} MATCH ${e.query})`;
972
1077
  },
973
1078
  mssql: () => n.or(e.columns.map((e) => n`LOWER(${n(e)}) LIKE LOWER(${i}) ESCAPE '\\'`)),
974
- orElse: () => n`${ci(e, n)} @@ plainto_tsquery(${e.config ?? "english"}, ${e.query})`
1079
+ orElse: () => n`${vi(e, n)} @@ plainto_tsquery(${e.config ?? "english"}, ${e.query})`
975
1080
  });
976
- }, di = (e, t, n) => {
977
- let r = `%${ti(e.query)}%`;
1081
+ }, xi = (e, t, n) => {
1082
+ let r = `%${di(e.query)}%`;
978
1083
  return n.onDialectOrElse({
979
1084
  mysql: () => n`MATCH(${n.csv(e.columns.map((e) => n`${n(e)}`))}) AGAINST(${e.query} IN NATURAL LANGUAGE MODE)`,
980
1085
  sqlite: () => {
981
- let r = n(li(e, t));
1086
+ let r = n(yi(e, t));
982
1087
  return n`COALESCE((SELECT -bm25(${r}) FROM ${r} WHERE ${r} MATCH ${e.query} AND ${r}.${n("row_id")} = ${n("id")}), 0)`;
983
1088
  },
984
1089
  mssql: () => e.columns.map((e) => n`(CASE WHEN LOWER(${n(e)}) LIKE LOWER(${r}) ESCAPE '\\' THEN 1 ELSE 0 END)`).reduce((e, t, r) => r === 0 ? t : n`${e} + ${t}`),
985
- orElse: () => n`ts_rank(${ci(e, n)}, plainto_tsquery(${e.config ?? "english"}, ${e.query}))`
1090
+ orElse: () => n`ts_rank(${vi(e, n)}, plainto_tsquery(${e.config ?? "english"}, ${e.query}))`
986
1091
  });
987
- }, fi = (e, t, n = null) => {
1092
+ }, Si = (e, t, n = null) => {
988
1093
  if (e.setOp && e.setOp.queries.length >= 2) {
989
- 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`(${fi(e, t, n)})`).reduce((e, n, i) => i === 0 ? n : t`${e} ${t.unsafe(r)} ${n}`), a = [];
990
- if (v(e).length > 0 && a.push(t` ORDER BY ${t.csv(v(e).map((e) => e.direction === "desc" ? t`${t(e.column)} DESC` : t`${t(e.column)} ASC`))}`), e.take !== void 0) {
1094
+ let r = e.setOp.kind === "union" ? "UNION" : e.setOp.kind === "union-all" ? "UNION ALL" : e.setOp.kind === "intersect" ? "INTERSECT" : "EXCEPT", i = e.setOp.queries.map((e) => t`(${Si(e, t, n)})`).reduce((e, n, i) => i === 0 ? n : t`${e} ${t.unsafe(r)} ${n}`), a = [];
1095
+ if (b(e).length > 0 && a.push(t` ORDER BY ${t.csv(b(e).map((e) => e.direction === "desc" ? t`${t(e.column)} DESC` : t`${t(e.column)} ASC`))}`), e.take !== void 0) {
991
1096
  if (!Number.isInteger(e.take) || e.take < 0) throw Error(`compileSelect: invalid take ${e.take}`);
992
1097
  a.push(t` LIMIT ${t.unsafe(String(e.take))}`);
993
1098
  }
@@ -997,7 +1102,7 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
997
1102
  }
998
1103
  return t`${i}${a.reduce((e, n) => t`${e}${n}`, t``)}`;
999
1104
  }
1000
- let r = e.annClause === void 0 ? null : ai(e.annClause, t);
1105
+ let r = e.annClause === void 0 ? null : hi(e.annClause, t);
1001
1106
  e.spatialClause !== void 0 && t.onDialectOrElse({
1002
1107
  mysql: () => {
1003
1108
  throw Error("@voltro/plugin-postgis: spatial distance / KNN ordering is postgres-only");
@@ -1010,7 +1115,7 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1010
1115
  },
1011
1116
  orElse: () => t``
1012
1117
  });
1013
- let i = e.spatialClause?.projectAs === void 0 ? null : oi(e.spatialClause, t), a = e.aggregations && e.aggregations.length > 0 ? ri(e.aggregations, t) : e.joinedProjection && e.joinedProjection.length > 0 ? t.csv(e.joinedProjection.map((e) => t`${t(e.source)} AS ${t(e.outputKey)}`)) : e.projection && e.projection.length > 0 ? t.csv(e.projection.map((e) => t`${t(e)}`)) : t`*`, o = (e.aggregations && e.aggregations.length > 0) === !0, s = r !== null && !o ? t`${a}, ${r} AS ${t("distance")}` : a, c = e.fullTextSearch, l = c?.rank !== void 0 && !o ? di(c, e.table, t) : null, u = l !== null && c?.rank !== void 0 ? t`${s}, ${l} AS ${t(c.rank.alias)}` : s, d = i !== null && !o && e.spatialClause?.projectAs !== void 0 ? t`${u}, ${i} AS ${t(e.spatialClause.projectAs)}` : u, f = e.distinctOn && e.distinctOn.length > 0 ? t.onDialectOrElse({
1118
+ let i = e.spatialClause?.projectAs === void 0 ? null : gi(e.spatialClause, t), a = e.aggregations && e.aggregations.length > 0 ? pi(e.aggregations, t) : e.joinedProjection && e.joinedProjection.length > 0 ? t.csv(e.joinedProjection.map((e) => t`${t(e.source)} AS ${t(e.outputKey)}`)) : e.projection && e.projection.length > 0 ? t.csv(e.projection.map((e) => t`${t(e)}`)) : t`*`, o = (e.aggregations && e.aggregations.length > 0) === !0, s = r !== null && !o ? t`${a}, ${r} AS ${t("distance")}` : a, c = e.fullTextSearch, l = c?.rank !== void 0 && !o ? xi(c, e.table, t) : null, u = l !== null && c?.rank !== void 0 ? t`${s}, ${l} AS ${t(c.rank.alias)}` : s, d = i !== null && !o && e.spatialClause?.projectAs !== void 0 ? t`${u}, ${i} AS ${t(e.spatialClause.projectAs)}` : u, f = e.distinctOn && e.distinctOn.length > 0 ? t.onDialectOrElse({
1014
1119
  orElse: () => t`DISTINCT ON (${t.csv(e.distinctOn.map((e) => t`${t(e)}`))}) `,
1015
1120
  mysql: () => t`DISTINCT `,
1016
1121
  mssql: () => t`DISTINCT `,
@@ -1022,52 +1127,52 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1022
1127
  mssql: () => t``,
1023
1128
  sqlite: () => t``,
1024
1129
  orElse: () => t` FOR UPDATE`
1025
- }) : t``, g = e.alias === void 0 ? t`${t(Yr(n, e.table))}${m}` : t`${t(Yr(n, e.table))} AS ${t(e.alias)}${m}`, ee = (e.joins ?? []).map((e) => {
1130
+ }) : t``, g = e.alias === void 0 ? t`${t(ai(n, e.table))}${m}` : t`${t(ai(n, e.table))} AS ${t(e.alias)}${m}`, _ = (e.joins ?? []).map((e) => {
1026
1131
  let r = e.kind === "inner" ? "INNER" : "LEFT";
1027
- return t` ${t.unsafe(r)} JOIN ${t(Yr(n, e.table))} AS ${t(e.alias)} ON ${L(e.on, t, n)}`;
1028
- }), te = ee.length > 0 ? ee.reduce((e, n) => t`${e}${n}`, g) : g, ne = c === void 0 ? null : ui(c, e.table, t), re = [e.predicate ? L(e.predicate, t, n, e.table) : null, ne].filter((e) => e !== null), _ = re.length > 0 ? t` WHERE ${t.and(re)}` : t``, ie = e.groupBy && e.groupBy.length > 0 ? t` GROUP BY ${t.csv(e.groupBy.map((e) => t`${t(e)}`))}` : t``, ae = e.having ? t` HAVING ${L(e.having, t, n, e.table)}` : t``, oe = e.skip !== void 0, y = [];
1029
- r !== null && y.push(t`${r} ASC`), e.spatialClause?.order !== void 0 && y.push(e.spatialClause.order === "desc" ? t`${si(e.spatialClause, t)} DESC` : t`${si(e.spatialClause, t)} ASC`), l !== null && c?.rank?.order === !0 && y.push(t`${l} DESC`);
1030
- for (let n of v(e)) y.push(n.direction === "desc" ? t`${t(n.column)} DESC` : t`${t(n.column)} ASC`);
1031
- let se = y.length > 0 ? t` ORDER BY ${t.csv(y)}` : oe ? t.onDialectOrElse({
1132
+ return t` ${t.unsafe(r)} JOIN ${t(ai(n, e.table))} AS ${t(e.alias)} ON ${L(e.on, t, n)}`;
1133
+ }), v = _.length > 0 ? _.reduce((e, n) => t`${e}${n}`, g) : g, ee = c === void 0 ? null : bi(c, e.table, t), te = [e.predicate ? L(e.predicate, t, n, e.table) : null, ee].filter((e) => e !== null), y = te.length > 0 ? t` WHERE ${t.and(te)}` : t``, ne = e.groupBy && e.groupBy.length > 0 ? t` GROUP BY ${t.csv(e.groupBy.map((e) => t`${t(e)}`))}` : t``, re = e.having ? t` HAVING ${L(e.having, t, n, e.table)}` : t``, ie = e.skip !== void 0, x = [];
1134
+ r !== null && x.push(t`${r} ASC`), e.spatialClause?.order !== void 0 && x.push(e.spatialClause.order === "desc" ? t`${_i(e.spatialClause, t)} DESC` : t`${_i(e.spatialClause, t)} ASC`), l !== null && c?.rank?.order === !0 && x.push(t`${l} DESC`);
1135
+ for (let n of b(e)) x.push(n.direction === "desc" ? t`${t(n.column)} DESC` : t`${t(n.column)} ASC`);
1136
+ let ae = x.length > 0 ? t` ORDER BY ${t.csv(x)}` : ie ? t.onDialectOrElse({
1032
1137
  mssql: () => t` ORDER BY (SELECT NULL)`,
1033
1138
  orElse: () => t``
1034
- }) : t``, b = (e) => {
1139
+ }) : t``, oe = (e) => {
1035
1140
  if (!Number.isFinite(e) || !Number.isInteger(e) || e < 0) throw Error(`compileSelect: expected non-negative integer take/skip, got ${e}`);
1036
1141
  return t.unsafe(String(e));
1037
- }, ce = (e.ctes ?? []).map((e) => t`${t(e.name)} AS (${fi(e.descriptor, t, n)})`), le = (e.ctes ?? []).some((e) => e.recursive === !0), ue = ce.length > 0 ? t`WITH ${t.unsafe(le ? "RECURSIVE " : "")}${t.csv(ce)} ` : t``;
1142
+ }, se = (e.ctes ?? []).map((e) => t`${t(e.name)} AS (${Si(e.descriptor, t, n)})`), ce = (e.ctes ?? []).some((e) => e.recursive === !0), le = se.length > 0 ? t`WITH ${t.unsafe(ce ? "RECURSIVE " : "")}${t.csv(se)} ` : t``;
1038
1143
  return t.onDialectOrElse({
1039
1144
  mssql: () => {
1040
- let n = e.take !== void 0 && !oe ? t`TOP ${b(e.take)} ` : t``, r = oe ? t` OFFSET ${b(e.skip)} ROWS FETCH NEXT ${b(e.take ?? 2 ** 53 - 1)} ROWS ONLY` : t``;
1041
- return t`${ue}SELECT ${n}${f}${d} FROM ${te}${_}${ie}${ae}${se}${r}`;
1145
+ let n = e.take !== void 0 && !ie ? t`TOP ${oe(e.take)} ` : t``, r = ie ? t` OFFSET ${oe(e.skip)} ROWS FETCH NEXT ${oe(e.take ?? 2 ** 53 - 1)} ROWS ONLY` : t``;
1146
+ return t`${le}SELECT ${n}${f}${d} FROM ${v}${y}${ne}${re}${ae}${r}`;
1042
1147
  },
1043
1148
  orElse: () => {
1044
- let n = e.take === void 0 ? t`` : t` LIMIT ${b(e.take)}`, r = oe ? t` OFFSET ${b(e.skip)}` : t``;
1045
- return t`${ue}SELECT ${f}${d} FROM ${te}${_}${ie}${ae}${se}${n}${r}${h}`;
1149
+ let n = e.take === void 0 ? t`` : t` LIMIT ${oe(e.take)}`, r = ie ? t` OFFSET ${oe(e.skip)}` : t``;
1150
+ return t`${le}SELECT ${f}${d} FROM ${v}${y}${ne}${re}${ae}${n}${r}${h}`;
1046
1151
  }
1047
1152
  });
1048
- }, pi = (e, t, n) => {
1153
+ }, Ci = (e, t, n) => {
1049
1154
  if (e.eager === void 0) return null;
1050
- let r = gi(e.table, e.eager, e.sourceTable);
1155
+ let r = Ei(e.table, e.eager, e.sourceTable);
1051
1156
  if (r === null) return null;
1052
- let i = Ci(n, e, r, Si(t, n));
1157
+ let i = Ni(n, e, r, Mi(t, n));
1053
1158
  return i === null ? null : {
1054
1159
  fragment: i,
1055
- decode: Ei(r, n)
1160
+ decode: Ii(r, n)
1056
1161
  };
1057
- }, mi = (e) => e.relation.kind === "one" && e.fkSide === "target", hi = (e) => ({
1162
+ }, wi = (e) => e.relation.kind === "one" && e.fkSide === "target", Ti = (e) => ({
1058
1163
  ...e,
1059
1164
  branch: {
1060
1165
  ...e.branch,
1061
1166
  limit: 2
1062
1167
  }
1063
- }), gi = (e, t, n) => {
1064
- let r = n ?? Ve(e), i = cr(e);
1168
+ }), Ei = (e, t, n) => {
1169
+ let r = n ?? Be(e), i = cr(e);
1065
1170
  if (i === void 0) return null;
1066
1171
  let a = [];
1067
1172
  for (let [e, n] of Object.entries(t)) {
1068
1173
  let t = i[e];
1069
1174
  if (t === void 0) return null;
1070
- let o = _i(e, t, r, n === !0 ? {} : n);
1175
+ let o = Di(e, t, r, n === !0 ? {} : n);
1071
1176
  if (o === null) return null;
1072
1177
  a.push(o);
1073
1178
  }
@@ -1075,11 +1180,11 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1075
1180
  table: r,
1076
1181
  children: a
1077
1182
  };
1078
- }, _i = (e, t, n, r) => {
1183
+ }, Di = (e, t, n, r) => {
1079
1184
  let i = t.target(), a = (t.kind === "manyToMany" ? void 0 : t.sourceKey) ?? "id", o, s;
1080
1185
  if (t.kind === "manyToMany") o = t.targetKey, s = "target";
1081
1186
  else if (t.kind === "one") {
1082
- let r = t.sourceKey ?? xi(n, i.tableName);
1187
+ let r = t.sourceKey ?? ji(n, i.tableName);
1083
1188
  if (r !== void 0) o = r, s = "source";
1084
1189
  else try {
1085
1190
  o = t.foreignKey ?? $n(i, n.tableName, e), s = "target";
@@ -1098,7 +1203,7 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1098
1203
  for (let [n, a] of Object.entries(r.with)) {
1099
1204
  let r = e?.[n];
1100
1205
  if (r === void 0) return null;
1101
- let o = _i(n, r, i, a === !0 ? {} : a);
1206
+ let o = Di(n, r, i, a === !0 ? {} : a);
1102
1207
  if (o === null) return null;
1103
1208
  t.push(o);
1104
1209
  }
@@ -1114,9 +1219,9 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1114
1219
  fkSide: s,
1115
1220
  branch: r,
1116
1221
  children: c,
1117
- junction: vi(t, r)
1222
+ junction: Oi(t, r)
1118
1223
  };
1119
- }, vi = (e, t) => {
1224
+ }, Oi = (e, t) => {
1120
1225
  if (e.kind !== "manyToMany" || t.junction === void 0) return;
1121
1226
  let n = e.through(), r = t.junction === !0 ? Object.keys(n.fields) : t.junction, i = r.filter((e) => e in n.fields);
1122
1227
  return {
@@ -1128,35 +1233,35 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1128
1233
  return t !== void 0 && (t.type === "timestamp" || t.type === "date");
1129
1234
  })
1130
1235
  };
1131
- }, yi = (e) => `__j_${e}`, bi = "__j", xi = (e, t) => {
1236
+ }, ki = (e) => `__j_${e}`, Ai = "__j", ji = (e, t) => {
1132
1237
  for (let [n, r] of Object.entries(e.fields)) if (r.type === "reference" && r.references?.()?.tableName === t) return n;
1133
- }, Si = (e, t) => {
1238
+ }, Mi = (e, t) => {
1134
1239
  let n = 0;
1135
1240
  return {
1136
1241
  sql: e,
1137
1242
  dialect: t,
1138
1243
  nextAlias: () => `__a${n++}`
1139
1244
  };
1140
- }, Ci = (e, t, n, r) => {
1245
+ }, Ni = (e, t, n, r) => {
1141
1246
  switch (e) {
1142
- case "postgres": return ki(t, n, r);
1247
+ case "postgres": return zi(t, n, r);
1143
1248
  case "sqlite":
1144
- case "turso": return Li(t, n, r);
1249
+ case "turso": return qi(t, n, r);
1145
1250
  case "mysql":
1146
- case "mariadb": return qi(t, n, r);
1147
- case "mssql": return ea(t, n, r);
1251
+ case "mariadb": return ra(t, n, r);
1252
+ case "mssql": return ua(t, n, r);
1148
1253
  }
1149
- }, wi = (e, t) => t === "mssql" && !Ti.test(e) ? /* @__PURE__ */ new Date(`${e}Z`) : new Date(e), Ti = /(?:Z|[+-]\d{2}:?\d{2})$/, Ei = (e, t) => {
1150
- let n = Di(e.table, e.children, t);
1254
+ }, Pi = (e, t) => t === "mssql" && !Fi.test(e) ? /* @__PURE__ */ new Date(`${e}Z`) : new Date(e), Fi = /(?:Z|[+-]\d{2}:?\d{2})$/, Ii = (e, t) => {
1255
+ let n = Li(e.table, e.children, t);
1151
1256
  return (e) => e.map((e) => {
1152
1257
  let t = e.__row, r = typeof t == "string" ? JSON.parse(t) : t;
1153
1258
  return n(r);
1154
1259
  });
1155
- }, Di = (e, t, n) => {
1260
+ }, Li = (e, t, n) => {
1156
1261
  let r = [];
1157
1262
  for (let [t, n] of Object.entries(e.fields)) (n.type === "timestamp" || n.type === "date") && r.push(t);
1158
1263
  let i = t.map((e) => {
1159
- let t = Di(e.target, e.children, n), r = e.relation.kind === "one", i = mi(e), a = i ? jr({
1264
+ let t = Li(e.target, e.children, n), r = e.relation.kind === "one", i = wi(e), a = i ? Vr({
1160
1265
  relationName: e.relationName,
1161
1266
  sourceTableName: e.source.tableName,
1162
1267
  targetTableName: e.target.tableName,
@@ -1169,14 +1274,14 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1169
1274
  isSingle: r,
1170
1275
  fromOverFetch: i,
1171
1276
  cardinalityMessage: a,
1172
- junction: Oi(e.junction, n)
1277
+ junction: Ri(e.junction, n)
1173
1278
  };
1174
1279
  });
1175
1280
  return (e) => {
1176
1281
  let t = { ...e };
1177
1282
  for (let e of r) {
1178
1283
  let r = t[e];
1179
- typeof r == "string" && (t[e] = wi(r, n));
1284
+ typeof r == "string" && (t[e] = Pi(r, n));
1180
1285
  }
1181
1286
  for (let e of i) {
1182
1287
  let n = t[e.name];
@@ -1186,7 +1291,7 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1186
1291
  }
1187
1292
  if (e.fromOverFetch) {
1188
1293
  let r = n;
1189
- if (r.length > 1) throw new Ar(e.cardinalityMessage);
1294
+ if (r.length > 1) throw new Br(e.cardinalityMessage);
1190
1295
  t[e.name] = r.length === 0 ? null : e.decode(r[0]);
1191
1296
  continue;
1192
1297
  }
@@ -1198,202 +1303,202 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1198
1303
  }
1199
1304
  return t;
1200
1305
  };
1201
- }, Oi = (e, t) => {
1306
+ }, Ri = (e, t) => {
1202
1307
  if (e === void 0) return;
1203
1308
  let n = new Set(e.dateColumns), r = e.requested;
1204
1309
  return (e) => {
1205
1310
  let i = e._junction ?? {}, a = {};
1206
1311
  for (let e of r) {
1207
1312
  let r = i[e];
1208
- a[e] = n.has(e) && typeof r == "string" ? wi(r, t) : r;
1313
+ a[e] = n.has(e) && typeof r == "string" ? Pi(r, t) : r;
1209
1314
  }
1210
1315
  return {
1211
1316
  ...e,
1212
1317
  _junction: a
1213
1318
  };
1214
1319
  };
1215
- }, ki = (e, t, n) => {
1216
- let r = n.sql, i = n.nextAlias(), a = r(t.table.tableName), o = r(i), s = Ai(i, t.children, n);
1217
- return s === null ? null : r`SELECT ${s} AS "__row" FROM ${a} AS ${o}${e.predicate ? r` WHERE ${U(e.predicate, i, r)}` : r``}${v(e).length > 0 ? r` ORDER BY ${r.csv(v(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)}`}`;
1218
- }, Ai = (e, t, n, r) => {
1219
- let i = n.sql, a = r === void 0 ? i`to_jsonb(${i(e)}.*)` : i`(to_jsonb(${i(e)}.*) - ${V(bi, i)}::text)`;
1320
+ }, zi = (e, t, n) => {
1321
+ let r = n.sql, i = n.nextAlias(), a = r(t.table.tableName), o = r(i), s = Bi(i, t.children, n);
1322
+ return s === null ? null : r`SELECT ${s} AS "__row" FROM ${a} AS ${o}${e.predicate ? r` WHERE ${U(e.predicate, i, r)}` : r``}${b(e).length > 0 ? r` ORDER BY ${r.csv(b(e).map((e) => e.direction === "desc" ? r`${B(i, e.column, r)} DESC` : r`${B(i, e.column, r)} ASC`))}` : r``}${e.take === void 0 ? r`` : r` LIMIT ${H(e.take, r)}`}${e.skip === void 0 ? r`` : r` OFFSET ${H(e.skip, r)}`}`;
1323
+ }, Bi = (e, t, n, r) => {
1324
+ let i = n.sql, a = r === void 0 ? i`to_jsonb(${i(e)}.*)` : i`(to_jsonb(${i(e)}.*) - ${V(Ai, i)}::text)`;
1220
1325
  if (t.length === 0 && r === void 0) return a;
1221
1326
  let o = [];
1222
- r !== void 0 && o.push(i`${V("_junction", i)}, ${B(e, bi, i)}`);
1327
+ r !== void 0 && o.push(i`${V("_junction", i)}, ${B(e, Ai, i)}`);
1223
1328
  for (let r of t) {
1224
- let t = ji(r, e, n);
1329
+ let t = Vi(r, e, n);
1225
1330
  if (t === null) return null;
1226
1331
  o.push(i`${V(r.relationName, i)}, ${t}`);
1227
1332
  }
1228
1333
  return i`${a} || jsonb_build_object(${i.csv(o)})`;
1229
- }, ji = (e, t, n) => {
1334
+ }, Vi = (e, t, n) => {
1230
1335
  switch (e.relation.kind) {
1231
- case "one": return mi(e) ? Ni(hi(e), t, n) : Mi(e, t, n);
1232
- case "many": return Ni(e, t, n);
1233
- case "manyToMany": return Pi(e, t, n);
1336
+ case "one": return wi(e) ? Ui(Ti(e), t, n) : Hi(e, t, n);
1337
+ case "many": return Ui(e, t, n);
1338
+ case "manyToMany": return Wi(e, t, n);
1234
1339
  }
1235
- }, Mi = (e, t, n) => {
1236
- let r = n.sql, i = n.nextAlias(), a = Ai(i, e.children, n);
1340
+ }, Hi = (e, t, n) => {
1341
+ let r = n.sql, i = n.nextAlias(), a = Bi(i, e.children, n);
1237
1342
  if (a === null) return null;
1238
1343
  let o = e.fkSide === "source" ? r`${B(i, "id", r)} = ${B(t, e.foreignKey, r)}` : r`${B(i, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${U(e.branch.where, i, r)}`, c = R(i, e.branch.orderBy, r);
1239
1344
  return r`(SELECT ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o}${s}${c} LIMIT 1)`;
1240
- }, Ni = (e, t, n) => {
1241
- let r = n.sql, i = n.nextAlias(), a = Ai(i, e.children, n);
1345
+ }, Ui = (e, t, n) => {
1346
+ let r = n.sql, i = n.nextAlias(), a = Bi(i, e.children, n);
1242
1347
  if (a === null) return null;
1243
- 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 = Ii(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`;
1348
+ let o = r`${B(void 0, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${L(e.branch.where, r)}`, c = Ki(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`;
1244
1349
  return r`COALESCE((SELECT jsonb_agg(${a}) FROM (SELECT * FROM ${r(e.target.tableName)} WHERE ${o}${s}${c}${l}${u}) AS ${r(i)}), '[]'::jsonb)`;
1245
- }, Pi = (e, t, n) => {
1246
- let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = Ai(o, e.children, n, e.junction);
1350
+ }, Wi = (e, t, n) => {
1351
+ let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = Bi(o, e.children, n, e.junction);
1247
1352
  if (c === null) return null;
1248
- let l = e.branch.where === void 0 ? r`` : r` AND ${L(e.branch.where, r)}`, u = ca(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`, ${Fi(e.junction, s, r)} AS ${r(bi)}`;
1353
+ let l = e.branch.where === void 0 ? r`` : r` AND ${L(e.branch.where, r)}`, u = va(e, s, r), d = R(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : r`, ${Gi(e.junction, s, r)} AS ${r(Ai)}`;
1249
1354
  return r`COALESCE((SELECT jsonb_agg(${c}) FROM (SELECT ${r(o)}.*${m} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${B(o, "id", r)} = ${B(s, i.targetKey, r)} WHERE ${B(s, i.sourceKey, r)} = ${B(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), '[]'::jsonb)`;
1250
- }, Fi = (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`))}`, Ii = (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`))}`, Li = (e, t, n) => {
1251
- let r = n.sql, i = n.nextAlias(), a = Ri(i, t.table, t.children, n);
1355
+ }, Gi = (e, t, n) => e.present.length === 0 ? n`jsonb_build_object()` : n`jsonb_build_object(${n.csv(e.present.map((e) => n`${V(e, n)}, ${B(t, e, n)}`))})`, R = (e, t, n) => t === void 0 || t.length === 0 ? n`` : n` ORDER BY ${n.csv(t.map((t) => t.direction === "desc" ? n`${B(e, t.column, n)} DESC` : n`${B(e, t.column, n)} ASC`))}`, Ki = (e, t) => e === void 0 || e.length === 0 ? t`` : t` ORDER BY ${t.csv(e.map((e) => e.direction === "desc" ? t`${t(e.column)} DESC` : t`${t(e.column)} ASC`))}`, qi = (e, t, n) => {
1356
+ let r = n.sql, i = n.nextAlias(), a = Ji(i, t.table, t.children, n);
1252
1357
  if (a === null) return null;
1253
- let o = e.predicate ? r` WHERE ${U(e.predicate, i, r)}` : r``, s = v(e).length > 0 ? r` ORDER BY ${r.csv(v(e).map((e) => e.direction === "desc" ? r`${B(i, e.column, r)} DESC` : r`${B(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${H(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${H(e.skip, r)}`;
1358
+ let o = e.predicate ? r` WHERE ${U(e.predicate, i, r)}` : r``, s = b(e).length > 0 ? r` ORDER BY ${r.csv(b(e).map((e) => e.direction === "desc" ? r`${B(i, e.column, r)} DESC` : r`${B(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${H(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${H(e.skip, r)}`;
1254
1359
  return r`SELECT ${a} AS "__row" FROM ${r(t.table.tableName)} AS ${r(i)}${o}${s}${c}${l}`;
1255
- }, Ri = (e, t, n, r, i) => {
1360
+ }, Ji = (e, t, n, r, i) => {
1256
1361
  let a = r.sql, o = [];
1257
1362
  for (let n of Object.keys(t.fields)) o.push(a`${V(n, a)}, ${B(e, n, a)}`);
1258
1363
  if (i !== void 0) {
1259
- let e = zi(i.projection, i.source, a);
1364
+ let e = Yi(i.projection, i.source, a);
1260
1365
  o.push(a`${V("_junction", a)}, json_object(${e})`);
1261
1366
  }
1262
1367
  for (let t of n) {
1263
- let n = Ui(t, e, r);
1368
+ let n = $i(t, e, r);
1264
1369
  if (n === null) return null;
1265
1370
  o.push(a`${V(t.relationName, a)}, ${n}`);
1266
1371
  }
1267
1372
  return a`json_object(${a.csv(o)})`;
1268
- }, zi = (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)}`)), Bi = (e, t, n) => e.present.length === 0 ? n`` : n`, ${n.csv(e.present.map((e) => n`${B(t, e, n)} AS ${n(yi(e))}`))}`, Vi = (e) => ({
1373
+ }, Yi = (e, t, n) => e.present.length === 0 ? n`` : n.csv(e.present.map((e) => n`${V(e, n)}, ${B(t.alias, t.physical(e), n)}`)), Xi = (e, t, n) => e.present.length === 0 ? n`` : n`, ${n.csv(e.present.map((e) => n`${B(t, e, n)} AS ${n(ki(e))}`))}`, Zi = (e) => ({
1269
1374
  alias: e,
1270
- physical: yi
1271
- }), Hi = (e) => ({
1375
+ physical: ki
1376
+ }), Qi = (e) => ({
1272
1377
  alias: e,
1273
1378
  physical: (e) => e
1274
- }), Ui = (e, t, n) => {
1379
+ }), $i = (e, t, n) => {
1275
1380
  switch (e.relation.kind) {
1276
- case "one": return mi(e) ? Gi(hi(e), t, n) : Wi(e, t, n);
1277
- case "many": return Gi(e, t, n);
1278
- case "manyToMany": return Ki(e, t, n);
1381
+ case "one": return wi(e) ? ta(Ti(e), t, n) : ea(e, t, n);
1382
+ case "many": return ta(e, t, n);
1383
+ case "manyToMany": return na(e, t, n);
1279
1384
  }
1280
- }, Wi = (e, t, n) => {
1281
- let r = n.sql, i = n.nextAlias(), a = Ri(i, e.target, e.children, n);
1385
+ }, ea = (e, t, n) => {
1386
+ let r = n.sql, i = n.nextAlias(), a = Ji(i, e.target, e.children, n);
1282
1387
  if (a === null) return null;
1283
1388
  let o = e.fkSide === "source" ? r`${B(i, "id", r)} = ${B(t, e.foreignKey, r)}` : r`${B(i, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`;
1284
1389
  return r`(SELECT ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o} LIMIT 1)`;
1285
- }, Gi = (e, t, n) => {
1286
- let r = n.sql, i = n.nextAlias(), a = Ri(i, e.target, e.children, n);
1390
+ }, ta = (e, t, n) => {
1391
+ let r = n.sql, i = n.nextAlias(), a = Ji(i, e.target, e.children, n);
1287
1392
  if (a === null) return null;
1288
- 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 = Ii(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`;
1393
+ let o = r`${B(void 0, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${L(W(e.branch.where), r)}`, c = Ki(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`;
1289
1394
  return r`COALESCE((SELECT json_group_array(${a}) FROM (SELECT * FROM ${r(e.target.tableName)} WHERE ${o}${s}${c}${l}${u}) AS ${r(i)}), json('[]'))`;
1290
- }, Ki = (e, t, n) => {
1291
- let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = Ri(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1395
+ }, na = (e, t, n) => {
1396
+ let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = Ji(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1292
1397
  projection: e.junction,
1293
- source: Vi(o)
1398
+ source: Zi(o)
1294
1399
  });
1295
1400
  if (c === null) return null;
1296
- let l = e.branch.where === void 0 ? r`` : r` AND ${L(W(e.branch.where), r)}`, u = ca(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`` : Bi(e.junction, s, r);
1401
+ let l = e.branch.where === void 0 ? r`` : r` AND ${L(W(e.branch.where), r)}`, u = va(e, s, r, !0), d = R(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : Xi(e.junction, s, r);
1297
1402
  return r`COALESCE((SELECT json_group_array(${c}) FROM (SELECT ${r(o)}.*${m} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${B(o, "id", r)} = ${B(s, i.targetKey, r)} WHERE ${B(s, i.sourceKey, r)} = ${B(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), json('[]'))`;
1298
- }, qi = (e, t, n) => {
1403
+ }, ra = (e, t, n) => {
1299
1404
  let r = n.sql, i = n.nextAlias(), a = z(i, t.table, t.children, n);
1300
1405
  if (a === null) return null;
1301
- let o = e.predicate ? r` WHERE ${U(e.predicate, i, r)}` : r``, s = v(e).length > 0 ? r` ORDER BY ${r.csv(v(e).map((e) => e.direction === "desc" ? r`${B(i, e.column, r)} DESC` : r`${B(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${H(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${H(e.skip, r)}`;
1406
+ let o = e.predicate ? r` WHERE ${U(e.predicate, i, r)}` : r``, s = b(e).length > 0 ? r` ORDER BY ${r.csv(b(e).map((e) => e.direction === "desc" ? r`${B(i, e.column, r)} DESC` : r`${B(i, e.column, r)} ASC`))}` : r``, c = e.take === void 0 ? r`` : r` LIMIT ${H(e.take, r)}`, l = e.skip === void 0 ? r`` : r` OFFSET ${H(e.skip, r)}`;
1302
1407
  return r`SELECT ${a} AS \`__row\` FROM ${r(t.table.tableName)} AS ${r(i)}${o}${s}${c}${l}`;
1303
1408
  }, z = (e, t, n, r, i) => {
1304
1409
  let a = r.sql, o = [];
1305
1410
  for (let n of Object.keys(t.fields)) o.push(a`${V(n, a)}, ${B(e, n, a)}`);
1306
1411
  if (i !== void 0) {
1307
- let e = zi(i.projection, i.source, a);
1412
+ let e = Yi(i.projection, i.source, a);
1308
1413
  o.push(a`${V("_junction", a)}, JSON_OBJECT(${e})`);
1309
1414
  }
1310
1415
  for (let t of n) {
1311
- let n = Ji(t, e, r);
1416
+ let n = ia(t, e, r);
1312
1417
  if (n === null) return null;
1313
1418
  o.push(a`${V(t.relationName, a)}, ${n}`);
1314
1419
  }
1315
1420
  return a`JSON_OBJECT(${a.csv(o)})`;
1316
- }, Ji = (e, t, n) => {
1421
+ }, ia = (e, t, n) => {
1317
1422
  switch (e.relation.kind) {
1318
1423
  case "one":
1319
- if (mi(e)) {
1320
- let r = hi(e);
1321
- return n.dialect === "mariadb" ? Qi(r, t, n) : Xi(r, t, n);
1424
+ if (wi(e)) {
1425
+ let r = Ti(e);
1426
+ return n.dialect === "mariadb" ? ca(r, t, n) : oa(r, t, n);
1322
1427
  }
1323
- return Yi(e, t, n);
1324
- case "many": return n.dialect === "mariadb" ? Qi(e, t, n) : Xi(e, t, n);
1325
- case "manyToMany": return n.dialect === "mariadb" ? $i(e, t, n) : Zi(e, t, n);
1428
+ return aa(e, t, n);
1429
+ case "many": return n.dialect === "mariadb" ? ca(e, t, n) : oa(e, t, n);
1430
+ case "manyToMany": return n.dialect === "mariadb" ? la(e, t, n) : sa(e, t, n);
1326
1431
  }
1327
- }, Yi = (e, t, n) => {
1432
+ }, aa = (e, t, n) => {
1328
1433
  let r = n.sql, i = n.nextAlias(), a = z(i, e.target, e.children, n);
1329
1434
  if (a === null) return null;
1330
1435
  let o = e.fkSide === "source" ? r`${B(i, "id", r)} = ${B(t, e.foreignKey, r)}` : r`${B(i, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`;
1331
1436
  return r`(SELECT ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o} LIMIT 1)`;
1332
- }, Xi = (e, t, n) => {
1437
+ }, oa = (e, t, n) => {
1333
1438
  let r = n.sql, i = n.nextAlias(), a = z(i, e.target, e.children, n);
1334
1439
  if (a === null) return null;
1335
- 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 = Ii(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`;
1440
+ let o = r`${B(void 0, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${L(W(e.branch.where), r)}`, c = Ki(e.branch.orderBy, r), l = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, u = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`;
1336
1441
  return r`COALESCE((SELECT JSON_ARRAYAGG(${a}) FROM (SELECT * FROM ${r(e.target.tableName)} WHERE ${o}${s}${c}${l}${u}) AS ${r(i)}), JSON_ARRAY())`;
1337
- }, Zi = (e, t, n) => {
1442
+ }, sa = (e, t, n) => {
1338
1443
  let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = z(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1339
1444
  projection: e.junction,
1340
- source: Vi(o)
1445
+ source: Zi(o)
1341
1446
  });
1342
1447
  if (c === null) return null;
1343
- let l = e.branch.where === void 0 ? r`` : r` AND ${L(W(e.branch.where), r)}`, u = ca(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`` : Bi(e.junction, s, r);
1448
+ let l = e.branch.where === void 0 ? r`` : r` AND ${L(W(e.branch.where), r)}`, u = va(e, s, r, !0), d = R(o, e.branch.orderBy, r), f = e.branch.limit === void 0 ? r`` : r` LIMIT ${H(e.branch.limit, r)}`, p = e.branch.offset === void 0 ? r`` : r` OFFSET ${H(e.branch.offset, r)}`, m = e.junction === void 0 ? r`` : Xi(e.junction, s, r);
1344
1449
  return r`COALESCE((SELECT JSON_ARRAYAGG(${c}) FROM (SELECT ${r(o)}.*${m} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${B(o, "id", r)} = ${B(s, i.targetKey, r)} WHERE ${B(s, i.sourceKey, r)} = ${B(t, "id", r)}${u}${l}${d}${f}${p}) AS ${r(o)}), JSON_ARRAY())`;
1345
- }, Qi = (e, t, n) => {
1450
+ }, ca = (e, t, n) => {
1346
1451
  let r = n.sql, i = n.nextAlias(), a = z(i, e.target, e.children, n);
1347
1452
  if (a === null) return null;
1348
1453
  let o = r`${B(i, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`, s = e.branch.where === void 0 ? r`` : r` AND ${L(W(e.branch.where), r)}`, c = e.branch.orderBy ?? [];
1349
1454
  if (e.branch.limit === void 0 && e.branch.offset === void 0) return r`COALESCE((SELECT JSON_ARRAYAGG(${a}${c.length > 0 ? r` ORDER BY ${r.csv(c.map((e) => e.direction === "desc" ? r`${B(i, e.column, r)} DESC` : r`${B(i, e.column, r)} ASC`))}` : r``}) FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o}${s}), JSON_ARRAY())`;
1350
1455
  let l = c.length > 0 ? r` ORDER BY ${r.csv(c.map((e) => e.direction === "desc" ? r`${r(e.column)} DESC` : r`${r(e.column)} ASC`))}` : r` ORDER BY ${r("id")}`, u = e.branch.limit, d = e.branch.offset, f = u !== void 0 && d !== void 0 ? r` AND ${B(i, "rn", r)} > ${H(d, r)} AND ${B(i, "rn", r)} <= ${H(d + u, r)}` : u === void 0 ? r` AND ${B(i, "rn", r)} > ${H(d, r)}` : r` AND ${B(i, "rn", r)} <= ${H(u, r)}`;
1351
1456
  return r`COALESCE((SELECT JSON_ARRAYAGG(${a} ORDER BY ${B(i, "rn", r)}) FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY ${r(e.foreignKey)}${l}) AS rn FROM ${r(e.target.tableName)}) AS ${r(i)} WHERE ${o}${s}${f}), JSON_ARRAY())`;
1352
- }, $i = (e, t, n) => {
1457
+ }, la = (e, t, n) => {
1353
1458
  let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = (t) => e.junction === void 0 ? void 0 : {
1354
1459
  projection: e.junction,
1355
1460
  source: t
1356
- }, 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 = ca(e, s, r, !0), p = e.branch.orderBy ?? [];
1461
+ }, l = r`${B(s, i.sourceKey, r)} = ${B(t, "id", r)}`, u = r`${B(o, "id", r)} = ${B(s, i.targetKey, r)}`, d = e.branch.where === void 0 ? r`` : r` AND ${L(W(e.branch.where), r)}`, f = va(e, s, r, !0), p = e.branch.orderBy ?? [];
1357
1462
  if (e.branch.limit === void 0 && e.branch.offset === void 0) {
1358
- let t = z(o, e.target, e.children, n, c(Hi(s)));
1463
+ let t = z(o, e.target, e.children, n, c(Qi(s)));
1359
1464
  return t === null ? null : r`COALESCE((SELECT JSON_ARRAYAGG(${t}${p.length > 0 ? r` ORDER BY ${r.csv(p.map((e) => e.direction === "desc" ? r`${B(o, e.column, r)} DESC` : r`${B(o, e.column, r)} ASC`))}` : r``}) FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${u} WHERE ${l}${f}${d}), JSON_ARRAY())`;
1360
1465
  }
1361
- 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, ee = 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)}`, te = e.branch.onJunction === void 0 ? r`` : r` WHERE ${U(W(e.branch.onJunction), s, r)}`, ne = z(o, e.target, e.children, n, c(Vi(o)));
1362
- if (ne === null) return null;
1363
- let re = e.junction === void 0 ? r`` : Bi(e.junction, s, r);
1364
- return r`COALESCE((SELECT JSON_ARRAYAGG(${ne} ORDER BY ${B(o, "rn", r)}) FROM (SELECT ${r(o)}.*${re}, ${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}${te}) AS ${r(o)} WHERE ${B(o, `__src_${i.sourceKey}`, r)} = ${B(t, "id", r)}${d}${ee}), JSON_ARRAY())`;
1365
- }, ea = (e, t, n) => {
1366
- let r = n.sql, i = n.nextAlias(), a = ta(i, t.table, t.children, n);
1466
+ let m = p.length > 0 ? r` ORDER BY ${r.csv(p.map((e) => e.direction === "desc" ? r`${B(o, e.column, r)} DESC` : r`${B(o, e.column, r)} ASC`))}` : r` ORDER BY ${B(o, "id", r)}`, h = e.branch.limit, g = e.branch.offset, _ = h !== void 0 && g !== void 0 ? r` AND ${B(o, "rn", r)} > ${H(g, r)} AND ${B(o, "rn", r)} <= ${H(g + h, r)}` : h === void 0 ? r` AND ${B(o, "rn", r)} > ${H(g, r)}` : r` AND ${B(o, "rn", r)} <= ${H(h, r)}`, v = e.branch.onJunction === void 0 ? r`` : r` WHERE ${U(W(e.branch.onJunction), s, r)}`, ee = z(o, e.target, e.children, n, c(Zi(o)));
1467
+ if (ee === null) return null;
1468
+ let te = e.junction === void 0 ? r`` : Xi(e.junction, s, r);
1469
+ return r`COALESCE((SELECT JSON_ARRAYAGG(${ee} ORDER BY ${B(o, "rn", r)}) FROM (SELECT ${r(o)}.*${te}, ${B(s, i.sourceKey, r)} AS ${r(`__src_${i.sourceKey}`)}, ROW_NUMBER() OVER (PARTITION BY ${B(s, i.sourceKey, r)}${m}) AS rn FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${u}${v}) AS ${r(o)} WHERE ${B(o, `__src_${i.sourceKey}`, r)} = ${B(t, "id", r)}${d}${_}), JSON_ARRAY())`;
1470
+ }, ua = (e, t, n) => {
1471
+ let r = n.sql, i = n.nextAlias(), a = da(i, t.table, t.children, n);
1367
1472
  if (a === null) return null;
1368
- let o = e.predicate ? r` WHERE ${U(e.predicate, i, r)}` : r``, s = v(e).length > 0 ? r` ORDER BY ${r.csv(v(e).map((e) => e.direction === "desc" ? r`${B(i, e.column, r)} DESC` : r`${B(i, e.column, r)} ASC`))}` : r``, c = r``, l = r``;
1473
+ let o = e.predicate ? r` WHERE ${U(e.predicate, i, r)}` : r``, s = b(e).length > 0 ? r` ORDER BY ${r.csv(b(e).map((e) => e.direction === "desc" ? r`${B(i, e.column, r)} DESC` : r`${B(i, e.column, r)} ASC`))}` : r``, c = r``, l = r``;
1369
1474
  if (e.skip !== void 0) {
1370
- let t = v(e).length > 0 ? s : r` ORDER BY (SELECT NULL)`;
1475
+ let t = b(e).length > 0 ? s : r` ORDER BY (SELECT NULL)`;
1371
1476
  l = e.take === void 0 ? r`${t} OFFSET ${H(e.skip, r)} ROWS` : r`${t} OFFSET ${H(e.skip, r)} ROWS FETCH NEXT ${H(e.take, r)} ROWS ONLY`;
1372
1477
  } else e.take !== void 0 && (c = r`TOP ${H(e.take, r)} `);
1373
1478
  let u = e.skip === void 0 ? s : r``;
1374
1479
  return r`SELECT ${c}(SELECT ${a} FOR JSON PATH, INCLUDE_NULL_VALUES, WITHOUT_ARRAY_WRAPPER) AS ${r("__row")} FROM ${r(t.table.tableName)} AS ${r(i)}${o}${u}${l}`;
1375
- }, ta = (e, t, n, r, i) => {
1480
+ }, da = (e, t, n, r, i) => {
1376
1481
  let a = r.sql, o = [];
1377
1482
  for (let n of Object.keys(t.fields)) o.push(a`${B(e, n, a)} AS ${a(n)}`);
1378
- if (i !== void 0) for (let e of i.projection.present) o.push(a`${B(i.source.alias, i.source.physical(e), a)} AS ${na(`_junction.${e}`, a)}`);
1483
+ if (i !== void 0) for (let e of i.projection.present) o.push(a`${B(i.source.alias, i.source.physical(e), a)} AS ${fa(`_junction.${e}`, a)}`);
1379
1484
  for (let t of n) {
1380
- let n = ra(t, e, r);
1485
+ let n = pa(t, e, r);
1381
1486
  if (n === null) return null;
1382
1487
  o.push(n);
1383
1488
  }
1384
1489
  return a.csv(o);
1385
- }, na = (e, t) => t.unsafe(`[${e.replace(/]/g, "]]")}]`), ra = (e, t, n) => {
1490
+ }, fa = (e, t) => t.unsafe(`[${e.replace(/]/g, "]]")}]`), pa = (e, t, n) => {
1386
1491
  switch (e.relation.kind) {
1387
- case "one": return mi(e) ? oa(hi(e), t, n) : ia(e, t, n);
1388
- case "many": return oa(e, t, n);
1389
- case "manyToMany": return sa(e, t, n);
1492
+ case "one": return wi(e) ? ga(Ti(e), t, n) : ma(e, t, n);
1493
+ case "many": return ga(e, t, n);
1494
+ case "manyToMany": return _a(e, t, n);
1390
1495
  }
1391
- }, ia = (e, t, n) => {
1392
- let r = n.sql, i = n.nextAlias(), a = ta(i, e.target, e.children, n);
1496
+ }, ma = (e, t, n) => {
1497
+ let r = n.sql, i = n.nextAlias(), a = da(i, e.target, e.children, n);
1393
1498
  if (a === null) return null;
1394
1499
  let o = e.fkSide === "source" ? r`${B(i, "id", r)} = ${B(t, e.foreignKey, r)}` : r`${B(i, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}`;
1395
1500
  return r`JSON_QUERY((SELECT TOP 1 ${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${o} FOR JSON PATH, INCLUDE_NULL_VALUES, WITHOUT_ARRAY_WRAPPER)) AS ${r(e.relationName)}`;
1396
- }, aa = (e, t, n) => {
1501
+ }, ha = (e, t, n) => {
1397
1502
  if (e.offset !== void 0) {
1398
1503
  let r = e.orderBy && e.orderBy.length > 0 ? t : n` ORDER BY (SELECT NULL)`, i = e.limit === void 0 ? n`${r} OFFSET ${H(e.offset, n)} ROWS` : n`${r} OFFSET ${H(e.offset, n)} ROWS FETCH NEXT ${H(e.limit, n)} ROWS ONLY`;
1399
1504
  return {
@@ -1407,29 +1512,29 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1407
1512
  pagination: n``,
1408
1513
  finalOrder: t
1409
1514
  };
1410
- }, oa = (e, t, n) => {
1411
- let r = n.sql, i = n.nextAlias(), a = ta(i, e.target, e.children, n);
1515
+ }, ga = (e, t, n) => {
1516
+ let r = n.sql, i = n.nextAlias(), a = da(i, e.target, e.children, n);
1412
1517
  if (a === null) return null;
1413
- 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 } = aa(e.branch, s, r);
1518
+ let o = e.branch.where === void 0 ? r`` : r` AND ${U(e.branch.where, i, r)}`, s = R(i, e.branch.orderBy, r), { top: c, pagination: l, finalOrder: u } = ha(e.branch, s, r);
1414
1519
  return r`ISNULL(JSON_QUERY((SELECT ${c}${a} FROM ${r(e.target.tableName)} AS ${r(i)} WHERE ${B(i, e.foreignKey, r)} = ${B(t, e.sourceKey, r)}${o}${u}${l} FOR JSON PATH, INCLUDE_NULL_VALUES)), JSON_QUERY('[]')) AS ${r(e.relationName)}`;
1415
- }, sa = (e, t, n) => {
1416
- let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = ta(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1520
+ }, _a = (e, t, n) => {
1521
+ let r = n.sql, i = e.relation, a = i.through(), o = n.nextAlias(), s = n.nextAlias(), c = da(o, e.target, e.children, n, e.junction === void 0 ? void 0 : {
1417
1522
  projection: e.junction,
1418
- source: Hi(s)
1523
+ source: Qi(s)
1419
1524
  });
1420
1525
  if (c === null) return null;
1421
- let l = e.branch.where === void 0 ? r`` : r` AND ${U(e.branch.where, o, r)}`, u = ca(e, s, r), d = R(o, e.branch.orderBy, r), { top: f, pagination: p, finalOrder: m } = aa(e.branch, d, r);
1526
+ let l = e.branch.where === void 0 ? r`` : r` AND ${U(e.branch.where, o, r)}`, u = va(e, s, r), d = R(o, e.branch.orderBy, r), { top: f, pagination: p, finalOrder: m } = ha(e.branch, d, r);
1422
1527
  return r`ISNULL(JSON_QUERY((SELECT ${f}${c} FROM ${r(a.tableName)} AS ${r(s)} INNER JOIN ${r(e.target.tableName)} AS ${r(o)} ON ${B(o, "id", r)} = ${B(s, i.targetKey, r)} WHERE ${B(s, i.sourceKey, r)} = ${B(t, "id", r)}${u}${l}${m}${p} FOR JSON PATH, INCLUDE_NULL_VALUES)), JSON_QUERY('[]')) AS ${r(e.relationName)}`;
1423
1528
  }, B = (e, t, n) => e === void 0 ? n`${n(t)}` : n`${n(e)}.${n(t)}`, V = (e, t) => t.unsafe(`'${e.replace(/'/g, "''")}'`), H = (e, t) => {
1424
1529
  if (!Number.isFinite(e) || !Number.isInteger(e) || e < 0) throw Error(`literalInt: expected non-negative integer, got ${e}`);
1425
1530
  return t.unsafe(String(e));
1426
- }, U = (e, t, n) => L(la(e, t), n), ca = (e, t, n, r = !1) => {
1531
+ }, U = (e, t, n) => L(ya(e, t), n), va = (e, t, n, r = !1) => {
1427
1532
  let i = e.branch.onJunction;
1428
1533
  return i === void 0 ? n`` : n` AND ${U(r ? W(i) : i, t, n)}`;
1429
- }, la = (e, t) => {
1430
- if ("not" in e) return { not: la(e.not, t) };
1431
- if ("and" in e) return { and: e.and.map((e) => la(e, t)) };
1432
- if ("or" in e) return { or: e.or.map((e) => la(e, t)) };
1534
+ }, ya = (e, t) => {
1535
+ if ("not" in e) return { not: ya(e.not, t) };
1536
+ if ("and" in e) return { and: e.and.map((e) => ya(e, t)) };
1537
+ if ("or" in e) return { or: e.or.map((e) => ya(e, t)) };
1433
1538
  if (e.op === "subquery-in" || e.op === "subquery-not-in") {
1434
1539
  let n = e;
1435
1540
  return {
@@ -1451,91 +1556,91 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1451
1556
  let t = e;
1452
1557
  return {
1453
1558
  ...t,
1454
- value: ua(t.value)
1559
+ value: ba(t.value)
1455
1560
  };
1456
- }, ua = (e) => e == null ? e : e instanceof Date ? e.toISOString() : typeof e == "boolean" ? +!!e : Array.isArray(e) ? e.map((e) => ua(e)) : e, da = Symbol.for("@voltro/database/coreTablesRegistry"), fa = globalThis, pa = fa[da] ?? (fa[da] = {}), ma = (e) => {
1457
- e.actors !== void 0 && (pa.actors = e.actors), e.tenants !== void 0 && (pa.tenants = e.tenants);
1458
- }, ha = (e, t) => () => {
1561
+ }, ba = (e) => e == null ? e : e instanceof Date ? e.toISOString() : typeof e == "boolean" ? +!!e : Array.isArray(e) ? e.map((e) => ba(e)) : e, xa = Symbol.for("@voltro/database/coreTablesRegistry"), Sa = globalThis, Ca = Sa[xa] ?? (Sa[xa] = {}), wa = (e) => {
1562
+ e.actors !== void 0 && (Ca.actors = e.actors), e.tenants !== void 0 && (Ca.tenants = e.tenants);
1563
+ }, Ta = (e, t) => () => {
1459
1564
  let n = e();
1460
1565
  if (n === void 0) throw Error(`core '${t}' table not registered; expected the framework CLI or your migrate step to call registerCoreTables({ ${t}: () => ${t}Table }) before the database handle is constructed`);
1461
1566
  return n();
1462
- }, ga = () => ha(() => pa.actors, "actors"), _a = () => ha(() => pa.tenants, "tenants"), va = w("actors", {
1463
- id: E(),
1464
- kind: C().oneOf([
1567
+ }, Ea = () => Ta(() => Ca.actors, "actors"), Da = () => Ta(() => Ca.tenants, "tenants"), Oa = T("actors", {
1568
+ id: D(),
1569
+ kind: w().oneOf([
1465
1570
  "user",
1466
1571
  "serviceAccount",
1467
1572
  "apiKey",
1468
1573
  "system"
1469
1574
  ]),
1470
- displayName: C().nullable(),
1471
- createdAt: T().default("now")
1472
- }), ya = (e, t) => ({
1575
+ displayName: w().nullable(),
1576
+ createdAt: E().default("now")
1577
+ }), ka = (e, t) => ({
1473
1578
  column: e,
1474
1579
  op: "eq",
1475
1580
  value: t
1476
- }), ba = (e, t) => ({
1581
+ }), Aa = (e, t) => ({
1477
1582
  column: e,
1478
1583
  op: "neq",
1479
1584
  value: t
1480
- }), xa = (e, t) => ({
1585
+ }), ja = (e, t) => ({
1481
1586
  column: e,
1482
1587
  op: "gt",
1483
1588
  value: t
1484
- }), Sa = (e, t) => ({
1589
+ }), Ma = (e, t) => ({
1485
1590
  column: e,
1486
1591
  op: "gte",
1487
1592
  value: t
1488
- }), Ca = (e, t) => ({
1593
+ }), Na = (e, t) => ({
1489
1594
  column: e,
1490
1595
  op: "lt",
1491
1596
  value: t
1492
- }), wa = (e, t) => ({
1597
+ }), Pa = (e, t) => ({
1493
1598
  column: e,
1494
1599
  op: "lte",
1495
1600
  value: t
1496
- }), Ta = (e, t) => ({
1601
+ }), Fa = (e, t) => ({
1497
1602
  column: e,
1498
1603
  op: "in",
1499
1604
  value: t
1500
- }), Ea = (e, t) => ({
1605
+ }), Ia = (e, t) => ({
1501
1606
  column: e,
1502
1607
  op: "notIn",
1503
1608
  value: t
1504
- }), Da = (e, t) => ({
1609
+ }), La = (e, t) => ({
1505
1610
  column: e,
1506
1611
  op: "contains",
1507
1612
  value: t
1508
- }), Oa = (e, t) => ({
1613
+ }), Ra = (e, t) => ({
1509
1614
  column: e,
1510
1615
  op: "startsWith",
1511
1616
  value: t
1512
- }), ka = (e, t) => ({
1617
+ }), za = (e, t) => ({
1513
1618
  column: e,
1514
1619
  op: "arrayContains",
1515
1620
  value: t
1516
- }), Aa = (e, t) => ({
1621
+ }), Ba = (e, t) => ({
1517
1622
  column: e,
1518
1623
  op: "arrayOverlaps",
1519
1624
  value: t
1520
- }), ja = (e, t) => ({
1625
+ }), Va = (e, t) => ({
1521
1626
  column: e,
1522
1627
  op: "arrayHas",
1523
1628
  value: t
1524
- }), Ma = {
1629
+ }), Ha = {
1525
1630
  column: "id",
1526
1631
  op: "in",
1527
1632
  value: []
1528
- }, Na = (e) => ({
1633
+ }, Ua = (e) => ({
1529
1634
  column: e,
1530
1635
  op: "isNull"
1531
- }), Pa = (e) => ({
1636
+ }), Wa = (e) => ({
1532
1637
  column: e,
1533
1638
  op: "isNotNull"
1534
- }), Fa = (e, t) => ({
1639
+ }), Ga = (e, t) => ({
1535
1640
  column: e,
1536
1641
  op: "spatial",
1537
1642
  value: t
1538
- }), Ia = (...e) => ({ and: e }), La = (...e) => ({ or: e }), Ra = (e) => ({ not: e }), za = (e, ...t) => {
1643
+ }), Ka = (...e) => ({ and: e }), qa = (...e) => ({ or: e }), Ja = (e) => ({ not: e }), Ya = (e, ...t) => {
1539
1644
  if (t.length === 0) throw Error(`jsonField("${e}"): at least one path segment is required`);
1540
1645
  let n = (n, r) => ({
1541
1646
  column: e,
@@ -1557,33 +1662,33 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1557
1662
  isNull: () => n("isNull"),
1558
1663
  isNotNull: () => n("isNotNull")
1559
1664
  };
1560
- }, Ba = (e) => "descriptor" in e ? e.descriptor : e, Va = (e, t) => ({
1665
+ }, Xa = (e) => "descriptor" in e ? e.descriptor : e, Za = (e, t) => ({
1561
1666
  column: e,
1562
1667
  op: "subquery-in",
1563
- subquery: Ba(t)
1564
- }), Ha = (e, t) => ({
1668
+ subquery: Xa(t)
1669
+ }), Qa = (e, t) => ({
1565
1670
  column: e,
1566
1671
  op: "subquery-not-in",
1567
- subquery: Ba(t)
1568
- }), Ua = (e) => ({
1672
+ subquery: Xa(t)
1673
+ }), $a = (e) => ({
1569
1674
  op: "exists",
1570
- subquery: Ba(e)
1571
- }), Wa = (e) => ({
1675
+ subquery: Xa(e)
1676
+ }), eo = (e) => ({
1572
1677
  op: "not-exists",
1573
- subquery: Ba(e)
1574
- }), Ga = (e, t) => e === t || e instanceof Date && t instanceof Date && e.getTime() === t.getTime(), Ka = (e, t) => {
1678
+ subquery: Xa(e)
1679
+ }), to = (e, t) => e === t || e instanceof Date && t instanceof Date && e.getTime() === t.getTime(), no = (e, t) => {
1575
1680
  if (e == null || t == null) return null;
1576
1681
  let n = e instanceof Date ? e.getTime() : e, r = t instanceof Date ? t.getTime() : t;
1577
1682
  return typeof n == typeof r ? n === r ? 0 : n > r ? 1 : -1 : null;
1578
- }, qa = (e, t, n = null) => {
1683
+ }, ro = (e, t, n = null) => {
1579
1684
  if (!t) return !1;
1580
- if ("not" in e) return !qa(e.not, t, n);
1685
+ if ("not" in e) return !ro(e.not, t, n);
1581
1686
  if ("and" in e) {
1582
- for (let r of e.and) if (!qa(r, t, n)) return !1;
1687
+ for (let r of e.and) if (!ro(r, t, n)) return !1;
1583
1688
  return !0;
1584
1689
  }
1585
1690
  if ("or" in e) {
1586
- for (let r of e.or) if (qa(r, t, n)) return !0;
1691
+ for (let r of e.or) if (ro(r, t, n)) return !0;
1587
1692
  return !1;
1588
1693
  }
1589
1694
  if (e.op === "subquery-in" || e.op === "subquery-not-in") {
@@ -1600,14 +1705,14 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1600
1705
  }
1601
1706
  let r = e, i = t[r.column];
1602
1707
  switch (r.op) {
1603
- case "eq": return Ga(i, r.value);
1604
- case "neq": return !Ga(i, r.value);
1605
- case "gt": return (Ka(i, r.value) ?? -1) > 0;
1606
- case "gte": return (Ka(i, r.value) ?? -1) >= 0;
1607
- case "lt": return (Ka(i, r.value) ?? 1) < 0;
1608
- case "lte": return (Ka(i, r.value) ?? 1) <= 0;
1609
- case "in": return Array.isArray(r.value) && r.value.some((e) => Ga(i, e));
1610
- case "notIn": return Array.isArray(r.value) && !r.value.some((e) => Ga(i, e));
1708
+ case "eq": return to(i, r.value);
1709
+ case "neq": return !to(i, r.value);
1710
+ case "gt": return (no(i, r.value) ?? -1) > 0;
1711
+ case "gte": return (no(i, r.value) ?? -1) >= 0;
1712
+ case "lt": return (no(i, r.value) ?? 1) < 0;
1713
+ case "lte": return (no(i, r.value) ?? 1) <= 0;
1714
+ case "in": return Array.isArray(r.value) && r.value.some((e) => to(i, e));
1715
+ case "notIn": return Array.isArray(r.value) && !r.value.some((e) => to(i, e));
1611
1716
  case "contains": return typeof i == "string" && typeof r.value == "string" && i.toLowerCase().includes(r.value.toLowerCase());
1612
1717
  case "startsWith": return typeof i == "string" && typeof r.value == "string" && i.startsWith(r.value);
1613
1718
  case "arrayContains": {
@@ -1623,17 +1728,17 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1623
1728
  case "isNotNull": return i != null;
1624
1729
  case "spatial": throw Error("@voltro/plugin-postgis: spatial predicates (ST_DWithin / ST_Contains / ST_Within / ST_Intersects / bbox &&) are not evaluable in-memory — use them in one-shot ctx.store.query reads, not reactive subscriptions.");
1625
1730
  }
1626
- }, Ja = function* (e) {
1731
+ }, io = function* (e) {
1627
1732
  if ("not" in e) {
1628
- yield* Ja(e.not);
1733
+ yield* io(e.not);
1629
1734
  return;
1630
1735
  }
1631
1736
  if ("and" in e) {
1632
- for (let t of e.and) yield* Ja(t);
1737
+ for (let t of e.and) yield* io(t);
1633
1738
  return;
1634
1739
  }
1635
1740
  if ("or" in e) {
1636
- for (let t of e.or) yield* Ja(t);
1741
+ for (let t of e.or) yield* io(t);
1637
1742
  return;
1638
1743
  }
1639
1744
  e.op === "subquery-in" || e.op === "subquery-not-in" ? yield {
@@ -1643,46 +1748,46 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1643
1748
  kind: "exists",
1644
1749
  descriptor: e.subquery
1645
1750
  });
1646
- }, Ya = function* (e, t = !0) {
1751
+ }, ao = function* (e, t = !0) {
1647
1752
  if ("not" in e) {
1648
- yield* Ya(e.not, !1);
1753
+ yield* ao(e.not, !1);
1649
1754
  return;
1650
1755
  }
1651
1756
  if ("and" in e) {
1652
- for (let n of e.and) yield* Ya(n, t);
1757
+ for (let n of e.and) yield* ao(n, t);
1653
1758
  return;
1654
1759
  }
1655
1760
  if ("or" in e) {
1656
- for (let t of e.or) yield* Ya(t, !1);
1761
+ for (let t of e.or) yield* ao(t, !1);
1657
1762
  return;
1658
1763
  }
1659
1764
  e.op !== "subquery-in" && e.op !== "subquery-not-in" && e.op !== "exists" && e.op !== "not-exists" && (yield {
1660
1765
  ...e,
1661
1766
  conjunctive: t
1662
1767
  });
1663
- }, Xa = (e, t) => ({
1768
+ }, oo = (e, t) => ({
1664
1769
  ...t,
1665
1770
  ...e,
1666
1771
  origin: e.origin ?? "injected"
1667
- }), Za = (e, t, n = {}) => ({
1772
+ }), so = (e, t, n = {}) => ({
1668
1773
  table: e,
1669
1774
  op: "insert",
1670
1775
  old: null,
1671
1776
  new: t,
1672
1777
  ...n
1673
- }), Qa = (e, t, n, r = {}) => ({
1778
+ }), co = (e, t, n, r = {}) => ({
1674
1779
  table: e,
1675
1780
  op: "update",
1676
1781
  old: t,
1677
1782
  new: n,
1678
1783
  ...r
1679
- }), $a = (e, t, n = {}) => ({
1784
+ }), lo = (e, t, n = {}) => ({
1680
1785
  table: e,
1681
1786
  op: "delete",
1682
1787
  old: t,
1683
1788
  new: null,
1684
1789
  ...n
1685
- }), eo = (e, t, n = {}) => {
1790
+ }), uo = (e, t, n = {}) => {
1686
1791
  let { at: r = "2026-01-01T00:00:00.000Z", column: i = "deletedAt", ...a } = n;
1687
1792
  return {
1688
1793
  table: e,
@@ -1697,13 +1802,13 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1697
1802
  },
1698
1803
  ...a
1699
1804
  };
1700
- }, to = (e) => e == null ? "null" : e instanceof Date ? JSON.stringify(e.toISOString()) : typeof e == "bigint" ? JSON.stringify(e.toString()) : Array.isArray(e) ? `[${e.map(to).join(",")}]` : typeof e == "object" ? `{${Object.entries(e).filter(([, e]) => e !== void 0).sort(([e], [t]) => e < t ? -1 : +(e > t)).map(([e, t]) => `${JSON.stringify(e)}:${to(t)}`).join(",")}}` : JSON.stringify(e) ?? "null", no = (e) => qt("sha256").update([
1805
+ }, fo = (e) => e == null ? "null" : e instanceof Date ? JSON.stringify(e.toISOString()) : typeof e == "bigint" ? JSON.stringify(e.toString()) : Array.isArray(e) ? `[${e.map(fo).join(",")}]` : typeof e == "object" ? `{${Object.entries(e).filter(([, e]) => e !== void 0).sort(([e], [t]) => e < t ? -1 : +(e > t)).map(([e, t]) => `${JSON.stringify(e)}:${fo(t)}`).join(",")}}` : JSON.stringify(e) ?? "null", po = (e) => qt("sha256").update([
1701
1806
  e.pipe,
1702
1807
  e.op,
1703
1808
  e.key,
1704
- to(e.next),
1705
- to(e.prev)
1706
- ].join("\0")).digest("hex").slice(0, 32), ro = (e, t) => `${e}:${t}`, io = (e) => {
1809
+ fo(e.next),
1810
+ fo(e.prev)
1811
+ ].join("\0")).digest("hex").slice(0, 32), mo = (e, t) => `${e}:${t}`, ho = (e) => {
1707
1812
  let t = e.lastIndexOf(":");
1708
1813
  if (t <= 0) return null;
1709
1814
  let n = Number(e.slice(t + 1));
@@ -1711,7 +1816,7 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1711
1816
  digest: e.slice(0, t),
1712
1817
  occurrence: n
1713
1818
  };
1714
- }, ao = class {
1819
+ }, go = class {
1715
1820
  #e = /* @__PURE__ */ new Map();
1716
1821
  #t;
1717
1822
  #n;
@@ -1733,7 +1838,7 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1733
1838
  }
1734
1839
  seedFromChangeKeys(e, t) {
1735
1840
  for (let n of e) {
1736
- let e = io(n);
1841
+ let e = ho(n);
1737
1842
  if (e === null) continue;
1738
1843
  let r = this.#e.get(e.digest), i = Math.max(r?.count ?? 0, e.occurrence + 1);
1739
1844
  this.#e.set(e.digest, {
@@ -1754,29 +1859,29 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1754
1859
  this.#e.delete(e.value);
1755
1860
  }
1756
1861
  }
1757
- }, oo = "VOLTRO_CHANGE_CLAIMS_TTL_HOURS", so = 1, co = (e = process.env) => {
1758
- let t = Number(e[oo]);
1862
+ }, _o = "VOLTRO_CHANGE_CLAIMS_TTL_HOURS", vo = 1, yo = (e = process.env) => {
1863
+ let t = Number(e[_o]);
1759
1864
  return (Number.isFinite(t) && t > 0 ? t : 1) * 2 * 36e5;
1760
- }, lo = new Jt(), uo = (e, t) => lo.run(e, t), fo = () => lo.getStore(), po = (e) => {
1761
- let t = e ?? lo.getStore();
1865
+ }, bo = new Jt(), xo = (e, t) => bo.run(e, t), So = () => bo.getStore(), Co = (e) => {
1866
+ let t = e ?? bo.getStore();
1762
1867
  return t === void 0 ? {} : {
1763
1868
  ...t.traceId === void 0 ? {} : { traceId: t.traceId },
1764
1869
  ...t.subjectId === void 0 ? {} : { subjectId: t.subjectId },
1765
1870
  ...t.procedure === void 0 ? {} : { procedure: t.procedure },
1766
1871
  ...t.via === void 0 ? {} : { via: t.via }
1767
1872
  };
1768
- }, mo = (e) => {
1769
- let t = lo.getStore();
1770
- return t === void 0 ? e(void 0) : lo.run(t, () => e(t));
1771
- }, ho = 3e4, go = 1e4, G = /* @__PURE__ */ new Map(), K = 0, _o = (e, t, n) => `${e}\u0000${t}\u0000${String(n)}`, vo = (e) => {
1873
+ }, wo = (e) => {
1874
+ let t = bo.getStore();
1875
+ return t === void 0 ? e(void 0) : bo.run(t, () => e(t));
1876
+ }, To = 3e4, Eo = 1e4, G = /* @__PURE__ */ new Map(), K = 0, Do = (e, t, n) => `${e}\u0000${t}\u0000${String(n)}`, Oo = (e) => {
1772
1877
  for (let [t, n] of G) {
1773
- let r = n.filter((t) => e - t.at < ho);
1878
+ let r = n.filter((t) => e - t.at < To);
1774
1879
  K -= n.length - r.length, r.length === 0 ? G.delete(t) : r.length !== n.length && G.set(t, r);
1775
1880
  }
1776
- }, yo = (e, t) => {
1881
+ }, ko = (e, t) => {
1777
1882
  if (t.traceId === void 0 && t.subjectId === void 0 && t.procedure === void 0) return;
1778
1883
  let n = Date.now();
1779
- if (K >= go && vo(n), K >= go) return;
1884
+ if (K >= Eo && Oo(n), K >= Eo) return;
1780
1885
  let r = G.get(e);
1781
1886
  r === void 0 ? G.set(e, [{
1782
1887
  attribution: t,
@@ -1785,38 +1890,38 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1785
1890
  attribution: t,
1786
1891
  at: n
1787
1892
  }), K += 1;
1788
- }, bo = (e) => {
1893
+ }, Ao = (e) => {
1789
1894
  let t = G.get(e);
1790
1895
  if (t === void 0 || t.length === 0) return;
1791
1896
  let n = t.shift();
1792
- if (--K, t.length === 0 && G.delete(e), !(Date.now() - n.at >= ho)) return n.attribution;
1793
- }, xo = (e) => (G.get(e)?.length ?? 0) > 0, q = /* @__PURE__ */ new Map(), So = /* @__PURE__ */ new Map(), Co = /* @__PURE__ */ new Map(), wo = 250, To = (e) => {
1794
- let t = So.get(e);
1897
+ if (--K, t.length === 0 && G.delete(e), !(Date.now() - n.at >= To)) return n.attribution;
1898
+ }, jo = (e) => (G.get(e)?.length ?? 0) > 0, q = /* @__PURE__ */ new Map(), Mo = /* @__PURE__ */ new Map(), No = /* @__PURE__ */ new Map(), Po = 250, Fo = (e) => {
1899
+ let t = Mo.get(e);
1795
1900
  if (t === void 0) return;
1796
- So.delete(e);
1797
- let n = Co.get(e);
1798
- n !== void 0 && (clearTimeout(n), Co.delete(e));
1901
+ Mo.delete(e);
1902
+ let n = No.get(e);
1903
+ n !== void 0 && (clearTimeout(n), No.delete(e));
1799
1904
  for (let e of t) e();
1800
- }, Eo = (e) => {
1905
+ }, Io = (e) => {
1801
1906
  q.set(e, (q.get(e) ?? 0) + 1);
1802
- }, Do = (e) => {
1907
+ }, Lo = (e) => {
1803
1908
  let t = (q.get(e) ?? 0) - 1;
1804
1909
  if (t > 0) {
1805
1910
  q.set(e, t);
1806
1911
  return;
1807
1912
  }
1808
- q.delete(e), To(e);
1809
- }, Oo = (e, t, n, r) => {
1810
- let i = n == null ? void 0 : _o(e, t, n), a = () => r(i === void 0 ? void 0 : bo(i));
1913
+ q.delete(e), Fo(e);
1914
+ }, Ro = (e, t, n, r) => {
1915
+ let i = n == null ? void 0 : Do(e, t, n), a = () => r(i === void 0 ? void 0 : Ao(i));
1811
1916
  if (i === void 0) {
1812
1917
  a();
1813
1918
  return;
1814
1919
  }
1815
- if (xo(i)) {
1920
+ if (jo(i)) {
1816
1921
  a();
1817
1922
  return;
1818
1923
  }
1819
- let o = So.get(e);
1924
+ let o = Mo.get(e);
1820
1925
  if (o === void 0 && (q.get(e) ?? 0) === 0) {
1821
1926
  a();
1822
1927
  return;
@@ -1825,35 +1930,35 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1825
1930
  o.push(a);
1826
1931
  return;
1827
1932
  }
1828
- So.set(e, [a]);
1829
- let s = setTimeout(() => To(e), wo);
1830
- typeof s == "object" && typeof s.unref == "function" && s.unref(), Co.set(e, s);
1831
- }, ko = () => {
1933
+ Mo.set(e, [a]);
1934
+ let s = setTimeout(() => Fo(e), Po);
1935
+ typeof s == "object" && typeof s.unref == "function" && s.unref(), No.set(e, s);
1936
+ }, zo = () => {
1832
1937
  G.clear(), K = 0, q.clear();
1833
- for (let e of Co.values()) clearTimeout(e);
1834
- Co.clear(), So.clear();
1835
- }, Ao = () => K, jo = 64, Mo = "\0", No = 32, Po = (e, ...t) => `${e}_${qt("sha256").update(t.map(String).join(Mo)).digest("hex").slice(0, No)}`, Fo = (e) => e.length + 1 + No, J = /* @__PURE__ */ new Map(), Io = (e, t) => {
1938
+ for (let e of No.values()) clearTimeout(e);
1939
+ No.clear(), Mo.clear();
1940
+ }, Bo = () => K, Vo = 64, Ho = "\0", Uo = 32, Wo = (e, ...t) => `${e}_${qt("sha256").update(t.map(String).join(Ho)).digest("hex").slice(0, Uo)}`, Go = (e) => e.length + 1 + Uo, J = /* @__PURE__ */ new Map(), Ko = (e, t) => {
1836
1941
  J.set(e, {
1837
1942
  recorder: t.recorder,
1838
1943
  tables: new Set(t.tables),
1839
1944
  ownTables: new Set(t.ownTables)
1840
1945
  });
1841
- }, Lo = (e) => {
1946
+ }, qo = (e) => {
1842
1947
  J.delete(e);
1843
- }, Ro = () => J.clear(), zo = new Jt(), Bo = (e) => zo.run({ n: 1 }, e), Vo = (e) => k.suspend(() => {
1844
- let t = zo.getStore();
1948
+ }, Jo = () => J.clear(), Yo = new Jt(), Xo = (e) => Yo.run({ n: 1 }, e), Zo = (e) => k.suspend(() => {
1949
+ let t = Yo.getStore();
1845
1950
  if (t !== void 0) return t.n += 1, k.ensuring(e, k.sync(() => {
1846
1951
  --t.n;
1847
1952
  }));
1848
1953
  let n = { n: 1 };
1849
- return zo.enterWith(n), k.ensuring(e, k.sync(() => {
1954
+ return Yo.enterWith(n), k.ensuring(e, k.sync(() => {
1850
1955
  --n.n;
1851
1956
  }));
1852
- }), Ho = () => (zo.getStore()?.n ?? 0) > 0, Uo = (e) => {
1853
- if (J.size === 0 || (zo.getStore()?.n ?? 0) > 0) return !1;
1957
+ }), Qo = () => (Yo.getStore()?.n ?? 0) > 0, $o = (e) => {
1958
+ if (J.size === 0 || (Yo.getStore()?.n ?? 0) > 0) return !1;
1854
1959
  for (let t of J.values()) if (!t.ownTables.has(e) && t.tables.has(e)) return !0;
1855
1960
  return !1;
1856
- }, Wo = async (e, t) => {
1961
+ }, es = async (e, t) => {
1857
1962
  if (J.size !== 0) {
1858
1963
  for (let [n, r] of J.entries()) if (!r.ownTables.has(t.table) && r.tables.has(t.table)) try {
1859
1964
  await r.recorder(e, t);
@@ -1862,54 +1967,54 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1862
1967
  throw r === void 0 ? e : Error(`write recorder '${n}' failed while recording a ${t.op} on '${t.table}': ${r}`, { cause: e });
1863
1968
  }
1864
1969
  }
1865
- }, Go = Ut.exponential({
1970
+ }, ts = Ut.exponential({
1866
1971
  start: 5e-4,
1867
1972
  factor: 2,
1868
1973
  count: 16
1869
- }), Ko = A.counter("voltro_db_queries_total", { description: "Database operations executed, by dialect and operation kind." }), qo = A.histogram("voltro_db_query_duration_seconds", Go, "Database operation duration in seconds, by dialect and operation kind."), Jo = A.counter("voltro_db_errors_total", { description: "Database operations that threw, by dialect and operation kind." }), Yo = 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." }), Xo = 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." }), Zo = [], Qo = /* @__PURE__ */ new Map(), $o = /* @__PURE__ */ new Map(), es = /* @__PURE__ */ new Map(), ts = (e, t) => {
1870
- let n = `${e}\u0000${t}`, r = Qo.get(n);
1974
+ }), ns = A.counter("voltro_db_queries_total", { description: "Database operations executed, by dialect and operation kind." }), rs = A.histogram("voltro_db_query_duration_seconds", ts, "Database operation duration in seconds, by dialect and operation kind."), is = A.counter("voltro_db_errors_total", { description: "Database operations that threw, by dialect and operation kind." }), as = A.gauge("voltro_db_operations_in_flight", { description: "Database operations currently executing, by dialect. An upper bound on connections the framework holds; NOT the driver pool's waiting count." }), os = A.counter("voltro_db_eager_fallback_total", { description: "Eager-load queries that degraded from the single-roundtrip JSON-agg path to the multi-query walker, by dialect and reason." }), ss = [], cs = /* @__PURE__ */ new Map(), ls = /* @__PURE__ */ new Map(), us = /* @__PURE__ */ new Map(), ds = (e, t) => {
1975
+ let n = `${e}\u0000${t}`, r = cs.get(n);
1871
1976
  if (r !== void 0) return r;
1872
1977
  let i = (n) => A.tagged(A.tagged(n, "dialect", e), "op", t), a = {
1873
- count: i(Ko),
1874
- duration: i(qo),
1875
- errors: i(Jo)
1978
+ count: i(ns),
1979
+ duration: i(rs),
1980
+ errors: i(is)
1876
1981
  };
1877
- return Qo.set(n, a), a;
1878
- }, ns = () => {
1879
- Qo.clear(), $o.clear(), es.clear();
1880
- }, rs = () => Qo.size + $o.size + es.size, is = /* @__PURE__ */ new Map(), as = (e, t) => {
1881
- let n = Math.max(0, (is.get(e) ?? 0) + t);
1882
- n === 0 ? is.delete(e) : is.set(e, n);
1883
- let r = $o.get(e);
1884
- r === void 0 && (r = A.tagged(Yo, "dialect", e), $o.set(e, r)), r.unsafeUpdate(n, Zo);
1885
- }, os = (e) => is.get(e) ?? 0, ss = (e) => {
1886
- let t = ts(String(e.dialect), e.op);
1887
- t.count.unsafeUpdate(1, Zo), t.duration.unsafeUpdate(e.durationMs / 1e3, Zo), e.status === "error" && t.errors.unsafeUpdate(1, Zo);
1888
- }, cs = async (e, t, n) => {
1982
+ return cs.set(n, a), a;
1983
+ }, fs = () => {
1984
+ cs.clear(), ls.clear(), us.clear();
1985
+ }, ps = () => cs.size + ls.size + us.size, ms = /* @__PURE__ */ new Map(), hs = (e, t) => {
1986
+ let n = Math.max(0, (ms.get(e) ?? 0) + t);
1987
+ n === 0 ? ms.delete(e) : ms.set(e, n);
1988
+ let r = ls.get(e);
1989
+ r === void 0 && (r = A.tagged(as, "dialect", e), ls.set(e, r)), r.unsafeUpdate(n, ss);
1990
+ }, gs = (e) => ms.get(e) ?? 0, _s = (e) => {
1991
+ let t = ds(String(e.dialect), e.op);
1992
+ t.count.unsafeUpdate(1, ss), t.duration.unsafeUpdate(e.durationMs / 1e3, ss), e.status === "error" && t.errors.unsafeUpdate(1, ss);
1993
+ }, vs = async (e, t, n) => {
1889
1994
  let r = performance.now(), i = String(e);
1890
- as(i, 1);
1995
+ hs(i, 1);
1891
1996
  let a = "ok";
1892
1997
  try {
1893
1998
  return await n();
1894
1999
  } catch (e) {
1895
2000
  throw a = "error", e;
1896
2001
  } finally {
1897
- as(i, -1), ss({
2002
+ hs(i, -1), _s({
1898
2003
  dialect: e,
1899
2004
  op: t,
1900
2005
  durationMs: performance.now() - r,
1901
2006
  status: a
1902
2007
  });
1903
2008
  }
1904
- }, ls = 3e5, us = (e) => {
2009
+ }, ys = 3e5, bs = (e) => {
1905
2010
  if (e == null || e === "") return;
1906
2011
  let t = Number(e);
1907
2012
  return Number.isFinite(t) && t >= 0 ? Math.floor(t) : void 0;
1908
- }, ds = (e, t = process.env) => us(t.VOLTRO_DB_EAGER_FALLBACK_WARN_INTERVAL_MS) ?? us(e) ?? 3e5, fs = (e, t = {}) => {
1909
- let n = ds(t.warnIntervalMs), r = t.now ?? (() => Date.now()), i = /* @__PURE__ */ new Map();
2013
+ }, xs = (e, t = process.env) => bs(t.VOLTRO_DB_EAGER_FALLBACK_WARN_INTERVAL_MS) ?? bs(e) ?? 3e5, Ss = (e, t = {}) => {
2014
+ let n = xs(t.warnIntervalMs), r = t.now ?? (() => Date.now()), i = /* @__PURE__ */ new Map();
1910
2015
  return (t) => {
1911
- let a = `${t.dialect} ${t.reason}`, o = es.get(a);
1912
- o === void 0 && (o = A.tagged(A.tagged(Xo, "dialect", String(t.dialect)), "reason", t.reason), es.set(a, o)), o.unsafeUpdate(1, Zo);
2016
+ let a = `${t.dialect} ${t.reason}`, o = us.get(a);
2017
+ o === void 0 && (o = A.tagged(A.tagged(os, "dialect", String(t.dialect)), "reason", t.reason), us.set(a, o)), o.unsafeUpdate(1, ss);
1913
2018
  let s = `${t.table}\u0000${t.reason}`, c = i.get(s), l = c === void 0 || n > 0 && r() - c >= n, u = {
1914
2019
  table: t.table,
1915
2020
  dialect: String(t.dialect),
@@ -1923,10 +2028,10 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1923
2028
  }
1924
2029
  i.set(s, r()), e.warn(t.reason === "execute-failed" ? "eager-load JSON-agg statement FAILED and was re-run on the multi-query walker — this query pays both paths on every call. Counted as voltro_db_eager_fallback_total{reason=\"execute-failed\"}." : "eager-load could not be compiled to a single JSON-agg roundtrip and is running on the multi-query walker — one round trip per relation level, on every call. Counted as voltro_db_eager_fallback_total{reason=\"not-compilable\"}.", u);
1925
2030
  };
1926
- }, ps = (e) => {
2031
+ }, Cs = (e) => {
1927
2032
  if (Ht.isSuccess(e)) return e.value;
1928
- throw O.squash(e.cause);
1929
- }, ms = "10 millis", hs = 3, gs = async (e) => {
2033
+ throw zt.squash(e.cause);
2034
+ }, ws = "10 millis", Ts = 3, Es = async (e) => {
1930
2035
  let t = 0, n = k.suspend(() => {
1931
2036
  let n = ++t;
1932
2037
  return e.withTransaction(k.flatMap(k.serviceOption(Yt), (t) => {
@@ -1937,10 +2042,10 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1937
2042
  });
1938
2043
  return e.prepare === void 0 ? i : k.flatMap(e.prepare(r), () => i);
1939
2044
  })).pipe(k.catchAllDefect((t) => e.isRetryable(t) ? k.fail(t) : k.die(t)));
1940
- }), r = Gt.exponential(ms).pipe(Gt.compose(Gt.recurs(hs)), Gt.whileInput(e.isRetryable)), i = n.pipe(k.retry(r), k.withSpan(e.span.name, { attributes: { ...e.span.attributes } }));
1941
- return cs(e.dialect, "transaction", async () => ps(await e.runPromiseExit(e.wrapProgram === void 0 ? i : e.wrapProgram(i))));
1942
- }, _s = async (e) => {
1943
- let t = fo(), n = t === void 0 ? (e) => e() : (e) => uo(t, e), r = await gs({
2045
+ }), r = Gt.exponential(ws).pipe(Gt.compose(Gt.recurs(Ts)), Gt.whileInput(e.isRetryable)), i = n.pipe(k.retry(r), k.withSpan(e.span.name, { attributes: { ...e.span.attributes } }));
2046
+ return vs(e.dialect, "transaction", async () => Cs(await e.runPromiseExit(e.wrapProgram === void 0 ? i : e.wrapProgram(i))));
2047
+ }, Ds = async (e) => {
2048
+ let t = So(), n = t === void 0 ? (e) => e() : (e) => xo(t, e), r = await Es({
1944
2049
  ...e,
1945
2050
  body: (r) => {
1946
2051
  let i = e.makeView(r, t);
@@ -1951,50 +2056,50 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
1951
2056
  }
1952
2057
  });
1953
2058
  return r.view.commitEvents(), r.result;
1954
- }, vs = /* @__PURE__ */ new Set([
2059
+ }, Os = /* @__PURE__ */ new Set([
1955
2060
  "1213",
1956
2061
  "ER_LOCK_DEADLOCK",
1957
2062
  "1205",
1958
2063
  "ER_LOCK_WAIT_TIMEOUT",
1959
2064
  "1020",
1960
2065
  "ER_CHECKREAD"
1961
- ]), ys = /* @__PURE__ */ new Set(["40001", "40P01"]), bs = /* @__PURE__ */ new Set(["1205"]), xs = /* @__PURE__ */ new Set([
2066
+ ]), ks = /* @__PURE__ */ new Set(["40001", "40P01"]), As = /* @__PURE__ */ new Set(["1205"]), js = /* @__PURE__ */ new Set([
1962
2067
  "SQLITE_BUSY",
1963
2068
  "5",
1964
2069
  "SQLITE_LOCKED",
1965
2070
  "6"
1966
- ]), Ss = /write-write conflict|write-read conflict|database is locked|table is locked|database is busy/i, Cs = /* @__PURE__ */ new Set([
2071
+ ]), Ms = /write-write conflict|write-read conflict|database is locked|table is locked|database is busy/i, Ns = /* @__PURE__ */ new Set([
1967
2072
  1213,
1968
2073
  1205,
1969
2074
  1020
1970
- ]), ws = /* @__PURE__ */ new Set([
1971
- ...vs,
1972
- ...ys,
1973
- ...bs,
1974
- ...xs
1975
- ]), Ts = (e) => xn(e).some(Es), Es = (e) => {
2075
+ ]), Ps = /* @__PURE__ */ new Set([
2076
+ ...Os,
2077
+ ...ks,
2078
+ ...As,
2079
+ ...js
2080
+ ]), Fs = (e) => xn(e).some(Is), Is = (e) => {
1976
2081
  let t = e;
1977
2082
  for (let e = 0; e < 6 && typeof t == "object" && t; e++) {
1978
2083
  let e = t;
1979
- if (typeof e.errno == "number" && Cs.has(e.errno) || typeof e.number == "number" && bs.has(String(e.number)) || typeof e.code == "string" && ws.has(e.code) || typeof e.sqlState == "string" && ys.has(e.sqlState) || typeof e.message == "string" && Ss.test(e.message)) return !0;
2084
+ if (typeof e.errno == "number" && Ns.has(e.errno) || typeof e.number == "number" && As.has(String(e.number)) || typeof e.code == "string" && Ps.has(e.code) || typeof e.sqlState == "string" && ks.has(e.sqlState) || typeof e.message == "string" && Ms.test(e.message)) return !0;
1980
2085
  t = e.cause;
1981
2086
  }
1982
2087
  return !1;
1983
- }, Ds = "voltro/expires", Os = () => Ct({
1984
- id: Ds,
1985
- fields: { expiresAt: T().nullable() },
2088
+ }, Ls = "voltro/expires", Rs = () => St({
2089
+ id: Ls,
2090
+ fields: { expiresAt: E().nullable() },
1986
2091
  behaviors: { defaultWhere: () => "expiresAt IS NULL OR expiresAt > now()" }
1987
- }), ks = "voltro/localFirst", As = () => Ct({
1988
- id: ks,
2092
+ }), zs = "voltro/localFirst", Bs = () => St({
2093
+ id: zs,
1989
2094
  fields: {}
1990
- }), js = (e) => e.appliedMixins.some((e) => e.id === ks), Ms = (e) => {
2095
+ }), Vs = (e) => e.appliedMixins.some((e) => e.id === zs), Hs = (e) => {
1991
2096
  let t = [];
1992
- for (let n of Object.values(e)) js(n) && t.push(n.tableName);
2097
+ for (let n of Object.values(e)) Vs(n) && t.push(n.tableName);
1993
2098
  return t;
1994
- }, Ns = class extends Vt.TaggedError("TableStreamError") {}, Ps = 1e3, Fs = (e, t, n, r) => {
2099
+ }, Us = class extends Vt.TaggedError("TableStreamError") {}, Ws = 1e3, Gs = (e, t, n, r) => {
1995
2100
  let i = j.match(r, {
1996
2101
  onNone: () => e.where,
1997
- onSome: (n) => e.where ? Ia(e.where, xa(t, n)) : xa(t, n)
2102
+ onSome: (n) => e.where ? Ka(e.where, ja(t, n)) : ja(t, n)
1998
2103
  });
1999
2104
  return {
2000
2105
  table: e.table,
@@ -2009,19 +2114,19 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
2009
2114
  ...e.includeDeleted === void 0 ? {} : { includeDeleted: e.includeDeleted },
2010
2115
  ...e.crossTenant === void 0 ? {} : { crossTenant: e.crossTenant }
2011
2116
  };
2012
- }, Is = (e, t) => {
2013
- let n = t.pk ?? "id", r = t.chunkSize ?? Ps;
2117
+ }, Ks = (e, t) => {
2118
+ let n = t.pk ?? "id", r = t.chunkSize ?? Ws;
2014
2119
  return Kt.paginateChunkEffect(j.none(), (i) => {
2015
2120
  let a = k.tryPromise({
2016
- try: () => e.query(Fs(t, n, r, i)),
2017
- catch: (e) => new Ns({
2121
+ try: () => e.query(Gs(t, n, r, i)),
2122
+ catch: (e) => new Us({
2018
2123
  table: t.table,
2019
2124
  cause: e
2020
2125
  })
2021
2126
  });
2022
2127
  return (t.retry ? a.pipe(k.retry(t.retry)) : a).pipe(k.map((e) => [Bt.fromIterable(e), e.length === r && e.length > 0 ? j.some(j.some(e[e.length - 1][n])) : j.none()]));
2023
2128
  });
2024
- }, Ls = (e) => {
2129
+ }, qs = (e) => {
2025
2130
  let t = e.alpha ?? .5;
2026
2131
  if (t < 0 || t > 1) throw Error(`hybridSearch: alpha must be in [0, 1], got ${t}`);
2027
2132
  return (n) => {
@@ -2048,17 +2153,17 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
2048
2153
  }
2049
2154
  };
2050
2155
  };
2051
- }, Rs = async (e, t) => {
2156
+ }, Js = async (e, t) => {
2052
2157
  let n = e.as ?? "embedding", r = t.row[e.from];
2053
2158
  if (typeof r != "string" || r.length === 0) return {};
2054
2159
  let i = await t.embed(r);
2055
2160
  return { [n]: i };
2056
- }, zs = (e) => {
2161
+ }, Ys = (e) => {
2057
2162
  if (!Number.isInteger(e.dimensions) || e.dimensions <= 0) throw Error(`vectorEmbedding: dimensions must be a positive integer, got ${String(e.dimensions)}.`);
2058
- let t = e.as ?? "embedding", n = (t) => Rs(e, t);
2059
- return Ct({
2163
+ let t = e.as ?? "embedding", n = (t) => Js(e, t);
2164
+ return St({
2060
2165
  id: "voltro/vectorEmbedding",
2061
- fields: { [t]: _t(e.dimensions) },
2166
+ fields: { [t]: gt(e.dimensions) },
2062
2167
  ...e.index === !1 ? {} : { indexes: [{
2063
2168
  fields: [t],
2064
2169
  kind: "hnsw",
@@ -2073,19 +2178,19 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
2073
2178
  beforeUpdate: n
2074
2179
  }
2075
2180
  });
2076
- }, Bs = 63, Vs = "br_pr", Y = class extends Error {
2181
+ }, Xs = 63, Zs = "br_pr", Y = class extends Error {
2077
2182
  _tag = "BranchNameInvalid";
2078
2183
  constructor(e) {
2079
2184
  super(e), this.name = "BranchNameInvalid";
2080
2185
  }
2081
- }, Hs = (e, t) => {
2186
+ }, Qs = (e, t) => {
2082
2187
  if (!Number.isInteger(t) || t < 0) throw new Y(`prNumber must be a non-negative integer, got ${String(t)}`);
2083
- let n = qr(e);
2188
+ let n = ri(e);
2084
2189
  if (n.replace(/_/g, "") === "") throw new Y(`app slug '${e}' has no usable identifier characters`);
2085
- let r = `${Vs}${t}_${n}`;
2086
- if (r.length > Bs) throw new Y(`branch namespace '${r}' exceeds the ${Bs}-byte identifier limit — use a shorter app slug`);
2190
+ let r = `${Zs}${t}_${n}`;
2191
+ if (r.length > Xs) throw new Y(`branch namespace '${r}' exceeds the ${Xs}-byte identifier limit — use a shorter app slug`);
2087
2192
  return r;
2088
- }, Us = (e) => e.startsWith(Vs), Ws = {
2193
+ }, $s = (e) => e.startsWith(Zs), ec = {
2089
2194
  requested: {
2090
2195
  provision: "provisioning",
2091
2196
  destroy: "destroying"
@@ -2104,18 +2209,18 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
2104
2209
  fail: "failed"
2105
2210
  },
2106
2211
  destroyed: {}
2107
- }, Gs = class extends Error {
2212
+ }, tc = class extends Error {
2108
2213
  from;
2109
2214
  event;
2110
2215
  _tag = "BranchTransitionInvalid";
2111
2216
  constructor(e, t) {
2112
2217
  super(`invalid branch transition: ${e} --${t}-->`), this.from = e, this.event = t, this.name = "BranchTransitionInvalid";
2113
2218
  }
2114
- }, Ks = (e, t) => {
2115
- let n = Ws[e][t];
2116
- if (n === void 0) throw new Gs(e, t);
2219
+ }, nc = (e, t) => {
2220
+ let n = ec[e][t];
2221
+ if (n === void 0) throw new tc(e, t);
2117
2222
  return n;
2118
- }, qs = (e, t, n, r, i = [], a = []) => {
2223
+ }, rc = (e, t, n, r, i = [], a = []) => {
2119
2224
  if (n === "copy" && (r === void 0 || r === "")) throw new Y("seed 'copy' requires a parentNamespace to snapshot from");
2120
2225
  let o = [{
2121
2226
  kind: "create-namespace",
@@ -2145,13 +2250,13 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
2145
2250
  kind: "seed",
2146
2251
  detail: `run boot seeds into ${e}`
2147
2252
  }), o;
2148
- }, Js = (e) => {
2149
- if (!Us(e)) throw new Y(`refusing to plan teardown of '${e}' — not a branch namespace`);
2253
+ }, ic = (e) => {
2254
+ if (!$s(e)) throw new Y(`refusing to plan teardown of '${e}' — not a branch namespace`);
2150
2255
  return [{
2151
2256
  kind: "drop-namespace",
2152
2257
  detail: e
2153
2258
  }];
2154
- }, Ys = (e) => {
2259
+ }, ac = (e) => {
2155
2260
  if (e === void 0 || e === "") return !1;
2156
2261
  try {
2157
2262
  let t = new URL(e).hostname.toLowerCase();
@@ -2159,27 +2264,27 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
2159
2264
  } catch {
2160
2265
  return /\bneon\.(tech|build)\b/i.test(e);
2161
2266
  }
2162
- }, Xs = (e) => e.prefer === void 0 ? e.seed === "copy" && Ys(e.dbUrl) ? "neon-cow" : "namespace" : e.prefer, Zs = (e, t = {}) => [{
2267
+ }, oc = (e) => e.prefer === void 0 ? e.seed === "copy" && ac(e.dbUrl) ? "neon-cow" : "namespace" : e.prefer, sc = (e, t = {}) => [{
2163
2268
  kind: "neon-branch-create",
2164
2269
  detail: `${t.parentBranch ?? "main"} → ${e} (copy-on-write)`
2165
- }], Qs = (e) => {
2166
- if (!Us(e)) throw new Y(`refusing to plan teardown of '${e}' — not a branch namespace`);
2270
+ }], cc = (e) => {
2271
+ if (!$s(e)) throw new Y(`refusing to plan teardown of '${e}' — not a branch namespace`);
2167
2272
  return [{
2168
2273
  kind: "neon-branch-delete",
2169
2274
  detail: e
2170
2275
  }];
2171
- }, $s = (e) => e.mechanism === "neon-cow" ? Zs(e.branchId, e.neonParentBranch === void 0 ? {} : { parentBranch: e.neonParentBranch }) : qs(e.branchId, e.tableNames, e.seed, e.parentNamespace, e.foreignKeys, e.indexNames), ec = (e, t) => e === "neon-cow" ? Qs(t) : Js(t), tc = (e, t, n) => {
2276
+ }, lc = (e) => e.mechanism === "neon-cow" ? sc(e.branchId, e.neonParentBranch === void 0 ? {} : { parentBranch: e.neonParentBranch }) : rc(e.branchId, e.tableNames, e.seed, e.parentNamespace, e.foreignKeys, e.indexNames), uc = (e, t) => e === "neon-cow" ? cc(t) : ic(t), dc = (e, t, n) => {
2172
2277
  let r = e.filter((e) => e.state !== "destroyed" && e.state !== "destroying"), i = r.filter((e) => n - e.createdAtMs > t.ttlMs).map((e) => e.namespace), a = new Set(i);
2173
2278
  return {
2174
2279
  evict: i,
2175
2280
  rejectNew: r.filter((e) => !a.has(e.namespace)).length >= t.maxBranches
2176
2281
  };
2177
- }, nc = async (e, t) => {
2178
- let n = Hs(e.appSlug, e.prNumber), r = Xs({
2282
+ }, fc = async (e, t) => {
2283
+ let n = Qs(e.appSlug, e.prNumber), r = oc({
2179
2284
  seed: e.seed,
2180
2285
  ...e.dbUrl === void 0 ? {} : { dbUrl: e.dbUrl },
2181
2286
  ...e.prefer === void 0 ? {} : { prefer: e.prefer }
2182
- }), i = $s({
2287
+ }), i = lc({
2183
2288
  mechanism: r,
2184
2289
  branchId: n,
2185
2290
  tableNames: e.tableNames,
@@ -2208,15 +2313,15 @@ var Zt = (e) => typeof e == "string" && e !== "" ? e : null, Qt = async (e, t, n
2208
2313
  mechanism: r,
2209
2314
  steps: i
2210
2315
  };
2211
- }, rc = async (e, t, n) => {
2212
- let r = ec(t, e);
2316
+ }, pc = async (e, t, n) => {
2317
+ let r = uc(t, e);
2213
2318
  return t === "neon-cow" ? await n.neonBranchDelete(e) : await n.dropNamespace(e), r;
2214
- }, ic = (e, t, n) => tc(e, t, n), X = (e) => `"${e.replace(/"/g, "\"\"")}"`, ac = {
2319
+ }, mc = (e, t, n) => dc(e, t, n), X = (e) => `"${e.replace(/"/g, "\"\"")}"`, hc = {
2215
2320
  cascade: "CASCADE",
2216
2321
  restrict: "RESTRICT",
2217
2322
  setNull: "SET NULL",
2218
2323
  noAction: "NO ACTION"
2219
- }, Z = (e) => `'${e.replace(/'/g, "''")}'`, oc = (e, t) => {
2324
+ }, Z = (e) => `'${e.replace(/'/g, "''")}'`, gc = (e, t) => {
2220
2325
  let n = t.columns.map(Z).join(", ");
2221
2326
  return `DO $voltro_branch$
2222
2327
  DECLARE derived name;
@@ -2243,10 +2348,10 @@ BEGIN
2243
2348
  END IF;
2244
2349
  END
2245
2350
  $voltro_branch$`;
2246
- }, sc = (e, t) => {
2247
- let n = t.onDelete === void 0 ? "" : ` ON DELETE ${ac[t.onDelete]}`, r = t.onUpdate === void 0 ? "" : ` ON UPDATE ${ac[t.onUpdate]}`;
2351
+ }, _c = (e, t) => {
2352
+ let n = t.onDelete === void 0 ? "" : ` ON DELETE ${hc[t.onDelete]}`, r = t.onUpdate === void 0 ? "" : ` ON UPDATE ${hc[t.onUpdate]}`;
2248
2353
  return `ALTER TABLE ${X(e)}.${X(t.table)} ADD FOREIGN KEY (${X(t.column)}) REFERENCES ${X(e)}.${X(t.targetTable)} (${X(t.targetColumn)})${n}${r}`;
2249
- }, cc = (e) => {
2354
+ }, vc = (e) => {
2250
2355
  let t = () => {
2251
2356
  throw Error("namespace branch executor: Neon ops require a neon-cow executor (use a Neon connection for copy-on-write branches)");
2252
2357
  };
@@ -2254,24 +2359,24 @@ $voltro_branch$`;
2254
2359
  createNamespace: (t) => e.run(`CREATE SCHEMA IF NOT EXISTS ${X(t)}`),
2255
2360
  createTable: (t, n) => e.run(`CREATE TABLE IF NOT EXISTS ${X(t)}.${X(n)} (LIKE ${X(n)} INCLUDING ALL)`),
2256
2361
  copyTable: (t, n, r) => e.run(`INSERT INTO ${X(n)}.${X(r)} SELECT * FROM ${X(t)}.${X(r)}`),
2257
- addForeignKey: (t, n) => e.run(sc(t, n)),
2258
- restoreIndexName: (t, n) => e.run(oc(t, n)),
2362
+ addForeignKey: (t, n) => e.run(_c(t, n)),
2363
+ restoreIndexName: (t, n) => e.run(gc(t, n)),
2259
2364
  dropNamespace: (t) => e.run(`DROP SCHEMA IF EXISTS ${X(t)} CASCADE`),
2260
2365
  neonBranchCreate: t,
2261
2366
  neonBranchDelete: t
2262
2367
  };
2263
- }, lc = class extends Error {
2368
+ }, yc = class extends Error {
2264
2369
  _tag = "TenantResidencyUnresolved";
2265
2370
  constructor(e) {
2266
2371
  super(e), this.name = "TenantResidencyUnresolved";
2267
2372
  }
2268
- }, uc = class extends Error {
2373
+ }, bc = class extends Error {
2269
2374
  region;
2270
2375
  _tag = "TenantRegionUnavailable";
2271
2376
  constructor(e, t) {
2272
2377
  super(t), this.region = e, this.name = "TenantRegionUnavailable";
2273
2378
  }
2274
- }, dc, fc = (e) => {
2379
+ }, xc, Sc = (e) => {
2275
2380
  if (e.homes === void 0) throw Error("setResidencyConfig: `homes` is required");
2276
2381
  if (e.servableRegions === void 0 || e.servableRegions.length === 0) throw Error("setResidencyConfig: `servableRegions` must be non-empty (which regions this deployment serves)");
2277
2382
  let t = /* @__PURE__ */ new Map();
@@ -2280,55 +2385,55 @@ $voltro_branch$`;
2280
2385
  if (e !== void 0 && e !== n.region) throw Error(`residency: tenant '${n.tenantId}' is mapped to two regions ('${e}' and '${n.region}')`);
2281
2386
  t.set(n.tenantId, n.region);
2282
2387
  }
2283
- return dc = e, e;
2284
- }, pc = () => dc, mc = () => {
2285
- dc = void 0;
2286
- }, hc = (e, t) => {
2287
- if (e == null || e === "") throw new lc("residency is on but the request has no resolvable tenant — refusing to bind a store");
2388
+ return xc = e, e;
2389
+ }, Cc = () => xc, wc = () => {
2390
+ xc = void 0;
2391
+ }, Tc = (e, t) => {
2392
+ if (e == null || e === "") throw new yc("residency is on but the request has no resolvable tenant — refusing to bind a store");
2288
2393
  let n = t.homes.find((t) => t.tenantId === e);
2289
- if (n === void 0) throw new lc(`no residency home is mapped for tenant '${e}' — refusing to fall back to a default store (would be a residency violation)`);
2394
+ if (n === void 0) throw new yc(`no residency home is mapped for tenant '${e}' — refusing to fall back to a default store (would be a residency violation)`);
2290
2395
  return n;
2291
- }, gc = (e, t) => t.servableRegions.includes(e), _c = (e, t) => {
2292
- let n = hc(e.tenantId, t), r = Jr(n.tenantId);
2396
+ }, Ec = (e, t) => t.servableRegions.includes(e), Dc = (e, t) => {
2397
+ let n = Tc(e.tenantId, t), r = ii(n.tenantId);
2293
2398
  return {
2294
2399
  region: n.region,
2295
2400
  namespace: r,
2296
2401
  ...n.connectionKey === void 0 ? {} : { connectionKey: n.connectionKey }
2297
2402
  };
2298
- }, vc = (e, t, n) => {
2299
- let r = _c(e, t);
2300
- if (!gc(r.region, t)) throw new uc(r.region, `tenant homed in region '${r.region}', which this deployment does not serve — route to the home region`);
2403
+ }, Oc = (e, t, n) => {
2404
+ let r = Dc(e, t);
2405
+ if (!Ec(r.region, t)) throw new bc(r.region, `tenant homed in region '${r.region}', which this deployment does not serve — route to the home region`);
2301
2406
  let i = n.get(r.region);
2302
- if (i === void 0) throw new uc(r.region, `no store handle for home region '${r.region}' (declared servable but not wired) — failing closed`);
2407
+ if (i === void 0) throw new bc(r.region, `no store handle for home region '${r.region}' (declared servable but not wired) — failing closed`);
2303
2408
  return {
2304
2409
  store: i,
2305
2410
  placement: r
2306
2411
  };
2307
- }, yc = async (e, t, n, r) => {
2308
- let { store: i, placement: a } = vc(e, t, n);
2412
+ }, kc = async (e, t, n, r) => {
2413
+ let { store: i, placement: a } = Oc(e, t, n);
2309
2414
  return await r(i, a), a;
2310
- }, bc = (e) => {
2415
+ }, Ac = (e) => {
2311
2416
  if (typeof e == "string") return e;
2312
2417
  if ("jsonPath" in e) {
2313
2418
  let { column: t, path: n, numeric: r } = e.jsonPath;
2314
2419
  return `(json:${t}->${n.join(".")}${r ? "::num" : ""})`;
2315
2420
  }
2316
2421
  return `(${e.expr})`;
2317
- }, Q = (e) => e.map(bc), xc = (e, t) => {
2422
+ }, Q = (e) => e.map(Ac), jc = (e, t) => {
2318
2423
  if (e.length !== t.length) return !1;
2319
- for (let n = 0; n < e.length; n++) if (bc(e[n]) !== bc(t[n])) return !1;
2424
+ for (let n = 0; n < e.length; n++) if (Ac(e[n]) !== Ac(t[n])) return !1;
2320
2425
  return !0;
2321
- }, Sc = (e, t) => {
2426
+ }, Mc = (e, t) => {
2322
2427
  if (e.length >= t.length) return !1;
2323
- for (let n = 0; n < e.length; n++) if (bc(e[n]) !== bc(t[n])) return !1;
2428
+ for (let n = 0; n < e.length; n++) if (Ac(e[n]) !== Ac(t[n])) return !1;
2324
2429
  return !0;
2325
- }, Cc = (e) => {
2430
+ }, Nc = (e) => {
2326
2431
  let t = [], n = e.appliedIndexes, r = e.tableName;
2327
2432
  for (let e = 0; e < n.length; e++) {
2328
2433
  let i = n[e];
2329
2434
  for (let a = e + 1; a < n.length; a++) {
2330
2435
  let e = n[a];
2331
- if (xc(i.fields, e.fields)) {
2436
+ if (jc(i.fields, e.fields)) {
2332
2437
  let [n, a] = i.name < e.name ? [i, e] : [e, i];
2333
2438
  t.push({
2334
2439
  kind: "duplicate-fields",
@@ -2339,13 +2444,13 @@ $voltro_branch$`;
2339
2444
  });
2340
2445
  continue;
2341
2446
  }
2342
- Sc(i.fields, e.fields) ? t.push({
2447
+ Mc(i.fields, e.fields) ? t.push({
2343
2448
  kind: "redundant-prefix",
2344
2449
  table: r,
2345
2450
  redundant: i,
2346
2451
  coveredBy: e,
2347
2452
  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).`
2348
- }) : Sc(e.fields, i.fields) && t.push({
2453
+ }) : Mc(e.fields, i.fields) && t.push({
2349
2454
  kind: "redundant-prefix",
2350
2455
  table: r,
2351
2456
  redundant: e,
@@ -2355,23 +2460,23 @@ $voltro_branch$`;
2355
2460
  }
2356
2461
  }
2357
2462
  return t;
2358
- }, wc = (e) => {
2463
+ }, Pc = (e) => {
2359
2464
  let t = [];
2360
- for (let n of e) t.push(...Cc(n));
2465
+ for (let n of e) t.push(...Nc(n));
2361
2466
  return t;
2362
- }, Tc = "\x1B[", Ec = `${Tc}38;2;245;158;11m`, Dc = `${Tc}38;2;16;185;129m`, Oc = (e, t) => `${e}${t}${N.reset}`, $ = (e, t, n) => e ? typeof t == "function" ? t(n) : Oc(t, n) : n, kc = (e, t = {}) => {
2363
- 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, Dc, e), c = (e) => $(n, Ec, e), l = (e) => $(n, N.dim, e), u = `${c("index audit")} ${l("·")} ${$(n, N.bold, e.kind)}`, d = e.redundant.fields.length, f = Q(e.coveredBy.fields.slice(d)), p = (e, t) => {
2467
+ }, Fc = "\x1B[", Ic = `${Fc}38;2;245;158;11m`, Lc = `${Fc}38;2;16;185;129m`, Rc = (e, t) => `${e}${t}${N.reset}`, $ = (e, t, n) => e ? typeof t == "function" ? t(n) : Rc(t, n) : n, zc = (e, t = {}) => {
2468
+ let n = t.color ?? !0, r = t.indent ?? " ", i = (e) => $(n, N.dim, e.padEnd(11)), a = (e) => $(n, (e) => N.bold(N.brand(e)), e), o = (e) => $(n, N.brightRed24, e), s = (e) => $(n, Lc, e), c = (e) => $(n, Ic, e), l = (e) => $(n, N.dim, e), u = `${c("index audit")} ${l("·")} ${$(n, N.bold, e.kind)}`, d = e.redundant.fields.length, f = Q(e.coveredBy.fields.slice(d)), p = (e, t) => {
2364
2469
  let n = e.slice(0, t), r = e.slice(t), i = [];
2365
2470
  return n.length > 0 && i.push(s(`[${n.join(", ")}]`)), r.length > 0 && i.push(c(`+ [${r.join(", ")}]`)), i.join(" ");
2366
2471
  }, m = [];
2367
2472
  return m.push(u), m.push(""), m.push(`${i("table")}${a(e.table)}`), m.push(""), m.push(`${i("redundant")}${o(e.redundant.name)}`), m.push(`${i("")}${p(Q(e.redundant.fields), d)}`), m.push(""), m.push(`${i("covered by")}${s(e.coveredBy.name)}`), m.push(`${i("")}${p(Q(e.coveredBy.fields), d)}`), f.length > 0 && m.push(`${i("")}${l(`└ extra columns: ${f.join(", ")}`)}`), m.push(""), e.kind === "redundant-prefix" ? (m.push(`${i("why")}B-tree indexes serve queries that filter on a LEADING PREFIX of`), m.push(`${i("")}their column list. The wider index already covers every`), m.push(`${i("")}query the narrower one can serve.`), m.push(`${i("")}${l("Same rule on Postgres / MySQL / MariaDB / MSSQL / SQLite.")}`)) : (m.push(`${i("why")}Two indexes on the same columns under different names.`), m.push(`${i("")}The B-tree engine builds both — same coverage, double cost.`), m.push(`${i("")}${l("Same rule on Postgres / MySQL / MariaDB / MSSQL / SQLite.")}`)), m.push(""), m.push(`${i("cost")}Every ${a("INSERT")} / ${a("UPDATE")} / ${a("DELETE")} on this table writes`), m.push(`${i("")}to ${$(n, N.bold, "both")} B-trees. Pure write overhead, zero read benefit.`), m.push(""), m.push(`${i("fix")}Drop ${o(e.redundant.name)}`), m.push(`${i("")}${l("Keep only if profiling shows the smaller index gives a")}`), m.push(`${i("")}${l("measurable cache-locality boost on a write-heavy hot path.")}`), m.push(`${i("")}${l("Silence with VOLTRO_INDEX_AUDIT=off if intentional.")}`), m.map((e) => `${r}${e}`).join("\n");
2368
- }, Ac = (e, { apply: t, undo: n }) => ({
2473
+ }, Bc = (e, { apply: t, undo: n }) => ({
2369
2474
  name: e,
2370
2475
  apply: t,
2371
2476
  undo: n
2372
- }), jc = (e) => {
2477
+ }), Vc = (e) => {
2373
2478
  if (!/^\d{14}_/.test(e.id)) throw Error(`migration "${e.id}": id must start with a 14-digit timestamp followed by "_" (convention: <YYYYMMDDHHMMSS>_<slug>)`);
2374
- let t = e.steps({ step: Ac });
2479
+ let t = e.steps({ step: Bc });
2375
2480
  if (t.length === 0) throw Error(`migration "${e.id}": at least one step is required`);
2376
2481
  return {
2377
2482
  __migration: !0,
@@ -2379,106 +2484,106 @@ $voltro_branch$`;
2379
2484
  name: e.name,
2380
2485
  steps: t
2381
2486
  };
2382
- }, Mc = (e) => typeof e == "object" && !!e && "__migration" in e && e.__migration === !0, Nc = w("_voltro_migrations", {
2383
- id: E({ prefix: "mig" }),
2384
- name: C(),
2385
- hash: C(),
2386
- status: C(),
2387
- appliedAt: T().nullable(),
2388
- durationMs: _().nullable(),
2389
- errorMessage: C().nullable(),
2390
- errorStack: C().nullable(),
2391
- workflowRunId: C().nullable(),
2392
- createdAt: T().default("now"),
2393
- updatedAt: T().default("now").onUpdate("now")
2394
- }).index(["status"]), Pc = w("_voltro_seeds", {
2395
- id: E({ prefix: "seed" }),
2396
- name: C(),
2397
- lifecycle: C(),
2398
- fingerprint: C(),
2399
- cronSchedule: C().nullable(),
2400
- watchedTables: x().nullable(),
2401
- nextRunAt: T().nullable(),
2402
- lastRunStatus: C().nullable(),
2403
- lastRunAt: T().nullable(),
2404
- lastRunDurationMs: _().nullable(),
2405
- lastRunRowsTouched: _().nullable(),
2406
- lastError: C().nullable(),
2407
- workflowRunId: C().nullable(),
2408
- createdAt: T().default("now"),
2409
- updatedAt: T().default("now").onUpdate("now")
2410
- }).index(["lifecycle"]).index(["nextRunAt"]), Fc = w("_voltro_migration_plans", {
2411
- id: E({ prefix: "plan" }),
2412
- fingerprint: C(),
2413
- liveFingerprint: C().nullable(),
2414
- operations: x(),
2415
- rollbackPlan: x().nullable(),
2416
- appliedBy: C(),
2417
- environment: C(),
2418
- source: C(),
2419
- onlineStrategy: C().nullable(),
2420
- durationMs: _(),
2421
- notes: C().nullable(),
2422
- squashedAt: T().nullable(),
2423
- appliedAt: T().default("now"),
2424
- createdAt: T().default("now"),
2425
- updatedAt: T().default("now").onUpdate("now")
2426
- }).index(["fingerprint"]).index(["environment"]), Ic = w("_voltro_idempotency", {
2427
- id: E({ prefix: "idem" }),
2428
- scope: C(),
2429
- key: C(),
2430
- status: C(),
2431
- response: x().nullable(),
2432
- createdAt: T().default("now")
2433
- }).unique(["scope", "key"]).index(["createdAt"]), Lc = w("_voltro_kv", {
2434
- id: E({ prefix: "kv" }),
2435
- key: C().unique(),
2436
- value: C().nullable(),
2437
- expiresAt: T().nullable(),
2438
- createdAt: T().default("now"),
2439
- updatedAt: T().default("now").onUpdate("now")
2440
- }).index(["expiresAt"]), Rc = w("_voltro_api_keys", {
2441
- id: E({ prefix: "apikey" }),
2442
- tenantId: C().nullable(),
2443
- name: C(),
2444
- hashedKey: C().maxLength(64).unique(),
2445
- keyPrefix: C(),
2446
- scopes: x().nullable(),
2447
- lastUsedAt: T().nullable(),
2448
- requestCount: _().default(0),
2449
- expiresAt: T().nullable(),
2450
- revokedAt: T().nullable(),
2451
- createdBy: C().nullable(),
2452
- onBehalfOf: C().nullable(),
2453
- metadata: x().nullable(),
2454
- createdAt: T().default("now")
2455
- }).index("byApiKeyTenant", ["tenantId"]), zc = w("_voltro_replica_observations", {
2456
- id: E({ prefix: "robs" }),
2457
- replicaId: C().maxLength(191),
2458
- startedAt: T(),
2459
- version: C().maxLength(64).nullable(),
2460
- kind: C().maxLength(64),
2461
- payload: C().nullable(),
2462
- reachableAt: C().maxLength(255).nullable(),
2463
- writtenAt: T().default("now").onUpdate("now")
2464
- }).unique(["replicaId", "kind"]).index(["kind"]), Bc = [
2465
- Nc,
2466
- Pc,
2467
- Fc
2468
- ], Vc = "_voltro_replace_in_progress", Hc = w(Vc, {
2469
- id: E({ prefix: "repl" }),
2470
- startedAt: T().default("now"),
2471
- kind: C().default("replace"),
2472
- tables: C().nullable(),
2473
- capture: C().nullable(),
2474
- via: C(),
2475
- staging: C().nullable(),
2476
- heartbeatAt: T().nullable(),
2487
+ }, Hc = (e) => typeof e == "object" && !!e && "__migration" in e && e.__migration === !0, Uc = T("_voltro_migrations", {
2488
+ id: D({ prefix: "mig" }),
2489
+ name: w(),
2490
+ hash: w(),
2491
+ status: w(),
2492
+ appliedAt: E().nullable(),
2493
+ durationMs: y().nullable(),
2494
+ errorMessage: w().nullable(),
2495
+ errorStack: w().nullable(),
2496
+ workflowRunId: w().nullable(),
2497
+ createdAt: E().default("now"),
2498
+ updatedAt: E().default("now").onUpdate("now")
2499
+ }).index(["status"]), Wc = T("_voltro_seeds", {
2500
+ id: D({ prefix: "seed" }),
2501
+ name: w(),
2502
+ lifecycle: w(),
2503
+ fingerprint: w(),
2504
+ cronSchedule: w().nullable(),
2505
+ watchedTables: S().nullable(),
2506
+ nextRunAt: E().nullable(),
2507
+ lastRunStatus: w().nullable(),
2508
+ lastRunAt: E().nullable(),
2509
+ lastRunDurationMs: y().nullable(),
2510
+ lastRunRowsTouched: y().nullable(),
2511
+ lastError: w().nullable(),
2512
+ workflowRunId: w().nullable(),
2513
+ createdAt: E().default("now"),
2514
+ updatedAt: E().default("now").onUpdate("now")
2515
+ }).index(["lifecycle"]).index(["nextRunAt"]), Gc = T("_voltro_migration_plans", {
2516
+ id: D({ prefix: "plan" }),
2517
+ fingerprint: w(),
2518
+ liveFingerprint: w().nullable(),
2519
+ operations: S(),
2520
+ rollbackPlan: S().nullable(),
2521
+ appliedBy: w(),
2522
+ environment: w(),
2523
+ source: w(),
2524
+ onlineStrategy: w().nullable(),
2525
+ durationMs: y(),
2526
+ notes: w().nullable(),
2527
+ squashedAt: E().nullable(),
2528
+ appliedAt: E().default("now"),
2529
+ createdAt: E().default("now"),
2530
+ updatedAt: E().default("now").onUpdate("now")
2531
+ }).index(["fingerprint"]).index(["environment"]), Kc = T("_voltro_idempotency", {
2532
+ id: D({ prefix: "idem" }),
2533
+ scope: w(),
2534
+ key: w(),
2535
+ status: w(),
2536
+ response: S().nullable(),
2537
+ createdAt: E().default("now")
2538
+ }).unique(["scope", "key"]).index(["createdAt"]), qc = T("_voltro_kv", {
2539
+ id: D({ prefix: "kv" }),
2540
+ key: w().unique(),
2541
+ value: w().nullable(),
2542
+ expiresAt: E().nullable(),
2543
+ createdAt: E().default("now"),
2544
+ updatedAt: E().default("now").onUpdate("now")
2545
+ }).index(["expiresAt"]), Jc = T("_voltro_api_keys", {
2546
+ id: D({ prefix: "apikey" }),
2547
+ tenantId: w().nullable(),
2548
+ name: w(),
2549
+ hashedKey: w().maxLength(64).unique(),
2550
+ keyPrefix: w(),
2551
+ scopes: S().nullable(),
2552
+ lastUsedAt: E().nullable(),
2553
+ requestCount: y().default(0),
2554
+ expiresAt: E().nullable(),
2555
+ revokedAt: E().nullable(),
2556
+ createdBy: w().nullable(),
2557
+ onBehalfOf: w().nullable(),
2558
+ metadata: S().nullable(),
2559
+ createdAt: E().default("now")
2560
+ }).index("byApiKeyTenant", ["tenantId"]), Yc = T("_voltro_replica_observations", {
2561
+ id: D({ prefix: "robs" }),
2562
+ replicaId: w().maxLength(191),
2563
+ startedAt: E(),
2564
+ version: w().maxLength(64).nullable(),
2565
+ kind: w().maxLength(64),
2566
+ payload: w().nullable(),
2567
+ reachableAt: w().maxLength(255).nullable(),
2568
+ writtenAt: E().default("now").onUpdate("now")
2569
+ }).unique(["replicaId", "kind"]).index(["kind"]), Xc = [
2570
+ Uc,
2571
+ Wc,
2572
+ Gc
2573
+ ], Zc = "_voltro_replace_in_progress", Qc = T(Zc, {
2574
+ id: D({ prefix: "repl" }),
2575
+ startedAt: E().default("now"),
2576
+ kind: w().default("replace"),
2577
+ tables: w().nullable(),
2578
+ capture: w().nullable(),
2579
+ via: w(),
2580
+ staging: w().nullable(),
2581
+ heartbeatAt: E().nullable(),
2477
2582
  resumable: p().nullable()
2478
- }), Uc = 30, Wc = (e, t) => {
2583
+ }), $c = 30, el = (e, t) => {
2479
2584
  let n = typeof t == "number" && Number.isFinite(t) && t > 0 ? t : 30, r = Number(e.VOLTRO_STAGING_STALE_MINUTES);
2480
2585
  return (Number.isFinite(r) && r > 0 ? r : n) * 6e4;
2481
- }, Gc = (e) => e == null || String(e).length === 0 ? [] : String(e).split(",").map((e) => e.trim()).filter((e) => e.length > 0), Kc = (e) => {
2586
+ }, tl = (e) => e == null || String(e).length === 0 ? [] : String(e).split(",").map((e) => e.trim()).filter((e) => e.length > 0), nl = (e) => {
2482
2587
  let t = e.filter((e) => e.kind !== "staging");
2483
2588
  if (t.length !== 0) return `refusing to start: a destructive data operation did not finish.
2484
2589
  ${t.map((e) => {
@@ -2493,7 +2598,7 @@ ${t.map((e) => {
2493
2598
 
2494
2599
  When the data is back, or you have decided the current state is correct, clear the marker:
2495
2600
  voltro data clear-replace-marker --yes`;
2496
- }, qc = (e, t, n) => {
2601
+ }, rl = (e, t, n) => {
2497
2602
  let r = e.filter((e) => e.kind === "staging");
2498
2603
  return {
2499
2604
  all: r,
@@ -2503,7 +2608,7 @@ ${t.map((e) => {
2503
2608
  return Number.isFinite(r) ? t - r >= n : !1;
2504
2609
  })
2505
2610
  };
2506
- }, Jc = (e, t) => {
2611
+ }, il = (e, t) => {
2507
2612
  if (e.all.length === 0) return;
2508
2613
  let n = new Set(e.droppable.map((e) => e.id));
2509
2614
  return `staged data-import leftovers:
@@ -2512,22 +2617,22 @@ ${e.all.map((e) => {
2512
2617
  return n.has(e.id) ? ` - ${a} — DROPPED: the run is not resumable and has been silent long enough that nothing is loading into them.` : e.resumable ? ` - ${a} — KEPT: the run was started \`--no-atomic\`, so these ARE its resume point. Re-run the same\n bundle to continue from them, or drop them with: voltro data clear-staging --yes` : ` - ${a} — KEPT: still beating, so an import is loading into them right now.`;
2513
2618
  }).join("\n")}\n The target of a staged \`replace\` is untouched until one short swap at the end, so none of this is
2514
2619
  a reason to refuse the boot — it is a reason to know the disk is holding a copy of a bundle.`;
2515
- }, Yc = "id", Xc = (e, t) => {
2516
- let n = S(e);
2620
+ }, al = "id", ol = (e, t) => {
2621
+ let n = C(e);
2517
2622
  if (n === void 0) return t;
2518
- let r = n.fields[Yc]?.idScheme;
2519
- if (r === void 0 || t[Yc] != null) return t;
2623
+ let r = n.fields[al]?.idScheme;
2624
+ if (r === void 0 || t[al] != null) return t;
2520
2625
  if (r.kind === "numeric") {
2521
- if (!(Yc in t)) return t;
2626
+ if (!(al in t)) return t;
2522
2627
  let e = { ...t };
2523
- return delete e[Yc], e;
2628
+ return delete e[al], e;
2524
2629
  }
2525
- let i = it(r, e);
2630
+ let i = rt(r, e);
2526
2631
  return i === null ? t : {
2527
2632
  ...t,
2528
- [Yc]: i
2633
+ [al]: i
2529
2634
  };
2530
- }, Zc = (e, t) => t.map((t) => Xc(e, t)), Qc = {
2635
+ }, sl = (e, t) => t.map((t) => ol(e, t)), cl = {
2531
2636
  postgres: { maxBindParameters: 65535 },
2532
2637
  mysql: { maxBindParameters: 65535 },
2533
2638
  mariadb: { maxBindParameters: 65535 },
@@ -2537,25 +2642,25 @@ ${e.all.map((e) => {
2537
2642
  },
2538
2643
  sqlite: { maxBindParameters: 32766 },
2539
2644
  turso: { maxBindParameters: 32766 }
2540
- }, $c = (e) => Qc[e], el = (e) => {
2645
+ }, ll = (e) => cl[e], ul = (e) => {
2541
2646
  let t = /* @__PURE__ */ new Set();
2542
2647
  for (let n of e) for (let e of Object.keys(n)) t.add(e);
2543
2648
  return t.size;
2544
- }, tl = (e, t) => {
2649
+ }, dl = (e, t) => {
2545
2650
  if (t === void 0 || e.length === 0) return [e];
2546
- let n = Math.max(1, el(e)), r = Math.floor(t.maxBindParameters / n), i = t.maxRowsPerStatement ?? Infinity, a = Math.max(1, Math.min(r, i));
2651
+ let n = Math.max(1, ul(e)), r = Math.floor(t.maxBindParameters / n), i = t.maxRowsPerStatement ?? Infinity, a = Math.max(1, Math.min(r, i));
2547
2652
  if (e.length <= a) return [e];
2548
2653
  let o = [];
2549
2654
  for (let t = 0; t < e.length; t += a) o.push(e.slice(t, t + a));
2550
2655
  return o;
2551
- }, nl = (e, t) => {
2656
+ }, fl = (e, t) => {
2552
2657
  let n = [], r = t;
2553
2658
  for (let [t, i] of Object.entries(e.fields)) {
2554
2659
  let e = i;
2555
2660
  e.nullable || e.hasDefault || e.idScheme !== void 0 || e.generatedAs !== void 0 || (r[t] === void 0 || r[t] === null) && n.push(t);
2556
2661
  }
2557
2662
  return n;
2558
- }, rl = (e, t, n) => {
2663
+ }, pl = (e, t, n) => {
2559
2664
  let r = n, i = new Set(e === void 0 ? [] : Object.entries(e.fields).filter(([, e]) => e.generatedAs !== void 0).map(([e]) => e)), a = [];
2560
2665
  for (let e of t) i.has(e) || (r[e] === void 0 ? a.push({
2561
2666
  column: e,
@@ -2565,28 +2670,29 @@ ${e.all.map((e) => {
2565
2670
  reason: "null"
2566
2671
  }));
2567
2672
  return a;
2568
- }, il = (e, t, n) => e.insert(t.tableName, n), al = (e, t, n, r) => e.upsert(t.tableName, n, {
2673
+ }, ml = (e, t, n) => e.insert(t.tableName, n), hl = (e, t, n, r) => e.upsert(t.tableName, n, {
2569
2674
  conflictColumns: r.conflictColumns,
2570
- ...r.update === void 0 ? {} : { update: r.update }
2571
- }), ol = (e, t, n, r) => e.updateMany(t.tableName, n, { where: r.where }), sl = 512, cl = (e) => {
2675
+ ...r.update === void 0 ? {} : { update: r.update },
2676
+ ...r.updateValues === void 0 ? {} : { updateValues: r.updateValues }
2677
+ }), gl = (e, t, n, r) => e.updateMany(t.tableName, n, { where: r.where }), _l = 512, vl = (e) => {
2572
2678
  e.setMaxListeners(512);
2573
- }, ll = (e, t, n) => ({
2679
+ }, yl = (e, t, n) => ({
2574
2680
  _tag: "PrimaryKeyConflictError",
2575
2681
  table: e,
2576
2682
  key: t,
2577
2683
  cause: n
2578
- }), ul = (e) => typeof e == "object" && !!e && e._tag === "PrimaryKeyConflictError", dl = {
2684
+ }), bl = (e) => typeof e == "object" && !!e && e._tag === "PrimaryKeyConflictError", xl = {
2579
2685
  postgres: 5432,
2580
2686
  mysql: 3306,
2581
2687
  mariadb: 3306,
2582
2688
  mssql: 1433
2583
- }, fl = /* @__PURE__ */ new Set([
2689
+ }, Sl = /* @__PURE__ */ new Set([
2584
2690
  "localhost",
2585
2691
  "127.0.0.1",
2586
2692
  "::1",
2587
2693
  "[::1]",
2588
2694
  "0.0.0.0"
2589
- ]), pl = (e) => {
2695
+ ]), Cl = (e) => {
2590
2696
  let t = e.host, n = e.port, r = e.database;
2591
2697
  if (e.url !== void 0 && e.url !== "") try {
2592
2698
  let i = new URL(e.url);
@@ -2595,29 +2701,29 @@ ${e.all.map((e) => {
2595
2701
  return;
2596
2702
  }
2597
2703
  if (t === void 0 || t === "" || r === void 0 || r === "") return;
2598
- let i = n ?? dl[(e.dialect ?? "").toLowerCase()];
2704
+ let i = n ?? xl[(e.dialect ?? "").toLowerCase()];
2599
2705
  if (i === void 0 || !Number.isFinite(i)) return;
2600
2706
  let a = t.toLowerCase();
2601
2707
  return {
2602
- host: fl.has(a) ? "localhost" : a,
2708
+ host: Sl.has(a) ? "localhost" : a,
2603
2709
  port: i,
2604
2710
  database: r.toLowerCase()
2605
2711
  };
2606
- }, ml = (e) => {
2607
- let t = pl(e);
2712
+ }, wl = (e) => {
2713
+ let t = Cl(e);
2608
2714
  if (t !== void 0) return qt("sha256").update(`${t.host}\u0000${t.port}\u0000${t.database}`).digest("hex").slice(0, 32);
2609
- }, hl = (e, t) => e === void 0 || t === void 0 ? "unknown" : e === t ? "same" : "different", gl = {
2715
+ }, Tl = (e, t) => e === void 0 || t === void 0 ? "unknown" : e === t ? "same" : "different", El = {
2610
2716
  app: 3,
2611
2717
  plugin: 2,
2612
2718
  framework: 1
2613
- }, _l = /* @__PURE__ */ new Map(), vl = [], yl = () => [...vl], bl = (e) => {
2719
+ }, Dl = /* @__PURE__ */ new Map(), Ol = [], kl = () => [...Ol], Al = (e) => {
2614
2720
  if (!e.table || !e.timeColumn) throw Error("registerRetention: table + timeColumn are required");
2615
2721
  if (!Number.isFinite(e.ttlMs) || e.ttlMs <= 0) throw Error(`registerRetention(${e.table}): ttlMs must be a positive number`);
2616
- let t = e.source ?? "app", n = _l.get(e.table);
2722
+ let t = e.source ?? "app", n = Dl.get(e.table);
2617
2723
  if (n !== void 0) {
2618
2724
  let r = n.source ?? "app", i = n.ttlMs !== e.ttlMs || n.where !== void 0 != (e.where !== void 0);
2619
- if (gl[t] < gl[r]) {
2620
- i && vl.push({
2725
+ if (El[t] < El[r]) {
2726
+ i && Ol.push({
2621
2727
  table: e.table,
2622
2728
  kept: {
2623
2729
  source: r,
@@ -2630,7 +2736,7 @@ ${e.all.map((e) => {
2630
2736
  });
2631
2737
  return;
2632
2738
  }
2633
- i && r !== t && vl.push({
2739
+ i && r !== t && Ol.push({
2634
2740
  table: e.table,
2635
2741
  kept: {
2636
2742
  source: t,
@@ -2642,13 +2748,13 @@ ${e.all.map((e) => {
2642
2748
  }
2643
2749
  });
2644
2750
  }
2645
- _l.set(e.table, {
2751
+ Dl.set(e.table, {
2646
2752
  ...e,
2647
2753
  source: t
2648
2754
  });
2649
- }, xl = () => [..._l.values()], Sl = () => {
2650
- _l.clear(), vl.length = 0;
2651
- }, Cl = async (e, t, n, r = 2e4) => {
2755
+ }, jl = () => [...Dl.values()], Ml = () => {
2756
+ Dl.clear(), Ol.length = 0;
2757
+ }, Nl = async (e, t, n, r = 2e4) => {
2652
2758
  let i = new Date(t - e.ttlMs), a = 0;
2653
2759
  try {
2654
2760
  for (;;) {
@@ -2656,45 +2762,45 @@ ${e.all.map((e) => {
2656
2762
  if (a += t, t < r) break;
2657
2763
  }
2658
2764
  } catch (t) {
2659
- throw k.runSync(A.increment(A.tagged(Tl, "table", e.table))), t;
2765
+ throw k.runSync(A.increment(A.tagged(Fl, "table", e.table))), t;
2660
2766
  }
2661
- return a > 0 && k.runSync(A.incrementBy(A.tagged(wl, "table", e.table), a)), a;
2662
- }, wl = A.counter("voltro_retention_swept_rows_total"), Tl = A.counter("voltro_retention_sweep_errors_total"), El = (e, t) => {
2767
+ return a > 0 && k.runSync(A.incrementBy(A.tagged(Pl, "table", e.table), a)), a;
2768
+ }, Pl = A.counter("voltro_retention_swept_rows_total"), Fl = A.counter("voltro_retention_sweep_errors_total"), Il = (e, t) => {
2663
2769
  let n = Number(e ?? String(t));
2664
2770
  return (Number.isFinite(n) && n > 0 ? n : t) * 36e5;
2665
- }, Dl = "_voltro_cdc_offsets", Ol = w(Dl, {
2666
- id: E({ prefix: "cdcoff" }),
2667
- replicaId: C(),
2668
- streamName: C(),
2669
- binlogFile: C(),
2670
- binlogPosition: C(),
2671
- updatedAt: T()
2672
- }).index(["replicaId"]), kl = w(Dl, {
2673
- id: E({ prefix: "cdcoff" }),
2674
- replicaId: C(),
2675
- streamName: C(),
2676
- ctVersion: C(),
2677
- updatedAt: T()
2678
- }).index(["replicaId"]), Al = "_voltro_data_transfers", jl = w(Al, {
2679
- id: E({ prefix: "dimp" }),
2680
- startedAt: T().default("now"),
2681
- finishedAt: T().nullable(),
2682
- direction: C().default("import"),
2683
- mode: C(),
2684
- via: C(),
2685
- bundle: C().nullable(),
2686
- sourceFingerprint: C().nullable(),
2687
- tablesWritten: _().default(0),
2688
- rowsWritten: _().default(0),
2689
- failure: C().nullable(),
2771
+ }, Ll = "_voltro_cdc_offsets", Rl = T(Ll, {
2772
+ id: D({ prefix: "cdcoff" }),
2773
+ replicaId: w(),
2774
+ streamName: w(),
2775
+ binlogFile: w(),
2776
+ binlogPosition: w(),
2777
+ updatedAt: E()
2778
+ }).index(["replicaId"]), zl = T(Ll, {
2779
+ id: D({ prefix: "cdcoff" }),
2780
+ replicaId: w(),
2781
+ streamName: w(),
2782
+ ctVersion: w(),
2783
+ updatedAt: E()
2784
+ }).index(["replicaId"]), Bl = "_voltro_data_transfers", Vl = T(Bl, {
2785
+ id: D({ prefix: "dimp" }),
2786
+ startedAt: E().default("now"),
2787
+ finishedAt: E().nullable(),
2788
+ direction: w().default("import"),
2789
+ mode: w(),
2790
+ via: w(),
2791
+ bundle: w().nullable(),
2792
+ sourceFingerprint: w().nullable(),
2793
+ tablesWritten: y().default(0),
2794
+ rowsWritten: y().default(0),
2795
+ failure: w().nullable(),
2690
2796
  staged: p().nullable()
2691
- }).renamedFrom("_voltro_data_imports").nonReactive(), Ml = (e) => {
2797
+ }).renamedFrom("_voltro_data_imports").nonReactive(), Hl = (e) => {
2692
2798
  let t = Number.isFinite(e.startedAt.getTime()) ? e.startedAt.toISOString() : "an unknown time", n = e.direction === "import" ? e.mode : `${e.direction} ${e.mode}`, r = e.failure === null ? e.finishedAt === null ? `${n} — started and never reported finishing` : e.direction === "backup" || e.direction === "restore" ? `${n} — finished${e.rowsWritten > 0 ? ` (${e.rowsWritten} blob(s))` : ""}` : `${n} — ${e.rowsWritten} row(s) across ${e.tablesWritten} table(s)` : `FAILED ${n} — ${e.failure}`, i = e.staged === null ? "" : e.staged ? " · staged (target untouched until the swap)" : " · NOT staged (target emptied first)";
2693
2799
  return `${t} · ${r} · via ${e.via}${i}` + (e.bundle === null ? "" : ` · from ${e.bundle}`) + (e.sourceFingerprint === null ? "" : ` · source schema ${e.sourceFingerprint}`);
2694
- }, Nl = 255, Pl = (e) => e == null ? "null" : typeof e == "string" || typeof e == "number" || typeof e == "boolean" ? JSON.stringify(e) : Array.isArray(e) ? `[${e.map(Pl).join(",")}]` : typeof e == "object" ? `{${Object.entries(e).filter(([, e]) => e !== void 0).sort(([e], [t]) => e < t ? -1 : +(e > t)).map(([e, t]) => `${JSON.stringify(e)}:${Pl(t)}`).join(",")}}` : JSON.stringify(String(e)), Fl = (e) => {
2800
+ }, Ul = 255, Wl = (e) => e == null ? "null" : typeof e == "string" || typeof e == "number" || typeof e == "boolean" ? JSON.stringify(e) : Array.isArray(e) ? `[${e.map(Wl).join(",")}]` : typeof e == "object" ? `{${Object.entries(e).filter(([, e]) => e !== void 0).sort(([e], [t]) => e < t ? -1 : +(e > t)).map(([e, t]) => `${JSON.stringify(e)}:${Wl(t)}`).join(",")}}` : JSON.stringify(String(e)), Gl = (e) => {
2695
2801
  if (e == null) return null;
2696
- let t = typeof e == "string" ? e : Pl(e);
2802
+ let t = typeof e == "string" ? e : Wl(e);
2697
2803
  return t.length > 255 ? t.slice(0, 255) : t;
2698
- }, Il = "postgres";
2804
+ }, Kl = "postgres";
2699
2805
  //#endregion
2700
- export { lt as AUTO_FILLED_COLUMNS, an as BOUND_ENCRYPTED_PREFIX, Qc as BULK_INSERT_LIMITS, Y as BranchNameInvalid, Gs as BranchTransitionInvalid, Dl as CDC_OFFSETS_TABLE, oo as CHANGE_CLAIM_TTL_ENV, sl as CHANGE_LISTENER_CEILING, Qe as ColumnBuilder, Al as DATA_TRANSFERS_TABLE, st as DEFAULT_ACQUIRE_TIMEOUT_MS, so as DEFAULT_CHANGE_CLAIM_TTL_HOURS, ls as DEFAULT_EAGER_FALLBACK_WARN_INTERVAL_MS, yt as DEFAULT_SOFT_DROP_RETENTION_DAYS, pr as DEFAULT_SUBJECT_GRAPH_DEPTH, rn as ENCRYPTED_PREFIX, Il as ENGINE, Ar as EagerCardinalityError, St as FILE_MIGRATION_PATTERN, at as FRAMEWORK_LIVE_TABLES, cn as FieldDecryptionError, jo as ID_COLUMN_MAX_LENGTH, Lt as INITIAL_VERSION, Ma as MATCHES_NO_ROWS, Tt as MAX_IDENTIFIER_LENGTH, bs as MSSQL_TRANSIENT_NUMBERS, vs as MYSQL_TRANSIENT_CODES, ao as OccurrenceCounter, ys as POSTGRES_TRANSIENT_STATES, Vc as REPLACE_IN_PROGRESS_TABLE, Nl as SCOPE_KEY_MAX_LENGTH, se as SELF_REFERENCE_TARGET, xs as SQLITE_TRANSIENT_CODES, Uc as STAGING_STALE_MINUTES, pt as STAGING_TABLE_PREFIX, Xt as SqlClient, Ss as TURSO_TRANSIENT_MESSAGE, Ns as TableStreamError, Wr as TenantNamespaceInvalid, Ur as TenantNamespaceUnresolved, uc as TenantRegionUnavailable, lc as TenantResidencyUnresolved, Ds as VOLTRO_EXPIRES_MIXIN_ID, ks as VOLTRO_LOCAL_FIRST_MIXIN_ID, Pt as VersionConflict, At as WARN_IDENTIFIER_LENGTH, Rc as _voltroApiKeysTable, Ol as _voltroCdcOffsetsTable, jl as _voltroDataTransfersTable, Ic as _voltroIdempotencyTable, Lc as _voltroKvTable, Fc as _voltroMigrationPlansTable, Nc as _voltroMigrationsTable, kl as _voltroMssqlCdcOffsetsTable, Hc as _voltroReplaceInProgressTable, zc as _voltroReplicaObservationsTable, Pc as _voltroSeedsTable, va as actorsTable, ic as admitBranch, Je as agedSoftDropSnapshots, be as allEnumRenames, ur as allRegisteredRelations, re as allRegisteredTables, Ia as and, ce as array, ka as arrayContains, ja as arrayHas, Aa as arrayOverlaps, Mr as attachEagerLoads, po as attributionFields, _o as attributionKey, wc as auditAllTableIndexes, Cc as auditTableIndexes, Et as avg, ye as avgOver, Eo as beginLocalWrite, fe as bigint, vc as bindResidentStore, p as boolean, Hs as branchNamespaceName, $c as bulkInsertLimitsFor, ne as bytes, xn as causeBranches, $a as changeDelete, no as changeDigest, Za as changeInsert, eo as changeSoftDelete, Qa as changeUpdate, tl as chunkRowsForInsert, bo as claimPendingAttribution, jn as classifyConstraintViolation, d as clearEnumRenames, ko as clearPendingAttribution, fr as clearRelationsRegistry, mc as clearResidencyConfig, Sl as clearRetentions, Oe as clearTableRegistry, Ro as clearWriteRecorders, W as coercePredicateForSqlite, Qr as coercePredicateValue, $r as coercePredicateValues, ua as coerceValueForSqlite, Ja as collectSubqueries, u as column, Bn as columnSchema, el as columnsPerRow, pi as compileEagerJson, L as compilePredicate, ei as compileRawFragment, fi as compileSelect, ro as composeChangeKey, Rs as computeEmbedding, ml as connectionIdentity, Da as contains, c as count, le as countDistinct, oe as crdtDoc, ge as crdtManagedColumns, Mt as crdtManagedColumnsOf, a as crdtText, fo as currentWriteAttribution, $e as databaseHandle, we as date, ee as dbEnum, rs as dbMetricTagCacheSizeForTests, os as dbOperationsInFlight, Se as decimal, l as declareEnumRename, pn as decodeFieldValue, Dr as decodeRowsFromSchema, yn as decryptFieldsOnRead, jc as defineMigration, Ct as defineMixin, ut as defineSeed, n as denseRank, br as deriveSubjectGraph, dt as deriveTypeIdPrefix, Po as derivedRowId, Fo as derivedRowIdLength, Ne as describeAgedSoftDropSnapshots, Pn as describeDriverError, Fn as describeRowBindings, Ml as describeTransferRun, nn as deserializeArraysOnRead, Ie as drainIdentifierWarnings, Ee as dropped, dn as encodeFieldValue, kr as encodeRowForSchema, vn as encryptFieldsForWrite, gn as encryptedColumnsOf, Do as endLocalWrite, tc as enforceBranchLimits, De as ensureTableRegistered, ya as eq, ti as escapeLike, qa as evaluatePredicate, Ze as except, Ua as exists, Os as expires, Xa as externalChangeEvent, wn as extractDbCause, on as fieldBinding, rt as fireSchemaChangeSeeds, Ke as fireTenantCreateSeeds, kc as formatIndexAuditIssue, xr as formatSubjectGraph, Bc as frameworkTables, it as generateId, Ge as generateSnowflake, h as geography, ae as geometry, ue as getEnumRenames, lr as getRelation, cr as getRelations, pc as getResidencyConfig, S as getTable, xa as gt, Sa as gte, Hr as hasEagerLoads, Ls as hybridSearch, E as id, Ta as inSet, Va as inSubquery, $n as inferForeignKey, il as insertRow, _ as integer, Kc as interruptedReplaceRefusal, y as intersect, ke as interval, sn as isBoundCiphertext, Us as isBranchNamespace, Jn as isEmptyRelationsSpec, un as isEncrypted, ln as isFieldDecryptionError, Re as isFileMigration, Mn as isForeignKeyViolation, ct as isFrameworkOwnedLiveTable, js as isLocalFirst, Mc as isMigrationDefinition, ht as isMysqlFamily, Ys as isNeonConnection, Pa as isNotNull, Na as isNull, ul as isPrimaryKeyConflictError, Nn as isQueryTimeout, mn as isRawEncoding, gc as isRegionServable, Yn as isRelationsSpec, We as isSeedDefinition, gt as isSoftDropSnapshotName, Xe as isSqliteFamily, Le as isStagingTableName, pe as isTableReactive, Ts as isTransientContention, Fe as isView, x as json, za as jsonField, vt as jsonIndex, b as lag, de as lead, yl as listRetentionConflicts, xl as listRetentions, As as localFirst, Ms as localFirstTables, Ca as lt, wa as lte, fs as makeEagerFallbackReporter, cc as makeNamespaceBranchExecutor, Zn as many, Qn as manyToMany, Ae as materializeFields, f as max, He as migration, te as min, rl as missingConflictColumns, nl as missingRequiredColumns, ze as mixin, ba as neq, Ks as nextBranchState, pl as normaliseTarget, Ra as not, Wa as notExists, Ea as notInSet, Ha as notInSubquery, me as numeric, cs as observeDbOp, co as occurrenceWindowMs, Xn as one, jr as oneCardinalityMessage, La as or, v as orderClausesOf, he as paginateBy, jt as paginateById, io as parseChangeKey, Ao as pendingAttributionCount, $s as planBranch, qs as planBranchProvision, Js as planBranchTeardown, ec as planBranchTeardownFor, Zs as planNeonBranchProvision, Qs as planNeonBranchTeardown, Nt as planVersionedUpdate, et as pluginRef, r as pluginRefSpecOf, ll as primaryKeyConflictError, nc as provisionBranch, yc as provisionResidentTenant, Yr as qualifyTable, i as queryFor, Ot as queryForView, Pe as quoteIdent, cl as raiseChangeListenerCeiling, Ce as rank, t as raw, Be as readableByColumns, bt as real, ss as recordDbOp, Uo as recordsTable, ot as reference, Rn as refuseWrite, ma as registerCoreTables, sr as registerDiscoveredRelations, yo as registerPendingAttribution, or as registerRelations, bl as registerRetention, e as registerTable, Io as registerWriteRecorder, qn as relations, ga as requireActors, Ve as requireTable, _a as requireTenants, ns as resetDbMetricTagCacheForTests, Me as resetSnowflake, _c as residentPlacement, Qt as resolveActorSnapshot, Xs as resolveBranchMechanism, ds as resolveEagerFallbackWarnIntervalMs, Oo as resolveEchoAttribution, g as resolveFullTextIndex, qe as resolveIdScheme, Ue as resolveMixinGraph, hc as resolveTenantHome, Jr as resolveTenantNamespace, El as retentionTtlMsFromEnv, xe as rowNumber, Vn as rowSchema, gs as runRetryingTransaction, _s as runStoreTransaction, uo as runWithWriteAttribution, Wo as runWriteRecorders, hl as sameDatabase, qr as sanitizeIdentifierFragment, Fl as scopeKeyOf, mt as selfReference, tn as serializeArraysForWrite, Ye as serverOnlyColumns, fc as setResidencyConfig, je as setSchemaChangeSeedHook, wt as setTenantCreateSeedHook, ps as settleTransactionExit, It as settleVersionedUpdate, tt as softDropSnapshotStamp, Fa as spatialPredicate, Jc as stagingLeftoverReport, qc as stagingLeftovers, Gc as stagingNamesOf, Wc as stagingStaleAfterMs, Xc as stampGeneratedId, Zc as stampGeneratedIds, Oa as startsWith, zn as storeRefusalOf, Is as streamTable, Te as sum, m as sumOver, Bo as suspendWriteRecorders, Vo as suspendWriteRecordersEffect, Cl as sweepRetention, w as table, rc as teardownBranch, C as text, T as timestamp, zt as timestampMs, Ft as timestampMsOrNull, ie as union, ft as unionAll, xt as unregisterTable, Lo as unregisterWriteRecorder, ol as updateManyRow, al as upsertRow, kt as validateColumnName, ve as validateIndexName, dr as validateRegisteredRelations, rr as validateRelationConfig, s as validateTableName, Dt as validateTypeIdPrefix, _t as vector, nt as vectorDistanceToOpclass, zs as vectorEmbedding, Rt as versionColumnOf, _e as view, o as viewSql, Ya as walkLeaves, Tn as wireSafeCause, mo as withCapturedAttribution, Ho as writeRecordersSuspended };
2806
+ export { ct as AUTO_FILLED_COLUMNS, an as BOUND_ENCRYPTED_PREFIX, cl as BULK_INSERT_LIMITS, Y as BranchNameInvalid, tc as BranchTransitionInvalid, Ll as CDC_OFFSETS_TABLE, _o as CHANGE_CLAIM_TTL_ENV, _l as CHANGE_LISTENER_CEILING, Ze as ColumnBuilder, Bl as DATA_TRANSFERS_TABLE, ot as DEFAULT_ACQUIRE_TIMEOUT_MS, vo as DEFAULT_CHANGE_CLAIM_TTL_HOURS, ys as DEFAULT_EAGER_FALLBACK_WARN_INTERVAL_MS, vt as DEFAULT_SOFT_DROP_RETENTION_DAYS, pr as DEFAULT_SUBJECT_GRAPH_DEPTH, rn as ENCRYPTED_PREFIX, Kl as ENGINE, Br as EagerCardinalityError, xt as FILE_MIGRATION_PATTERN, it as FRAMEWORK_LIVE_TABLES, cn as FieldDecryptionError, Vo as ID_COLUMN_MAX_LENGTH, It as INITIAL_VERSION, Ha as MATCHES_NO_ROWS, wt as MAX_IDENTIFIER_LENGTH, As as MSSQL_TRANSIENT_NUMBERS, Os as MYSQL_TRANSIENT_CODES, go as OccurrenceCounter, ks as POSTGRES_TRANSIENT_STATES, Zc as REPLACE_IN_PROGRESS_TABLE, Ul as SCOPE_KEY_MAX_LENGTH, ae as SELF_REFERENCE_TARGET, js as SQLITE_TRANSIENT_CODES, $c as STAGING_STALE_MINUTES, ft as STAGING_TABLE_PREFIX, Xt as SqlClient, Ms as TURSO_TRANSIENT_MESSAGE, Us as TableStreamError, ei as TenantNamespaceInvalid, $r as TenantNamespaceUnresolved, bc as TenantRegionUnavailable, yc as TenantResidencyUnresolved, Ls as VOLTRO_EXPIRES_MIXIN_ID, zs as VOLTRO_LOCAL_FIRST_MIXIN_ID, Nt as VersionConflict, kt as WARN_IDENTIFIER_LENGTH, Jc as _voltroApiKeysTable, Rl as _voltroCdcOffsetsTable, Vl as _voltroDataTransfersTable, Kc as _voltroIdempotencyTable, qc as _voltroKvTable, Gc as _voltroMigrationPlansTable, Uc as _voltroMigrationsTable, zl as _voltroMssqlCdcOffsetsTable, Qc as _voltroReplaceInProgressTable, Yc as _voltroReplicaObservationsTable, Wc as _voltroSeedsTable, Oa as actorsTable, mc as admitBranch, qe as agedSoftDropSnapshots, ye as allEnumRenames, ur as allRegisteredRelations, te as allRegisteredTables, Ka as and, Rr as applyJsonPatch, se as array, za as arrayContains, Va as arrayHas, Ba as arrayOverlaps, Hr as attachEagerLoads, Co as attributionFields, Do as attributionKey, Pc as auditAllTableIndexes, Nc as auditTableIndexes, Tt as avg, ve as avgOver, Io as beginLocalWrite, de as bigint, Oc as bindResidentStore, p as boolean, Qs as branchNamespaceName, ll as bulkInsertLimitsFor, ee as bytes, xn as causeBranches, lo as changeDelete, po as changeDigest, so as changeInsert, uo as changeSoftDelete, co as changeUpdate, dl as chunkRowsForInsert, Ao as claimPendingAttribution, jn as classifyConstraintViolation, d as clearEnumRenames, zo as clearPendingAttribution, fr as clearRelationsRegistry, wc as clearResidencyConfig, Ml as clearRetentions, De as clearTableRegistry, Jo as clearWriteRecorders, W as coercePredicateForSqlite, ci as coercePredicateValue, li as coercePredicateValues, ba as coerceValueForSqlite, io as collectSubqueries, u as column, Bn as columnSchema, ul as columnsPerRow, Ci as compileEagerJson, zr as compileJsonPatch, L as compilePredicate, ui as compileRawFragment, Si as compileSelect, mo as composeChangeKey, Js as computeEmbedding, wl as connectionIdentity, La as contains, c as count, ce as countDistinct, ie as crdtDoc, he as crdtManagedColumns, jt as crdtManagedColumnsOf, a as crdtText, So as currentWriteAttribution, Qe as databaseHandle, Ce as date, _ as dbEnum, ps as dbMetricTagCacheSizeForTests, gs as dbOperationsInFlight, xe as decimal, l as declareEnumRename, pn as decodeFieldValue, Dr as decodeRowsFromSchema, yn as decryptFieldsOnRead, Vc as defineMigration, St as defineMixin, lt as defineSeed, n as denseRank, br as deriveSubjectGraph, ut as deriveTypeIdPrefix, Wo as derivedRowId, Go as derivedRowIdLength, Me as describeAgedSoftDropSnapshots, Pn as describeDriverError, Fn as describeRowBindings, Hl as describeTransferRun, nn as deserializeArraysOnRead, Fe as drainIdentifierWarnings, Te as dropped, dn as encodeFieldValue, kr as encodeRowForSchema, vn as encryptFieldsForWrite, gn as encryptedColumnsOf, Lo as endLocalWrite, dc as enforceBranchLimits, Ee as ensureTableRegistered, ka as eq, di as escapeLike, ro as evaluatePredicate, Xe as except, $a as exists, Rs as expires, oo as externalChangeEvent, wn as extractDbCause, on as fieldBinding, nt as fireSchemaChangeSeeds, Ge as fireTenantCreateSeeds, zc as formatIndexAuditIssue, xr as formatSubjectGraph, Xc as frameworkTables, rt as generateId, We as generateSnowflake, h as geography, re as geometry, le as getEnumRenames, lr as getRelation, cr as getRelations, Cc as getResidencyConfig, C as getTable, ja as gt, Ma as gte, Qr as hasEagerLoads, qs as hybridSearch, D as id, Fa as inSet, Za as inSubquery, $n as inferForeignKey, ml as insertRow, y as integer, nl as interruptedReplaceRefusal, x as intersect, Oe as interval, sn as isBoundCiphertext, $s as isBranchNamespace, Pr as isCompositeRowKey, Jn as isEmptyRelationsSpec, un as isEncrypted, ln as isFieldDecryptionError, Le as isFileMigration, Mn as isForeignKeyViolation, st as isFrameworkOwnedLiveTable, Vs as isLocalFirst, Hc as isMigrationDefinition, mt as isMysqlFamily, ac as isNeonConnection, Wa as isNotNull, Ua as isNull, bl as isPrimaryKeyConflictError, Nn as isQueryTimeout, mn as isRawEncoding, Ec as isRegionServable, Yn as isRelationsSpec, Ue as isSeedDefinition, ht as isSoftDropSnapshotName, Ye as isSqliteFamily, Ie as isStagingTableName, fe as isTableReactive, Fs as isTransientContention, Pe as isView, S as json, Ya as jsonField, _t as jsonIndex, Fr as jsonPatchAssignments, oe as lag, ue as lead, kl as listRetentionConflicts, jl as listRetentions, Bs as localFirst, Hs as localFirstTables, Na as lt, Pa as lte, Ss as makeEagerFallbackReporter, vc as makeNamespaceBranchExecutor, Zn as many, Qn as manyToMany, ke as materializeFields, f as max, Ve as migration, v as min, pl as missingConflictColumns, fl as missingRequiredColumns, Re as mixin, Aa as neq, nc as nextBranchState, Cl as normaliseTarget, Lr as normalizeJsonPatchValue, Ja as not, eo as notExists, Ia as notInSet, Qa as notInSubquery, pe as numeric, vs as observeDbOp, yo as occurrenceWindowMs, Xn as one, Vr as oneCardinalityMessage, qa as or, b as orderClausesOf, me as paginateBy, At as paginateById, ho as parseChangeKey, Bo as pendingAttributionCount, lc as planBranch, rc as planBranchProvision, ic as planBranchTeardown, uc as planBranchTeardownFor, sc as planNeonBranchProvision, cc as planNeonBranchTeardown, Mt as planVersionedUpdate, $e as pluginRef, r as pluginRefSpecOf, yl as primaryKeyConflictError, fc as provisionBranch, kc as provisionResidentTenant, ai as qualifyTable, i as queryFor, Dt as queryForView, Ne as quoteIdent, vl as raiseChangeListenerCeiling, Se as rank, t as raw, ze as readableByColumns, yt as real, _s as recordDbOp, $o as recordsTable, at as reference, Rn as refuseWrite, wa as registerCoreTables, sr as registerDiscoveredRelations, ko as registerPendingAttribution, or as registerRelations, Al as registerRetention, e as registerTable, Ko as registerWriteRecorder, qn as relations, Ea as requireActors, Be as requireTable, Da as requireTenants, fs as resetDbMetricTagCacheForTests, je as resetSnowflake, Dc as residentPlacement, Qt as resolveActorSnapshot, oc as resolveBranchMechanism, xs as resolveEagerFallbackWarnIntervalMs, Ro as resolveEchoAttribution, g as resolveFullTextIndex, Ke as resolveIdScheme, He as resolveMixinGraph, Tc as resolveTenantHome, ii as resolveTenantNamespace, Il as retentionTtlMsFromEnv, Mr as rowKeyColumns, Nr as rowKeyIdentity, be as rowNumber, Vn as rowSchema, Es as runRetryingTransaction, Ds as runStoreTransaction, xo as runWithWriteAttribution, es as runWriteRecorders, Tl as sameDatabase, ri as sanitizeIdentifierFragment, Gl as scopeKeyOf, pt as selfReference, tn as serializeArraysForWrite, Je as serverOnlyColumns, Sc as setResidencyConfig, Ae as setSchemaChangeSeedHook, Ct as setTenantCreateSeedHook, Cs as settleTransactionExit, Ft as settleVersionedUpdate, et as softDropSnapshotStamp, Ga as spatialPredicate, il as stagingLeftoverReport, rl as stagingLeftovers, tl as stagingNamesOf, el as stagingStaleAfterMs, ol as stampGeneratedId, sl as stampGeneratedIds, Ra as startsWith, zn as storeRefusalOf, Ks as streamTable, we as sum, m as sumOver, Xo as suspendWriteRecorders, Zo as suspendWriteRecordersEffect, Nl as sweepRetention, T as table, pc as teardownBranch, w as text, E as timestamp, Rt as timestampMs, Pt as timestampMsOrNull, ne as union, dt as unionAll, bt as unregisterTable, qo as unregisterWriteRecorder, gl as updateManyRow, hl as upsertRow, jr as upsertUpdatePatch, Ar as upsertUpdateValues, Ot as validateColumnName, _e as validateIndexName, dr as validateRegisteredRelations, rr as validateRelationConfig, s as validateTableName, Et as validateTypeIdPrefix, gt as vector, tt as vectorDistanceToOpclass, Ys as vectorEmbedding, Lt as versionColumnOf, ge as view, o as viewSql, ao as walkLeaves, Tn as wireSafeCause, wo as withCapturedAttribution, Qo as writeRecordersSuspended };