@solvapay/server 2.4.1 → 2.5.0-preview-4dcf60c628500a6210ba69edbf7ae56ee47fbb3a

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.
@@ -208,6 +208,32 @@ async function getAuthenticatedUserCore(request, options = {}) {
208
208
 
209
209
  // src/client.ts
210
210
  var import_core2 = require("@solvapay/core");
211
+ var API_ERROR_BODY_MAX = 240;
212
+ function apiDebugLog(...args) {
213
+ if (process.env.SOLVAPAY_DEBUG === "true") {
214
+ console.log(...args);
215
+ }
216
+ }
217
+ function isNonJsonResponseBody(body, contentType) {
218
+ const ct = contentType?.split(";")[0]?.trim().toLowerCase() ?? "";
219
+ if (ct.includes("json")) return false;
220
+ const trimmed = body.trimStart();
221
+ if (trimmed.startsWith("<")) return true;
222
+ if (ct && !ct.includes("json")) return true;
223
+ return false;
224
+ }
225
+ async function throwApiError(operation, res) {
226
+ const body = await res.text();
227
+ const contentType = res.headers.get("content-type");
228
+ const nonJson = isNonJsonResponseBody(body, contentType);
229
+ const snippet = body.length > API_ERROR_BODY_MAX ? `${body.slice(0, API_ERROR_BODY_MAX)}\u2026` : body;
230
+ const detail = nonJson ? `non-JSON response (${contentType ?? "unknown content-type"}) \u2014 the API may not have been reached. Body: ${snippet}` : snippet;
231
+ apiDebugLog(`\u274C API Error: ${res.status} - ${detail}`);
232
+ throw new import_core2.SolvaPayError(`${operation} failed (${res.status}): ${detail}`, {
233
+ status: res.status,
234
+ code: nonJson ? "non_json_response" : void 0
235
+ });
236
+ }
211
237
  function createSolvaPayClient(opts) {
212
238
  const base = opts.apiBaseUrl ?? "https://api.solvapay.com";
213
239
  if (!opts.apiKey) throw new import_core2.SolvaPayError("Missing apiKey");
@@ -215,12 +241,6 @@ function createSolvaPayClient(opts) {
215
241
  "Content-Type": "application/json",
216
242
  Authorization: `Bearer ${opts.apiKey}`
217
243
  };
218
- const debug = process.env.SOLVAPAY_DEBUG === "true";
219
- const log = (...args) => {
220
- if (debug) {
221
- console.log(...args);
222
- }
223
- };
224
244
  return {
225
245
  // POST: /v1/sdk/limits
226
246
  async checkLimits(params) {
@@ -231,11 +251,7 @@ function createSolvaPayClient(opts) {
231
251
  body: JSON.stringify(params)
232
252
  });
233
253
  if (!res.ok) {
234
- const error = await res.text();
235
- log(`\u274C API Error: ${res.status} - ${error}`);
236
- throw new import_core2.SolvaPayError(`Check limits failed (${res.status}): ${error}`, {
237
- status: res.status
238
- });
254
+ await throwApiError("Check limits", res);
239
255
  }
240
256
  const result = await res.json();
241
257
  return result;
@@ -249,11 +265,7 @@ function createSolvaPayClient(opts) {
249
265
  body: JSON.stringify(params)
250
266
  });
251
267
  if (!res.ok) {
252
- const error = await res.text();
253
- log(`\u274C API Error: ${res.status} - ${error}`);
254
- throw new import_core2.SolvaPayError(`Track usage failed (${res.status}): ${error}`, {
255
- status: res.status
256
- });
268
+ await throwApiError("Track usage", res);
257
269
  }
258
270
  return await res.json();
259
271
  },
@@ -266,11 +278,7 @@ function createSolvaPayClient(opts) {
266
278
  body: JSON.stringify(params)
267
279
  });
268
280
  if (!res.ok) {
269
- const error = await res.text();
270
- log(`\u274C API Error: ${res.status} - ${error}`);
271
- throw new import_core2.SolvaPayError(`Track usage bulk failed (${res.status}): ${error}`, {
272
- status: res.status
273
- });
281
+ await throwApiError("Track usage bulk", res);
274
282
  }
275
283
  return await res.json();
276
284
  },
@@ -283,11 +291,7 @@ function createSolvaPayClient(opts) {
283
291
  body: JSON.stringify(params)
284
292
  });
285
293
  if (!res.ok) {
286
- const error = await res.text();
287
- log(`\u274C API Error: ${res.status} - ${error}`);
288
- throw new import_core2.SolvaPayError(`Create customer failed (${res.status}): ${error}`, {
289
- status: res.status
290
- });
294
+ await throwApiError("Create customer", res);
291
295
  }
292
296
  const result = await res.json();
293
297
  return {
@@ -303,11 +307,7 @@ function createSolvaPayClient(opts) {
303
307
  body: JSON.stringify(params)
304
308
  });
305
309
  if (!res.ok) {
306
- const error = await res.text();
307
- log(`\u274C API Error: ${res.status} - ${error}`);
308
- throw new import_core2.SolvaPayError(`Update customer failed (${res.status}): ${error}`, {
309
- status: res.status
310
- });
310
+ await throwApiError("Update customer", res);
311
311
  }
312
312
  const result = await res.json();
313
313
  return {
@@ -335,11 +335,7 @@ function createSolvaPayClient(opts) {
335
335
  headers
336
336
  });
337
337
  if (!res.ok) {
338
- const error = await res.text();
339
- log(`\u274C API Error: ${res.status} - ${error}`);
340
- throw new import_core2.SolvaPayError(`Get customer failed (${res.status}): ${error}`, {
341
- status: res.status
342
- });
338
+ await throwApiError("Get customer", res);
343
339
  }
344
340
  const result = await res.json();
345
341
  let customer = result;
@@ -373,11 +369,7 @@ function createSolvaPayClient(opts) {
373
369
  body: JSON.stringify(body)
374
370
  });
375
371
  if (!res.ok) {
376
- const error = await res.text();
377
- log(`\u274C API Error: ${res.status} - ${error}`);
378
- throw new import_core2.SolvaPayError(`Assign credits failed (${res.status}): ${error}`, {
379
- status: res.status
380
- });
372
+ await throwApiError("Assign credits", res);
381
373
  }
382
374
  return await res.json();
383
375
  },
@@ -389,11 +381,7 @@ function createSolvaPayClient(opts) {
389
381
  headers
390
382
  });
391
383
  if (!res.ok) {
392
- const error = await res.text();
393
- log(`\u274C API Error: ${res.status} - ${error}`);
394
- throw new import_core2.SolvaPayError(`Get merchant failed (${res.status}): ${error}`, {
395
- status: res.status
396
- });
384
+ await throwApiError("Get merchant", res);
397
385
  }
398
386
  return res.json();
399
387
  },
@@ -405,11 +393,7 @@ function createSolvaPayClient(opts) {
405
393
  headers
406
394
  });
407
395
  if (!res.ok) {
408
- const error = await res.text();
409
- log(`\u274C API Error: ${res.status} - ${error}`);
410
- throw new import_core2.SolvaPayError(`Get platform config failed (${res.status}): ${error}`, {
411
- status: res.status
412
- });
396
+ await throwApiError("Get platform config", res);
413
397
  }
