@debugkit/cli 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -98,6 +98,48 @@ var firestore_indexes_default = {
98
98
  }
99
99
  ]
100
100
  },
101
+ {
102
+ collectionGroup: "events",
103
+ queryScope: "COLLECTION",
104
+ fields: [
105
+ {
106
+ fieldPath: "sessionId",
107
+ order: "ASCENDING"
108
+ },
109
+ {
110
+ fieldPath: "ts",
111
+ order: "DESCENDING"
112
+ }
113
+ ]
114
+ },
115
+ {
116
+ collectionGroup: "events",
117
+ queryScope: "COLLECTION",
118
+ fields: [
119
+ {
120
+ fieldPath: "user.anonymousId",
121
+ order: "ASCENDING"
122
+ },
123
+ {
124
+ fieldPath: "ts",
125
+ order: "DESCENDING"
126
+ }
127
+ ]
128
+ },
129
+ {
130
+ collectionGroup: "events",
131
+ queryScope: "COLLECTION",
132
+ fields: [
133
+ {
134
+ fieldPath: "user.id",
135
+ order: "ASCENDING"
136
+ },
137
+ {
138
+ fieldPath: "ts",
139
+ order: "DESCENDING"
140
+ }
141
+ ]
142
+ },
101
143
  {
102
144
  collectionGroup: "users",
103
145
  queryScope: "COLLECTION",
@@ -273,7 +315,7 @@ var dim = (s) => pc.dim(s);
273
315
  var bold = (s) => pc.bold(s);
274
316
 
275
317
  // src/dashboard.ts
276
- var VERSION = true ? "0.7.0" : "0.0.0-dev";
318
+ var VERSION = true ? "0.8.0" : "0.0.0-dev";
277
319
  var DASHBOARD_VERSION = VERSION;
278
320
  function hashPassword(password2) {
279
321
  const salt = randomBytes(16);
@@ -375,13 +417,13 @@ async function summary(cwd, url, app) {
375
417
  const token = readEnv(paths(cwd).dashboardEnv).DEBUG_API_TOKEN;
376
418
  try {
377
419
  const r = await fetch(`${url}/api/summary?app=${encodeURIComponent(app)}`, { headers: token ? { authorization: `Bearer ${token}` } : {} });
378
- const text2 = await r.text();
420
+ const text3 = await r.text();
379
421
  let data;
380
422
  try {
381
- data = JSON.parse(text2);
423
+ data = JSON.parse(text3);
382
424
  } catch {
383
425
  }
384
- return { ok: r.ok, status: r.status, data, error: r.ok ? void 0 : text2.slice(0, 300) };
426
+ return { ok: r.ok, status: r.status, data, error: r.ok ? void 0 : text3.slice(0, 300) };
385
427
  } catch (err) {
386
428
  return { ok: false, status: 0, error: err.message };
387
429
  }
@@ -745,7 +787,7 @@ async function firebaseCli() {
745
787
  }
746
788
  return ["npx", ["-y", "firebase-tools@latest"]];
747
789
  }
748
- var emailsIn = (text2) => [...new Set(text2.match(/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g) ?? [])];
790
+ var emailsIn = (text3) => [...new Set(text3.match(/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g) ?? [])];
749
791
  async function setupFirebase(ctx) {
750
792
  const [fbCmd, fbPre] = await firebaseCli();
751
793
  const fb = (args, opts = {}) => capture(fbCmd, [...fbPre, ...args], opts);
@@ -863,7 +905,7 @@ async function setupFirebase(ctx) {
863
905
  `In ${bold(projectId)}${environment.get() ? ` (your ${environment.get()} environment)` : ""}, deBug will add:`,
864
906
  `\u2022 a Cloud Function ${code(FUNCTION_NAME)} in ${region}, with a public URL (each request needs the ingest key)`,
865
907
  `\u2022 a ${code("debug_apps")} collection in Firestore, with raw events expiring after 30 days`,
866
- `\u2022 two Firestore indexes for it (your existing indexes are left alone)`,
908
+ `\u2022 ${firestore_indexes_default.indexes.length} Firestore indexes for it (your existing indexes are left alone)`,
867
909
  "",
868
910
  "Nothing else in the project is changed. Usage is billed to the project's Blaze plan."
869
911
  ].join("\n"),
@@ -1473,7 +1515,117 @@ function installCommand(pm, pkgs) {
1473
1515
  }
1474
1516
  }
1475
1517
 
1518
+ // ../schema/src/frames.ts
1519
+ var LIBRARY = /* @__PURE__ */ new Set([
1520
+ // axios
1521
+ "dispatchXhrRequest",
1522
+ "throwIfCancellationRequested",
1523
+ "AxiosError",
1524
+ "onloadend",
1525
+ // React Native networking
1526
+ "__didCompleteResponse",
1527
+ "__didReceiveResponse",
1528
+ "__didReceiveData",
1529
+ "setReadyState",
1530
+ // Hermes / React Native runtime (also in InternalBytecode.js, which is never in-app)
1531
+ "tryCallOne",
1532
+ "tryCallTwo",
1533
+ "doResolve",
1534
+ "handleResolved",
1535
+ "finale",
1536
+ "flushedQueue",
1537
+ "invokeCallbackAndReturnFlushedQueue",
1538
+ "callFunctionReturnFlushedQueue",
1539
+ "__callFunction",
1540
+ "__guard",
1541
+ "callTimers",
1542
+ "_callTimer",
1543
+ "_allocateCallback",
1544
+ "asyncGeneratorStep",
1545
+ "_asyncToGenerator",
1546
+ "_next",
1547
+ "_throw",
1548
+ // React (renderer and events)
1549
+ "executeDispatch",
1550
+ "executeDispatchesInOrder",
1551
+ "processDispatchQueue",
1552
+ "dispatchEvent",
1553
+ "dispatchEventForPluginEventSystem",
1554
+ "batchedUpdatesImpl",
1555
+ "batchedUpdates$1",
1556
+ "batchedUpdates",
1557
+ "invokeGuardedCallbackImpl",
1558
+ "invokeGuardedCallback",
1559
+ "commitRootImpl",
1560
+ "performSyncWorkOnRoot",
1561
+ "renderWithHooks",
1562
+ "mountIndeterminateComponent",
1563
+ "beginWork",
1564
+ "flushPassiveEffects",
1565
+ "commitHookEffectListMount",
1566
+ // TanStack Query
1567
+ "#executeFetch"
1568
+ ]);
1569
+ var LIBRARY_AT_TOP = /* @__PURE__ */ new Set([
1570
+ // axios
1571
+ "xhr",
1572
+ "_request",
1573
+ "request",
1574
+ "wrap",
1575
+ "dispatchRequest",
1576
+ "transformData",
1577
+ "settle",
1578
+ "createError",
1579
+ "handleLoad",
1580
+ "handleError",
1581
+ "handleTimeout",
1582
+ // Babel's async helpers, when they're in the bundle rather than in Hermes' InternalBytecode
1583
+ "step",
1584
+ "spawn",
1585
+ // React Native networking
1586
+ "send",
1587
+ "sendRequest",
1588
+ "fetch",
1589
+ // TanStack Query
1590
+ "fetchFn",
1591
+ "fetchQuery",
1592
+ "executeMutation",
1593
+ "run",
1594
+ "start",
1595
+ "refetch",
1596
+ "onFetch"
1597
+ ]);
1598
+ function cleanFnName(fn) {
1599
+ if (!fn) return fn;
1600
+ return fn.replace(/^\?anon_\d+_/, "");
1601
+ }
1602
+ var RN_BUNDLE = /\.(?:js)?bundle\b/;
1603
+ function markLibraryFrames(frames) {
1604
+ let underLibrary = false;
1605
+ let seenBundleFrame = false;
1606
+ return frames.map((f) => {
1607
+ if (!f.file || !RN_BUNDLE.test(f.file)) return f;
1608
+ const name = cleanFnName(f.fn);
1609
+ const library = !!name && (LIBRARY.has(name) || underLibrary && LIBRARY_AT_TOP.has(name));
1610
+ if (library) {
1611
+ if (!seenBundleFrame) underLibrary = true;
1612
+ } else if (f.inApp !== false) underLibrary = false;
1613
+ seenBundleFrame = true;
1614
+ return library && f.inApp !== false ? { ...f, inApp: false } : f;
1615
+ });
1616
+ }
1617
+
1618
+ // ../schema/src/taxonomy.ts
1619
+ var OWNERS = ["app", "backend", "infrastructure", "third_party", "unknown"];
1620
+ var IMPACTS = ["blocked", "degraded", "silent"];
1621
+ var IMPACT_ORDER = Object.fromEntries(IMPACTS.map((impact, i) => [impact, IMPACTS.length - 1 - i]));
1622
+
1623
+ // ../schema/src/hosts.ts
1624
+ var OWNER_SET = new Set(OWNERS.filter((o) => o !== "unknown"));
1625
+
1476
1626
  // ../schema/src/core.ts
1627
+ var MAX_CAPTURED_BODY = 16384;
1628
+ var MAX_BREADCRUMBS = 50;
1477
1629
  var LATENCY_BUCKETS_MS = [50, 100, 200, 300, 500, 750, 1e3, 1500, 2e3, 3e3, 5e3, 1e4];
1478
1630
  function latencyBucket(ms) {
1479
1631
  const i = LATENCY_BUCKETS_MS.findIndex((edge) => ms <= edge);
@@ -1482,7 +1634,6 @@ function latencyBucket(ms) {
1482
1634
  var V8 = /^\s*at (?:(.+?) \()?(.+?):(\d+):(\d+)\)?\s*$/;
1483
1635
  var GECKO = /^\s*(.*?)@(.+?):(\d+):(\d+)\s*$/;
1484
1636
  var NOT_IN_APP = [/node_modules/, /\bnative\b/, /\[native code\]/, /InternalBytecode/];
1485
- var RN_BUNDLE = /\.(?:js)?bundle\b/;
1486
1637
  function cleanFile(file) {
1487
1638
  return file.replace(/^address at /, "");
1488
1639
  }
@@ -1503,7 +1654,7 @@ function parseStack(stack) {
1503
1654
  });
1504
1655
  if (frames.length >= 100) break;
1505
1656
  }
1506
- return frames;
1657
+ return markLibraryFrames(frames);
1507
1658
  }
1508
1659
 
1509
1660
  // ../sdk/src/context.ts
@@ -1578,6 +1729,41 @@ function safeDecode(s) {
1578
1729
  return s;
1579
1730
  }
1580
1731
  }
