@hop-top/kit 0.4.0-alpha.1 → 0.4.0-alpha.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/CHANGELOG.md CHANGED
@@ -4,6 +4,19 @@ All notable changes to `@hop-top/kit` are documented in this file.
4
4
  Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/);
5
5
  versions follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
+ ## [0.4.0-alpha.2](https://github.com/hop-top/poly-kit/compare/kit-ts/v0.4.0-alpha.1...kit-ts/v0.4.0-alpha.2) (2026-06-03)
8
+
9
+ The hop-top team is happy to announce Kit's TS SDK 0.4.0-alpha.2. This release includes new features.
10
+
11
+
12
+ ### Features
13
+
14
+ * **contracts:** typeid-v1 cross-language parity fixtures
15
+ * **telemetry:** consenting telemetry stack across kit-go + 4 SDKs
16
+ * **ts:** kit-sdk/id — typeid primitive
17
+
18
+ Full diff: [kit-ts/v0.4.0-alpha.1...kit-ts/v0.4.0-alpha.2](https://github.com/hop-top/poly-kit/compare/kit-ts/v0.4.0-alpha.1...kit-ts/v0.4.0-alpha.2)
19
+
7
20
  ## [0.4.0-alpha.1](https://github.com/hop-top/poly-kit/compare/kit-ts/v0.4.0-alpha.0...kit-ts/v0.4.0-alpha.1) (2026-05-17)
8
21
 
9
22
  The hop-top team is happy to announce Kit's TS SDK 0.4.0-alpha.1. This release includes new features.
package/README.md CHANGED
@@ -138,6 +138,9 @@ render(process.stdout, JSON_FORMAT, { ok: true });
138
138
  - `@hop-top/kit/cli` — `createCLI(cfg)` builds a Commander root program
139
139
  with the hop-top contract: `--format`, `--quiet`, `--no-color`,
140
140
  `--no-hints`, themed help, version, hidden completion command.
141
+ - `@hop-top/kit/id` — TypeID primitive (cross-language; see
142
+ [ADR 0001](../../docs/adr/0001-typeid-primitive.md)). Source:
143
+ [`src/id/`](src/id/).
141
144
  - `@hop-top/kit/xdg` — XDG Base Directory paths.
142
145
  - `@hop-top/kit/config` — config-file loading.
143
146
  - `@hop-top/kit/sqlstore` — embedded SQLite key/value store.
@@ -184,6 +187,96 @@ const id = handler.id({
184
187
  });
185
188
  ```
186
189
 
190
+ ## Telemetry
191
+
192
+ `@hop-top/kit/telemetry` ships the SDK-side primitives for the kit
193
+ telemetry contract: a non-blocking `Client`, a best-effort PII /
194
+ secret redactor, and the consent + install-id readers needed to gate
195
+ emission.
196
+
197
+ **Default-denied**: a fresh install never emits. The `Client.record()`
198
+ call is a no-op unless the operator has run `kit consent grant` AND a
199
+ mode is selected via `KIT_TELEMETRY_MODE=anon|full` (or the prefixed
200
+ `<APP>_TELEMETRY_MODE` equivalent). Inspect what would ship with `kit
201
+ telemetry inspect`.
202
+
203
+ ```ts
204
+ import { Client } from '@hop-top/kit/telemetry';
205
+
206
+ const client = new Client({
207
+ sink: 'jsonl', // or 'https'
208
+ sinkFile: '/tmp/kit-events.jsonl', // jsonl sink only
209
+ endpoint: 'https://telemetry.example', // https sink only
210
+ sdkVersion: '1.2.3',
211
+ });
212
+
213
+ // Fire-and-forget. Returns synchronously; never throws.
214
+ client.record('cmd.invoked', { command: 'launch', exit_code: 0 });
215
+
216
+ // Best-effort drain on process exit.
217
+ await client.shutdown(5_000);
218
+ ```
219
+
220
+ ### Configuration
221
+
222
+ All `ClientOptions` fields are mirrored by env vars (env wins when the
223
+ option is omitted):
224
+
225
+ | Field | Env var | Default |
226
+ | ----------- | ----------------------------- | ---------------------------------------------------- |
227
+ | `endpoint` | `KIT_TELEMETRY_ENDPOINT` | — |
228
+ | `sink` | `KIT_TELEMETRY_SINK` | `jsonl` |
229
+ | `sinkFile` | `KIT_TELEMETRY_SINK_FILE` | `$XDG_STATE_HOME/kit/telemetry/events.jsonl` |
230
+ | `queueSize` | `KIT_TELEMETRY_QUEUE_SIZE` | `1024` |
231
+
232
+ ### Redactor
233
+
234
+ The default `redact()` pass scrubs emails, IPv4 / IPv6 addresses, `sk-`
235
+ / `gh[pousr]_` / `xoxb-` token prefixes, and `$HOME` path prefixes
236
+ before the envelope hits a sink. Placeholders (`<redacted:email>`,
237
+ `<redacted:ipv4>`, `<redacted:ipv6>`, `<redacted:token>`) are
238
+ byte-parity with the py / rs / php SDKs so the cross-language contract
239
+ harness can diff outputs.
240
+
241
+ ```ts
242
+ import { redact, redactString } from '@hop-top/kit/telemetry';
243
+
244
+ redactString('user@example.com from 10.0.0.1'); // → '<redacted:email> from <redacted:ipv4>'
245
+ redact({ ip: '8.8.8.8', count: 3 }); // → { ip: '<redacted:ipv4>', count: 3 }
246
+ ```
247
+
248
+ A per-`Client` `redactor` callback runs BEFORE the default pass — use
249
+ it for adopter-specific allowlists or stricter rules. Throwing
250
+ callbacks are isolated (the event still goes through the default
251
+ pass).
252
+
253
+ ### Envelope
254
+
255
+ Each emitted event is one NDJSON line with the shape:
256
+
257
+ ```json
258
+ {
259
+ "schema_version": "1",
260
+ "sdk_lang": "ts",
261
+ "sdk_version": "0.4.0",
262
+ "installation_id": "<64-char hex sha256>",
263
+ "mode": "anon",
264
+ "occurred_at": "2026-05-19T12:00:00.000Z",
265
+ "event": "cmd.invoked",
266
+ "attrs": { "command": "launch", "exit_code": 0 }
267
+ }
268
+ ```
269
+
270
+ The `event` + `attrs` extension is the TS / Py divergence from Go's
271
+ canonical envelope (Go pins a typed `Event` struct). See
272
+ `sdk/docs/telemetry-event-schema.md` for the cross-language contract.
273
+
274
+ ### Cross-SDK contract harness
275
+
276
+ The harness at `hops/main/sdk/tests/cross-lang/` (planned in T-0709)
277
+ diffs envelopes across SDKs. As of this revision the harness is not
278
+ landed; TS-side wiring is deferred until the directory exists.
279
+
187
280
  ## License
188
281
 
189
282
  MIT.
@@ -0,0 +1,83 @@
1
+ import { z } from 'zod';
2
+
3
+ /**
4
+ * @module id
5
+ * @package @hop-top/kit
6
+ *
7
+ * TypeID primitive — thin wrapper around `typeid-js` (jetify-com)
8
+ * implementing the cross-language kit API SHAPE per ADR 0001.
9
+ *
10
+ * Canonical wire form: `<prefix>_<26-char-base32>` where the suffix is
11
+ * a Crockford-base32-encoded UUIDv7. The TS surface adds a
12
+ * template-literal `Typed<P>` for compile-time prefix safety on top of
13
+ * the runtime guarantees provided by `typeid-js`.
14
+ *
15
+ * URI composition (e.g. `tlc://task/task_…`) is NOT in this module —
16
+ * callers should use the `@hop-top/uri` package directly. This
17
+ * keeps `kit/id` free of any transitive dependency on the URI
18
+ * registry, per the ADR's scope boundary.
19
+ */
20
+
21
+ /**
22
+ * Compile-time-typed canonical TypeID string for prefix `P`.
23
+ *
24
+ * The template-literal `${P}_${string}` form means a `Typed<'task'>`
25
+ * is statically distinguishable from a `Typed<'invoice'>` even though
26
+ * both are runtime `string`s. Pair with {@link newTyped} or
27
+ * {@link parseTyped} to mint values whose prefix is enforced both at
28
+ * compile time and at runtime.
29
+ */
30
+ type Typed<P extends string> = `${P}_${string}`;
31
+ /** Parsed components of a canonical TypeID string. */
32
+ interface Parsed {
33
+ /** Prefix segment (everything before the final underscore). */
34
+ prefix: string;
35
+ /** Backing UUID in canonical 8-4-4-4-12 hyphenated form. */
36
+ uuid: string;
37
+ }
38
+ /**
39
+ * Generate a new TypeID with the given prefix, returning the canonical
40
+ * string `<prefix>_<26-char-base32>`.
41
+ *
42
+ * @example
43
+ * newId('task') // => 'task_01h2e8kqv8000000000000000'
44
+ */
45
+ declare function newId(prefix: string): string;
46
+ /**
47
+ * Parse a canonical TypeID string into its prefix and backing UUID.
48
+ *
49
+ * @throws {Error} when the input is not a syntactically valid TypeID
50
+ * (e.g. malformed suffix, illegal prefix characters).
51
+ */
52
+ declare function parse(s: string): Parsed;
53
+ /**
54
+ * Typed variant of {@link newId}. Returns a `Typed<P>` whose static
55
+ * type carries the literal prefix, enabling compile-time discrimination
56
+ * between e.g. `TaskId` and `InvoiceId`.
57
+ */
58
+ declare function newTyped<P extends string>(prefix: P): Typed<P>;
59
+ /**
60
+ * Typed variant of {@link parse}. Validates that the parsed prefix
61
+ * matches the expected `prefix` argument at runtime; returns the
62
+ * canonical string narrowed to `Typed<P>`.
63
+ *
64
+ * @throws {Error} when the parsed prefix does not match `prefix`, or
65
+ * when the input is not a syntactically valid TypeID.
66
+ */
67
+ declare function parseTyped<P extends string>(prefix: P, s: string): Typed<P>;
68
+ /**
69
+ * Zod schema for runtime validation of a `${prefix}_<26-char-base32>`
70
+ * canonical TypeID string.
71
+ *
72
+ * The schema only validates structure (prefix match + 26-char Crockford
73
+ * base32 suffix with the spec's leading-bit constraint). It does not
74
+ * decode the UUIDv7 timestamp; use {@link parse} if you need the
75
+ * underlying UUID.
76
+ *
77
+ * @example
78
+ * const TaskIdSchema = typeIdSchema('task');
79
+ * TaskIdSchema.parse('task_01h2e8kqv8000000000000000');
80
+ */
81
+ declare function typeIdSchema(prefix: string): z.ZodString;
82
+
83
+ export { type Parsed, type Typed, newId, newTyped, parse, parseTyped, typeIdSchema };
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/id/index.ts
21
+ var id_exports = {};
22
+ __export(id_exports, {
23
+ newId: () => newId,
24
+ newTyped: () => newTyped,
25
+ parse: () => parse,
26
+ parseTyped: () => parseTyped,
27
+ typeIdSchema: () => typeIdSchema
28
+ });
29
+ module.exports = __toCommonJS(id_exports);
30
+ var import_typeid_js = require("typeid-js");
31
+ var import_zod = require("zod");
32
+ function newId(prefix) {
33
+ return (0, import_typeid_js.typeid)(prefix).toString();
34
+ }
35
+ function parse(s) {
36
+ const tid = import_typeid_js.TypeID.fromString(s);
37
+ return {
38
+ prefix: tid.getType(),
39
+ uuid: tid.toUUID()
40
+ };
41
+ }
42
+ function newTyped(prefix) {
43
+ return (0, import_typeid_js.typeid)(prefix).toString();
44
+ }
45
+ function parseTyped(prefix, s) {
46
+ const tid = import_typeid_js.TypeID.fromString(s, prefix);
47
+ return tid.toString();
48
+ }
49
+ var SUFFIX_RE = /^[0-7][0-9a-hjkmnp-tv-z]{25}$/;
50
+ function typeIdSchema(prefix) {
51
+ const pattern = new RegExp(
52
+ `^${escapeRegExp(prefix)}_${SUFFIX_RE.source.slice(1, -1)}$`
53
+ );
54
+ return import_zod.z.string().regex(pattern, `invalid typeid for prefix '${prefix}'`);
55
+ }
56
+ function escapeRegExp(s) {
57
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
58
+ }
59
+ // Annotate the CommonJS export names for ESM import in node:
60
+ 0 && (module.exports = {
61
+ newId,
62
+ newTyped,
63
+ parse,
64
+ parseTyped,
65
+ typeIdSchema
66
+ });
@@ -0,0 +1,315 @@
1
+ /**
2
+ * @module telemetry/mode
3
+ * @package @hop-top/kit
4
+ *
5
+ * Telemetry Mode + env-variable precedence — the TS mirror of
6
+ * `go/runtime/telemetry/mode.go`. Three tiers control what an emit
7
+ * call ships:
8
+ *
9
+ * - `Mode.Off`: default; emit is a no-op.
10
+ * - `Mode.Anon`: anonymous payload (installation_id, command_path,
11
+ * exit_code, duration_ms, occurred_at, kit_version, sdk_lang/version).
12
+ * - `Mode.Full`: anon + args + flags, both post-redact.
13
+ *
14
+ * See the event-schema doc at `sdk/docs/telemetry-event-schema.md`
15
+ * for the on-wire shape.
16
+ *
17
+ * The env-precedence rule is intentionally simple:
18
+ *
19
+ * 1. If `KIT_APP_PREFIX=spaced` is set AND `SPACED_TELEMETRY_MODE` has
20
+ * a parseable value, that wins.
21
+ * 2. Otherwise `KIT_TELEMETRY_MODE` is consulted.
22
+ * 3. Anything else (missing, garbage, whitespace) → `Mode.Off`.
23
+ */
24
+ /**
25
+ * Mode controls how much detail the telemetry emitter ships.
26
+ *
27
+ * Encoded as a string-literal union so the on-disk / on-wire token IS
28
+ * the enum value. Mirrors Go's `Mode.String()` which renders these same
29
+ * three lowercase tokens.
30
+ */
31
+ declare const Mode: {
32
+ readonly Off: "off";
33
+ readonly Anon: "anon";
34
+ readonly Full: "full";
35
+ };
36
+ type Mode = (typeof Mode)[keyof typeof Mode];
37
+ /**
38
+ * parseMode maps a string token (case-insensitive: "off", "anon",
39
+ * "full") to a Mode. Empty / null / undefined input returns
40
+ * `[Mode.Off, true]` so an unset env var doesn't masquerade as an
41
+ * error. Unknown tokens return `[Mode.Off, false]` so callers can
42
+ * distinguish "operator typoed the env var" from "operator opted out".
43
+ *
44
+ * Mirrors `telemetry.ParseMode` in `go/runtime/telemetry/mode.go`.
45
+ */
46
+ declare function parseMode(s: string | undefined | null): [Mode, boolean];
47
+ /**
48
+ * resolveMode reads the env vars in canonical precedence order and
49
+ * returns the resolved Mode. Defaults to `Mode.Off`.
50
+ *
51
+ * Precedence (mirrors `telemetry.readEnvMode`):
52
+ *
53
+ * 1. `<APP>_TELEMETRY_MODE` where `<APP>` = uppercased `KIT_APP_PREFIX`.
54
+ * 2. `KIT_TELEMETRY_MODE`.
55
+ * 3. `Mode.Off`.
56
+ *
57
+ * Unparseable values at any tier are skipped (NOT a hard error); the
58
+ * resolver falls through to the next tier and ultimately to Off.
59
+ *
60
+ * @param env Inject a custom env map for testing. Defaults to `process.env`.
61
+ */
62
+ declare function resolveMode(env?: NodeJS.ProcessEnv): Mode;
63
+
64
+ /**
65
+ * @module telemetry/installId
66
+ * @package @hop-top/kit
67
+ *
68
+ * Persisted anonymous installation identifier — the TS mirror of
69
+ * `go/runtime/telemetry/installid.go`.
70
+ *
71
+ * On-disk format: 32 raw bytes from `crypto.randomBytes` stored at
72
+ * `<XDG_STATE_HOME>/kit/telemetry/installation_id`. The surface API
73
+ * returns the lowercase hex SHA-256 of those bytes (64 chars) so the
74
+ * file format stays canonical across polyglot SDKs (Go / Py / TS / Rs /
75
+ * PHP) while the hashed string is what flows through events.
76
+ *
77
+ * Perms: file 0600, parent dir 0700.
78
+ */
79
+ /**
80
+ * installIdPath returns the canonical on-disk path used by this module.
81
+ * Useful for SDK consumers and compliance checks that need to verify
82
+ * the storage location without invoking the read path.
83
+ */
84
+ declare function installIdPath(): string;
85
+ /**
86
+ * getInstallId returns the persisted anonymous install identifier as
87
+ * lowercase hex SHA-256 of 32 random bytes stored on disk. It generates
88
+ * and persists the bytes on first call. Concurrent first calls across
89
+ * processes are race-safe via a tmp + rename pattern with an
90
+ * existence-precheck: if a peer already wrote a valid file by the time
91
+ * we go to rename, we adopt their bytes.
92
+ *
93
+ * Mirrors `telemetry.InstallationID` in Go.
94
+ */
95
+ declare function getInstallId(): Promise<string>;
96
+ /**
97
+ * rotate atomically replaces the persisted bytes with 32 fresh
98
+ * `crypto.randomBytes` and returns the new hex. Used by the
99
+ * `kit consent reset` CLI flow.
100
+ *
101
+ * Mirrors `telemetry.Rotate` in Go.
102
+ */
103
+ declare function rotate(): Promise<string>;
104
+ /**
105
+ * resetForTest deletes the persisted file. Test helper exposed so
106
+ * adopters can drive first-run code paths in their own tests. Never
107
+ * call from production code.
108
+ *
109
+ * Mirrors `telemetry.ResetForTest` in Go.
110
+ */
111
+ declare function resetForTest(): Promise<void>;
112
+
113
+ /**
114
+ * @module telemetry/consent
115
+ * @package @hop-top/kit
116
+ *
117
+ * Read-only consent-file loader — the TS mirror of the read path in
118
+ * `go/core/consent/file_store.go`.
119
+ *
120
+ * On-disk shape (YAML under `<XDG_CONFIG_HOME>/kit/config.yaml` at the
121
+ * `kit.telemetry.consent` partition):
122
+ *
123
+ * ```yaml
124
+ * kit:
125
+ * telemetry:
126
+ * consent:
127
+ * state: granted # | denied
128
+ * prompt_version: 1
129
+ * decision_source: prompt # | flag | config | env
130
+ * decided_at: 2026-05-19T12:00:00Z
131
+ * ```
132
+ *
133
+ * A pre-refactor layout at `<XDG_CONFIG_HOME>/kit/telemetry.yaml` (with
134
+ * a bare `telemetry.consent` block at the top level) is read as a
135
+ * fallback so installs that have not been migrated yet still work.
136
+ *
137
+ * This TS module is **read-only**: writing the consent file remains the
138
+ * job of the Go `kit consent` CLI. SDK consumers just need to know
139
+ * whether emission is allowed.
140
+ *
141
+ * Anything that isn't a clean, parseable, `state: granted` block
142
+ * collapses to `deniedConsent` — a fail-closed default so a corrupt
143
+ * config can never accidentally enable emission.
144
+ */
145
+ /**
146
+ * Consent is the resolved telemetry decision for the current
147
+ * installation. The shape mirrors the relevant subset of the Go
148
+ * `consent.Decision` struct.
149
+ */
150
+ interface Consent {
151
+ /** allowed is true only when state == "granted". */
152
+ readonly allowed: boolean;
153
+ /** promptVersion records which prompt revision the user accepted. */
154
+ readonly promptVersion: number;
155
+ /**
156
+ * decisionSource records how the decision was captured —
157
+ * "prompt" | "flag" | "config" | "env". Defaults to "config" when
158
+ * the file is missing or unreadable.
159
+ */
160
+ readonly decisionSource: string;
161
+ /** decidedAt is the RFC3339 timestamp of the decision, if present. */
162
+ readonly decidedAt?: string;
163
+ }
164
+ /**
165
+ * deniedConsent is the canonical fail-closed default. Returned whenever
166
+ * the file is missing, unreadable, malformed, or carries an unknown
167
+ * state value.
168
+ */
169
+ declare const deniedConsent: Consent;
170
+ /**
171
+ * consentPath returns the canonical on-disk path used by this module
172
+ * (`<XDG_CONFIG_HOME>/kit/config.yaml`). Useful for `kit telemetry
173
+ * status` diagnostics and SDK consumers that want to surface the
174
+ * location.
175
+ */
176
+ declare function consentPath(): string;
177
+ /**
178
+ * loadConsent reads and parses the consent file, returning a fully
179
+ * resolved Consent struct. Failure modes fold to `deniedConsent`:
180
+ *
181
+ * - File missing → denied.
182
+ * - File unreadable → denied.
183
+ * - YAML parse error → denied.
184
+ * - Missing `kit.telemetry.consent` block (and no legacy) → denied.
185
+ * - `state` neither "granted" nor "denied" → denied.
186
+ *
187
+ * `state: "denied"` returns a Consent with `allowed=false` but with the
188
+ * other fields populated, so callers can distinguish an explicit deny
189
+ * from a fail-closed default.
190
+ *
191
+ * Read order: canonical `config.yaml` (`kit.telemetry.consent`) first,
192
+ * then legacy `telemetry.yaml` (`telemetry.consent`) as a fallback.
193
+ */
194
+ declare function loadConsent(): Promise<Consent>;
195
+
196
+ /**
197
+ * redactString applies every pattern in the opinionated set to `s`.
198
+ * Returns a new string; the input is never mutated.
199
+ */
200
+ declare function redactString(s: string): string;
201
+ /**
202
+ * redact returns a NEW value with the opinionated regex set applied to
203
+ * every reachable string. Walks plain objects and arrays recursively.
204
+ * Non-string scalars (number, boolean, null, undefined, bigint, symbol)
205
+ * pass through unchanged. Input is never mutated.
206
+ *
207
+ * NOT parity with `go/core/redact`. Use a per-Client redactor callback
208
+ * for stricter or custom rules; this is the default-on backstop.
209
+ */
210
+ declare function redact(value: unknown): unknown;
211
+
212
+ /** Sink kinds understood by the Client. */
213
+ type SinkKind = 'https' | 'jsonl';
214
+ /**
215
+ * ClientOptions tune the Client. Every field has an env-var equivalent
216
+ * so adopters can configure via the process environment without a
217
+ * code-side touch.
218
+ */
219
+ interface ClientOptions {
220
+ /** HTTPS endpoint for the `https` sink. Env: `KIT_TELEMETRY_ENDPOINT`. */
221
+ endpoint?: string;
222
+ /** Sink kind. Env: `KIT_TELEMETRY_SINK`. Default `jsonl`. */
223
+ sink?: SinkKind;
224
+ /** Target file for the `jsonl` sink. Env: `KIT_TELEMETRY_SINK_FILE`. */
225
+ sinkFile?: string;
226
+ /** Bounded queue capacity. Env: `KIT_TELEMETRY_QUEUE_SIZE`. Default 1024. */
227
+ queueSize?: number;
228
+ /** Custom redactor — runs BEFORE the default opinionated redact pass. */
229
+ redactor?: (attrs: Record<string, unknown>) => Record<string, unknown>;
230
+ /** SDK version surfaced in the envelope's `sdk_version` field. */
231
+ sdkVersion?: string;
232
+ }
233
+ /**
234
+ * Envelope shape this Client emits. Aligned with the cross-language
235
+ * event-schema doc's "common fields" plus the TS/Py free-form `event`
236
+ * + `attrs` extension.
237
+ *
238
+ * `attrs` is `null` when `mode === Mode.Anon` (matches the rs SDK's
239
+ * ``Value::Null`` strip) — the key stays for envelope-shape stability,
240
+ * the payload is dropped to avoid PII leakage. In `Mode.Full` it carries
241
+ * the caller's attrs dict after the redactor pipeline.
242
+ */
243
+ interface Envelope {
244
+ schema_version: string;
245
+ sdk_lang: 'ts';
246
+ sdk_version: string;
247
+ installation_id: string;
248
+ mode: Mode;
249
+ occurred_at: string;
250
+ event: string;
251
+ attrs: Record<string, unknown> | null;
252
+ }
253
+ /**
254
+ * Client is the non-blocking telemetry emitter. Construct one per
255
+ * process (or per long-lived adopter context) and call `record()` from
256
+ * any path; call `shutdown()` before process exit to drain queued
257
+ * events.
258
+ */
259
+ declare class Client {
260
+ private readonly endpoint?;
261
+ private readonly sinkKind;
262
+ private readonly sinkFile;
263
+ private readonly queueCap;
264
+ private readonly userRedactor?;
265
+ private readonly sdkVersion;
266
+ private readonly queue;
267
+ private dropped;
268
+ private installIdPromise?;
269
+ private flushTimer?;
270
+ private flushing;
271
+ private closed;
272
+ constructor(opts?: ClientOptions);
273
+ /**
274
+ * record enqueues an event for background delivery. Returns
275
+ * synchronously; never throws. Gating order: closed → consent → mode.
276
+ * Queue-full bumps `droppedCount` and returns silently.
277
+ */
278
+ record(event: string, attrs?: Record<string, unknown>): void;
279
+ /** Saturation counter — reads, not writes. */
280
+ get droppedCount(): number;
281
+ /**
282
+ * shutdown stops the flush timer, drains pending events to the sink,
283
+ * and resolves once drained OR the timeout elapses (default 5000ms).
284
+ * Idempotent.
285
+ */
286
+ shutdown(timeoutMs?: number): Promise<void>;
287
+ /**
288
+ * drainOnce ships every event currently in the queue (snapshot at
289
+ * call time) to the configured sink. Errors bump `dropped` but never
290
+ * propagate.
291
+ */
292
+ private drainOnce;
293
+ /**
294
+ * envelopeBatch materialises pending records into on-wire envelopes,
295
+ * applying the user redactor first and then the default `redact()`
296
+ * pass. install_id is resolved lazily + cached.
297
+ */
298
+ private envelopeBatch;
299
+ /**
300
+ * shipHttps POSTs the batch as NDJSON. One retry on 5xx OR network
301
+ * error, then drops the batch. `AbortController` enforces the
302
+ * connect + total timeouts.
303
+ */
304
+ private shipHttps;
305
+ /**
306
+ * shipJsonl appends envelopes as NDJSON to `sinkFile`. Rotates to
307
+ * `<sinkFile>.1` once the file crosses `JSONL_ROTATE_BYTES`. Single
308
+ * append per batch keeps the I/O cost predictable.
309
+ */
310
+ private shipJsonl;
311
+ /** Rotate the JSONL sink when it crosses the size threshold. */
312
+ private maybeRotateJsonl;
313
+ }
314
+
315
+ export { Client, type ClientOptions, type Consent, type Envelope, Mode, type SinkKind, consentPath, deniedConsent, getInstallId, installIdPath, loadConsent, parseMode, redact, redactString, resetForTest, resolveMode, rotate };