414
398
  return res.json();
415
399
  },
@@ -421,11 +405,7 @@ function createSolvaPayClient(opts) {
421
405
  headers
422
406
  });
423
407
  if (!res.ok) {
424
- const error = await res.text();
425
- log(`\u274C API Error: ${res.status} - ${error}`);
426
- throw new import_core2.SolvaPayError(`Get product failed (${res.status}): ${error}`, {
427
- status: res.status
428
- });
408
+ await throwApiError("Get product", res);
429
409
  }
430
410
  const result = await res.json();
431
411
  const data = result.data || {};
@@ -440,11 +420,7 @@ function createSolvaPayClient(opts) {
440
420
  headers
441
421
  });
442
422
  if (!res.ok) {
443
- const error = await res.text();
444
- log(`\u274C API Error: ${res.status} - ${error}`);
445
- throw new import_core2.SolvaPayError(`List products failed (${res.status}): ${error}`, {
446
- status: res.status
447
- });
423
+ await throwApiError("List products", res);
448
424
  }
449
425
  const result = await res.json();
450
426
  const products = Array.isArray(result) ? result : result.products || [];
@@ -462,11 +438,7 @@ function createSolvaPayClient(opts) {
462
438
  body: JSON.stringify(params)
463
439
  });
464
440
  if (!res.ok) {
465
- const error = await res.text();
466
- log(`\u274C API Error: ${res.status} - ${error}`);
467
- throw new import_core2.SolvaPayError(`Create product failed (${res.status}): ${error}`, {
468
- status: res.status
469
- });
441
+ await throwApiError("Create product", res);
470
442
  }
471
443
  const result = await res.json();
472
444
  return result;
@@ -480,11 +452,7 @@ function createSolvaPayClient(opts) {
480
452
  body: JSON.stringify(params)
481
453
  });
482
454
  if (!res.ok) {
483
- const error = await res.text();
484
- log(`\u274C API Error: ${res.status} - ${error}`);
485
- throw new import_core2.SolvaPayError(`Bootstrap MCP product failed (${res.status}): ${error}`, {
486
- status: res.status
487
- });
455
+ await throwApiError("Bootstrap MCP product", res);
488
456
  }
489
457
  return await res.json();
490
458
  },
@@ -497,11 +465,7 @@ function createSolvaPayClient(opts) {
497
465
  body: JSON.stringify(params)
498
466
  });
499
467
  if (!res.ok) {
500
- const error = await res.text();
501
- log(`\u274C API Error: ${res.status} - ${error}`);
502
- throw new import_core2.SolvaPayError(`Configure MCP plans failed (${res.status}): ${error}`, {
503
- status: res.status
504
- });
468
+ await throwApiError("Configure MCP plans", res);
505
469
  }
506
470
  return await res.json();
507
471
  },
@@ -513,11 +477,7 @@ function createSolvaPayClient(opts) {
513
477
  headers
514
478
  });
515
479
  if (!res.ok && res.status !== 404) {
516
- const error = await res.text();
517
- log(`\u274C API Error: ${res.status} - ${error}`);
518
- throw new import_core2.SolvaPayError(`Delete product failed (${res.status}): ${error}`, {
519
- status: res.status
520
- });
480
+ await throwApiError("Delete product", res);
521
481
  }
522
482
  },
523
483
  // POST: /v1/sdk/products/{productRef}/clone
@@ -529,11 +489,7 @@ function createSolvaPayClient(opts) {
529
489
  body: JSON.stringify(overrides || {})
530
490
  });
531
491
  if (!res.ok) {
532
- const error = await res.text();
533
- log(`\u274C API Error: ${res.status} - ${error}`);
534
- throw new import_core2.SolvaPayError(`Clone product failed (${res.status}): ${error}`, {
535
- status: res.status
536
- });
492
+ await throwApiError("Clone product", res);
537
493
  }
538
494
  return await res.json();
539
495
  },
@@ -545,11 +501,7 @@ function createSolvaPayClient(opts) {
545
501
  headers
546
502
  });
547
503
  if (!res.ok) {
548
- const error = await res.text();
549
- log(`\u274C API Error: ${res.status} - ${error}`);
550
- throw new import_core2.SolvaPayError(`List plans failed (${res.status}): ${error}`, {
551
- status: res.status
552
- });
504
+ await throwApiError("List plans", res);
553
505
  }
554
506
  const result = await res.json();
555
507
  const plans = Array.isArray(result) ? result : result.plans || [];
@@ -574,11 +526,7 @@ function createSolvaPayClient(opts) {
574
526
  body: JSON.stringify(params)
575
527
  });
576
528
  if (!res.ok) {
577
- const error = await res.text();
578
- log(`\u274C API Error: ${res.status} - ${error}`);
579
- throw new import_core2.SolvaPayError(`Create plan failed (${res.status}): ${error}`, {
580
- status: res.status
581
- });
529
+ await throwApiError("Create plan", res);
582
530
  }
583
531
  const result = await res.json();
584
532
  return result;
@@ -592,11 +540,7 @@ function createSolvaPayClient(opts) {
592
540
  body: JSON.stringify(params)
593
541
  });
594
542
  if (!res.ok) {
595
- const error = await res.text();
596
- log(`\u274C API Error: ${res.status} - ${error}`);
597
- throw new import_core2.SolvaPayError(`Update plan failed (${res.status}): ${error}`, {
598
- status: res.status
599
- });
543
+ await throwApiError("Update plan", res);
600
544
  }
601
545
  return await res.json();
602
546
  },
@@ -608,11 +552,7 @@ function createSolvaPayClient(opts) {
608
552
  headers
609
553
  });
610
554
  if (!res.ok && res.status !== 404) {
611
- const error = await res.text();
612
- log(`\u274C API Error: ${res.status} - ${error}`);
613
- throw new import_core2.SolvaPayError(`Delete plan failed (${res.status}): ${error}`, {
614
- status: res.status
615
- });
555
+ await throwApiError("Delete plan", res);
616
556
  }
617
557
  },
618
558
  // POST: /payment-intents
@@ -633,11 +573,7 @@ function createSolvaPayClient(opts) {
633
573
  })
634
574
  });
635
575
  if (!res.ok) {
636
- const error = await res.text();
637
- log(`\u274C API Error: ${res.status} - ${error}`);
638
- throw new import_core2.SolvaPayError(`Create payment intent failed (${res.status}): ${error}`, {
639
- status: res.status
640
- });
576
+ await throwApiError("Create payment intent", res);
641
577
  }
642
578
  return await res.json();
643
579
  },
@@ -661,11 +597,7 @@ function createSolvaPayClient(opts) {
661
597
  })
662
598
  });
663
599
  if (!res.ok) {
664
- const error = await res.text();
665
- log(`\u274C API Error: ${res.status} - ${error}`);
666
- throw new import_core2.SolvaPayError(`Create topup payment intent failed (${res.status}): ${error}`, {
667
- status: res.status
668
- });
600
+ await throwApiError("Create topup payment intent", res);
669
601
  }
670
602
  return await res.json();
671
603
  },
@@ -685,11 +617,7 @@ function createSolvaPayClient(opts) {
685
617
  })
686
618
  });