1732
+ var MAX_BODY_CHARS = 64 * 1024;
1733
+ var BODY_WAIT_MS = 3e3;
1734
+ var TEXT_TYPE = /^(?:text\/|application\/(?:[\w.+-]*json|[\w.+-]*xml|x-www-form-urlencoded|problem\+json|javascript))/i;
1735
+ function describeBody(body, type) {
1736
+ if (body === void 0 || body === null || body === "") return {};
1737
+ if (typeof body === "string") return { text: body.slice(0, MAX_BODY_CHARS) };
1738
+ if (typeof URLSearchParams !== "undefined" && body instanceof URLSearchParams) return { text: body.toString().slice(0, MAX_BODY_CHARS) };
1739
+ if (typeof ArrayBuffer !== "undefined" && (body instanceof ArrayBuffer || ArrayBuffer.isView(body))) return { binary: { bytes: body.byteLength, type } };
1740
+ const blob = body;
1741
+ if (typeof blob.size === "number") return { binary: { bytes: blob.size, type: typeof blob.type === "string" && blob.type ? blob.type : type } };
1742
+ return { binary: { type: type ?? "multipart/form-data" } };
1743
+ }
1744
+ function headerValue(headers, name) {
1745
+ if (!headers) return void 0;
1746
+ const lower = name.toLowerCase();
1747
+ return Object.entries(headers).find(([k]) => k.toLowerCase() === lower)?.[1];
1748
+ }
1749
+ function headerRecord(h) {
1750
+ if (!h) return void 0;
1751
+ const out = {};
1752
+ const pairs = h;
1753
+ if (typeof pairs.forEach === "function" && !Array.isArray(h)) pairs.forEach((v, k) => out[k] = String(v));
1754
+ else if (Array.isArray(h)) for (const [k, v] of h) out[k] = String(v);
1755
+ else for (const [k, v] of Object.entries(h)) out[k] = String(v);
1756
+ return out;
1757
+ }
1758
+ function parseRawHeaders(raw) {
1759
+ if (!raw) return void 0;
1760
+ const out = {};
1761
+ for (const line of raw.split(/\r?\n/)) {
1762
+ const i = line.indexOf(":");
1763
+ if (i > 0) out[line.slice(0, i).trim().toLowerCase()] = line.slice(i + 1).trim();
1764
+ }
1765
+ return out;
1766
+ }
1581
1767
  var insideFetch = 0;
