@trafficwar/node 2.0.0 → 2.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,13 +2,14 @@
2
2
 
3
3
  Official, dependency-free TrafficWar server SDK for Node.js 22 and newer.
4
4
 
5
- > **Breaking change in 2.0.0:** `capture` now enqueues events for automatic
6
- > batching instead of waiting for an individual ingestion response.
7
-
8
5
  ## Install
9
6
 
10
7
  ```sh
11
8
  npm install @trafficwar/node
9
+ # or
10
+ pnpm add @trafficwar/node
11
+ # or
12
+ bun add @trafficwar/node
12
13
  ```
13
14
 
14
15
  ## Capture events
@@ -25,7 +26,6 @@ const trafficwar = new TrafficWar({
25
26
 
26
27
  trafficwar.capture({
27
28
  event: "checkout.completed",
28
- timestamp: new Date(),
29
29
  latency_ms: 184.2,
30
30
  status_code: 200,
31
31
  source: "checkout-api",
@@ -47,7 +47,8 @@ enqueues the input synchronously, then returns `void`; it does not return an
47
47
 
48
48
  `Date` timestamps are serialized as RFC3339 without changing the caller's
49
49
  object. String timestamps must be RFC3339; numeric timestamps are integer epoch
50
- milliseconds.
50
+ milliseconds. If `timestamp` is omitted, the SDK sets it to the current time at
51
+ capture.
51
52
 
52
53
  ## Automatic batching
53
54
 
@@ -72,6 +73,17 @@ const trafficwar = new TrafficWar({
72
73
  If enqueueing would exceed the configured queue limit, `capture` throws a
73
74
  `TrafficWarValidationError` and enqueues none of that call.
74
75
 
76
+ Set `debug: true` to print queue, flush, request, retry, and acknowledgement
77
+ diagnostics with `console.debug`. Debug logging is off by default and never
78
+ includes API keys or queued event payloads.
79
+
80
+ ```ts
81
+ const trafficwar = new TrafficWar({
82
+ apiKey: process.env.TRAFFICWAR_API_KEY!,
83
+ debug: true,
84
+ });
85
+ ```
86
+
75
87
  The SDK generates a process-monotonic RFC 9562 UUIDv7 `event_id` for each event
76
88
  that omits one. A caller may override it with any valid UUID. Caller-owned
77
89
  objects are never modified.
@@ -134,6 +146,8 @@ attempt, `flush`, or `close` retries that same batch, and explicit `flush` or
134
146
 
135
147
  - `apiKey` (required): TrafficWar server API key.
136
148
  - `baseUrl`: ingest origin. Defaults to `https://ingest.trafficwar.tech`.
149
+ - `debug`: print safe batch lifecycle diagnostics with `console.debug`.
150
+ Defaults to `false`.
137
151
  - `timeoutMs`: timeout for each attempt. Defaults to 30,000 ms, safely above
138
152
  TrafficWar's 10-second durable acknowledgement window.
139
153
  - `maxRetries`: retries after the first attempt. Defaults to 3.
package/dist/index.cjs CHANGED
@@ -309,6 +309,8 @@ function normalizeEvent(input, path, idempotencyKey) {
309
309
  `${path}.timestamp`,
310
310
  idempotencyKey
311
311
  );
312
+ } else {
313
+ normalized.timestamp = (/* @__PURE__ */ new Date()).toISOString();
312
314
  }
313
315
  if (Object.hasOwn(normalized, "latency_ms") && (typeof normalized.latency_ms !== "number" || !Number.isFinite(normalized.latency_ms))) {
314
316
  throw validationError(
@@ -448,7 +450,7 @@ function uuidv7() {
448
450
 
449
451
  // package.json
450
452
  var package_default = {
451
- version: "2.0.0"};
453
+ version: "2.1.1"};
452
454
 
453
455
  // src/client.ts
454
456
  var TRAFFICWAR_DEFAULT_BASE_URL = "https://ingest.trafficwar.tech";
@@ -537,6 +539,16 @@ function validateIntegerOption(name, value, fallback, minimum, maximum) {
537
539
  }
538
540
  return actual;
539
541
  }
542
+ function validateBooleanOption(name, value, fallback) {
543
+ const actual = value ?? fallback;
544
+ if (typeof actual !== "boolean") {
545
+ throw new TrafficWarValidationError(
546
+ `${name} must be a boolean`,
547
+ { path: `options.${name}` }
548
+ );
549
+ }
550
+ return actual;
551
+ }
540
552
  function validateCompression(value) {
541
553
  const actual = value ?? "auto";
542
554
  if (actual !== "auto" && actual !== "gzip" && actual !== "none") {
@@ -772,6 +784,7 @@ function parseSuccess(response, parsed, expectedCount, idempotencyKey) {
772
784
  }
773
785
  var TrafficWar = class {
774
786
  baseUrl;
787
+ debug;
775
788
  timeoutMs;
776
789
  maxRetries;
777
790
  compression;
@@ -801,6 +814,7 @@ var TrafficWar = class {
801
814
  }
802
815
  this.#apiKey = validateApiKey(options.apiKey);
803
816
  this.baseUrl = normalizeBaseUrl(options.baseUrl);
817
+ this.debug = validateBooleanOption("debug", options.debug, false);
804
818
  this.timeoutMs = validateIntegerOption(
805
819
  "timeoutMs",
806
820
  options.timeoutMs,
@@ -853,6 +867,23 @@ var TrafficWar = class {
853
867
  return globalThis.fetch(input, init);
854
868
  });
855
869
  this.#onError = options.onError;
870
+ this.#debugLog("client initialized", {
871
+ baseUrl: this.baseUrl,
872
+ compression: this.compression,
873
+ flushIntervalMs: this.flushIntervalMs,
874
+ maxQueueSize: this.maxQueueSize,
875
+ maxRetries: this.maxRetries,
876
+ timeoutMs: this.timeoutMs
877
+ });
878
+ }
879
+ #debugLog(message, details) {
880
+ if (!this.debug) {
881
+ return;
882
+ }
883
+ try {
884
+ console.debug(`[TrafficWar] ${message}`, details);
885
+ } catch {
886
+ }
856
887
  }
857
888
  capture(eventOrEvents) {
858
889
  if (this.#closed) {
@@ -919,8 +950,16 @@ var TrafficWar = class {
919
950
  this.#pendingEventIds.add(event.event_id);
920
951
  }
921
952
  this.#pendingCount += normalized.length;
953
+ this.#debugLog("events queued", {
954
+ added: normalized.length,
955
+ pending: this.#pendingCount
956
+ });
922
957
  if (this.#pendingCount >= TRAFFICWAR_MAX_BATCH_SIZE) {
923
958
  this.#clearTimer();
959
+ this.#debugLog("automatic flush triggered", {
960
+ pending: this.#pendingCount,
961
+ reason: "batch-size"
962
+ });
924
963
  this.#startBackgroundDrain();
925
964
  } else {
926
965
  this.#ensureTimer();
@@ -939,6 +978,9 @@ var TrafficWar = class {
939
978
  this.capture(events);
940
979
  }
941
980
  flush() {
981
+ this.#debugLog("manual flush requested", {
982
+ pending: this.#pendingCount
983
+ });
942
984
  if (this.#closePromise) {
943
985
  return this.#closePromise;
944
986
  }
@@ -952,6 +994,9 @@ var TrafficWar = class {
952
994
  if (this.#closePromise) {
953
995
  return this.#closePromise;
954
996
  }
997
+ this.#debugLog("close requested", {
998
+ pending: this.#pendingCount
999
+ });
955
1000
  this.#clearTimer();
956
1001
  this.#closing = true;
957
1002
  let closing;
@@ -968,6 +1013,10 @@ var TrafficWar = class {
968
1013
  } while (this.#pendingCount > 0);
969
1014
  this.#clearTimer();
970
1015
  this.#closed = true;
1016
+ this.#debugLog("client closed", {
1017
+ accepted,
1018
+ batches: batches.length
1019
+ });
971
1020
  return { accepted, batches };
972
1021
  } finally {
973
1022
  if (this.#closePromise === closing) {
@@ -990,10 +1039,18 @@ var TrafficWar = class {
990
1039
  if (this.#timer === timer) {
991
1040
  this.#timer = void 0;
992
1041
  }
1042
+ this.#debugLog("automatic flush triggered", {
1043
+ pending: this.#pendingCount,
1044
+ reason: "interval"
1045
+ });
993
1046
  this.#startBackgroundDrain();
994
1047
  }, this.flushIntervalMs);
