@cosmosapp/pay_sdk 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,1205 @@
1
+ 'use strict';
2
+
3
+ var events = require('events');
4
+ var crypto = require('crypto');
5
+
6
+ // src/client/Client.ts
7
+
8
+ // src/managers/AnalyticsManager.ts
9
+ var AnalyticsManager = class {
10
+ constructor(client) {
11
+ this.client = client;
12
+ }
13
+ get rest() {
14
+ return this.client.rest;
15
+ }
16
+ /** Overview metrics: totals, settled volume, webhook health, 30-day series. */
17
+ summary() {
18
+ return this.rest.get("/summary");
19
+ }
20
+ /** Settled (and pending) amount per asset. */
21
+ balances() {
22
+ return this.rest.get("/balances");
23
+ }
24
+ /** Recent API requests reaching the service (with details). */
25
+ apiLogs() {
26
+ return this.rest.get("/logs");
27
+ }
28
+ /** Recent webhook deliveries across all endpoints (with details). */
29
+ webhookLogs() {
30
+ return this.rest.get("/logs/webhooks");
31
+ }
32
+ };
33
+
34
+ // src/structures/Base.ts
35
+ var Base = class {
36
+ constructor(client, data) {
37
+ this.client = client;
38
+ this._patch(data);
39
+ }
40
+ /** Merge raw API data onto this instance. Subclasses override and call super. */
41
+ _patch(data) {
42
+ this.id = data.id;
43
+ return this;
44
+ }
45
+ /** Allow `String(structure)` / template literals to resolve to the id. */
46
+ valueOf() {
47
+ return this.id;
48
+ }
49
+ };
50
+
51
+ // src/structures/Customer.ts
52
+ var Customer = class extends Base {
53
+ constructor(client, data) {
54
+ super(client, data);
55
+ /** Number of payment intents from this customer's account (list view only). */
56
+ this.payments = null;
57
+ /** Number of succeeded payments (list view only). */
58
+ this.succeeded = null;
59
+ /** Total settled amount as a decimal string (list view only). */
60
+ this.total = null;
61
+ }
62
+ _patch(data) {
63
+ super._patch(data);
64
+ this.consumerId = data.consumerId;
65
+ this.name = data.name;
66
+ this.alias = data.alias;
67
+ this.note = data.note;
68
+ this.email = data.email;
69
+ this.account = data.account;
70
+ this.reference = data.reference;
71
+ this.createdAt = new Date(data.createdAt);
72
+ this.updatedAt = new Date(data.updatedAt);
73
+ if (data.payments !== void 0) this.payments = data.payments;
74
+ if (data.succeeded !== void 0) this.succeeded = data.succeeded;
75
+ if (data.total !== void 0) this.total = data.total;
76
+ return this;
77
+ }
78
+ /** Re-fetch this customer. */
79
+ fetch() {
80
+ return this.client.customers.fetch(this.id);
81
+ }
82
+ /** Update this customer. Mutates and returns this. */
83
+ async edit(options) {
84
+ const updated = await this.client.customers.update(this.id, options);
85
+ return this._patch(updated.toJSON());
86
+ }
87
+ /** Delete this customer. */
88
+ delete() {
89
+ return this.client.customers.delete(this.id);
90
+ }
91
+ toJSON() {
92
+ return {
93
+ id: this.id,
94
+ consumerId: this.consumerId,
95
+ name: this.name,
96
+ alias: this.alias,
97
+ note: this.note,
98
+ email: this.email,
99
+ account: this.account,
100
+ reference: this.reference,
101
+ createdAt: this.createdAt.toISOString(),
102
+ updatedAt: this.updatedAt.toISOString(),
103
+ ...this.payments !== null ? { payments: this.payments } : {},
104
+ ...this.succeeded !== null ? { succeeded: this.succeeded } : {},
105
+ ...this.total !== null ? { total: this.total } : {}
106
+ };
107
+ }
108
+ };
109
+ var BaseManager = class extends events.EventEmitter {
110
+ constructor(client) {
111
+ super();
112
+ /** Cache of structures keyed by id, populated on fetch/create. */
113
+ this.cache = /* @__PURE__ */ new Map();
114
+ this.client = client;
115
+ }
116
+ /** Shortcut to the shared REST instance. */
117
+ get rest() {
118
+ return this.client.rest;
119
+ }
120
+ /** Store a structure in the cache and return it. */
121
+ _add(structure) {
122
+ this.cache.set(structure.id, structure);
123
+ return structure;
124
+ }
125
+ /** Resolve an id from either a raw id or a structure instance. */
126
+ resolveId(idOrStructure) {
127
+ return typeof idOrStructure === "string" ? idOrStructure : idOrStructure.id;
128
+ }
129
+ };
130
+
131
+ // src/managers/CustomerManager.ts
132
+ var CustomerManager = class extends BaseManager {
133
+ constructor() {
134
+ super(...arguments);
135
+ this.route = "/customers";
136
+ }
137
+ /** Create a customer. */
138
+ async create(options) {
139
+ const data = await this.rest.post(this.route, { body: options });
140
+ return this._add(new Customer(this.client, data));
141
+ }
142
+ /** List the consumer's customers (with payment stats). */
143
+ async list() {
144
+ const data = await this.rest.get(this.route);
145
+ return data.data.map((d) => this._add(new Customer(this.client, d)));
146
+ }
147
+ /** Get a customer by id. */
148
+ async fetch(id) {
149
+ const data = await this.rest.get(`${this.route}/${id}`);
150
+ return this._add(new Customer(this.client, data));
151
+ }
152
+ /** Update a customer. */
153
+ async update(id, options) {
154
+ const data = await this.rest.patch(`${this.route}/${id}`, {
155
+ body: options
156
+ });
157
+ return this._add(new Customer(this.client, data));
158
+ }
159
+ /** Delete a customer. */
160
+ async delete(id) {
161
+ const result = await this.rest.delete(
162
+ `${this.route}/${id}`
163
+ );
164
+ this.cache.delete(id);
165
+ return result;
166
+ }
167
+ };
168
+
169
+ // src/managers/HealthManager.ts
170
+ var HealthManager = class {
171
+ constructor(client) {
172
+ this.client = client;
173
+ }
174
+ get rest() {
175
+ return this.client.rest;
176
+ }
177
+ /** Liveness probe — resolves when the service is up. */
178
+ async liveness() {
179
+ await this.rest.get("/health/liveness");
180
+ return true;
181
+ }
182
+ /** Readiness probe (checks the database). Returns the health report. */
183
+ readiness() {
184
+ return this.rest.get("/health/readiness");
185
+ }
186
+ };
187
+
188
+ // src/types/index.ts
189
+ var PaymentIntentStatus = {
190
+ Pending: "PENDING",
191
+ Submitted: "SUBMITTED",
192
+ Succeeded: "SUCCEEDED",
193
+ Failed: "FAILED",
194
+ Cancelled: "CANCELLED",
195
+ Expired: "EXPIRED"
196
+ };
197
+ var PaymentIntentKind = {
198
+ /** Source account is known → unsigned XDR + `web+stellar:tx` URI. */
199
+ Tx: "TX",
200
+ /** No source → `web+stellar:pay` URI only (wallet picks the source). */
201
+ Pay: "PAY"
202
+ };
203
+ var WebhookEventType = {
204
+ PaymentIntentCreated: "PAYMENT_INTENT_CREATED",
205
+ PaymentIntentUpdated: "PAYMENT_INTENT_UPDATED",
206
+ PaymentIntentSucceeded: "PAYMENT_INTENT_SUCCEEDED",
207
+ PaymentIntentFailed: "PAYMENT_INTENT_FAILED",
208
+ PaymentIntentCancelled: "PAYMENT_INTENT_CANCELLED",
209
+ PaymentIntentDeleted: "PAYMENT_INTENT_DELETED"
210
+ };
211
+ var WebhookDeliveryStatus = {
212
+ Pending: "PENDING",
213
+ Succeeded: "SUCCEEDED",
214
+ Failed: "FAILED"
215
+ };
216
+ var ProductKind = {
217
+ Recurring: "recurring",
218
+ OneTime: "one_time",
219
+ Link: "link"
220
+ };
221
+
222
+ // src/structures/PaymentIntent.ts
223
+ var PaymentIntent = class extends Base {
224
+ constructor(client, data) {
225
+ super(client, data);
226
+ }
227
+ _patch(data) {
228
+ super._patch(data);
229
+ this.kind = data.kind;
230
+ this.status = data.status;
231
+ this.network = data.network;
232
+ this.source = data.source;
233
+ this.destination = data.destination;
234
+ this.amount = data.amount;
235
+ this.asset = data.asset;
236
+ this.assetIssuer = data.assetIssuer;
237
+ this.memo = data.memo;
238
+ this.msg = data.msg;
239
+ this.callback = data.callback;
240
+ this.xdr = data.xdr;
241
+ this.uri = data.uri;
242
+ this.qr = data.qr;
243
+ this.txHash = data.txHash;
244
+ this.reference = data.reference;
245
+ this.createdAt = new Date(data.createdAt);
246
+ this.updatedAt = new Date(data.updatedAt);
247
+ return this;
248
+ }
249
+ /** Whether this is a SEP-7 `tx` intent (known source, has XDR). */
250
+ get isTx() {
251
+ return this.kind === PaymentIntentKind.Tx;
252
+ }
253
+ /** Whether this is a SEP-7 `pay` intent (no source). */
254
+ get isPay() {
255
+ return this.kind === PaymentIntentKind.Pay;
256
+ }
257
+ /** Whether the payment has settled on-chain. */
258
+ get isSucceeded() {
259
+ return this.status === PaymentIntentStatus.Succeeded;
260
+ }
261
+ /** Whether the intent is still awaiting payment. */
262
+ get isPending() {
263
+ return this.status === PaymentIntentStatus.Pending;
264
+ }
265
+ /** Human-readable asset label (`XLM` for native). */
266
+ get assetLabel() {
267
+ return !this.asset || this.asset === "native" ? "XLM" : this.asset;
268
+ }
269
+ /** Re-fetch this intent from the API, returning a fresh instance. */
270
+ fetch() {
271
+ return this.client.paymentIntents.fetch(this.id);
272
+ }
273
+ /** Update this intent (status / txHash / reference). Mutates and returns it. */
274
+ async edit(options) {
275
+ const updated = await this.client.paymentIntents.update(this.id, options);
276
+ return this._patch(updated.toJSON());
277
+ }
278
+ /**
279
+ * Validate a submitted transaction against this intent. On a match the status
280
+ * is finalized server-side and the webhook fires.
281
+ */
282
+ validate(txHash) {
283
+ return this.client.paymentIntents.validate(this.id, { txHash });
284
+ }
285
+ /** Mark this intent as cancelled. */
286
+ cancel() {
287
+ return this.edit({ status: PaymentIntentStatus.Cancelled });
288
+ }
289
+ /** Delete this intent. */
290
+ delete() {
291
+ return this.client.paymentIntents.delete(this.id);
292
+ }
293
+ toJSON() {
294
+ return {
295
+ id: this.id,
296
+ kind: this.kind,
297
+ status: this.status,
298
+ network: this.network,
299
+ source: this.source,
300
+ destination: this.destination,
301
+ amount: this.amount,
302
+ asset: this.asset,
303
+ assetIssuer: this.assetIssuer,
304
+ memo: this.memo,
305
+ msg: this.msg,
306
+ callback: this.callback,
307
+ xdr: this.xdr,
308
+ uri: this.uri,
309
+ qr: this.qr,
310
+ txHash: this.txHash,
311
+ reference: this.reference,
312
+ createdAt: this.createdAt.toISOString(),
313
+ updatedAt: this.updatedAt.toISOString()
314
+ };
315
+ }
316
+ };
317
+
318
+ // src/managers/PaymentIntentManager.ts
319
+ var PaymentIntentManager = class extends BaseManager {
320
+ constructor() {
321
+ super(...arguments);
322
+ this.route = "/payment-intents";
323
+ }
324
+ /** Create a SEP-7 `tx` intent (source known → unsigned XDR + tx URI + QR). */
325
+ async createTx(options) {
326
+ const data = await this.rest.post(`${this.route}/tx`, {
327
+ body: options
328
+ });
329
+ return this._add(new PaymentIntent(this.client, data));
330
+ }
331
+ /** Create a SEP-7 `pay` intent (no source → pay URI + QR, no XDR). */
332
+ async createPay(options) {
333
+ const data = await this.rest.post(`${this.route}/pay`, {
334
+ body: options
335
+ });
336
+ return this._add(new PaymentIntent(this.client, data));
337
+ }
338
+ /** Get a single payment intent by id. */
339
+ async fetch(id) {
340
+ const data = await this.rest.get(`${this.route}/${id}`);
341
+ return this._add(new PaymentIntent(this.client, data));
342
+ }
343
+ /** List the consumer's payment intents (paginated). */
344
+ async list(options = {}) {
345
+ const data = await this.rest.get(this.route, {
346
+ query: {
347
+ status: options.status,
348
+ take: options.take,
349
+ skip: options.skip
350
+ }
351
+ });
352
+ return {
353
+ items: data.data.map((d) => this._add(new PaymentIntent(this.client, d))),
354
+ total: data.total,
355
+ take: data.take,
356
+ skip: data.skip
357
+ };
358
+ }
359
+ /** Update a payment intent (status / txHash / reference). */
360
+ async update(id, options) {
361
+ const data = await this.rest.patch(`${this.route}/${id}`, {
362
+ body: options
363
+ });
364
+ return this._add(new PaymentIntent(this.client, data));
365
+ }
366
+ /** Delete a payment intent. */
367
+ async delete(id) {
368
+ const result = await this.rest.delete(`${this.route}/${id}`);
369
+ this.cache.delete(id);
370
+ return result;
371
+ }
372
+ /**
373
+ * Validate a submitted transaction against the intent (tx success +
374
+ * destination + amount + memo). Finalizes status server-side and fires events.
375
+ */
376
+ async validate(id, options) {
377
+ const data = await this.rest.post(
378
+ `${this.route}/${id}/validate`,
379
+ { body: options }
380
+ );
381
+ const paymentIntent = data.paymentIntent ? this._add(new PaymentIntent(this.client, data.paymentIntent)) : null;
382
+ return {
383
+ valid: data.valid,
384
+ status: data.status,
385
+ reason: data.reason ?? null,
386
+ paymentIntent
387
+ };
388
+ }
389
+ };
390
+
391
+ // src/structures/Product.ts
392
+ var Product = class extends Base {
393
+ constructor(client, data) {
394
+ super(client, data);
395
+ }
396
+ _patch(data) {
397
+ super._patch(data);
398
+ this.name = data.name;
399
+ this.description = data.description;
400
+ this.amount = data.amount;
401
+ this.asset = data.asset;
402
+ this.kind = data.kind;
403
+ this.active = data.active;
404
+ this.reference = data.reference;
405
+ this.createdAt = new Date(data.createdAt);
406
+ this.updatedAt = new Date(data.updatedAt);
407
+ return this;
408
+ }
409
+ /** Human-readable asset label (`XLM` for native). */
410
+ get assetLabel() {
411
+ return !this.asset || this.asset === "native" ? "XLM" : this.asset;
412
+ }
413
+ /** Re-fetch this product. */
414
+ fetch() {
415
+ return this.client.products.fetch(this.id);
416
+ }
417
+ /** Update this product. Mutates and returns this. */
418
+ async edit(options) {
419
+ const updated = await this.client.products.update(this.id, options);
420
+ return this._patch(updated.toJSON());
421
+ }
422
+ /** Mark the product active. */
423
+ activate() {
424
+ return this.edit({ active: true });
425
+ }
426
+ /** Mark the product inactive. */
427
+ deactivate() {
428
+ return this.edit({ active: false });
429
+ }
430
+ /** Delete this product. */
431
+ delete() {
432
+ return this.client.products.delete(this.id);
433
+ }
434
+ toJSON() {
435
+ return {
436
+ id: this.id,
437
+ name: this.name,
438
+ description: this.description,
439
+ amount: this.amount,
440
+ asset: this.asset,
441
+ kind: this.kind,
442
+ active: this.active,
443
+ reference: this.reference,
444
+ createdAt: this.createdAt.toISOString(),
445
+ updatedAt: this.updatedAt.toISOString()
446
+ };
447
+ }
448
+ };
449
+
450
+ // src/managers/ProductManager.ts
451
+ var ProductManager = class extends BaseManager {
452
+ constructor() {
453
+ super(...arguments);
454
+ this.route = "/products";
455
+ }
456
+ /** Create a product. */
457
+ async create(options) {
458
+ const data = await this.rest.post(this.route, { body: options });
459
+ return this._add(new Product(this.client, data));
460
+ }
461
+ /** List the consumer's products. */
462
+ async list() {
463
+ const data = await this.rest.get(this.route);
464
+ return data.map((d) => this._add(new Product(this.client, d)));
465
+ }
466
+ /** Get a product by id. */
467
+ async fetch(id) {
468
+ const data = await this.rest.get(`${this.route}/${id}`);
469
+ return this._add(new Product(this.client, data));
470
+ }
471
+ /** Update a product. */
472
+ async update(id, options) {
473
+ const data = await this.rest.patch(`${this.route}/${id}`, {
474
+ body: options
475
+ });
476
+ return this._add(new Product(this.client, data));
477
+ }
478
+ /** Delete a product. */
479
+ async delete(id) {
480
+ const result = await this.rest.delete(
481
+ `${this.route}/${id}`
482
+ );
483
+ this.cache.delete(id);
484
+ return result;
485
+ }
486
+ };
487
+
488
+ // src/structures/WebhookDelivery.ts
489
+ var WebhookDelivery = class extends Base {
490
+ constructor(client, data) {
491
+ super(client, data);
492
+ }
493
+ _patch(data) {
494
+ super._patch(data);
495
+ this.endpointId = data.endpointId;
496
+ this.eventType = data.eventType;
497
+ this.eventId = data.eventId;
498
+ this.payload = data.payload;
499
+ this.status = data.status;
500
+ this.attempts = data.attempts;
501
+ this.responseStatus = data.responseStatus;
502
+ this.error = data.error;
503
+ this.lastAttemptAt = data.lastAttemptAt ? new Date(data.lastAttemptAt) : null;
504
+ this.createdAt = new Date(data.createdAt);
505
+ this.updatedAt = new Date(data.updatedAt);
506
+ return this;
507
+ }
508
+ get isSucceeded() {
509
+ return this.status === WebhookDeliveryStatus.Succeeded;
510
+ }
511
+ /** Manually re-send this delivery. */
512
+ redeliver() {
513
+ return this.client.webhooks.redeliver(this.endpointId, this.id);
514
+ }
515
+ toJSON() {
516
+ return {
517
+ id: this.id,
518
+ endpointId: this.endpointId,
519
+ eventType: this.eventType,
520
+ eventId: this.eventId,
521
+ payload: this.payload,
522
+ status: this.status,
523
+ attempts: this.attempts,
524
+ responseStatus: this.responseStatus,
525
+ error: this.error,
526
+ lastAttemptAt: this.lastAttemptAt ? this.lastAttemptAt.toISOString() : null,
527
+ createdAt: this.createdAt.toISOString(),
528
+ updatedAt: this.updatedAt.toISOString()
529
+ };
530
+ }
531
+ };
532
+
533
+ // src/structures/WebhookEndpoint.ts
534
+ var WebhookEndpoint = class extends Base {
535
+ constructor(client, data) {
536
+ super(client, data);
537
+ this.secret = "secret" in data ? data.secret : null;
538
+ }
539
+ _patch(data) {
540
+ super._patch(data);
541
+ this.url = data.url;
542
+ this.description = data.description;
543
+ this.enabled = data.enabled;
544
+ this.eventTypes = data.eventTypes;
545
+ this.createdAt = new Date(data.createdAt);
546
+ this.updatedAt = new Date(data.updatedAt);
547
+ return this;
548
+ }
549
+ /** Whether the endpoint receives all events (empty subscription). */
550
+ get receivesAllEvents() {
551
+ return this.eventTypes.length === 0;
552
+ }
553
+ /** Re-fetch this endpoint. */
554
+ fetch() {
555
+ return this.client.webhooks.fetch(this.id);
556
+ }
557
+ /** Update url/description/enabled/eventTypes. Mutates and returns this. */
558
+ async edit(options) {
559
+ const updated = await this.client.webhooks.update(this.id, options);
560
+ return this._patch(updated.toJSON());
561
+ }
562
+ /** Pause deliveries to this endpoint. */
563
+ disable() {
564
+ return this.edit({ enabled: false });
565
+ }
566
+ /** Resume deliveries to this endpoint. */
567
+ enable() {
568
+ return this.edit({ enabled: true });
569
+ }
570
+ /** Rotate the signing secret (returns a new instance carrying the secret). */
571
+ rotateSecret() {
572
+ return this.client.webhooks.rotateSecret(this.id);
573
+ }
574
+ /** Send a test event to verify the endpoint. */
575
+ ping() {
576
+ return this.client.webhooks.ping(this.id);
577
+ }
578
+ /** List delivery attempts for this endpoint. */
579
+ fetchDeliveries(options) {
580
+ return this.client.webhooks.fetchDeliveries(this.id, options);
581
+ }
582
+ /** Delete this endpoint. */
583
+ delete() {
584
+ return this.client.webhooks.delete(this.id);
585
+ }
586
+ toJSON() {
587
+ return {
588
+ id: this.id,
589
+ url: this.url,
590
+ description: this.description,
591
+ enabled: this.enabled,
592
+ eventTypes: this.eventTypes,
593
+ createdAt: this.createdAt.toISOString(),
594
+ updatedAt: this.updatedAt.toISOString()
595
+ };
596
+ }
597
+ };
598
+
599
+ // src/util/Constants.ts
600
+ var version = "1.0.0";
601
+ var DEFAULT_BASE_URL = "https://api.cosmospay.io";
602
+ var DEFAULT_VERSION = "v1";
603
+ var DEFAULT_TIMEOUT = 3e4;
604
+ var DEFAULT_RETRIES = 2;
605
+ var SIGNATURE_HEADER = "x-cosmos-signature";
606
+ var Events = {
607
+ Debug: "debug",
608
+ Request: "request",
609
+ Response: "response",
610
+ RateLimited: "rateLimited"
611
+ };
612
+
613
+ // src/util/Webhooks.ts
614
+ var WebhookSignatureError = class extends Error {
615
+ constructor(message) {
616
+ super(message);
617
+ this.name = "WebhookSignatureError";
618
+ }
619
+ };
620
+ var Webhooks = {
621
+ /** Header name the dispatcher uses for the signature. */
622
+ SIGNATURE_HEADER,
623
+ /**
624
+ * Verify a webhook signature. Returns `true` on success, throws
625
+ * {@link WebhookSignatureError} on any failure (so it never silently passes).
626
+ */
627
+ verify(rawBody, signatureHeader, secret, options = {}) {
628
+ if (!signatureHeader) {
629
+ throw new WebhookSignatureError("Missing signature header.");
630
+ }
631
+ if (!secret) {
632
+ throw new WebhookSignatureError("Missing signing secret.");
633
+ }
634
+ const { timestamp, signature } = parseSignatureHeader(signatureHeader);
635
+ const payload = typeof rawBody === "string" ? rawBody : decode(rawBody);
636
+ const expected = crypto.createHmac("sha256", secret).update(`${timestamp}.${payload}`).digest("hex");
637
+ if (!safeEqualHex(expected, signature)) {
638
+ throw new WebhookSignatureError("Signature mismatch.");
639
+ }
640
+ const tolerance = options.toleranceSeconds ?? 300;
641
+ if (tolerance > 0) {
642
+ const now = options.now ?? Math.floor(Date.now() / 1e3);
643
+ if (Math.abs(now - timestamp) > tolerance) {
644
+ throw new WebhookSignatureError(
645
+ `Timestamp outside tolerance (${tolerance}s).`
646
+ );
647
+ }
648
+ }
649
+ return true;
650
+ },
651
+ /**
652
+ * Verify the signature and return the parsed {@link WebhookEvent}. Throws
653
+ * {@link WebhookSignatureError} if verification fails.
654
+ */
655
+ constructEvent(rawBody, signatureHeader, secret, options = {}) {
656
+ this.verify(rawBody, signatureHeader, secret, options);
657
+ const payload = typeof rawBody === "string" ? rawBody : decode(rawBody);
658
+ try {
659
+ return JSON.parse(payload);
660
+ } catch {
661
+ throw new WebhookSignatureError("Body is not valid JSON.");
662
+ }
663
+ }
664
+ };
665
+ function parseSignatureHeader(header) {
666
+ let timestamp;
667
+ let signature;
668
+ for (const part of header.split(",")) {
669
+ const [key, value] = part.split("=");
670
+ if (!key || value === void 0) continue;
671
+ const k = key.trim();
672
+ if (k === "t") timestamp = Number(value.trim());
673
+ else if (k === "v1") signature = value.trim();
674
+ }
675
+ if (timestamp === void 0 || Number.isNaN(timestamp) || !signature) {
676
+ throw new WebhookSignatureError("Malformed signature header.");
677
+ }
678
+ return { timestamp, signature };
679
+ }
680
+ function safeEqualHex(a, b) {
681
+ if (a.length !== b.length) return false;
682
+ try {
683
+ return crypto.timingSafeEqual(Buffer.from(a, "hex"), Buffer.from(b, "hex"));
684
+ } catch {
685
+ return false;
686
+ }
687
+ }
688
+ function decode(bytes) {
689
+ return Buffer.from(bytes).toString("utf8");
690
+ }
691
+
692
+ // src/managers/WebhookManager.ts
693
+ var WebhookManager = class extends BaseManager {
694
+ constructor() {
695
+ super(...arguments);
696
+ this.route = "/webhooks";
697
+ }
698
+ // ── Endpoint CRUD ───────────────────────────────────────────────────────────
699
+ /** Register a webhook endpoint (the returned instance carries the secret once). */
700
+ async create(options) {
701
+ const data = await this.rest.post(this.route, {
702
+ body: options
703
+ });
704
+ return this._add(new WebhookEndpoint(this.client, data));
705
+ }
706
+ /** List the consumer's webhook endpoints. */
707
+ async list() {
708
+ const data = await this.rest.get(this.route);
709
+ return data.map((d) => this._add(new WebhookEndpoint(this.client, d)));
710
+ }
711
+ /** Get a webhook endpoint by id. */
712
+ async fetch(id) {
713
+ const data = await this.rest.get(`${this.route}/${id}`);
714
+ return this._add(new WebhookEndpoint(this.client, data));
715
+ }
716
+ /** Update a webhook endpoint (url/description/enabled/eventTypes). */
717
+ async update(id, options) {
718
+ const data = await this.rest.patch(
719
+ `${this.route}/${id}`,
720
+ { body: options }
721
+ );
722
+ return this._add(new WebhookEndpoint(this.client, data));
723
+ }
724
+ /** Delete a webhook endpoint. */
725
+ async delete(id) {
726
+ const result = await this.rest.delete(
727
+ `${this.route}/${id}`
728
+ );
729
+ this.cache.delete(id);
730
+ return result;
731
+ }
732
+ /** Rotate the signing secret (returns a new instance carrying the secret). */
733
+ async rotateSecret(id) {
734
+ const data = await this.rest.post(
735
+ `${this.route}/${id}/rotate-secret`
736
+ );
737
+ return this._add(new WebhookEndpoint(this.client, data));
738
+ }
739
+ /** Send a test event to verify the endpoint. */
740
+ ping(id) {
741
+ return this.rest.post(`${this.route}/${id}/ping`);
742
+ }
743
+ /** List delivery attempts for an endpoint (audit trail). */
744
+ async fetchDeliveries(id, options = {}) {
745
+ const data = await this.rest.get(
746
+ `${this.route}/${id}/deliveries`,
747
+ {
748
+ query: {
749
+ status: options.status,
750
+ take: options.take,
751
+ skip: options.skip
752
+ }
753
+ }
754
+ );
755
+ return {
756
+ items: data.data.map((d) => new WebhookDelivery(this.client, d)),
757
+ total: data.total,
758
+ take: data.take,
759
+ skip: data.skip
760
+ };
761
+ }
762
+ /** Manually re-send a past delivery. */
763
+ async redeliver(id, deliveryId) {
764
+ const data = await this.rest.post(
765
+ `${this.route}/${id}/deliveries/${deliveryId}/redeliver`
766
+ );
767
+ return new WebhookDelivery(this.client, data);
768
+ }
769
+ // ── Incoming event listener ──────────────────────────────────────────────────
770
+ /**
771
+ * Verify a raw incoming webhook request and dispatch it to the listeners
772
+ * registered via {@link WebhookManager.on}. Returns the parsed event.
773
+ *
774
+ * Emits, in order: the raw type (`PAYMENT_INTENT_SUCCEEDED`), the camelCase
775
+ * alias (`paymentIntentSucceeded`) and the catch-all `event`.
776
+ *
777
+ * @throws {WebhookSignatureError} when the signature is missing/invalid.
778
+ */
779
+ process(rawBody, signatureHeader, options = {}) {
780
+ const secret = options.secret ?? this.client.webhookSecret;
781
+ if (!secret) {
782
+ throw new WebhookSignatureError(
783
+ "No webhook secret configured. Pass `{ secret }` or set `webhookSecret` on the client."
784
+ );
785
+ }
786
+ const event = Webhooks.constructEvent(
787
+ rawBody,
788
+ signatureHeader,
789
+ secret,
790
+ { toleranceSeconds: options.toleranceSeconds }
791
+ );
792
+ this.emit(event.type, event);
793
+ this.emit(toCamelEvent(event.type), event);
794
+ this.emit("event", event);
795
+ return event;
796
+ }
797
+ /**
798
+ * Build a Node.js `http`/`https` request handler that verifies the signature,
799
+ * dispatches the event to your listeners, and replies `200`/`400`.
800
+ *
801
+ * @example
802
+ * import { createServer } from 'node:http';
803
+ * createServer(client.webhooks.createHandler({ secret })).listen(4242);
804
+ */
805
+ createHandler(options = {}) {
806
+ return (req, res) => {
807
+ void this.collectBody(req).then((raw) => {
808
+ const sig = headerValue(req.headers[SIGNATURE_HEADER]);
809
+ this.process(raw, sig, options);
810
+ res.statusCode = 200;
811
+ res.end("ok");
812
+ }).catch((err) => {
813
+ res.statusCode = err instanceof WebhookSignatureError ? 400 : 500;
814
+ res.end(
815
+ err instanceof WebhookSignatureError ? "invalid signature" : "error"
816
+ );
817
+ });
818
+ };
819
+ }
820
+ /**
821
+ * Express-style middleware. Expects the **raw** body (e.g. mounted with
822
+ * `express.raw({ type: '*​/*' })`). On success it attaches the parsed event to
823
+ * `req.cosmosEvent` and calls `next()`; on a bad signature it replies `400`.
824
+ *
825
+ * @example
826
+ * app.post('/hooks', express.raw({ type: '*​/*' }), client.webhooks.middleware({ secret }));
827
+ */
828
+ middleware(options = {}) {
829
+ return (req, res, next) => {
830
+ try {
831
+ const raw = extractRawBody(req);
832
+ const sig = headerValue(req.headers[SIGNATURE_HEADER]);
833
+ const event = this.process(raw, sig, options);
834
+ req.cosmosEvent = event;
835
+ next();
836
+ } catch (err) {
837
+ if (err instanceof WebhookSignatureError) {
838
+ res.status(400).send("invalid signature");
839
+ return;
840
+ }
841
+ next(err);
842
+ }
843
+ };
844
+ }
845
+ /** Read a Node.js request stream into a single Buffer. */
846
+ collectBody(req) {
847
+ return new Promise((resolve, reject) => {
848
+ const chunks = [];
849
+ req.on("data", (chunk) => chunks.push(chunk));
850
+ req.on("end", () => resolve(Buffer.concat(chunks)));
851
+ req.on("error", reject);
852
+ });
853
+ }
854
+ };
855
+ function toCamelEvent(type) {
856
+ return type.toLowerCase().replace(
857
+ /_([a-z])/g,
858
+ (_, c) => c.toUpperCase()
859
+ );
860
+ }
861
+ function headerValue(value) {
862
+ return Array.isArray(value) ? value[0] : value;
863
+ }
864
+ function extractRawBody(req) {
865
+ const candidate = req.rawBody ?? req.body;
866
+ if (typeof candidate === "string" || candidate instanceof Uint8Array) {
867
+ return candidate;
868
+ }
869
+ if (candidate && typeof candidate === "object") {
870
+ return JSON.stringify(candidate);
871
+ }
872
+ return "";
873
+ }
874
+
875
+ // src/errors/CosmosPayError.ts
876
+ var CosmosPayAPIError = class _CosmosPayAPIError extends Error {
877
+ constructor(options) {
878
+ const message = _CosmosPayAPIError.resolveMessage(options.status, options.body);
879
+ super(message);
880
+ this.name = "CosmosPayAPIError";
881
+ this.status = options.status;
882
+ this.method = options.method;
883
+ this.url = options.url;
884
+ this.body = options.body;
885
+ this.code = _CosmosPayAPIError.resolveCode(options.body);
886
+ Error.captureStackTrace?.(this, _CosmosPayAPIError);
887
+ }
888
+ static resolveMessage(status, body) {
889
+ if (body && typeof body === "object") {
890
+ const maybe = body;
891
+ const msg = maybe.message ?? maybe.error;
892
+ if (Array.isArray(msg)) return `[${status}] ${msg.join(", ")}`;
893
+ if (typeof msg === "string") return `[${status}] ${msg}`;
894
+ }
895
+ if (typeof body === "string" && body.length) return `[${status}] ${body}`;
896
+ return `[${status}] Request failed`;
897
+ }
898
+ static resolveCode(body) {
899
+ if (body && typeof body === "object") {
900
+ const maybe = body;
901
+ if (typeof maybe.code === "string") return maybe.code;
902
+ if (typeof maybe.error === "string") return maybe.error;
903
+ }
904
+ return void 0;
905
+ }
906
+ };
907
+ var CosmosPayRequestError = class _CosmosPayRequestError extends Error {
908
+ constructor(options) {
909
+ const reason = options.cause instanceof Error ? options.cause.message : String(options.cause);
910
+ super(`Request to ${options.method} ${options.url} failed: ${reason}`);
911
+ this.name = "CosmosPayRequestError";
912
+ this.method = options.method;
913
+ this.url = options.url;
914
+ this.cause = options.cause;
915
+ Error.captureStackTrace?.(this, _CosmosPayRequestError);
916
+ }
917
+ };
918
+
919
+ // src/rest/REST.ts
920
+ var RETRYABLE_STATUS = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
921
+ var REST = class extends events.EventEmitter {
922
+ constructor(options) {
923
+ super();
924
+ if (!options.baseURL) {
925
+ throw new TypeError("REST requires a `baseURL`.");
926
+ }
927
+ this.baseURL = options.baseURL.replace(/\/+$/, "");
928
+ this.version = options.version ?? DEFAULT_VERSION;
929
+ this.timeout = options.timeout ?? DEFAULT_TIMEOUT;
930
+ this.retries = options.retries ?? DEFAULT_RETRIES;
931
+ this.extraHeaders = options.headers ?? {};
932
+ this.apiKey = options.apiKey;
933
+ this.gatewaySecret = options.gatewaySecret;
934
+ this.consumerUsername = options.consumerUsername;
935
+ const fetchFn = options.fetch ?? globalThis.fetch;
936
+ if (typeof fetchFn !== "function") {
937
+ throw new TypeError(
938
+ "No global `fetch` found. Use Node.js >= 18 or pass a `fetch` implementation in the client options."
939
+ );
940
+ }
941
+ this.fetchFn = fetchFn.bind(globalThis);
942
+ }
943
+ /** Replace the API key used for subsequent requests. */
944
+ setApiKey(apiKey) {
945
+ this.apiKey = apiKey;
946
+ return this;
947
+ }
948
+ /** Set direct-access gateway credentials (local/dev usage). */
949
+ setGatewayCredentials(secret, consumerUsername) {
950
+ this.gatewaySecret = secret;
951
+ this.consumerUsername = consumerUsername;
952
+ return this;
953
+ }
954
+ get(path, options = {}) {
955
+ return this.request("GET", path, options);
956
+ }
957
+ post(path, options = {}) {
958
+ return this.request("POST", path, options);
959
+ }
960
+ patch(path, options = {}) {
961
+ return this.request("PATCH", path, options);
962
+ }
963
+ delete(path, options = {}) {
964
+ return this.request("DELETE", path, options);
965
+ }
966
+ /** Build the absolute URL for a route, applying the version prefix + query. */
967
+ buildURL(path, query) {
968
+ const clean = path.startsWith("/") ? path : `/${path}`;
969
+ const prefix = this.version ? `/${this.version}` : "";
970
+ const url = new URL(`${this.baseURL}${prefix}${clean}`);
971
+ if (query) {
972
+ for (const [key, value] of Object.entries(query)) {
973
+ if (value === void 0 || value === null) continue;
974
+ url.searchParams.set(key, String(value));
975
+ }
976
+ }
977
+ return url.toString();
978
+ }
979
+ buildHeaders(extra) {
980
+ const headers = {
981
+ Accept: "application/json",
982
+ "User-Agent": `@cosmosapp/pay_sdk/${version}`,
983
+ ...this.extraHeaders
984
+ };
985
+ if (this.apiKey) {
986
+ headers["Authorization"] = `Bearer ${this.apiKey}`;
987
+ headers["apikey"] = this.apiKey;
988
+ }
989
+ if (this.gatewaySecret) headers["X-Gateway-Secret"] = this.gatewaySecret;
990
+ if (this.consumerUsername) {
991
+ headers["X-Consumer-Username"] = this.consumerUsername;
992
+ }
993
+ return { ...headers, ...extra };
994
+ }
995
+ /** Core request with retry, timeout and structured error handling. */
996
+ async request(method, path, options = {}) {
997
+ const url = this.buildURL(path, options.query);
998
+ const headers = this.buildHeaders(options.headers);
999
+ let serializedBody;
1000
+ if (options.body !== void 0) {
1001
+ serializedBody = JSON.stringify(options.body);
1002
+ headers["Content-Type"] = "application/json";
1003
+ }
1004
+ let attempt = 0;
1005
+ let lastError;
1006
+ while (attempt <= this.retries) {
1007
+ const controller = new AbortController();
1008
+ const timer = setTimeout(() => controller.abort(), this.timeout);
1009
+ const signal = options.signal ? anySignal([options.signal, controller.signal]) : controller.signal;
1010
+ this.emit(Events.Request, { method, url, attempt });
1011
+ try {
1012
+ const response = await this.fetchFn(url, {
1013
+ method,
1014
+ headers,
1015
+ body: serializedBody,
1016
+ signal
1017
+ });
1018
+ clearTimeout(timer);
1019
+ this.emit(Events.Response, {
1020
+ method,
1021
+ url,
1022
+ status: response.status,
1023
+ attempt
1024
+ });
1025
+ if (response.status === 429) {
1026
+ this.emit(Events.RateLimited, { method, url, attempt });
1027
+ }
1028
+ if (!response.ok) {
1029
+ const body = await safeParse(response);
1030
+ if (RETRYABLE_STATUS.has(response.status) && attempt < this.retries) {
1031
+ await this.backoff(response, attempt);
1032
+ attempt++;
1033
+ continue;
1034
+ }
1035
+ throw new CosmosPayAPIError({ status: response.status, method, url, body });
1036
+ }
1037
+ return await safeParse(response);
1038
+ } catch (error) {
1039
+ clearTimeout(timer);
1040
+ if (error instanceof CosmosPayAPIError) throw error;
1041
+ lastError = error;
1042
+ if (attempt < this.retries) {
1043
+ await sleep(backoffDelay(attempt));
1044
+ attempt++;
1045
+ continue;
1046
+ }
1047
+ throw new CosmosPayRequestError({ method, url, cause: error });
1048
+ }
1049
+ }
1050
+ throw new CosmosPayRequestError({ method, url, cause: lastError });
1051
+ }
1052
+ async backoff(response, attempt) {
1053
+ const retryAfter = response.headers.get("retry-after");
1054
+ const ms = retryAfter ? Number(retryAfter) * 1e3 : backoffDelay(attempt);
1055
+ await sleep(Number.isFinite(ms) ? ms : backoffDelay(attempt));
1056
+ }
1057
+ };
1058
+ function backoffDelay(attempt) {
1059
+ return Math.min(1e3 * 2 ** attempt, 8e3);
1060
+ }
1061
+ function sleep(ms) {
1062
+ return new Promise((resolve) => setTimeout(resolve, ms));
1063
+ }
1064
+ async function safeParse(response) {
1065
+ const text = await response.text();
1066
+ if (!text) return null;
1067
+ const contentType = response.headers.get("content-type") ?? "";
1068
+ if (contentType.includes("application/json")) {
1069
+ try {
1070
+ return JSON.parse(text);
1071
+ } catch {
1072
+ return text;
1073
+ }
1074
+ }
1075
+ return text;
1076
+ }
1077
+ function anySignal(signals) {
1078
+ const controller = new AbortController();
1079
+ const onAbort = (signal) => () => controller.abort(signal.reason);
1080
+ for (const signal of signals) {
1081
+ if (signal.aborted) {
1082
+ controller.abort(signal.reason);
1083
+ break;
1084
+ }
1085
+ signal.addEventListener("abort", onAbort(signal), { once: true });
1086
+ }
1087
+ return controller.signal;
1088
+ }
1089
+
1090
+ // src/util/shared.ts
1091
+ var shared = {
1092
+ baseURL: DEFAULT_BASE_URL,
1093
+ version: DEFAULT_VERSION
1094
+ };
1095
+ function resolveShared(overrides = {}) {
1096
+ const defined = {};
1097
+ for (const key of Object.keys(overrides)) {
1098
+ const value = overrides[key];
1099
+ if (value !== void 0) {
1100
+ Object.assign(defined, { [key]: value });
1101
+ }
1102
+ }
1103
+ return { ...shared, ...defined };
1104
+ }
1105
+
1106
+ // src/client/Client.ts
1107
+ var Client = class extends events.EventEmitter {
1108
+ static {
1109
+ /** Library version. */
1110
+ this.version = version;
1111
+ }
1112
+ static {
1113
+ /**
1114
+ * Process-wide shared defaults maintained by Cosmos Pay (gateway URL, version,
1115
+ * internal secrets). Mutate once at startup to change them for every client:
1116
+ * `Client.shared.baseURL = 'https://staging.cosmospay.io'`.
1117
+ */
1118
+ this.shared = shared;
1119
+ }
1120
+ constructor(options) {
1121
+ super();
1122
+ if (!options || !options.apiKey) {
1123
+ throw new TypeError("Client requires an `apiKey` option.");
1124
+ }
1125
+ this.shared = resolveShared({
1126
+ baseURL: options.baseURL,
1127
+ version: options.version,
1128
+ gatewaySecret: options.gatewaySecret,
1129
+ consumerUsername: options.consumerUsername,
1130
+ webhookSecret: options.webhookSecret
1131
+ });
1132
+ this.webhookSecret = this.shared.webhookSecret;
1133
+ this.rest = new REST({
1134
+ baseURL: this.shared.baseURL,
1135
+ apiKey: options.apiKey,
1136
+ gatewaySecret: this.shared.gatewaySecret,
1137
+ consumerUsername: this.shared.consumerUsername,
1138
+ version: this.shared.version,
1139
+ timeout: options.timeout,
1140
+ retries: options.retries,
1141
+ headers: options.headers,
1142
+ fetch: options.fetch
1143
+ });
1144
+ this.rest.on("request", (p) => this.emit("request", p));
1145
+ this.rest.on("response", (p) => this.emit("response", p));
1146
+ this.rest.on("rateLimited", (p) => this.emit("rateLimited", p));
1147
+ this.paymentIntents = new PaymentIntentManager(this);
1148
+ this.webhooks = new WebhookManager(this);
1149
+ this.products = new ProductManager(this);
1150
+ this.customers = new CustomerManager(this);
1151
+ this.analytics = new AnalyticsManager(this);
1152
+ this.health = new HealthManager(this);
1153
+ }
1154
+ /** Update the API key used for subsequent requests. */
1155
+ setApiKey(apiKey) {
1156
+ this.rest.setApiKey(apiKey);
1157
+ return this;
1158
+ }
1159
+ /** Set the default webhook signing secret for the webhook listener. */
1160
+ setWebhookSecret(secret) {
1161
+ this.webhookSecret = secret;
1162
+ return this;
1163
+ }
1164
+ /** Set direct-access gateway credentials (internal / local dev usage). */
1165
+ setGatewayCredentials(secret, consumerUsername) {
1166
+ this.rest.setGatewayCredentials(secret, consumerUsername);
1167
+ return this;
1168
+ }
1169
+ };
1170
+
1171
+ exports.AnalyticsManager = AnalyticsManager;
1172
+ exports.Base = Base;
1173
+ exports.BaseManager = BaseManager;
1174
+ exports.Client = Client;
1175
+ exports.CosmosPayAPIError = CosmosPayAPIError;
1176
+ exports.CosmosPayRequestError = CosmosPayRequestError;
1177
+ exports.Customer = Customer;
1178
+ exports.CustomerManager = CustomerManager;
1179
+ exports.DEFAULT_BASE_URL = DEFAULT_BASE_URL;
1180
+ exports.DEFAULT_RETRIES = DEFAULT_RETRIES;
1181
+ exports.DEFAULT_TIMEOUT = DEFAULT_TIMEOUT;
1182
+ exports.DEFAULT_VERSION = DEFAULT_VERSION;
1183
+ exports.Events = Events;
1184
+ exports.HealthManager = HealthManager;
1185
+ exports.PaymentIntent = PaymentIntent;
1186
+ exports.PaymentIntentKind = PaymentIntentKind;
1187
+ exports.PaymentIntentManager = PaymentIntentManager;
1188
+ exports.PaymentIntentStatus = PaymentIntentStatus;
1189
+ exports.Product = Product;
1190
+ exports.ProductKind = ProductKind;
1191
+ exports.ProductManager = ProductManager;
1192
+ exports.REST = REST;
1193
+ exports.SIGNATURE_HEADER = SIGNATURE_HEADER;
1194
+ exports.WebhookDelivery = WebhookDelivery;
1195
+ exports.WebhookDeliveryStatus = WebhookDeliveryStatus;
1196
+ exports.WebhookEndpoint = WebhookEndpoint;
1197
+ exports.WebhookEventType = WebhookEventType;
1198
+ exports.WebhookManager = WebhookManager;
1199
+ exports.WebhookSignatureError = WebhookSignatureError;
1200
+ exports.Webhooks = Webhooks;
1201
+ exports.resolveShared = resolveShared;
1202
+ exports.shared = shared;
1203
+ exports.version = version;
1204
+ //# sourceMappingURL=index.cjs.map
1205
+ //# sourceMappingURL=index.cjs.map