1582
1768
  function instrumentFetch(sink) {
1583
1769
  const orig = g.fetch;
@@ -1588,6 +1774,15 @@ function instrumentFetch(sink) {
1588
1774
  const method = String(init2?.method ?? input?.method ?? "GET").toUpperCase();
1589
1775
  const start = Date.now();
1590
1776
  const stack = new Error().stack;
1777
+ let sent = {};
1778
+ if (sink.capturesBodies()) {
1779
+ try {
1780
+ const requestHeaders = headerRecord(init2?.headers ?? input?.headers);
1781
+ const body = describeBody(init2?.body, headerValue(requestHeaders, "content-type"));
1782
+ sent = { requestHeaders, requestBody: body.text, requestBinary: body.binary };
1783
+ } catch {
1784
+ }
1785
+ }
1591
1786
  let p2;
1592
1787
  insideFetch++;
1593
1788
  try {
@@ -1597,12 +1792,41 @@ function instrumentFetch(sink) {
1597
1792
  }
1598
1793
  return p2.then(
1599
1794
  (res) => {
1600
- sink.request({ method, url, status: res.status, durationMs: Date.now() - start, stack });
1795
+ let clone;
1796
+ let failedResponse = {};
1797
+ try {
1798
+ if (sink.wantsBody(res.status, url)) {
1799
+ const type = res.headers?.get?.("content-type") ?? void 0;
1800
+ if (sink.capturesBodies()) failedResponse.responseHeaders = headerRecord(res.headers);
1801
+ if (!type || TEXT_TYPE.test(type)) clone = res.clone();
1802
+ else {
1803
+ const length = Number(res.headers.get("content-length"));
1804
+ failedResponse = { ...failedResponse, responseBinary: { bytes: Number.isFinite(length) && length > 0 ? length : void 0, type } };
1805
+ }
1806
+ }
1807
+ } catch {
1808
+ clone = void 0;
1809
+ }
1810
+ const addBody = sink.request({ method, url, status: res.status, durationMs: Date.now() - start, stack, bodyPending: !!clone, ...sent, ...failedResponse });
1811
+ if (clone && addBody) {
1812
+ let done = false;
1813
+ const finish = (body) => {
1814
+ if (done) return;
1815
+ done = true;
1816
+ clearTimeout(timer);
1817
+ addBody(body);
1818
+ };
1819
+ const timer = setTimeout(() => finish(""), BODY_WAIT_MS);
1820
+ clone.text().then(
1821
+ (body) => finish(body.slice(0, MAX_BODY_CHARS)),
1822
+ () => finish("")
1823
+ );
1824
+ }
1601
1825
  return res;
1602
1826
  },
1603
1827
  (error) => {
1604
1828
  const aborted = error?.name === "AbortError";
1605
- sink.request({ method, url, error, aborted, durationMs: Date.now() - start, stack });
1829
+ sink.request({ method, url, error, aborted, durationMs: Date.now() - start, stack, ...sent });
1606
1830
  throw error;
1607
1831
  }
1608
1832
  );
@@ -1613,39 +1837,102 @@ function instrumentFetch(sink) {
1613
1837
  if (g.fetch === wrapped) g.fetch = orig;
1614
1838
  };
1615
1839
  }
1840
+ function decodeUtf8(buf) {
1841
+ if (buf.byteLength > MAX_BODY_CHARS) return void 0;
1842
+ const bytes = new Uint8Array(buf);
1843
+ if (typeof TextDecoder !== "undefined") return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
1844
+ let escaped = "";
1845
+ for (const b of bytes) escaped += `%${b.toString(16).padStart(2, "0")}`;
1846
+ return decodeURIComponent(escaped);
1847
+ }
1848
+ function readXhrBody(x) {
1849
+ let type;
1850
+ try {
1851
+ type = x.getResponseHeader?.("content-type") ?? void 0;
1852
+ const kind = x.responseType ?? "";
1853
+ if (kind === "" || kind === "text") return { text: x.responseText?.slice(0, MAX_BODY_CHARS) };
1854
+ if (kind === "json" && x.response != null) return { text: JSON.stringify(x.response).slice(0, MAX_BODY_CHARS) };
1855
+ if (kind === "arraybuffer" && x.response instanceof ArrayBuffer) {
1856
+ const text3 = decodeUtf8(x.response);
1857
+ return text3 !== void 0 ? { text: text3 } : { binary: { bytes: x.response.byteLength, type } };
1858
+ }
1859
+ const blob = x.response;
1860
+ return { binary: { bytes: typeof blob?.size === "number" ? blob.size : void 0, type } };
1861
+ } catch {
1862
+ return x.response instanceof ArrayBuffer ? { binary: { bytes: x.response.byteLength, type } } : {};
1863
+ }
1864
+ }
1616
1865
  function instrumentXhr(sink) {
1617
1866
  const X = g.XMLHttpRequest;
1618
1867
  const proto = X?.prototype;
1619
1868
  if (!proto || proto.open.__debug) return;
1620
1869
  const open = proto.open;
1621
1870
  const send = proto.send;
1871
+ const setRequestHeader = proto.setRequestHeader;
1622
1872
  const wrappedOpen = function(method, url, ...rest) {
1623
1873
  const u = String(url);
1624
1874
  this.__debug = insideFetch > 0 || sink.ignored(u) ? null : { method: String(method).toUpperCase(), url: u };
1625
1875
  return open.call(this, method, url, ...rest);
1626
1876
  };
1877
+ const wrappedSetRequestHeader = function(name, value) {
1878
+ const d = this.__debug;
1879
+ if (d && sink.capturesBodies()) (d.headers ??= {})[String(name)] = String(value);
1880
+ return setRequestHeader?.call(this, name, value);
1881
+ };
1627
1882
  const wrappedSend = function(...args) {
1628
1883
  const d = this.__debug;
1629
1884
  if (d) {
1885
+ let sent = {};
1886
+ if (sink.capturesBodies()) {
1887
+ try {
1888
+ const body = describeBody(args[0], headerValue(d.headers, "content-type"));
1889
+ sent = { requestHeaders: d.headers, requestBody: body.text, requestBinary: body.binary };
1890
+ } catch {
1891
+ }
1892
+ }
1630
1893
  const start = Date.now();
1631
1894
  const stack = new Error().stack;
1632
1895
  let aborted = false;
1633
1896
  let timedOut = false;
1634
1897
  this.addEventListener("abort", () => aborted = true);
1635
1898
  this.addEventListener("timeout", () => timedOut = true);
1636
- this.addEventListener(
1637
- "loadend",
1638
- () => sink.request({ ...d, status: this.status || void 0, aborted, timedOut, durationMs: Date.now() - start, stack })
1639
- );
1899
+ this.addEventListener("loadend", () => {
1900
+ const status = this.status || void 0;
1901
+ const failed = status !== void 0 && sink.wantsBody(status, d.url);
1902
+ const body = failed ? readXhrBody(this) : {};
1903
+ let responseHeaders;
1904
+ if (failed && sink.capturesBodies()) {
1905
+ try {
1906
+ responseHeaders = parseRawHeaders(this.getAllResponseHeaders?.());
1907
+ } catch {
1908
+ responseHeaders = void 0;
1909
+ }
1910
+ }
1911
+ sink.request({
1912
+ method: d.method,
1913
+ url: d.url,
1914
+ status,
1915
+ aborted,
1916
+ timedOut,
1917
+ durationMs: Date.now() - start,
1918
+ stack,
1919
+ responseBody: body.text,
1920
+ responseBinary: body.binary,
1921
+ responseHeaders,
1922
+ ...sent
1923
+ });
1924
+ });
1640
1925
  }
1641
1926
  return send.apply(this, args);
1642
1927
  };
1643
1928
  wrappedOpen.__debug = true;
1644
1929
  proto.open = wrappedOpen;
1645
1930
  proto.send = wrappedSend;
1931
+ if (setRequestHeader) proto.setRequestHeader = wrappedSetRequestHeader;
1646
1932
  return () => {
1647
1933
  proto.open = open;
1648
1934
  proto.send = send;
1935
+ if (setRequestHeader) proto.setRequestHeader = setRequestHeader;
1649
1936
  };
1650
1937
  }
1651
1938
  function format(arg) {
@@ -1697,8 +1984,8 @@ function describeElement(el) {
1697
1984
  const tag = el.tagName.toLowerCase();
1698
1985
  const label = el.getAttribute("aria-label") || el.getAttribute("data-testid") || el.getAttribute("title") || (tag === "input" ? el.getAttribute("name") || el.type : el.innerText || el.textContent || "");
1699
1986
  const id = el.id ? `#${el.id}` : "";
1700
- const text2 = label.replace(/\s+/g, " ").trim().slice(0, 60);
1701
- return `${tag}${id}${text2 ? ` "${text2}"` : ""}`;
1987
+ const text3 = label.replace(/\s+/g, " ").trim().slice(0, 60);
1988
+ return `${tag}${id}${text3 ? ` "${text3}"` : ""}`;
1702
1989
  }
1703
1990
  function instrumentClicks(sink) {
1704
1991
  const d = g.document;
@@ -1727,10 +2014,195 @@ function instrumentWebLifecycle(sink) {
1727
2014
  };
1728
2015
  }
1729
2016
 
2017
+ // ../sdk/src/redact.ts
2018
+ var REDACTED = "[redacted]";
2019
+ var SECRET_FIELDS = [
2020
+ "password",
2021
+ "pin",
2022
+ "otp",
2023
+ "otpcode",
2024
+ "verificationcode",
2025
+ "cvv",
2026
+ "cvc",
2027
+ "cardnumber",
2028
+ "pan",
2029
+ "idtoken",
2030
+ "accesstoken",
2031
+ "refreshtoken",
2032
+ "token",
2033
+ "secret",
2034
+ "apikey"
2035
+ ];
2036
+ var SECRET_HEADERS = ["authorization", "proxy-authorization", "cookie", "set-cookie"];
2037
+ var SECRET_HEADER_WORDS = /token|key|secret/i;
2038
+ var JWT = /eyJ[\w-]+\.[\w-]+\.[\w-]*(?:\.[\w-]*){0,2}/g;
2039
+ var CARD_CANDIDATE = /\d(?:[ ._-]?\d){12,18}/g;
2040
+ var MAX_HEADERS = 50;
2041
+ var MAX_HEADER_VALUE = 1e3;
2042
+ function luhn(digits) {
2043
+ let sum = 0;
2044
+ for (let i = 0; i < digits.length; i++) {
2045
+ let d = Number(digits[digits.length - 1 - i]);
2046
+ if (i % 2 === 1) {
2047
+ d *= 2;
2048
+ if (d > 9) d -= 9;
2049
+ }
2050
+ sum += d;
2051
+ }
2052
+ return sum % 10 === 0;
2053
+ }
2054
+ function redactValues(text3) {
2055
+ return text3.replace(JWT, REDACTED).replace(CARD_CANDIDATE, (m, offset, whole) => {
2056
+ if (/\d/.test(whole[offset - 1] ?? "") || /\d/.test(whole[offset + m.length] ?? "")) return m;
2057
+ const digits = m.replace(/\D/g, "");
2058
+ return luhn(digits) ? `\u2022\u2022\u2022\u2022 ${digits.slice(-4)}` : m;
2059
+ });
2060
+ }
2061
+ var PERSONAL_TEXT = /[^\s@<>"']+@[^\s@<>"']+\.[^\s@<>"']+|\+?\d(?:[\s().-]?\d){6,}/g;
2062
+ function maskPersonal(text3) {
2063
+ return text3.replace(PERSONAL_TEXT, "\u2022\u2022\u2022");
2064
+ }
2065
+ var escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2066
+ function redactKeyValues(text3, fields) {
2067
+ if (fields.size === 0) return text3;
2068
+ const names = [...fields].map(escapeRe).join("|");
2069
+ const quoted = new RegExp(`((["'])(?:${names})\\2\\s*:\\s*)("(?:[^"\\\\]|\\\\.)*"?|'[^']*'?|[^,}\\]\\s]+)`, "gi");
2070
+ const bare = new RegExp(`((?:^|[\\s,{;&?])(?:${names})\\s*[:=]\\s*)("(?:[^"\\\\]|\\\\.)*"?|[^,}\\]\\s&;]+)`, "gi");
2071
+ return text3.replace(quoted, (_m, key) => `${key}"${REDACTED}"`).replace(bare, (_m, key) => `${key}${REDACTED}`);
2072
+ }
2073
+ function secretFields(opts) {
2074
+ return /* @__PURE__ */ new Set([...SECRET_FIELDS, ...(opts.fields ?? []).map((f) => f.toLowerCase())]);
2075
+ }
2076
+ function redactJson(value, fields) {
2077
+ if (typeof value === "string") return redactTextWith(value, fields);
2078
+ if (typeof value === "number" && Number.isInteger(value) && value >= 1e12) {
2079
+ const masked2 = redactValues(String(value));
2080
+ return masked2 === String(value) ? value : masked2;
2081
+ }
2082
+ if (Array.isArray(value)) return value.map((v) => redactJson(v, fields));
2083
+ if (value && typeof value === "object") {
2084
+ const out = {};
2085
+ for (const [k, v] of Object.entries(value)) out[k] = fields.has(k.toLowerCase()) ? REDACTED : redactJson(v, fields);
2086
+ return out;
2087
+ }
2088
+ return value;
2089
+ }
2090
+ function formField(key) {
2091
+ let name = key;
2092
+ try {
2093
+ name = decodeURIComponent(key.replace(/\+/g, " "));
2094
+ } catch {
2095
+ }
2096
+ return (/([^[\].]+)\]?$/.exec(name)?.[1] ?? name).toLowerCase();
2097
+ }
2098
+ function redactForm(text3, fields) {
2099
+ return text3.split("&").map((pair) => {
2100
+ const eq = pair.indexOf("=");
2101
+ if (eq < 0) return redactValues(pair);
2102
+ const key = pair.slice(0, eq);
2103
+ return fields.has(formField(key)) ? `${key}=${encodeURIComponent(REDACTED)}` : redactValues(pair);
2104
+ }).join("&");
2105
+ }
2106
+ function redactTextWith(text3, fields) {
2107
+ const trimmed = text3.trim();
2108
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
2109
+ try {
2110
+ return JSON.stringify(redactJson(JSON.parse(trimmed), fields));
2111
+ } catch {
2112
+ }
2113
+ }
2114
+ if (trimmed.includes("=") && !/\s/.test(trimmed)) return redactForm(trimmed, fields);
2115
+ return redactValues(redactKeyValues(text3, fields));
2116
+ }
2117
+ function redactText(text3, opts = {}) {
2118
+ return redactTextWith(text3, secretFields(opts));
2119
+ }
2120
+ function redactHeaders(headers, opts = {}) {
2121
+ if (!headers) return void 0;
2122
+ const extra = new Set((opts.headers ?? []).map((h) => h.toLowerCase()));
2123
+ const out = {};
2124
+ for (const [name, value] of Object.entries(headers).slice(0, MAX_HEADERS)) {
2125
+ const lower = name.toLowerCase();
2126
+ out[lower] = SECRET_HEADERS.includes(lower) || extra.has(lower) || SECRET_HEADER_WORDS.test(lower) ? REDACTED : redactValues(String(value)).slice(0, MAX_HEADER_VALUE);
2127
+ }
2128
+ return out;
2129
+ }
2130
+ function captureBody(text3, maxChars, opts = {}) {
2131
+ if (text3 === void 0 || text3 === "") return {};
2132
+ const redacted = redactText(text3, opts);
2133
+ if (redacted.length <= maxChars) return { body: redacted, bodySize: redacted.length };
2134
+ const kb = Math.ceil(redacted.length / 1024);
2135
+ return { body: `${redacted.slice(0, maxChars)}\u2026[truncated, ${kb} KB total]`, bodySize: redacted.length, truncated: true };
2136
+ }
2137
+ function bodyOf(text3, binary, maxChars, opts = {}) {
2138
+ return binary ? binaryBody(binary.bytes, binary.type) : captureBody(text3, maxChars, opts);
2139
+ }
2140
+ function binaryBody(bytes, type) {
2141
+ const size = bytes === void 0 ? "" : ` ${Math.max(1, Math.ceil(bytes / 1024))} KB`;
2142
+ return { body: `[binary${size}${type ? `, ${type}` : ""}]`, bodySize: bytes };
2143
+ }
2144
+
2145
+ // ../sdk/src/network.ts
2146
+ var MAX_TEXT = 200;
2147
+ var MAX_ERRORS = 500;
2148
+ function findBase(url, baseUrls) {
2149
+ const lower = url.toLowerCase();
2150
+ return baseUrls.map((b) => b.replace(/\/+$/, "")).filter((b) => b && lower.startsWith(b.toLowerCase()) && /^(?:[/?#]|$)/.test(url.slice(b.length))).sort((a, b) => b.length - a.length)[0];
2151
+ }
2152
+ function nameRequest(url, baseUrls = []) {
2153
+ const base = findBase(url, baseUrls);
2154
+ const masked2 = normaliseUrl(base ? url.slice(base.length) || "/" : url);
2155
+ const slash = masked2.indexOf("/");
2156
+ const host = !base && slash > 0 ? masked2.slice(0, slash) : "";
2157
+ const path2 = host ? masked2.slice(slash) : masked2.startsWith("/") ? masked2 : `/${masked2}`;
2158
+ const first = path2.split("/").find(Boolean);
2159
+ return { service: host || first || "/", path: path2, matched: !!base };
2160
+ }
2161
+ function text2(v) {
2162
+ return typeof v === "string" && v.trim() ? v.trim().slice(0, MAX_TEXT) : void 0;
2163
+ }
2164
+ function masked(v) {
2165
+ return v === void 0 ? void 0 : maskPersonal(redactValues(v));
2166
+ }
2167
+ function flattenErrors(v) {
2168
+ const parts = [];
2169
+ if (Array.isArray(v)) {
2170
+ for (const e of v) {
2171
+ const s = typeof e === "string" ? e : text2(e?.message) ?? text2(e?.detail);
2172
+ if (s) parts.push(s);
2173
+ }
2174
+ } else if (v && typeof v === "object") {
2175
+ for (const [field, msgs] of Object.entries(v)) {
2176
+ const list = (Array.isArray(msgs) ? msgs : [msgs]).filter((m) => typeof m === "string");
2177
+ if (list.length) parts.push(`${field}: ${list.join(", ")}`);
2178
+ }
2179
+ }
2180
+ const joined = parts.join("; ").slice(0, MAX_ERRORS);
2181
+ return joined || void 0;
2182
+ }
2183
+ function readProblemDetails(body) {
2184
+ if (!body) return void 0;
2185
+ let json;
2186
+ try {
2187
+ json = JSON.parse(body);
2188
+ } catch {
2189
+ return void 0;
2190
+ }
2191
+ if (!json || typeof json !== "object" || Array.isArray(json)) return void 0;
2192
+ const o = json;
2193
+ const title = masked(text2(o.title) ?? text2(o.message) ?? text2(o.error));
2194
+ const code2 = typeof o.code === "number" || text2(o.code) ? o.code : null;
2195
+ const traceId = text2(o.traceId) ?? text2(o.traceID) ?? text2(o.trace_id) ?? text2(o.correlationId) ?? null;
2196
+ const errors = masked(flattenErrors(o.errors)) ?? null;
2197
+ if (!title && code2 === null && !traceId && !errors) return void 0;
2198
+ return { backendTitle: title ?? null, backendCode: code2, traceId, backendErrors: errors };
2199
+ }
2200
+
1730
2201
  // ../sdk/src/client.ts
1731
2202
  var SDK_NAME = "@debugkit/sdk";
1732
2203
  var SDK_VERSION = typeof __DEBUGKIT_SDK_VERSION__ === "string" ? __DEBUGKIT_SDK_VERSION__ : "0.0.0-dev";
1733
2204
  var QUEUE_KEY = "@debugkit/queue";
2205
+ var MAX_BATCH_CHARS = 384 * 1024;
1734
2206
  var ANON_KEY = "@debugkit/anonymousId";
1735
2207
  function webStorage() {
1736
2208
  try {
@@ -1763,18 +2235,23 @@ var DebugClient = class {
1763
2235
  backoffUntil = 0;
1764
2236
  failures = 0;
1765
2237
  ready = false;
2238
+ /** Set by close(): nothing more is recorded or queued until the next init(). */
2239
+ closed = false;
1766
2240
  handlersInstalled = false;
1767
2241
  auto = { errors: false, network: false, console: false, navigation: false, clicks: false, lifecycle: false, sessions: false };
1768
2242
  restores = [];
1769
2243
  sessionState = { errored: false, crashed: false };
1770
2244
  lastNav;
2245
+ /** Failures waiting for their response body (fetch), reported on close if it hasn't come. */
2246
+ pendingReports = /* @__PURE__ */ new Set();
1771
2247
  limits = /* @__PURE__ */ new Map();
1772
2248
  /** fetch as it was before instrumentation, so our own uploads are never recorded. */
1773
2249
  rawFetch;
1774
2250
  init(options) {
1775
2251
  if (this.timer) clearInterval(this.timer);
1776
2252
  this.uninstrument();
1777
- this.opts = { flushIntervalMs: 5e3, maxBatch: 50, maxBreadcrumbs: 30, ...options };
2253
+ this.opts = { flushIntervalMs: 5e3, maxBatch: 50, ...options, maxBreadcrumbs: Math.min(options.maxBreadcrumbs ?? 30, MAX_BREADCRUMBS) };
2254
+ this.closed = false;
1778
2255
  this.globalTags = { ...options.tags };
1779
2256
  if (options.enabled === false) {
1780
2257
  this.ready = false;
@@ -1814,9 +2291,17 @@ var DebugClient = class {
1814
2291
  }
1815
2292
  /** Record a navigation breadcrumb ("from → to"). Repeated paths are ignored. */
1816
2293
  navigated(to) {
1817
- if (!to || to === this.lastNav) return;
1818
- this.breadcrumb("navigation", this.lastNav ? `${this.lastNav} \u2192 ${to}` : to);
1819
- this.lastNav = to;
2294
+ if (this.closed || !to || to === this.lastNav) return;
2295
+ try {
2296
+ this.breadcrumb("navigation", this.lastNav ? `${this.lastNav} \u2192 ${to}` : to);
2297
+ this.lastNav = String(to);
2298
+ } catch (err) {
2299
+ this.log("navigation breadcrumb failed", err);
2300
+ }
2301
+ }
2302
+ /** The screen the app is on, from the last navigation breadcrumb. */
2303
+ get screen() {
2304
+ return this.lastNav;
1820
2305
  }
1821
2306
  get initialized() {
1822
2307
  return this.ready;
@@ -1853,16 +2338,28 @@ var DebugClient = class {
1853
2338
  setUser(id) {
1854
2339
  this.user = { ...this.user, id };
1855
2340
  }
2341
+ /** Record a breadcrumb. Never throws; does nothing after close(). */
1856
2342
  breadcrumb(category, message, data, level = "info") {
1857
- const msg = message.slice(0, 500);
2343
+ if (this.closed) return;
2344
+ try {
2345
+ this.addCrumb(category, message, data, level);
2346
+ } catch (err) {
2347
+ this.log("breadcrumb failed", err);
2348
+ }
2349
+ }
2350
+ /** Records a breadcrumb and returns the one stored (a repeat collapses into the last). */
2351
+ addCrumb(category, message, data, level) {
2352
+ const msg = String(message).slice(0, 500);
1858
2353
  const last = this.crumbs[this.crumbs.length - 1];
1859
2354
  if (last && last.category === category && last.message === msg && last.level === level) {
1860
2355
  last.ts = now();
1861
2356
  last.data = { ...data, repeated: Number(last.data?.repeated ?? 1) + 1 };
1862
- return;
2357
+ return last;
1863
2358
  }
1864
- this.crumbs.push({ ts: now(), category, message: msg, data, level });
2359
+ const crumb = { ts: now(), category, message: msg, data, level };
2360
+ this.crumbs.push(crumb);
1865
2361
  if (this.crumbs.length > (this.opts?.maxBreadcrumbs ?? 30)) this.crumbs.shift();
2362
+ return crumb;
1866
2363
  }
1867
2364
  /** Log an error. `flow` is the part of the app it belongs to, e.g. "auth.login". */
1868
2365
  error(err, meta = {}) {
@@ -1912,13 +2409,32 @@ var DebugClient = class {
1912
2409
  this.timings.clear();
1913
2410
  this.timingsSince = Date.now();
1914
2411
  }
2412
+ /**
2413
+ * How many queued events the next upload takes: at most `maxBatch`, and no more than about
2414
+ * 384 KB of events (ingest refuses uploads over 512 KB), but always at least one.
2415
+ */
2416
+ batchSize() {
2417
+ let size = 0;
2418
+ let n = 0;
2419
+ for (const e of this.queue) {
2420
+ if (n >= this.opts.maxBatch) break;
2421
+ try {
2422
+ size += JSON.stringify(e).length;
2423
+ } catch {
2424
+ size += 1024;
2425
+ }
2426
+ if (n > 0 && size > MAX_BATCH_CHARS) break;
2427
+ n++;
2428
+ }
2429
+ return Math.max(1, n);
2430
+ }
1915
2431
  async flush() {
1916
2432
  this.queueTimings(this.closing);
1917
2433
  if (this.flushing) await this.flushing.catch(() => {
1918
2434
  });
1919
2435
  if (this.flushing) return this.flushing;
1920
2436
  if (!this.ready || this.queue.length === 0 || Date.now() < this.backoffUntil) return;
1921
- const batch = this.queue.splice(0, this.opts.maxBatch);
2437
+ const batch = this.queue.splice(0, this.batchSize());
1922
2438
  this.inflight = batch;
1923
2439
  this.flushing = this.send(batch).then(() => {
1924
2440
  this.failures = 0;
@@ -1937,16 +2453,23 @@ var DebugClient = class {
1937
2453
  }
1938
2454
  /** Stop the flush timer, undo automatic instrumentation and send what is queued. */
1939
2455
  closing = false;
2456
+ /**
2457
+ * Sends what is queued and stops: automatic capture is removed, and errors, events, sessions
2458
+ * and breadcrumbs are ignored until the next init(). A remote kill switch can rely on it.
2459
+ */
1940
2460
  close() {
1941
2461
  if (this.timer) clearInterval(this.timer);
1942
2462
  this.uninstrument();
2463
+ for (const report of [...this.pendingReports]) report();
2464
+ this.closed = true;
2465
+ this.lastNav = void 0;
1943
2466
  this.closing = true;
1944
2467
  return this.flush().finally(() => this.closing = false);
1945
2468
  }
1946
2469
  /* ---------------- internals ---------------- */
1947
2470
  /** @internal Used by the platform entry points for errors that have no thrown value. */
1948
- captureError(e, meta, request) {
1949
- if (!this.ready) return;
2471
+ captureError(e, meta, request, breadcrumbs = [...this.crumbs], response) {
2472
+ if (!this.ready || this.closed) return;
1950
2473
  const handled = meta.handled ?? true;
1951
2474
  const frames = e.frames ?? parseStack(e.stack);
1952
2475
  if (!meta.fatal && !this.allowError(`${e.name}|${e.message.slice(0, 120)}|${frames[0]?.file ?? ""}:${frames[0]?.line ?? ""}`)) return;
@@ -1970,8 +2493,9 @@ var DebugClient = class {
1970
2493
  severity: meta.severity ?? (meta.fatal ? "critical" : void 0),
1971
2494
  handled,
1972
2495
  error: { name: e.name, message: e.message, stack: e.stack, frames },
1973
- breadcrumbs: [...this.crumbs],
1974
- request
2496
+ breadcrumbs,
2497
+ request,
2498
+ response
1975
2499
  });
1976
2500
  }
1977
2501
  /** Per-minute limits: one runaway error can't flood the queue, the network or your database. */
@@ -1998,7 +2522,7 @@ var DebugClient = class {
1998
2522
  }
1999
2523
  /** Queue without sampling (sessions must be complete for crash-free rates to be right). */
2000
2524
  push(e) {
2001
- if (!this.ready) return;
2525
+ if (!this.ready || this.closed && !this.closing) return;
2002
2526
  let out = e.type === "error" || e.type === "event" ? this.withTags(e) : e;
2003
2527
  if (this.opts.beforeSend) {
2004
2528
  try {
@@ -2198,7 +2722,9 @@ var DebugClient = class {
2198
2722
  void this.flush();
2199
2723
  }
2200
2724
  },
2201
- ignored: (url) => this.isIgnored(url)
2725
+ ignored: (url) => this.isIgnored(url),
2726
+ wantsBody: (status, url) => this.isFailedStatus(status, url),
2727
+ capturesBodies: () => !!this.bodiesOption()
2202
2728
  };
2203
2729
  }
2204
2730
  isIgnored(url) {
@@ -2207,26 +2733,96 @@ var DebugClient = class {
2207
2733
  if (url.includes(ep) || /\/symbolicate\b|\/logs(?:\?|$)/.test(url)) return true;
2208
2734
  return (this.opts.network?.ignoreUrls ?? []).some((p2) => typeof p2 === "string" ? url.includes(p2) : p2.test(url));
2209
2735
  }
2736
+ isFailedStatus(status, rawUrl) {
2737
+ try {
2738
+ return (this.opts.network?.isFailure ?? ((s) => s >= 500))(status, normaliseUrl(rawUrl));
2739
+ } catch {
2740
+ return false;
2741
+ }
2742
+ }
2743
+ /**
2744
+ * Records one request: a breadcrumb now, in call order, and an error for a failure. When the
2745
+ * body is still being read (fetch), returns a function that adds what the backend said to the
2746
+ * breadcrumb and then reports the error, since an error is sent as soon as it is queued.
2747
+ */
2210
2748
  recordRequest(r) {
2211
2749
  if (!this.ready) return;
2212
2750
  const net = this.opts.network ?? {};
2213
2751
  const url = normaliseUrl(r.url);
2214
2752
  const ms = Math.round(r.durationMs);
2215
- const failed = r.status === void 0 ? !r.aborted : (net.isFailure ?? ((s) => s >= 500))(r.status, url);
2753
+ const failed = r.status === void 0 ? !r.aborted : this.isFailedStatus(r.status, r.url);
2216
2754
  const slow = ms >= (net.slowMs ?? 3e3);
2217
- const outcome = r.aborted ? "aborted" : r.timedOut ? "timed out" : r.status !== void 0 ? String(r.status) : "failed";
2218
- this.breadcrumb("network", `${r.method} ${url} \u2192 ${outcome} (${ms}ms)`, { status: r.status ?? null, durationMs: ms }, failed ? "error" : slow ? "warning" : "info");
2755
+ const [ended, outcome] = r.aborted ? ["aborted", "aborted"] : r.timedOut ? ["timed out", "unreachable"] : r.status !== void 0 ? [String(r.status), "answered"] : ["failed", "unreachable"];
2756
+ const name = nameRequest(r.url, net.baseUrls);
2757
+ const data = {
2758
+ service: name.service,
2759
+ path: name.path,
2760
+ method: r.method,
2761
+ status: r.status ?? null,
2762
+ durationMs: ms,
2763
+ outcome,
2764
+ ...failed && readProblemDetails(r.responseBody)
2765
+ };
2766
+ const crumb = this.addCrumb("network", `${r.method} ${name.matched ? name.path : url} \u2192 ${ended} (${ms}ms)`, data, failed ? "error" : slow ? "warning" : "info");
2219
2767
  if (!r.aborted) this.timeRequest(`${r.method} ${url}`, ms, failed);
2220
2768
  if (!failed) return;
2221
2769
  const flow = net.flows?.find(([p2]) => typeof p2 === "string" ? url.includes(p2) : p2.test(url))?.[1];
2222
2770
  const cause = r.error ? normaliseError(r.error) : void 0;
2223
2771
  const message = r.status !== void 0 ? `${r.method} ${url} responded ${r.status}` : `${r.method} ${url} ${r.timedOut ? "timed out" : "failed"}${cause ? `: ${cause.message}` : ""}`;
2224
- const frames = parseStack(r.stack).slice(1);
2225
- this.captureError(
2226
- { name: r.status !== void 0 ? "HttpError" : "NetworkError", message, stack: r.stack, frames },
2227
- { flow, handled: true, tags: { source: "network" } },
2228
- { method: r.method, url, status: r.status, durationMs: ms }
2229
- );
2772
+ const frames = markLibraryFrames(parseStack(r.stack).slice(1));
2773
+ const trail = [...this.crumbs];
2774
+ const bodies = this.bodiesOption();
2775
+ if (bodies) data.hasBodies = true;
2776
+ const report = (responseBody = r.responseBody) => {
2777
+ const http = bodies ? this.describeFailedCall(r, responseBody, bodies) : void 0;
2778
+ this.captureError(
2779
+ { name: r.status !== void 0 ? "HttpError" : "NetworkError", message, stack: r.stack, frames },
2780
+ { flow, handled: true, tags: { source: "network" } },
2781
+ { method: r.method, url, status: r.status, durationMs: ms, ...http?.request },
2782
+ trail,
2783
+ http?.response
2784
+ );
2785
+ };
2786
+ if (!r.bodyPending) return report();
2787
+ let done = false;
2788
+ const finish = (responseBody) => {
2789
+ if (done) return;
2790
+ done = true;
2791
+ this.pendingReports.delete(finishNow);
2792
+ const backend = readProblemDetails(responseBody);
2793
+ if (backend) crumb.data = { ...crumb.data, ...backend };
2794
+ report(responseBody);
2795
+ };
2796
+ const finishNow = () => finish();
2797
+ this.pendingReports.add(finishNow);
2798
+ return (responseBody) => finish(responseBody);
2799
+ }
2800
+ /** `network.bodies` when it is on, else undefined: the one place that decides. */
2801
+ bodiesOption() {
2802
+ const b = this.opts.network?.bodies;
2803
+ return b?.onFailure ? b : void 0;
2804
+ }
2805
+ /** A failed call's request and response, redacted and cut, for `network.bodies`. Never throws. */
2806
+ describeFailedCall(r, responseBody, bodies) {
2807
+ try {
2808
+ const max = bodies.maxChars ?? MAX_CAPTURED_BODY;
2809
+ const redact = bodies.redact ?? {};
2810
+ const rawQuery = /\?([^#]*)/.exec(r.url)?.[1];
2811
+ const request = {
2812
+ query: rawQuery ? redactText(rawQuery, redact).slice(0, max) : void 0,
2813
+ headers: redactHeaders(r.requestHeaders, redact),
2814
+ ...bodyOf(r.requestBody, r.requestBinary, max, redact)
2815
+ };
2816
+ const response = r.status === void 0 ? void 0 : {
2817
+ status: r.status,
2818
+ headers: redactHeaders(r.responseHeaders, redact),
2819
+ ...bodyOf(responseBody, r.responseBinary, max, redact)
2820
+ };
2821
+ return { request, response };
2822
+ } catch (err) {
2823
+ this.log("couldn't describe the failed call", err);
2824
+ return { request: {} };
2825
+ }
2230
2826
  }
2231
2827
  log(...args) {
2232
2828
  if (this.opts?.debug) console.warn("[deBug]", ...args);
@@ -2255,13 +2851,13 @@ function resolveAuto(o) {
2255
2851
  sessions: pick("sessions")
2256
2852
  };
2257
2853
  }
2258
- var hasNewFields = (events) => events.some((e) => e.type === "session" || e.type === "error" && e.request);
2854
+ var hasNewFields = (events) => events.some((e) => e.type === "session" || e.type === "error" && (e.request || e.response));
2259
2855
  function toLegacy(events) {
2260
2856
  const out = [];
2261
2857
  for (const e of events) {
2262
2858
  if (e.type === "session" || e.type === "metric") continue;
2263
- if (e.type === "error" && e.request) {
2264
- const { request: _r, ...rest } = e;
2859
+ if (e.type === "error" && (e.request || e.response)) {
2860
+ const { request: _r, response: _s, ...rest } = e;
2265
2861
  out.push(rest);
2266
2862
  } else out.push(e);
2267
2863
  }