995
1048
  timer.unref();
996
1049
  this.#timer = timer;
1050
+ this.#debugLog("flush timer scheduled", {
1051
+ delayMs: this.flushIntervalMs,
1052
+ pending: this.#pendingCount
1053
+ });
997
1054
  }
998
1055
  #clearTimer() {
999
1056
  if (this.#timer !== void 0) {
@@ -1044,8 +1101,24 @@ var TrafficWar = class {
1044
1101
  }
1045
1102
  let drain;
1046
1103
  drain = (async () => {
1104
+ this.#debugLog("flush started", {
1105
+ pending: this.#pendingCount
1106
+ });
1047
1107
  try {
1048
- return await this.#drain();
1108
+ const result = await this.#drain();
1109
+ this.#debugLog("flush completed", {
1110
+ accepted: result.accepted,
1111
+ batches: result.batches.length,
1112
+ pending: this.#pendingCount
1113
+ });
1114
+ return result;
1115
+ } catch (error) {
1116
+ this.#debugLog("flush failed", {
1117
+ errorMessage: error instanceof Error ? error.message : String(error),
1118
+ errorName: error instanceof Error ? error.name : typeof error,
1119
+ pending: this.#pendingCount
1120
+ });
1121
+ throw error;
1049
1122
  } finally {
1050
1123
  if (this.#drainPromise === drain) {
1051
1124
  this.#drainPromise = void 0;
@@ -1093,7 +1166,14 @@ var TrafficWar = class {
1093
1166
  this.compressionThresholdBytes
1094
1167
  );
1095
1168
  this.#queue.splice(0, count);
1096
- return { ...prepared, events, idempotencyKey };
1169
+ const batch = { ...prepared, events, idempotencyKey };
1170
+ this.#debugLog("batch prepared", {
1171
+ bodyBytes: prepared.body.byteLength,
1172
+ contentEncoding: prepared.contentEncoding ?? "identity",
1173
+ events: events.length,
1174
+ idempotencyKey
1175
+ });
1176
+ return batch;
1097
1177
  } catch (error) {
1098
1178
  if (!(error instanceof PreparedRequestTooLarge)) {
1099
1179
  throw error;
@@ -1143,6 +1223,13 @@ var TrafficWar = class {
1143
1223
  }
1144
1224
  );
1145
1225
  }
