@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.
package/dist/index.cjs CHANGED
@@ -51,6 +51,7 @@ __export(index_exports, {
51
51
  createSolvaPayClient: () => createSolvaPayClient,
52
52
  createTopupPaymentIntentCore: () => createTopupPaymentIntentCore,
53
53
  createVirtualTools: () => createVirtualTools,
54
+ creditSignals: () => creditSignals,
54
55
  deriveUsageSnapshot: () => deriveUsageSnapshot,
55
56
  disableAutoRechargeCore: () => disableAutoRechargeCore,
56
57
  getAuthenticatedUserCore: () => getAuthenticatedUserCore,
@@ -65,8 +66,11 @@ __export(index_exports, {
65
66
  isErrorResult: () => isErrorResult,
66
67
  isPaywallStructuredContent: () => isPaywallStructuredContent,
67
68
  jsonSchemaToZodRawShape: () => jsonSchemaToZodRawShape,
69
+ linkLabel: () => linkLabel,
68
70
  listPlansCore: () => listPlansCore,
71
+ nextActionFor: () => nextActionFor,
69
72
  paywallErrorToClientPayload: () => paywallErrorToClientPayload,
73
+ planLadder: () => planLadder,
70
74
  pollBalanceUntilIncreased: () => pollBalanceUntilIncreased,
71
75
  processPaymentIntentCore: () => processPaymentIntentCore,
72
76
  processTopupPaymentIntentCore: () => processTopupPaymentIntentCore,
@@ -81,10 +85,36 @@ __export(index_exports, {
81
85
  });
82
86
  module.exports = __toCommonJS(index_exports);
83
87
  var import_node_crypto = __toESM(require("crypto"), 1);
84
- var import_core12 = require("@solvapay/core");
88
+ var import_core13 = require("@solvapay/core");
85
89
 
86
90
  // src/client.ts
87
91
  var import_core = require("@solvapay/core");
92
+ var API_ERROR_BODY_MAX = 240;
93
+ function apiDebugLog(...args) {
94
+ if (process.env.SOLVAPAY_DEBUG === "true") {
95
+ console.log(...args);
96
+ }
97
+ }
98
+ function isNonJsonResponseBody(body, contentType) {
99
+ const ct = contentType?.split(";")[0]?.trim().toLowerCase() ?? "";
100
+ if (ct.includes("json")) return false;
101
+ const trimmed = body.trimStart();
102
+ if (trimmed.startsWith("<")) return true;
103
+ if (ct && !ct.includes("json")) return true;
104
+ return false;
105
+ }
106
+ async function throwApiError(operation, res) {
107
+ const body = await res.text();
108
+ const contentType = res.headers.get("content-type");
109
+ const nonJson = isNonJsonResponseBody(body, contentType);
110
+ const snippet = body.length > API_ERROR_BODY_MAX ? `${body.slice(0, API_ERROR_BODY_MAX)}\u2026` : body;
111
+ const detail = nonJson ? `non-JSON response (${contentType ?? "unknown content-type"}) \u2014 the API may not have been reached. Body: ${snippet}` : snippet;
112
+ apiDebugLog(`\u274C API Error: ${res.status} - ${detail}`);
113
+ throw new import_core.SolvaPayError(`${operation} failed (${res.status}): ${detail}`, {
114
+ status: res.status,
115
+ code: nonJson ? "non_json_response" : void 0
116
+ });
117
+ }
88
118
  function createSolvaPayClient(opts) {
89
119
  const base = opts.apiBaseUrl ?? "https://api.solvapay.com";
90
120
  if (!opts.apiKey) throw new import_core.SolvaPayError("Missing apiKey");
@@ -92,12 +122,6 @@ function createSolvaPayClient(opts) {
92
122
  "Content-Type": "application/json",
93
123
  Authorization: `Bearer ${opts.apiKey}`
94
124
  };
95
- const debug = process.env.SOLVAPAY_DEBUG === "true";
96
- const log = (...args) => {
97
- if (debug) {
98
- console.log(...args);
99
- }
100
- };
101
125
  return {
102
126
  // POST: /v1/sdk/limits
103
127
  async checkLimits(params) {
@@ -108,11 +132,7 @@ function createSolvaPayClient(opts) {
108
132
  body: JSON.stringify(params)
109
133
  });
110
134
  if (!res.ok) {
111
- const error = await res.text();
112
- log(`\u274C API Error: ${res.status} - ${error}`);
113
- throw new import_core.SolvaPayError(`Check limits failed (${res.status}): ${error}`, {
114
- status: res.status
115
- });
135
+ await throwApiError("Check limits", res);
116
136
  }
117
137
  const result = await res.json();
118
138
  return result;
@@ -126,11 +146,7 @@ function createSolvaPayClient(opts) {
126
146
  body: JSON.stringify(params)
127
147
  });
128
148
  if (!res.ok) {
129
- const error = await res.text();
130
- log(`\u274C API Error: ${res.status} - ${error}`);
131
- throw new import_core.SolvaPayError(`Track usage failed (${res.status}): ${error}`, {
132
- status: res.status
133
- });
149
+ await throwApiError("Track usage", res);
134
150
  }
135
151
  return await res.json();
136
152
  },
@@ -143,11 +159,7 @@ function createSolvaPayClient(opts) {
143
159
  body: JSON.stringify(params)
144
160
  });
145
161
  if (!res.ok) {
146
- const error = await res.text();
147
- log(`\u274C API Error: ${res.status} - ${error}`);
148
- throw new import_core.SolvaPayError(`Track usage bulk failed (${res.status}): ${error}`, {
149
- status: res.status
150
- });
162
+ await throwApiError("Track usage bulk", res);
151
163
  }
152
164
  return await res.json();
153
165
  },
@@ -160,11 +172,7 @@ function createSolvaPayClient(opts) {
160
172
  body: JSON.stringify(params)
161
173
  });
162
174
  if (!res.ok) {
163
- const error = await res.text();
164
- log(`\u274C API Error: ${res.status} - ${error}`);
165
- throw new import_core.SolvaPayError(`Create customer failed (${res.status}): ${error}`, {
166
- status: res.status
167
- });
175
+ await throwApiError("Create customer", res);
168
176
  }
169
177
  const result = await res.json();
170
178
  return {
@@ -180,11 +188,7 @@ function createSolvaPayClient(opts) {
180
188
  body: JSON.stringify(params)
181
189
  });
182
190
  if (!res.ok) {
183
- const error = await res.text();
184
- log(`\u274C API Error: ${res.status} - ${error}`);
185
- throw new import_core.SolvaPayError(`Update customer failed (${res.status}): ${error}`, {
186
- status: res.status
187
- });
191
+ await throwApiError("Update customer", res);
188
192
  }
189
193
  const result = await res.json();
190
194
  return {
@@ -212,11 +216,7 @@ function createSolvaPayClient(opts) {
212
216
  headers
213
217
  });
214
218
  if (!res.ok) {
215
- const error = await res.text();
216
- log(`\u274C API Error: ${res.status} - ${error}`);
217
- throw new import_core.SolvaPayError(`Get customer failed (${res.status}): ${error}`, {
218
- status: res.status
219
- });
219
+ await throwApiError("Get customer", res);
220
220
  }
221
221
  const result = await res.json();
222
222
  let customer = result;
@@ -250,11 +250,7 @@ function createSolvaPayClient(opts) {
250
250
  body: JSON.stringify(body)
251
251
  });
252
252
  if (!res.ok) {
253
- const error = await res.text();
254
- log(`\u274C API Error: ${res.status} - ${error}`);
255
- throw new import_core.SolvaPayError(`Assign credits failed (${res.status}): ${error}`, {
256
- status: res.status
257
- });
253
+ await throwApiError("Assign credits", res);
258
254
  }
259
255
  return await res.json();
260
256
  },
@@ -266,11 +262,7 @@ function createSolvaPayClient(opts) {
266
262
  headers
267
263
  });
268
264
  if (!res.ok) {
269
- const error = await res.text();
270
- log(`\u274C API Error: ${res.status} - ${error}`);
271
- throw new import_core.SolvaPayError(`Get merchant failed (${res.status}): ${error}`, {
272
- status: res.status
273
- });
265
+ await throwApiError("Get merchant", res);
274
266
  }
275
267
  return res.json();
276
268
  },
@@ -282,11 +274,7 @@ function createSolvaPayClient(opts) {
282
274
  headers
283
275
  });