687
619
  if (!res.ok) {
688
- const error = await res.text();
689
- log(`\u274C API Error: ${res.status} - ${error}`);
690
- throw new import_core2.SolvaPayError(`Process payment failed (${res.status}): ${error}`, {
691
- status: res.status
692
- });
620
+ await throwApiError("Process payment", res);
693
621
  }
694
622
  const result = await res.json();
695
623
  return result;
@@ -710,54 +638,20 @@ function createSolvaPayClient(opts) {
710
638
  })
711
639
  });
712
640
  if (!res.ok) {
713
- const error = await res.text();
714
- log(`\u274C API Error: ${res.status} - ${error}`);
715
- throw new import_core2.SolvaPayError(
716
- `Attach business details failed (${res.status}): ${error}`,
717
- { status: res.status }
718
- );
719
- }
720
- return await res.json();
721
- },
722
- // POST: /v1/sdk/purchases/{purchaseRef}/cancel
723
- async cancelPurchase(params) {
724
- const url = `${base}/v1/sdk/purchases/${params.purchaseRef}/cancel`;
725
- const requestOptions = {
726
- method: "POST",
727
- headers
728
- };
729
- if (params.reason) {
730
- requestOptions.body = JSON.stringify({ reason: params.reason });
731
- }
732
- const res = await fetch(url, requestOptions);
733
- if (!res.ok) {
734
- const error = await res.text();
735
- log(`\u274C API Error: ${res.status} - ${error}`);
736
- if (res.status === 404) {
737
- throw new import_core2.SolvaPayError(`Purchase not found: ${error}`, { status: 404 });
738
- }
739
- if (res.status === 400) {
740
- throw new import_core2.SolvaPayError(
741
- `Purchase cannot be cancelled or does not belong to provider: ${error}`,
742
- { status: 400 }
743
- );
744
- }
745
- throw new import_core2.SolvaPayError(`Cancel purchase failed (${res.status}): ${error}`, {
746
- status: res.status
747
- });
641
+ await throwApiError("Cancel purchase", res);
748
642
  }
749
643
  const responseText = await res.text();
750
644
  let responseData;
751
645
  try {
752
646
  responseData = JSON.parse(responseText);
753
647
  } catch (parseError) {
754
- log(`\u274C Failed to parse response as JSON: ${parseError}`);
648
+ apiDebugLog(`\u274C Failed to parse response as JSON: ${parseError}`);
755
649
  throw new import_core2.SolvaPayError(
756
650
  `Invalid JSON response from cancel purchase endpoint: ${responseText.substring(0, 200)}`
757
651
  );
758
652
  }
759
653
  if (!responseData || typeof responseData !== "object") {
760
- log(`\u274C Invalid response structure: ${JSON.stringify(responseData)}`);
654
+ apiDebugLog(`\u274C Invalid response structure: ${JSON.stringify(responseData)}`);
761
655
  throw new import_core2.SolvaPayError(`Invalid response structure from cancel purchase endpoint`);
762
656
  }
763
657
  let result;
@@ -769,7 +663,7 @@ function createSolvaPayClient(opts) {
769
663
  result = responseData.purchase || responseData;
770
664
  }
771
665
  if (!result || typeof result !== "object") {
772
- log(`\u274C Invalid purchase data in response. Full response:`, responseData);
666
+ apiDebugLog(`\u274C Invalid purchase data in response. Full response:`, responseData);
773
667
  throw new import_core2.SolvaPayError(`Invalid purchase data in cancel purchase response`);
774
668
  }
775
669
  return result;
@@ -782,30 +676,20 @@ function createSolvaPayClient(opts) {
782
676
  headers
783
677
  });
784
678
  if (!res.ok) {
785
- const error = await res.text();
786
- log(`\u274C API Error: ${res.status} - ${error}`);
787
- if (res.status === 404) {
788
- throw new import_core2.SolvaPayError(`Purchase not found: ${error}`, { status: 404 });
789
- }
790
- if (res.status === 400) {
791
- throw new import_core2.SolvaPayError(`Purchase cannot be reactivated: ${error}`, { status: 400 });
792
- }
793
- throw new import_core2.SolvaPayError(`Reactivate purchase failed (${res.status}): ${error}`, {
794
- status: res.status
795
- });
679
+ await throwApiError("Reactivate purchase", res);
796
680
  }
797
681
  const responseText = await res.text();
798
682
  let responseData;
799
683
  try {
800
684
  responseData = JSON.parse(responseText);
801
685
  } catch (parseError) {
802
- log(`\u274C Failed to parse response as JSON: ${parseError}`);
686
+ apiDebugLog(`\u274C Failed to parse response as JSON: ${parseError}`);
803
687
  throw new import_core2.SolvaPayError(
804
688
  `Invalid JSON response from reactivate purchase endpoint: ${responseText.substring(0, 200)}`
805
689
  );
806
690
  }
807
691
  if (!responseData || typeof responseData !== "object") {
808
- log(`\u274C Invalid response structure: ${JSON.stringify(responseData)}`);
692
+ apiDebugLog(`\u274C Invalid response structure: ${JSON.stringify(responseData)}`);
809
693
  throw new import_core2.SolvaPayError(`Invalid response structure from reactivate purchase endpoint`);
810
694
  }
811
695
  let result;
@@ -817,7 +701,7 @@ function createSolvaPayClient(opts) {
817
701
  result = responseData.purchase || responseData;
818
702
  }
819
703
  if (!result || typeof result !== "object") {
820
- log(`\u274C Invalid purchase data in response. Full response:`, responseData);
704
+ apiDebugLog(`\u274C Invalid purchase data in response. Full response:`, responseData);
821
705
  throw new import_core2.SolvaPayError(`Invalid purchase data in reactivate purchase response`);
822
706
  }
823
707
  return result;
@@ -831,11 +715,7 @@ function createSolvaPayClient(opts) {
831
715
  body: JSON.stringify(params)
832
716
  });
833
717
  if (!res.ok) {
834
- const error = await res.text();
835
- log(`\u274C API Error: ${res.status} - ${error}`);
836
- throw new import_core2.SolvaPayError(`Get user info failed (${res.status}): ${error}`, {
837
- status: res.status
838
- });
718
+ await throwApiError("Get user info", res);
839
719
  }
840
720
  return await res.json();
841
721
  },
@@ -847,11 +727,7 @@ function createSolvaPayClient(opts) {
847
727
  headers
848
728
  });
849
729
  if (!res.ok) {
850
- const error = await res.text();
851
- log(`\u274C API Error: ${res.status} - ${error}`);
852
- throw new import_core2.SolvaPayError(`Get customer balance failed (${res.status}): ${error}`, {
853
- status: res.status
854
- });
730
+ await throwApiError("Get customer balance", res);
855
731
  }
856
732
  return await res.json();
857
733
  },
@@ -864,11 +740,7 @@ function createSolvaPayClient(opts) {
864
740
  body: JSON.stringify(params)
865
741
  });
866
742
  if (!res.ok) {
867
- const error = await res.text();
868
- log(`\u274C API Error: ${res.status} - ${error}`);
869
- throw new import_core2.SolvaPayError(`Create checkout session failed (${res.status}): ${error}`, {
870
- status: res.status
871
- });
743
+ await throwApiError("Create checkout session", res);
872
744
  }
