@drip-sdk/node 1.0.10 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -140,6 +140,327 @@ declare class StreamMeter {
140
140
  reset(): void;
141
141
  }
142
142
 
143
+ /**
144
+ * Production-grade resilience patterns for the Drip SDK.
145
+ *
146
+ * This module provides:
147
+ * - Rate limiting (token bucket algorithm)
148
+ * - Retry with exponential backoff
149
+ * - Circuit breaker pattern
150
+ * - Request metrics and observability
151
+ */
152
+ /**
153
+ * Configuration for rate limiting.
154
+ */
155
+ interface RateLimiterConfig {
156
+ /**
157
+ * Maximum requests per second.
158
+ * @default 100
159
+ */
160
+ requestsPerSecond: number;
161
+ /**
162
+ * Maximum burst size (bucket capacity).
163
+ * @default 200
164
+ */
165
+ burstSize: number;
166
+ /**
167
+ * Whether rate limiting is enabled.
168
+ * @default true
169
+ */
170
+ enabled: boolean;
171
+ }
172
+ /**
173
+ * Thread-safe token bucket rate limiter.
174
+ *
175
+ * Allows bursting up to `burstSize` requests, then limits to
176
+ * `requestsPerSecond` sustained rate.
177
+ */
178
+ declare class RateLimiter {
179
+ private readonly config;
180
+ private tokens;
181
+ private lastRefill;
182
+ constructor(config?: Partial<RateLimiterConfig>);
183
+ /**
184
+ * Refill tokens based on elapsed time.
185
+ */
186
+ private refill;
187
+ /**
188
+ * Acquire a token, blocking if necessary.
189
+ *
190
+ * @param timeout - Maximum time to wait for a token in ms (undefined = wait forever)
191
+ * @returns Promise that resolves to true if token acquired, false if timeout
192
+ */
193
+ acquire(timeout?: number): Promise<boolean>;
194
+ /**
195
+ * Try to acquire a token without waiting.
196
+ *
197
+ * @returns true if token acquired, false otherwise
198
+ */
199
+ tryAcquire(): boolean;
200
+ /**
201
+ * Get current number of available tokens.
202
+ */
203
+ get availableTokens(): number;
204
+ private sleep;
205
+ }
206
+ /**
207
+ * Configuration for retry behavior.
208
+ */
209
+ interface RetryConfig {
210
+ /**
211
+ * Maximum number of retry attempts.
212
+ * @default 3
213
+ */
214
+ maxRetries: number;
215
+ /**
216
+ * Base delay in milliseconds.
217
+ * @default 100
218
+ */
219
+ baseDelayMs: number;
220
+ /**
221
+ * Maximum delay in milliseconds.
222
+ * @default 10000
223
+ */
224
+ maxDelayMs: number;
225
+ /**
226
+ * Exponential backoff base.
227
+ * @default 2
228
+ */
229
+ exponentialBase: number;
230
+ /**
231
+ * Random jitter factor (0-1).
232
+ * @default 0.1
233
+ */
234
+ jitter: number;
235
+ /**
236
+ * HTTP status codes that should trigger retry.
237
+ * @default [429, 500, 502, 503, 504]
238
+ */
239
+ retryableStatusCodes: number[];
240
+ /**
241
+ * Whether retry is enabled.
242
+ * @default true
243
+ */
244
+ enabled: boolean;
245
+ }
246
+ /**
247
+ * Error thrown when all retry attempts have been exhausted.
248
+ */
249
+ declare class RetryExhaustedError extends Error {
250
+ readonly attempts: number;
251
+ readonly lastError: Error;
252
+ constructor(attempts: number, lastError: Error);
253
+ }
254
+ /**
255
+ * Calculate backoff delay for a given attempt.
256
+ */
257
+ declare function calculateBackoff(attempt: number, config: RetryConfig): number;
258
+ /**
259
+ * Check if an error is retryable based on configuration.
260
+ */
261
+ declare function isRetryableError(error: unknown, config: RetryConfig): boolean;
262
+ /**
263
+ * Circuit breaker states.
264
+ */
265
+ type CircuitState = 'closed' | 'open' | 'half_open';
266
+ /**
267
+ * Configuration for circuit breaker.
268
+ */
269
+ interface CircuitBreakerConfig {
270
+ /**
271
+ * Number of failures before opening circuit.
272
+ * @default 5
273
+ */
274
+ failureThreshold: number;
275
+ /**
276
+ * Number of successes in half-open to close circuit.
277
+ * @default 2
278
+ */
279
+ successThreshold: number;
280
+ /**
281
+ * Milliseconds to wait before transitioning from open to half-open.
282
+ * @default 30000
283
+ */
284
+ timeoutMs: number;
285
+ /**
286
+ * Whether circuit breaker is enabled.
287
+ * @default true
288
+ */
289
+ enabled: boolean;
290
+ }
291
+ /**
292
+ * Error thrown when circuit breaker is open.
293
+ */
294
+ declare class CircuitBreakerOpenError extends Error {
295
+ readonly circuitName: string;
296
+ readonly timeUntilRetryMs: number;
297
+ constructor(circuitName: string, timeUntilRetryMs: number);
298
+ }
299
+ /**
300
+ * Circuit breaker pattern implementation.
301
+ *
302
+ * Prevents cascading failures by failing fast when a service is unhealthy.
303
+ */
304
+ declare class CircuitBreaker {
305
+ readonly name: string;
306
+ private readonly config;
307
+ private state;
308
+ private failureCount;
309
+ private successCount;
310
+ private lastFailureTime;
311
+ constructor(name: string, config?: Partial<CircuitBreakerConfig>);
312
+ /**
313
+ * Get current circuit state.
314
+ */
315
+ getState(): CircuitState;
316
+ /**
317
+ * Check if state should transition based on timeout.
318
+ */
319
+ private checkStateTransition;
320
+ /**
321
+ * Record a successful call.
322
+ */
323
+ recordSuccess(): void;
324
+ /**
325
+ * Record a failed call.
326
+ */
327
+ recordFailure(): void;
328
+ /**
329
+ * Check if a request should be allowed.
330
+ */
331
+ allowRequest(): boolean;
332
+ /**
333
+ * Get milliseconds until circuit transitions to half-open.
334
+ */
335
+ getTimeUntilRetry(): number;
336
+ /**
337
+ * Reset the circuit breaker to initial state.
338
+ */
339
+ reset(): void;
340
+ }
341
+ /**
342
+ * Metrics for a single request.
343
+ */
344
+ interface RequestMetrics {
345
+ method: string;
346
+ endpoint: string;
347
+ statusCode: number | null;
348
+ durationMs: number;
349
+ success: boolean;
350
+ timestamp: number;
351
+ error?: string;
352
+ retryCount: number;
353
+ }
354
+ /**
355
+ * Aggregated metrics summary.
356
+ */
357
+ interface MetricsSummary {
358
+ windowSize: number;
359
+ totalRequests: number;
360
+ totalSuccesses: number;
361
+ totalFailures: number;
362
+ successRate: number;
363
+ avgLatencyMs: number;
364
+ minLatencyMs: number;
365
+ maxLatencyMs: number;
366
+ p50LatencyMs: number;
367
+ p95LatencyMs: number;
368
+ p99LatencyMs: number;
369
+ requestsByEndpoint: Record<string, number>;
370
+ errorsByType: Record<string, number>;
371
+ }
372
+ /**
373
+ * Collects and aggregates request metrics.
374
+ *
375
+ * Thread-safe metrics collection with windowed aggregation.
376
+ */
377
+ declare class MetricsCollector {
378
+ private readonly windowSize;
379
+ private readonly metrics;
380
+ private totalRequests;
381
+ private totalSuccesses;
382
+ private totalFailures;
383
+ constructor(windowSize?: number);
384
+ /**
385
+ * Record a request's metrics.
386
+ */
387
+ record(metrics: RequestMetrics): void;
388
+ /**
389
+ * Get aggregated metrics summary.
390
+ */
391
+ getSummary(): MetricsSummary;
392
+ /**
393
+ * Reset all metrics.
394
+ */
395
+ reset(): void;
396
+ }
397
+ /**
398
+ * Combined configuration for all resilience features.
399
+ */
400
+ interface ResilienceConfig {
401
+ rateLimiter: RateLimiterConfig;
402
+ retry: RetryConfig;
403
+ circuitBreaker: CircuitBreakerConfig;
404
+ collectMetrics: boolean;
405
+ }
406
+ /**
407
+ * Create default production configuration.
408
+ */
409
+ declare function createDefaultResilienceConfig(): ResilienceConfig;
410
+ /**
411
+ * Create configuration with all features disabled.
412
+ */
413
+ declare function createDisabledResilienceConfig(): ResilienceConfig;
414
+ /**
415
+ * Create configuration optimized for high throughput.
416
+ */
417
+ declare function createHighThroughputResilienceConfig(): ResilienceConfig;
418
+ /**
419
+ * Health status of resilience components.
420
+ */
421
+ interface ResilienceHealth {
422
+ circuitBreaker: {
423
+ state: CircuitState;
424
+ timeUntilRetryMs: number;
425
+ };
426
+ rateLimiter: {
427
+ availableTokens: number;
428
+ requestsPerSecond: number;
429
+ };
430
+ metrics: MetricsSummary | null;
431
+ }
432
+ /**
433
+ * Manages all resilience features for the SDK.
434
+ *
435
+ * Provides a unified interface for rate limiting, retry, circuit breaker,
436
+ * and metrics collection.
437
+ */
438
+ declare class ResilienceManager {
439
+ readonly config: ResilienceConfig;
440
+ readonly rateLimiter: RateLimiter;
441
+ readonly circuitBreaker: CircuitBreaker;
442
+ readonly metrics: MetricsCollector | null;
443
+ constructor(config?: Partial<ResilienceConfig>);
444
+ /**
445
+ * Execute a function with all resilience features.
446
+ *
447
+ * @param fn - The function to execute
448
+ * @param method - HTTP method for metrics
449
+ * @param endpoint - Endpoint for metrics
450
+ * @returns Result of the function
451
+ */
452
+ execute<T>(fn: () => Promise<T>, method?: string, endpoint?: string): Promise<T>;
453
+ /**
454
+ * Get current metrics summary.
455
+ */
456
+ getMetrics(): MetricsSummary | null;
457
+ /**
458
+ * Get health status of all resilience components.
459
+ */
460
+ getHealth(): ResilienceHealth;
461
+ private sleep;
462
+ }
463
+
143
464
  /**
144
465
  * Drip SDK - Usage-based billing for Node.js
145
466
  *
@@ -177,17 +498,29 @@ interface RetryOptions {
177
498
  }
178
499
  /**
179
500
  * Configuration options for the Drip SDK client.
501
+ *
502
+ * All fields are optional - the SDK will read from environment variables:
503
+ * - `DRIP_API_KEY` - Your Drip API key
504
+ * - `DRIP_BASE_URL` - Override API base URL (optional)
180
505
  */
