@trafficwar/node 3.0.1 → 5.0.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/AGENTS.md CHANGED
@@ -10,36 +10,59 @@ application. Installing the package alone does not capture requests.
10
10
  - Create one long-lived `TrafficWar` client per service/API key, not per
11
11
  request. Load the key from a server-side environment variable. Never send
12
12
  it to a browser or commit it.
13
- - `strictCatalog` defaults to true. Deploy application source and set
14
- `catalogRoot` to include instrumentation and its relative imports. Check
15
- `captureEnabled` after construction; startup issues disable all sending.
16
- Do not silently opt out to hide scanner issues. Use `strictCatalog: false`
17
- only when the application intentionally accepts unrestricted identities
18
- or cannot deploy scannable source.
19
13
  - `capture(event)` and `capture([events])` validate, snapshot, and enqueue
20
14
  synchronously and return `void`. They do not acknowledge durable delivery.
21
- - A clean startup scan uploads fixed declarations to `/v1/server/catalog`
22
- independently of events; `close()` waits for that registration too. The panel
23
- preloads stations and event/label choices from this service-scoped catalog.
24
- Keep station `source`, `span_kind`, and `operation_type` statically resolvable
25
- to preload them. Unresolved metadata registers the pair with
26
- `station_known: false` and waits for live traffic to identify its station.
27
- No source paths, payloads, latency, clients, or lanes are registered. Catalog
28
- writes replace that service's stored list; pairs missing from the upload are deleted.
29
- Registration failures use `onError` without blocking event capture. Both
30
- `strictCatalog: false` and `verbose: false` disable scanning/registration.
31
- - The scan includes all recognized TrafficWar calls under `catalogRoot`, not
32
- only one client instance's calls. Use separate per-service source roots when
33
- an application contains clients for different service keys.
34
15
  - Automatic batching starts after one second or at 10,000 pending events;
35
16
  the default queue bound is 100,000 unacknowledged events. Validation and
36
17
  queue overflow can throw; do not let instrumentation replace an
37
18
  application's response or hide its original error.
38
- - Supply `onError` to observe background delivery failures. Await `close()`
39
- at graceful shutdown or the end of a short-lived job; do not close or flush
40
- the shared client on every request. Do not exit before shutdown finishes.
19
+ - Supply `onError` to observe background delivery and catalog failures. Await
20
+ `close()` at graceful shutdown or the end of a short-lived job; do not close
21
+ or flush the shared client on every request. Do not exit before shutdown finishes.
41
22
  - Omit `event_id` to use the generated UUIDv7. Do not reuse IDs across
42
23
  distinct events. Spans share `trace_id`, not `event_id`.