284
276
  if (!res.ok) {
285
- const error = await res.text();
286
- log(`\u274C API Error: ${res.status} - ${error}`);
287
- throw new import_core.SolvaPayError(`Get platform config failed (${res.status}): ${error}`, {
288
- status: res.status
289
- });
277
+ await throwApiError("Get platform config", res);
290
278
  }
291
279
  return res.json();
292
280
  },
@@ -298,11 +286,7 @@ function createSolvaPayClient(opts) {
298
286
  headers
299
287
  });
300
288
  if (!res.ok) {
301
- const error = await res.text();
302
- log(`\u274C API Error: ${res.status} - ${error}`);
303
- throw new import_core.SolvaPayError(`Get product failed (${res.status}): ${error}`, {
304
- status: res.status
305
- });
289
+ await throwApiError("Get product", res);
306
290
  }
307
291
  const result = await res.json();
308
292
  const data = result.data || {};
@@ -317,11 +301,7 @@ function createSolvaPayClient(opts) {
317
301
  headers
318
302
  });
319
303
  if (!res.ok) {
320
- const error = await res.text();
321
- log(`\u274C API Error: ${res.status} - ${error}`);
322
- throw new import_core.SolvaPayError(`List products failed (${res.status}): ${error}`, {
323
- status: res.status
324
- });
304
+ await throwApiError("List products", res);
325
305
  }
326
306
  const result = await res.json();
327
307
  const products = Array.isArray(result) ? result : result.products || [];
@@ -339,11 +319,7 @@ function createSolvaPayClient(opts) {
339
319
  body: JSON.stringify(params)
340
320
  });
341
321
  if (!res.ok) {
342
- const error = await res.text();
343
- log(`\u274C API Error: ${res.status} - ${error}`);
344
- throw new import_core.SolvaPayError(`Create product failed (${res.status}): ${error}`, {
345
- status: res.status
346
- });
322
+ await throwApiError("Create product", res);
347
323
  }
348
324
  const result = await res.json();
349
325
  return result;
@@ -357,11 +333,7 @@ function createSolvaPayClient(opts) {
357
333
  body: JSON.stringify(params)
358
334
  });
359
335
  if (!res.ok) {
360
- const error = await res.text();
361
- log(`\u274C API Error: ${res.status} - ${error}`);
362
- throw new import_core.SolvaPayError(`Bootstrap MCP product failed (${res.status}): ${error}`, {
363
- status: res.status
364
- });
336
+ await throwApiError("Bootstrap MCP product", res);
365
337
  }
366
338
  return await res.json();
367
339
  },
@@ -374,11 +346,7 @@ function createSolvaPayClient(opts) {
374
346
  body: JSON.stringify(params)
375
347
  });
376
348
  if (!res.ok) {
377
- const error = await res.text();
378
- log(`\u274C API Error: ${res.status} - ${error}`);
379
- throw new import_core.SolvaPayError(`Configure MCP plans failed (${res.status}): ${error}`, {
380
- status: res.status
381
- });
349
+ await throwApiError("Configure MCP plans", res);
382
350
  }
383
351
  return await res.json();
384
352
  },
@@ -390,11 +358,7 @@ function createSolvaPayClient(opts) {
390
358
  headers
391
359
  });
392
360
  if (!res.ok && res.status !== 404) {
393
- const error = await res.text();
394
- log(`\u274C API Error: ${res.status} - ${error}`);
395
- throw new import_core.SolvaPayError(`Delete product failed (${res.status}): ${error}`, {
396
- status: res.status
397
- });
361
+ await throwApiError("Delete product", res);
398
362
  }
399
363
  },
400
364
  // POST: /v1/sdk/products/{productRef}/clone
@@ -406,11 +370,7 @@ function createSolvaPayClient(opts) {
406
370
  body: JSON.stringify(overrides || {})
407
371
  });
408
372
  if (!res.ok) {
409
- const error = await res.text();
410
- log(`\u274C API Error: ${res.status} - ${error}`);
411
- throw new import_core.SolvaPayError(`Clone product failed (${res.status}): ${error}`, {
412
- status: res.status
413
- });
373
+ await throwApiError("Clone product", res);
414
374
  }
415
375
  return await res.json();
416
376
  },
@@ -422,11 +382,7 @@ function createSolvaPayClient(opts) {
422
382
  headers
423
383
  });
424
384
  if (!res.ok) {
425
- const error = await res.text();
426
- log(`\u274C API Error: ${res.status} - ${error}`);
427
- throw new import_core.SolvaPayError(`List plans failed (${res.status}): ${error}`, {
428
- status: res.status
429
- });
385
+ await throwApiError("List plans", res);
430
386
  }
431
387
  const result = await res.json();
432
388
  const plans = Array.isArray(result) ? result : result.plans || [];
@@ -451,11 +407,7 @@ function createSolvaPayClient(opts) {
451
407
  body: JSON.stringify(params)
452
408
  });
453
409
  if (!res.ok) {
454
- const error = await res.text();
455
- log(`\u274C API Error: ${res.status} - ${error}`);
456
- throw new import_core.SolvaPayError(`Create plan failed (${res.status}): ${error}`, {
457
- status: res.status
458
- });
410
+ await throwApiError("Create plan", res);
459
411
  }
460
412
  const result = await res.json();
461
413
  return result;
@@ -469,11 +421,7 @@ function createSolvaPayClient(opts) {
469
421
  body: JSON.stringify(params)
470
422
  });
471
423
  if (!res.ok) {
472
- const error = await res.text();
473
- log(`\u274C API Error: ${res.status} - ${error}`);
474
- throw new import_core.SolvaPayError(`Update plan failed (${res.status}): ${error}`, {
475
- status: res.status
476
- });
424
+ await throwApiError("Update plan", res);
477
425
  }
478
426
  return await res.json();
479
427
  },
@@ -485,11 +433,7 @@ function createSolvaPayClient(opts) {
485
433
  headers
486
434
  });
487
435
  if (!res.ok && res.status !== 404) {
488
- const error = await res.text();
489
- log(`\u274C API Error: ${res.status} - ${error}`);
490
- throw new import_core.SolvaPayError(`Delete plan failed (${res.status}): ${error}`, {
491
- status: res.status
492
- });
436
+ await throwApiError("Delete plan", res);
493
437
  }
494
438
  },
495
439
  // POST: /payment-intents
@@ -510,11 +454,7 @@ function createSolvaPayClient(opts) {
510
454
  })
511
455
  });
512
456
  if (!res.ok) {
513
- const error = await res.text();
514
- log(`\u274C API Error: ${res.status} - ${error}`);
515
- throw new import_core.SolvaPayError(`Create payment intent failed (${res.status}): ${error}`, {
516
- status: res.status
517
- });
457
+ await throwApiError("Create payment intent", res);
518
458
  }
519
459
  return await res.json();
520
460
  },
@@ -538,11 +478,7 @@ function createSolvaPayClient(opts) {
538
478
  })
539
479
  });
540
480
  if (!res.ok) {
541
- const error = await res.text();
542
- log(`\u274C API Error: ${res.status} - ${error}`);
543
- throw new import_core.SolvaPayError(`Create topup payment intent failed (${res.status}): ${error}`, {
544
- status: res.status
545
- });
481
+ await throwApiError("Create topup payment intent", res);
546
482
  }
547
483
  return await res.json();
548
484
  },
@@ -562,11 +498,7 @@ function createSolvaPayClient(opts) {
562
498
  })
563
499
  });
564
500
  if (!res.ok) {
565
- const error = await res.text();
566
- log(`\u274C API Error: ${res.status} - ${error}`);
567
- throw new import_core.SolvaPayError(`Process payment failed (${res.status}): ${error}`, {
568
- status: res.status
569
- });
501
+ await throwApiError("Process payment", res);
570
502
  }
571
503
  const result = await res.json();
572
504
  return result;
@@ -587,54 +519,20 @@ function createSolvaPayClient(opts) {
587
519
  })
588
520
  });
