@authhero/cloudflare-adapter 2.36.1 → 2.37.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.
@@ -784,26 +784,26 @@ function me(e) {
784
784
  }
785
785
  //#endregion
786
786
  //#region src/analytics-engine-logs/stats.ts
787
- var N = ["s"], P = ["pwd_leak"];
788
- function F(e) {
787
+ var N = ["s"], he = ["pwd_leak"];
788
+ function P(e) {
789
789
  return `${e.slice(0, 4)}-${e.slice(4, 6)}-${e.slice(6, 8)}`;
790
790
  }
791
- function I(e) {
791
+ function F(e) {
792
792
  return e.toISOString().split("T")[0];
793
793
  }
794
- function L(e) {
794
+ function I(e) {
795
795
  let t = e.dataset || "authhero_logs";
796
796
  return {
797
797
  async getDaily(n, r = {}) {
798
798
  let { from: i, to: a } = r, o = /* @__PURE__ */ new Date(), s = new Date(o);
799
799
  s.setDate(s.getDate() - 30);
800
- let c = i ? F(i) : I(s), l = a ? F(a) : I(o), u = (/* @__PURE__ */ new Date(`${c}T00:00:00Z`)).getTime(), d = (/* @__PURE__ */ new Date(`${l}T23:59:59.999Z`)).getTime();
800
+ let c = i ? P(i) : F(s), l = a ? P(a) : F(o), u = (/* @__PURE__ */ new Date(`${c}T00:00:00Z`)).getTime(), d = (/* @__PURE__ */ new Date(`${l}T23:59:59.999Z`)).getTime();
801
801
  return (await O(e, `
802
802
  SELECT
803
803
  toDate(toDateTime(double2 / 1000)) AS date,
804
804
  SUM(CASE WHEN blob3 IN (${N.map((e) => k(e)).join(", ")}) THEN 1 ELSE 0 END) AS logins,
805
805
  SUM(CASE WHEN blob3 = 'ss' THEN 1 ELSE 0 END) AS signups,
806
- SUM(CASE WHEN blob3 IN (${P.map((e) => k(e)).join(", ")}) THEN 1 ELSE 0 END) AS leaked_passwords,
806
+ SUM(CASE WHEN blob3 IN (${he.map((e) => k(e)).join(", ")}) THEN 1 ELSE 0 END) AS leaked_passwords,
807
807
  MIN(double2) AS first_event,
808
808
  MAX(double2) AS last_event
809
809
  FROM "${t}"
@@ -839,7 +839,7 @@ function L(e) {
839
839
  }
840
840
  //#endregion
841
841
  //#region src/analytics-engine-logs/analytics.ts
842
- var R = {
842
+ var L = {
843
843
  "active-users": ["s", "seacft"],
844
844
  logins: [
845
845
  "s",
@@ -849,17 +849,17 @@ var R = {
849
849
  signups: ["ss", "fs"],
850
850
  "refresh-tokens": ["seacft", "fertft"],
851
851
  sessions: ["slo"]
852
- }, z = {
852
+ }, R = {
853
853
  connection: "blob9",
854
854
  client_id: "blob11",
855
855
  user_type: "blob16",
856
856
  event: "blob3"
857
- }, he = {
857
+ }, ge = {
858
858
  connection: "blob9",
859
859
  client_id: "blob11",
860
860
  user_type: "blob16",
861
861
  user_id: "blob7"
862
- }, ge = {
862
+ }, _e = {
863
863
  "active-users": {
864
864
  expr: "count(DISTINCT blob7)",
865
865
  alias: "active_users",
@@ -886,7 +886,7 @@ var R = {
886
886
  type: "UInt64"
887
887
  }
888
888
  };
889
- function _e(e, t) {
889
+ function ve(e, t) {
890
890
  let n = `toDateTime(intDiv(double2, 1000), ${k(t)})`;
891
891
  switch (e) {
892
892
  case "hour": return `toStartOfHour(${n})`;
@@ -895,17 +895,17 @@ function _e(e, t) {
895
895
  default: return `toStartOfDay(${n})`;
896
896
  }
897
897
  }
898
- function ve(e) {
898
+ function ye(e) {
899
899
  return e === "hour" ? "DateTime" : "Date";
900
900
  }
901
- function ye(e, t, n) {
901
+ function be(e, t, n) {
902
902
  let r = new Date(e.from).getTime(), i = new Date(e.to).getTime(), a = n.map((e) => k(e)).join(", "), o = [
903
903
  `index1 = ${k(t)}`,
904
904
  `double2 >= ${r}`,
905
905
  `double2 < ${i}`,
906
906
  `blob3 IN (${a})`
907
907
  ];
908
- for (let [t, n] of Object.entries(he)) {
908
+ for (let [t, n] of Object.entries(ge)) {
909
909
  let r = e.filters[t];
910
910
  if (r && r.length > 0) {
911
911
  let e = r.map((e) => k(e)).join(", ");
@@ -914,25 +914,25 @@ function ye(e, t, n) {
914
914
  }
915
915
  return o.join(" AND ");
916
916
  }
917
- function be(e, t, n) {
917
+ function xe(e, t, n) {
918
918
  if (e.order_by) {
919
919
  let t = e.order_by.startsWith("-");
920
920
  return `${A(t ? e.order_by.slice(1) : e.order_by)} ${t ? "DESC" : "ASC"}`;
921
921
  }
922
922
  return t.length > 0 && t[0] === "time" ? `${A("time")} ASC` : `${A(n)} DESC`;
923
923
  }
924
- function B(e) {
924
+ function z(e) {
925
925
  let t = e.dataset || "authhero_logs";
926
926
  return { async query(n, r, i) {
927
- let a = R[r], o = ge[r], s = [], c = [];
927
+ let a = L[r], o = _e[r], s = [], c = [];
928
928
  for (let e of i.group_by) if (e === "time") {
929
- let e = _e(i.interval, i.tz);
929
+ let e = ve(i.interval, i.tz);
930
930
  s.push(`${e} AS ${A("time")}`), c.push({
931
931
  name: "time",
932
- type: ve(i.interval)
932
+ type: ye(i.interval)
933
933
  });
934
934
  } else {
935
- let t = z[e];
935
+ let t = R[e];
936
936
  s.push(`${t} AS ${A(e)}`), c.push({
937
937
  name: e,
938
938
  type: "String"
@@ -942,10 +942,10 @@ function B(e) {
942
942
  name: o.alias,
943
943
  type: o.type
944
944
  });
945
- let l = [...s, `${o.expr} AS ${A(o.alias)}`], u = i.group_by.length ? `GROUP BY ${i.group_by.map((e) => A(e === "time" ? "time" : e)).join(", ")}` : "", d = be(i, i.group_by.map((e) => e === "time" ? "time" : e), o.alias), f = `
945
+ let l = [...s, `${o.expr} AS ${A(o.alias)}`], u = i.group_by.length ? `GROUP BY ${i.group_by.map((e) => A(e === "time" ? "time" : e)).join(", ")}` : "", d = xe(i, i.group_by.map((e) => e === "time" ? "time" : e), o.alias), f = `
946
946
  SELECT ${l.join(", ")}
947
947
  FROM ${A(t)}
948
- WHERE ${ye(i, n, a)}
948
+ WHERE ${be(i, n, a)}
949
949
  ${u}
950
950
  ORDER BY ${d}
951
951
  LIMIT ${Math.max(0, i.limit)} OFFSET ${Math.max(0, i.offset)}
@@ -982,7 +982,7 @@ function B(e) {
982
982
  }
983
983
  //#endregion
984
984
  //#region src/analytics-engine-logs/index.ts
985
- function V(e) {
985
+ function B(e) {
986
986
  return e.analyticsEngineBinding || console.warn("Analytics Engine: No binding configured. Logs will not be written to Analytics Engine."), (!e.accountId || !e.apiToken) && console.warn("Analytics Engine: accountId and apiToken are required for querying logs via SQL API."), {
987
987
  create: ce(e),
988
988
  list: me(e),
@@ -991,38 +991,38 @@ function V(e) {
991
991
  }
992
992
  //#endregion
993
993
  //#region src/analytics-engine-action-executions/actionExecutions.ts
994
- var xe = "authhero_action_executions", Se = 1024, Ce = "[truncated]";
995
- function H(e) {
994
+ var Se = "authhero_action_executions", Ce = 1024, we = "[truncated]";
995
+ function V(e) {
996
996
  if (!(typeof e != "string" || e.length === 0)) try {
997
997
  return JSON.parse(e);
998
998
  } catch {
999
999
  return;
1000
1000
  }
1001
1001
  }
1002
- function we(t) {
1002
+ function Te(t) {
1003
1003
  let n = e.safeParse(t);
1004
1004
  return n.success ? n.data : "unspecified";
1005
1005
  }
1006
- function U(e, t = Se) {
1007
- return e.length <= t ? e : `${e.substring(0, t - 11)}${Ce}`;
1006
+ function H(e, t = Ce) {
1007
+ return e.length <= t ? e : `${e.substring(0, t - 11)}${we}`;
1008
1008
  }
1009
- function W(e) {
1009
+ function U(e) {
1010
1010
  return e == null ? "" : JSON.stringify(e);
1011
1011
  }
1012
- function Te(e) {
1012
+ function Ee(e) {
1013
1013
  let t = typeof e.blob6 == "string" && e.blob6.length > 0 ? e.blob6 : typeof e.double1 == "number" ? new Date(e.double1).toISOString() : "", n = typeof e.blob7 == "string" && e.blob7.length > 0 ? e.blob7 : t;
1014
1014
  return {
1015
1015
  id: typeof e.blob1 == "string" ? e.blob1 : "",
1016
1016
  tenant_id: typeof e.index1 == "string" ? e.index1 : "",
1017
1017
  trigger_id: typeof e.blob2 == "string" ? e.blob2 : "",
1018
- status: we(e.blob3),
1019
- results: H(e.blob4) ?? [],
1020
- logs: H(e.blob5),
1018
+ status: Te(e.blob3),
1019
+ results: V(e.blob4) ?? [],
1020
+ logs: V(e.blob5),
1021
1021
  created_at: t,
1022
1022
  updated_at: n
1023
1023
  };
1024
1024
  }
1025
- function Ee(e) {
1025
+ function De(e) {
1026
1026
  return async (t, n) => {
1027
1027
  let r = Date.now(), i = new Date(r).toISOString(), a = {
1028
1028
  id: n.id,
@@ -1034,10 +1034,10 @@ function Ee(e) {
1034
1034
  created_at: i,
1035
1035
  updated_at: i
1036
1036
  };
1037
- return De(e, t, a, r), a;
1037
+ return Oe(e, t, a, r), a;
1038
1038
  };
1039
1039
  }
1040
- function De(e, t, n, r) {
1040
+ function Oe(e, t, n, r) {
1041
1041
  if (!e.analyticsEngineBinding) {
1042
1042
  console.error("Analytics Engine action_executions binding not configured; skipping write");
1043
1043
  return;
@@ -1045,13 +1045,13 @@ function De(e, t, n, r) {
1045
1045
  try {
1046
1046
  e.analyticsEngineBinding.writeDataPoint({
1047
1047
  blobs: [
1048
- U(n.id),
1049
- U(n.trigger_id),
1050
- U(n.status),
1051
- U(W(n.results)),
1052
- U(W(n.logs)),
1053
- U(n.created_at),
1054
- U(n.updated_at)
1048
+ H(n.id),
1049
+ H(n.trigger_id),
1050
+ H(n.status),
1051
+ H(U(n.results)),
1052
+ H(U(n.logs)),
1053
+ H(n.created_at),
1054
+ H(n.updated_at)
1055
1055
  ],
1056
1056
  doubles: [r],
1057
1057
  indexes: [t.substring(0, 96)]
@@ -1060,29 +1060,29 @@ function De(e, t, n, r) {
1060
1060
  console.error("Failed to write action_execution to Analytics Engine:", e);
1061
1061
  }
1062
1062
  }
1063
- function Oe(e) {
1063
+ function ke(e) {
1064
1064
  return async (t, n) => {
1065
1065
  let r = await O(e, `
1066
1066
  SELECT *
1067
- FROM ${A(e.dataset || xe)}
1067
+ FROM ${A(e.dataset || Se)}
1068
1068
  WHERE index1 = ${k(t)}
1069
1069
  AND blob1 = ${k(n)}
1070
1070
  LIMIT 1
1071
1071
  `);
1072
- return r.length === 0 || !r[0] ? null : Te(r[0]);
1072
+ return r.length === 0 || !r[0] ? null : Ee(r[0]);
1073
1073
  };
1074
1074
  }
1075
1075
  //#endregion
1076
1076
  //#region src/analytics-engine-action-executions/index.ts
1077
- function G(e) {
1077
+ function W(e) {
1078
1078
  return e.analyticsEngineBinding || console.warn("Analytics Engine: No action_executions binding configured. Executions will not be written."), (!e.accountId || !e.apiToken) && console.warn("Analytics Engine: accountId and apiToken are required to read action_executions via the SQL API."), {
1079
- create: Ee(e),
1080
- get: Oe(e)
1079
+ create: De(e),
1080
+ get: ke(e)
1081
1081
  };
1082
1082
  }
1083
1083
  //#endregion
1084
1084
  //#region src/geo/index.ts
1085
- function ke() {
1085
+ function Ae() {
1086
1086
  return { async getGeoInfo(e) {
1087
1087
  try {
1088
1088
  let t = e["cf-ipcountry"], n = e["cf-ipcity"], r = e["cf-iplatitude"], i = e["cf-iplongitude"], a = e["cf-timezone"], o = e["cf-ipcontinent"];
@@ -1101,7 +1101,7 @@ function ke() {
1101
1101
  }
1102
1102
  //#endregion
1103
1103
  //#region src/rate-limit/index.ts
1104
- var Ae = class {
1104
+ var je = class {
1105
1105
  bindings;
1106
1106
  constructor(e) {
1107
1107
  this.bindings = e;
@@ -1117,12 +1117,12 @@ var Ae = class {
1117
1117
  }
1118
1118
  }
1119
1119
  };
1120
- function K(e) {
1121
- if (e && Object.keys(e).some((t) => e[t])) return new Ae(e);
1120
+ function G(e) {
1121
+ if (e && Object.keys(e).some((t) => e[t])) return new je(e);
1122
1122
  }
1123
1123
  //#endregion
1124
1124
  //#region src/code-executor/worker-template.ts
1125
- function q(e) {
1125
+ function K(e) {
1126
1126
  return `// Auto-generated AuthHero code hook worker
1127
1127
 
1128
1128
  const fnNames = {
@@ -1230,7 +1230,7 @@ export default {
1230
1230
  }
1231
1231
  //#endregion
1232
1232
  //#region src/code-executor/index.ts
1233
- var J = class {
1233
+ var q = class {
1234
1234
  config;
1235
1235
  constructor(e) {
1236
1236
  this.config = e;
@@ -1291,7 +1291,7 @@ var J = class {
1291
1291
  }
1292
1292
  }
1293
1293
  async deploy(e, t) {
1294
- let n = `hook-${e}`, r = q(t), i = `https://api.cloudflare.com/client/v4/accounts/${this.config.accountId}/workers/dispatch/namespaces/${this.config.dispatchNamespace}/scripts/${n}`, a = JSON.stringify({
1294
+ let n = `hook-${e}`, r = K(t), i = `https://api.cloudflare.com/client/v4/accounts/${this.config.accountId}/workers/dispatch/namespaces/${this.config.dispatchNamespace}/scripts/${n}`, a = JSON.stringify({
1295
1295
  main_module: "index.js",
1296
1296
  compatibility_date: this.config.compatibilityDate ?? "2024-11-20"
1297
1297
  }), o = new FormData();
@@ -1316,12 +1316,12 @@ var J = class {
1316
1316
  throw Error(`Failed to remove hook worker ${t}: ${r.status} ${e}`);
1317
1317
  }
1318
1318
  }
1319
- }, je = J, Me = {
1319
+ }, Me = q, Ne = {
1320
1320
  "post-user-login": "onExecutePostLogin",
1321
1321
  "credentials-exchange": "onExecuteCredentialsExchange",
1322
1322
  "pre-user-registration": "onExecutePreUserRegistration",
1323
1323
  "post-user-registration": "onExecutePostUserRegistration"
1324
- }, Ne = {
1324
+ }, Pe = {
1325
1325
  "post-user-login": {
1326
1326
  accessToken: ["setCustomClaim"],
1327
1327
  idToken: ["setCustomClaim"],
@@ -1340,15 +1340,15 @@ var J = class {
1340
1340
  },
1341
1341
  "post-user-registration": {}
1342
1342
  };
1343
- async function Pe(e) {
1343
+ async function Fe(e) {
1344
1344
  let t = new TextEncoder().encode(e), n = await crypto.subtle.digest("SHA-256", t), r = new Uint8Array(n), i = "";
1345
1345
  for (let e of r) i += e.toString(16).padStart(2, "0");
1346
1346
  return i;
1347
1347
  }
1348
- function Fe(e) {
1348
+ function Ie(e) {
1349
1349
  return `
1350
- const TRIGGER_FN_NAMES = ${JSON.stringify(Me)};
1351
- const API_SHAPES = ${JSON.stringify(Ne)};
1350
+ const TRIGGER_FN_NAMES = ${JSON.stringify(Ne)};
1351
+ const API_SHAPES = ${JSON.stringify(Pe)};
1352
1352
  const MAX_LOG_ENTRIES = 50;
1353
1353
  const MAX_LOG_LENGTH = 500;
1354
1354
 
@@ -1448,7 +1448,7 @@ export default {
1448
1448
  };
1449
1449
  `;
1450
1450
  }
1451
- var Ie = class {
1451
+ var Le = class {
1452
1452
  loader;
1453
1453
  compatibilityDate;
1454
1454
  constructor(e) {
@@ -1457,11 +1457,11 @@ var Ie = class {
1457
1457
  async execute(e) {
1458
1458
  let t = Date.now();
1459
1459
  try {
1460
- let t = Fe(e.code), n = {
1460
+ let t = Ie(e.code), n = {
1461
1461
  compatibilityDate: this.compatibilityDate,
1462
1462
  mainModule: "hook.js",
1463
1463
  modules: { "hook.js": t }
1464
- }, r = e.hookCodeId ? `${e.hookCodeId}-${await Pe(e.code)}` : null;
1464
+ }, r = e.hookCodeId ? `${e.hookCodeId}-${await Fe(e.code)}` : null;
1465
1465
  return await (await (r ? this.loader.get(r, async () => n) : this.loader.load(n)).getEntrypoint().fetch(new Request("https://hook/execute", {
1466
1466
  method: "POST",
1467
1467
  headers: { "Content-Type": "application/json" },
@@ -1479,19 +1479,19 @@ var Ie = class {
1479
1479
  };
1480
1480
  }
1481
1481
  }
1482
- }, Y = class extends Error {
1482
+ }, J = class extends Error {
1483
1483
  status;
1484
1484
  endpoint;
1485
1485
  errors;
1486
1486
  body;
1487
1487
  constructor(e, t, n, r = []) {
1488
- super(`Cloudflare API ${e} ${t}: ${Le(n, 256)}`), this.name = "CloudflareApiError", this.status = e, this.endpoint = t, this.body = n, this.errors = r;
1488
+ super(`Cloudflare API ${e} ${t}: ${Re(n, 256)}`), this.name = "CloudflareApiError", this.status = e, this.endpoint = t, this.body = n, this.errors = r;
1489
1489
  }
1490
1490
  };
1491
- function Le(e, t) {
1491
+ function Re(e, t) {
1492
1492
  return e.length <= t ? e : `${e.slice(0, t)}…`;
1493
1493
  }
1494
- var X = class {
1494
+ var Y = class {
1495
1495
  accountId;
1496
1496
  apiToken;
1497
1497
  fetchImpl;
@@ -1562,29 +1562,29 @@ var X = class {
1562
1562
  let t = JSON.parse(c);
1563
1563
  Array.isArray(t.errors) && (e = t.errors);
1564
1564
  } catch {}
1565
- throw new Y(s.status, t, c, e);
1565
+ throw new J(s.status, t, c, e);
1566
1566
  }
1567
1567
  if (!(c === "" || s.status === 204)) return JSON.parse(c);
1568
1568
  }
1569
- }, Re = "{tenant_id}", ze = "tenant-{tenant_id}", Be = "index.js", Ve = "2026-05-01";
1569
+ }, ze = "{tenant_id}", Be = "tenant-{tenant_id}", Ve = "index.js", He = "2026-05-01", X = 64;
1570
1570
  function Z(e, t) {
1571
1571
  return e.replace(/\{tenant_id\}/g, t);
1572
1572
  }
1573
- function He(e) {
1574
- if (!(e instanceof Y)) return !1;
1573
+ function Q(e) {
1574
+ if (!(e instanceof J)) return !1;
1575
1575
  let t = e.body.toLowerCase();
1576
1576
  return e.status === 409 || t.includes("already exists") || t.includes("name is already taken") || t.includes("already in use");
1577
1577
  }
1578
- function Q(e) {
1579
- return e instanceof Y ? e.status === 404 : !1;
1578
+ function $(e) {
1579
+ return e instanceof J ? e.status === 404 : !1;
1580
1580
  }
1581
1581
  function Ue(e) {
1582
- let t = new X({
1582
+ let t = new Y({
1583
1583
  accountId: e.accountId,
1584
1584
  apiToken: e.apiToken,
1585
1585
  fetch: e.fetch,
1586
1586
  timeoutMs: e.timeoutMs
1587
- }), n = e.scriptNameTemplate ?? Re, r = e.d1NameTemplate ?? ze, i = e.scriptMetadata?.main_module ?? Be, a = e.scriptMetadata?.compatibility_date ?? Ve, o = e.scriptMetadata?.compatibility_flags ?? ["nodejs_compat"], s = e.dispatchNamespace, c = e.logger;
1587
+ }), n = e.scriptNameTemplate ?? ze, r = e.d1NameTemplate ?? Be, i = e.scriptMetadata?.main_module ?? Ve, a = e.scriptMetadata?.compatibility_date ?? He, o = e.scriptMetadata?.compatibility_flags ?? ["nodejs_compat"], s = e.dispatchNamespace, c = e.logger;
1588
1588
  async function l(e) {
1589
1589
  let n = (await t.listD1Databases(e)).find((t) => t.name === e);
1590
1590
  if (n) return {
@@ -1597,7 +1597,7 @@ function Ue(e) {
1597
1597
  created: !0
1598
1598
  };
1599
1599
  } catch (n) {
1600
- if (!He(n)) throw n;
1600
+ if (!Q(n)) throw n;
1601
1601
  let r = (await t.listD1Databases(e)).find((t) => t.name === e);
1602
1602
  if (r) return {
1603
1603
  id: r.uuid,
@@ -1672,16 +1672,21 @@ function Ue(e) {
1672
1672
  }
1673
1673
  return {
1674
1674
  async onProvision(t) {
1675
- let i = Z(n, t), a = Z(r, t), { id: o, created: s } = await l(a), u = s ? !1 : await f(o);
1676
- if (s || u) await p(o), await _(o);
1675
+ let i = Z(n, t), a = Z(r, t), o = e.migrations[e.migrations.length - 1]?.name;
1676
+ if (o !== void 0 && o.length > X) throw Error(`Migration name "${o}" exceeds the ${X}-character database_version limit.`);
1677
+ let { id: s, created: u } = await l(a), d = u ? !1 : await f(s);
1678
+ if (u || d) await p(s), await _(s);
1677
1679
  else {
1678
- c?.warn(`D1 "${a}" has no migration-tracking table — assuming it predates tracking and is fully migrated; backfilling the tracking table and skipping migrations.`), await p(o);
1679
- for (let t of e.migrations) await g(o, t.name);
1680
+ c?.warn(`D1 "${a}" has no migration-tracking table — assuming it predates tracking and is fully migrated; backfilling the tracking table and skipping migrations.`), await p(s);
1681
+ for (let t of e.migrations) await g(s, t.name);
1680
1682
  }
1681
- return await v(i, o), await y(i, t), {
1682
- d1DatabaseId: o,
1683
+ return await v(i, s), await y(i, t), {
1684
+ d1DatabaseId: s,
1683
1685
  scriptName: i,
1684
- d1Name: a
1686
+ d1Name: a,
1687
+ bundleConfiguration: e.bundleConfiguration,
1688
+ workerVersion: e.workerVersion,
1689
+ databaseVersion: o
1685
1690
  };
1686
1691
  },
1687
1692
  async onDeprovision(e) {
@@ -1689,14 +1694,14 @@ function Ue(e) {
1689
1694
  try {
1690
1695
  await t.deleteNamespacedScript(s, i);
1691
1696
  } catch (e) {
1692
- Q(e) || o.push(e);
1697
+ $(e) || o.push(e);
1693
1698
  }
1694
1699
  try {
1695
1700
  let e = (await t.listD1Databases(a)).find((e) => e.name === a);
1696
1701
  if (e) try {
1697
1702
  await t.deleteD1Database(e.uuid);
1698
1703
  } catch (e) {
1699
- Q(e) || o.push(e);
1704
+ $(e) || o.push(e);
1700
1705
  }
1701
1706
  } catch (e) {
1702
1707
  o.push(e);
@@ -1713,13 +1718,13 @@ function Ue(e) {
1713
1718
  function We(e) {
1714
1719
  return e.deployment_type === "wfp";
1715
1720
  }
1716
- function $(e) {
1721
+ function Ge(e) {
1717
1722
  if (typeof e != "object" || !e) return [];
1718
1723
  let t = [];
1719
1724
  for (let n of Object.values(e)) if (typeof n == "object" && n && "errors" in n && Array.isArray(n.errors)) for (let e of n.errors) typeof e == "string" && t.push(e);
1720
1725
  return t;
1721
1726
  }
1722
- function Ge(e) {
1727
+ function Ke(e) {
1723
1728
  let { provisioner: t, tenants: n, syncDefaults: r } = e, i = e.shouldProvision ?? We, a = e.logger;
1724
1729
  async function o(e, t) {
1725
1730
  let r = t instanceof Error ? t.message : String(t);
@@ -1733,45 +1738,65 @@ function Ge(e) {
1733
1738
  a?.warn(`Failed to write provisioning_state="failed" for tenant ${e}:`, t);
1734
1739
  }
1735
1740
  }
1736
- return {
1737
- async onProvision(e) {
1738
- let s = await n.get(e);
1739
- if (!s || !i(s)) return;
1740
- let c;
1741
- try {
1742
- c = await t.onProvision(e);
1743
- } catch (t) {
1744
- throw await o(e, t), t;
1745
- }
1746
- let l = {
1747
- d1_database_id: c.d1DatabaseId,
1748
- worker_script_name: c.scriptName
1749
- };
1750
- try {
1751
- if (r) {
1752
- let t = $(await r(e));
1753
- if (t.length > 0) throw Error(`sync-defaults seed reported ${t.length} error(s): ${t.join("; ")}`);
1754
- }
1755
- } catch (t) {
1756
- let r = t instanceof Error ? t.message : String(t);
1757
- try {
1758
- await n.update(e, {
1759
- ...l,
1760
- provisioning_state: "failed",
1761
- provisioning_error: r.slice(0, 2048),
1762
- provisioning_state_changed_at: (/* @__PURE__ */ new Date()).toISOString()
1763
- });
1764
- } catch (t) {
1765
- a?.warn(`Failed to write provisioning_state="failed" for tenant ${e}:`, t);
1766
- }
1767
- throw t;
1741
+ async function s(e) {
1742
+ let i;
1743
+ try {
1744
+ i = await t.onProvision(e);
1745
+ } catch (t) {
1746
+ throw await o(e, t), t;
1747
+ }
1748
+ let s = {
1749
+ d1_database_id: i.d1DatabaseId,
1750
+ worker_script_name: i.scriptName,
1751
+ bundle_configuration: i.bundleConfiguration,
1752
+ worker_version: i.workerVersion,
1753
+ database_version: i.databaseVersion
1754
+ };
1755
+ try {
1756
+ if (r) {
1757
+ let t = Ge(await r(e));
1758
+ if (t.length > 0) throw Error(`sync-defaults seed reported ${t.length} error(s): ${t.join("; ")}`);
1768
1759
  }
1769
1760
  await n.update(e, {
1770
- ...l,
1761
+ ...s,
1771
1762
  provisioning_state: "ready",
1772
1763
  provisioning_error: void 0,
1773
1764
  provisioning_state_changed_at: (/* @__PURE__ */ new Date()).toISOString()
1774
1765
  });
1766
+ } catch (t) {
1767
+ let r = t instanceof Error ? t.message : String(t);
1768
+ try {
1769
+ await n.update(e, {
1770
+ ...s,
1771
+ provisioning_state: "failed",
1772
+ provisioning_error: r.slice(0, 2048),
1773
+ provisioning_state_changed_at: (/* @__PURE__ */ new Date()).toISOString()
1774
+ });
1775
+ } catch (t) {
1776
+ a?.warn(`Failed to write provisioning_state="failed" for tenant ${e}:`, t);
1777
+ }
1778
+ throw t;
1779
+ }
1780
+ }
1781
+ return {
1782
+ async onProvision(e) {
1783
+ let t = await n.get(e);
1784
+ t && i(t) && await s(e);
1785
+ },
1786
+ async onUpgrade(e) {
1787
+ let t = await n.get(e);
1788
+ if (!t) throw Error(`Cannot upgrade tenant "${e}": not found.`);
1789
+ if (!i(t)) throw Error(`Cannot upgrade tenant "${e}": not a WFP-provisioned tenant.`);
1790
+ try {
1791
+ await n.update(e, {
1792
+ provisioning_state: "pending",
1793
+ provisioning_error: void 0,
1794
+ provisioning_state_changed_at: (/* @__PURE__ */ new Date()).toISOString()
1795
+ });
1796
+ } catch (t) {
1797
+ a?.warn(`Failed to write provisioning_state="pending" for tenant ${e}:`, t);
1798
+ }
1799
+ await s(e);
1775
1800
  },
1776
1801
  async onDeprovision(e) {
1777
1802
  let r = await n.get(e);
@@ -1781,29 +1806,46 @@ function Ge(e) {
1781
1806
  }
1782
1807
  //#endregion
1783
1808
  //#region src/wfp-provisioner/wfp-forward.ts
1784
- var Ke = "DISPATCHER", qe = "tenant-{tenant_id}-auth";
1785
- function Je(e) {
1809
+ var qe = "DISPATCHER", Je = "tenant-{tenant_id}-auth";
1810
+ function Ye(e) {
1786
1811
  return typeof e == "object" && !!e && "get" in e && typeof Reflect.get(e, "get") == "function";
1787
1812
  }
1788
- function Ye(e, t) {
1813
+ function Xe(e, t) {
1789
1814
  return e.replace(/\{tenant_id\}/g, t);
1790
1815
  }
1791
- function Xe(e) {
1792
- let { tenants: t, controlPlaneTenantId: n, dispatcherBinding: r = Ke, scriptNameTemplate: i = qe, resolveTenantId: a = (e) => e.req.header("tenant-id") } = e;
1816
+ function Ze(e) {
1817
+ let { tenants: t, controlPlaneTenantId: n, dispatcherBinding: r = qe, scriptNameTemplate: i = Je, resolveTenantId: a = (e) => e.req.header("tenant-id") } = e;
1793
1818
  return async (e, o) => {
1794
1819
  let s = await a(e);
1795
1820
  if (!s || s === n) return o();
1796
1821
  let c = await t.get(s);
1797
1822
  if (!c || c.deployment_type !== "wfp" || c.provisioning_state && c.provisioning_state !== "ready") return o();
1798
1823
  let l = Reflect.get(e.env ?? {}, r);
1799
- if (!Je(l)) return o();
1800
- let u = Ye(i, s), d = await l.get(u).fetch(e.req.raw);
1801
- return d.status === 101 || "webSocket" in d ? d : new Response(d.body, d);
1824
+ if (!Ye(l)) return o();
1825
+ let u = Xe(i, s), d;
1826
+ try {
1827
+ d = await l.get(u).fetch(e.req.raw);
1828
+ } catch (t) {
1829
+ let n = t instanceof Error ? t.message : String(t), r = /not\s*found|no\s*such|does not exist/i.test(n), i = r ? "wfp_worker_not_found" : "wfp_dispatch_failed";
1830
+ return console.error(`[wfp-forward] ${i} tenant=${s} script=${u}: ${n}`), e.header("X-Authhero-Error", i), e.header("X-Wfp-Tenant", s), e.json({
1831
+ error: i,
1832
+ detail: r ? `Tenant '${s}' is marked ready but its worker '${u}' is not deployed in the dispatch namespace.` : `The worker for tenant '${s}' could not be reached.`,
1833
+ tenant_id: s
1834
+ }, r ? 503 : 502);
1835
+ }
1836
+ if (d.status >= 500) {
1837
+ let e = d.headers.get("X-Authhero-Error");
1838
+ console.error(`[wfp-forward] tenant worker ${d.status}${e ? ` (${e})` : ""} tenant=${s} script=${u}`);
1839
+ }
1840
+ let f = Reflect.get(d, "webSocket");
1841
+ if (d.status === 101 || f != null) return d;
1842
+ let p = new Response(d.body, d);
1843
+ return p.headers.set("X-Wfp-Tenant", s), p;
1802
1844
  };
1803
1845
  }
1804
1846
  //#endregion
1805
1847
  //#region src/index.ts
1806
- function Ze(e) {
1848
+ function Qe(e) {
1807
1849
  let t = {
1808
1850
  customDomains: y(e),
1809
1851
  cache: te({
@@ -1811,11 +1853,11 @@ function Ze(e) {
1811
1853
  ...e.defaultTtlSeconds !== void 0 && { defaultTtlSeconds: e.defaultTtlSeconds },
1812
1854
  ...e.keyPrefix && { keyPrefix: e.keyPrefix }
1813
1855
  }),
1814
- geo: ke()
1856
+ geo: Ae()
1815
1857
  };
1816
- e.r2SqlLogs ? t.logs = D(e.r2SqlLogs) : e.analyticsEngineLogs && (t.logs = V(e.analyticsEngineLogs)), e.analyticsEngineLogs && (t.analytics = B(e.analyticsEngineLogs)), e.analyticsEngineActionExecutions && (t.actionExecutions = G(e.analyticsEngineActionExecutions));
1817
- let n = K(e.rateLimitBindings);
1858
+ e.r2SqlLogs ? t.logs = D(e.r2SqlLogs) : e.analyticsEngineLogs && (t.logs = B(e.analyticsEngineLogs)), e.analyticsEngineLogs && (t.analytics = z(e.analyticsEngineLogs)), e.analyticsEngineActionExecutions && (t.actionExecutions = W(e.analyticsEngineActionExecutions));
1859
+ let n = G(e.rateLimitBindings);
1818
1860
  return n && (t.rateLimit = n), t;
1819
1861
  }
1820
1862
  //#endregion
1821
- export { X as CloudflareApiClient, Y as CloudflareApiError, je as CloudflareCodeExecutor, J as DispatchNamespaceCodeExecutor, Ie as WorkerLoaderCodeExecutor, G as createAnalyticsEngineActionExecutionsAdapter, B as createAnalyticsEngineAnalyticsAdapter, V as createAnalyticsEngineLogsAdapter, L as createAnalyticsEngineStatsAdapter, K as createCloudflareRateLimitAdapter, Ue as createCloudflareWfpD1Provisioner, D as createR2SQLLogsAdapter, se as createR2SQLStatsAdapter, Xe as createWfpForwardMiddleware, Ge as createWfpTenantProvisioningHook, Ze as default, q as generateWorkerScript };
1863
+ export { Y as CloudflareApiClient, J as CloudflareApiError, Me as CloudflareCodeExecutor, q as DispatchNamespaceCodeExecutor, Le as WorkerLoaderCodeExecutor, W as createAnalyticsEngineActionExecutionsAdapter, z as createAnalyticsEngineAnalyticsAdapter, B as createAnalyticsEngineLogsAdapter, I as createAnalyticsEngineStatsAdapter, G as createCloudflareRateLimitAdapter, Ue as createCloudflareWfpD1Provisioner, D as createR2SQLLogsAdapter, se as createR2SQLStatsAdapter, Ze as createWfpForwardMiddleware, Ke as createWfpTenantProvisioningHook, Qe as default, K as generateWorkerScript };