@naturalpay/sdk 0.0.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.
@@ -0,0 +1,703 @@
1
+ /**
2
+ * HTTP client for Natural Server API with JWT caching.
3
+ */
4
+ interface HTTPClientOptions {
5
+ apiKey?: string;
6
+ baseUrl?: string;
7
+ timeout?: number;
8
+ }
9
+ interface RequestOptions {
10
+ body?: Record<string, unknown>;
11
+ params?: Record<string, unknown>;
12
+ headers?: Record<string, string>;
13
+ }
14
+ declare class HTTPClient {
15
+ private readonly apiKey;
16
+ private readonly baseUrl;
17
+ private readonly timeout;
18
+ private readonly jwtCache;
19
+ constructor(options?: HTTPClientOptions);
20
+ /**
21
+ * Get a cached JWT or exchange API key for a new one.
22
+ */
23
+ private getJwt;
24
+ /**
25
+ * Build URL with query parameters.
26
+ */
27
+ private buildUrl;
28
+ /**
29
+ * Handle API response and throw appropriate errors.
30
+ */
31
+ private handleResponse;
32
+ /**
33
+ * Make an authenticated request.
34
+ */
35
+ request<T>(method: string, path: string, options?: RequestOptions): Promise<T>;
36
+ get<T>(path: string, options?: Omit<RequestOptions, 'body'>): Promise<T>;
37
+ post<T>(path: string, options?: RequestOptions): Promise<T>;
38
+ put<T>(path: string, options?: RequestOptions): Promise<T>;
39
+ delete<T>(path: string): Promise<T>;
40
+ }
41
+
42
+ /**
43
+ * Base resource class.
44
+ */
45
+
46
+ declare abstract class BaseResource {
47
+ protected readonly http: HTTPClient;
48
+ constructor(http: HTTPClient);
49
+ }
50
+
51
+ /**
52
+ * Payment types.
53
+ */
54
+ interface Payment {
55
+ transferId: string;
56
+ paymentId?: string;
57
+ status: string;
58
+ amount?: number;
59
+ currency: string;
60
+ recipientEmail?: string;
61
+ recipientPhone?: string;
62
+ memo?: string;
63
+ createdAt?: string;
64
+ claimLink?: string;
65
+ counterpartyPartyId?: string;
66
+ instanceId?: string;
67
+ }
68
+ interface PaymentCreateParams {
69
+ recipientEmail?: string;
70
+ recipientPhone?: string;
71
+ recipientPartyId?: string;
72
+ amount: number;
73
+ memo?: string;
74
+ agentId?: string;
75
+ customerPartyId?: string;
76
+ instanceId?: string;
77
+ idempotencyKey?: string;
78
+ }
79
+ interface CancellationResult {
80
+ status: string;
81
+ message: string;
82
+ }
83
+
84
+ /**
85
+ * Payments resource.
86
+ */
87
+
88
+ declare class PaymentsResource extends BaseResource {
89
+ /**
90
+ * Generate idempotency key based on payment details + time window.
91
+ */
92
+ private generateIdempotencyKey;
93
+ /**
94
+ * Create a payment.
95
+ *
96
+ * Must provide exactly one of: recipientEmail, recipientPhone, or recipientPartyId.
97
+ *
98
+ * @param params - Payment creation parameters
99
+ * @returns Payment object with transfer_id, status, etc.
100
+ */
101
+ create(params: PaymentCreateParams): Promise<Payment>;
102
+ /**
103
+ * Get payment status by transfer ID.
104
+ *
105
+ * @param transferId - The transfer ID to look up
106
+ * @returns Payment object with current status
107
+ */
108
+ retrieve(transferId: string): Promise<Payment>;
109
+ /**
110
+ * Cancel a pending payment.
111
+ *
112
+ * @param transferId - The transfer ID to cancel
113
+ * @returns Cancellation result with status and message
114
+ */
115
+ cancel(transferId: string): Promise<CancellationResult>;
116
+ }
117
+
118
+ /**
119
+ * Wallet types.
120
+ */
121
+ interface AmountInfo {
122
+ amountMinor: number;
123
+ amountDollars: string;
124
+ }
125
+ interface BalanceBreakdown {
126
+ operatingFunded: AmountInfo;
127
+ operatingAdvanced: AmountInfo;
128
+ escrowFundedSettled: AmountInfo;
129
+ escrowAdvanced: AmountInfo;
130
+ holdsOutbound: AmountInfo;
131
+ }
132
+ interface AssetBalance {
133
+ assetCode: string;
134
+ breakdown: BalanceBreakdown;
135
+ available: AmountInfo;
136
+ metadata?: Record<string, unknown>;
137
+ }
138
+ interface AccountBalance {
139
+ walletId: string;
140
+ balances: AssetBalance[];
141
+ }
142
+ interface DepositParams {
143
+ amount: number;
144
+ paymentInstrumentId: string;
145
+ currency?: string;
146
+ description?: string;
147
+ idempotencyKey: string;
148
+ }
149
+ interface DepositResponse {
150
+ transferId?: string;
151
+ status: string;
152
+ amount: number | string;
153
+ currency: string;
154
+ estimatedSettlement?: string;
155
+ error?: string;
156
+ errorDetails?: string;
157
+ }
158
+ interface WithdrawParams {
159
+ amount: number;
160
+ paymentInstrumentId: string;
161
+ currency?: string;
162
+ description?: string;
163
+ idempotencyKey: string;
164
+ }
165
+ interface WithdrawResponse {
166
+ transferId?: string;
167
+ status: string;
168
+ amount: number | string;
169
+ currency: string;
170
+ estimatedSettlement?: string;
171
+ kycRequired: boolean;
172
+ kycStatus?: string;
173
+ kycSessionUrl?: string;
174
+ mfaRequired: boolean;
175
+ mfaChallengeId?: string;
176
+ mfaExpiresAt?: string;
177
+ error?: string;
178
+ errorDetails?: string;
179
+ }
180
+
181
+ /**
182
+ * Wallet resource.
183
+ */
184
+
185
+ declare class WalletResource extends BaseResource {
186
+ /**
187
+ * Get current wallet balance.
188
+ *
189
+ * @returns AccountBalance with available, current, pending amounts
190
+ */
191
+ balance(): Promise<AccountBalance>;
192
+ /**
193
+ * Initiate a deposit from a linked bank account.
194
+ *
195
+ * @param params - Deposit parameters
196
+ * @returns DepositResponse with transfer status
197
+ */
198
+ deposit(params: DepositParams): Promise<DepositResponse>;
199
+ /**
200
+ * Initiate a withdrawal to a linked bank account.
201
+ *
202
+ * @param params - Withdrawal parameters
203
+ * @returns WithdrawResponse with transfer status (may require KYC/MFA)
204
+ */
205
+ withdraw(params: WithdrawParams): Promise<WithdrawResponse>;
206
+ }
207
+
208
+ /**
209
+ * Transaction types.
210
+ */
211
+ /**
212
+ * Filter for transaction types in list operations.
213
+ */
214
+ declare enum TransactionTypeFilter {
215
+ PAYMENT = "payment",
216
+ TRANSFER = "transfer",
217
+ ALL = "all"
218
+ }
219
+ type TransactionType = 'payment_sent' | 'payment_received' | 'deposit' | 'withdrawal';
220
+ type TransactionStatus = 'pending' | 'processing' | 'completed' | 'failed';
221
+ interface Transaction {
222
+ transactionId: string;
223
+ type: TransactionType;
224
+ status: TransactionStatus;
225
+ amount: number;
226
+ currency: string;
227
+ counterparty?: string;
228
+ memo?: string;
229
+ createdAt: string;
230
+ completedAt?: string;
231
+ }
232
+ interface TransactionListParams {
233
+ limit?: number;
234
+ customerFilter?: string;
235
+ offset?: number;
236
+ agentId?: string;
237
+ customerPartyId?: string;
238
+ /** Filter by transaction type (payment, transfer, or all) */
239
+ type?: TransactionTypeFilter;
240
+ }
241
+
242
+ /**
243
+ * Transactions resource.
244
+ */
245
+
246
+ declare class TransactionsResource extends BaseResource {
247
+ /**
248
+ * List recent transactions.
249
+ *
250
+ * @param params - List parameters including agent context
251
+ * @returns List of Transaction objects
252
+ */
253
+ list(params?: TransactionListParams): Promise<Transaction[]>;
254
+ }
255
+
256
+ /**
257
+ * Agent types.
258
+ */
259
+ type AgentStatus = 'ACTIVE' | 'REVOKED';
260
+ interface Agent {
261
+ agentId: string;
262
+ id: string;
263
+ name: string;
264
+ description?: string;
265
+ status: AgentStatus;
266
+ partyId: string;
267
+ createdAt: string;
268
+ createdBy: string;
269
+ updatedAt: string;
270
+ updatedBy: string;
271
+ }
272
+ interface AgentCreateParams {
273
+ name: string;
274
+ partyId: string;
275
+ description?: string;
276
+ idempotencyKey?: string;
277
+ }
278
+ interface AgentCreateResponse {
279
+ agentId: string;
280
+ name: string;
281
+ description?: string;
282
+ status: AgentStatus;
283
+ partyId: string;
284
+ createdAt: string;
285
+ createdBy: string;
286
+ }
287
+ interface AgentUpdateParams {
288
+ name?: string;
289
+ description?: string;
290
+ status?: AgentStatus;
291
+ idempotencyKey?: string;
292
+ }
293
+ interface AgentUpdateResponse {
294
+ agentId: string;
295
+ name: string;
296
+ description?: string;
297
+ status: AgentStatus;
298
+ partyId: string;
299
+ updatedAt: string;
300
+ updatedBy: string;
301
+ }
302
+ interface AgentListParams {
303
+ status?: AgentStatus;
304
+ partyId?: string;
305
+ limit?: number;
306
+ offset?: number;
307
+ }
308
+ interface AgentListResponse {
309
+ agents: Agent[];
310
+ total: number;
311
+ page: number;
312
+ pageSize: number;
313
+ }
314
+
315
+ /**
316
+ * Agents resource.
317
+ */
318
+
319
+ declare class AgentsResource extends BaseResource {
320
+ /**
321
+ * List agents for the partner.
322
+ *
323
+ * @param params - Filter and pagination parameters
324
+ * @returns AgentListResponse with list of agents
325
+ */
326
+ list(params?: AgentListParams): Promise<AgentListResponse>;
327
+ /**
328
+ * Get agent by ID.
329
+ *
330
+ * @param agentId - The agent ID to retrieve (agt_xxx)
331
+ * @returns Agent details
332
+ */
333
+ get(agentId: string): Promise<Agent>;
334
+ /**
335
+ * Create a new agent.
336
+ *
337
+ * @param params - Agent creation parameters
338
+ * @returns AgentCreateResponse with created agent details
339
+ */
340
+ create(params: AgentCreateParams): Promise<AgentCreateResponse>;
341
+ /**
342
+ * Update an existing agent.
343
+ *
344
+ * @param agentId - The agent ID to update (agt_xxx)
345
+ * @param params - Update parameters
346
+ * @returns AgentUpdateResponse with updated agent details
347
+ */
348
+ update(agentId: string, params: AgentUpdateParams): Promise<AgentUpdateResponse>;
349
+ /**
350
+ * Delete an agent.
351
+ *
352
+ * @param agentId - The agent ID to delete (agt_xxx)
353
+ */
354
+ delete(agentId: string): Promise<void>;
355
+ }
356
+
357
+ /**
358
+ * Delegation types.
359
+ */
360
+ type DelegationStatus = 'ACTIVE' | 'SUSPENDED' | 'REVOKED';
361
+ interface Delegation {
362
+ id: string;
363
+ handle: string;
364
+ delegatingPartyId: string;
365
+ delegatedPartyId: string;
366
+ permissions: string[];
367
+ expiresAt?: string;
368
+ status: string;
369
+ createdAt: string;
370
+ createdBy?: string;
371
+ }
372
+ interface DelegationListParams {
373
+ status?: DelegationStatus;
374
+ delegatingPartyId?: string;
375
+ delegatedPartyId?: string;
376
+ }
377
+ interface DelegationListResponse {
378
+ delegations: Delegation[];
379
+ total: number;
380
+ }
381
+ interface DelegationCreateParams {
382
+ delegatingPartyId: string;
383
+ delegatedPartyId: string;
384
+ permissions: string[];
385
+ expiresAt?: string;
386
+ idempotencyKey?: string;
387
+ }
388
+ interface DelegationUpdateParams {
389
+ status?: DelegationStatus;
390
+ permissions?: string[];
391
+ expiresAt?: string;
392
+ }
393
+
394
+ /**
395
+ * Delegations resource.
396
+ */
397
+
398
+ declare class DelegationsResource extends BaseResource {
399
+ /**
400
+ * List delegations with optional filters.
401
+ *
402
+ * @param params - Filter parameters
403
+ * @returns DelegationListResponse with list of delegations
404
+ */
405
+ list(params?: DelegationListParams): Promise<DelegationListResponse>;
406
+ /**
407
+ * Get delegation by ID.
408
+ *
409
+ * @param delegationId - The delegation handle (dlg_xxx)
410
+ * @returns Delegation details
411
+ */
412
+ get(delegationId: string): Promise<Delegation>;
413
+ /**
414
+ * Create a new delegation (party-to-party trust relationship).
415
+ *
416
+ * @param params - Delegation creation parameters
417
+ * @returns Created Delegation
418
+ */
419
+ create(params: DelegationCreateParams): Promise<Delegation>;
420
+ /**
421
+ * Update an existing delegation.
422
+ *
423
+ * @param delegationId - Delegation handle (dlg_xxx)
424
+ * @param params - Update parameters
425
+ * @returns Updated Delegation
426
+ */
427
+ update(delegationId: string, params: DelegationUpdateParams): Promise<Delegation>;
428
+ /**
429
+ * Revoke a delegation (soft delete by setting status to REVOKED).
430
+ *
431
+ * @param delegationId - Delegation handle (dlg_xxx)
432
+ * @returns Revoked Delegation
433
+ */
434
+ revoke(delegationId: string): Promise<Delegation>;
435
+ }
436
+
437
+ /**
438
+ * Customer types.
439
+ */
440
+ interface CustomerPartyInfo {
441
+ id: string;
442
+ handle?: string;
443
+ type: string;
444
+ legalName?: string;
445
+ displayName?: string;
446
+ status?: string;
447
+ }
448
+ interface Customer {
449
+ party: CustomerPartyInfo;
450
+ delegationId: string;
451
+ permissions: string[];
452
+ delegationStatus: string;
453
+ createdAt: string;
454
+ }
455
+
456
+ /**
457
+ * Customers resource.
458
+ */
459
+
460
+ declare class CustomersResource extends BaseResource {
461
+ /**
462
+ * List customers onboarded by the partner via delegation.
463
+ *
464
+ * @returns List of Customer objects with party info and delegation details
465
+ */
466
+ list(): Promise<Customer[]>;
467
+ }
468
+
469
+ /**
470
+ * Natural Payments SDK client.
471
+ */
472
+
473
+ interface NaturalClientOptions extends HTTPClientOptions {
474
+ }
475
+ /**
476
+ * Natural Payments SDK client.
477
+ *
478
+ * @example
479
+ * ```typescript
480
+ * import { NaturalClient } from 'naturalpay';
481
+ *
482
+ * const client = new NaturalClient({ apiKey: 'pk_sandbox_xxx' });
483
+ *
484
+ * // Create a payment
485
+ * const payment = await client.payments.create({
486
+ * recipientEmail: 'alice@example.com',
487
+ * amount: 50.00,
488
+ * memo: 'For consulting',
489
+ * });
490
+ *
491
+ * // Check balance
492
+ * const balance = await client.wallet.balance();
493
+ * ```
494
+ */
495
+ declare class NaturalClient {
496
+ private readonly http;
497
+ /** Payments API resource. */
498
+ readonly payments: PaymentsResource;
499
+ /** Wallet API resource for balance, transfers, deposits, and withdrawals. */
500
+ readonly wallet: WalletResource;
501
+ /** Transactions API resource. */
502
+ readonly transactions: TransactionsResource;
503
+ /** Agents API resource for managing agents. */
504
+ readonly agents: AgentsResource;
505
+ /** Delegations API resource for managing party-to-party delegations. */
506
+ readonly delegations: DelegationsResource;
507
+ /** Customers API resource for listing customers onboarded via delegation. */
508
+ readonly customers: CustomersResource;
509
+ /**
510
+ * Initialize the Natural client.
511
+ *
512
+ * @param options - Client configuration options
513
+ * @param options.apiKey - API key (defaults to NATURAL_API_KEY env var)
514
+ * @param options.baseUrl - API base URL (defaults to https://api.natural.co)
515
+ * @param options.timeout - Request timeout in milliseconds (default: 30000)
516
+ */
517
+ constructor(options?: NaturalClientOptions);
518
+ }
519
+
520
+ /**
521
+ * Structured logging for Natural Payments SDK.
522
+ *
523
+ * Supports two modes:
524
+ * 1. Plain text logging (default, for local development)
525
+ * 2. JSON logging with Datadog correlation (when NATURAL_LOG_FORMAT=json)
526
+ *
527
+ * Features:
528
+ * - Source info: file, line, function on every log (for error grouping)
529
+ * - Context binding for request_id, agent_id, instance_id
530
+ * - Datadog trace correlation fields
531
+ * - AsyncLocalStorage for proper async context isolation
532
+ */
533
+ type LogLevel = 'debug' | 'info' | 'warning' | 'error';
534
+ /**
535
+ * Get the current logging context.
536
+ * Uses AsyncLocalStorage if available, falls back to global context.
537
+ */
538
+ declare function getContext(): Record<string, unknown>;
539
+ /**
540
+ * Bind additional context to current scope (e.g., request_id, agent_id).
541
+ *
542
+ * Values are sanitized to prevent log injection attacks.
543
+ * Updates both AsyncLocalStorage (if active) and global context.
544
+ *
545
+ * @example
546
+ * bindContext({ requestId: 'req_123', agentId: 'agt_456' });
547
+ * logger.info('Processing payment'); // Will include requestId and agentId
548
+ */
549
+ declare function bindContext(context: Record<string, unknown>): void;
550
+ /**
551
+ * Clear all bound context.
552
+ */
553
+ declare function clearContext(): void;
554
+ /**
555
+ * Run a function with isolated logging context.
556
+ *
557
+ * Context bound within the callback is isolated from other async operations.
558
+ * This is the recommended way to set context for request handling.
559
+ *
560
+ * @example
561
+ * await runWithContext({ requestId: 'req_123' }, async () => {
562
+ * logger.info('Processing request'); // Includes requestId
563
+ * await doAsyncWork();
564
+ * logger.info('Request complete'); // Still includes requestId
565
+ * });
566
+ */
567
+ declare function runWithContext<T>(context: Record<string, unknown>, fn: () => T | Promise<T>): T | Promise<T>;
568
+ /**
569
+ * Configure logging for the Natural SDK.
570
+ *
571
+ * @param options - Logging configuration options
572
+ * @param options.level - Log level (debug, info, warning, error)
573
+ * @param options.jsonFormat - Use JSON format (default: auto-detect from NATURAL_LOG_FORMAT env var)
574
+ * @param options.serviceName - Service name for structured logs
575
+ *
576
+ * Environment variables:
577
+ * - NATURAL_LOG_LEVEL: Override log level (DEBUG, INFO, WARNING, ERROR)
578
+ * - NATURAL_LOG_FORMAT: Set to "json" for JSON output, "text" for plain text
579
+ */
580
+ declare function configureLogging(options?: {
581
+ level?: LogLevel;
582
+ jsonFormat?: boolean;
583
+ serviceName?: string;
584
+ }): void;
585
+ /**
586
+ * Logger instance for a specific module/context.
587
+ */
588
+ declare class Logger {
589
+ private readonly name;
590
+ constructor(name: string);
591
+ private log;
592
+ debug(message: string, extra?: Record<string, unknown>): void;
593
+ info(message: string, extra?: Record<string, unknown>): void;
594
+ warning(message: string, extra?: Record<string, unknown>): void;
595
+ warn(message: string, extra?: Record<string, unknown>): void;
596
+ error(message: string, extra?: Record<string, unknown>): void;
597
+ }
598
+ /**
599
+ * Get a logger for the given module name.
600
+ *
601
+ * @param name - Module name (e.g., 'naturalpay.http')
602
+ * @returns Logger instance
603
+ *
604
+ * @example
605
+ * const logger = getLogger('naturalpay.payments');
606
+ * logger.info('Payment initiated', { amount: 100 });
607
+ */
608
+ declare function getLogger(name: string): Logger;
609
+ /**
610
+ * Log an error with full context and exception info.
611
+ */
612
+ declare function logError(logger: Logger, message: string, options?: {
613
+ error?: Error;
614
+ statusCode?: number;
615
+ code?: string;
616
+ [key: string]: unknown;
617
+ }): void;
618
+ /**
619
+ * Log an API call with standard fields.
620
+ */
621
+ declare function logApiCall(logger: Logger, method: string, path: string, options?: {
622
+ statusCode?: number;
623
+ durationMs?: number;
624
+ error?: Error;
625
+ [key: string]: unknown;
626
+ }): void;
627
+ /**
628
+ * Log an MCP tool invocation.
629
+ */
630
+ declare function logToolCall(logger: Logger, toolName: string, options?: {
631
+ success?: boolean;
632
+ durationMs?: number;
633
+ error?: Error;
634
+ [key: string]: unknown;
635
+ }): void;
636
+
637
+ /**
638
+ * Natural Payments SDK error classes.
639
+ */
640
+ /**
641
+ * Base error for all Natural SDK errors.
642
+ */
643
+ declare class NaturalError extends Error {
644
+ readonly statusCode?: number;
645
+ readonly code?: string;
646
+ constructor(message: string, options?: {
647
+ statusCode?: number;
648
+ code?: string;
649
+ });
650
+ }
651
+ /**
652
+ * Invalid or missing API key.
653
+ */
654
+ declare class AuthenticationError extends NaturalError {
655
+ constructor(message?: string);
656
+ }
657
+ /**
658
+ * Malformed request parameters.
659
+ */
660
+ declare class InvalidRequestError extends NaturalError {
661
+ constructor(message: string, code?: string);
662
+ }
663
+ /**
664
+ * Payment-specific failure.
665
+ */
666
+ declare class PaymentError extends NaturalError {
667
+ constructor(message: string, code?: string);
668
+ }
669
+ /**
670
+ * Not enough balance for payment.
671
+ */
672
+ declare class InsufficientFundsError extends PaymentError {
673
+ constructor(message?: string);
674
+ }
675
+ /**
676
+ * Invalid recipient.
677
+ */
678
+ declare class RecipientNotFoundError extends PaymentError {
679
+ constructor(message?: string);
680
+ }
681
+ /**
682
+ * Too many requests.
683
+ */
684
+ declare class RateLimitError extends NaturalError {
685
+ readonly retryAfter?: number;
686
+ constructor(message?: string, retryAfter?: number);
687
+ }
688
+ /**
689
+ * Internal server error.
690
+ */
691
+ declare class ServerError extends NaturalError {
692
+ constructor(message?: string);
693
+ }
694
+
695
+ /**
696
+ * Natural Payments SDK - AI agent payment infrastructure.
697
+ *
698
+ * @packageDocumentation
699
+ */
700
+
701
+ declare const VERSION = "0.0.1";
702
+
703
+ export { type AccountBalance, type Agent, type AgentCreateParams, type AgentCreateResponse, type AgentListParams, type AgentListResponse, type AgentStatus, type AgentUpdateParams, type AgentUpdateResponse, type AmountInfo, type AssetBalance, AuthenticationError, type BalanceBreakdown, type CancellationResult, type Customer, type CustomerPartyInfo, type Delegation, type DelegationCreateParams, type DelegationListParams, type DelegationListResponse, type DelegationStatus, type DelegationUpdateParams, type DepositParams, type DepositResponse, InsufficientFundsError, InvalidRequestError, type LogLevel, Logger, NaturalClient, type NaturalClientOptions, NaturalError, type Payment, type PaymentCreateParams, PaymentError, RateLimitError, RecipientNotFoundError, ServerError, type Transaction, type TransactionListParams, type TransactionStatus, type TransactionType, TransactionTypeFilter, VERSION, type WithdrawParams, type WithdrawResponse, bindContext, clearContext, configureLogging, getContext, getLogger, logApiCall, logError, logToolCall, runWithContext };