@trafficwar/node 3.0.0 → 4.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,37 +10,61 @@ 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 merge idempotently; removed declarations are not automatically 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`.
43
24
 
25
+ ## Automatic observed pairs
26
+
27
+ - Accepted captures automatically discover exact event/label pairs. Captured
28
+ values are never rewritten or pinned to a code location. A shared wrapper
29
+ can send different categories and labels on every call, as can batch slots.
30
+ - Only an entire call that passes event validation, duplicate-ID checks and
31
+ queue capacity teaches pairs. Missing labels and strings unsuitable for the
32
+ catalog do not block otherwise valid event delivery. Event validation is
33
+ unchanged: supplied non-string labels are still invalid event fields.
34
+ - Register only non-blank event/label strings, at most 128 Unicode code points
35
+ each, with no control characters. Preserve case and whitespace exactly;
36
+ identity is the pair, not a concatenation of its values or their cross product.
37
+ - One in-memory sent/pending list belongs to each client. New pairs coalesce
38
+ for a fixed 1-second window, not a resetting debounce. Uploads serialize,
39
+ send unsent deltas only and mark sent only after a successful response.
40
+ Repeated captures and concurrent flush calls do not create duplicate uploads.
41
+ - Bearer-authenticated `POST /v1/server/catalog` sends only
42
+ `{ captures: [{ event, label, station_known: false }] }`. The backend adds
43
+ and deduplicates rather than replacing the service list. Actual events supply
44
+ station metadata; declarations do not create traffic, clients, latency or lanes.
45
+ - No AST/source scanning, explicit declarations, strict/static switches,
46
+ captureEnabled getter, location pinning, filesystem access, JSON persistence,
47
+ API polling, startup registration or wrapper-first-value rewriting exists.
48
+ Do not invent fake captures to register pairs. Python does not register pairs.
49
+ - Registration reuses bounded transport retries/timeouts. Failures report
50
+ safely through `onError` and retain pending pairs. Automatic retry cycles
51
+ use exponential cooldowns from 1 s up to 30 s; captures and flush calls cannot
52
+ bypass a cooldown. Without `onError`, a generic error is printed.
53
+ - `flush()` awaits current catalog uploads and sends eligible pending pairs,
54
+ bypassing the initial coalescing window but not a failure cooldown. `close()`
55
+ does the same, then stops catalog timers. Catalog failures never reject event
56
+ delivery; counts returned by flush/close are event-only. Failed pending pairs
57
+ can be lost on close or abrupt process exit; there is no durable catalog log.
58
+ - Sent pairs remain remembered for the lifetime of that client. Deleting one
59
+ on the server does not clear SDK memory; after SDK restart it can reappear
60
+ when observed again. Independent clients/replicas may upload the same pair;
61
+ the additive server deduplicates them. No complete-list coordination is needed.
62
+ - Use stable low-cardinality names: client memory grows with distinct observed
63
+ pairs. Uploads are chunked to 4,000 pairs, but the backend's service capacity
64
+ still applies; permanent errors remain pending on cooldown until close.
65
+ - `debug` keeps safe delivery diagnostics. `verbose` logs only successfully
66
+ registered new pairs, not source inventory or every capture. Both default off.
67
+
44
68
  ## Stable event identity
45
69
 
46
70
  - `event` is the category: `http`, `database`, `redis`, `s3`, or `external`.
@@ -102,63 +126,3 @@ trafficwar.capture({
102
126
  - Errors require `status_code >= 400`, non-empty `error`, or non-empty
103
127
  `error_code`. Put stack traces in `properties`. Properties alone do not
104
128
  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
@@ -53,11 +53,10 @@ request.
53
53
  enqueues the input synchronously, then returns `void`; it does not return an
54
54
  `IngestResult` or wait for the network.
55
55
 
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.
56
+ **Accepted captures automatically register observed event/label pairs.** Values
57
+ are never rewritten, including calls through shared wrappers. Registration is
58
+ memory-only, sends unsent deltas and has no startup inventory, source scanning
59
+ or persistence. See [Automatic observed event/label registration](#automatic-observed-eventlabel-registration).
61
60
 
62
61
  `Date` timestamps are serialized as RFC3339 without changing the caller's
63
62
  object. String timestamps must be RFC3339; numeric timestamps are integer epoch
@@ -99,142 +98,62 @@ const trafficwar = new TrafficWar({
99
98
  });
100
99
  ```
101
100
 
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.
101
+ ### Automatic observed event/label registration
109
102
 
110
103
  ```ts
111
104
  const trafficwar = new TrafficWar({
112
105
  apiKey: process.env.TRAFFICWAR_API_KEY!,
113
- verbose: true,
114
106
  });
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.
190
-
191
- ```ts
192
- const trafficwar = new TrafficWar({
193
- 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
- });
198
- ```
199
-
200
- An example startup error is:
201
107
 
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
- });
108
+ function captureWork(event: string, label: string, latency_ms: number) {
109
+ trafficwar.capture({ event, label, latency_ms });
110
+ }
111
+ captureWork("database", "Checkout", 12);
112
+ captureWork("redis", "Different label", 29);
113
+ // Emits database / Checkout and redis / Different label, unchanged.
233
114
  ```