181
506
  interface DripConfig {
182
507
  /**
183
508
  * Your Drip API key. Obtain this from the Drip dashboard.
184
- * @example "drip_live_abc123..."
509
+ * Falls back to `DRIP_API_KEY` environment variable if not provided.
510
+ *
511
+ * Supports both key types:
512
+ * - **Secret keys** (`sk_live_...` / `sk_test_...`): Full access to all endpoints
513
+ * - **Public keys** (`pk_live_...` / `pk_test_...`): Safe for client-side use.
514
+ * Can access usage, customers, charges, sessions, analytics, etc.
515
+ * Cannot access webhook management, API key management, or feature flags.
516
+ *
517
+ * @example "sk_live_abc123..." or "pk_live_abc123..."
185
518
  */
186
- apiKey: string;
519
+ apiKey?: string;
187
520
  /**
188
521
  * Base URL for the Drip API. Defaults to production API.
189
- * Override for staging/development environments.
190
- * @default "https://api.drip.dev/v1"
522
+ * Falls back to `DRIP_BASE_URL` environment variable if not provided.
523
+ * @default "https://drip-app-hlunj.ondigitalocean.app/v1"
191
524
  */
192
525
  baseUrl?: string;
193
526
  /**
@@ -195,6 +528,36 @@ interface DripConfig {
195
528
  * @default 30000
196
529
  */
197
530
  timeout?: number;
531
+ /**
532
+ * Enable production resilience features (rate limiting, retry with backoff,
533
+ * circuit breaker, metrics).
534
+ *
535
+ * - `true`: Use default production settings (100 req/s, 3 retries)
536
+ * - `'high-throughput'`: Optimized for high throughput (1000 req/s, 2 retries)
537
+ * - `ResilienceConfig`: Custom configuration object
538
+ * - `undefined`/`false`: Disabled (default for backward compatibility)
539
+ *
540
+ * @example
541
+ * ```typescript
542
+ * // Enable with defaults
543
+ * const drip = new Drip({ apiKey: '...', resilience: true });
544
+ *
545
+ * // High throughput mode
546
+ * const drip = new Drip({ apiKey: '...', resilience: 'high-throughput' });
547
+ *
548
+ * // Custom config
549
+ * const drip = new Drip({
550
+ * apiKey: '...',
551
+ * resilience: {
552
+ * rateLimiter: { requestsPerSecond: 500, burstSize: 1000, enabled: true },
553
+ * retry: { maxRetries: 5, enabled: true },
554
+ * circuitBreaker: { failureThreshold: 10, enabled: true },
555
+ * collectMetrics: true,
556
+ * },
557
+ * });
558
+ * ```
559
+ */
560
+ resilience?: boolean | 'high-throughput' | Partial<ResilienceConfig>;
198
561
  }