589
521
  if (!res.ok) {
590
- const error = await res.text();
591
- log(`\u274C API Error: ${res.status} - ${error}`);
592
- throw new import_core.SolvaPayError(
593
- `Attach business details failed (${res.status}): ${error}`,
594
- { status: res.status }
595
- );
596
- }
597
- return await res.json();
598
- },
599
- // POST: /v1/sdk/purchases/{purchaseRef}/cancel
600
- async cancelPurchase(params) {
601
- const url = `${base}/v1/sdk/purchases/${params.purchaseRef}/cancel`;
602
- const requestOptions = {
603
- method: "POST",
604
- headers
605
- };
606
- if (params.reason) {
607
- requestOptions.body = JSON.stringify({ reason: params.reason });
608
- }
609
- const res = await fetch(url, requestOptions);
610
- if (!res.ok) {
611
- const error = await res.text();
612
- log(`\u274C API Error: ${res.status} - ${error}`);
613
- if (res.status === 404) {
614
- throw new import_core.SolvaPayError(`Purchase not found: ${error}`, { status: 404 });
615
- }
616
- if (res.status === 400) {
617
- throw new import_core.SolvaPayError(
618
- `Purchase cannot be cancelled or does not belong to provider: ${error}`,
619
- { status: 400 }
620
- );
621
- }
622
- throw new import_core.SolvaPayError(`Cancel purchase failed (${res.status}): ${error}`, {
623
- status: res.status
624
- });
522
+ await throwApiError("Cancel purchase", res);
625
523
  }
626
524
  const responseText = await res.text();
627
525
  let responseData;
628
526
  try {
629
527
  responseData = JSON.parse(responseText);
630
528
  } catch (parseError) {
631
- log(`\u274C Failed to parse response as JSON: ${parseError}`);
529
+ apiDebugLog(`\u274C Failed to parse response as JSON: ${parseError}`);
632
530
  throw new import_core.SolvaPayError(
633
531
  `Invalid JSON response from cancel purchase endpoint: ${responseText.substring(0, 200)}`
634
532
  );
635
533
  }
636
534
  if (!responseData || typeof responseData !== "object") {
637
- log(`\u274C Invalid response structure: ${JSON.stringify(responseData)}`);
535
+ apiDebugLog(`\u274C Invalid response structure: ${JSON.stringify(responseData)}`);
638
536
  throw new import_core.SolvaPayError(`Invalid response structure from cancel purchase endpoint`);
639
537
  }
640
538
  let result;
@@ -646,7 +544,7 @@ function createSolvaPayClient(opts) {
646
544
  result = responseData.purchase || responseData;
647
545
  }
648
546
  if (!result || typeof result !== "object") {
649
- log(`\u274C Invalid purchase data in response. Full response:`, responseData);
547
+ apiDebugLog(`\u274C Invalid purchase data in response. Full response:`, responseData);
650
548
  throw new import_core.SolvaPayError(`Invalid purchase data in cancel purchase response`);
651
549
  }
652
550
  return result;
@@ -659,30 +557,20 @@ function createSolvaPayClient(opts) {
659
557
  headers
660
558
  });
661
559
  if (!res.ok) {
662
- const error = await res.text();
663
- log(`\u274C API Error: ${res.status} - ${error}`);
664
- if (res.status === 404) {
665
- throw new import_core.SolvaPayError(`Purchase not found: ${error}`, { status: 404 });
666
- }
667
- if (res.status === 400) {
668
- throw new import_core.SolvaPayError(`Purchase cannot be reactivated: ${error}`, { status: 400 });
669
- }
670
- throw new import_core.SolvaPayError(`Reactivate purchase failed (${res.status}): ${error}`, {
671
- status: res.status
672
- });
560
+ await throwApiError("Reactivate purchase", res);
673
561
  }
674
562
  const responseText = await res.text();
675
563
  let responseData;
676
564
  try {
677
565
  responseData = JSON.parse(responseText);
678
566
  } catch (parseError) {
679
- log(`\u274C Failed to parse response as JSON: ${parseError}`);
567
+ apiDebugLog(`\u274C Failed to parse response as JSON: ${parseError}`);
680
568
  throw new import_core.SolvaPayError(
681
569
  `Invalid JSON response from reactivate purchase endpoint: ${responseText.substring(0, 200)}`
682
570
  );
683
571
  }
684
572
  if (!responseData || typeof responseData !== "object") {
685
- log(`\u274C Invalid response structure: ${JSON.stringify(responseData)}`);
573
+ apiDebugLog(`\u274C Invalid response structure: ${JSON.stringify(responseData)}`);
686
574
  throw new import_core.SolvaPayError(`Invalid response structure from reactivate purchase endpoint`);
687
575
  }
688
576
  let result;
@@ -694,7 +582,7 @@ function createSolvaPayClient(opts) {
694
582
  result = responseData.purchase || responseData;
695
583
  }
696
584
  if (!result || typeof result !== "object") {
697
- log(`\u274C Invalid purchase data in response. Full response:`, responseData);
585
+ apiDebugLog(`\u274C Invalid purchase data in response. Full response:`, responseData);
698
586
  throw new import_core.SolvaPayError(`Invalid purchase data in reactivate purchase response`);
699
587
  }
700
588
  return result;
@@ -708,11 +596,7 @@ function createSolvaPayClient(opts) {
708
596
  body: JSON.stringify(params)
709
597
  });
710
598
  if (!res.ok) {
711
- const error = await res.text();
712
- log(`\u274C API Error: ${res.status} - ${error}`);
713
- throw new import_core.SolvaPayError(`Get user info failed (${res.status}): ${error}`, {
714
- status: res.status
715
- });
599
+ await throwApiError("Get user info", res);
716
600
  }
717
601
  return await res.json();
718
602
  },
@@ -724,11 +608,7 @@ function createSolvaPayClient(opts) {
724
608
  headers
725
609
  });
726
610
  if (!res.ok) {
727
- const error = await res.text();
728
- log(`\u274C API Error: ${res.status} - ${error}`);
729
- throw new import_core.SolvaPayError(`Get customer balance failed (${res.status}): ${error}`, {
730
- status: res.status
731
- });
611
+ await throwApiError("Get customer balance", res);
732
612
  }
733
613
  return await res.json();
734
614
  },
@@ -741,11 +621,7 @@ function createSolvaPayClient(opts) {
741
621
  body: JSON.stringify(params)
742
622
  });
743
623
  if (!res.ok) {
744
- const error = await res.text();
745
- log(`\u274C API Error: ${res.status} - ${error}`);
746
- throw new import_core.SolvaPayError(`Create checkout session failed (${res.status}): ${error}`, {
747
- status: res.status
748
- });
624
+ await throwApiError("Create checkout session", res);
749
625
  }
750
626
  const result = await res.json();
751
627
  return result;
@@ -759,11 +635,7 @@ function createSolvaPayClient(opts) {
759
635
  body: JSON.stringify(params)
760
636
  });
761
637
  if (!res.ok) {
762
- const error = await res.text();
763
- log(`\u274C API Error: ${res.status} - ${error}`);
764
- throw new import_core.SolvaPayError(`Create customer session failed (${res.status}): ${error}`, {
765
- status: res.status
766
- });
638
+ await throwApiError("Create customer session", res);
767
639
  }
768
640
  const result = await res.json();
769
641
  return result;
@@ -777,11 +649,7 @@ function createSolvaPayClient(opts) {
777
649
  body: JSON.stringify(params)
778
650
  });
779
651
  if (!res.ok) {
780
- const error = await res.text();
781
- log(`\u274C API Error: ${res.status} - ${error}`);
782
- throw new import_core.SolvaPayError(`Activate plan failed (${res.status}): ${error}`, {
783
- status: res.status
784
- });
652
+ await throwApiError("Activate plan", res);
785
653
  }
786
654
  return await res.json();
787
655
  },
@@ -790,11 +658,7 @@ function createSolvaPayClient(opts) {
790
658
  url.searchParams.set("customerRef", params.customerRef);
791
659
  const res = await fetch(url.toString(), { method: "GET", headers });
792
660
  if (!res.ok) {
793
- const error = await res.text();
794
- log(`\u274C API Error: ${res.status} - ${error}`);
795
- throw new import_core.SolvaPayError(`Get payment method failed (${res.status}): ${error}`, {
796
- status: res.status
797
- });
661
+ await throwApiError("Get payment method", res);
798
662
  }
799
663
  return await res.json();
800
664
  },
@@ -803,11 +667,7 @@ function createSolvaPayClient(opts) {
803
667
  url.searchParams.set("customerRef", params.customerRef);
804
668
  const res = await fetch(url.toString(), { method: "GET", headers });
805
669
  if (!res.ok) {
806
- const error = await res.text();
807
- log(`\u274C API Error: ${res.status} - ${error}`);
808
- throw new import_core.SolvaPayError(`Get auto-recharge failed (${res.status}): ${error}`, {
809
- status: res.status
810
- });
670
+ await throwApiError("Get auto-recharge", res);
811
671
  }
812
672
  return await res.json();
813
673
  },
