@refactorlabs/recount 0.11.0 → 0.11.2

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.cjs CHANGED
@@ -12,6 +12,30 @@ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read fr
12
12
  var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
13
13
  var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value);
14
14
  var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
15
+ var __privateWrapper = (obj, member, setter, getter) => ({
16
+ set _(value) {
17
+ __privateSet(obj, member, value);
18
+ },
19
+ get _() {
20
+ return __privateGet(obj, member, getter);
21
+ }
22
+ });
23
+
24
+ // src/lib/error.ts
25
+ var RecountError = class extends Error {
26
+ constructor(status, message) {
27
+ super(message);
28
+ this.name = "RecountError";
29
+ this.status = status;
30
+ }
31
+ };
32
+ function errorText(err) {
33
+ try {
34
+ return err instanceof Error ? err.message : String(err);
35
+ } catch {
36
+ return "unknown error";
37
+ }
38
+ }
15
39
 
16
40
  // src/lib/http.ts
17
41
  var HTTP_METHODS = /* @__PURE__ */ new Set(["GET", "POST", "PUT", "PATCH", "DELETE"]);
@@ -240,6 +264,11 @@ async function executeFetch(input, init2, recordSpan) {
240
264
 
241
265
  // src/lib/decimal.ts
242
266
  var DECIMAL = /^-?(\d+(\.\d+)?|\.\d+)$/;
267
+ var SIGNIFICANT_DIGITS = 15;
268
+ function withoutFloatNoise(n) {
269
+ if (!Number.isFinite(n) || Number.isInteger(n)) return n === 0 ? 0 : n;
270
+ return Number(n.toPrecision(SIGNIFICANT_DIGITS));
271
+ }
243
272
  function decimalText(n) {
244
273
  if (!Number.isFinite(n)) return void 0;
245
274
  if (Object.is(n, -0) || n === 0) return "0";
@@ -407,7 +436,7 @@ function isValidKey(key) {
407
436
  return KEY.test(key) && !RESERVED.has(key);
408
437
  }
409
438
  var _key, _options, _ops, _built, _CalculationBuilder_instances, push_fn, kindLine_fn;
410
- var CalculationBuilder = class {
439
+ var _CalculationBuilder = class _CalculationBuilder {
411
440
  constructor(key, options = {}) {
412
441
  __privateAdd(this, _CalculationBuilder_instances);
413
442
  __privateAdd(this, _key);
@@ -518,7 +547,20 @@ var CalculationBuilder = class {
518
547
  /** The calculation as it's sent. Attach calls build it for you. */
519
548
  build() {
520
549
  const { calculation: calculation2 } = this.compile();
521
- return calculation2 ? structuredClone(calculation2) : { version: 1, key: __privateGet(this, _key), lines: [] };
550
+ return calculation2 ? structuredClone(calculation2) : {
551
+ version: 1,
552
+ key: repairKey(__privateGet(this, _key), "calculation", /* @__PURE__ */ new Set(), [], ""),
553
+ lines: []
554
+ };
555
+ }
556
+ /**
557
+ * @internal A copy holding the steps so far, so adding to this builder
558
+ * doesn't change it. Cheap: nothing is built.
559
+ */
560
+ snapshot() {
561
+ const copy = new _CalculationBuilder(__privateGet(this, _key), copyData(__privateGet(this, _options)));
562
+ for (const op of __privateGet(this, _ops)) __privateGet(copy, _ops).push(copyData(op));
563
+ return copy;
522
564
  }
523
565
  /** @internal Builds once, never throws. */
524
566
  compile() {
@@ -529,7 +571,7 @@ var CalculationBuilder = class {
529
571
  __privateSet(this, _built, {
530
572
  calculation: void 0,
531
573
  problems: [
532
- `${String(__privateGet(this, _key))}: couldn't be built (${err instanceof Error ? err.message : String(err)})`
574
+ `${keyText(__privateGet(this, _key))}: couldn't be built (${errorText(err)})`
533
575
  ]
534
576
  });
535
577
  }
@@ -553,6 +595,28 @@ kindLine_fn = function(kind, key, label, formula, options) {
553
595
  spec: { key, label, kind, formula: formula ?? null, options }
554
596
  });
555
597
  };
598
+ var CalculationBuilder = _CalculationBuilder;
599
+ function copyData(value, seen = /* @__PURE__ */ new Set()) {
600
+ if (typeof value !== "object" || value === null || seen.has(value)) {
601
+ return value;
602
+ }
603
+ if (Array.isArray(value)) {
604
+ seen.add(value);
605
+ const out2 = value.map((v) => copyData(v, seen));
606
+ seen.delete(value);
607
+ return out2;
608
+ }
609
+ if (!isPlainObject(value)) return value;
610
+ seen.add(value);
611
+ const out = Object.fromEntries(
612
+ Object.entries(value).map(([k, v]) => [k, copyData(v, seen)])
613
+ );
614
+ seen.delete(value);
615
+ return out;
616
+ }
617
+ function isRedacted(value) {
618
+ return typeof value === "object" && value !== null && value.__redacted === true;
619
+ }
556
620
  function calculation(key, options) {
557
621
  return new CalculationBuilder(key, options);
558
622
  }
@@ -620,6 +684,14 @@ function compile(rawKey, options, ops) {
620
684
  for (const op of ops) {
621
685
  if (op.type === "input") addInput(s, op.key, op.value, op.options ?? {});
622
686
  }
687
+ if (s.inputs.length > MAX_INPUTS) {
688
+ problems.push(
689
+ `${key}: ${s.inputs.length} inputs; only the first ${MAX_INPUTS} are sent`
690
+ );
691
+ s.inputs.length = MAX_INPUTS;
692
+ s.inputKeys = new Set(s.inputs.map((input) => input.key));
693
+ s.taken = new Set(s.inputKeys);
694
+ }
623
695
  for (const op of ops) {
624
696
  switch (op.type) {
625
697
  case "line":
@@ -654,12 +726,6 @@ function compile(rawKey, options, ops) {
654
726
  }
655
727
  }
656
728
  }
657
- if (s.inputs.length > MAX_INPUTS) {
658
- problems.push(
659
- `${key}: ${s.inputs.length} inputs; only the first ${MAX_INPUTS} are sent`
660
- );
661
- s.inputs.length = MAX_INPUTS;
662
- }
663
729
  if (s.lines.length > MAX_LINES) {
664
730
  problems.push(
665
731
  `${key}: ${s.lines.length} lines; only the first ${MAX_LINES} are sent`
@@ -802,7 +868,10 @@ function addLine(s, spec) {
802
868
  s.problems
803
869
  );
804
870
  const expected = expectedOf(options.expected, at, s.problems);
805
- if (expected !== void 0) line.expected = expected;
871
+ if (expected !== void 0) {
872
+ if (isRedacted(line.value)) expected.value = REDACTED;
873
+ line.expected = expected;
874
+ }
806
875
  const tolerance = toleranceOf(
807
876
  options.tolerance,
808
877
  `${at}: tolerance`,
@@ -856,6 +925,9 @@ function addTiers(s, rawKey, options) {
856
925
  `${s.calcKey}: tiers`
857
926
  );
858
927
  const at = `${s.calcKey}.${key}`;
928
+ if (overflow !== void 0 && overflow !== "none" && overflow !== "last") {
929
+ s.problems.push(`${at}: overflow is 'none' or 'last'; using 'none'`);
930
+ }
859
931
  if (!Array.isArray(bands) || bands.length === 0) {
860
932
  s.problems.push(`${at}: tiers need at least one band`);
861
933
  s.taken.delete(key);
@@ -890,7 +962,13 @@ function addTiers(s, rawKey, options) {
890
962
  const formula = p === void 0 || p === 1 || p === "1" ? amount : `${amount} * ${operandText(p)}`;
891
963
  const range = size === null ? before === "0" ? `all${unitText}${perText}` : `over ${before}${unitText}${perText}` : i === 0 ? `first ${size}${unitText}${perText}` : `next ${size}${unitText}${perText}`;
892
964
  const bandLabel = band?.label ?? `${base} tier ${n} (${range})`;
893
- const bandKey = `${key}_${n}`;
965
+ const wanted = withSuffix(key, `_${n}`);
966
+ const bandKey = unique(wanted, s.taken);
967
+ if (bandKey !== wanted) {
968
+ s.problems.push(
969
+ `${at}: band ${n}'s key "${wanted}" is taken; sent as "${bandKey}"`
970
+ );
971
+ }
894
972
  const tooLong = formula.length > MAX_FORMULA;
895
973
  if (tooLong) {
896
974
  s.problems.push(
@@ -911,7 +989,11 @@ function addTiers(s, rawKey, options) {
911
989
  rateUnit: subtotalOptions.rateUnit
912
990
  },
913
991
  tags,
914
- taxFree
992
+ taxFree,
993
+ // A redacted subtotal would be the sum of the bands' values.
994
+ ...(subtotalOptions.redact || isRedacted(value)) && {
995
+ redact: true
996
+ }
915
997
  }
916
998
  })
917
999
  );
@@ -1093,7 +1175,7 @@ function cleanValue(value, at, problems) {
1093
1175
  );
1094
1176
  return null;
1095
1177
  }
1096
- return Object.is(value, -0) ? 0 : value;
1178
+ return withoutFloatNoise(value);
1097
1179
  }
1098
1180
  if (typeof value === "string") {
1099
1181
  return text(value, MAX_TEXT_VALUE, at, problems);
@@ -1105,7 +1187,9 @@ function cleanValue(value, at, problems) {
1105
1187
  }
1106
1188
  const decimal = decimalObjectText(value);
1107
1189
  if (decimal !== void 0) return decimal;
1108
- problems.push(`${at}: a ${typeof value} isn't a value; left out`);
1190
+ problems.push(
1191
+ `${at}: ${typeof value === "object" ? "an object" : `a ${typeof value}`} isn't a value; left out`
1192
+ );
1109
1193
  return void 0;
1110
1194
  }
1111
1195
  function operandOf(value, at, problems) {
@@ -1117,7 +1201,7 @@ function operandOf(value, at, problems) {
1117
1201
  problems.push(`${at}: ${value} can't be sent; sent as not calculated`);
1118
1202
  return null;
1119
1203
  }
1120
- return Object.is(value, -0) ? 0 : value;
1204
+ return withoutFloatNoise(value);
1121
1205
  }
1122
1206
  if (typeof value === "string") return formulaText(value, at, problems);
1123
1207
  const decimal = decimalObjectText(value);
@@ -1141,7 +1225,7 @@ function formulaText(formula, at, problems) {
1141
1225
  }
1142
1226
  function sizeText(value, at, problems) {
1143
1227
  if (typeof value === "number" && Number.isFinite(value) && value >= 0) {
1144
- return decimalText(value);
1228
+ return decimalText(withoutFloatNoise(value));
1145
1229
  }
1146
1230
  const text2 = typeof value === "string" ? value.trim() : decimalObjectText(value);
1147
1231
  if (text2 !== void 0 && isDecimalText(text2) && !text2.startsWith("-")) {
@@ -1343,16 +1427,35 @@ function repairKey(given, label, taken, problems, at) {
1343
1427
  taken.add(key);
1344
1428
  return key;
1345
1429
  }
1430
+ function withSuffix(base, suffix) {
1431
+ const room = MAX_KEY - suffix.length;
1432
+ if (base.length <= room) return base + suffix;
1433
+ return base.slice(0, room).replace(/_+$/, "") + suffix;
1434
+ }
1435
+ var nextSuffix = /* @__PURE__ */ new WeakMap();
1346
1436
  function unique(base, taken) {
1347
1437
  if (!taken.has(base)) return base;
1348
- for (let n = 2; ; n++) {
1349
- const key = `${base}_${n}`;
1350
- if (!taken.has(key)) return key;
1438
+ let next = nextSuffix.get(taken);
1439
+ if (!next) {
1440
+ next = /* @__PURE__ */ new Map();
1441
+ nextSuffix.set(taken, next);
1442
+ }
1443
+ for (let n = next.get(base) ?? 2; ; n++) {
1444
+ const key = withSuffix(base, `_${n}`);
1445
+ if (!taken.has(key)) {
1446
+ next.set(base, n);
1447
+ return key;
1448
+ }
1351
1449
  }
1352
1450
  }
1353
1451
  function buildCalculations(calcs) {
1354
1452
  const problems = [];
1355
- const list = Array.isArray(calcs) ? calcs : [calcs];
1453
+ let list;
1454
+ try {
1455
+ list = itemsOf(calcs);
1456
+ } catch (err) {
1457
+ list = [failed(`the calculations couldn't be read (${errorText(err)})`)];
1458
+ }
1356
1459
  const calculations = [];
1357
1460
  const keys = /* @__PURE__ */ new Set();
1358
1461
  let rows = 0;
@@ -1364,7 +1467,7 @@ function buildCalculations(calcs) {
1364
1467
  problems.push("a calculation couldn't be built and was left out");
1365
1468
  continue;
1366
1469
  }
1367
- problems.push(...built.problems);
1470
+ for (const problem of built.problems) problems.push(problem);
1368
1471
  const calc = built.calculation;
1369
1472
  if (!calc) continue;
1370
1473
  if (calculations.length === MAX_CALCULATIONS) {
@@ -1395,6 +1498,56 @@ function buildCalculations(calcs) {
1395
1498
  }
1396
1499
  return { calculations, problems };
1397
1500
  }
1501
+ function itemsOf(calcs) {
1502
+ if (Array.isArray(calcs)) return calcs;
1503
+ if (calcs instanceof Map) return [...calcs.values()];
1504
+ if (!isBuilder(calcs) && typeof calcs === "object" && calcs !== null && typeof calcs[Symbol.iterator] === "function") {
1505
+ const items = [];
1506
+ try {
1507
+ for (const item of calcs) items.push(item);
1508
+ } catch (err) {
1509
+ items.push(
1510
+ failed(
1511
+ `the list of calculations couldn't be read to the end (${errorText(err)}); kept the ${items.length} read before it`
1512
+ )
1513
+ );
1514
+ }
1515
+ return items;
1516
+ }
1517
+ return [calcs];
1518
+ }
1519
+ function failed(problem) {
1520
+ return { compile: () => ({ calculation: void 0, problems: [problem] }) };
1521
+ }
1522
+ function keyText(key) {
1523
+ try {
1524
+ return String(key);
1525
+ } catch {
1526
+ return "calculation";
1527
+ }
1528
+ }
1529
+ function snapshotCalculations(calcs) {
1530
+ let items;
1531
+ try {
1532
+ items = itemsOf(calcs);
1533
+ } catch (err) {
1534
+ return [
1535
+ failed(
1536
+ `the calculations couldn't be read (${errorText(err)})`
1537
+ )
1538
+ ];
1539
+ }
1540
+ return items.map((item) => {
1541
+ try {
1542
+ if (!isBuilder(item)) {
1543
+ return fromPlain(item).snapshot();
1544
+ }
1545
+ return typeof item.snapshot === "function" ? item.snapshot() : item;
1546
+ } catch {
1547
+ return item;
1548
+ }
1549
+ });
1550
+ }
1398
1551
  function isBuilder(item) {
1399
1552
  return typeof item === "object" && item !== null && typeof item.compile === "function";
1400
1553
  }
@@ -1431,9 +1584,22 @@ var units = {
1431
1584
 
1432
1585
  // src/trace.ts
1433
1586
  var NOOP_RESULT = { traceId: "" };
1587
+ var MAX_SPANS = 500;
1588
+ function describe(value) {
1589
+ try {
1590
+ return typeof value === "string" ? JSON.stringify(value) : String(value);
1591
+ } catch {
1592
+ return "an unreadable value";
1593
+ }
1594
+ }
1434
1595
  function calculationSpanOptions(calcs, options, log, name) {
1435
1596
  const { side, ...rest } = options ?? {};
1436
1597
  const { calculations, problems } = buildCalculations(calcs);
1598
+ if (side !== void 0 && side !== "input" && side !== "output") {
1599
+ problems.push(
1600
+ `side is 'input' or 'output', not ${describe(side)}; using 'output'`
1601
+ );
1602
+ }
1437
1603
  for (const problem of problems) {
1438
1604
  log(`calculation span=${name} ${problem}`);
1439
1605
  }
@@ -1466,10 +1632,16 @@ var SpanGroup = class {
1466
1632
  }
1467
1633
  /** A table span holding these calculations, as a child of the group. */
1468
1634
  calculation(name, calcs, options) {
1635
+ const snapshot = snapshotCalculations(calcs);
1636
+ let opts = options;
1637
+ try {
1638
+ opts = options && { ...options };
1639
+ } catch {
1640
+ }
1469
1641
  const item = {
1470
1642
  type: "table",
1471
1643
  name,
1472
- calculations: (log) => calculationSpanOptions(calcs, options, log, name)
1644
+ calculations: (log) => calculationSpanOptions(snapshot, opts, log, name)
1473
1645
  };
1474
1646
  __privateGet(this, _buffer).push(item);
1475
1647
  __privateSet(this, _lastSpan, item);
@@ -1508,7 +1680,8 @@ var SpanGroup = class {
1508
1680
  let built = {};
1509
1681
  try {
1510
1682
  built = calculations(log);
1511
- } catch {
1683
+ } catch (err) {
1684
+ log(`calculation span=${name} couldn't be built (${errorText(err)})`);
1512
1685
  }
1513
1686
  push(type, name, {
1514
1687
  ...built,
@@ -1522,7 +1695,7 @@ var SpanGroup = class {
1522
1695
  };
1523
1696
  _buffer = new WeakMap();
1524
1697
  _lastSpan = new WeakMap();
1525
- var _client, _name, _options2, _spans, _startTime, _disabled, _log, _metadata, _environment, _lastSpan2, _Trace_instances, pushSpan_fn, applyRedaction_fn;
1698
+ var _client, _name, _options2, _spans, _startTime, _disabled, _log, _metadata, _environment, _lastSpan2, _nonGroupSpans, _Trace_instances, pushSpan_fn, makeSpan_fn, applyRedaction_fn;
1526
1699
  var Trace = class {
1527
1700
  constructor(client, name, options = {}, disabled = false, log = () => {
1528
1701
  }) {
@@ -1537,6 +1710,7 @@ var Trace = class {
1537
1710
  __privateAdd(this, _metadata);
1538
1711
  __privateAdd(this, _environment);
1539
1712
  __privateAdd(this, _lastSpan2);
1713
+ __privateAdd(this, _nonGroupSpans, 0);
1540
1714
  __privateSet(this, _client, client);
1541
1715
  __privateSet(this, _name, name);
1542
1716
  __privateSet(this, _options2, options);
@@ -1554,29 +1728,30 @@ var Trace = class {
1554
1728
  }
1555
1729
  group(name, builder, options) {
1556
1730
  if (!__privateGet(this, _disabled)) {
1557
- const groupOrder = __privateGet(this, _spans).length;
1558
1731
  __privateGet(this, _log).call(this, `span type=group name=${name}`);
1559
1732
  const g = new SpanGroup();
1560
1733
  try {
1561
1734
  builder(g);
1562
- } catch {
1735
+ } catch (err) {
1736
+ __privateGet(this, _log).call(this, `span type=group name=${name} builder threw (${errorText(err)}); sending what it added`);
1563
1737
  }
1564
- __privateGet(this, _spans).push({
1738
+ const groupOrder = __privateGet(this, _spans).length;
1739
+ const group = {
1565
1740
  type: "group",
1566
1741
  name,
1567
1742
  order: groupOrder,
1568
1743
  ...options?.description !== void 0 && {
1569
1744
  description: options.description
1570
1745
  }
1571
- });
1572
- const spanCountBeforeFlush = __privateGet(this, _spans).length;
1746
+ };
1747
+ __privateGet(this, _spans).push(group);
1573
1748
  g._flush(
1574
1749
  (type, spanName, opts) => __privateMethod(this, _Trace_instances, pushSpan_fn).call(this, type, spanName, opts, groupOrder),
1575
1750
  options,
1576
1751
  __privateGet(this, _log)
1577
1752
  );
1578
- if (__privateGet(this, _spans).length === spanCountBeforeFlush) {
1579
- __privateGet(this, _spans).splice(groupOrder, 1);
1753
+ if (__privateGet(this, _spans)[__privateGet(this, _spans).length - 1] === group) {
1754
+ __privateGet(this, _spans).pop();
1580
1755
  __privateGet(this, _log).call(this, `span type=group name=${name} dropped (no children)`);
1581
1756
  }
1582
1757
  }
@@ -1605,7 +1780,8 @@ var Trace = class {
1605
1780
  let opts;
1606
1781
  try {
1607
1782
  opts = calculationSpanOptions(calcs, options, __privateGet(this, _log), name);
1608
- } catch {
1783
+ } catch (err) {
1784
+ __privateGet(this, _log).call(this, `calculation span=${name} couldn't be built (${errorText(err)})`);
1609
1785
  return this;
1610
1786
  }
1611
1787
  return this.span("table", name, opts);
@@ -1660,6 +1836,7 @@ _log = new WeakMap();
1660
1836
  _metadata = new WeakMap();
1661
1837
  _environment = new WeakMap();
1662
1838
  _lastSpan2 = new WeakMap();
1839
+ _nonGroupSpans = new WeakMap();
1663
1840
  _Trace_instances = new WeakSet();
1664
1841
  pushSpan_fn = function(type, name, options, parentOrder) {
1665
1842
  if (type !== "group" && type !== "message") {
@@ -1668,6 +1845,25 @@ pushSpan_fn = function(type, name, options, parentOrder) {
1668
1845
  return;
1669
1846
  }
1670
1847
  }
1848
+ if (type !== "group" && __privateGet(this, _nonGroupSpans) >= MAX_SPANS) {
1849
+ __privateGet(this, _log).call(this, `span type=${type} name=${name} dropped (a trace holds ${MAX_SPANS} spans)`);
1850
+ __privateSet(this, _lastSpan2, void 0);
1851
+ return;
1852
+ }
1853
+ let span;
1854
+ try {
1855
+ span = __privateMethod(this, _Trace_instances, makeSpan_fn).call(this, type, name, options, parentOrder);
1856
+ } catch (err) {
1857
+ __privateGet(this, _log).call(this, `span type=${type} name=${name} dropped (couldn't be recorded: ${errorText(err)})`);
1858
+ __privateSet(this, _lastSpan2, void 0);
1859
+ return;
1860
+ }
1861
+ __privateGet(this, _spans).push(span);
1862
+ if (type !== "group") __privateWrapper(this, _nonGroupSpans)._++;
1863
+ __privateSet(this, _lastSpan2, span);
1864
+ __privateGet(this, _log).call(this, `span type=${type} name=${name}`);
1865
+ };
1866
+ makeSpan_fn = function(type, name, options, parentOrder) {
1671
1867
  let span;
1672
1868
  if (type === "message") {
1673
1869
  span = {
@@ -1695,9 +1891,7 @@ pushSpan_fn = function(type, name, options, parentOrder) {
1695
1891
  ...__privateMethod(this, _Trace_instances, applyRedaction_fn).call(this, type, options)
1696
1892
  };
1697
1893
  }
1698
- __privateGet(this, _spans).push(span);
1699
- __privateSet(this, _lastSpan2, span);
1700
- __privateGet(this, _log).call(this, `span type=${type} name=${name}`);
1894
+ return span;
1701
1895
  };
1702
1896
  applyRedaction_fn = function(type, options) {
1703
1897
  if (!options) return {};
@@ -1741,15 +1935,6 @@ applyRedaction_fn = function(type, options) {
1741
1935
  return { ...rest, input, output };
1742
1936
  };
1743
1937
 
1744
- // src/lib/error.ts
1745
- var RecountError = class extends Error {
1746
- constructor(status, message) {
1747
- super(message);
1748
- this.name = "RecountError";
1749
- this.status = status;
1750
- }
1751
- };
1752
-
1753
1938
  // src/client.ts
1754
1939
  var DEFAULT_API_URL = "https://api.recount.refactor.gg";
1755
1940
  var NOOP_RESULT2 = { traceId: "" };
@@ -1775,6 +1960,59 @@ function retryDelayMs(res, attempt) {
1775
1960
  }
1776
1961
  return BASE_RETRY_MS * 2 ** (attempt - 1);
1777
1962
  }
1963
+ function bigintAsString(_key3, value) {
1964
+ return typeof value === "bigint" ? value.toString() : value;
1965
+ }
1966
+ function serialize(payload, log) {
1967
+ try {
1968
+ return JSON.stringify(payload);
1969
+ } catch {
1970
+ }
1971
+ try {
1972
+ return JSON.stringify(payload, bigintAsString);
1973
+ } catch {
1974
+ }
1975
+ const sendable = payload.spans.filter((span) => {
1976
+ try {
1977
+ JSON.stringify(span, bigintAsString);
1978
+ return true;
1979
+ } catch (err) {
1980
+ log(
1981
+ `span type=${span.type} name=${span.name} dropped (can't be sent as JSON: ${errorText(err)})`
1982
+ );
1983
+ return false;
1984
+ }
1985
+ });
1986
+ const spans = sendable.filter(
1987
+ (span) => span.type !== "group" || sendable.some((child) => child.parentOrder === span.order)
1988
+ );
1989
+ if (spans.length === 0) {
1990
+ log("ingest serialize error: no span can be sent as JSON");
1991
+ return void 0;
1992
+ }
1993
+ let error;
1994
+ try {
1995
+ return JSON.stringify({ ...payload, spans }, bigintAsString);
1996
+ } catch (err) {
1997
+ error = err;
1998
+ }
1999
+ if (payload.metadata !== void 0) {
2000
+ try {
2001
+ const body = JSON.stringify(
2002
+ { ...payload, spans, metadata: void 0 },
2003
+ bigintAsString
2004
+ );
2005
+ log(
2006
+ `ingest metadata dropped (can't be sent as JSON: ${errorText(error)})`
2007
+ );
2008
+ return body;
2009
+ } catch (err) {
2010
+ error = err;
2011
+ }
2012
+ }
2013
+ log(`ingest serialize error: ${errorText(error)}`);
2014
+ return void 0;
2015
+ }
1778
2016
  var _apiKey, _apiUrl, _environment2, _disabled2, _timeoutMs, _log2;
1779
2017
  var Recount = class {
1780
2018
  constructor(options = {}) {
@@ -1818,11 +2056,8 @@ var Recount = class {
1818
2056
  return NOOP_RESULT2;
1819
2057
  }
1820
2058
  __privateGet(this, _log2).call(this, `ingest name=${payload.name} spans=${payload.spans.length}`);
1821
- let body;
1822
- try {
1823
- body = JSON.stringify(payload);
1824
- } catch (err) {
1825
- __privateGet(this, _log2).call(this, `ingest serialize error: ${err instanceof Error ? err.message : String(err)}`);
2059
+ const body = serialize(payload, __privateGet(this, _log2));
2060
+ if (body === void 0) {
1826
2061
  return NOOP_RESULT2;
1827
2062
  }
1828
2063
  const headers = {
@@ -1855,7 +2090,8 @@ var Recount = class {
1855
2090
  }
1856
2091
  if (!res.ok) {
1857
2092
  const text2 = await res.text().catch(() => res.statusText);
1858
- __privateGet(this, _log2).call(this, `ingest error status=${res.status} message=${text2}`);
2093
+ const size = res.status === 413 ? ` bytes=${new TextEncoder().encode(body).length}` : "";
2094
+ __privateGet(this, _log2).call(this, `ingest error status=${res.status}${size} message=${text2}`);
1859
2095
  return NOOP_RESULT2;
1860
2096
  }
1861
2097
  let json;
@@ -1934,8 +2170,45 @@ function cleanCellValue(value) {
1934
2170
  }
1935
2171
  return value;
1936
2172
  }
1937
- function signOf(value, highlight) {
1938
- const n = typeof value === "number" ? value : typeof value === "string" && value.trim() !== "" ? Number(value) : NaN;
2173
+ function contentOf(value) {
2174
+ return typeof value === "object" && value !== null && (value.__cell === true || value.__cellSpan === true) ? value.value : value;
2175
+ }
2176
+ function numberOf(value) {
2177
+ if (typeof value === "number") return value;
2178
+ if (typeof value === "string" && value.trim() !== "") return Number(value);
2179
+ return NaN;
2180
+ }
2181
+ function shownAs(sent) {
2182
+ if (typeof sent !== "object" || sent === null || sent.__cell !== true) {
2183
+ return void 0;
2184
+ }
2185
+ const { format, currency, unit, places } = sent;
2186
+ const kind = format ?? (currency ? "money" : unit !== void 0 || places !== void 0 ? "number" : void 0);
2187
+ if (kind === void 0 || kind === "text") return void 0;
2188
+ return {
2189
+ places: kind === "integer" ? 0 : typeof places === "number" && Number.isInteger(places) && places >= 0 ? places : 2,
2190
+ percent: kind === "percent" || unit === "%" && !(kind === "money" && currency)
2191
+ };
2192
+ }
2193
+ function showsAsZero(n, places, percent) {
2194
+ const text2 = decimalText(n);
2195
+ if (text2 === void 0) return false;
2196
+ let [whole, fraction = ""] = text2.replace("-", "").split(".");
2197
+ if (percent) {
2198
+ whole += fraction.slice(0, 2).padEnd(2, "0");
2199
+ fraction = fraction.slice(2);
2200
+ }
2201
+ return /^0*$/.test(whole) && /^0*$/.test(fraction.slice(0, places)) && (fraction[places] ?? "0") < "5";
2202
+ }
2203
+ function signOf(sent, raw, highlight) {
2204
+ const shown = contentOf(sent);
2205
+ let n = numberOf(shown);
2206
+ const format = shownAs(sent);
2207
+ if (!Number.isNaN(n) && format && showsAsZero(n, format.places, format.percent)) {
2208
+ n = 0;
2209
+ }
2210
+ const fallsBack = shown !== null && shown !== void 0 && (typeof shown !== "string" || /\d/.test(shown));
2211
+ if (Number.isNaN(n) && fallsBack) n = numberOf(contentOf(raw));
1939
2212
  if (Number.isNaN(n)) return null;
1940
2213
  if (n > 0) return highlight.positive ?? null;
1941
2214
  if (n < 0) return highlight.negative ?? null;
@@ -2024,6 +2297,13 @@ var TableBuilder = class {
2024
2297
  /**
2025
2298
  * Colours a column's numbers (records) or a row (objects) by sign:
2026
2299
  * `.signHighlight('saving', { positive: 'success', negative: 'danger' })`.
2300
+ * A row takes the sign of the number shown, after `transformValues()`,
2301
+ * `.round()` and a format's places, as Recount shows it: money, number and
2302
+ * percent to 2 places unless given, an integer to none, and a percent times
2303
+ * 100. So -0.004 as money is zero, and 0.004 as a percent (0.40%) positive.
2304
+ * When what's shown is text with a number in it, such as `'$-5'`, it
2305
+ * takes the raw value's sign; a blank row, or text with no number such as
2306
+ * `'N/A'`, takes none.
2027
2307
  */
2028
2308
  signHighlight(key, highlight) {
2029
2309
  this._signHighlights[key] = highlight;
@@ -2148,24 +2428,25 @@ var TableBuilder = class {
2148
2428
  const order = this._pick;
2149
2429
  rows = order.filter((k) => rows.some(([rk]) => rk === k)).map((k) => rows.find(([rk]) => rk === k));
2150
2430
  }
2431
+ const sentValues = [];
2151
2432
  const finalRows = rows.map(([k, v]) => {
2152
2433
  const key = k;
2153
2434
  if (this._shouldRedact(key)) {
2435
+ sentValues.push(REDACTED);
2154
2436
  return [this._resolveLabel(key), REDACTED];
2155
2437
  }
2156
2438
  const transformed = this._valueTransforms[key] ? this._valueTransforms[key](v) : v;
2157
2439
  const format = this._formats[key];
2158
- if (format !== void 0 && isCellValue(transformed)) {
2159
- return [this._resolveLabel(key), cell(transformed, format)];
2160
- }
2161
- return [this._resolveLabel(key), this._finalValue(key, transformed)];
2440
+ const sent = format !== void 0 && isCellValue(transformed) ? cell(transformed, format) : this._finalValue(key, transformed);
2441
+ sentValues.push(sent);
2442
+ return [this._resolveLabel(key), sent];
2162
2443
  });
2163
2444
  const allRows = this._extraRows.length ? [...finalRows, ...this._extraRows.map((r) => r.cells)] : finalRows;
2164
2445
  const hasSigns = Object.keys(this._signHighlights).length > 0;
2165
- const rowHighlights = this._rowHighlightFn || hasSigns ? rows.map(([k, v]) => {
2446
+ const rowHighlights = this._rowHighlightFn || hasSigns ? rows.map(([k, v], i) => {
2166
2447
  const fromFn = this._rowHighlightFn ? this._rowHighlightFn({ [k]: v }) : null;
2167
2448
  const sign = this._signHighlights[k];
2168
- return fromFn ?? (sign && !this._shouldRedact(k) ? signOf(v, sign) : null);
2449
+ return fromFn ?? (sign && !this._shouldRedact(k) ? signOf(sentValues[i], v, sign) : null);
2169
2450
  }) : void 0;
2170
2451
  const allRowHighlights = this._mergeRowHighlights(
2171
2452
  rowHighlights,