pycer-sdk 0.0.0-stage → 1.0.3

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