1226
+ this.#debugLog("request attempt", {
1227
+ attempt: attempt + 1,
1228
+ bodyBytes: batch.body.byteLength,
1229
+ events: batch.events.length,
1230
+ idempotencyKey: batch.idempotencyKey,
1231
+ maxAttempts: this.maxRetries + 1
1232
+ });
1146
1233
  let result;
1147
1234
  try {
1148
1235
  result = await executeAttempt(
@@ -1178,8 +1265,15 @@ var TrafficWar = class {
1178
1265
  }
1179
1266
  );
1180
1267
  }
1268
+ const delayMs = retryDelayMs(attempt, void 0);
1269
+ this.#debugLog("request retry scheduled", {
1270
+ attempt: attempt + 1,
1271
+ delayMs,
1272
+ idempotencyKey: batch.idempotencyKey,
1273
+ reason: failure.timedOut ? "timeout" : "transport"
1274
+ });
1181
1275
  try {
1182
- await sleep(retryDelayMs(attempt, void 0), signal);
1276
+ await sleep(delayMs, signal);
1183
1277
  } catch (cause) {
1184
1278
  throw new TrafficWarConnectionError(
1185
1279
  "TrafficWar request was aborted",
@@ -1196,18 +1290,32 @@ var TrafficWar = class {
1196
1290
  }
1197
1291
  const parsed = parseBody(result.text);
1198
1292
  if (result.response.ok) {
1199
- return parseSuccess(
1293
+ const ingest = parseSuccess(
1200
1294
  result.response,
1201
1295
  parsed,
1202
1296
  batch.events.length,
1203
1297
  batch.idempotencyKey
1204
1298
  );
1299
+ this.#debugLog("request accepted", {
1300
+ accepted: ingest.accepted,
1301
+ attempt: attempt + 1,
1302
+ idempotencyKey: batch.idempotencyKey,
1303
+ ingestId: ingest.ingestId
1304
+ });
1305
+ return ingest;
1205
1306
  }
1206
1307
  if (RETRYABLE_STATUSES.has(result.response.status) && attempt < this.maxRetries) {
1207
1308
  const retryAfter = retryAfterSeconds(result.response, parsed);
1208
1309
  if (retryAfter === void 0 || retryAfter <= MAX_RETRY_AFTER_SECONDS) {
1310
+ const delayMs = retryDelayMs(attempt, retryAfter);
1311
+ this.#debugLog("request retry scheduled", {
1312
+ attempt: attempt + 1,
1313
+ delayMs,
1314
+ idempotencyKey: batch.idempotencyKey,
1315
+ reason: `http-${result.response.status}`
1316
+ });
1209
1317
  try {
1210
- await sleep(retryDelayMs(attempt, retryAfter), signal);
1318
+ await sleep(delayMs, signal);
1211
1319
  } catch (cause) {
1212
1320
  throw new TrafficWarConnectionError(
1213
1321
  "TrafficWar request was aborted",
@@ -1223,6 +1331,11 @@ var TrafficWar = class {
1223
1331
  continue;
1224
1332
  }
1225
1333
  }
1334
+ this.#debugLog("request rejected", {
1335
+ attempt: attempt + 1,
1336
+ idempotencyKey: batch.idempotencyKey,
1337
+ status: result.response.status
1338
+ });
1226
1339
  throw buildApiError(
1227
1340
  result.response,
1228
1341
  parsed,