@intentproof/sdk 0.1.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/dist/index.cjs ADDED
@@ -0,0 +1,783 @@
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/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ BoundedQueueExporter: () => BoundedQueueExporter,
24
+ HttpExporter: () => HttpExporter,
25
+ IntentProofClient: () => IntentProofClient,
26
+ MemoryExporter: () => MemoryExporter,
27
+ VERSION: () => VERSION,
28
+ assertCorrelationId: () => assertCorrelationId,
29
+ assertWrapOptionsShape: () => assertWrapOptionsShape,
30
+ client: () => client,
31
+ createIntentProofClient: () => createIntentProofClient,
32
+ getCorrelationId: () => getCorrelationId,
33
+ getIntentProofClient: () => getIntentProofClient,
34
+ runWithCorrelationId: () => runWithCorrelationId,
35
+ snapshot: () => snapshot
36
+ });
37
+ module.exports = __toCommonJS(index_exports);
38
+
39
+ // src/client.ts
40
+ var import_async_hooks = require("async_hooks");
41
+ var import_crypto = require("crypto");
42
+
43
+ // src/exporters/memory.ts
44
+ var MemoryExporter = class {
45
+ maxEvents;
46
+ events = [];
47
+ constructor(options = {}) {
48
+ const cap = options.maxEvents ?? 1e3;
49
+ if (!Number.isFinite(cap) || cap < 1) {
50
+ throw new TypeError('MemoryExporter: "maxEvents" must be a finite number >= 1');
51
+ }
52
+ this.maxEvents = Math.trunc(cap);
53
+ }
54
+ export(event) {
55
+ this.events.push(event);
56
+ const overflow = this.events.length - this.maxEvents;
57
+ if (overflow > 0) this.events.splice(0, overflow);
58
+ }
59
+ /** Mutable snapshot for inspection — newest last. */
60
+ getEvents() {
61
+ return this.events;
62
+ }
63
+ clear() {
64
+ this.events.length = 0;
65
+ }
66
+ flush() {
67
+ return Promise.resolve();
68
+ }
69
+ };
70
+
71
+ // src/runtime.ts
72
+ function describeValueType(value) {
73
+ if (value === null) return "null";
74
+ if (Array.isArray(value)) return "array";
75
+ return typeof value;
76
+ }
77
+ function isPromiseLike(x) {
78
+ return x !== null && typeof x === "object" && typeof x.then === "function";
79
+ }
80
+
81
+ // src/snapshot.ts
82
+ var DEFAULT_MAX_DEPTH = 6;
83
+ var DEFAULT_MAX_KEYS = 50;
84
+ function snapshotLimit(n, fallback) {
85
+ if (n === void 0) return fallback;
86
+ if (!Number.isFinite(n)) return fallback;
87
+ const i = Math.trunc(n);
88
+ return i < 0 ? fallback : i;
89
+ }
90
+ function snapshotStringLimit(n) {
91
+ if (n === void 0) return void 0;
92
+ if (!Number.isFinite(n)) return void 0;
93
+ const i = Math.trunc(n);
94
+ return i < 0 ? void 0 : i;
95
+ }
96
+ function normalizeRedactSet(redactKeys) {
97
+ if (!redactKeys?.length) return void 0;
98
+ const set = new Set(
99
+ redactKeys.filter((k) => typeof k === "string" && k.length > 0).map((k) => k.toLowerCase())
100
+ );
101
+ return set.size > 0 ? set : void 0;
102
+ }
103
+ function shouldRedactKey(key, redact) {
104
+ if (!redact) return false;
105
+ return redact.has(key.toLowerCase());
106
+ }
107
+ function truncateString(s, maxLen) {
108
+ if (maxLen === void 0 || s.length <= maxLen) return s;
109
+ return `${s.slice(0, maxLen)}\u2026[truncated ${s.length - maxLen} chars]`;
110
+ }
111
+ function snapshot(value, options = {}) {
112
+ const maxDepth = snapshotLimit(options.maxDepth, DEFAULT_MAX_DEPTH);
113
+ const maxKeys = snapshotLimit(options.maxKeys, DEFAULT_MAX_KEYS);
114
+ const maxStringLength = snapshotStringLimit(options.maxStringLength);
115
+ const redact = normalizeRedactSet(options.redactKeys);
116
+ const seen = /* @__PURE__ */ new WeakSet();
117
+ function walk(v, depth) {
118
+ if (v === null || v === void 0) return v;
119
+ const t = typeof v;
120
+ if (t === "string" || t === "number" || t === "boolean") {
121
+ if (t === "string") return truncateString(v, maxStringLength);
122
+ return v;
123
+ }
124
+ if (t === "bigint") return v.toString();
125
+ if (t === "symbol") return v.toString();
126
+ if (t === "function") {
127
+ const fn = v;
128
+ return `[Function ${fn.name || "anonymous"}]`;
129
+ }
130
+ if (v instanceof Date) return v.toISOString();
131
+ if (Array.isArray(v)) {
132
+ if (depth >= maxDepth) return "[Array]";
133
+ return v.slice(0, maxKeys).map((item) => walk(item, depth + 1));
134
+ }
135
+ if (t === "object") {
136
+ const o = v;
137
+ if (seen.has(o)) return "[Circular]";
138
+ seen.add(o);
139
+ if (depth >= maxDepth) return "[Object]";
140
+ const out = {};
141
+ const keys = Object.keys(o);
142
+ let n = 0;
143
+ for (const k of keys) {
144
+ if (n >= maxKeys) {
145
+ out["\u2026"] = `${keys.length - maxKeys} more keys`;
146
+ break;
147
+ }
148
+ try {
149
+ if (shouldRedactKey(k, redact)) {
150
+ out[k] = "[REDACTED]";
151
+ } else {
152
+ out[k] = walk(o[k], depth + 1);
153
+ }
154
+ } catch {
155
+ out[k] = "[Unserializable]";
156
+ }
157
+ n += 1;
158
+ }
159
+ return out;
160
+ }
161
+ }
162
+ try {
163
+ return walk(value, 0);
164
+ } catch {
165
+ return "[SnapshotError]";
166
+ }
167
+ }
168
+
169
+ // src/client.ts
170
+ var correlationStore = new import_async_hooks.AsyncLocalStorage();
171
+ function assertCorrelationId(id) {
172
+ if (typeof id !== "string") {
173
+ throw new TypeError(
174
+ `IntentProofClient: "correlationId" must be a string, got ${describeValueType(id)}`
175
+ );
176
+ }
177
+ if (id.trim().length === 0) {
178
+ throw new TypeError(
179
+ `IntentProofClient: "correlationId" must be a non-empty string (trimmed length is 0)`
180
+ );
181
+ }
182
+ }
183
+ function getCorrelationId() {
184
+ return correlationStore.getStore();
185
+ }
186
+ function runWithCorrelationId(correlationId, fn) {
187
+ if (typeof fn !== "function") {
188
+ throw new TypeError(
189
+ "IntentProofClient: expected runWithCorrelationId(correlationId, fn)"
190
+ );
191
+ }
192
+ assertCorrelationId(correlationId);
193
+ return correlationStore.run(correlationId, fn);
194
+ }
195
+ function defaultOnExporterError(error, _event) {
196
+ console.error("[intentproof] exporter error", error);
197
+ }
198
+ function toErrorSnapshot(e, includeStack) {
199
+ if (e instanceof Error) {
200
+ return includeStack ? { name: e.name, message: e.message, stack: e.stack } : { name: e.name, message: e.message };
201
+ }
202
+ return { name: "Error", message: String(e) };
203
+ }
204
+ function assertExporterAtIndex(ex, index) {
205
+ if (ex == null || typeof ex !== "object" || typeof ex.export !== "function") {
206
+ throw new TypeError(
207
+ `IntentProofClient: exporters[${index}] must be an object with an export() method`
208
+ );
209
+ }
210
+ }
211
+ function assertAttributesRecord(label, value) {
212
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
213
+ throw new TypeError(
214
+ `IntentProofClient: ${label} must be a plain object, got ${describeValueType(value)}`
215
+ );
216
+ }
217
+ const o = value;
218
+ for (const key of Object.keys(o)) {
219
+ const v = o[key];
220
+ const t = typeof v;
221
+ if (t !== "string" && t !== "number" && t !== "boolean") {
222
+ throw new TypeError(
223
+ `IntentProofClient: ${label}[${JSON.stringify(key)}] must be a string, number, or boolean, got ${describeValueType(v)}`
224
+ );
225
+ }
226
+ }
227
+ }
228
+ function assertWrapOptionsShape(options) {
229
+ if (typeof options.intent !== "string") {
230
+ throw new TypeError(
231
+ `IntentProofClient: "intent" must be a string, got ${describeValueType(options.intent)}`
232
+ );
233
+ }
234
+ if (options.intent.trim().length === 0) {
235
+ throw new TypeError(
236
+ `IntentProofClient: "intent" must be a non-empty string (trimmed length is 0)`
237
+ );
238
+ }
239
+ if (typeof options.action !== "string") {
240
+ throw new TypeError(
241
+ `IntentProofClient: "action" must be a string, got ${describeValueType(options.action)}`
242
+ );
243
+ }
244
+ if (options.action.trim().length === 0) {
245
+ throw new TypeError(
246
+ `IntentProofClient: "action" must be a non-empty string (trimmed length is 0)`
247
+ );
248
+ }
249
+ if (options.correlationId !== void 0 && typeof options.correlationId !== "string") {
250
+ throw new TypeError(
251
+ `IntentProofClient: "correlationId" must be a string when provided, got ${describeValueType(options.correlationId)}`
252
+ );
253
+ }
254
+ if (options.correlationId !== void 0 && options.correlationId.trim().length === 0) {
255
+ throw new TypeError(
256
+ `IntentProofClient: "correlationId" must be a non-empty string when provided (trimmed length is 0)`
257
+ );
258
+ }
259
+ if (options.attributes !== void 0) {
260
+ assertAttributesRecord("WrapOptions.attributes", options.attributes);
261
+ }
262
+ if (options.includeErrorStack !== void 0) {
263
+ if (typeof options.includeErrorStack !== "boolean") {
264
+ throw new TypeError(
265
+ `IntentProofClient: "includeErrorStack" must be a boolean when provided, got ${describeValueType(options.includeErrorStack)}`
266
+ );
267
+ }
268
+ }
269
+ }
270
+ var IntentProofClient = class {
271
+ exporters = [new MemoryExporter()];
272
+ onExporterError = defaultOnExporterError;
273
+ defaultAttributes = {};
274
+ includeErrorStack = true;
275
+ constructor(config = {}) {
276
+ this.configure(config);
277
+ }
278
+ configure(config) {
279
+ if (config.exporters !== void 0) {
280
+ for (let i = 0; i < config.exporters.length; i++) {
281
+ assertExporterAtIndex(config.exporters[i], i);
282
+ }
283
+ this.exporters = [...config.exporters];
284
+ }
285
+ if (config.onExporterError !== void 0) {
286
+ if (typeof config.onExporterError !== "function") {
287
+ throw new TypeError(
288
+ `IntentProofClient: onExporterError must be a function, got ${describeValueType(config.onExporterError)}`
289
+ );
290
+ }
291
+ this.onExporterError = config.onExporterError;
292
+ }
293
+ if (config.defaultAttributes !== void 0) {
294
+ assertAttributesRecord("defaultAttributes", config.defaultAttributes);
295
+ this.defaultAttributes = config.defaultAttributes;
296
+ }
297
+ if (config.includeErrorStack !== void 0) {
298
+ if (typeof config.includeErrorStack !== "boolean") {
299
+ throw new TypeError(
300
+ `IntentProofClient: includeErrorStack must be a boolean when provided, got ${describeValueType(config.includeErrorStack)}`
301
+ );
302
+ }
303
+ this.includeErrorStack = config.includeErrorStack;
304
+ }
305
+ }
306
+ /**
307
+ * Await optional {@link Exporter.flush} on each exporter (parallel).
308
+ * Used for graceful shutdown or tests.
309
+ */
310
+ flush() {
311
+ return Promise.all(
312
+ this.exporters.map(
313
+ (ex) => typeof ex.flush === "function" ? Promise.resolve(ex.flush()) : Promise.resolve()
314
+ )
315
+ ).then(() => {
316
+ });
317
+ }
318
+ /**
319
+ * {@link Exporter.shutdown} when present, otherwise {@link Exporter.flush}.
320
+ */
321
+ shutdown() {
322
+ return Promise.all(
323
+ this.exporters.map((ex) => {
324
+ if (typeof ex.shutdown === "function") {
325
+ return Promise.resolve(ex.shutdown());
326
+ }
327
+ if (typeof ex.flush === "function") {
328
+ return Promise.resolve(ex.flush());
329
+ }
330
+ return Promise.resolve();
331
+ })
332
+ ).then(() => {
333
+ });
334
+ }
335
+ /** Read active correlation id (AsyncLocalStorage). */
336
+ getCorrelationId() {
337
+ return getCorrelationId();
338
+ }
339
+ withCorrelation(correlationIdOrFn, maybeFn) {
340
+ if (typeof correlationIdOrFn === "function") {
341
+ return runWithCorrelationId((0, import_crypto.randomUUID)(), correlationIdOrFn);
342
+ }
343
+ if (typeof correlationIdOrFn !== "string") {
344
+ throw new TypeError(
345
+ "IntentProofClient: withCorrelation: correlation id must be a string"
346
+ );
347
+ }
348
+ if (typeof maybeFn !== "function") {
349
+ throw new TypeError(
350
+ "IntentProofClient: expected withCorrelation(fn) or withCorrelation(correlationId, fn)"
351
+ );
352
+ }
353
+ const fn = maybeFn;
354
+ const id = correlationIdOrFn;
355
+ if (id.trim().length === 0) {
356
+ return runWithCorrelationId((0, import_crypto.randomUUID)(), fn);
357
+ }
358
+ return runWithCorrelationId(id, fn);
359
+ }
360
+ /**
361
+ * Wrap a function to emit one `ExecutionEvent` per invocation (sync or async).
362
+ */
363
+ wrap(options, fn) {
364
+ assertWrapOptionsShape(options);
365
+ if (typeof fn !== "function") {
366
+ throw new TypeError(
367
+ `IntentProofClient: wrap() second argument must be a function, got ${describeValueType(fn)}`
368
+ );
369
+ }
370
+ const self = this;
371
+ const wrapped = function(...args) {
372
+ const correlationId = options.correlationId ?? getCorrelationId() ?? void 0;
373
+ const startedAt = /* @__PURE__ */ new Date();
374
+ const serOpts = {
375
+ maxDepth: options.maxDepth,
376
+ maxKeys: options.maxKeys,
377
+ redactKeys: options.redactKeys,
378
+ maxStringLength: options.maxStringLength
379
+ };
380
+ let inputs;
381
+ if (options.captureInput) {
382
+ try {
383
+ inputs = options.captureInput(args);
384
+ } catch {
385
+ inputs = snapshot(args, serOpts);
386
+ }
387
+ } else {
388
+ inputs = snapshot(args, serOpts);
389
+ }
390
+ const base = {
391
+ id: (0, import_crypto.randomUUID)(),
392
+ correlationId,
393
+ intent: options.intent,
394
+ action: options.action,
395
+ inputs,
396
+ startedAt: startedAt.toISOString(),
397
+ attributes: mergeAttrs(self.defaultAttributes, options.attributes)
398
+ };
399
+ try {
400
+ const out = fn.apply(this, args);
401
+ if (isPromiseLike(out)) {
402
+ return self.handleAsync(out, base, options, serOpts, startedAt);
403
+ }
404
+ self.emitComplete(
405
+ base,
406
+ "ok",
407
+ out,
408
+ void 0,
409
+ options,
410
+ serOpts,
411
+ startedAt,
412
+ self.includeErrorStack
413
+ );
414
+ return out;
415
+ } catch (e) {
416
+ self.emitComplete(
417
+ base,
418
+ "error",
419
+ void 0,
420
+ e,
421
+ options,
422
+ serOpts,
423
+ startedAt,
424
+ self.includeErrorStack
425
+ );
426
+ throw e;
427
+ }
428
+ };
429
+ Object.defineProperty(wrapped, "name", {
430
+ value: `intentproof(${fn.name || "anonymous"})`,
431
+ configurable: true
432
+ });
433
+ return wrapped;
434
+ }
435
+ handleAsync(p, base, options, serOpts, startedAt) {
436
+ const includeStack = this.includeErrorStack;
437
+ return Promise.resolve(p).then(
438
+ (value) => {
439
+ this.emitComplete(
440
+ base,
441
+ "ok",
442
+ value,
443
+ void 0,
444
+ options,
445
+ serOpts,
446
+ startedAt,
447
+ includeStack
448
+ );
449
+ return value;
450
+ },
451
+ (err) => {
452
+ this.emitComplete(
453
+ base,
454
+ "error",
455
+ void 0,
456
+ err,
457
+ options,
458
+ serOpts,
459
+ startedAt,
460
+ includeStack
461
+ );
462
+ throw err;
463
+ }
464
+ );
465
+ }
466
+ emitComplete(base, status, result, error, options, serOpts, startedAt, defaultIncludeErrorStack) {
467
+ const completedAt = /* @__PURE__ */ new Date();
468
+ const durationMs = completedAt.getTime() - startedAt.getTime();
469
+ let output;
470
+ let errSnap;
471
+ const includeStack = options.includeErrorStack ?? defaultIncludeErrorStack;
472
+ if (status === "ok") {
473
+ try {
474
+ output = options.captureOutput ? options.captureOutput(result) : snapshot(result, serOpts);
475
+ } catch {
476
+ output = snapshot(result, serOpts);
477
+ }
478
+ } else {
479
+ errSnap = toErrorSnapshot(error, includeStack);
480
+ if (options.captureError) {
481
+ try {
482
+ output = options.captureError(error);
483
+ } catch {
484
+ output = void 0;
485
+ }
486
+ }
487
+ }
488
+ const event = status === "ok" ? {
489
+ ...base,
490
+ status,
491
+ completedAt: completedAt.toISOString(),
492
+ durationMs,
493
+ output
494
+ } : {
495
+ ...base,
496
+ status,
497
+ completedAt: completedAt.toISOString(),
498
+ durationMs,
499
+ error: errSnap,
500
+ ...output !== void 0 ? { output } : {}
501
+ };
502
+ this.dispatch(event);
503
+ }
504
+ dispatch(event) {
505
+ for (const ex of this.exporters) {
506
+ try {
507
+ const r = ex.export(event);
508
+ if (isPromiseLike(r)) {
509
+ void r.catch((e) => this.onExporterError(e, event));
510
+ }
511
+ } catch (e) {
512
+ this.onExporterError(e, event);
513
+ }
514
+ }
515
+ }
516
+ };
517
+ function mergeAttrs(a, b) {
518
+ if (!b || Object.keys(b).length === 0) {
519
+ return Object.keys(a).length ? { ...a } : void 0;
520
+ }
521
+ return { ...a, ...b };
522
+ }
523
+ var defaultClient = null;
524
+ function getIntentProofClient() {
525
+ if (!defaultClient) defaultClient = new IntentProofClient();
526
+ return defaultClient;
527
+ }
528
+
529
+ // src/exporters/http.ts
530
+ var HTTP_EXPORTER_FALLBACK_BODY = '{"intentproof":"1","eventSerializeFailed":true}';
531
+ function safeJsonEnvelope(event) {
532
+ try {
533
+ return JSON.stringify({ intentproof: "1", event });
534
+ } catch {
535
+ try {
536
+ return JSON.stringify({
537
+ intentproof: "1",
538
+ eventPartial: {
539
+ id: event.id,
540
+ action: event.action,
541
+ intent: event.intent,
542
+ status: event.status,
543
+ correlationId: event.correlationId,
544
+ startedAt: event.startedAt,
545
+ completedAt: event.completedAt,
546
+ durationMs: event.durationMs
547
+ },
548
+ note: "full event not JSON-serializable"
549
+ });
550
+ } catch {
551
+ return HTTP_EXPORTER_FALLBACK_BODY;
552
+ }
553
+ }
554
+ }
555
+ var HttpExporter = class {
556
+ url;
557
+ method;
558
+ headers;
559
+ body;
560
+ awaitEach;
561
+ timeoutMs;
562
+ onError;
563
+ inFlight = /* @__PURE__ */ new Set();
564
+ closed = false;
565
+ constructor(options) {
566
+ if (typeof options.url !== "string") {
567
+ throw new TypeError(
568
+ `HttpExporter: "url" must be a non-empty string, got ${describeValueType(options.url)}`
569
+ );
570
+ }
571
+ if (options.url.trim().length === 0) {
572
+ throw new TypeError(
573
+ 'HttpExporter: "url" must be a non-empty string (trimmed length is 0)'
574
+ );
575
+ }
576
+ this.url = options.url;
577
+ this.method = (options.method ?? "POST").trim() || "POST";
578
+ const rawHeaders = options.headers;
579
+ const extraHeaders = rawHeaders !== void 0 && rawHeaders !== null && typeof rawHeaders === "object" && !Array.isArray(rawHeaders) ? rawHeaders : {};
580
+ this.headers = {
581
+ "content-type": "application/json",
582
+ ...extraHeaders
583
+ };
584
+ this.body = options.body ?? ((event) => safeJsonEnvelope(event));
585
+ this.awaitEach = options.awaitEach ?? false;
586
+ if (options.timeoutMs !== void 0) {
587
+ const t = options.timeoutMs;
588
+ if (!Number.isFinite(t) || t <= 0) {
589
+ throw new TypeError(
590
+ 'HttpExporter: "timeoutMs" must be a finite number > 0 when set'
591
+ );
592
+ }
593
+ this.timeoutMs = Math.trunc(t);
594
+ } else {
595
+ this.timeoutMs = void 0;
596
+ }
597
+ this.onError = options.onError;
598
+ }
599
+ track(p) {
600
+ this.inFlight.add(p);
601
+ void p.finally(() => this.inFlight.delete(p));
602
+ }
603
+ export(event) {
604
+ if (this.closed) {
605
+ this.onError?.(new Error("HttpExporter has been shut down"), event);
606
+ return;
607
+ }
608
+ let payload;
609
+ try {
610
+ payload = this.body(event);
611
+ } catch (e) {
612
+ this.onError?.(e, event);
613
+ payload = safeJsonEnvelope(event);
614
+ }
615
+ const run = async () => {
616
+ try {
617
+ const res = await fetch(this.url, {
618
+ method: this.method,
619
+ headers: this.headers,
620
+ body: payload,
621
+ credentials: "omit",
622
+ signal: this.timeoutMs !== void 0 ? AbortSignal.timeout(this.timeoutMs) : void 0
623
+ });
624
+ if (!res.ok) {
625
+ const err = new Error(`HTTP ${res.status}: ${res.statusText}`);
626
+ this.onError?.(err, event);
627
+ }
628
+ } catch (e) {
629
+ this.onError?.(e, event);
630
+ }
631
+ };
632
+ const p = run();
633
+ this.track(p);
634
+ if (this.awaitEach) return p;
635
+ void p;
636
+ }
637
+ /** Waits until every started request has settled (success or failure). */
638
+ flush() {
639
+ if (this.inFlight.size === 0) return Promise.resolve();
640
+ return Promise.all([...this.inFlight]).then(() => {
641
+ });
642
+ }
643
+ /** Stops accepting new events and waits for in-flight requests to finish. */
644
+ async shutdown() {
645
+ this.closed = true;
646
+ await this.flush();
647
+ }
648
+ };
649
+
650
+ // src/exporters/queue.ts
651
+ var BoundedQueueExporter = class {
652
+ inner;
653
+ maxConcurrent;
654
+ maxQueue;
655
+ strategy;
656
+ onDrop;
657
+ onInnerError;
658
+ queue = [];
659
+ active = 0;
660
+ /** When false, {@link export} drops events with reason `shutdown`; queued work still drains. */
661
+ accepting = true;
662
+ idleResolvers = [];
663
+ constructor(options) {
664
+ const inner = options.exporter;
665
+ if (inner == null || typeof inner !== "object" || typeof inner.export !== "function") {
666
+ throw new TypeError(
667
+ 'BoundedQueueExporter: "exporter" must be an object with an export() method'
668
+ );
669
+ }
670
+ this.inner = inner;
671
+ const rawMc = options.maxConcurrent ?? 4;
672
+ this.maxConcurrent = !Number.isFinite(rawMc) ? 4 : Math.max(1, Math.trunc(rawMc));
673
+ const rawQ = options.maxQueue ?? 1e3;
674
+ if (!Number.isFinite(rawQ)) {
675
+ this.maxQueue = 1e3;
676
+ } else {
677
+ const q = Math.trunc(rawQ);
678
+ if (q === 0) {
679
+ this.maxQueue = 0;
680
+ } else if (q < 0) {
681
+ this.maxQueue = 1e3;
682
+ } else {
683
+ this.maxQueue = q;
684
+ }
685
+ }
686
+ const strategy = options.strategy ?? "drop-newest";
687
+ if (strategy !== "drop-newest" && strategy !== "drop-oldest") {
688
+ throw new TypeError(
689
+ 'BoundedQueueExporter: "strategy" must be "drop-newest" or "drop-oldest"'
690
+ );
691
+ }
692
+ this.strategy = strategy;
693
+ this.onDrop = options.onDrop;
694
+ this.onInnerError = options.onInnerError;
695
+ }
696
+ export(event) {
697
+ if (!this.accepting) {
698
+ this.onDrop?.(event, "shutdown");
699
+ return;
700
+ }
701
+ const cap = this.maxQueue <= 0 ? Number.POSITIVE_INFINITY : this.maxQueue;
702
+ if (this.queue.length >= cap) {
703
+ if (this.strategy === "drop-oldest") {
704
+ const dropped = this.queue.shift();
705
+ if (dropped) this.onDrop?.(dropped, "queue-overflow-drop-oldest");
706
+ this.queue.push(event);
707
+ } else {
708
+ this.onDrop?.(event, "queue-overflow-drop-newest");
709
+ }
710
+ this.pump();
711
+ return;
712
+ }
713
+ this.queue.push(event);
714
+ this.pump();
715
+ }
716
+ pump() {
717
+ while (this.active < this.maxConcurrent && this.queue.length > 0) {
718
+ const next = this.queue.shift();
719
+ this.active++;
720
+ void this.runInner(next).finally(() => {
721
+ this.active--;
722
+ this.pump();
723
+ this.resolveIdleWaitersIfNeeded();
724
+ });
725
+ }
726
+ }
727
+ async runInner(event) {
728
+ try {
729
+ const r = this.inner.export(event);
730
+ if (isPromiseLike(r)) await r;
731
+ } catch (e) {
732
+ this.onInnerError?.(e, event);
733
+ }
734
+ }
735
+ resolveIdleWaitersIfNeeded() {
736
+ if (this.queue.length === 0 && this.active === 0) {
737
+ const waiters = this.idleResolvers;
738
+ this.idleResolvers = [];
739
+ for (const r of waiters) r();
740
+ }
741
+ }
742
+ /** Resolves when the queue is empty and no inner export is in flight. */
743
+ flush() {
744
+ if (this.queue.length === 0 && this.active === 0) {
745
+ return Promise.resolve();
746
+ }
747
+ return new Promise((resolve) => {
748
+ this.idleResolvers.push(resolve);
749
+ });
750
+ }
751
+ /**
752
+ * Stops accepting new events; does **not** drop items already in the queue—
753
+ * {@link flush} waits until queued and in-flight work finishes.
754
+ */
755
+ async shutdown() {
756
+ this.accepting = false;
757
+ await this.flush();
758
+ }
759
+ };
760
+
761
+ // src/index.ts
762
+ var VERSION = "0.1.0";
763
+ var client = getIntentProofClient();
764
+ function createIntentProofClient(config) {
765
+ return new IntentProofClient(config);
766
+ }
767
+ // Annotate the CommonJS export names for ESM import in node:
768
+ 0 && (module.exports = {
769
+ BoundedQueueExporter,
770
+ HttpExporter,
771
+ IntentProofClient,
772
+ MemoryExporter,
773
+ VERSION,
774
+ assertCorrelationId,
775
+ assertWrapOptionsShape,
776
+ client,
777
+ createIntentProofClient,
778
+ getCorrelationId,
779
+ getIntentProofClient,
780
+ runWithCorrelationId,
781
+ snapshot
782
+ });
783
+ //# sourceMappingURL=index.cjs.map