234
115
 
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.
116
+ - Accepted captures discover exact pairs; values are never rewritten, including
117
+ shared wrappers and reordered batch slots. Failed validation, duplicate IDs
118
+ and queue rejection never teach any pairs.
119
+ - One long-lived client keeps one sent/pending pair list in memory. New pairs
120
+ coalesce for a fixed 1-second window, not a resetting debounce. Uploads are
121
+ serialized; repeats and concurrent flushes cannot duplicate an in-flight POST.
122
+ Uploads contain only unsent deltas, marked sent only after success.
123
+ - `POST /v1/server/catalog` uses the same Bearer key and sends only
124
+ `{ captures: [{ event, label, station_known: false }] }`. No station metadata,
125
+ source locations, properties or identifiers are uploaded. Actual events supply
126
+ station metadata. The backend adds/deduplicates instead of replacing the
127
+ service list, so replicas do not need complete-list coordination.
128
+ - Registration requires non-blank strings of at most 128 Unicode code points
129
+ without controls. Case and whitespace are preserved exactly. Missing labels,
130
+ empty/blank labels, overly long strings and control-containing strings are
131
+ skipped for catalog purposes but do not block otherwise valid events. Event
132
+ validation remains unchanged (a supplied non-string label is not valid).
133
+ - There is no source scanning, explicit catalog, strict/static switch,
134
+ capture-location pinning, filesystem access, JSON persistence, API polling,
135
+ startup registration or first-value rewriting. Remove obsolete `catalog`,
136
+ `catalogRoot`, `catalogFile`, `strictCatalog`, `staticCatalog` options and use
137
+ neither `TrafficWarCatalogEntry` nor `captureEnabled`; these APIs are removed.
138
+ Do not send fake traffic to register pairs. Python does not register pairs.
139
+ - Catalog uploads reuse the client's bounded transport retries and timeout.
140
+ On failure, `onError` is called safely; pending pairs remain in memory and
141
+ automatic retry cycles back off from 1 s up to 30 s. Captures and repeated
142
+ flushes cannot bypass the cooldown. Without `onError`, a generic error prints.
143
+ - `flush()` awaits catalog uploads and sends eligible pending deltas, bypassing
144
+ the initial window, but not a failure cooldown. `close()` also awaits work
145
+ and stops catalog timers. Catalog failures do not reject event delivery or
146
+ alter its accepted count. A failed pending registration can be lost on close
147
+ or abrupt exit; there is no durable catalog log or unbounded shutdown retry.
148
+ - Sent pairs stay in memory for that client's lifetime. Removing a pair on
149
+ the server does not clear this memory; after SDK restart it can reappear when
150
+ observed again. Independent clients can upload the same pair; the server
151
+ deduplicates it. Use one client per service/key, not one per request.
152
+ - Keep identities low-cardinality: memory grows with distinct observed pairs.
153
+ Uploads are chunked at 4,000 entries; the backend service capacity still
154
+ applies. Permanent errors remain pending on cooldown until close.
155
+ - `verbose: true` logs successful new-pair registrations only, never a source
156
+ inventory or every capture. Debug and verbose remain off by default.
238
157
 
239
158
  The SDK generates a process-monotonic RFC 9562 UUIDv7 `event_id` for each event
240
159
  that omits one. A caller may override it with any valid UUID. Caller-owned
@@ -469,14 +388,7 @@ delivery still fails.
469
388
  - `baseUrl`: ingest origin. Defaults to `https://ingest.trafficwar.tech`.
470
389
  - `debug`: print safe batch lifecycle diagnostics with `console.debug`.
471
390
  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.
391
+ - `verbose`: log successfully registered new pairs. Defaults to `false`.
480
392
  - `timeoutMs`: timeout for each attempt. Defaults to 30,000 ms, safely above
481
393
  TrafficWar's 10-second durable acknowledgement window.
482
394
  - `maxRetries`: retries after the first attempt. Defaults to 3.
@@ -485,7 +397,7 @@ delivery still fails.
485
397
  - `flushIntervalMs`: delay from the first pending event to automatic flush.
486
398
  Defaults to 1,000 ms.
487
399
  - `maxQueueSize`: maximum unacknowledged events. Defaults to 100,000.
488
- - `onError`: optional callback for automatic background delivery errors.
400
+ - `onError`: optional callback for automatic delivery and catalog errors.
489
401
  - `fetch`: injected Fetch-compatible function, primarily for testing.
490
402
 
491
403
  The SDK sends `Content-Type: application/json`, `Authorization: Bearer ...`, a