@@ -818,11 +678,7 @@ function createSolvaPayClient(opts) {
818
678
  body: JSON.stringify(params)
819
679
  });
820
680
  if (!res.ok) {
821
- const error = await res.text();
822
- log(`\u274C API Error: ${res.status} - ${error}`);
823
- throw new import_core.SolvaPayError(`Save auto-recharge failed (${res.status}): ${error}`, {
824
- status: res.status
825
- });
681
+ await throwApiError("Save auto-recharge", res);
826
682
  }
827
683
  return await res.json();
828
684
  },
@@ -831,11 +687,7 @@ function createSolvaPayClient(opts) {
831
687
  url.searchParams.set("customerRef", params.customerRef);
832
688
  const res = await fetch(url.toString(), { method: "DELETE", headers });
833
689
  if (!res.ok) {
834
- const error = await res.text();
835
- log(`\u274C API Error: ${res.status} - ${error}`);
836
- throw new import_core.SolvaPayError(`Disable auto-recharge failed (${res.status}): ${error}`, {
837
- status: res.status
838
- });
690
+ await throwApiError("Disable auto-recharge", res);
839
691
  }
840
692
  return await res.json();
841
693
  },
@@ -849,11 +701,7 @@ function createSolvaPayClient(opts) {
849
701
  }
850
702
  const res = await fetch(url.toString(), { method: "GET", headers });
851
703
  if (!res.ok) {
852
- const error = await res.text();
853
- log(`\u274C API Error: ${res.status} - ${error}`);
854
- throw new import_core.SolvaPayError(`List purchases failed (${res.status}): ${error}`, {
855
- status: res.status
856
- });
704
+ await throwApiError("List purchases", res);
857
705
  }
858
706
  const data = await res.json();
859
707
  return { purchases: data.purchases ?? [] };
@@ -864,11 +712,7 @@ function createSolvaPayClient(opts) {
864
712
  if (params.limit !== void 0) url.searchParams.set("limit", String(params.limit));
865
713
  const res = await fetch(url.toString(), { method: "GET", headers });
866
714
  if (!res.ok) {
867
- const error = await res.text();
868
- log(`\u274C API Error: ${res.status} - ${error}`);
869
- throw new import_core.SolvaPayError(`Get credit activity failed (${res.status}): ${error}`, {
870
- status: res.status
871
- });
715
+ await throwApiError("Get credit activity", res);
872
716
  }
873
717
  return await res.json();
874
718
  }
@@ -876,46 +720,92 @@ function createSolvaPayClient(opts) {
876
720
  }
877
721
 
878
722
  // src/paywall-state.ts
723
+ var import_core2 = require("@solvapay/core");
879
724
  var CHECKOUT_SESSION_TTL_MINUTES = 15;
880
725
  var DOCS_HINT = "See docs://solvapay/overview.md.";
