pycer-sdk 0.0.0-stage → 1.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.
package/dist/index.js ADDED
@@ -0,0 +1,1246 @@
1
+ import { ValidationError, PermissionError, OwnPayError, AbortError, NetworkError, createErrorFromResponse } from './chunk-ERUWKVNC.js';
2
+ export { AbortError, ApiError, AuthenticationError, IdempotencyError, NetworkError, NotFoundError, OwnPayError, PermissionError, RateLimitError, ValidationError, WebhookVerificationError, generateSignature, parseWebhookPayload, verifyWebhookSignature } from './chunk-ERUWKVNC.js';
3
+ import { randomUUID } from 'crypto';
4
+
5
+ // src/resources/switch.ts
6
+ function validateAmount(amount) {
7
+ const decimal = String(amount);
8
+ if (!/^\d+(?:\.\d{1,2})?$/.test(decimal) || !/[1-9]/.test(decimal)) {
9
+ throw new ValidationError("Use a positive decimal amount with at most two fractional digits", []);
10
+ }
11
+ return decimal;
12
+ }
13
+ var SwitchResource = class {
14
+ constructor(client) {
15
+ this.client = client;
16
+ }
17
+ client;
18
+ initiate(params, options) {
19
+ const amount = validateAmount(params.amount);
20
+ const phone = params.partyA?.phone?.trim();
21
+ const umid = params.partyB?.umid?.trim();
22
+ const currency = params.currency?.trim().toUpperCase();
23
+ const preferredRail = params.preferredRail?.trim().toUpperCase();
24
+ if (!phone || !/^\+[1-9]\d{6,14}$/.test(phone)) {
25
+ throw new ValidationError("Payer phone must use strict E.164", []);
26
+ }
27
+ if (!umid || !preferredRail || !currency || !/^[A-Z]{3}$/.test(currency)) {
28
+ throw new ValidationError("Merchant UMID, preferred rail and three-letter currency are required", []);
29
+ }
30
+ return this.client.request({
31
+ method: "POST",
32
+ path: "/payments",
33
+ body: { ...params, amount, currency, preferredRail, partyA: { ...params.partyA, phone }, partyB: { ...params.partyB, umid } },
34
+ options
35
+ });
36
+ }
37
+ charge(params, options) {
38
+ const { customerPhone, customerName, merchantUmid, accountReference, recipientAccount, ...payment } = params;
39
+ return this.initiate({
40
+ ...payment,
41
+ partyA: { phone: customerPhone, name: customerName },
42
+ partyB: { umid: merchantUmid, accountReference, recipientAccount }
43
+ }, options);
44
+ }
45
+ };
46
+
47
+ // src/resources/cards.ts
48
+ var CardsResource = class {
49
+ constructor(client) {
50
+ this.client = client;
51
+ }
52
+ client;
53
+ async charge(params, options) {
54
+ const { data } = await this.client.request({
55
+ method: "POST",
56
+ path: "/cards/charges",
57
+ body: {
58
+ payment_method_id: params.paymentMethodId,
59
+ amount: validateAmount(params.amount),
60
+ currency: params.currency.toUpperCase(),
61
+ reference: params.reference
62
+ },
63
+ options
64
+ });
65
+ return data;
66
+ }
67
+ async list(customerId, options) {
68
+ const result = await this.client.request({
69
+ method: "GET",
70
+ path: this.path(customerId),
71
+ query: { type: "card" },
72
+ options
73
+ });
74
+ return result.data;
75
+ }
76
+ async vault(customerId, params, options) {
77
+ if (!params.gatewayToken.trim()) throw new ValidationError("Gateway token is required", []);
78
+ const result = await this.client.request({
79
+ method: "POST",
80
+ path: this.path(customerId),
81
+ body: { type: "card", gateway_token: params.gatewayToken, provider: params.provider, label: params.label, gateway_customer_id: params.gatewayCustomerId },
82
+ options
83
+ });
84
+ return result.data;
85
+ }
86
+ async setDefault(customerId, methodId, options) {
87
+ await this.client.request({ method: "PUT", path: this.path(customerId, methodId) + "/default", options });
88
+ }
89
+ async revoke(customerId, methodId, options) {
90
+ await this.client.request({ method: "DELETE", path: this.path(customerId, methodId), options });
91
+ }
92
+ path(customerId, methodId) {
93
+ for (const id of methodId === void 0 ? [customerId] : [customerId, methodId]) {
94
+ if (!Number.isSafeInteger(id) || id < 1) throw new ValidationError("A positive numeric ID is required", []);
95
+ }
96
+ const base = `/customers/${customerId}/payment-methods`;
97
+ return methodId === void 0 ? base : `${base}/${methodId}`;
98
+ }
99
+ };
100
+
101
+ // src/resources/checkout.ts
102
+ var CheckoutResource = class {
103
+ constructor(client, baseUrl) {
104
+ this.client = client;
105
+ this.baseUrl = baseUrl;
106
+ }
107
+ client;
108
+ baseUrl;
109
+ async create(params, options) {
110
+ const { data } = await this.client.request({
111
+ method: "POST",
112
+ path: "/checkout/sessions",
113
+ body: { amount: validateAmount(params.amount), currency: params.currency.toUpperCase(), description: params.description },
114
+ options
115
+ });
116
+ return { ...data, checkoutUrl: this.url(data.token) };
117
+ }
118
+ async get(id, options) {
119
+ if (!/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(id)) {
120
+ throw new ValidationError("A valid checkout session ID is required", []);
121
+ }
122
+ const { data } = await this.client.request({
123
+ method: "GET",
124
+ path: `/checkout/sessions/${id}`,
125
+ options
126
+ });
127
+ return data;
128
+ }
129
+ url(token, kind = "intent") {
130
+ if (!token || /\s/.test(token) || token === "." || token === "..") {
131
+ throw new ValidationError("A valid OwnPay checkout token is required", []);
132
+ }
133
+ const prefix = kind === "intent" ? "/checkout/intent/" : "/checkout/";
134
+ return new URL(prefix + encodeURIComponent(token), this.baseUrl).href;
135
+ }
136
+ };
137
+ function generateUUID() {
138
+ return randomUUID();
139
+ }
140
+ function isValidApiKeyFormat(apiKey) {
141
+ return typeof apiKey === "string" && apiKey.startsWith("op_") && apiKey.length >= 12;
142
+ }
143
+ function isPositiveNumber(value) {
144
+ if (typeof value === "number") {
145
+ return value > 0 && Number.isFinite(value);
146
+ }
147
+ if (typeof value === "string") {
148
+ const num = Number(value);
149
+ return !isNaN(num) && num > 0 && Number.isFinite(num);
150
+ }
151
+ return false;
152
+ }
153
+ function isValidUrl(url) {
154
+ try {
155
+ const parsed = new URL(url);
156
+ return parsed.protocol === "http:" || parsed.protocol === "https:";
157
+ } catch {
158
+ return false;
159
+ }
160
+ }
161
+ function buildQueryString(params) {
162
+ const searchParams = new URLSearchParams();
163
+ for (const [key, value] of Object.entries(params)) {
164
+ if (value !== void 0 && value !== null) {
165
+ searchParams.set(key, String(value));
166
+ }
167
+ }
168
+ const qs = searchParams.toString();
169
+ return qs ? `?${qs}` : "";
170
+ }
171
+ function sleep(ms) {
172
+ return new Promise((resolve) => setTimeout(resolve, ms));
173
+ }
174
+ function calculateBackoff(attempt, baseDelay = 1e3, maxDelay = 3e4) {
175
+ const exponentialDelay = baseDelay * Math.pow(2, attempt);
176
+ const jitter = exponentialDelay * 0.25 * (Math.random() * 2 - 1);
177
+ return Math.min(exponentialDelay + jitter, maxDelay);
178
+ }
179
+
180
+ // src/core/client.ts
181
+ var DEFAULT_CONFIG = {
182
+ TIMEOUT: 3e4,
183
+ MAX_RETRIES: 2,
184
+ API_VERSION: "v1",
185
+ USER_AGENT: "OwnPay-NodeJS/1.0.0"
186
+ };
187
+ var RETRYABLE_STATUS_CODES = /* @__PURE__ */ new Set([429, 500, 502, 503, 504]);
188
+ var HttpClient = class {
189
+ apiKey;
190
+ baseUrl;
191
+ timeout;
192
+ maxRetries;
193
+ apiVersion;
194
+ defaultHeaders;
195
+ constructor(config, auth = "ownpay") {
196
+ if (auth === "platform" && (!config.apiKey || /\s/.test(config.apiKey) || !config.baseUrl)) {
197
+ throw new OwnPayError("Platform services require a base URL and a bearer token.", "INVALID_CONFIG");
198
+ }
199
+ if (auth === "ownpay" && !isValidApiKeyFormat(config.apiKey)) {
200
+ throw new OwnPayError(
201
+ 'Invalid API key format. API key must start with "op_" and be at least 12 characters.',
202
+ "INVALID_CONFIG"
203
+ );
204
+ }
205
+ this.apiKey = config.apiKey;
206
+ const configuredBaseUrl = config.baseUrl ?? process.env.OWNPAY_BASE_URL;
207
+ if (!configuredBaseUrl || !isValidUrl(configuredBaseUrl)) {
208
+ throw new OwnPayError(
209
+ "A valid HTTP/HTTPS base URL is required. Set config.baseUrl or OWNPAY_BASE_URL.",
210
+ "INVALID_CONFIG"
211
+ );
212
+ }
213
+ let normalizedBaseUrl = configuredBaseUrl;
214
+ while (normalizedBaseUrl.endsWith("/")) {
215
+ normalizedBaseUrl = normalizedBaseUrl.slice(0, -1);
216
+ }
217
+ this.baseUrl = normalizedBaseUrl;
218
+ this.timeout = config.timeout ?? DEFAULT_CONFIG.TIMEOUT;
219
+ this.maxRetries = config.maxRetries ?? DEFAULT_CONFIG.MAX_RETRIES;
220
+ this.apiVersion = config.apiVersion ?? DEFAULT_CONFIG.API_VERSION;
221
+ this.defaultHeaders = {
222
+ "User-Agent": DEFAULT_CONFIG.USER_AGENT,
223
+ "Accept": "application/json",
224
+ "Content-Type": "application/json",
225
+ ...config.headers
226
+ };
227
+ }
228
+ /**
229
+ * Makes an HTTP request to the OwnPay API.
230
+ *
231
+ * @param config - Request configuration
232
+ * @returns Parsed API response
233
+ */
234
+ async request(config) {
235
+ const { method, path, query, body, options } = config;
236
+ let lastError;
237
+ for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
238
+ try {
239
+ return await this.executeRequest(method, path, query, body, options);
240
+ } catch (error) {
241
+ if (error instanceof OwnPayError) {
242
+ lastError = error;
243
+ if (method !== "GET" || error instanceof AbortError || !this.isRetryableError(error) || attempt === this.maxRetries) {
244
+ throw error;
245
+ }
246
+ const retryAfter = "retryAfter" in error ? error.retryAfter : void 0;
247
+ const delay = retryAfter !== void 0 ? retryAfter * 1e3 : calculateBackoff(attempt);
248
+ await sleep(delay);
249
+ continue;
250
+ }
251
+ throw error;
252
+ }
253
+ }
254
+ throw lastError ?? new NetworkError("Request failed after all retries");
255
+ }
256
+ /**
257
+ * Executes a single HTTP request.
258
+ */
259
+ async executeRequest(method, path, query, body, options) {
260
+ const url = this.buildUrl(path, query);
261
+ const headers = this.buildHeaders(options);
262
+ const timeout = options?.timeout ?? this.timeout;
263
+ const controller = new AbortController();
264
+ const timeoutId = setTimeout(() => {
265
+ controller.abort();
266
+ }, timeout);
267
+ const { signal, cleanup } = options?.signal ? this.combineSignals(options.signal, controller.signal) : { signal: controller.signal, cleanup: () => {
268
+ } };
269
+ try {
270
+ const response = await fetch(url, {
271
+ method,
272
+ headers,
273
+ body: body ? JSON.stringify(body) : void 0,
274
+ signal,
275
+ redirect: "error"
276
+ });
277
+ const responseText = await response.text();
278
+ if (response.ok && responseText.trim() === "") {
279
+ return void 0;
280
+ }
281
+ let responseData;
282
+ try {
283
+ responseData = JSON.parse(responseText);
284
+ } catch {
285
+ throw new NetworkError(
286
+ `Invalid JSON response from API (HTTP ${response.status})`
287
+ );
288
+ }
289
+ if (!response.ok) {
290
+ throw createErrorFromResponse(
291
+ response.status,
292
+ responseData
293
+ );
294
+ }
295
+ return responseData;
296
+ } catch (error) {
297
+ if (error instanceof Error && error.name === "AbortError") {
298
+ throw new AbortError(options?.signal?.aborted ? "Request was aborted" : "Request timed out");
299
+ }
300
+ if (error instanceof OwnPayError) {
301
+ throw error;
302
+ }
303
+ if (error instanceof TypeError && error.message.includes("fetch")) {
304
+ throw new NetworkError("Network request failed", error);
305
+ }
306
+ if (error instanceof Error && "cause" in error) {
307
+ throw new NetworkError(error.message, error);
308
+ }
309
+ if (error instanceof Error) {
310
+ throw new NetworkError(error.message, error);
311
+ }
312
+ throw new NetworkError("Unknown network error");
313
+ } finally {
314
+ clearTimeout(timeoutId);
315
+ cleanup();
316
+ }
317
+ }
318
+ /**
319
+ * Builds the full request URL.
320
+ */
321
+ buildUrl(path, query) {
322
+ const basePath = `/api/${this.apiVersion}`;
323
+ const fullPath = path.startsWith("/") ? path : `/${path}`;
324
+ const queryString = query ? buildQueryString(query) : "";
325
+ return `${this.baseUrl}${basePath}${fullPath}${queryString}`;
326
+ }
327
+ /**
328
+ * Builds request headers including authentication.
329
+ */
330
+ buildHeaders(options) {
331
+ const headers = {
332
+ ...this.defaultHeaders,
333
+ "Authorization": `Bearer ${this.apiKey}`,
334
+ "X-Request-ID": generateUUID()
335
+ };
336
+ if (options?.idempotencyKey) {
337
+ headers["Idempotency-Key"] = options.idempotencyKey;
338
+ }
339
+ if (options?.headers) {
340
+ Object.assign(headers, options.headers);
341
+ }
342
+ return headers;
343
+ }
344
+ /**
345
+ * Combines two abort signals (external + timeout).
346
+ * Returns a combined signal and a cleanup function to remove listeners.
347
+ */
348
+ combineSignals(external, timeout) {
349
+ const controller = new AbortController();
350
+ const onAbort = () => {
351
+ controller.abort();
352
+ };
353
+ if (external.aborted || timeout.aborted) {
354
+ controller.abort();
355
+ return { signal: controller.signal, cleanup: () => {
356
+ } };
357
+ }
358
+ external.addEventListener("abort", onAbort, { once: true });
359
+ timeout.addEventListener("abort", onAbort, { once: true });
360
+ const cleanup = () => {
361
+ external.removeEventListener("abort", onAbort);
362
+ timeout.removeEventListener("abort", onAbort);
363
+ };
364
+ return { signal: controller.signal, cleanup };
365
+ }
366
+ /**
367
+ * Determines if an error is eligible for retry.
368
+ */
369
+ isRetryableError(error) {
370
+ if (error instanceof NetworkError) return true;
371
+ if (error.status && RETRYABLE_STATUS_CODES.has(error.status)) {
372
+ return true;
373
+ }
374
+ return false;
375
+ }
376
+ };
377
+
378
+ // src/resources/payments.ts
379
+ var PaymentsResource = class {
380
+ constructor(client) {
381
+ this.client = client;
382
+ this.rail = new SwitchResource(client);
383
+ }
384
+ client;
385
+ rail;
386
+ create(params, options) {
387
+ return this.rail.initiate(params, options);
388
+ }
389
+ /**
390
+ * Retrieves a payment by its ID.
391
+ *
392
+ * @param paymentId - The payment UUID
393
+ * @param options - Optional request options
394
+ * @returns Payment details
395
+ *
396
+ * @example
397
+ * ```typescript
398
+ * const payment = await client.payments.get('pay_abc123...');
399
+ * console.log(payment.status); // 'completed'
400
+ * ```
401
+ */
402
+ async get(paymentId, options) {
403
+ if (!paymentId || typeof paymentId !== "string" || paymentId.trim() === "") {
404
+ throw new ValidationError("Payment ID is required", [
405
+ { code: "REQUIRED", message: "Payment ID is required", field: "payment_id" }
406
+ ]);
407
+ }
408
+ const response = await this.client.request({
409
+ method: "GET",
410
+ path: `/payments/${encodeURIComponent(paymentId.trim())}`,
411
+ options
412
+ });
413
+ return response.data;
414
+ }
415
+ };
416
+
417
+ // src/resources/transactions.ts
418
+ var TransactionsResource = class {
419
+ constructor(client) {
420
+ this.client = client;
421
+ }
422
+ client;
423
+ /**
424
+ * Lists transactions with optional filtering and pagination.
425
+ *
426
+ * @param params - Optional filter and pagination parameters
427
+ * @param options - Optional request options
428
+ * @returns Paginated list of transactions
429
+ *
430
+ * @example
431
+ * ```typescript
432
+ * // Get completed transactions from last 7 days
433
+ * const result = await client.transactions.list({
434
+ * status: 'completed',
435
+ * from: '2024-01-01',
436
+ * to: '2024-01-07',
437
+ * per_page: 50,
438
+ * });
439
+ *
440
+ * for (const txn of result.items) {
441
+ * console.log(`${txn.trx_id}: ${txn.amount} ${txn.currency}`);
442
+ * }
443
+ * ```
444
+ */
445
+ async list(params, options) {
446
+ const query = {};
447
+ if (params?.page !== void 0) query.page = params.page;
448
+ if (params?.per_page !== void 0) query.per_page = params.per_page;
449
+ if (params?.status) query.status = params.status;
450
+ if (params?.gateway) query.gateway = params.gateway;
451
+ if (params?.from) query.from = params.from;
452
+ if (params?.to) query.to = params.to;
453
+ const response = await this.client.request({
454
+ method: "GET",
455
+ path: "/transactions",
456
+ query,
457
+ options
458
+ });
459
+ return {
460
+ items: response.data || [],
461
+ meta: response.meta ?? {
462
+ page: params?.page ?? 1,
463
+ per_page: params?.per_page ?? 25,
464
+ total: 0,
465
+ total_pages: 0
466
+ }
467
+ };
468
+ }
469
+ /**
470
+ * Retrieves a single transaction by ID.
471
+ *
472
+ * Accepts either an OwnPay transaction reference (e.g., 'OP-XXXX')
473
+ * or a gateway transaction ID.
474
+ *
475
+ * @param trxId - Transaction ID (OwnPay reference or gateway ID)
476
+ * @param options - Optional request options
477
+ * @returns Transaction details
478
+ *
479
+ * @example
480
+ * ```typescript
481
+ * // By OwnPay reference
482
+ * const txn = await client.transactions.get('OP-ABC123');
483
+ *
484
+ * // By gateway transaction ID
485
+ * const txn = await client.transactions.get('gw_xyz789');
486
+ * ```
487
+ */
488
+ async get(trxId, options) {
489
+ if (!trxId || typeof trxId !== "string" || trxId.trim() === "") {
490
+ throw new ValidationError("Transaction ID is required", [
491
+ { code: "REQUIRED", message: "Transaction ID is required", field: "trx_id" }
492
+ ]);
493
+ }
494
+ const response = await this.client.request({
495
+ method: "GET",
496
+ path: `/transactions/${encodeURIComponent(trxId.trim())}`,
497
+ options
498
+ });
499
+ return response.data;
500
+ }
501
+ };
502
+
503
+ // src/resources/refunds.ts
504
+ var RefundsResource = class {
505
+ constructor(client) {
506
+ this.client = client;
507
+ }
508
+ client;
509
+ /**
510
+ * Creates a new refund for a transaction.
511
+ *
512
+ * @param params - Refund creation parameters
513
+ * @param options - Optional request options
514
+ * @returns Created refund details
515
+ *
516
+ * @example
517
+ * ```typescript
518
+ * const refund = await client.refunds.create({
519
+ * transaction_id: 'OP-ABC123',
520
+ * amount: '25.00',
521
+ * reason: 'Item returned',
522
+ * });
523
+ *
524
+ * console.log(refund.status); // 'pending' or 'completed'
525
+ * ```
526
+ */
527
+ async create(params, options) {
528
+ this.validateCreateParams(params);
529
+ const body = {};
530
+ if (params.transaction_id !== void 0) {
531
+ body.transaction_id = params.transaction_id;
532
+ } else if (params.trx_id !== void 0) {
533
+ body.trx_id = params.trx_id;
534
+ }
535
+ if (params.amount !== void 0) {
536
+ body.amount = String(params.amount);
537
+ }
538
+ if (params.reason !== void 0) {
539
+ body.reason = params.reason;
540
+ }
541
+ const response = await this.client.request({
542
+ method: "POST",
543
+ path: "/refunds",
544
+ body,
545
+ options
546
+ });
547
+ return response.data;
548
+ }
549
+ /**
550
+ * Lists refunds with optional filtering and pagination.
551
+ *
552
+ * @param params - Optional filter and pagination parameters
553
+ * @param options - Optional request options
554
+ * @returns Paginated list of refunds
555
+ *
556
+ * @example
557
+ * ```typescript
558
+ * const result = await client.refunds.list({
559
+ * status: 'completed',
560
+ * page: 1,
561
+ * per_page: 25,
562
+ * });
563
+ *
564
+ * for (const refund of result.items) {
565
+ * console.log(`${refund.uuid}: ${refund.amount}`);
566
+ * }
567
+ * ```
568
+ */
569
+ async list(params, options) {
570
+ const query = {};
571
+ if (params?.page !== void 0) query.page = params.page;
572
+ if (params?.per_page !== void 0) query.per_page = params.per_page;
573
+ if (params?.status) query.status = params.status;
574
+ if (params?.trx_id) query.trx_id = params.trx_id;
575
+ if (params?.transaction_id) query.transaction_id = params.transaction_id;
576
+ if (params?.from) query.from = params.from;
577
+ if (params?.to) query.to = params.to;
578
+ const response = await this.client.request({
579
+ method: "GET",
580
+ path: "/refunds",
581
+ query,
582
+ options
583
+ });
584
+ return {
585
+ items: response.data || [],
586
+ meta: response.meta ?? {
587
+ page: params?.page ?? 1,
588
+ per_page: params?.per_page ?? 25,
589
+ total: 0,
590
+ total_pages: 0
591
+ }
592
+ };
593
+ }
594
+ /**
595
+ * Retrieves a single refund by transaction reference.
596
+ *
597
+ * @param trxId - Transaction ID (OwnPay reference or gateway ID)
598
+ * @param options - Optional request options
599
+ * @returns Refund details
600
+ *
601
+ * @example
602
+ * ```typescript
603
+ * const refund = await client.refunds.get('OP-ABC123');
604
+ * ```
605
+ */
606
+ async get(trxId, options) {
607
+ if (!trxId || typeof trxId !== "string" || trxId.trim() === "") {
608
+ throw new ValidationError("Transaction ID is required", [
609
+ { code: "REQUIRED", message: "Transaction ID is required", field: "trx_id" }
610
+ ]);
611
+ }
612
+ const response = await this.client.request({
613
+ method: "GET",
614
+ path: `/refunds/${encodeURIComponent(trxId.trim())}`,
615
+ options
616
+ });
617
+ return response.data;
618
+ }
619
+ /**
620
+ * Validates refund creation parameters.
621
+ */
622
+ validateCreateParams(params) {
623
+ const errors = [];
624
+ if ((params.transaction_id === void 0 || params.transaction_id === null) && (params.trx_id === void 0 || params.trx_id === null)) {
625
+ errors.push({
626
+ code: "REQUIRED",
627
+ message: "transaction_id or trx_id is required",
628
+ field: "transaction_id"
629
+ });
630
+ }
631
+ if (params.amount !== void 0 && params.amount !== null) {
632
+ if (!isPositiveNumber(params.amount)) {
633
+ errors.push({
634
+ code: "INVALID_AMOUNT",
635
+ message: "Amount must be a positive number",
636
+ field: "amount"
637
+ });
638
+ }
639
+ }
640
+ if (errors.length > 0) {
641
+ throw new ValidationError(
642
+ errors[0]?.message ?? "Validation failed",
643
+ errors.map((e) => ({
644
+ code: e.code,
645
+ message: e.message,
646
+ field: e.field
647
+ }))
648
+ );
649
+ }
650
+ }
651
+ };
652
+
653
+ // src/resources/customers.ts
654
+ var CustomersResource = class {
655
+ constructor(client) {
656
+ this.client = client;
657
+ }
658
+ client;
659
+ /**
660
+ * Creates a new customer.
661
+ *
662
+ * @param params - Customer creation parameters
663
+ * @param options - Optional request options
664
+ * @returns Created customer with ID and UUID
665
+ *
666
+ * @example
667
+ * ```typescript
668
+ * const customer = await client.customers.create({
669
+ * name: 'Jane Smith',
670
+ * email: 'jane@example.com',
671
+ * phone: '+8801712345678',
672
+ * });
673
+ *
674
+ * console.log(customer.id); // Internal ID
675
+ * console.log(customer.uuid); // Public UUID
676
+ * ```
677
+ */
678
+ async create(params, options) {
679
+ this.validateCreateParams(params);
680
+ const body = {
681
+ name: params.name
682
+ };
683
+ if (params.email) body.email = params.email;
684
+ if (params.phone) body.phone = params.phone;
685
+ const response = await this.client.request({
686
+ method: "POST",
687
+ path: "/customers",
688
+ body,
689
+ options
690
+ });
691
+ return response.data;
692
+ }
693
+ /**
694
+ * Lists customers with pagination.
695
+ *
696
+ * @param params - Optional pagination parameters
697
+ * @param options - Optional request options
698
+ * @returns Paginated list of customers
699
+ *
700
+ * @example
701
+ * ```typescript
702
+ * const result = await client.customers.list({ page: 1, per_page: 50 });
703
+ *
704
+ * for (const customer of result.items) {
705
+ * console.log(`${customer.name}: ${customer.email}`);
706
+ * }
707
+ * ```
708
+ */
709
+ async list(params, options) {
710
+ const query = {};
711
+ if (params?.page !== void 0) query.page = params.page;
712
+ if (params?.per_page !== void 0) query.per_page = params.per_page;
713
+ const response = await this.client.request({
714
+ method: "GET",
715
+ path: "/customers",
716
+ query,
717
+ options
718
+ });
719
+ return {
720
+ items: response.data || [],
721
+ meta: response.meta ?? {
722
+ page: params?.page ?? 1,
723
+ per_page: params?.per_page ?? 25,
724
+ total: 0,
725
+ total_pages: 0
726
+ }
727
+ };
728
+ }
729
+ /**
730
+ * Retrieves a customer by email or phone number.
731
+ *
732
+ * The identifier is auto-detected:
733
+ * - Contains '@' → treated as email
734
+ * - Otherwise → treated as phone
735
+ *
736
+ * @param identifier - Customer email or phone number
737
+ * @param options - Optional request options
738
+ * @returns Customer details
739
+ *
740
+ * @example
741
+ * ```typescript
742
+ * // By email
743
+ * const customer = await client.customers.get('john@example.com');
744
+ *
745
+ * // By phone
746
+ * const customer = await client.customers.get('+8801712345678');
747
+ * ```
748
+ */
749
+ async get(identifier, options) {
750
+ if (!identifier || typeof identifier !== "string" || identifier.trim() === "") {
751
+ throw new ValidationError("Identifier is required", [
752
+ { code: "REQUIRED", message: "Email or phone identifier is required", field: "identifier" }
753
+ ]);
754
+ }
755
+ const response = await this.client.request({
756
+ method: "GET",
757
+ path: `/customers/${encodeURIComponent(identifier.trim())}`,
758
+ options
759
+ });
760
+ return response.data;
761
+ }
762
+ /**
763
+ * Validates customer creation parameters.
764
+ */
765
+ validateCreateParams(params) {
766
+ const errors = [];
767
+ if (!params.name || typeof params.name !== "string" || params.name.trim() === "") {
768
+ errors.push({
769
+ code: "REQUIRED",
770
+ message: "Customer name is required",
771
+ field: "name"
772
+ });
773
+ }
774
+ if (params.name && params.name.length > 150) {
775
+ errors.push({
776
+ code: "INVALID_LENGTH",
777
+ message: "Customer name must be 150 characters or less",
778
+ field: "name"
779
+ });
780
+ }
781
+ if (errors.length > 0) {
782
+ throw new ValidationError(
783
+ errors[0]?.message ?? "Validation failed",
784
+ errors.map((e) => ({
785
+ code: e.code,
786
+ message: e.message,
787
+ field: e.field
788
+ }))
789
+ );
790
+ }
791
+ }
792
+ };
793
+
794
+ // src/resources/api-keys.ts
795
+ var ApiKeysResource = class {
796
+ constructor(client) {
797
+ this.client = client;
798
+ }
799
+ client;
800
+ /**
801
+ * Lists all API keys for the authenticated merchant.
802
+ *
803
+ * Note: Requires API key with 'write' and 'admin' scopes.
804
+ *
805
+ * @param options - Optional request options (must include superAdminEmail header)
806
+ * @returns Array of API key metadata
807
+ *
808
+ * @example
809
+ * ```typescript
810
+ * const keys = await client.apiKeys.list({
811
+ * headers: { 'X-Super-Admin-Email': 'admin@example.com' },
812
+ * });
813
+ * ```
814
+ */
815
+ async list(options) {
816
+ this.ensureAdminHeaders(options);
817
+ const response = await this.client.request({
818
+ method: "GET",
819
+ path: "/api-keys",
820
+ options
821
+ });
822
+ return response.data || [];
823
+ }
824
+ /**
825
+ * Generates a new API key.
826
+ *
827
+ * Note: Requires API key with 'write' and 'admin' scopes.
828
+ * The actual key is only shown once in the response.
829
+ *
830
+ * @param params - Key generation parameters
831
+ * @param options - Optional request options (must include superAdminEmail header)
832
+ * @returns Generated API key (store securely, cannot be retrieved again)
833
+ *
834
+ * @example
835
+ * ```typescript
836
+ * const result = await client.apiKeys.generate({
837
+ * name: 'My App Key',
838
+ * scopes: ['read', 'write'],
839
+ * }, {
840
+ * headers: { 'X-Super-Admin-Email': 'admin@example.com' },
841
+ * });
842
+ *
843
+ * // IMPORTANT: Store this key securely!
844
+ * console.log(result.key); // 'op_xxxxx...'
845
+ * console.log(result.warning); // 'Store this key securely...'
846
+ * ```
847
+ */
848
+ async generate(params, options) {
849
+ this.ensureAdminHeaders(options);
850
+ const body = {};
851
+ if (params?.name) body.name = params.name;
852
+ if (params?.scopes) {
853
+ this.validateScopes(params.scopes);
854
+ body.scopes = params.scopes;
855
+ }
856
+ const response = await this.client.request({
857
+ method: "POST",
858
+ path: "/api-keys",
859
+ body,
860
+ options
861
+ });
862
+ return response.data;
863
+ }
864
+ /**
865
+ * Revokes an API key by ID.
866
+ *
867
+ * Note: Requires API key with 'write' and 'admin' scopes.
868
+ *
869
+ * @param keyId - The API key ID to revoke
870
+ * @param options - Optional request options (must include superAdminEmail header)
871
+ *
872
+ * @example
873
+ * ```typescript
874
+ * await client.apiKeys.revoke(123, {
875
+ * headers: { 'X-Super-Admin-Email': 'admin@example.com' },
876
+ * });
877
+ * ```
878
+ */
879
+ async revoke(keyId, options) {
880
+ this.ensureAdminHeaders(options);
881
+ if (!Number.isInteger(keyId) || keyId <= 0) {
882
+ throw new ValidationError("Valid API key ID is required", [
883
+ { code: "REQUIRED", message: "Valid API key ID is required", field: "id" }
884
+ ]);
885
+ }
886
+ await this.client.request({
887
+ method: "DELETE",
888
+ path: `/api-keys/${keyId}`,
889
+ options
890
+ });
891
+ }
892
+ /**
893
+ * Ensures the X-Super-Admin-Email header is present.
894
+ */
895
+ ensureAdminHeaders(options) {
896
+ const email = options?.headers?.["X-Super-Admin-Email"];
897
+ if (!email) {
898
+ throw new PermissionError(
899
+ 'API key operations require the X-Super-Admin-Email header. Pass it in options.headers["X-Super-Admin-Email"].'
900
+ );
901
+ }
902
+ }
903
+ /**
904
+ * Validates API key scopes.
905
+ */
906
+ validateScopes(scopes) {
907
+ const allowed = ["read", "write", "admin"];
908
+ for (const scope of scopes) {
909
+ if (!allowed.includes(scope)) {
910
+ throw new ValidationError(
911
+ `Invalid scope: ${scope}. Allowed: ${allowed.join(", ")}`,
912
+ [{ code: "INVALID_SCOPE", message: `Invalid scope: ${scope}`, field: "scopes" }]
913
+ );
914
+ }
915
+ }
916
+ }
917
+ };
918
+
919
+ // src/resources/webhooks.ts
920
+ var WebhooksResource = class {
921
+ constructor(client) {
922
+ this.client = client;
923
+ }
924
+ client;
925
+ /**
926
+ * Sends a test webhook to the configured endpoint.
927
+ *
928
+ * @param options - Optional request options
929
+ * @returns Test result with status code and response time
930
+ *
931
+ * @example
932
+ * ```typescript
933
+ * const result = await client.webhooks.test();
934
+ *
935
+ * if (result.status_code === 200) {
936
+ * console.log('Webhook endpoint is working!');
937
+ * }
938
+ * ```
939
+ */
940
+ async test(options) {
941
+ const response = await this.client.request({
942
+ method: "POST",
943
+ path: "/webhooks/tests",
944
+ options
945
+ });
946
+ return response.data;
947
+ }
948
+ /**
949
+ * Lists recent webhook deliveries.
950
+ *
951
+ * @param options - Optional request options
952
+ * @returns Array of webhook delivery records
953
+ *
954
+ * @example
955
+ * ```typescript
956
+ * const deliveries = await client.webhooks.deliveries();
957
+ *
958
+ * for (const delivery of deliveries) {
959
+ * console.log(`${delivery.event}: ${delivery.status} (${delivery.status_code})`);
960
+ * }
961
+ * ```
962
+ */
963
+ async deliveries(options) {
964
+ const response = await this.client.request({
965
+ method: "GET",
966
+ path: "/webhooks/deliveries",
967
+ options
968
+ });
969
+ return response.data || [];
970
+ }
971
+ };
972
+
973
+ // src/resources/merchant.ts
974
+ var MerchantResource = class {
975
+ constructor(client) {
976
+ this.client = client;
977
+ }
978
+ client;
979
+ disburse(params, options) {
980
+ const phone = params.recipient.phone.trim();
981
+ if (!/^\+[1-9]\d{6,14}$/.test(phone)) throw new ValidationError("Recipient phone must use strict E.164", []);
982
+ return this.client.request({
983
+ method: "POST",
984
+ path: "/disburse",
985
+ body: { ...params, amount: validateAmount(params.amount), recipient: { phone } },
986
+ options
987
+ });
988
+ }
989
+ async float(currency, options) {
990
+ const { data } = await this.client.request({
991
+ method: "GET",
992
+ path: "/merchants/float",
993
+ query: { currency: currency.toUpperCase() },
994
+ options
995
+ });
996
+ return data;
997
+ }
998
+ virtualAccounts = {
999
+ provision: async (params, options) => {
1000
+ const { data } = await this.client.request({
1001
+ method: "POST",
1002
+ path: "/virtual-accounts",
1003
+ body: { reference: params.reference, currency: params.currency.toUpperCase() },
1004
+ options
1005
+ });
1006
+ return data;
1007
+ },
1008
+ list: async (afterId, options) => {
1009
+ const { data } = await this.client.request({ method: "GET", path: "/virtual-accounts", query: { after_id: afterId }, options });
1010
+ return data;
1011
+ }
1012
+ };
1013
+ payoutMethods = {
1014
+ list: (options) => this.call("GET", "/merchants/payout-methods", options),
1015
+ create: (body, options) => this.call("POST", "/merchants/payout-methods", options, body),
1016
+ setDefault: (id, options) => this.call("PUT", `/merchants/payout-methods/${segment(id)}/default`, options)
1017
+ };
1018
+ settlement = {
1019
+ getPolicy: (options) => this.call("GET", "/merchants/settlement/policy", options),
1020
+ updatePolicy: (body, options) => this.call("PUT", "/merchants/settlement/policy", options, body),
1021
+ sweep: (body, options) => this.call("POST", "/merchants/settlement/sweep", options, body)
1022
+ };
1023
+ paymentMethods = {
1024
+ list: (customerId, options) => this.call("GET", `/customers/${segment(customerId)}/payment-methods`, options),
1025
+ create: (customerId, body, options) => this.call("POST", `/customers/${segment(customerId)}/payment-methods`, options, body),
1026
+ setDefault: (customerId, id, options) => this.call("PUT", `/customers/${segment(customerId)}/payment-methods/${segment(id)}/default`, options),
1027
+ revoke: (customerId, id, options) => this.call("DELETE", `/customers/${segment(customerId)}/payment-methods/${segment(id)}`, options)
1028
+ };
1029
+ wallets = {
1030
+ list: (customerId, options) => this.call("GET", `/customers/${segment(customerId)}/wallets`, options),
1031
+ create: (customerId, body, options) => this.call("POST", `/customers/${segment(customerId)}/wallets`, options, body),
1032
+ topUp: (customerId, currency, body, options) => this.call("POST", `/customers/${segment(customerId)}/wallets/${segment(currency.toUpperCase())}/topup`, options, body)
1033
+ };
1034
+ accountReferences = {
1035
+ list: (query, options) => this.call("GET", "/merchants/account-references", options, void 0, query),
1036
+ get: (id, options) => this.call("GET", `/merchants/account-references/${segment(id)}`, options),
1037
+ create: (body, options) => this.call("POST", "/merchants/account-references", options, body),
1038
+ update: (id, body, options) => this.call("PUT", `/merchants/account-references/${segment(id)}`, options, body),
1039
+ remove: (id, options) => this.call("DELETE", `/merchants/account-references/${segment(id)}`, options)
1040
+ };
1041
+ commerce = {
1042
+ listProducts: (query, options) => this.call("GET", "/products", options, void 0, query),
1043
+ createProduct: (body, options) => this.call("POST", "/products", options, body),
1044
+ listStorefronts: (query, options) => this.call("GET", "/storefronts", options, void 0, query),
1045
+ listOrders: (query, options) => this.call("GET", "/orders", options, void 0, query)
1046
+ };
1047
+ terminals = {
1048
+ list: (options) => this.call("GET", "/terminals", options),
1049
+ pushIntent: (body, options) => this.call("POST", "/terminals/intents", options, body),
1050
+ settle: (id, body, options) => this.call("POST", `/terminals/${segment(id)}/settle`, options, body)
1051
+ };
1052
+ call(method, path, options, body, query) {
1053
+ return this.client.request({ method, path, options, body, query });
1054
+ }
1055
+ };
1056
+ function segment(value) {
1057
+ if (!value.trim() || value === "." || value === "..") throw new ValidationError("Invalid resource identifier", []);
1058
+ return encodeURIComponent(value);
1059
+ }
1060
+
1061
+ // src/resources/health.ts
1062
+ var HealthResource = class {
1063
+ constructor(client) {
1064
+ this.client = client;
1065
+ }
1066
+ client;
1067
+ /**
1068
+ * Performs a system health check.
1069
+ *
1070
+ * Returns detailed information about:
1071
+ * - System status (healthy/degraded)
1072
+ * - Database connectivity
1073
+ * - Mobile companion app status
1074
+ * - Active gateway count
1075
+ * - Customer count
1076
+ *
1077
+ * @param options - Optional request options
1078
+ * @returns Health status information
1079
+ *
1080
+ * @example
1081
+ * ```typescript
1082
+ * const health = await client.health.check();
1083
+ *
1084
+ * console.log(`Status: ${health.status}`);
1085
+ * console.log(`Version: ${health.version}`);
1086
+ * console.log(`Database: ${health.db}`);
1087
+ * console.log(`Active gateways: ${health.gateways}`);
1088
+ * console.log(`Total customers: ${health.customers}`);
1089
+ *
1090
+ * // Check mobile companion status
1091
+ * if (health.mobile.connected) {
1092
+ * console.log(`Mobile devices: ${health.mobile.active_devices}`);
1093
+ * }
1094
+ * ```
1095
+ */
1096
+ async check(options) {
1097
+ const response = await this.client.request({
1098
+ method: "GET",
1099
+ path: "/health",
1100
+ options
1101
+ });
1102
+ return response.data;
1103
+ }
1104
+ };
1105
+
1106
+ // src/platform.ts
1107
+ function transport(config) {
1108
+ const client = new HttpClient({ ...config, apiKey: config.token }, "platform");
1109
+ return (method, path, options, body, query) => client.request({ method, path, options, body, query });
1110
+ }
1111
+ var Notifications = class {
1112
+ call;
1113
+ constructor(config) {
1114
+ this.call = transport(config);
1115
+ }
1116
+ sendSms(body, options) {
1117
+ return this.call("POST", "/notifications/sms", options, body);
1118
+ }
1119
+ sendEmail(body, options) {
1120
+ return this.call("POST", "/notifications/email", options, body);
1121
+ }
1122
+ sendPush(body, options) {
1123
+ return this.call("POST", "/notifications/push", options, body);
1124
+ }
1125
+ sendOtp(body, options) {
1126
+ return this.call("POST", "/notifications/otp", options, body);
1127
+ }
1128
+ };
1129
+ var Billing = class {
1130
+ call;
1131
+ constructor(config) {
1132
+ this.call = transport(config);
1133
+ }
1134
+ catalog(query, options) {
1135
+ return this.call("GET", "/utilities/catalog", options, void 0, query);
1136
+ }
1137
+ lookupAccount(body, options) {
1138
+ return this.call("POST", "/utilities/account-lookup", options, body);
1139
+ }
1140
+ quote(body, options) {
1141
+ return this.call("POST", "/utilities/quotes", options, body);
1142
+ }
1143
+ vend(body, options) {
1144
+ return this.call("POST", "/utilities/vend", options, body);
1145
+ }
1146
+ quoteAirtime(body, options) {
1147
+ return this.call("POST", "/airtime/query", options, body);
1148
+ }
1149
+ };
1150
+ var DeveloperTools = class {
1151
+ call;
1152
+ constructor(config) {
1153
+ this.call = transport(config);
1154
+ }
1155
+ usage(query, options) {
1156
+ return this.call("GET", "/developer/usage", options, void 0, query);
1157
+ }
1158
+ executeSandbox(body, options) {
1159
+ return this.call("POST", "/developer/sandbox/execute", options, body);
1160
+ }
1161
+ simulateWebhook(body, options) {
1162
+ return this.call("POST", "/developer/webhooks/simulate", options, body);
1163
+ }
1164
+ };
1165
+ var ForeignExchange = class {
1166
+ call;
1167
+ constructor(config) {
1168
+ this.call = transport(config);
1169
+ }
1170
+ quote(body, options) {
1171
+ return this.call("POST", "/fx/quotes", options, body);
1172
+ }
1173
+ currencies(options) {
1174
+ return this.call("GET", "/fx/currencies", options);
1175
+ }
1176
+ };
1177
+ var Banking = class {
1178
+ call;
1179
+ constructor(config) {
1180
+ this.call = transport(config);
1181
+ }
1182
+ walletBalance(currency, options) {
1183
+ return this.call("GET", "/wallets/balance", options, void 0, { currency });
1184
+ }
1185
+ };
1186
+
1187
+ // src/index.ts
1188
+ var OwnPay = class {
1189
+ /** HTTP client instance */
1190
+ client;
1191
+ /** Payment operations */
1192
+ payments;
1193
+ /** Direct switch & multi-rail operations (M-Pesa STK push, Airtel Money) */
1194
+ switch;
1195
+ /** Transaction queries */
1196
+ transactions;
1197
+ /** Refund operations */
1198
+ refunds;
1199
+ /** Customer management */
1200
+ customers;
1201
+ /** API key management */
1202
+ apiKeys;
1203
+ /** Webhook operations */
1204
+ webhooks;
1205
+ /** Health checks */
1206
+ health;
1207
+ merchant;
1208
+ cards;
1209
+ checkout;
1210
+ /**
1211
+ * Creates a new OwnPay client instance.
1212
+ *
1213
+ * @param apiKeyOrConfig - API key string or configuration object
1214
+ *
1215
+ * @example
1216
+ * ```typescript
1217
+ * // With configuration
1218
+ * const client = new OwnPay({
1219
+ * apiKey: 'op_xxx...',
1220
+ * baseUrl: 'https://custom.domain.com',
1221
+ * timeout: 30000,
1222
+ * maxRetries: 3,
1223
+ * });
1224
+ * ```
1225
+ */
1226
+ constructor(apiKeyOrConfig) {
1227
+ const config = typeof apiKeyOrConfig === "string" ? { apiKey: apiKeyOrConfig } : apiKeyOrConfig;
1228
+ this.client = new HttpClient(config);
1229
+ this.payments = new PaymentsResource(this.client);
1230
+ this.switch = new SwitchResource(this.client);
1231
+ this.transactions = new TransactionsResource(this.client);
1232
+ this.refunds = new RefundsResource(this.client);
1233
+ this.customers = new CustomersResource(this.client);
1234
+ this.apiKeys = new ApiKeysResource(this.client);
1235
+ this.webhooks = new WebhooksResource(this.client);
1236
+ this.health = new HealthResource(this.client);
1237
+ this.merchant = new MerchantResource(this.client);
1238
+ this.cards = new CardsResource(this.client);
1239
+ this.checkout = new CheckoutResource(this.client, config.checkoutBaseUrl ?? config.baseUrl ?? process.env.OWNPAY_BASE_URL);
1240
+ }
1241
+ };
1242
+ var src_default = OwnPay;
1243
+
1244
+ export { ApiKeysResource, Banking, Billing, CardsResource, CheckoutResource, OwnPay as Client, CustomersResource, DeveloperTools, ForeignExchange, HealthResource, MerchantResource, Notifications, OwnPay, PaymentsResource, RefundsResource, SwitchResource, TransactionsResource, WebhooksResource, src_default as default };
1245
+ //# sourceMappingURL=index.js.map
1246
+ //# sourceMappingURL=index.js.map