24
+ - Supply `event`, `label`, `source`, `operation_type`, `span_kind`, `timestamp`, and `latency_ms` on every event. Identity strings must be non-blank; latency must be finite and nonnegative. Record the actual start before work and measure duration with a monotonic clock; there is no timestamp default. Do not fill missing measurements with capture time or zero to pass validation.
25
+ - HTTP events require `http_method`. HTTP events and `external` events carrying `http_method` require the actual `status_code`, or a non-blank `error`/`error_code` when no response exists. Include the method on outbound HTTP calls; do not omit it to bypass outcome validation.
26
+
27
+ ## Automatic observed pairs
28
+
29
+ - Accepted captures automatically discover exact event/label pairs. Captured
30
+ values are never rewritten or pinned to a code location. A shared wrapper
31
+ can send different categories and labels on every call, as can batch slots.
32
+ - Only an entire call that passes event validation, duplicate-ID checks and queue capacity teaches pairs. Missing, blank, and non-string labels fail validation. Non-blank strings exceeding catalog limits still deliver events but do not register pairs.
33
+ - Register only non-blank event/label strings, at most 128 Unicode code points
34
+ each, with no control characters. Preserve case and whitespace exactly;
35
+ identity is the pair, not a concatenation of its values or their cross product.
36
+ - One in-memory sent/pending list belongs to each client. New pairs coalesce
37
+ for a fixed 1-second window, not a resetting debounce. Uploads serialize,
38
+ send unsent deltas only and mark sent only after a successful response.
39
+ Repeated captures and concurrent flush calls do not create duplicate uploads.
40
+ - Bearer-authenticated `POST /v1/server/catalog` sends only
41
+ `{ captures: [{ event, label, station_known: false }] }`. The backend adds
42
+ and deduplicates rather than replacing the service list. Actual events supply
43
+ station metadata; declarations do not create traffic, clients, latency or lanes.
44
+ - No AST/source scanning, explicit declarations, strict/static switches,
45
+ captureEnabled getter, location pinning, filesystem access, JSON persistence,
46
+ API polling, startup registration or wrapper-first-value rewriting exists.
47
+ Do not invent fake captures to register pairs. Python does not register pairs.
48
+ - Registration reuses bounded transport retries/timeouts. Failures report
49
+ safely through `onError` and retain pending pairs. Automatic retry cycles
50
+ use exponential cooldowns from 1 s up to 30 s; captures and flush calls cannot
51
+ bypass a cooldown. Without `onError`, a generic error is printed.
52
+ - `flush()` awaits current catalog uploads and sends eligible pending pairs,
53
+ bypassing the initial coalescing window but not a failure cooldown. `close()`
54
+ does the same, then stops catalog timers. Catalog failures never reject event
55
+ delivery; counts returned by flush/close are event-only. Failed pending pairs
56
+ can be lost on close or abrupt process exit; there is no durable catalog log.
57
+ - Sent pairs remain remembered for the lifetime of that client. Deleting one
58
+ on the server does not clear SDK memory; after SDK restart it can reappear
59
+ when observed again. Independent clients/replicas may upload the same pair;
60
+ the additive server deduplicates them. No complete-list coordination is needed.
61
+ - Use stable low-cardinality names: client memory grows with distinct observed
62
+ pairs. Uploads are chunked to 4,000 pairs, but the backend's service capacity
63
+ still applies; permanent errors remain pending on cooldown until close.
64
+ - `debug` keeps safe delivery diagnostics. `verbose` logs only successfully
65
+ registered new pairs, not source inventory or every capture. Both default off.
43
66
 
44
67
  ## Stable event identity
45
68
 