873
745
  const result = await res.json();
874
746
  return result;
@@ -882,11 +754,7 @@ function createSolvaPayClient(opts) {
882
754
  body: JSON.stringify(params)
883
755
  });
884
756
  if (!res.ok) {
885
- const error = await res.text();
886
- log(`\u274C API Error: ${res.status} - ${error}`);
887
- throw new import_core2.SolvaPayError(`Create customer session failed (${res.status}): ${error}`, {
888
- status: res.status
889
- });
757
+ await throwApiError("Create customer session", res);
890
758
  }
891
759
  const result = await res.json();
892
760
  return result;
@@ -900,11 +768,7 @@ function createSolvaPayClient(opts) {
900
768
  body: JSON.stringify(params)
901
769
  });
902
770
  if (!res.ok) {
903
- const error = await res.text();
904
- log(`\u274C API Error: ${res.status} - ${error}`);
905
- throw new import_core2.SolvaPayError(`Activate plan failed (${res.status}): ${error}`, {
906
- status: res.status
907
- });
771
+ await throwApiError("Activate plan", res);
908
772
  }
909
773
  return await res.json();
910
774
  },
@@ -913,11 +777,7 @@ function createSolvaPayClient(opts) {
913
777
  url.searchParams.set("customerRef", params.customerRef);
914
778
  const res = await fetch(url.toString(), { method: "GET", headers });
915
779
  if (!res.ok) {
916
- const error = await res.text();
917
- log(`\u274C API Error: ${res.status} - ${error}`);
918
- throw new import_core2.SolvaPayError(`Get payment method failed (${res.status}): ${error}`, {
919
- status: res.status
920
- });
780
+ await throwApiError("Get payment method", res);
921
781
  }
922
782
  return await res.json();
923
783
  },
@@ -926,11 +786,7 @@ function createSolvaPayClient(opts) {
926
786
  url.searchParams.set("customerRef", params.customerRef);
927
787
  const res = await fetch(url.toString(), { method: "GET", headers });
928
788
  if (!res.ok) {
929
- const error = await res.text();
930
- log(`\u274C API Error: ${res.status} - ${error}`);
931
- throw new import_core2.SolvaPayError(`Get auto-recharge failed (${res.status}): ${error}`, {
932
- status: res.status
933
- });
789
+ await throwApiError("Get auto-recharge", res);
934
790
  }
935
791
  return await res.json();
936
792
  },
@@ -941,11 +797,7 @@ function createSolvaPayClient(opts) {
941
797
  body: JSON.stringify(params)
942
798
  });
943
799
  if (!res.ok) {
944
- const error = await res.text();
945
- log(`\u274C API Error: ${res.status} - ${error}`);
946
- throw new import_core2.SolvaPayError(`Save auto-recharge failed (${res.status}): ${error}`, {
947
- status: res.status
948
- });
800
+ await throwApiError("Save auto-recharge", res);
949
801
  }
950
802
  return await res.json();
951
803
  },
@@ -954,11 +806,7 @@ function createSolvaPayClient(opts) {
954
806
  url.searchParams.set("customerRef", params.customerRef);
955
807
  const res = await fetch(url.toString(), { method: "DELETE", headers });
956
808
  if (!res.ok) {
957
- const error = await res.text();
958
- log(`\u274C API Error: ${res.status} - ${error}`);
959
- throw new import_core2.SolvaPayError(`Disable auto-recharge failed (${res.status}): ${error}`, {
960
- status: res.status
961
- });
809
+ await throwApiError("Disable auto-recharge", res);
962
810
  }
963
811
  return await res.json();
964
812
  },
@@ -972,11 +820,7 @@ function createSolvaPayClient(opts) {
972
820
  }
973
821
  const res = await fetch(url.toString(), { method: "GET", headers });
974
822
  if (!res.ok) {
975
- const error = await res.text();
976
- log(`\u274C API Error: ${res.status} - ${error}`);
977
- throw new import_core2.SolvaPayError(`List purchases failed (${res.status}): ${error}`, {
978
- status: res.status
979
- });
823
+ await throwApiError("List purchases", res);
980
824
  }
981
825
  const data = await res.json();
982
826
  return { purchases: data.purchases ?? [] };
@@ -987,11 +831,7 @@ function createSolvaPayClient(opts) {
987
831
  if (params.limit !== void 0) url.searchParams.set("limit", String(params.limit));
988
832
  const res = await fetch(url.toString(), { method: "GET", headers });
989
833
  if (!res.ok) {
990
- const error = await res.text();
991
- log(`\u274C API Error: ${res.status} - ${error}`);
992
- throw new import_core2.SolvaPayError(`Get credit activity failed (${res.status}): ${error}`, {
993
- status: res.status
994
- });
834
+ await throwApiError("Get credit activity", res);
995
835
  }
996
836
  return await res.json();
997
837
  }
@@ -999,46 +839,92 @@ function createSolvaPayClient(opts) {
999
839
  }
1000
840
 
1001
841
  // src/paywall-state.ts
842
+ var import_core3 = require("@solvapay/core");
1002
843
  var CHECKOUT_SESSION_TTL_MINUTES = 15;
1003
844
  var DOCS_HINT = "See docs://solvapay/overview.md.";