726
+ function creditSignals(limits) {
727
+ if (!limits) return { isCreditBased: false };
728
+ const creditBalance = limits.balance?.creditBalance ?? limits.creditBalance;
729
+ const creditsPerCall = limits.balance?.creditsPerUnit ?? limits.creditsPerUnit;
730
+ const isCreditBased = creditBalance !== void 0 || creditsPerCall !== void 0;
731
+ const shortfallCredits = creditBalance !== void 0 && creditsPerCall !== void 0 ? Math.max(0, creditsPerCall - creditBalance) : void 0;
732
+ let remainingCalls;
733
+ if (limits.balance?.remainingUnits !== void 0) {
734
+ remainingCalls = limits.balance.remainingUnits;
735
+ } else if (creditBalance !== void 0 && creditsPerCall !== void 0 && creditsPerCall > 0) {
736
+ remainingCalls = Math.floor(creditBalance / creditsPerCall);
737
+ } else if (limits.remaining >= 0) {
738
+ remainingCalls = limits.remaining;
739
+ }
740
+ return { creditBalance, creditsPerCall, shortfallCredits, remainingCalls, isCreditBased };
741
+ }
742
+ function nextActionFor(state) {
743
+ switch (state.kind) {
744
+ case "activation_required":
745
+ return "activate";
746
+ case "topup_required":
747
+ return "topup";
748
+ case "upgrade_required":
749
+ case "limit_reached":
750
+ return "checkout";
751
+ case "reactivation_required":
752
+ return "account";
753
+ }
754
+ }
755
+ function activePlanRefOf(limits) {
756
+ const ref = limits.planRef ?? limits.plan;
757
+ return ref && ref.length > 0 ? ref : void 0;
758
+ }
881
759
  function classifyPaywallState(limits) {
882
760
  if (!limits) return { kind: "upgrade_required" };
883
- if (limits.activationRequired === true) {
761
+ if (limits.activationRequired === true || limits.paywallReason === "activation_required") {
884
762
  return { kind: "activation_required" };
885
763
  }
764
+ if (limits.paywallReason === "topup_required") {
765
+ return { kind: "topup_required" };
766
+ }
886
767
  if (limits.needsTopUp === true) {
887
768
  return { kind: "topup_required" };
888
769
  }
889
770
  if (limits.needsUpgrade === true) {
890
771
  return { kind: "upgrade_required" };
891
772
  }
892
- const activePlan = limits.plans?.find((p) => p.reference === limits.plan);
893
- const isUsageBased = activePlan?.type === "usage-based" || limits.balance !== void 0;
894
- const creditBalance = limits.balance?.creditBalance ?? limits.creditBalance;
895
- if (isUsageBased) {
896
- if (creditBalance === 0) return { kind: "topup_required" };
897
- if (creditBalance === void 0 && limits.remaining === 0) {
773
+ const signals = creditSignals(limits);
774
+ if (signals.isCreditBased) {
775
+ if (signals.creditBalance !== void 0 && signals.creditsPerCall !== void 0 && signals.creditBalance < signals.creditsPerCall) {
776
+ return { kind: "topup_required" };
777
+ }
778
+ if (signals.creditBalance === 0) return { kind: "topup_required" };
779
+ if (signals.creditsPerCall === void 0 && limits.remaining === 0) {
898
780
  return { kind: "topup_required" };
899
781
  }
900
782
  }
901
- if (limits.plan.length > 0 && limits.remaining <= 0) {
783
+ const activeRef = activePlanRefOf(limits);
784
+ if ((limits.purchaseRef || activeRef) && limits.remaining <= 0) {
902
785
  return { kind: "limit_reached" };
903
786
  }
787
+ if (signals.isCreditBased) return { kind: "topup_required" };
788
+ if (limits.purchaseRef) return { kind: "limit_reached" };
904
789
  return { kind: "upgrade_required" };
905
790
  }
906
791
  function formatMinor(amountMinor, currency) {
907
- const major = amountMinor / 100;
792
+ const divisor = (0, import_core2.minorUnitsPerMajor)(currency);
793
+ const major = amountMinor / divisor;
794
+ const fractionDigits = divisor === 1 ? 0 : 2;
908
795
  try {
909
796
  return new Intl.NumberFormat("en-US", {
910
797
  style: "currency",
911
798
  currency: currency.toUpperCase(),
912
- minimumFractionDigits: 2,
913
- maximumFractionDigits: 2
799
+ minimumFractionDigits: fractionDigits,
800
+ maximumFractionDigits: fractionDigits
914
801
  }).format(major);
915
802
  } catch {
916
- return `${currency.toUpperCase()} ${major.toFixed(2)}`;
803
+ return `${currency.toUpperCase()} ${divisor === 1 ? String(Math.round(major)) : major.toFixed(2)}`;
917
804
  }
918
805
  }
806
+ function formatCredits(value) {
807
+ return value.toLocaleString("en-US");
808
+ }
919
809
  function meterLabel(gate) {
920
810
  if (!gate.meterName) return "units";
921
811
  return gate.meterName.replace(/_/g, " ");
@@ -923,6 +813,14 @@ function meterLabel(gate) {
923
813
  function namedCheckoutMarkdown(url) {
924
814
  return `[Open checkout](${url})`;
925
815
  }
816
+ function linkLabel(name) {
817
+ return name.replace(/([[\]])/g, "\\$1");
818
+ }
819
+ function planLadder(gate) {
820
+ 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);
821
+ if (linkable.length === 0) return null;
822
+ return linkable.map((p) => `[${linkLabel(p.name ?? p.reference)}](${p.checkoutUrl})`).join(" \xB7 ");
823
+ }
926
824
  var VIEWER_TOOL = "account";
927
825
  function callViewer(view) {
928
826
  return view ? `call the \`${VIEWER_TOOL}\` tool with view: '${view}'` : `call the \`${VIEWER_TOOL}\` tool`;
@@ -933,25 +831,57 @@ function recoverClause(url, verb, view) {
933
831
  }
934
832
  return ` ${callViewer(view).replace(/^c/, "C")}.`;
935
833
  }
834
+ function hasActivePlan(gate) {
835
+ return Boolean(gate.purchaseRef || gate.planRef && gate.planRef.length > 0);
836
+ }
837
+ function autoRechargeDisabled(gate) {
838
+ return gate.autoRecharge?.enabled === false;
839
+ }
936
840
  function buildGateMessage(state, gate) {
937
841
  const url = gate.checkoutUrl && gate.checkoutUrl.length > 0 ? gate.checkoutUrl : null;
842
+ const ladder = planLadder(gate);
938
843
  switch (state.kind) {
939
844
  case "limit_reached": {
940
845
  const included = gate.included;
941
846
  const price = gate.unitPriceMinor != null && gate.currency ? formatMinor(gate.unitPriceMinor, gate.currency) : null;
942
847
  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.`;
943
848
  const nextLine = price ? ` The next call is ${price}.` : "";
944
- return `${usedLine}${nextLine}${recoverClause(url, "continue", "checkout")} ${DOCS_HINT}`;
849
+ const planName = gate.planName ?? "This plan";
850
+ 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.` : "";
851
+ const switchLine = ladder ? ` Or switch plan: ${ladder}.` : recoverClause(url, "continue", "checkout");
852
+ return `${usedLine}${nextLine}${antiTrap}${switchLine} ${DOCS_HINT}`;
945
853
  }
946
854
  case "activation_required":
947
855
  return `Your plan needs activation.${recoverClause(url, "activate", "checkout")} Or call \`activate_plan\` with a \`planRef\`. ${DOCS_HINT}`;
948
856
  case "topup_required": {
949
- const currency = gate.currency ?? gate.balance?.currency ?? "USD";
950
- const presets = [1e3, 2500, 5e3, 1e4].map((m) => formatMinor(m, currency)).join(" \xB7 ");
951
- return `You're out of credits. Top up first (${presets}).${recoverClause(url, "add credits", "topup")} ${DOCS_HINT}`;
952
- }
953
- case "upgrade_required":
857
+ const balance = gate.creditBalance;
858
+ const cost = gate.creditsPerCall;
859
+ const shortfall = gate.shortfallCredits;
860
+ let lead;
861
+ if (balance !== void 0 && cost !== void 0 && shortfall !== void 0) {
862
+ lead = `Out of credits for this call. Balance ${formatCredits(balance)} credits; this call costs ${formatCredits(cost)} credits \u2014 ${formatCredits(shortfall)} short.`;
863
+ } else {
864
+ lead = "Included usage is exhausted.";
865
+ }
866
+ const topup = recoverClause(url, "add credits", "topup");
867
+ const auto = autoRechargeDisabled(gate) ? " Auto-recharge is off \u2014 turn it on from the account tool to avoid this next time." : "";
868
+ const switchLine = ladder ? ` Or switch plan: ${ladder}.` : "";
869
+ return `${lead}${topup}${auto}${switchLine} ${DOCS_HINT}`;
870
+ }
871
+ case "upgrade_required": {
872
+ if (hasActivePlan(gate)) {
873
+ const planName = gate.planName ?? "This plan";
874
+ const lead = `${planName} is active but its included usage is exhausted, and the automatic switch to the next plan did not complete.`;
875
+ if (ladder) {
876
+ return `${lead} Switch here: ${ladder}. ${DOCS_HINT}`;
877
+ }
878
+ return `${lead}${recoverClause(url, "switch plan", "checkout")} ${DOCS_HINT}`;
879
+ }
880
+ if (ladder) {
881
+ 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}`;
882
+ }
954
883
  return `You don't have an active plan for this tool.${recoverClause(url, "pick a plan", "checkout")} ${DOCS_HINT}`;
884
+ }
955
885
  case "reactivation_required":
956
886
  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}`;
957
887
  }
@@ -959,11 +889,18 @@ function buildGateMessage(state, gate) {
959
889
  function buildNudgeMessage(state, limits) {
960
890
  const url = limits?.checkoutUrl && limits.checkoutUrl.length > 0 ? limits.checkoutUrl : null;
961
891
  const visitClause = url ? `, or ${namedCheckoutMarkdown(url)}` : "";
892
+ const remaining = creditSignals(limits).remainingCalls;
962
893
  switch (state.kind) {
963
894
  case "topup_required":
895
+ if (remaining === 0) {
896
+ return `Heads up \u2014 0 calls left \u2014 the next call needs a top-up. ${callViewer("topup").replace(/^c/, "C")} to add more${visitClause}.`;
897
+ }
964
898
  return `Heads up \u2014 running low on credits. ${callViewer("topup").replace(/^c/, "C")} to add more${visitClause}.`;
965
899
  case "upgrade_required":
966
900
  case "limit_reached":
901
+ if (remaining === 0) {
902
+ return `Heads up \u2014 0 calls left \u2014 the next call needs a top-up. ${callViewer("checkout").replace(/^c/, "C")} for more headroom${visitClause}.`;
903
+ }
967
904
  return `Heads up \u2014 approaching your plan's limit this period. ${callViewer("checkout").replace(/^c/, "C")} for more headroom${visitClause}.`;
968
905
  case "activation_required":
969
906
  return `Heads up \u2014 this plan still needs activation. Call the \`activate_plan\` tool with a \`planRef\`${visitClause}.`;
@@ -979,11 +916,23 @@ function allPaidPlansArePayg(plans) {
979
916
  if (paidPlans.length === 0) return false;
980
917
  return paidPlans.every((p) => p.type === "usage-based" || p.type === "hybrid");
981
918
  }
919
+ function activePlanRefOf2(limits) {
920
+ const ref = limits.planRef ?? limits.plan;
921
+ return ref && ref.length > 0 ? ref : void 0;
922
+ }
982
923
  function activePlanOf(limits) {
983
- if (!limits.plan) return void 0;
984
- return limits.plans?.find((p) => p.reference === limits.plan);
924
+ const ref = activePlanRefOf2(limits);
925
+ if (!ref) return void 0;
926
+ return limits.plans?.find((p) => p.reference === ref);
985
927
  }
986
928
  function includedFromLimits(limits) {
929
+ if (limits.used !== void 0 && limits.limit !== void 0) {
930
+ return {
931
+ total: limits.limit,
932
+ used: limits.used,
933
+ remaining: limits.remaining
934
+ };
935
+ }
987
936
  const total = activePlanOf(limits)?.freeUnits;
988
937
  if (total == null || total === 0) return void 0;
989
938
  const remaining = limits.remaining;
@@ -993,24 +942,49 @@ function includedFromLimits(limits) {
993
942
  remaining
994
943
  };
995
944
  }
996
- function recoveryFields(limits) {
945
+ function recoveryLinks(limits) {
946
+ const links = {};
947
+ if (limits.checkoutUrl) {
948
+ if (limits.checkoutUrl.includes("/topup")) {
949
+ links.topup = limits.checkoutUrl;
950
+ } else {
951
+ links.checkout = limits.checkoutUrl;
952
+ }
953
+ }
954
+ if (limits.confirmationUrl) {
955
+ links.manage = limits.confirmationUrl;
956
+ }
957
+ return Object.keys(links).length > 0 ? links : void 0;
958
+ }
959
+ function recoveryFields(limits, state) {
997
960
  const plan = activePlanOf(limits);
998
961
  const included = includedFromLimits(limits);
999
- const creditBalance = limits.balance?.creditBalance ?? limits.creditBalance;
962
+ const signals = creditSignals(limits);
963
+ const planRef = activePlanRefOf2(limits);
964
+ const links = recoveryLinks(limits);
1000
965
  return {
1001
- ...limits.plan ? { planRef: limits.plan } : {},
966
+ ...planRef ? { planRef } : {},
967
+ ...limits.planName !== void 0 ? { planName: limits.planName } : {},
1002
968
  ...limits.plans !== void 0 ? { plans: limits.plans } : {},
1003
969
  ...limits.meterName !== void 0 ? { meterName: limits.meterName } : {},
1004
970
  ...plan?.perUnitChargeMinor != null ? { unitPriceMinor: plan.perUnitChargeMinor, currency: plan.currency } : limits.currency ? { currency: limits.currency } : {},
1005
971
  ...included ? { included } : {},
1006
- ...creditBalance !== void 0 ? { creditBalance } : {}
972
+ ...signals.creditBalance !== void 0 ? { creditBalance: signals.creditBalance } : {},
973
+ reason: state.kind,
974
+ nextAction: nextActionFor(state),
975
+ ...signals.creditsPerCall !== void 0 ? { creditsPerCall: signals.creditsPerCall } : {},
976
+ ...signals.shortfallCredits !== void 0 ? { shortfallCredits: signals.shortfallCredits } : {},
977
+ ...signals.remainingCalls !== void 0 ? { remainingCalls: signals.remainingCalls } : {},
978
+ ...limits.purchaseRef !== void 0 ? { purchaseRef: limits.purchaseRef } : {},
979
+ ...limits.autoRecharge !== void 0 ? { autoRecharge: limits.autoRecharge } : {},
980
+ ...links ? { links } : {}
1007
981
  };
1008
982
  }
1009
983
  function buildPaywallGate(productRef, limits) {
1010
984
  const checkoutUrl = limits.checkoutUrl;
1011
- const state = classifyPaywallState({ ...limits, plan: limits.plan ?? "" });
985
+ const state = classifyPaywallState(limits);
1012
986
  const useActivationForTopup = !limits.activationRequired && state.kind === "topup_required" && allPaidPlansArePayg(limits.plans);
1013
- const recovery = recoveryFields(limits);
987
+ const recovery = recoveryFields(limits, state);
1014
988
  const preMessage = limits.activationRequired || useActivationForTopup ? {
1015
989
  kind: "activation_required",
1016
990
  product: productRef,
@@ -1033,7 +1007,7 @@ function buildPaywallGate(productRef, limits) {
1033
1007
  }
1034
1008
 
1035
1009
  // src/resolve-product-ref.ts
1036
- var import_core2 = require("@solvapay/core");
1010
+ var import_core3 = require("@solvapay/core");
1037
1011
  var MISSING_PRODUCT_REF_MESSAGE = "No product ref resolved. Pass productRef to payable() or set SOLVAPAY_PRODUCT_REF. Run `npx solvapay doctor` to diagnose.";
1038
1012
  function readEnvProductRef() {
1039
1013
  if (typeof process === "undefined") return void 0;
@@ -1046,7 +1020,7 @@ function resolveProductRef(explicit) {
1046
1020
  function requireProductRef(explicit) {
1047
1021
  const resolved = resolveProductRef(explicit);
1048
1022
  if (!resolved) {
1049
- throw new import_core2.SolvaPayError(MISSING_PRODUCT_REF_MESSAGE);
1023
+ throw new import_core3.SolvaPayError(MISSING_PRODUCT_REF_MESSAGE);
1050
1024
  }
1051
1025
  return resolved;
1052
1026
  }
@@ -2010,7 +1984,7 @@ var McpAdapter = class {
2010
1984
  };
2011
1985
 
2012
1986
  // src/factory.ts
2013
- var import_core3 = require("@solvapay/core");
1987
+ var import_core4 = require("@solvapay/core");
2014
1988
 
2015
1989
  // src/virtual-tools.ts
2016
1990
  var TOOL_GET_USER_INFO = {
@@ -2252,7 +2226,7 @@ function registerVirtualToolsMcpImpl(server, apiClient, options) {
2252
2226
  function createSolvaPay(config) {
2253
2227
  let resolvedConfig;
2254
2228
  if (!config) {
2255
- const envConfig = (0, import_core3.getSolvaPayConfig)();
2229
+ const envConfig = (0, import_core4.getSolvaPayConfig)();
2256
2230
  resolvedConfig = {
2257
2231
  apiKey: envConfig.apiKey,
2258
2232
  apiBaseUrl: envConfig.apiBaseUrl
@@ -2285,25 +2259,25 @@ function createSolvaPay(config) {
2285
2259
  },
2286
2260
  createPaymentIntent(params) {
2287
2261
  if (!apiClient.createPaymentIntent) {
2288
- throw new import_core3.SolvaPayError("createPaymentIntent is not available on this API client");
2262
+ throw new import_core4.SolvaPayError("createPaymentIntent is not available on this API client");
2289
2263
  }
2290
2264
  return apiClient.createPaymentIntent(params);
2291
2265
  },
2292
2266
  createTopupPaymentIntent(params) {
2293
2267
  if (!apiClient.createTopupPaymentIntent) {
2294
- throw new import_core3.SolvaPayError("createTopupPaymentIntent is not available on this API client");
2268
+ throw new import_core4.SolvaPayError("createTopupPaymentIntent is not available on this API client");
2295
2269
  }
2296
2270
  return apiClient.createTopupPaymentIntent(params);
2297
2271
  },
2298
2272
  processPaymentIntent(params) {
2299
2273
  if (!apiClient.processPaymentIntent) {
2300
- throw new import_core3.SolvaPayError("processPaymentIntent is not available on this API client");
2274
+ throw new import_core4.SolvaPayError("processPaymentIntent is not available on this API client");
2301
2275
  }
2302
2276
  return apiClient.processPaymentIntent(params);
2303
2277
  },
2304
2278
  attachBusinessDetails(params) {
2305
2279
  if (!apiClient.attachBusinessDetails) {
2306
- throw new import_core3.SolvaPayError("attachBusinessDetails is not available on this API client");
2280
+ throw new import_core4.SolvaPayError("attachBusinessDetails is not available on this API client");
2307
2281
  }
2308
2282
  return apiClient.attachBusinessDetails(params);
2309
2283
  },
@@ -2315,13 +2289,13 @@ function createSolvaPay(config) {
2315
2289
  },
2316
2290
  trackUsageBulk(params) {
2317
2291
  if (!apiClient.trackUsageBulk) {
2318
- throw new import_core3.SolvaPayError("trackUsageBulk is not available on this API client");
2292
+ throw new import_core4.SolvaPayError("trackUsageBulk is not available on this API client");
2319
2293
  }
2320
2294
  return apiClient.trackUsageBulk(params);
2321
2295
  },
2322
2296
  createCustomer(params) {
2323
2297
  if (!apiClient.createCustomer) {
2324
- throw new import_core3.SolvaPayError("createCustomer is not available on this API client");
2298
+ throw new import_core4.SolvaPayError("createCustomer is not available on this API client");
2325
2299
  }
2326
2300
  return apiClient.createCustomer({ ...params, metadata: params.metadata ?? {} });
2327
2301
  },
@@ -2330,13 +2304,13 @@ function createSolvaPay(config) {
2330
2304
  },
2331
2305
  assignCredits(params) {
2332
2306
  if (!apiClient.assignCredits) {
2333
- throw new import_core3.SolvaPayError("assignCredits is not available on this API client");
2307
+ throw new import_core4.SolvaPayError("assignCredits is not available on this API client");
2334
2308
  }
2335
2309
  return apiClient.assignCredits(params);
2336
2310
  },
2337
2311
  getCustomerBalance(params) {
2338
2312
  if (!apiClient.getCustomerBalance) {
2339
- throw new import_core3.SolvaPayError("getCustomerBalance is not available on this API client");
2313
+ throw new import_core4.SolvaPayError("getCustomerBalance is not available on this API client");
2340
2314
  }
2341
2315
  return apiClient.getCustomerBalance(params);
2342
2316
  },
@@ -2352,19 +2326,19 @@ function createSolvaPay(config) {
2352
2326
  },
2353
2327
  activatePlan(params) {
2354
2328
  if (!apiClient.activatePlan) {
2355
- throw new import_core3.SolvaPayError("activatePlan is not available on this API client");
2329
+ throw new import_core4.SolvaPayError("activatePlan is not available on this API client");
2356
2330
  }
2357
2331
  return apiClient.activatePlan(params);
2358
2332
  },
2359
2333
  bootstrapMcpProduct(params) {
2360
2334
  if (!apiClient.bootstrapMcpProduct) {
2361
- throw new import_core3.SolvaPayError("bootstrapMcpProduct is not available on this API client");
2335
+ throw new import_core4.SolvaPayError("bootstrapMcpProduct is not available on this API client");
2362
2336
  }
2363
2337
  return apiClient.bootstrapMcpProduct(params);
2364
2338
  },
2365
2339
  configureMcpPlans(productRef, params) {
2366
2340
  if (!apiClient.configureMcpPlans) {
2367
- throw new import_core3.SolvaPayError("configureMcpPlans is not available on this API client");
2341
+ throw new import_core4.SolvaPayError("configureMcpPlans is not available on this API client");
2368
2342
  }
2369
2343
  return apiClient.configureMcpPlans(productRef, params);
2370
2344
  },
@@ -2515,7 +2489,7 @@ async function resolveCustomerRefFromRequest(req, options) {
2515
2489
  }
2516
2490
 
2517
2491
  // src/verify-product-configuration.ts
2518
- var import_core4 = require("@solvapay/core");
2492
+ var import_core5 = require("@solvapay/core");
2519
2493
  async function verifyProductConfiguration(options) {
2520
2494
  const { apiClient, productRef } = options;
2521
2495
  const apiBaseUrl = options.apiBaseUrl ?? "(unknown API base URL)";
@@ -2526,7 +2500,7 @@ async function verifyProductConfiguration(options) {
2526
2500
  }
2527
2501
  try {
2528
2502
  const product = await apiClient.getProduct(productRef);
2529
- const readiness = (0, import_core4.evaluateProductReadiness)({
2503
+ const readiness = (0, import_core5.evaluateProductReadiness)({
2530
2504
  status: product.status,
2531
2505
  plans: product.plans
2532
2506
  });
@@ -2539,7 +2513,13 @@ async function verifyProductConfiguration(options) {
2539
2513
  issues: readiness.issues
2540
2514
  };
2541
2515
  } catch (error) {
2542
- const status = error instanceof import_core4.SolvaPayError ? error.status : void 0;
2516
+ const status = error instanceof import_core5.SolvaPayError ? error.status : void 0;
2517
+ const code = error instanceof import_core5.SolvaPayError ? error.code : void 0;
2518
+ if (status === 404 && code === "non_json_response") {
2519
+ throw new Error(
2520
+ `Could not reach ${apiBaseUrl} while verifying SOLVAPAY_PRODUCT_REF "${productRef}": the server returned a non-JSON response (often an offline ngrok tunnel or proxy error page). Check SOLVAPAY_API_BASE_URL and that the API tunnel is running.`
2521
+ );
2522
+ }
2543
2523
  if (status === 404) {
2544
2524
  throw new Error(
2545
2525
  `SOLVAPAY_PRODUCT_REF "${productRef}" does not exist on ${apiBaseUrl}. OAuth dynamic client registration resolves the provider from this ref, so every connection attempt would fail with a 400 "Invalid identifier" and no MCP host could connect. Point SOLVAPAY_PRODUCT_REF at a product that exists on this account (SolvaPay Console \u2192 Products, or \`npx solvapay init\` / \`npx solvapay doctor\`), and check SOLVAPAY_API_BASE_URL is the environment you created the product in.`
@@ -2558,6 +2538,15 @@ async function verifyProductConfiguration(options) {
2558
2538
  }
2559
2539
 
2560
2540
  // src/types/paywall.ts
2541
+ var PAYWALL_REASONS = [
2542
+ "activation_required",
2543
+ "topup_required",
2544
+ "payment_required",
2545
+ "upgrade_required",
2546
+ "limit_reached",
2547
+ "reactivation_required"
2548
+ ];
2549
+ var PAYWALL_NEXT_ACTIONS = ["topup", "checkout", "activate", "account"];
2561
2550
  function isPaywallStructuredContent(value) {
2562
2551
  if (typeof value !== "object" || value === null || !("kind" in value)) {
2563
2552
  return false;
@@ -2575,6 +2564,7 @@ var includedSchema = import_zod.z.object({
2575
2564
  });
2576
2565
  var recoveryFields2 = {
2577
2566
  planRef: import_zod.z.string().optional(),
2567
+ planName: import_zod.z.string().optional(),
2578
2568
  plans: import_zod.z.array(import_zod.z.record(import_zod.z.string(), import_zod.z.unknown())).optional(),
2579
2569
  meterName: import_zod.z.string().optional(),
2580
2570
  unitPriceMinor: import_zod.z.number().optional(),
@@ -2582,7 +2572,23 @@ var recoveryFields2 = {
2582
2572
  included: includedSchema.optional(),
2583
2573
  creditBalance: import_zod.z.number().optional(),
2584
2574
  balance: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).optional(),
2585
- productDetails: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).optional()
2575
+ productDetails: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).optional(),
2576
+ reason: import_zod.z.enum(PAYWALL_REASONS).optional(),
2577
+ nextAction: import_zod.z.enum(PAYWALL_NEXT_ACTIONS).optional(),
2578
+ creditsPerCall: import_zod.z.number().optional(),
2579
+ shortfallCredits: import_zod.z.number().optional(),
2580
+ remainingCalls: import_zod.z.number().optional(),
2581
+ purchaseRef: import_zod.z.string().optional(),
2582
+ planStatus: import_zod.z.string().optional(),
2583
+ autoRecharge: import_zod.z.object({
2584
+ enabled: import_zod.z.boolean(),
2585
+ status: import_zod.z.string().optional()
2586
+ }).optional(),
2587
+ links: import_zod.z.object({
2588
+ topup: import_zod.z.string().optional(),
2589
+ checkout: import_zod.z.string().optional(),
2590
+ manage: import_zod.z.string().optional()
2591
+ }).optional()
2586
2592
  };
2587
2593
  var PaywallStructuredContentSchema = import_zod.z.discriminatedUnion("kind", [
2588
2594
  import_zod.z.object({
@@ -2603,13 +2609,13 @@ var PaywallStructuredContentSchema = import_zod.z.discriminatedUnion("kind", [
2603
2609
  ]);
2604
2610
 
2605
2611
  // src/helpers/error.ts
2606
- var import_core5 = require("@solvapay/core");
2612
+ var import_core6 = require("@solvapay/core");
2607
2613
  function isErrorResult(result) {
2608
2614
  return typeof result === "object" && result !== null && "error" in result && "status" in result;
2609
2615
  }
2610
2616
  function handleRouteError(error, operationName, defaultMessage) {
2611
2617
  console.error(`[${operationName}] Error:`, error);
2612
- if (error instanceof import_core5.SolvaPayError) {
2618
+ if (error instanceof import_core6.SolvaPayError) {
2613
2619
  const errorMessage2 = error.message;
2614
2620
  return {
2615
2621
  error: errorMessage2,
@@ -2797,7 +2803,7 @@ async function getCustomerBalanceCore(request, options = {}) {
2797
2803
  }
2798
2804
 
2799
2805
  // src/helpers/payment.ts
2800
- var import_core6 = require("@solvapay/core");
2806
+ var import_core7 = require("@solvapay/core");
2801
2807
 
2802
2808
  // src/helpers/balance-poll.ts
2803
2809
  var TOPUP_BALANCE_POLL_DELAYS_MS = [500, 1e3, 2e3, 4e3];
@@ -2939,7 +2945,7 @@ async function attachBusinessDetailsCore(request, body, options = {}) {
2939
2945
  status: 400
2940
2946
  };
2941
2947
  }
2942
- const validation = (0, import_core6.validateBusinessDetails)({
2948
+ const validation = (0, import_core7.validateBusinessDetails)({
2943
2949
  isBusiness: body.isBusiness,
2944
2950
  businessName: body.businessName,
2945
2951
  country: body.country,
@@ -3102,7 +3108,7 @@ async function createCustomerSessionCore(request, options = {}) {
3102
3108
  }
3103
3109
 
3104
3110
  // src/helpers/renewal.ts
3105
- var import_core7 = require("@solvapay/core");
3111
+ var import_core8 = require("@solvapay/core");
3106
3112
  async function cancelPurchaseCore(request, body, options = {}) {
3107
3113
  try {
3108
3114
  if (!body.purchaseRef) {
@@ -3148,7 +3154,7 @@ async function cancelPurchaseCore(request, body, options = {}) {
3148
3154
  await new Promise((resolve) => setTimeout(resolve, 500));
3149
3155
  return cancelledPurchase;
3150
3156
  } catch (error) {
3151
- if (error instanceof import_core7.SolvaPayError) {
3157
+ if (error instanceof import_core8.SolvaPayError) {
3152
3158
  const errorMessage = error.message;
3153
3159
  if (errorMessage.includes("not found")) {
3154
3160
  return {
@@ -3216,7 +3222,7 @@ async function reactivatePurchaseCore(request, body, options = {}) {
3216
3222
  await new Promise((resolve) => setTimeout(resolve, 500));
3217
3223
  return reactivatedPurchase;
3218
3224
  } catch (error) {
3219
- if (error instanceof import_core7.SolvaPayError) {
3225
+ if (error instanceof import_core8.SolvaPayError) {
3220
3226
  const errorMessage = error.message;
3221
3227
  if (errorMessage.includes("not found")) {
3222
3228
  return {
@@ -3386,7 +3392,7 @@ async function getHistoryCore(request, input, options = {}) {
3386
3392
  }
3387
3393
 
3388
3394
  // src/helpers/plans.ts
3389
- var import_core8 = require("@solvapay/core");
3395
+ var import_core9 = require("@solvapay/core");
3390
3396
  async function listPlansCore(request, options = {}) {
3391
3397
  try {
3392
3398
  const url = new URL(request.url);
@@ -3398,7 +3404,7 @@ async function listPlansCore(request, options = {}) {
3398
3404
  };
3399
3405
  }
3400
3406
  const apiClient = options.solvaPay?.apiClient ?? (() => {
3401
- const config = (0, import_core8.getSolvaPayConfig)();
3407
+ const config = (0, import_core9.getSolvaPayConfig)();
3402
3408
  if (!config.apiKey) return null;
3403
3409
  return createSolvaPayClient({
3404
3410
  apiKey: config.apiKey,
@@ -3461,11 +3467,11 @@ async function checkLimitsCore(request, options = {}) {
3461
3467
  }
3462
3468
 
3463
3469
  // src/helpers/merchant.ts
3464
- var import_core9 = require("@solvapay/core");
3470
+ var import_core10 = require("@solvapay/core");
3465
3471
  async function getMerchantCore(_request, options = {}) {
3466
3472
  try {
3467
3473
  const apiClient = options.solvaPay?.apiClient ?? (() => {
3468
- const config = (0, import_core9.getSolvaPayConfig)();
3474
+ const config = (0, import_core10.getSolvaPayConfig)();
3469
3475
  if (!config.apiKey) return null;
3470
3476
  return createSolvaPayClient({
3471
3477
  apiKey: config.apiKey,
@@ -3492,7 +3498,7 @@ async function getMerchantCore(_request, options = {}) {
3492
3498
  }
3493
3499
 
3494
3500
  // src/helpers/product.ts
3495
- var import_core10 = require("@solvapay/core");
3501
+ var import_core11 = require("@solvapay/core");
3496
3502
  async function getProductCore(request, options = {}) {
3497
3503
  try {
3498
3504
  const url = new URL(request.url);
@@ -3504,7 +3510,7 @@ async function getProductCore(request, options = {}) {
3504
3510
  };
3505
3511
  }
3506
3512
  const apiClient = options.solvaPay?.apiClient ?? (() => {
3507
- const config = (0, import_core10.getSolvaPayConfig)();
3513
+ const config = (0, import_core11.getSolvaPayConfig)();
3508
3514
  if (!config.apiKey) return null;
3509
3515
  return createSolvaPayClient({
3510
3516
  apiKey: config.apiKey,
@@ -3587,7 +3593,7 @@ async function checkPurchaseCore(request, options = {}) {
3587
3593
  }
3588
3594
 
3589
3595
  // src/helpers/usage.ts
3590
- var import_core11 = require("@solvapay/core");
3596
+ var import_core12 = require("@solvapay/core");
3591
3597
  function deriveUsageSnapshot(input) {
3592
3598
  const period = {
3593
3599
  ...input.periodStart ? { periodStart: input.periodStart } : {},
@@ -3637,7 +3643,7 @@ async function getUsageCore(request, options = {}) {
3637
3643
  if ("limits" in options) {
3638
3644
  return deriveUsageSnapshot({ used, ...period, limits: options.limits ?? null });
3639
3645
  }
3640
- const usageCounted = (0, import_core11.countsUsage)(activePurchase.planSnapshot) || activePurchase.planSnapshot?.isMetered === true;
3646
+ const usageCounted = (0, import_core12.countsUsage)(activePurchase.planSnapshot) || activePurchase.planSnapshot?.isMetered === true;
3641
3647
  if (!usageCounted || !activePurchase.productRef) {
3642
3648
  return deriveUsageSnapshot({ used, ...period, limits: null });
3643
3649
  }
@@ -3682,34 +3688,34 @@ function verifyWebhook({
3682
3688
  secret
3683
3689
  }) {
3684
3690
  const toleranceSec = 300;
3685
- if (!signature) throw new import_core12.SolvaPayError("Missing webhook signature");
3691
+ if (!signature) throw new import_core13.SolvaPayError("Missing webhook signature");
3686
3692
  const parts = signature.split(",");
3687
3693
  const tPart = parts.find((p) => p.startsWith("t="));
3688
3694
  const v1Part = parts.find((p) => p.startsWith("v1="));
3689
3695
  if (!tPart || !v1Part) {
3690
- throw new import_core12.SolvaPayError("Malformed webhook signature");
3696
+ throw new import_core13.SolvaPayError("Malformed webhook signature");
3691
3697
  }
3692
3698
  const timestamp = parseInt(tPart.slice(2), 10);
3693
3699
  const receivedHmac = v1Part.slice(3);
3694
3700
  if (Number.isNaN(timestamp) || !receivedHmac) {
3695
- throw new import_core12.SolvaPayError("Malformed webhook signature");
3701
+ throw new import_core13.SolvaPayError("Malformed webhook signature");
3696
3702
  }
3697
3703
  if (toleranceSec > 0) {
3698
3704
  const age = Math.abs(Math.floor(Date.now() / 1e3) - timestamp);
3699
3705
  if (age > toleranceSec) {
3700
- throw new import_core12.SolvaPayError("Webhook signature timestamp too old");
3706
+ throw new import_core13.SolvaPayError("Webhook signature timestamp too old");
3701
3707
  }
3702
3708
  }
3703
3709
  const expectedHmac = import_node_crypto.default.createHmac("sha256", secret).update(`${timestamp}.${body}`).digest("hex");
3704
3710
  if (receivedHmac.length !== expectedHmac.length) {
3705
- throw new import_core12.SolvaPayError("Invalid webhook signature");
3711
+ throw new import_core13.SolvaPayError("Invalid webhook signature");
3706
3712
  }
3707
3713
  const ok = import_node_crypto.default.timingSafeEqual(Buffer.from(expectedHmac), Buffer.from(receivedHmac));
3708
- if (!ok) throw new import_core12.SolvaPayError("Invalid webhook signature");
3714
+ if (!ok) throw new import_core13.SolvaPayError("Invalid webhook signature");
3709
3715
  try {
3710
3716
  return JSON.parse(body);
3711
3717
  } catch {
3712
- throw new import_core12.SolvaPayError("Invalid webhook payload: body is not valid JSON");
3718
+ throw new import_core13.SolvaPayError("Invalid webhook payload: body is not valid JSON");
3713
3719
  }
3714
3720
  }
3715
3721
  // Annotate the CommonJS export names for ESM import in node:
@@ -3735,6 +3741,7 @@ function verifyWebhook({
3735
3741
  createSolvaPayClient,
3736
3742
  createTopupPaymentIntentCore,
3737
3743
  createVirtualTools,
3744
+ creditSignals,
3738
3745
  deriveUsageSnapshot,
3739
3746
  disableAutoRechargeCore,
3740
3747
  getAuthenticatedUserCore,
@@ -3749,8 +3756,11 @@ function verifyWebhook({
3749
3756
  isErrorResult,
3750
3757
  isPaywallStructuredContent,
3751
3758
  jsonSchemaToZodRawShape,
3759
+ linkLabel,
3752
3760
  listPlansCore,
3761
+ nextActionFor,
3753
3762
  paywallErrorToClientPayload,
3763
+ planLadder,
3754
3764
  pollBalanceUntilIncreased,
3755
3765
  processPaymentIntentCore,
3756
3766
  processTopupPaymentIntentCore,