199
562
  /**
200
563
  * Parameters for creating a new customer.
@@ -221,8 +584,8 @@ interface CreateCustomerParams {
221
584
  interface Customer {
222
585
  /** Unique customer ID in Drip */
223
586
  id: string;
224
- /** Your business ID */
225
- businessId: string;
587
+ /** Your business ID (optional - may not be returned by all endpoints) */
588
+ businessId?: string;
226
589
  /** Your external customer ID (if provided) */
227
590
  externalCustomerId: string | null;
228
591
  /** Customer's on-chain address */
@@ -294,8 +657,8 @@ interface ChargeParams {
294
657
  */
295
658
  quantity: number;
296
659
  /**
297
- * Unique key to prevent duplicate charges.
298
- * If provided, retrying with the same key returns the original charge.
660
+ * Unique key to prevent duplicate charges and map each call to a single event.
661
+ * Auto-generated if not provided. Retrying with the same key returns the original charge.
299
662
  * @example "req_abc123"
300
663
  */
301
664
  idempotencyKey?: string;
@@ -593,7 +956,7 @@ interface CreateWorkflowParams {
593
956
  /** URL-safe identifier (lowercase alphanumeric with underscores/hyphens) */
594
957
  slug: string;
595
958
  /** Type of workflow */
596
- productSurface?: 'RPC' | 'WEBHOOK' | 'AGENT' | 'PIPELINE' | 'CUSTOM';
959
+ productSurface?: 'API' | 'RPC' | 'WEBHOOK' | 'AGENT' | 'PIPELINE' | 'CUSTOM';
597
960
  /** Optional description */
598
961
  description?: string;
599
962
  /** Additional metadata */
@@ -722,6 +1085,96 @@ interface ListMetersResponse {
722
1085
  /** Total count */
723
1086
  count: number;
724
1087
  }
1088
+ /**
1089
+ * Custom pricing map for cost estimation.
1090
+ * Maps usage type to unit price (e.g., { "api_call": "0.005", "token": "0.0001" })
1091
+ */
1092
+ type CustomPricing = Record<string, string>;
1093
+ /**
1094
+ * Parameters for estimating costs from historical usage events.
1095
+ */
1096
+ interface EstimateFromUsageParams {
1097
+ /** Filter to a specific customer (optional) */
1098
+ customerId?: string;
1099
+ /** Start of the period to estimate */
1100
+ periodStart: Date | string;
1101
+ /** End of the period to estimate */
1102
+ periodEnd: Date | string;
1103
+ /** Default price for usage types without pricing plans */
1104
+ defaultUnitPrice?: string;
1105
+ /** Include events that already have charges (default: true) */
1106
+ includeChargedEvents?: boolean;
1107
+ /** Filter to specific usage types */
1108
+ usageTypes?: string[];
1109
+ /** Custom pricing overrides (takes precedence over DB pricing) */
1110
+ customPricing?: CustomPricing;
1111
+ }
1112
+ /**
1113
+ * A usage item for hypothetical cost estimation.
1114
+ */
1115
+ interface HypotheticalUsageItem {
1116
+ /** The usage type (e.g., "api_call", "token") */
1117
+ usageType: string;
1118
+ /** The quantity of usage */
1119
+ quantity: number;
1120
+ /** Override unit price for this specific item */
1121
+ unitPriceOverride?: string;
1122
+ }
1123
+ /**
1124
+ * Parameters for estimating costs from hypothetical usage.
1125
+ */
1126
+ interface EstimateFromHypotheticalParams {
1127
+ /** List of usage items to estimate */
1128
+ items: HypotheticalUsageItem[];
1129
+ /** Default price for usage types without pricing plans */
1130
+ defaultUnitPrice?: string;
1131
+ /** Custom pricing overrides (takes precedence over DB pricing) */
1132
+ customPricing?: CustomPricing;
1133
+ }
1134
+ /**
1135
+ * A line item in the cost estimate.
1136
+ */
1137
+ interface CostEstimateLineItem {
1138
+ /** The usage type */
1139
+ usageType: string;
1140
+ /** Total quantity */
1141
+ quantity: string;
1142
+ /** Unit price used */
1143
+ unitPrice: string;
1144
+ /** Estimated cost in USDC */
1145
+ estimatedCostUsdc: string;
1146
+ /** Number of events (for usage-based estimates) */
1147
+ eventCount?: number;
1148
+ /** Whether a pricing plan was found for this usage type */
1149
+ hasPricingPlan: boolean;
1150
+ }
1151
+ /**
1152
+ * Response from cost estimation.
1153
+ */
1154
+ interface CostEstimateResponse {
1155
+ /** Business ID (optional - may not be returned by all endpoints) */
1156
+ businessId?: string;
1157
+ /** Customer ID (if filtered) */
1158
+ customerId?: string;
1159
+ /** Period start (for usage-based estimates) */
1160
+ periodStart?: string;
1161
+ /** Period end (for usage-based estimates) */
1162
+ periodEnd?: string;
1163
+ /** Breakdown by usage type */
1164
+ lineItems: CostEstimateLineItem[];
1165
+ /** Subtotal in USDC */
1166
+ subtotalUsdc: string;
1167
+ /** Total estimated cost in USDC */
1168
+ estimatedTotalUsdc: string;
1169
+ /** Currency (always USDC) */
1170
+ currency: 'USDC';
1171
+ /** Indicates this is an estimate, not a charge */
1172
+ isEstimate: true;
1173
+ /** When the estimate was generated */
1174
+ generatedAt: string;
1175
+ /** Notes about the estimate (e.g., missing pricing plans, custom pricing applied) */
1176
+ notes: string[];
1177
+ }
725
1178
  /**
726
1179
  * A single event to record in a run.
727
1180
  */
@@ -790,47 +1243,88 @@ interface RecordRunResult {
790
1243
  summary: string;
791
1244
  }
792
1245
  /**
793
- * Full run timeline response.
1246
+ * Full run timeline response from GET /runs/:id/timeline.
794
1247
  */
795
1248
  interface RunTimeline {
796
- run: {
797
- id: string;
798
- customerId: string;
799
- customerName: string | null;
800
- workflowId: string;
801
- workflowName: string;
802
- status: RunStatus;
803
- startedAt: string | null;
804
- endedAt: string | null;
805
- durationMs: number | null;
806
- errorMessage: string | null;
807
- errorCode: string | null;
808
- correlationId: string | null;
809
- metadata: Record<string, unknown> | null;
810
- };
811
- timeline: Array<{
1249
+ runId: string;
1250
+ workflowId: string | null;
1251
+ customerId: string;
1252
+ status: RunStatus;
1253
+ startedAt: string | null;
1254
+ endedAt: string | null;
1255
+ durationMs: number | null;
1256
+ events: Array<{
812
1257
  id: string;
813
1258
  eventType: string;
814
- quantity: number;
815
- units: string | null;
1259
+ actionName: string | null;
1260
+ outcome: 'SUCCESS' | 'FAILED' | 'PENDING' | 'TIMEOUT' | 'RETRYING';
1261
+ explanation: string | null;
816
1262
  description: string | null;
817
- costUnits: number | null;
818
1263
  timestamp: string;
819
- correlationId: string | null;
1264
+ durationMs: number | null;
820
1265
  parentEventId: string | null;
821
- charge: {
822
- id: string;
823
- amountUsdc: string;
824
- status: string;
1266
+ retryOfEventId: string | null;
1267
+ attemptNumber: number;
1268
+ retriedByEventId: string | null;
1269
+ costUsdc: string | null;
1270
+ isRetry: boolean;
1271
+ retryChain: {
1272
+ totalAttempts: number;
1273
+ finalOutcome: string;
1274
+ events: string[];
1275
+ } | null;
1276
+ metadata: {
1277
+ usageType: string;
1278
+ quantity: number;
1279
+ units: string | null;
825
1280
  } | null;
826
1281
  }>;
1282
+ anomalies: Array<{
1283
+ id: string;
1284
+ type: string;
1285
+ severity: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL';
1286
+ title: string;
1287
+ explanation: string;
1288
+ relatedEventIds: string[];
1289
+ detectedAt: string;
1290
+ status: 'OPEN' | 'INVESTIGATING' | 'RESOLVED' | 'FALSE_POSITIVE' | 'IGNORED';
1291
+ }>;
1292
+ summary: {
1293
+ totalEvents: number;
1294
+ byType: Record<string, number>;
1295
+ byOutcome: Record<string, number>;
1296
+ retriedEvents: number;
1297
+ failedEvents: number;
1298
+ totalCostUsdc: string | null;
1299
+ };
1300
+ hasMore: boolean;
1301
+ nextCursor: string | null;
1302
+ }
1303
+ /**
1304
+ * Run details response from GET /runs/:id.
1305
+ */
1306
+ interface RunDetails {
1307
+ id: string;
1308
+ customerId: string;
1309
+ customerName: string | null;
1310
+ workflowId: string;
1311
+ workflowName: string;
1312
+ status: RunStatus;
1313
+ startedAt: string | null;
1314
+ endedAt: string | null;
1315
+ durationMs: number | null;
1316
+ errorMessage: string | null;
1317
+ errorCode: string | null;
1318
+ correlationId: string | null;
1319
+ metadata: Record<string, unknown> | null;
827
1320
  totals: {
828
1321
  eventCount: number;
829
1322
  totalQuantity: string;
830
1323
  totalCostUnits: string;
831
- totalChargedUsdc: string;
832
1324
  };
833
- summary: string;
1325
+ _links: {
1326
+ timeline: string;
1327
+ };
834
1328
  }
835
1329
  /**
836
1330
  * Parameters for wrapping an external API call with usage tracking.
@@ -934,6 +1428,15 @@ declare class Drip {
934
1428
  private readonly apiKey;
935
1429
  private readonly baseUrl;
936
1430
  private readonly timeout;
1431
+ private readonly resilience;
1432
+ /**
1433
+ * The type of API key being used.
1434
+ *
1435
+ * - `'secret'` — Full access (sk_live_... / sk_test_...)
1436
+ * - `'public'` — Client-safe, restricted access (pk_live_... / pk_test_...)
1437
+ * - `'unknown'` — Key format not recognized (legacy or custom)
1438
+ */
1439
+ readonly keyType: 'secret' | 'public' | 'unknown';
937
1440
  /**
938
1441
  * Creates a new Drip SDK client.
939
1442
  *
@@ -942,17 +1445,41 @@ declare class Drip {
942
1445
  *
943
1446
  * @example
944
1447
  * ```typescript
1448
+ * // Basic usage
1449
+ * const drip = new Drip({
1450
+ * apiKey: 'sk_live_...',
1451
+ * });
1452
+ *
1453
+ * // With production resilience (recommended)
1454
+ * const drip = new Drip({
1455
+ * apiKey: 'sk_live_...',
1456
+ * resilience: true,
1457
+ * });
1458
+ *
1459
+ * // High throughput mode
945
1460
  * const drip = new Drip({
946
- * apiKey: 'drip_live_abc123...',
1461
+ * apiKey: 'sk_live_...',
1462
+ * resilience: 'high-throughput',
947
1463
  * });
948
1464
  * ```
949
1465
  */
950
- constructor(config: DripConfig);
1466
+ constructor(config?: DripConfig);
1467
+ /**
1468
+ * Asserts that the SDK was initialized with a secret key (sk_).
1469
+ * Throws a clear error if a public key is being used for a secret-key-only operation.
1470
+ * @internal
1471
+ */
1472
+ private assertSecretKey;
951
1473
  /**
952
1474
  * Makes an authenticated request to the Drip API.
953
1475
  * @internal
954
1476
  */
955
1477
  private request;
1478
+ /**
1479
+ * Execute the actual HTTP request (internal).
1480
+ * @internal
1481
+ */
1482
+ private rawRequest;
956
1483
  /**
957
1484
  * Pings the Drip API to check connectivity and measure latency.
958
1485
  *
@@ -973,6 +1500,45 @@ declare class Drip {
973
1500
  latencyMs: number;
974
1501
  timestamp: number;
975
1502
  }>;
1503
+ /**
1504
+ * Get SDK metrics (requires resilience to be enabled).
1505
+ *
1506
+ * Returns aggregated metrics including success rates, latencies, and errors.
1507
+ *
1508
+ * @returns Metrics summary or null if resilience is not enabled
1509
+ *
1510
+ * @example
1511
+ * ```typescript
1512
+ * const drip = new Drip({ apiKey: '...', resilience: true });
1513
+ * // ... make some requests ...
1514
+ *
1515
+ * const metrics = drip.getMetrics();
1516
+ * if (metrics) {
1517
+ * console.log(`Success rate: ${metrics.successRate.toFixed(1)}%`);
1518
+ * console.log(`P95 latency: ${metrics.p95LatencyMs.toFixed(0)}ms`);
1519
+ * }
1520
+ * ```
1521
+ */
1522
+ getMetrics(): MetricsSummary | null;
1523
+ /**
1524
+ * Get SDK health status (requires resilience to be enabled).
1525
+ *
1526
+ * Returns health status including circuit breaker state and rate limiter status.
1527
+ *
1528
+ * @returns Health status or null if resilience is not enabled
1529
+ *
1530
+ * @example
1531
+ * ```typescript
1532
+ * const drip = new Drip({ apiKey: '...', resilience: true });
1533
+ *
1534
+ * const health = drip.getHealth();
1535
+ * if (health) {
1536
+ * console.log(`Circuit: ${health.circuitBreaker.state}`);
1537
+ * console.log(`Available tokens: ${health.rateLimiter.availableTokens}`);
1538
+ * }
1539
+ * ```
1540
+ */
1541
+ getHealth(): ResilienceHealth | null;
976
1542
  /**
977
1543
  * Creates a new customer in your Drip account.
978
1544
  *
@@ -1375,8 +1941,8 @@ declare class Drip {
1375
1941
  * @example
1376
1942
  * ```typescript
1377
1943
  * const workflow = await drip.createWorkflow({
1378
- * name: 'Prescription Intake',
1379
- * slug: 'prescription_intake',
1944
+ * name: 'Document Processing',
1945
+ * slug: 'doc_processing',
1380
1946
  * productSurface: 'AGENT',
1381
1947
  * });
1382
1948
  * ```
@@ -1441,33 +2007,53 @@ declare class Drip {
1441
2007
  totalCostUnits: string | null;
1442
2008
  }>;
1443
2009
  /**
1444
- * Gets a run's full timeline with events and computed totals.
2010
+ * Gets run details with summary totals.
2011
+ *
2012
+ * For full event history with retry chains and anomalies, use `getRunTimeline()`.
2013
+ *
2014
+ * @param runId - The run ID
2015
+ * @returns Run details with totals
2016
+ *
2017
+ * @example
2018
+ * ```typescript
2019
+ * const run = await drip.getRun('run_abc123');
2020
+ * console.log(`Status: ${run.status}, Events: ${run.totals.eventCount}`);
2021
+ * ```
2022
+ */
2023
+ getRun(runId: string): Promise<RunDetails>;
2024
+ /**
2025
+ * Gets a run's full timeline with events, anomalies, and analytics.
1445
2026
  *
1446
2027
  * This is the key endpoint for debugging "what happened" in an execution.
1447
2028
  *
1448
2029
  * @param runId - The run ID
1449
- * @returns Full timeline with events and summary
2030
+ * @param options - Pagination and filtering options
2031
+ * @returns Full timeline with events, anomalies, and summary
1450
2032
  *
1451
2033
  * @example
1452
2034
  * ```typescript
1453
- * const { run, timeline, totals, summary } = await drip.getRunTimeline('run_abc123');
2035
+ * const timeline = await drip.getRunTimeline('run_abc123');
1454
2036
  *
1455
- * console.log(`Status: ${run.status}`);
1456
- * console.log(`Summary: ${summary}`);
1457
- * console.log(`Total cost: ${totals.totalCostUnits}`);
2037
+ * console.log(`Status: ${timeline.status}`);
2038
+ * console.log(`Events: ${timeline.summary.totalEvents}`);
1458
2039
  *
1459
- * for (const event of timeline) {
1460
- * console.log(`${event.eventType}: ${event.quantity} ${event.units}`);
2040
+ * for (const event of timeline.events) {
2041
+ * console.log(`${event.eventType}: ${event.outcome}`);
1461
2042
  * }
1462
2043
  * ```
1463
2044
  */
1464
- getRunTimeline(runId: string): Promise<RunTimeline>;
2045
+ getRunTimeline(runId: string, options?: {
2046
+ limit?: number;
2047
+ cursor?: string;
2048
+ includeAnomalies?: boolean;
2049
+ collapseRetries?: boolean;
2050
+ }): Promise<RunTimeline>;
1465
2051
  /**
1466
2052
  * Emits an event to a run.
1467
2053
  *
1468
- * Events can be stored idempotently when an `idempotencyKey` is provided.
2054
+ * Each event is assigned a unique idempotency key (auto-generated if not provided).
2055
+ * This maps each inference or API call to a single trackable event.
1469
2056
  * Use `Drip.generateIdempotencyKey()` for deterministic key generation.
1470
- * If `idempotencyKey` is omitted, repeated calls may create duplicate events.
1471
2057
  *
1472
2058
  * @param params - Event parameters
1473
2059
  * @returns The created event
@@ -1508,10 +2094,13 @@ declare class Drip {
1508
2094
  success: boolean;
1509
2095
  created: number;
1510
2096
  duplicates: number;
2097
+ skipped: number;
1511
2098
  events: Array<{
1512
2099
  id: string;
1513
2100
  eventType: string;
1514
2101
  isDuplicate: boolean;
2102
+ skipped?: boolean;
2103
+ reason?: string;
1515
2104
  }>;
1516
2105
  }>;
1517
2106
  /**
@@ -1540,6 +2129,82 @@ declare class Drip {
1540
2129
  * ```
1541
2130
  */
1542
2131
  listMeters(): Promise<ListMetersResponse>;
2132
+ /**
2133
+ * Estimates costs from historical usage events.
2134
+ *
2135
+ * Use this to preview what existing usage would cost before creating charges,
2136
+ * or to run "what-if" scenarios with custom pricing.
2137
+ *
2138
+ * @param params - Parameters for the estimate
2139
+ * @returns Cost estimate with line item breakdown
2140
+ *
2141
+ * @example
2142
+ * ```typescript
2143
+ * // Estimate costs for last month's usage
2144
+ * const estimate = await drip.estimateFromUsage({
2145
+ * periodStart: new Date('2024-01-01'),
2146
+ * periodEnd: new Date('2024-01-31'),
2147
+ * });
2148
+ *
2149
+ * console.log(`Estimated total: $${estimate.estimatedTotalUsdc}`);
2150
+ * ```
2151
+ *
2152
+ * @example
2153
+ * ```typescript
2154
+ * // "What-if" scenario with custom pricing
2155
+ * const estimate = await drip.estimateFromUsage({
2156
+ * periodStart: new Date('2024-01-01'),
2157
+ * periodEnd: new Date('2024-01-31'),
2158
+ * customPricing: {
2159
+ * 'api_call': '0.005', // What if we charged $0.005 per call?
2160
+ * 'token': '0.0001', // What if we charged $0.0001 per token?
2161
+ * },
2162
+ * });
2163
+ * ```
2164
+ */
2165
+ estimateFromUsage(params: EstimateFromUsageParams): Promise<CostEstimateResponse>;
2166
+ /**
2167
+ * Estimates costs from hypothetical usage.
2168
+ *
2169
+ * Use this for "what-if" scenarios, budget planning, or to preview
2170
+ * costs before usage occurs.
2171
+ *
2172
+ * @param params - Parameters for the estimate
2173
+ * @returns Cost estimate with line item breakdown
2174
+ *
2175
+ * @example
2176
+ * ```typescript
2177
+ * // Estimate what 10,000 API calls and 1M tokens would cost
2178
+ * const estimate = await drip.estimateFromHypothetical({
2179
+ * items: [
2180
+ * { usageType: 'api_call', quantity: 10000 },
2181
+ * { usageType: 'token', quantity: 1000000 },
2182
+ * ],
2183
+ * });
2184
+ *
2185
+ * console.log(`Estimated total: $${estimate.estimatedTotalUsdc}`);
2186
+ * for (const item of estimate.lineItems) {
2187
+ * console.log(` ${item.usageType}: ${item.quantity} × $${item.unitPrice} = $${item.estimatedCostUsdc}`);
2188
+ * }
2189
+ * ```
2190
+ *
2191
+ * @example
2192
+ * ```typescript
2193
+ * // Compare different pricing scenarios
2194
+ * const currentPricing = await drip.estimateFromHypothetical({
2195
+ * items: [{ usageType: 'api_call', quantity: 100000 }],
2196
+ * });
2197
+ *
2198
+ * const newPricing = await drip.estimateFromHypothetical({
2199
+ * items: [{ usageType: 'api_call', quantity: 100000 }],
2200
+ * customPricing: { 'api_call': '0.0005' }, // 50% discount
2201
+ * });
2202
+ *
2203
+ * console.log(`Current: $${currentPricing.estimatedTotalUsdc}`);
2204
+ * console.log(`With 50% discount: $${newPricing.estimatedTotalUsdc}`);
2205
+ * ```
2206
+ */
2207
+ estimateFromHypothetical(params: EstimateFromHypotheticalParams): Promise<CostEstimateResponse>;
1543
2208
  /**
1544
2209
  * Records a complete agent run in a single call.
1545
2210
  *
@@ -1560,7 +2225,7 @@ declare class Drip {
1560
2225
  * // Record a complete agent run in one call
1561
2226
  * const result = await drip.recordRun({
1562
2227
  * customerId: 'cust_123',
1563
- * workflow: 'prescription_intake', // Auto-creates if doesn't exist
2228
+ * workflow: 'doc_processing', // Auto-creates if doesn't exist
1564
2229
  * events: [
1565
2230
  * { eventType: 'agent.start', description: 'Started processing' },
1566
2231
  * { eventType: 'tool.ocr', quantity: 3, units: 'pages', costUnits: 0.15 },
@@ -1579,7 +2244,7 @@ declare class Drip {
1579
2244
  * // Record a failed run with error details
1580
2245
  * const result = await drip.recordRun({
1581
2246
  * customerId: 'cust_123',
1582
- * workflow: 'prescription_intake',
2247
+ * workflow: 'doc_processing',
1583
2248
  * events: [
1584
2249
  * { eventType: 'agent.start', description: 'Started processing' },
1585
2250
  * { eventType: 'tool.ocr', quantity: 1, units: 'pages' },
@@ -1751,4 +2416,31 @@ declare class Drip {
1751
2416
  createStreamMeter(options: StreamMeterOptions): StreamMeter;
1752
2417
  }
1753
2418
 
1754
- export { type BalanceResult, type Charge, type ChargeParams, type ChargeResult, type ChargeStatus, type CheckoutParams, type CheckoutResult, type CreateCustomerParams, type CreateWebhookParams, type CreateWebhookResponse, type CreateWorkflowParams, type Customer, type DeleteWebhookResponse, Drip, type DripConfig, DripError, type EmitEventParams, type EndRunParams, type EventResult, type ListChargesOptions, type ListChargesResponse, type ListCustomersOptions, type ListCustomersResponse, type ListMetersResponse, type ListWebhooksResponse, type Meter, type RecordRunEvent, type RecordRunParams, type RecordRunResult, type RetryOptions, type RunResult, type RunStatus, type RunTimeline, type StartRunParams, StreamMeter, type StreamMeterFlushResult, type StreamMeterOptions, type TrackUsageParams, type TrackUsageResult, type Webhook, type WebhookEventType, type Workflow, type WrapApiCallParams, type WrapApiCallResult, Drip as default };
2419
+ /**
2420
+ * Pre-initialized Drip client singleton.
2421
+ *
2422
+ * Uses lazy initialization - only creates the client when first accessed.
2423
+ * Reads `DRIP_API_KEY` from environment variables.
2424
+ *
2425
+ * @example
2426
+ * ```typescript
2427
+ * import { drip } from '@drip-sdk/node';
2428
+ *
2429
+ * // Track usage with one line
2430
+ * await drip.trackUsage({ customerId: 'cust_123', meter: 'api_calls', quantity: 1 });
2431
+ *
2432
+ * // Charge with one line
2433
+ * await drip.charge({ customerId: 'cust_123', meter: 'api_calls', quantity: 1 });
2434
+ *
2435
+ * // Record a run
2436
+ * await drip.recordRun({
2437
+ * customerId: 'cust_123',
2438
+ * workflow: 'agent-run',
2439
+ * events: [{ eventType: 'llm.call', quantity: 1000, units: 'tokens' }],
2440
+ * status: 'COMPLETED',
2441
+ * });
2442
+ * ```
2443
+ */
2444
+ declare const drip: Drip;
2445
+
2446
+ export { type BalanceResult, type Charge, type ChargeParams, type ChargeResult, type ChargeStatus, type CheckoutParams, type CheckoutResult, CircuitBreaker, type CircuitBreakerConfig, CircuitBreakerOpenError, type CircuitState, type CostEstimateLineItem, type CostEstimateResponse, type CreateCustomerParams, type CreateWebhookParams, type CreateWebhookResponse, type CreateWorkflowParams, type CustomPricing, type Customer, type DeleteWebhookResponse, Drip, type DripConfig, DripError, type EmitEventParams, type EndRunParams, type EstimateFromHypotheticalParams, type EstimateFromUsageParams, type EventResult, type HypotheticalUsageItem, type ListChargesOptions, type ListChargesResponse, type ListCustomersOptions, type ListCustomersResponse, type ListMetersResponse, type ListWebhooksResponse, type Meter, MetricsCollector, type MetricsSummary, RateLimiter, type RateLimiterConfig, type RecordRunEvent, type RecordRunParams, type RecordRunResult, type RequestMetrics, type ResilienceConfig, type ResilienceHealth, ResilienceManager, type RetryConfig, RetryExhaustedError, type RetryOptions, type RunDetails, type RunResult, type RunStatus, type RunTimeline, type StartRunParams, StreamMeter, type StreamMeterFlushResult, type StreamMeterOptions, type TrackUsageParams, type TrackUsageResult, type Webhook, type WebhookEventType, type Workflow, type WrapApiCallParams, type WrapApiCallResult, calculateBackoff, createDefaultResilienceConfig, createDisabledResilienceConfig, createHighThroughputResilienceConfig, Drip as default, drip, isRetryableError };