@@ -85,10 +108,9 @@ trafficwar.capture({
85
108
 
86
109
  ## Traces and errors
87
110
 
88
- - Spans for one request share `trace_id` and `label`. Measure durations with
111
+ - Spans for one request must share a non-blank `trace_id` and the same `label`; propagate one request-level ID, never generate an independent ID for each span. Standalone events may omit `trace_id`; a batch alone does not imply a trace. Measure durations with
89
112
  a monotonic clock; `timestamp` is the actual span start as a `Date`, RFC3339
90
- string, or integer epoch milliseconds. If captured after completion,
91
- default capture-time timestamps do not describe the span's start.
113
+ string, or integer epoch milliseconds, not capture time after completion.
92
114
  - Keep inclusive durations nested. Emit dependency spans first, then the
93
115
  server span, then an edge span if one was actually measured. Do not invent
94
116
  browser latency or emit a synthetic edge span solely to populate the map.
@@ -102,63 +124,3 @@ trafficwar.capture({
102
124
  - Errors require `status_code >= 400`, non-empty `error`, or non-empty
103
125
  `error_code`. Put stack traces in `properties`. Properties alone do not
104
126
  mark an event as an error; redact secrets before capture.
105
-
106
- ## Startup inventory is best-effort diagnostics
107
-
108
- - `verbose: true` prints a source inventory at client construction;
109
- `debug: true` separately prints batch lifecycle logs. Both default to off.
110
- - The AST inventory resolves literals, unchanged constant bindings, shorthand
111
- fields, shared objects/arrays, static spreads/computed keys, string enums,
112
- TypeScript assertions, and concatenations/templates with fixed inputs.
113
- Relative ESM imports and reexports within the scan root are resolved too.
114
- - Calls must belong to TrafficWar: import/require `@trafficwar/node`, construct
115
- the client, or annotate an injected client/parameter with its imported
116
- `TrafficWar` type. A variable named `client` alone is not evidence. Prefer
117
- direct SDK calls with explicit stable identities inside framework hooks;
118
- do not hide identity selection behind opaque wrappers.
119
- - Optional/bracket calls, simple `.bind(client)` aliases, `captureBatch`,
120
- `.call`/`.apply`, and calls inside template expressions are recognized.
121
- The scanner never runs application code to determine values.
122
- - Runtime values, opaque function results, parameter-derived identities,
123
- TypeScript path aliases, dynamic imports, and CommonJS local export graphs
124
- are not generally resolved. Mutated objects or objects passed to unknown
125
- code are treated conservatively; unknown spreads/keys can override literals.
126
- - Set `catalogRoot` to the application source directory. The scan defaults
127
- to `process.cwd()`, runs synchronously per client, and skips dependencies,
128
- build output (`dist`, `build`, `.next`, etc.), declarations, `test`/`tests`/
129
- `__tests__`, and `*.test.*`/`*.spec.*`. Symlinks are skipped and mark the
130
- scan incomplete. Limits: 4,000 files, depth 12, 512 KiB/file, 16 MiB total
131
- source, 128 resolution levels, and 100,000 value evaluations.
132
- - Other libraries' `capture` APIs and branches proven unreachable are ignored.
133
- Conditions requiring runtime information and unused function bodies remain
134
- scanned. This is bounded binding analysis, not a full TypeScript checker or
135
- whole-program proof; an empty catalog does not prove missing instrumentation.
136
- - No standalone CLI, framework route enumeration, or Python equivalent is
137
- provided. Do not claim the startup list is an exhaustive event catalog or
138
- proof that any listed event has been sent.
139
-
140
- ## Default protection: strictCatalog
141
-
142
- - `strictCatalog: true` is the default and requires fixed event/label
143
- identities with source available at `catalogRoot`. It works independently
144
- of `verbose`; verbose and debug output remain disabled by default.
145
- - Explicit `strictCatalog: false` disables the startup gate and runtime
146
- allowlist. With verbose also off, no source scan runs. This opt-out preserves
147
- the previous unrestricted capture behavior; it is not a warning-only guard.
148
- - Any missing/unresolved fields, failed or incomplete scan, or empty catalog
149
- sets `captureEnabled` to false. Startup prints file/line issues with
150
- `console.error`; subsequent capture calls enqueue nothing and the client
151
- sends nothing. Fix the issues and recreate the client to enable capture.
152
- - Unresolved does not mean proven dynamic. Use literals or statically
153
- resolvable constants for event/label fields. Keep all required relative
154
- imports inside `catalogRoot`; parse failures or missing local imports also
155
- disable capture. Tests in nonstandard locations can still be scanned.
156
- - Put runtime-dependent object spreads before explicit `event` and `label`
157
- fields so those identities cannot be overridden by an unresolved spread.
158
- - A clean catalog becomes a runtime pair allowlist. An unlisted event/label
159
- throws `TrafficWarValidationError`, rejecting the entire capture call.
160
- Previously queued valid events are still delivered. Catch instrumentation
161
- errors where needed to preserve application responses.
162
- - Do not restrict dynamic timestamps, measured durations, IDs, or properties.
163
- This guard bounds event/label values; it cannot prove source provenance for
164
- a computed runtime value that happens to equal a permitted pair.
package/README.md CHANGED
@@ -28,6 +28,8 @@ const trafficwar = new TrafficWar({
28
28
  },
29
29
  });
30
30
 
31
+ // Example measured request start and duration; use your handler's real measurements.
32
+ const requestStartedAt = new Date(Date.now() - 184);
31
33
  trafficwar.capture({
32
34
  event: "http",
33
35
  http_method: "POST",
@@ -37,6 +39,7 @@ trafficwar.capture({
37
39
  span_kind: "server",
38
40
  operation_type: "route.handler",
39
41
  status_code: 200,
42
+ timestamp: requestStartedAt,
40
43
  latency_ms: 184.2,
41
44
  distinct_id: "usr_7f3a91c2",
42
45
  properties: {
@@ -53,17 +56,16 @@ request.
53
56
  enqueues the input synchronously, then returns `void`; it does not return an
54
57
  `IngestResult` or wait for the network.
55
58
 
56
- **Strict catalog protection is enabled by default.** Application source must
57
- be available under `catalogRoot` (default: `process.cwd()`). Startup catalog
58
- issues disable capture without preventing the application from starting.
59
- See [Default event/label protection](#default-eventlabel-protection) before
60
- deploying a source-free build or upgrading an existing integration.
59
+ **Accepted captures automatically register observed event/label pairs.** Values
60
+ are never rewritten, including calls through shared wrappers. Registration is
61
+ memory-only, sends unsent deltas and has no startup inventory, source scanning
62
+ or persistence. See [Automatic observed event/label registration](#automatic-observed-eventlabel-registration).
61
63
 
62
- `Date` timestamps are serialized as RFC3339 without changing the caller's
63
- object. String timestamps must be RFC3339; numeric timestamps are integer epoch
64
- milliseconds. If `timestamp` is omitted, the SDK sets it to the current time at
65
- capture, which is right for a standalone event and wrong for a trace captured
66
- after the request has already finished.
64
+ Every event requires `event`, `label`, `source`, `operation_type`, `span_kind`, `timestamp`, and `latency_ms`. The four identity strings must be non-blank; values are preserved, not trimmed or rewritten. Latency must be finite and ≥ 0. Missing fields reject the whole capture call before enqueue or catalog discovery.
65
+
66
+ `timestamp` is the actual span start, with no capture-time default. `Date` values are serialized as RFC3339 without changing the caller's object; strings must be RFC3339 and numbers must be integer epoch milliseconds.
67
+
68
+ HTTP events require `http_method`. HTTP events, and `external` events carrying `http_method`, require `status_code` or a non-blank `error`/`error_code` for failures without a response. Send the real response status when available; never fabricate one for a network failure. HTTP category checks ignore case and surrounding whitespace. Related spans must share a non-blank `trace_id`; it remains optional at runtime because a batch can contain independent events.
67
69
 
68
70
  ## Automatic batching
69
71
 
@@ -99,142 +101,69 @@ const trafficwar = new TrafficWar({
99
101
  });
100
102
  ```
101
103
 
102
- Set `verbose: true` to print, once per client at startup, `capture()` calls whose
103
- `event` and `label` resolve to fixed strings. The scan looks under the
104
- working directory, or `catalogRoot` when that is set. A call is omitted when
105
- either value is missing or unresolved. The scan skips `node_modules` and does not print
106
- payloads, API keys, or other properties. Scanning runs by default because
107
- strict protection is enabled; verbose only controls inventory output. A scan
108
- failure is logged and disables capture unless `strictCatalog: false` is set.
104
+ ### Automatic observed event/label registration
109
105
 
110
106
  ```ts
111
- const trafficwar = new TrafficWar({
112
- apiKey: process.env.TRAFFICWAR_API_KEY!,
113
- verbose: true,
114
- });
115
- ```
116
-
117
- This is a best-effort source inventory, not a complete list of instrumented
118
- routes or proof of delivery. AST binding analysis recognizes literals, unchanged
119
- constant bindings, shorthand, shared objects/arrays, static spreads and keys,
120
- string enums, TypeScript assertions, and concatenations/templates with fixed
121
- inputs. Relative ESM imports/reexports inside the root are resolved. The
122
- scanner never executes application code.
123
-
124
- Calls are attributed to imports/require of `@trafficwar/node`, constructed
125
- clients, aliases, and injected clients with an imported `TrafficWar` type.
126
- Optional/bracket calls, simple `.bind(client)` aliases, `captureBatch`,
127
- `.call`/`.apply`, and calls inside template expressions are recognized.
128
- Other libraries' `capture` methods, comments/regex text, conventional tests,
129
- and branches proven unreachable are ignored. Runtime-dependent branches and
130
- unused function bodies remain scanned; this is not whole-program reachability.
131
-
132
- Opaque function results, wrapper parameters, TypeScript path aliases, dynamic
133
- imports, and CommonJS local export graphs are not generally resolved. Unknown
134
- spreads/keys can override preceding literals. Mutated objects and objects
135
- passed to opaque code are treated conservatively, even if their declarations
136
- use `const`. Type annotations alone do not prove that identities are static.
137
-
138
- Scanning is synchronous and bounded to 4,000 source files, depth 12, and
139
- 512 KiB per file, with a 16 MiB total source budget, 128 resolution levels,
140
- and 100,000 value evaluations. Declarations, `test`/`tests`/`__tests__`, and
141
- `*.test.*`/`*.spec.*` are skipped, along with symlinks and build directories
142
- such as `dist`, `build`, and `.next`. The parser is bundled at build time;
143
- the package still has no npm runtime dependencies. Point `catalogRoot` at available application
144
- source; a production image containing only build output can print an empty
145
- catalog. No standalone inventory CLI or framework route discovery is included.
146
-
147
- ### Register the startup catalog
148
-
149
- A complete, non-empty source scan registers its deduplicated declarations with
150
- `POST /v1/server/catalog` in the background at construction, before any request
151
- is captured. Authentication uses the same service API key. The wire contains
152
- only `event`, `label`, statically resolved `source`, `span_kind`,
153
- `operation_type`, and `station_known`; source files, line numbers, paths to the
154
- scan root, properties, and request identifiers are never uploaded.
155
-
156
- The panel reads `GET /panel/api/catalog?service=<service_id>` to preload idle
157
- SpaceWar stations and event/label choices. API-key callers can also read
158
- `GET /v1/server/catalog`, pinned to their key's service. Declarations are not
159
- events and do not create traffic, clients, latency samples, or map lanes.
160
- Registration merges idempotently per service, so replicas and separate apps
161
- cannot erase one another's declarations. Removed declarations are not deleted
162
- automatically. The API accepts at most 4,000 distinct declarations per service.
163
-
164
- The scan includes all recognized TrafficWar calls under `catalogRoot`; it does
165
- not attribute calls to individual client instances. Applications with multiple
166
- service keys should use separate per-service source roots to avoid registering
167
- another service's declarations.
168
-
169
- Dynamic station metadata is omitted and marked `station_known: false`: the
170
- event/label pair still populates selectors, but the station waits for real
171
- traffic. Missing optional fields use the same defaults as ingest. The map
172
- keeps its existing station/instance limits and folds overflow into `other`.
173
-
174
- Registration uses the client's bounded retries and timeout. Failures go to
175
- `onError` and never disable event delivery. `close()` also waits for registration;
176
- its accepted count remains event-only. Empty, failed, incomplete, or blocked
177
- scans do not upload. Setting both `strictCatalog: false` and `verbose: false`
178
- opts out of scanning and registration; verbose-only mode registers only clean,
179
- complete scans. Python does not yet register a catalog.
180
-
181
- ### Default event/label protection
182
-
183
- `strictCatalog` defaults to `true` and disables capture if the startup scan finds any
184
- missing or unresolved `event`/`label`. The SDK prints the affected file and
185
- object/argument line with `console.error`, even when `verbose` is off. A
186
- failed, incomplete, or empty scan also disables capture. The application can
187
- still start: `client.captureEnabled` is `false`, capture calls enqueue
188
- nothing, and `flush()`/`close()` return zero accepted events without sending.
189
- Fix the source and recreate the client; there is no automatic rescan.
107
+ import { TrafficWar, type TrafficWarEvent } from "@trafficwar/node";
190
108
 
191
- ```ts
192
109
  const trafficwar = new TrafficWar({
193
110
  apiKey: process.env.TRAFFICWAR_API_KEY!,
194
- strictCatalog: true,
195
- catalogRoot: "./src",
196
- verbose: true, // Optional: also print the catalog when the check passes.
197
111
  });
198
- ```
199
-
200
- An example startup error is:
201
112
 
202
- ```text
203
- [TrafficWar] capture disabled by strictCatalog; fix these issues and restart the client:
204
- checkout.ts:42: label missing or not a statically resolved string
205
- ```
206
-
207
- If the scan passes, capture accepts only exact event/label pairs in that
208
- startup catalog. An unlisted pair throws `TrafficWarValidationError` before
209
- any events from that call are queued; already queued valid events remain
210
- deliverable. Catch instrumentation validation errors at the application's
211
- boundary if they must not affect request handling. Dynamic timestamps,
212
- durations, actor IDs, paths, and properties are not restricted by this guard.
213
-
214
- This is deliberately conservative, not proof that a value changes at runtime:
215
- unsupported expressions and opaque wrapper arguments remain unresolved.
216
- Point `catalogRoot` at the instrumented application source, including required
217
- relative imports. Source must be present; skipped symlinks, missing local
218
- imports, parse errors, and unreadable/oversized files make the scan incomplete.
219
- The scanner cannot establish the provenance of runtime values; a computed value
220
- equal to an allowed pair can pass the runtime check. `strictCatalog` defaults
221
- to `true`, while `verbose` and `debug` remain `false`. Python has no equivalent.
222
-
223
- This default changes existing integrations: source-free builds, missing labels,
224
- or unsupported/unresolved instrumentation will stop sending until the source
225
- is fixed or the application deliberately opts out. To retain the previous
226
- unrestricted capture behavior, explicitly set:
227
-
228
- ```ts
229
- const trafficwar = new TrafficWar({
230
- apiKey: process.env.TRAFFICWAR_API_KEY!,
231
- strictCatalog: false,
232
- });
113
+ function captureWork(input: TrafficWarEvent) {
114
+ trafficwar.capture(input);
115
+ }
116
+ // Illustrative timings; supply actual measured span starts and durations.
117
+ captureWork({ event: "database", label: "Checkout", source: "db-primary",
118
+ operation_type: "postgres.select", span_kind: "client",
119
+ timestamp: new Date(Date.now() - 12), latency_ms: 12 });
120
+ captureWork({ event: "redis", label: "Different label", source: "redis-1",
121
+ operation_type: "redis.get", span_kind: "client",
122
+ timestamp: new Date(Date.now() - 29), latency_ms: 29 });
123
+ // Emits database / Checkout and redis / Different label, unchanged.
233
124
  ```
234
125
 
235
- Opting out disables both startup blocking and the runtime pair allowlist.
236
- With verbose also off, no source scan runs; with verbose on, the inventory
237
- remains diagnostics only and never blocks capture.
126
+ - Accepted captures discover exact pairs; values are never rewritten, including
127
+ shared wrappers and reordered batch slots. Failed validation, duplicate IDs
128
+ and queue rejection never teach any pairs.
129
+ - One long-lived client keeps one sent/pending pair list in memory. New pairs
130
+ coalesce for a fixed 1-second window, not a resetting debounce. Uploads are
131
+ serialized; repeats and concurrent flushes cannot duplicate an in-flight POST.
132
+ Uploads contain only unsent deltas, marked sent only after success.
133
+ - `POST /v1/server/catalog` uses the same Bearer key and sends only
134
+ `{ captures: [{ event, label, station_known: false }] }`. No station metadata,
135
+ source locations, properties or identifiers are uploaded. Actual events supply
136
+ station metadata. The backend adds/deduplicates instead of replacing the
137
+ service list, so replicas do not need complete-list coordination.
138
+ - Registration requires non-blank strings of at most 128 Unicode code points
139
+ without controls. Case and whitespace are preserved exactly. Overly long
140
+ strings and control-containing strings are skipped for catalog purposes but
141
+ do not block otherwise valid events. Missing, blank, or non-string labels
142
+ fail event validation before discovery.
143
+ - There is no source scanning, explicit catalog, strict/static switch,
144
+ capture-location pinning, filesystem access, JSON persistence, API polling,
145
+ startup registration or first-value rewriting. Remove obsolete `catalog`,
146
+ `catalogRoot`, `catalogFile`, `strictCatalog`, `staticCatalog` options and use
147
+ neither `TrafficWarCatalogEntry` nor `captureEnabled`; these APIs are removed.
148
+ Do not send fake traffic to register pairs. Python does not register pairs.
149
+ - Catalog uploads reuse the client's bounded transport retries and timeout.
150
+ On failure, `onError` is called safely; pending pairs remain in memory and
151
+ automatic retry cycles back off from 1 s up to 30 s. Captures and repeated
152
+ flushes cannot bypass the cooldown. Without `onError`, a generic error prints.
153
+ - `flush()` awaits catalog uploads and sends eligible pending deltas, bypassing
154
+ the initial window, but not a failure cooldown. `close()` also awaits work
155
+ and stops catalog timers. Catalog failures do not reject event delivery or
156
+ alter its accepted count. A failed pending registration can be lost on close
157
+ or abrupt exit; there is no durable catalog log or unbounded shutdown retry.
158
+ - Sent pairs stay in memory for that client's lifetime. Removing a pair on
159
+ the server does not clear this memory; after SDK restart it can reappear when
160
+ observed again. Independent clients can upload the same pair; the server
161
+ deduplicates it. Use one client per service/key, not one per request.
162
+ - Keep identities low-cardinality: memory grows with distinct observed pairs.
163
+ Uploads are chunked at 4,000 entries; the backend service capacity still
164
+ applies. Permanent errors remain pending on cooldown until close.
165
+ - `verbose: true` logs successful new-pair registrations only, never a source
166
+ inventory or every capture. Debug and verbose remain off by default.
238
167
 
239
168
  The SDK generates a process-monotonic RFC 9562 UUIDv7 `event_id` for each event
240
169
  that omits one. A caller may override it with any valid UUID. Caller-owned
@@ -252,7 +181,7 @@ the human route name (`Checkout`), `path` for the route URL
252
181
  normalized to uppercase and must be a 1–64-character RFC HTTP token. Spans
253
182
  of one request share `trace_id`. `span_kind` is one of `server`, `client`,
254
183
  `producer`, `consumer`, or `internal`, lowercase; any other value is
255
- discarded. It does not replace `source`, and it is not decorative: `event`,
184
+ rejected. It does not replace `source`, and it is not decorative: `event`,
256
185
  `source`, and `span_kind` are the three fields that place a span on a tier.
257
186
 
258
187
  ## Traces and tiers
@@ -291,10 +220,7 @@ from `event` and `source`, so `db-primary`, `redis-1`, `receipts.ovh-s3`, and
291
220
 
292
221
  Emit dependency spans first and the edge span last, and keep inclusive
293
222
  durations nested: the sum of the dependency spans must not exceed the server
294
- span, which must not exceed the client span. Set `timestamp` on every span of a
295
- trace. A server normally captures all of its spans after the request has
296
- finished, and the default capture-time timestamp would collapse them onto one
297
- instant, leaving the waterfall with no chronological axis.
223
+ span, which must not exceed the client span. Set `timestamp` to each span's actual start, not the time at which the completed trace is captured, so the waterfall retains its chronological axis.
298
224
 
299
225
  ```ts
300
226
  const trace_id = crypto.randomUUID();
@@ -332,8 +258,7 @@ That trace renders as one journey: an edge station for `Checkout` with
332
258
  `https://app.example.com` as its caller, a backend station for `Checkout`
333
259
  served by `backend-a`, and four infrastructure stations beneath it.
334
260
 
335
- A single-span request needs none of this. One `http` span with
336
- `span_kind: "server"` is a complete, valid event.
261
+ A single-span request can send one complete `http` server event with all required fields; it does not need synthetic dependency or edge spans.
337
262
 
338
263
  ### Edge spans emitted by a server
339
264
 
@@ -341,8 +266,7 @@ A server cannot measure a browser's round trip. If you emit the edge span from
341
266
  your backend, make it the widest interval you actually measured — the full
342
267
  server-side hop including routing and middleware — and let the server span
343
268
  cover only the handler. Do not invent a client round trip, and do not drop
344
- `latency_ms` to sidestep the problem: an absent value is stored as `0` and
345
- enters the latency histogram. If you have nothing wider than the handler to
269
+ `latency_ms` to sidestep the problem: missing latency is rejected. If you have nothing wider than the handler to
346
270
  report, send the server span alone. A trace does not require an edge span.
347
271
 
348
272
  ### Two cautions
@@ -363,6 +287,9 @@ trafficwar.capture({
363
287
  label: "Route planner",
364
288
  span_kind: "client",
365
289
  operation_type: "google.routes.compute",
290
+ timestamp: new Date(Date.now() - 13),
291
+ http_method: "POST",
292
+ status_code: 200,
366
293
  latency_ms: 13,
367
294
  });
368
295
  ```
@@ -383,6 +310,8 @@ Send application failures with first-class outcome fields and keep the full
383
310
  stack trace in `properties`:
384
311
 
385
312
  ```ts
313
+ const requestStartedAt = new Date();
314
+ const started = performance.now();
386
315
  try {
387
316
  await submitOrder();
388
317
  } catch (caught) {
@@ -394,6 +323,9 @@ try {
394
323
  path: "/v1/checkout",
395
324
  source: "backend-a",
396
325
  span_kind: "server",
326
+ operation_type: "route.handler",
327
+ timestamp: requestStartedAt,
328
+ latency_ms: performance.now() - started,
397
329
  http_method: "POST",
398
330
  status_code: 500,
399
331
  error: error.message,
@@ -469,14 +401,7 @@ delivery still fails.
469
401
  - `baseUrl`: ingest origin. Defaults to `https://ingest.trafficwar.tech`.
470
402
  - `debug`: print safe batch lifecycle diagnostics with `console.debug`.
471
403
  Defaults to `false`.
472
- - `verbose`: at startup, statically scan source for `capture()` calls and
473
- print pairs whose `event` and `label` resolve to fixed strings.
474
- Unresolved or missing values are omitted. Defaults to `false`.
475
- - `strictCatalog`: disable capture on unresolved/empty/incomplete source scans
476
- and reject runtime pairs outside the startup catalog. Defaults to `true`;
477
- explicitly set `false` to opt out.
478
- - `catalogRoot`: directory scanned when `verbose` or `strictCatalog` is true.
479
- Defaults to the process working directory.
404
+ - `verbose`: log successfully registered new pairs. Defaults to `false`.
480
405
  - `timeoutMs`: timeout for each attempt. Defaults to 30,000 ms, safely above
481
406
  TrafficWar's 10-second durable acknowledgement window.
482
407
  - `maxRetries`: retries after the first attempt. Defaults to 3.
@@ -485,7 +410,7 @@ delivery still fails.
485
410
  - `flushIntervalMs`: delay from the first pending event to automatic flush.
486
411
  Defaults to 1,000 ms.
487
412
  - `maxQueueSize`: maximum unacknowledged events. Defaults to 100,000.
488
- - `onError`: optional callback for automatic background delivery errors.
413
+ - `onError`: optional callback for automatic delivery and catalog errors.
489
414
  - `fetch`: injected Fetch-compatible function, primarily for testing.
490
415
 
491
416
  The SDK sends `Content-Type: application/json`, `Authorization: Bearer ...`, a
@@ -503,7 +428,9 @@ import {
503
428
  TrafficWarValidationError,
504
429
  } from "@trafficwar/node";
505
430
 
506
- trafficwar.capture({ event: "http", label: "Checkout", status_code: 500 });
431
+ trafficwar.capture({ event: "http", label: "Checkout", source: "backend-a",
432
+ span_kind: "server", operation_type: "route.handler", http_method: "POST",
433
+ timestamp: new Date(Date.now() - 184), latency_ms: 184, status_code: 500 });
507
434
 
508
435
  try {
509
436
  await trafficwar.close();