@drip-sdk/node 1.0.10 → 1.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.
@@ -0,0 +1,640 @@
1
+ /**
2
+ * Drip SDK Core - Essential API for pilots and new integrations
3
+ *
4
+ * This SDK focuses on two core concepts:
5
+ * - **Usage tracking**: trackUsage() for recording usage without billing
6
+ * - **Execution logging**: recordRun() and related methods for tracking runs/events
7
+ *
8
+ * For billing, webhooks, cost estimation, and advanced features:
9
+ * `import { Drip } from '@drip-sdk/node'`
10
+ *
11
+ * @packageDocumentation
12
+ */
13
+ /**
14
+ * Configuration options for the Drip SDK client.
15
+ */
16
+ interface DripConfig {
17
+ /**
18
+ * Your Drip API key. Obtain this from the Drip dashboard.
19
+ * @example "drip_live_abc123..."
20
+ */
21
+ apiKey: string;
22
+ /**
23
+ * Base URL for the Drip API. Defaults to production API.
24
+ * Override for staging/development environments.
25
+ * @default "https://api.drip.dev/v1"
26
+ */
27
+ baseUrl?: string;
28
+ /**
29
+ * Request timeout in milliseconds.
30
+ * @default 30000
31
+ */
32
+ timeout?: number;
33
+ }
34
+ /**
35
+ * Parameters for creating a new customer.
36
+ */
37
+ interface CreateCustomerParams {
38
+ /**
39
+ * Your internal customer/user ID for reconciliation.
40
+ * @example "user_12345"
41
+ */
42
+ externalCustomerId?: string;
43
+ /**
44
+ * The customer's Drip Smart Account address (derived from their EOA).
45
+ * @example "0x1234567890abcdef..."
46
+ */
47
+ onchainAddress: string;
48
+ /**
49
+ * Additional metadata to store with the customer.
50
+ */
51
+ metadata?: Record<string, unknown>;
52
+ }
53
+ /**
54
+ * A Drip customer record.
55
+ */
56
+ interface Customer {
57
+ /** Unique customer ID in Drip */
58
+ id: string;
59
+ /** Your business ID (optional - may not be returned by all endpoints) */
60
+ businessId?: string;
61
+ /** Your external customer ID (if provided) */
62
+ externalCustomerId: string | null;
63
+ /** Customer's on-chain address */
64
+ onchainAddress: string;
65
+ /** Custom metadata */
66
+ metadata: Record<string, unknown> | null;
67
+ /** ISO timestamp of creation */
68
+ createdAt: string;
69
+ /** ISO timestamp of last update */
70
+ updatedAt: string;
71
+ }
72
+ /**
73
+ * Options for listing customers.
74
+ */
75
+ interface ListCustomersOptions {
76
+ /**
77
+ * Maximum number of customers to return (1-100).
78
+ * @default 100
79
+ */
80
+ limit?: number;
81
+ /**
82
+ * Filter by customer status.
83
+ */
84
+ status?: 'ACTIVE' | 'LOW_BALANCE' | 'PAUSED';
85
+ }
86
+ /**
87
+ * Response from listing customers.
88
+ */
89
+ interface ListCustomersResponse {
90
+ /** Array of customers */
91
+ data: Customer[];
92
+ /** Total count returned */
93
+ count: number;
94
+ }
95
+ /**
96
+ * Parameters for tracking usage without billing.
97
+ */
98
+ interface TrackUsageParams {
99
+ /**
100
+ * The Drip customer ID to track usage for.
101
+ */
102
+ customerId: string;
103
+ /**
104
+ * The meter/usage type (e.g., 'api_calls', 'tokens').
105
+ */
106
+ meter: string;
107
+ /**
108
+ * The quantity of usage to record.
109
+ */
110
+ quantity: number;
111
+ /**
112
+ * Unique key to prevent duplicate records.
113
+ */
114
+ idempotencyKey?: string;
115
+ /**
116
+ * Human-readable unit label (e.g., 'tokens', 'requests').
117
+ */
118
+ units?: string;
119
+ /**
120
+ * Human-readable description of this usage event.
121
+ */
122
+ description?: string;
123
+ /**
124
+ * Additional metadata to attach to this usage event.
125
+ */
126
+ metadata?: Record<string, unknown>;
127
+ }
128
+ /**
129
+ * Result of tracking usage (no billing).
130
+ */
131
+ interface TrackUsageResult {
132
+ /** Whether the usage was recorded */
133
+ success: boolean;
134
+ /** The usage event ID */
135
+ usageEventId: string;
136
+ /** Customer ID */
137
+ customerId: string;
138
+ /** Usage type that was recorded */
139
+ usageType: string;
140
+ /** Quantity recorded */
141
+ quantity: number;
142
+ /** Whether this customer is internal-only */
143
+ isInternal: boolean;
144
+ /** Confirmation message */
145
+ message: string;
146
+ }
147
+ /**
148
+ * Parameters for starting a new run.
149
+ */
150
+ interface StartRunParams {
151
+ /** Customer ID this run belongs to */
152
+ customerId: string;
153
+ /** Workflow ID this run executes */
154
+ workflowId: string;
155
+ /** Your external run ID for correlation */
156
+ externalRunId?: string;
157
+ /** Correlation ID for distributed tracing */
158
+ correlationId?: string;
159
+ /** Parent run ID for nested runs */
160
+ parentRunId?: string;
161
+ /** Additional metadata */
162
+ metadata?: Record<string, unknown>;
163
+ }
164
+ /**
165
+ * Possible run statuses.
166
+ */
167
+ type RunStatus = 'PENDING' | 'RUNNING' | 'COMPLETED' | 'FAILED' | 'CANCELLED' | 'TIMEOUT';
168
+ /**
169
+ * Result of starting a run.
170
+ */
171
+ interface RunResult {
172
+ id: string;
173
+ customerId: string;
174
+ workflowId: string;
175
+ workflowName: string;
176
+ status: RunStatus;
177
+ correlationId: string | null;
178
+ createdAt: string;
179
+ }
180
+ /**
181
+ * Parameters for ending/updating a run.
182
+ */
183
+ interface EndRunParams {
184
+ /** New status for the run */
185
+ status: 'COMPLETED' | 'FAILED' | 'CANCELLED' | 'TIMEOUT';
186
+ /** Error message if failed */
187
+ errorMessage?: string;
188
+ /** Error code for categorization */
189
+ errorCode?: string;
190
+ /** Additional metadata */
191
+ metadata?: Record<string, unknown>;
192
+ }
193
+ /**
194
+ * Result of ending a run.
195
+ */
196
+ interface EndRunResult {
197
+ id: string;
198
+ status: RunStatus;
199
+ endedAt: string | null;
200
+ durationMs: number | null;
201
+ eventCount: number;
202
+ totalCostUnits: string | null;
203
+ }
204
+ /**
205
+ * Parameters for emitting an event to a run.
206
+ */
207
+ interface EmitEventParams {
208
+ /** Run ID to attach this event to */
209
+ runId: string;
210
+ /** Event type (e.g., "request.start", "llm.call") */
211
+ eventType: string;
212
+ /** Quantity of units consumed */
213
+ quantity?: number;
214
+ /** Human-readable unit label */
215
+ units?: string;
216
+ /** Human-readable description */
217
+ description?: string;
218
+ /** Cost in abstract units */
219
+ costUnits?: number;
220
+ /** Currency for cost */
221
+ costCurrency?: string;
222
+ /** Correlation ID for tracing */
223
+ correlationId?: string;
224
+ /** Parent event ID for trace tree */
225
+ parentEventId?: string;
226
+ /** OpenTelemetry-style span ID */
227
+ spanId?: string;
228
+ /** Idempotency key */
229
+ idempotencyKey?: string;
230
+ /** Additional metadata */
231
+ metadata?: Record<string, unknown>;
232
+ }
233
+ /**
234
+ * Result of emitting an event.
235
+ */
236
+ interface EventResult {
237
+ id: string;
238
+ runId: string;
239
+ eventType: string;
240
+ quantity: number;
241
+ costUnits: number | null;
242
+ isDuplicate: boolean;
243
+ timestamp: string;
244
+ }
245
+ /**
246
+ * A single event to record in a run.
247
+ */
248
+ interface RecordRunEvent {
249
+ /** Event type (e.g., "request.start", "llm.call", "request.end") */
250
+ eventType: string;
251
+ /** Quantity of units consumed */
252
+ quantity?: number;
253
+ /** Human-readable unit label */
254
+ units?: string;
255
+ /** Human-readable description */
256
+ description?: string;
257
+ /** Cost in abstract units */
258
+ costUnits?: number;
259
+ /** Additional metadata */
260
+ metadata?: Record<string, unknown>;
261
+ }
262
+ /**
263
+ * Parameters for recording a complete run in one call.
264
+ */
265
+ interface RecordRunParams {
266
+ /** Customer ID this run belongs to */
267
+ customerId: string;
268
+ /**
269
+ * Workflow/request type identifier. Examples:
270
+ * - "rpc-request" for RPC providers
271
+ * - "api-request" for API providers
272
+ * - "agent-run" for AI agents
273
+ *
274
+ * Auto-creates if it doesn't exist.
275
+ */
276
+ workflow: string;
277
+ /** Events that occurred during the run */
278
+ events: RecordRunEvent[];
279
+ /** Final status of the run */
280
+ status: 'COMPLETED' | 'FAILED' | 'CANCELLED' | 'TIMEOUT';
281
+ /** Error message if status is FAILED */
282
+ errorMessage?: string;
283
+ /** Error code if status is FAILED */
284
+ errorCode?: string;
285
+ /** Your external run ID for correlation */
286
+ externalRunId?: string;
287
+ /** Correlation ID for distributed tracing */
288
+ correlationId?: string;
289
+ /** Additional metadata */
290
+ metadata?: Record<string, unknown>;
291
+ }
292
+ /**
293
+ * Result of recording a run.
294
+ */
295
+ interface RecordRunResult {
296
+ /** The created run */
297
+ run: {
298
+ id: string;
299
+ workflowId: string;
300
+ workflowName: string;
301
+ status: RunStatus;
302
+ durationMs: number | null;
303
+ };
304
+ /** Summary of events created */
305
+ events: {
306
+ created: number;
307
+ duplicates: number;
308
+ };
309
+ /** Total cost computed */
310
+ totalCostUnits: string | null;
311
+ /** Human-readable summary */
312
+ summary: string;
313
+ }
314
+ /**
315
+ * Full run timeline response.
316
+ */
317
+ interface RunTimeline {
318
+ run: {
319
+ id: string;
320
+ customerId: string;
321
+ customerName: string | null;
322
+ workflowId: string;
323
+ workflowName: string;
324
+ status: RunStatus;
325
+ startedAt: string | null;
326
+ endedAt: string | null;
327
+ durationMs: number | null;
328
+ errorMessage: string | null;
329
+ errorCode: string | null;
330
+ correlationId: string | null;
331
+ metadata: Record<string, unknown> | null;
332
+ };
333
+ timeline: Array<{
334
+ id: string;
335
+ eventType: string;
336
+ quantity: number;
337
+ units: string | null;
338
+ description: string | null;
339
+ costUnits: number | null;
340
+ timestamp: string;
341
+ correlationId: string | null;
342
+ parentEventId: string | null;
343
+ charge: {
344
+ id: string;
345
+ amountUsdc: string;
346
+ status: string;
347
+ } | null;
348
+ }>;
349
+ totals: {
350
+ eventCount: number;
351
+ totalQuantity: string;
352
+ totalCostUnits: string;
353
+ totalChargedUsdc: string;
354
+ };
355
+ summary: string;
356
+ }
357
+ /**
358
+ * Error thrown by Drip SDK operations.
359
+ */
360
+ declare class DripError extends Error {
361
+ statusCode: number;
362
+ code?: string | undefined;
363
+ constructor(message: string, statusCode: number, code?: string | undefined);
364
+ }
365
+ /**
366
+ * Drip SDK Core - Essential API for pilots and new integrations.
367
+ *
368
+ * Two core concepts:
369
+ * - **Usage tracking**: `trackUsage()` - record usage without billing
370
+ * - **Execution logging**: `recordRun()` - track request/run lifecycle with events
371
+ *
372
+ * For billing (`charge()`), webhooks, and advanced features:
373
+ * ```typescript
374
+ * import { Drip } from '@drip-sdk/node';
375
+ * ```
376
+ *
377
+ * @example
378
+ * ```typescript
379
+ * import { Drip } from '@drip-sdk/node/core';
380
+ *
381
+ * const drip = new Drip({ apiKey: process.env.DRIP_API_KEY! });
382
+ *
383
+ * // Verify connection
384
+ * const health = await drip.ping();
385
+ * console.log(`API healthy: ${health.ok}`);
386
+ *
387
+ * // Track usage (no billing)
388
+ * await drip.trackUsage({
389
+ * customerId: 'cust_123',
390
+ * meter: 'api_calls',
391
+ * quantity: 1,
392
+ * });
393
+ *
394
+ * // Record a complete request/run with events
395
+ * const result = await drip.recordRun({
396
+ * customerId: 'cust_123',
397
+ * workflow: 'rpc-request', // or 'api-request', 'agent-run'
398
+ * events: [
399
+ * { eventType: 'request.start' },
400
+ * { eventType: 'llm.call', quantity: 1500, units: 'tokens' },
401
+ * { eventType: 'request.end' },
402
+ * ],
403
+ * status: 'COMPLETED',
404
+ * });
405
+ *
406
+ * console.log(result.summary);
407
+ * ```
408
+ */
409
+ declare class Drip {
410
+ private readonly apiKey;
411
+ private readonly baseUrl;
412
+ private readonly timeout;
413
+ /**
414
+ * Creates a new Drip SDK client.
415
+ *
416
+ * @param config - Configuration options
417
+ * @throws {Error} If apiKey is not provided
418
+ */
419
+ constructor(config: DripConfig);
420
+ /**
421
+ * Makes an authenticated request to the Drip API.
422
+ * @internal
423
+ */
424
+ private request;
425
+ /**
426
+ * Pings the Drip API to check connectivity and measure latency.
427
+ *
428
+ * Use this to verify:
429
+ * - API key is valid
430
+ * - Base URL is correct
431
+ * - Network connectivity works
432
+ *
433
+ * @returns Health status with latency information
434
+ * @throws {DripError} If the request fails or times out
435
+ *
436
+ * @example
437
+ * ```typescript
438
+ * const health = await drip.ping();
439
+ * if (health.ok) {
440
+ * console.log(`API healthy, latency: ${health.latencyMs}ms`);
441
+ * } else {
442
+ * console.error(`API unhealthy: ${health.status}`);
443
+ * }
444
+ * ```
445
+ */
446
+ ping(): Promise<{
447
+ ok: boolean;
448
+ status: string;
449
+ latencyMs: number;
450
+ timestamp: number;
451
+ }>;
452
+ /**
453
+ * Creates a new customer in your Drip account.
454
+ *
455
+ * @param params - Customer creation parameters
456
+ * @returns The created customer
457
+ * @throws {DripError} If creation fails (e.g., duplicate customer)
458
+ *
459
+ * @example
460
+ * ```typescript
461
+ * const customer = await drip.createCustomer({
462
+ * onchainAddress: '0x1234567890abcdef...',
463
+ * externalCustomerId: 'user_123',
464
+ * });
465
+ * ```
466
+ */
467
+ createCustomer(params: CreateCustomerParams): Promise<Customer>;
468
+ /**
469
+ * Retrieves a customer by their Drip ID.
470
+ *
471
+ * @param customerId - The Drip customer ID
472
+ * @returns The customer details
473
+ * @throws {DripError} If customer not found (404)
474
+ */
475
+ getCustomer(customerId: string): Promise<Customer>;
476
+ /**
477
+ * Lists all customers for your business.
478
+ *
479
+ * @param options - Optional filtering and pagination
480
+ * @returns List of customers
481
+ */
482
+ listCustomers(options?: ListCustomersOptions): Promise<ListCustomersResponse>;
483
+ /**
484
+ * Records usage for tracking WITHOUT billing.
485
+ *
486
+ * Use this for:
487
+ * - Pilot programs (track before billing)
488
+ * - Internal team usage
489
+ * - Pre-billing tracking before customer setup
490
+ *
491
+ * For actual billing, use `charge()` from the full SDK.
492
+ *
493
+ * @param params - Usage tracking parameters
494
+ * @returns The tracked usage event
495
+ *
496
+ * @example
497
+ * ```typescript
498
+ * const result = await drip.trackUsage({
499
+ * customerId: 'cust_abc123',
500
+ * meter: 'api_calls',
501
+ * quantity: 100,
502
+ * description: 'API calls during pilot',
503
+ * });
504
+ *
505
+ * console.log(`Tracked: ${result.usageEventId}`);
506
+ * ```
507
+ */
508
+ trackUsage(params: TrackUsageParams): Promise<TrackUsageResult>;
509
+ private createWorkflow;
510
+ private listWorkflows;
511
+ /**
512
+ * Starts a new run for tracking execution.
513
+ *
514
+ * @param params - Run parameters
515
+ * @returns The started run
516
+ *
517
+ * @example
518
+ * ```typescript
519
+ * const run = await drip.startRun({
520
+ * customerId: 'cust_abc123',
521
+ * workflowId: 'wf_xyz789',
522
+ * });
523
+ *
524
+ * // Emit events during execution...
525
+ * await drip.emitEvent({ runId: run.id, eventType: 'llm.call', quantity: 1000 });
526
+ *
527
+ * // End the run
528
+ * await drip.endRun(run.id, { status: 'COMPLETED' });
529
+ * ```
530
+ */
531
+ startRun(params: StartRunParams): Promise<RunResult>;
532
+ /**
533
+ * Ends a run with a final status.
534
+ *
535
+ * @param runId - The run ID to end
536
+ * @param params - End parameters including status
537
+ * @returns Updated run info
538
+ */
539
+ endRun(runId: string, params: EndRunParams): Promise<EndRunResult>;
540
+ /**
541
+ * Gets a run's full timeline with events and computed totals.
542
+ *
543
+ * @param runId - The run ID
544
+ * @returns Full timeline with events and summary
545
+ *
546
+ * @example
547
+ * ```typescript
548
+ * const { run, timeline, totals, summary } = await drip.getRunTimeline('run_abc123');
549
+ *
550
+ * console.log(`Status: ${run.status}`);
551
+ * console.log(`Summary: ${summary}`);
552
+ *
553
+ * for (const event of timeline) {
554
+ * console.log(`${event.eventType}: ${event.quantity} ${event.units}`);
555
+ * }
556
+ * ```
557
+ */
558
+ getRunTimeline(runId: string): Promise<RunTimeline>;
559
+ /**
560
+ * Emits an event to a run.
561
+ *
562
+ * @param params - Event parameters
563
+ * @returns The created event
564
+ *
565
+ * @example
566
+ * ```typescript
567
+ * await drip.emitEvent({
568
+ * runId: run.id,
569
+ * eventType: 'llm.call',
570
+ * quantity: 1500,
571
+ * units: 'tokens',
572
+ * description: 'GPT-4 completion',
573
+ * });
574
+ * ```
575
+ */
576
+ emitEvent(params: EmitEventParams): Promise<EventResult>;
577
+ /**
578
+ * Emits multiple events in a single request.
579
+ *
580
+ * @param events - Array of events to emit
581
+ * @returns Summary of created events
582
+ */
583
+ emitEventsBatch(events: Array<EmitEventParams>): Promise<{
584
+ success: boolean;
585
+ created: number;
586
+ duplicates: number;
587
+ events: Array<{
588
+ id: string;
589
+ eventType: string;
590
+ isDuplicate: boolean;
591
+ }>;
592
+ }>;
593
+ /**
594
+ * Records a complete request/run in a single call.
595
+ *
596
+ * This is the **hero method** for tracking execution. It combines:
597
+ * - Workflow creation (auto-creates if needed)
598
+ * - Run creation
599
+ * - Event emission
600
+ * - Run completion
601
+ *
602
+ * @param params - Run parameters including events
603
+ * @returns The created run with event summary
604
+ *
605
+ * @example
606
+ * ```typescript
607
+ * // RPC provider example
608
+ * const result = await drip.recordRun({
609
+ * customerId: 'cust_123',
610
+ * workflow: 'rpc-request',
611
+ * events: [
612
+ * { eventType: 'request.start' },
613
+ * { eventType: 'eth_call', quantity: 1 },
614
+ * { eventType: 'request.end' },
615
+ * ],
616
+ * status: 'COMPLETED',
617
+ * });
618
+ *
619
+ * // API provider example
620
+ * const result = await drip.recordRun({
621
+ * customerId: 'cust_123',
622
+ * workflow: 'api-request',
623
+ * events: [
624
+ * { eventType: 'request.start' },
625
+ * { eventType: 'llm.call', quantity: 2000, units: 'tokens' },
626
+ * { eventType: 'request.end' },
627
+ * ],
628
+ * status: 'COMPLETED',
629
+ * });
630
+ *
631
+ * console.log(result.summary);
632
+ * // Output: "✓ Rpc Request: 3 events recorded (152ms)"
633
+ * ```
634
+ */
635
+ recordRun(params: RecordRunParams): Promise<RecordRunResult>;
636
+ }
637
+
638
+ // @ts-ignore
639
+ export = Drip;
640
+ export { type CreateCustomerParams, type Customer, Drip, type DripConfig, DripError, type EmitEventParams, type EndRunParams, type EndRunResult, type EventResult, type ListCustomersOptions, type ListCustomersResponse, type RecordRunEvent, type RecordRunParams, type RecordRunResult, type RunResult, type RunStatus, type RunTimeline, type StartRunParams, type TrackUsageParams, type TrackUsageResult };