845
+ function creditSignals(limits) {
846
+ if (!limits) return { isCreditBased: false };
847
+ const creditBalance = limits.balance?.creditBalance ?? limits.creditBalance;
848
+ const creditsPerCall = limits.balance?.creditsPerUnit ?? limits.creditsPerUnit;
849
+ const isCreditBased = creditBalance !== void 0 || creditsPerCall !== void 0;
850
+ const shortfallCredits = creditBalance !== void 0 && creditsPerCall !== void 0 ? Math.max(0, creditsPerCall - creditBalance) : void 0;
851
+ let remainingCalls;
852
+ if (limits.balance?.remainingUnits !== void 0) {
853
+ remainingCalls = limits.balance.remainingUnits;
854
+ } else if (creditBalance !== void 0 && creditsPerCall !== void 0 && creditsPerCall > 0) {
855
+ remainingCalls = Math.floor(creditBalance / creditsPerCall);
856
+ } else if (limits.remaining >= 0) {
857
+ remainingCalls = limits.remaining;
858
+ }
859
+ return { creditBalance, creditsPerCall, shortfallCredits, remainingCalls, isCreditBased };
860
+ }
861
+ function nextActionFor(state) {
862
+ switch (state.kind) {
863
+ case "activation_required":
864
+ return "activate";
865
+ case "topup_required":
866
+ return "topup";
867
+ case "upgrade_required":
868
+ case "limit_reached":
869
+ return "checkout";
870
+ case "reactivation_required":
871
+ return "account";
872
+ }
873
+ }
874
+ function activePlanRefOf(limits) {
875
+ const ref = limits.planRef ?? limits.plan;
876
+ return ref && ref.length > 0 ? ref : void 0;
877
+ }
1004
878
  function classifyPaywallState(limits) {
1005
879
  if (!limits) return { kind: "upgrade_required" };
1006
- if (limits.activationRequired === true) {
880
+ if (limits.activationRequired === true || limits.paywallReason === "activation_required") {
1007
881
  return { kind: "activation_required" };
1008
882
  }
883
+ if (limits.paywallReason === "topup_required") {
884
+ return { kind: "topup_required" };
885
+ }
1009
886
  if (limits.needsTopUp === true) {
1010
887
  return { kind: "topup_required" };
1011
888
  }
1012
889
  if (limits.needsUpgrade === true) {
1013
890
  return { kind: "upgrade_required" };
1014
891
  }
1015
- const activePlan = limits.plans?.find((p) => p.reference === limits.plan);
1016
- const isUsageBased = activePlan?.type === "usage-based" || limits.balance !== void 0;
1017
- const creditBalance = limits.balance?.creditBalance ?? limits.creditBalance;
1018
- if (isUsageBased) {
1019
- if (creditBalance === 0) return { kind: "topup_required" };
1020
- if (creditBalance === void 0 && limits.remaining === 0) {
892
+ const signals = creditSignals(limits);
893
+ if (signals.isCreditBased) {
894
+ if (signals.creditBalance !== void 0 && signals.creditsPerCall !== void 0 && signals.creditBalance < signals.creditsPerCall) {
895
+ return { kind: "topup_required" };
896
+ }
897
+ if (signals.creditBalance === 0) return { kind: "topup_required" };
898
+ if (signals.creditsPerCall === void 0 && limits.remaining === 0) {
1021
899
  return { kind: "topup_required" };
1022
900
  }
1023
901
  }
1024
- if (limits.plan.length > 0 && limits.remaining <= 0) {
902
+ const activeRef = activePlanRefOf(limits);
903
+ if ((limits.purchaseRef || activeRef) && limits.remaining <= 0) {
1025
904
  return { kind: "limit_reached" };
1026
905
  }
906
+ if (signals.isCreditBased) return { kind: "topup_required" };
907
+ if (limits.purchaseRef) return { kind: "limit_reached" };
1027
908
  return { kind: "upgrade_required" };
1028
909
  }
1029
910
  function formatMinor(amountMinor, currency) {
1030
- const major = amountMinor / 100;
911
+ const divisor = (0, import_core3.minorUnitsPerMajor)(currency);
912
+ const major = amountMinor / divisor;
913
+ const fractionDigits = divisor === 1 ? 0 : 2;
1031
914
  try {
1032
915
  return new Intl.NumberFormat("en-US", {
1033
916
  style: "currency",
1034
917
  currency: currency.toUpperCase(),
1035
- minimumFractionDigits: 2,
1036
- maximumFractionDigits: 2
918
+ minimumFractionDigits: fractionDigits,
919
+ maximumFractionDigits: fractionDigits
1037
920
  }).format(major);
1038
921
  } catch {
1039
- return `${currency.toUpperCase()} ${major.toFixed(2)}`;
922
+ return `${currency.toUpperCase()} ${divisor === 1 ? String(Math.round(major)) : major.toFixed(2)}`;
1040
923
  }
1041
924
  }
925
+ function formatCredits(value) {
926
+ return value.toLocaleString("en-US");
927
+ }
1042
928
  function meterLabel(gate) {
1043
929
  if (!gate.meterName) return "units";
1044
930
  return gate.meterName.replace(/_/g, " ");
@@ -1046,6 +932,14 @@ function meterLabel(gate) {
1046
932
  function namedCheckoutMarkdown(url) {
1047
933
  return `[Open checkout](${url})`;
1048
934
  }
935
+ function linkLabel(name) {
936
+ return name.replace(/([[\]])/g, "\\$1");
937
+ }
938
+ function planLadder(gate) {
939
+ const linkable = (gate.plans ?? []).filter((p) => typeof p.checkoutUrl === "string" && p.checkoutUrl.length > 0).filter((p) => p.reference !== gate.planRef).sort((a, b) => a.price - b.price).slice(0, 4);
940
+ if (linkable.length === 0) return null;
941
+ return linkable.map((p) => `[${linkLabel(p.name ?? p.reference)}](${p.checkoutUrl})`).join(" \xB7 ");
942
+ }
1049
943
  var VIEWER_TOOL = "account";
1050
944
  function callViewer(view) {
1051
945
  return view ? `call the \`${VIEWER_TOOL}\` tool with view: '${view}'` : `call the \`${VIEWER_TOOL}\` tool`;
@@ -1056,25 +950,57 @@ function recoverClause(url, verb, view) {
1056
950
  }
1057
951
  return ` ${callViewer(view).replace(/^c/, "C")}.`;
1058
952
  }
953
+ function hasActivePlan(gate) {
954
+ return Boolean(gate.purchaseRef || gate.planRef && gate.planRef.length > 0);
955
+ }
956
+ function autoRechargeDisabled(gate) {
957
+ return gate.autoRecharge?.enabled === false;
958
+ }
1059
959
  function buildGateMessage(state, gate) {
1060
960
  const url = gate.checkoutUrl && gate.checkoutUrl.length > 0 ? gate.checkoutUrl : null;
961
+ const ladder = planLadder(gate);
1061
962
  switch (state.kind) {
1062
963
  case "limit_reached": {
1063
964
  const included = gate.included;
1064
965
  const price = gate.unitPriceMinor != null && gate.currency ? formatMinor(gate.unitPriceMinor, gate.currency) : null;
1065
966
  const usedLine = included ? `You've used ${included.used} of ${included.total} included ${meterLabel(gate)} this period.` : `You've reached the included usage for this period.`;
1066
967
  const nextLine = price ? ` The next call is ${price}.` : "";
1067
- return `${usedLine}${nextLine}${recoverClause(url, "continue", "checkout")} ${DOCS_HINT}`;
968
+ const planName = gate.planName ?? "This plan";
969
+ const antiTrap = gate.creditBalance !== void 0 && gate.creditBalance > 0 && (gate.creditsPerCall === void 0 || gate.creditsPerCall === 0) ? ` Adding credits will not help, because ${planName} does not spend them.` : "";
970
+ const switchLine = ladder ? ` Or switch plan: ${ladder}.` : recoverClause(url, "continue", "checkout");
971
+ return `${usedLine}${nextLine}${antiTrap}${switchLine} ${DOCS_HINT}`;
1068
972
  }
1069
973
  case "activation_required":
1070
974
  return `Your plan needs activation.${recoverClause(url, "activate", "checkout")} Or call \`activate_plan\` with a \`planRef\`. ${DOCS_HINT}`;
1071
975
  case "topup_required": {
1072
- const currency = gate.currency ?? gate.balance?.currency ?? "USD";
1073
- const presets = [1e3, 2500, 5e3, 1e4].map((m) => formatMinor(m, currency)).join(" \xB7 ");
1074
- return `You're out of credits. Top up first (${presets}).${recoverClause(url, "add credits", "topup")} ${DOCS_HINT}`;
1075
- }
1076
- case "upgrade_required":
976
+ const balance = gate.creditBalance;
977
+ const cost = gate.creditsPerCall;
978
+ const shortfall = gate.shortfallCredits;
979
+ let lead;
980
+ if (balance !== void 0 && cost !== void 0 && shortfall !== void 0) {
981
+ lead = `Out of credits for this call. Balance ${formatCredits(balance)} credits; this call costs ${formatCredits(cost)} credits \u2014 ${formatCredits(shortfall)} short.`;
982
+ } else {
983
+ lead = "Included usage is exhausted.";
984
+ }
985
+ const topup = recoverClause(url, "add credits", "topup");
986
+ const auto = autoRechargeDisabled(gate) ? " Auto-recharge is off \u2014 turn it on from the account tool to avoid this next time." : "";
987
+ const switchLine = ladder ? ` Or switch plan: ${ladder}.` : "";
988
+ return `${lead}${topup}${auto}${switchLine} ${DOCS_HINT}`;
989
+ }
990
+ case "upgrade_required": {
991
+ if (hasActivePlan(gate)) {
992
+ const planName = gate.planName ?? "This plan";
993
+ const lead = `${planName} is active but its included usage is exhausted, and the automatic switch to the next plan did not complete.`;
994
+ if (ladder) {
995
+ return `${lead} Switch here: ${ladder}. ${DOCS_HINT}`;
996
+ }
997
+ return `${lead}${recoverClause(url, "switch plan", "checkout")} ${DOCS_HINT}`;
998
+ }
999
+ if (ladder) {
1000
+ return `You don't have an active plan for this tool. Pick a plan to use this tool: ${ladder} (links expire in ${CHECKOUT_SESSION_TTL_MINUTES} minutes), or ${callViewer("checkout")}. ${DOCS_HINT}`;
1001
+ }
1077
1002
  return `You don't have an active plan for this tool.${recoverClause(url, "pick a plan", "checkout")} ${DOCS_HINT}`;
1003
+ }
1078
1004
  case "reactivation_required":
1079
1005
  return `Your previous plan is no longer active. ${callViewer("account").replace(/^c/, "C")} to reactivate it, or ${callViewer("checkout")} to pick a new plan. ${DOCS_HINT}`;
1080
1006
  }
@@ -1087,11 +1013,23 @@ function allPaidPlansArePayg(plans) {
1087
1013
  if (paidPlans.length === 0) return false;
1088
1014
  return paidPlans.every((p) => p.type === "usage-based" || p.type === "hybrid");
1089
1015
  }
1016
+ function activePlanRefOf2(limits) {
1017
+ const ref = limits.planRef ?? limits.plan;
1018
+ return ref && ref.length > 0 ? ref : void 0;
1019
+ }
1090
1020
  function activePlanOf(limits) {
1091
- if (!limits.plan) return void 0;
1092
- return limits.plans?.find((p) => p.reference === limits.plan);
1021
+ const ref = activePlanRefOf2(limits);
1022
+ if (!ref) return void 0;
1023
+ return limits.plans?.find((p) => p.reference === ref);
1093
1024
  }
1094
1025
  function includedFromLimits(limits) {
1026
+ if (limits.used !== void 0 && limits.limit !== void 0) {
1027
+ return {
1028
+ total: limits.limit,
1029
+ used: limits.used,
1030
+ remaining: limits.remaining
1031
+ };
1032
+ }
1095
1033
  const total = activePlanOf(limits)?.freeUnits;
1096
1034
  if (total == null || total === 0) return void 0;
1097
1035
  const remaining = limits.remaining;
@@ -1101,24 +1039,49 @@ function includedFromLimits(limits) {
1101
1039
  remaining
1102
1040
  };
1103
1041
  }
1104
- function recoveryFields(limits) {
1042
+ function recoveryLinks(limits) {
1043
+ const links = {};
1044
+ if (limits.checkoutUrl) {
1045
+ if (limits.checkoutUrl.includes("/topup")) {
1046
+ links.topup = limits.checkoutUrl;
1047
+ } else {
1048
+ links.checkout = limits.checkoutUrl;
1049
+ }
1050
+ }
1051
+ if (limits.confirmationUrl) {
1052
+ links.manage = limits.confirmationUrl;
1053
+ }
1054
+ return Object.keys(links).length > 0 ? links : void 0;
1055
+ }
1056
+ function recoveryFields(limits, state) {
1105
1057
  const plan = activePlanOf(limits);
1106
1058
  const included = includedFromLimits(limits);
1107
- const creditBalance = limits.balance?.creditBalance ?? limits.creditBalance;
1059
+ const signals = creditSignals(limits);
1060
+ const planRef = activePlanRefOf2(limits);
1061
+ const links = recoveryLinks(limits);
1108
1062
  return {
1109
- ...limits.plan ? { planRef: limits.plan } : {},
1063
+ ...planRef ? { planRef } : {},
1064
+ ...limits.planName !== void 0 ? { planName: limits.planName } : {},
1110
1065
  ...limits.plans !== void 0 ? { plans: limits.plans } : {},
1111
1066
  ...limits.meterName !== void 0 ? { meterName: limits.meterName } : {},
1112
1067
  ...plan?.perUnitChargeMinor != null ? { unitPriceMinor: plan.perUnitChargeMinor, currency: plan.currency } : limits.currency ? { currency: limits.currency } : {},
1113
1068
  ...included ? { included } : {},
1114
- ...creditBalance !== void 0 ? { creditBalance } : {}
1069
+ ...signals.creditBalance !== void 0 ? { creditBalance: signals.creditBalance } : {},
1070
+ reason: state.kind,
1071
+ nextAction: nextActionFor(state),
1072
+ ...signals.creditsPerCall !== void 0 ? { creditsPerCall: signals.creditsPerCall } : {},
1073
+ ...signals.shortfallCredits !== void 0 ? { shortfallCredits: signals.shortfallCredits } : {},
1074
+ ...signals.remainingCalls !== void 0 ? { remainingCalls: signals.remainingCalls } : {},
1075
+ ...limits.purchaseRef !== void 0 ? { purchaseRef: limits.purchaseRef } : {},
1076
+ ...limits.autoRecharge !== void 0 ? { autoRecharge: limits.autoRecharge } : {},
1077
+ ...links ? { links } : {}
1115
1078
  };
1116
1079
  }
1117
1080
  function buildPaywallGate(productRef, limits) {
1118
1081
  const checkoutUrl = limits.checkoutUrl;
1119
- const state = classifyPaywallState({ ...limits, plan: limits.plan ?? "" });
1082
+ const state = classifyPaywallState(limits);
1120
1083
  const useActivationForTopup = !limits.activationRequired && state.kind === "topup_required" && allPaidPlansArePayg(limits.plans);
1121
- const recovery = recoveryFields(limits);
1084
+ const recovery = recoveryFields(limits, state);
1122
1085
  const preMessage = limits.activationRequired || useActivationForTopup ? {
1123
1086
  kind: "activation_required",
1124
1087
  product: productRef,
@@ -1141,7 +1104,7 @@ function buildPaywallGate(productRef, limits) {
1141
1104
  }
1142
1105
 
1143
1106
  // src/resolve-product-ref.ts
1144
- var import_core3 = require("@solvapay/core");
1107
+ var import_core4 = require("@solvapay/core");
1145
1108
  var MISSING_PRODUCT_REF_MESSAGE = "No product ref resolved. Pass productRef to payable() or set SOLVAPAY_PRODUCT_REF. Run `npx solvapay doctor` to diagnose.";
1146
1109
  function readEnvProductRef() {
1147
1110
  if (typeof process === "undefined") return void 0;
@@ -1154,7 +1117,7 @@ function resolveProductRef(explicit) {
1154
1117
  function requireProductRef(explicit) {
1155
1118
  const resolved = resolveProductRef(explicit);
1156
1119
  if (!resolved) {
1157
- throw new import_core3.SolvaPayError(MISSING_PRODUCT_REF_MESSAGE);
1120
+ throw new import_core4.SolvaPayError(MISSING_PRODUCT_REF_MESSAGE);
1158
1121
  }
1159
1122
  return resolved;
1160
1123
  }
@@ -2118,7 +2081,7 @@ var McpAdapter = class {
2118
2081
  };
2119
2082
 
2120
2083
  // src/factory.ts
2121
- var import_core4 = require("@solvapay/core");
2084
+ var import_core5 = require("@solvapay/core");
2122
2085
 
2123
2086
  // src/virtual-tools.ts
2124
2087
  var TOOL_GET_USER_INFO = {
@@ -2359,7 +2322,7 @@ function registerVirtualToolsMcpImpl(server, apiClient, options) {
2359
2322
  function createSolvaPay(config) {
2360
2323
  let resolvedConfig;
2361
2324
  if (!config) {
2362
- const envConfig = (0, import_core4.getSolvaPayConfig)();
2325
+ const envConfig = (0, import_core5.getSolvaPayConfig)();
2363
2326
  resolvedConfig = {
2364
2327
  apiKey: envConfig.apiKey,
2365
2328
  apiBaseUrl: envConfig.apiBaseUrl
@@ -2392,25 +2355,25 @@ function createSolvaPay(config) {
2392
2355
  },
2393
2356
  createPaymentIntent(params) {
2394
2357
  if (!apiClient.createPaymentIntent) {
2395
- throw new import_core4.SolvaPayError("createPaymentIntent is not available on this API client");
2358
+ throw new import_core5.SolvaPayError("createPaymentIntent is not available on this API client");
2396
2359
  }
2397
2360
  return apiClient.createPaymentIntent(params);
2398
2361
  },
2399
2362
  createTopupPaymentIntent(params) {
2400
2363
  if (!apiClient.createTopupPaymentIntent) {
2401
- throw new import_core4.SolvaPayError("createTopupPaymentIntent is not available on this API client");
2364
+ throw new import_core5.SolvaPayError("createTopupPaymentIntent is not available on this API client");
2402
2365
  }
2403
2366
  return apiClient.createTopupPaymentIntent(params);
2404
2367
  },
2405
2368
  processPaymentIntent(params) {
2406
2369
  if (!apiClient.processPaymentIntent) {
2407
- throw new import_core4.SolvaPayError("processPaymentIntent is not available on this API client");
2370
+ throw new import_core5.SolvaPayError("processPaymentIntent is not available on this API client");
2408
2371
  }
2409
2372
  return apiClient.processPaymentIntent(params);
2410
2373
  },
2411
2374
  attachBusinessDetails(params) {
2412
2375
  if (!apiClient.attachBusinessDetails) {
2413
- throw new import_core4.SolvaPayError("attachBusinessDetails is not available on this API client");
2376
+ throw new import_core5.SolvaPayError("attachBusinessDetails is not available on this API client");
2414
2377
  }
2415
2378
  return apiClient.attachBusinessDetails(params);
2416
2379
  },
@@ -2422,13 +2385,13 @@ function createSolvaPay(config) {
2422
2385
  },
2423
2386
  trackUsageBulk(params) {
2424
2387
  if (!apiClient.trackUsageBulk) {
2425
- throw new import_core4.SolvaPayError("trackUsageBulk is not available on this API client");
2388
+ throw new import_core5.SolvaPayError("trackUsageBulk is not available on this API client");
2426
2389
  }
2427
2390
  return apiClient.trackUsageBulk(params);
2428
2391
  },
2429
2392
  createCustomer(params) {
2430
2393
  if (!apiClient.createCustomer) {
2431
- throw new import_core4.SolvaPayError("createCustomer is not available on this API client");
2394
+ throw new import_core5.SolvaPayError("createCustomer is not available on this API client");
2432
2395
  }
2433
2396
  return apiClient.createCustomer({ ...params, metadata: params.metadata ?? {} });
2434
2397
  },
@@ -2437,13 +2400,13 @@ function createSolvaPay(config) {
2437
2400
  },
2438
2401
  assignCredits(params) {
2439
2402
  if (!apiClient.assignCredits) {
2440
- throw new import_core4.SolvaPayError("assignCredits is not available on this API client");
2403
+ throw new import_core5.SolvaPayError("assignCredits is not available on this API client");
2441
2404
  }
2442
2405
  return apiClient.assignCredits(params);
2443
2406
  },
2444
2407
  getCustomerBalance(params) {
2445
2408
  if (!apiClient.getCustomerBalance) {
2446
- throw new import_core4.SolvaPayError("getCustomerBalance is not available on this API client");
2409
+ throw new import_core5.SolvaPayError("getCustomerBalance is not available on this API client");
2447
2410
  }
2448
2411
  return apiClient.getCustomerBalance(params);
2449
2412
  },
@@ -2459,19 +2422,19 @@ function createSolvaPay(config) {
2459
2422
  },
2460
2423
  activatePlan(params) {
2461
2424
  if (!apiClient.activatePlan) {
2462
- throw new import_core4.SolvaPayError("activatePlan is not available on this API client");
2425
+ throw new import_core5.SolvaPayError("activatePlan is not available on this API client");
2463
2426
  }
2464
2427
  return apiClient.activatePlan(params);
2465
2428
  },
2466
2429
  bootstrapMcpProduct(params) {
2467
2430
  if (!apiClient.bootstrapMcpProduct) {
2468
- throw new import_core4.SolvaPayError("bootstrapMcpProduct is not available on this API client");
2431
+ throw new import_core5.SolvaPayError("bootstrapMcpProduct is not available on this API client");
2469
2432
  }
2470
2433
  return apiClient.bootstrapMcpProduct(params);
2471
2434
  },
2472
2435
  configureMcpPlans(productRef, params) {
2473
2436
  if (!apiClient.configureMcpPlans) {
2474
- throw new import_core4.SolvaPayError("configureMcpPlans is not available on this API client");
2437
+ throw new import_core5.SolvaPayError("configureMcpPlans is not available on this API client");
2475
2438
  }
2476
2439
  return apiClient.configureMcpPlans(productRef, params);
2477
2440
  },
@@ -2662,7 +2625,7 @@ async function getCustomerBalanceCore(request, options = {}) {
2662
2625
  }
2663
2626
 
2664
2627
  // src/helpers/payment.ts
2665
- var import_core5 = require("@solvapay/core");
2628
+ var import_core6 = require("@solvapay/core");
2666
2629
  async function createPaymentIntentCore(request, body, options = {}) {
2667
2630
  try {
2668
2631
  if (!body.planRef || !body.productRef) {
@@ -2841,7 +2804,7 @@ async function createCustomerSessionCore(request, options = {}) {
2841
2804
  }
2842
2805
 
2843
2806
  // src/helpers/renewal.ts
2844
- var import_core6 = require("@solvapay/core");
2807
+ var import_core7 = require("@solvapay/core");
2845
2808
  async function cancelPurchaseCore(request, body, options = {}) {
2846
2809
  try {
2847
2810
  if (!body.purchaseRef) {
@@ -2887,7 +2850,7 @@ async function cancelPurchaseCore(request, body, options = {}) {
2887
2850
  await new Promise((resolve) => setTimeout(resolve, 500));
2888
2851
  return cancelledPurchase;
2889
2852
  } catch (error) {
2890
- if (error instanceof import_core6.SolvaPayError) {
2853
+ if (error instanceof import_core7.SolvaPayError) {
2891
2854
  const errorMessage = error.message;
2892
2855
  if (errorMessage.includes("not found")) {
2893
2856
  return {
@@ -2955,7 +2918,7 @@ async function reactivatePurchaseCore(request, body, options = {}) {
2955
2918
  await new Promise((resolve) => setTimeout(resolve, 500));
2956
2919
  return reactivatedPurchase;
2957
2920
  } catch (error) {
2958
- if (error instanceof import_core6.SolvaPayError) {
2921
+ if (error instanceof import_core7.SolvaPayError) {
2959
2922
  const errorMessage = error.message;
2960
2923
  if (errorMessage.includes("not found")) {
2961
2924
  return {
@@ -3077,7 +3040,7 @@ async function getHistoryCore(request, input, options = {}) {
3077
3040
  }
3078
3041
 
3079
3042
  // src/helpers/plans.ts
3080
- var import_core7 = require("@solvapay/core");
3043
+ var import_core8 = require("@solvapay/core");
3081
3044
  async function listPlansCore(request, options = {}) {
3082
3045
  try {
3083
3046
  const url = new URL(request.url);
@@ -3089,7 +3052,7 @@ async function listPlansCore(request, options = {}) {
3089
3052
  };
3090
3053
  }
3091
3054
  const apiClient = options.solvaPay?.apiClient ?? (() => {
3092
- const config = (0, import_core7.getSolvaPayConfig)();
3055
+ const config = (0, import_core8.getSolvaPayConfig)();
3093
3056
  if (!config.apiKey) return null;
3094
3057
  return createSolvaPayClient({
3095
3058
  apiKey: config.apiKey,
@@ -3119,11 +3082,11 @@ async function listPlansCore(request, options = {}) {
3119
3082
  }
3120
3083
 
3121
3084
  // src/helpers/merchant.ts
3122
- var import_core8 = require("@solvapay/core");
3085
+ var import_core9 = require("@solvapay/core");
3123
3086
  async function getMerchantCore(_request, options = {}) {
3124
3087
  try {
3125
3088
  const apiClient = options.solvaPay?.apiClient ?? (() => {
3126
- const config = (0, import_core8.getSolvaPayConfig)();
3089
+ const config = (0, import_core9.getSolvaPayConfig)();
3127
3090
  if (!config.apiKey) return null;
3128
3091
  return createSolvaPayClient({
3129
3092
  apiKey: config.apiKey,
@@ -3150,7 +3113,7 @@ async function getMerchantCore(_request, options = {}) {
3150
3113
  }
3151
3114
 
3152
3115
  // src/helpers/product.ts
3153
- var import_core9 = require("@solvapay/core");
3116
+ var import_core10 = require("@solvapay/core");
3154
3117
  async function getProductCore(request, options = {}) {
3155
3118
  try {
3156
3119
  const url = new URL(request.url);
@@ -3162,7 +3125,7 @@ async function getProductCore(request, options = {}) {
3162
3125
  };
3163
3126
  }
3164
3127
  const apiClient = options.solvaPay?.apiClient ?? (() => {
3165
- const config = (0, import_core9.getSolvaPayConfig)();
3128
+ const config = (0, import_core10.getSolvaPayConfig)();
3166
3129
  if (!config.apiKey) return null;
3167
3130
  return createSolvaPayClient({
3168
3131
  apiKey: config.apiKey,
@@ -3245,7 +3208,7 @@ async function checkPurchaseCore(request, options = {}) {
3245
3208
  }
3246
3209
 
3247
3210
  // src/helpers/usage.ts
3248
- var import_core10 = require("@solvapay/core");
3211
+ var import_core11 = require("@solvapay/core");
3249
3212
  async function trackUsageCore(request, body, options = {}) {
3250
3213
  try {
3251
3214
  const userResult = await getAuthenticatedUserCore(request);
@@ -3274,7 +3237,7 @@ async function trackUsageCore(request, body, options = {}) {
3274
3237
  }
3275
3238
 
3276
3239
  // src/edge.ts
3277
- var import_core11 = require("@solvapay/core");
3240
+ var import_core12 = require("@solvapay/core");
3278
3241
  function timingSafeEqual(a, b) {
3279
3242
  if (a.length !== b.length) return false;
3280
3243
  let mismatch = 0;
@@ -3289,22 +3252,22 @@ async function verifyWebhook({
3289
3252
  secret
3290
3253
  }) {
3291
3254
  const toleranceSec = 300;
3292
- if (!signature) throw new import_core11.SolvaPayError("Missing webhook signature");
3255
+ if (!signature) throw new import_core12.SolvaPayError("Missing webhook signature");
3293
3256
  const parts = signature.split(",");
3294
3257
  const tPart = parts.find((p) => p.startsWith("t="));
3295
3258
  const v1Part = parts.find((p) => p.startsWith("v1="));
3296
3259
  if (!tPart || !v1Part) {
3297
- throw new import_core11.SolvaPayError("Malformed webhook signature");
3260
+ throw new import_core12.SolvaPayError("Malformed webhook signature");
3298
3261
  }
3299
3262
  const timestamp = parseInt(tPart.slice(2), 10);
3300
3263
  const receivedHmac = v1Part.slice(3);
3301
3264
  if (Number.isNaN(timestamp) || !receivedHmac) {
3302
- throw new import_core11.SolvaPayError("Malformed webhook signature");
3265
+ throw new import_core12.SolvaPayError("Malformed webhook signature");
3303
3266
  }
3304
3267
  if (toleranceSec > 0) {
3305
3268
  const age = Math.abs(Math.floor(Date.now() / 1e3) - timestamp);
3306
3269
  if (age > toleranceSec) {
3307
- throw new import_core11.SolvaPayError("Webhook signature timestamp too old");
3270
+ throw new import_core12.SolvaPayError("Webhook signature timestamp too old");
3308
3271
  }
3309
3272
  }
3310
3273
  const enc = new TextEncoder();
@@ -3318,12 +3281,12 @@ async function verifyWebhook({
3318
3281
  const sigBuf = await crypto.subtle.sign("HMAC", key, enc.encode(`${timestamp}.${body}`));
3319
3282
  const expectedHmac = Array.from(new Uint8Array(sigBuf)).map((b) => b.toString(16).padStart(2, "0")).join("");
3320
3283
  if (!timingSafeEqual(expectedHmac, receivedHmac)) {
3321
- throw new import_core11.SolvaPayError("Invalid webhook signature");
3284
+ throw new import_core12.SolvaPayError("Invalid webhook signature");
3322
3285
  }
3323
3286
  try {
3324
3287
  return JSON.parse(body);
3325
3288
  } catch {
3326
- throw new import_core11.SolvaPayError("Invalid webhook payload: body is not valid JSON");
3289
+ throw new import_core12.SolvaPayError("Invalid webhook payload: body is not valid JSON");
3327
3290
  }
3328
3291
  }
3329
3292