better-auth-streampay 1.2.0 → 1.2.1

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
@@ -240,6 +240,20 @@ function formatStreamPayError(err) {
240
240
  }
241
241
  }
242
242
 
243
+ // src/utils/logger.ts
244
+ var PLUGIN_PREFIX = "[streampay]";
245
+ function scopedLogger(logger2) {
246
+ return {
247
+ error: (message) => logger2.error(`${PLUGIN_PREFIX} ${message}`),
248
+ warn: (message) => logger2.warn(`${PLUGIN_PREFIX} ${message}`),
249
+ info: (message) => logger2.info(`${PLUGIN_PREFIX} ${message}`),
250
+ debug: (message) => logger2.debug(`${PLUGIN_PREFIX} ${message}`)
251
+ };
252
+ }
253
+ function getLogger(ctx) {
254
+ return scopedLogger(ctx.context.logger);
255
+ }
256
+
243
257
  // src/utils/ensure-consumer.ts
244
258
  function sameEmail(a, b) {
245
259
  if (!a || !b) return false;
@@ -278,8 +292,8 @@ async function resolveDuplicateConsumer(options, createPayload, context) {
278
292
  if (canClaimBy(options.claimExistingConsumerBy, "phone") && samePhone(existing.phone_number, createPayload.phone_number)) {
279
293
  return existing.id;
280
294
  }
281
- context.context.logger.error(
282
- `StreamPay duplicate: consumer ${existing.id} is already linked to external_id=${existing.external_id}`
295
+ getLogger(context).error(
296
+ `duplicate: consumer ${existing.id} is already linked to external_id=${existing.external_id}`
283
297
  );
284
298
  throw new api.APIError("CONFLICT", {
285
299
  code: "CONSUMER_DUPLICATE_LINKED",
@@ -330,16 +344,16 @@ async function ensureConsumerForUser(options, ctx, user) {
330
344
  try {
331
345
  await options.client.updateConsumer(reusedId, { external_id: user.id });
332
346
  } catch (backfillErr) {
333
- ctx.context.logger.error(
334
- `StreamPay consumer external_id backfill failed for user=${user.id} consumer=${reusedId}: ${formatStreamPayError(backfillErr)}`
347
+ getLogger(ctx).error(
348
+ `consumer external_id backfill failed for user=${user.id} consumer=${reusedId}: ${formatStreamPayError(backfillErr)}`
335
349
  );
336
350
  }
337
351
  await persistConsumerId(ctx, user.id, reusedId);
338
352
  return { consumerId: reusedId, created: false };
339
353
  }
340
354
  }
341
- ctx.context.logger.error(
342
- `StreamPay consumer creation failed for user=${user.id}: ${formatStreamPayError(err)}`
355
+ getLogger(ctx).error(
356
+ `consumer creation failed for user=${user.id}: ${formatStreamPayError(err)}`
343
357
  );
344
358
  throw new api.APIError("INTERNAL_SERVER_ERROR", {
345
359
  message: "StreamPay consumer provisioning failed. Please try again."
@@ -352,8 +366,8 @@ async function persistConsumerId(ctx, userId, consumerId) {
352
366
  streampayConsumerId: consumerId
353
367
  });
354
368
  } catch (err) {
355
- ctx.context.logger.error(
356
- `StreamPay consumer link write failed for user=${userId}: ${formatStreamPayError(err)}`
369
+ getLogger(ctx).error(
370
+ `consumer link write failed for user=${userId}: ${formatStreamPayError(err)}`
357
371
  );
358
372
  }
359
373
  }
@@ -408,7 +422,7 @@ function statusToAPIErrorStatus(status) {
408
422
  return "INTERNAL_SERVER_ERROR";
409
423
  }
410
424
  }
411
- function toAPIError(messageOrConfig, err, logger) {
425
+ function toAPIError(messageOrConfig, err, logger2) {
412
426
  if (err instanceof api.APIError) throw err;
413
427
  const { logPrefix, userMessage } = typeof messageOrConfig === "string" ? { logPrefix: messageOrConfig, userMessage: messageOrConfig } : messageOrConfig;
414
428
  const parsed = parseStreamPayError(err);
@@ -419,7 +433,7 @@ function toAPIError(messageOrConfig, err, logger) {
419
433
  ].filter((segment) => segment !== void 0);
420
434
  const validationSummary = parsed.validationErrors.length > 0 ? ` validation=${parsed.validationErrors.map((issue) => `${issue.loc.join(".")}: ${issue.message}`).join(" | ")}` : "";
421
435
  const logDetail = (tail.length > 0 ? `${parsed.message} [${tail.join(" ")}]` : parsed.message) + validationSummary;
422
- logger.error(`${logPrefix} ${logDetail}`);
436
+ logger2.error(`${logPrefix} ${logDetail}`);
423
437
  throw new api.APIError(statusToAPIErrorStatus(parsed.status), {
424
438
  code: mapToErrorCode(parsed.code, parsed.status),
425
439
  message: userMessage
@@ -500,19 +514,32 @@ var REFERENCE_ID_METADATA_KEY = "streampay_plugin_reference_id";
500
514
  // src/plugins/subscriptions/sync.ts
501
515
  var SUBSCRIPTION_MODEL = "subscription";
502
516
  var WEBHOOK_EVENT_MODEL = "streampayWebhookEvent";
517
+ function logger(ctx) {
518
+ return scopedLogger(ctx.context.logger);
519
+ }
503
520
  var DEFAULT_MAX_WEBHOOK_ATTEMPTS = 10;
504
- function isUniqueConstraintError(err) {
521
+ var MAX_CAUSE_DEPTH = 5;
522
+ function matchesUniqueMarker(err) {
505
523
  if (!err || typeof err !== "object") return false;
506
524
  const message = "message" in err && typeof err.message === "string" ? err.message : "";
507
525
  if (/unique/i.test(message) || /duplicate/i.test(message)) return true;
508
526
  const code = "code" in err && typeof err.code === "string" ? err.code : "";
509
527
  return code === "P2002" || code === "23505" || code === "SQLITE_CONSTRAINT_UNIQUE";
510
528
  }
529
+ function isUniqueConstraintError(err) {
530
+ let current = err;
531
+ for (let depth = 0; depth <= MAX_CAUSE_DEPTH; depth++) {
532
+ if (matchesUniqueMarker(current)) return true;
533
+ if (!current || typeof current !== "object" || !("cause" in current)) return false;
534
+ current = current.cause;
535
+ }
536
+ return false;
537
+ }
511
538
  async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader, maxAttempts) {
512
539
  const eventId = extractEventId(payload);
513
540
  if (!eventId) {
514
- ctx.context.logger.warn(
515
- `StreamPay webhook ${payload.event_type}: missing entity_id/timestamp \u2014 processing without dedupe.`
541
+ logger(ctx).warn(
542
+ `webhook ${payload.event_type}: missing entity_id/timestamp \u2014 processing without dedupe.`
516
543
  );
517
544
  return { action: "process", row: null };
518
545
  }
@@ -538,20 +565,18 @@ async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader
538
565
  where: [{ field: "eventId", value: eventId }]
539
566
  });
540
567
  if (!existing) {
541
- ctx.context.logger.warn(
542
- `StreamPay webhook ${payload.event_type} (${eventId}): unique conflict but row missing, processing without tracking.`
568
+ logger(ctx).warn(
569
+ `webhook ${payload.event_type} (${eventId}): unique conflict but row missing, processing without tracking.`
543
570
  );
544
571
  return { action: "process", row: null };
545
572
  }
546
573
  if (existing.status === "completed") {
547
- ctx.context.logger.info(
548
- `StreamPay webhook ${payload.event_type} (${eventId}) already completed \u2014 skipping.`
549
- );
574
+ logger(ctx).info(`webhook ${payload.event_type} (${eventId}) already completed \u2014 skipping.`);
550
575
  return { action: "skip", reason: "completed" };
551
576
  }
552
577
  if (existing.status === "dead_letter") {
553
- ctx.context.logger.warn(
554
- `StreamPay webhook ${payload.event_type} (${eventId}) already dead-lettered \u2014 skipping (replay manually).`
578
+ logger(ctx).warn(
579
+ `webhook ${payload.event_type} (${eventId}) already dead-lettered \u2014 skipping (replay manually).`
555
580
  );
556
581
  return { action: "skip", reason: "dead_letter" };
557
582
  }
@@ -621,7 +646,7 @@ async function findSubscriptionByStreampayId(ctx, streampaySubscriptionId) {
621
646
  where: [{ field: "streampaySubscriptionId", value: streampaySubscriptionId }]
622
647
  });
623
648
  }
624
- async function applySubscriptionProjection(adapter, stream, logger, source) {
649
+ async function applySubscriptionProjection(adapter, stream, log, source) {
625
650
  const streampaySubscriptionId = stream?.id;
626
651
  if (!stream || !streampaySubscriptionId) return;
627
652
  try {
@@ -637,23 +662,23 @@ async function applySubscriptionProjection(adapter, stream, logger, source) {
637
662
  });
638
663
  } catch (err) {
639
664
  const msg = err instanceof Error ? err.message : String(err);
640
- logger.warn(
641
- `StreamPay ${source}: project for sub=${streampaySubscriptionId} failed (${msg}). Local row will reconcile on next webhook.`
665
+ log.warn(
666
+ `${source}: project for sub=${streampaySubscriptionId} failed (${msg}). Local row will reconcile on next webhook.`
642
667
  );
643
668
  }
644
669
  }
645
- async function syncSubscriptionFromUpstream(client, adapter, streampaySubscriptionId, logger, source) {
670
+ async function syncSubscriptionFromUpstream(client, adapter, streampaySubscriptionId, log, source) {
646
671
  let stream;
647
672
  try {
648
673
  stream = await client.getSubscription(streampaySubscriptionId);
649
674
  } catch (err) {
650
675
  const msg = err instanceof Error ? err.message : String(err);
651
- logger.warn(
652
- `StreamPay ${source}: getSubscription(${streampaySubscriptionId}) failed (${msg}). Local row will reconcile on next webhook.`
676
+ log.warn(
677
+ `${source}: getSubscription(${streampaySubscriptionId}) failed (${msg}). Local row will reconcile on next webhook.`
653
678
  );
654
679
  return;
655
680
  }
656
- await applySubscriptionProjection(adapter, stream, logger, source);
681
+ await applySubscriptionProjection(adapter, stream, log, source);
657
682
  }
658
683
  async function findIncompleteRow(ctx, referenceId, plan) {
659
684
  const candidates = await ctx.context.adapter.findMany({
@@ -716,15 +741,13 @@ async function fireCallback(ctx, callback, data, callbackName) {
716
741
  await callback(data);
717
742
  } catch (err) {
718
743
  const msg = err instanceof Error ? err.message : String(err);
719
- ctx.context.logger.error(`StreamPay subscription callback ${callbackName} failed: ${msg}`);
744
+ logger(ctx).error(`subscription callback ${callbackName} failed: ${msg}`);
720
745
  }
721
746
  }
722
747
  async function reconcileFromStreamPay(ctx, payload, client, plans) {
723
748
  const streampaySubscriptionId = payload.entity_id;
724
749
  if (!streampaySubscriptionId) {
725
- ctx.context.logger.warn(
726
- `StreamPay webhook ${payload.event_type} has no entity_id \u2014 cannot reconcile.`
727
- );
750
+ logger(ctx).warn(`webhook ${payload.event_type} has no entity_id \u2014 cannot reconcile.`);
728
751
  return { row: null, stream: null };
729
752
  }
730
753
  let stream;
@@ -732,8 +755,8 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
732
755
  stream = await client.getSubscription(streampaySubscriptionId);
733
756
  } catch (err) {
734
757
  const msg = err instanceof Error ? err.message : String(err);
735
- ctx.context.logger.error(
736
- `StreamPay webhook ${payload.event_type}: getSubscription(${streampaySubscriptionId}) failed: ${msg}`
758
+ logger(ctx).error(
759
+ `webhook ${payload.event_type}: getSubscription(${streampaySubscriptionId}) failed: ${msg}`
737
760
  );
738
761
  throw err;
739
762
  }
@@ -750,8 +773,8 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
750
773
  const planName = readMetadataString(payload.data, PLAN_NAME_METADATA_KEY) ?? inferPlanFromItems(stream, plans);
751
774
  const referenceId = readMetadataString(payload.data, REFERENCE_ID_METADATA_KEY);
752
775
  if (!planName || !referenceId) {
753
- ctx.context.logger.warn(
754
- `StreamPay webhook ${payload.event_type}: cannot link sub=${streampaySubscriptionId} \u2014 missing plan_name (${planName}) or reference_id (${referenceId}) metadata.`
776
+ logger(ctx).warn(
777
+ `webhook ${payload.event_type}: cannot link sub=${streampaySubscriptionId} \u2014 missing plan_name (${planName}) or reference_id (${referenceId}) metadata.`
755
778
  );
756
779
  return { row: null, stream };
757
780
  }
@@ -805,8 +828,8 @@ async function syncWebhookPayload(ctx, payload, client, plans, callbacks, option
805
828
  claim = await claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader, maxAttempts);
806
829
  if (claim.action === "skip") return;
807
830
  if (claim.action === "dead_letter") {
808
- ctx.context.logger.warn(
809
- `StreamPay webhook ${payload.event_type} (${claim.row.eventId}) dead-lettered after ${claim.row.attemptCount} attempts. Replay manually.`
831
+ logger(ctx).warn(
832
+ `webhook ${payload.event_type} (${claim.row.eventId}) dead-lettered after ${claim.row.attemptCount} attempts. Replay manually.`
810
833
  );
811
834
  return;
812
835
  }
@@ -848,9 +871,7 @@ async function handleInvoiceCompleted(ctx, payload, client, _plans, callbacks) {
848
871
  }
849
872
  } catch (err) {
850
873
  const msg = err instanceof Error ? err.message : String(err);
851
- ctx.context.logger.error(
852
- `StreamPay INVOICE_COMPLETED: getInvoice(${invoiceId}) failed: ${msg}`
853
- );
874
+ logger(ctx).error(`INVOICE_COMPLETED: getInvoice(${invoiceId}) failed: ${msg}`);
854
875
  throw err;
855
876
  }
856
877
  if (!subscriptionId) return;
@@ -859,9 +880,7 @@ async function handleInvoiceCompleted(ctx, payload, client, _plans, callbacks) {
859
880
  stream = await client.getSubscription(subscriptionId);
860
881
  } catch (err) {
861
882
  const msg = err instanceof Error ? err.message : String(err);
862
- ctx.context.logger.error(
863
- `StreamPay INVOICE_COMPLETED: getSubscription(${subscriptionId}) failed: ${msg}`
864
- );
883
+ logger(ctx).error(`INVOICE_COMPLETED: getSubscription(${subscriptionId}) failed: ${msg}`);
865
884
  throw err;
866
885
  }
867
886
  const existing = await findSubscriptionByStreampayId(ctx, subscriptionId);
@@ -996,7 +1015,7 @@ function buildPaymentsEndpoints(client, adminOptions) {
996
1015
  userMessage: "StreamPay refund failed."
997
1016
  },
998
1017
  err,
999
- ctx.context.logger
1018
+ getLogger(ctx)
1000
1019
  );
1001
1020
  }
1002
1021
  }
@@ -1018,7 +1037,7 @@ function buildPaymentsEndpoints(client, adminOptions) {
1018
1037
  const response = await client.listPayments(params);
1019
1038
  return ctx.json(response);
1020
1039
  } catch (err) {
1021
- toAPIError("StreamPay listPayments failed.", err, ctx.context.logger);
1040
+ toAPIError("StreamPay listPayments failed.", err, getLogger(ctx));
1022
1041
  }
1023
1042
  }
1024
1043
  ),
@@ -1037,7 +1056,7 @@ function buildPaymentsEndpoints(client, adminOptions) {
1037
1056
  toAPIError(
1038
1057
  `StreamPay getPayment failed for payment=${ctx.params.id}:`,
1039
1058
  err,
1040
- ctx.context.logger
1059
+ getLogger(ctx)
1041
1060
  );
1042
1061
  }
1043
1062
  }
@@ -1060,7 +1079,7 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1060
1079
  const subscription = await client.createSubscription(input);
1061
1080
  return ctx.json(subscription);
1062
1081
  } catch (err) {
1063
- toAPIError("StreamPay createSubscription failed.", err, ctx.context.logger);
1082
+ toAPIError("StreamPay createSubscription failed.", err, getLogger(ctx));
1064
1083
  }
1065
1084
  }
1066
1085
  ),
@@ -1083,7 +1102,7 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1083
1102
  toAPIError(
1084
1103
  `StreamPay getSubscription failed for subscription=${subscriptionId}:`,
1085
1104
  err,
1086
- ctx.context.logger
1105
+ getLogger(ctx)
1087
1106
  );
1088
1107
  }
1089
1108
  await adminOptions.onPlanChange({ user, subscriptionId, current, patch });
@@ -1093,7 +1112,7 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1093
1112
  await applySubscriptionProjection(
1094
1113
  getAdapter(ctx),
1095
1114
  subscription,
1096
- ctx.context.logger,
1115
+ getLogger(ctx),
1097
1116
  "adminUpdateSubscription"
1098
1117
  );
1099
1118
  return ctx.json(subscription);
@@ -1101,7 +1120,7 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1101
1120
  toAPIError(
1102
1121
  `StreamPay updateSubscription failed for subscription=${subscriptionId}:`,
1103
1122
  err,
1104
- ctx.context.logger
1123
+ getLogger(ctx)
1105
1124
  );
1106
1125
  }
1107
1126
  }
@@ -1122,7 +1141,7 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1122
1141
  const response = await client.listSubscriptions(params);
1123
1142
  return ctx.json(response);
1124
1143
  } catch (err) {
1125
- toAPIError("StreamPay listSubscriptions failed.", err, ctx.context.logger);
1144
+ toAPIError("StreamPay listSubscriptions failed.", err, getLogger(ctx));
1126
1145
  }
1127
1146
  }
1128
1147
  ),
@@ -1141,7 +1160,7 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1141
1160
  toAPIError(
1142
1161
  `StreamPay getSubscription failed for subscription=${ctx.params.id}:`,
1143
1162
  err,
1144
- ctx.context.logger
1163
+ getLogger(ctx)
1145
1164
  );
1146
1165
  }
1147
1166
  }
@@ -1170,7 +1189,7 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1170
1189
  await applySubscriptionProjection(
1171
1190
  getAdapter(ctx),
1172
1191
  result,
1173
- ctx.context.logger,
1192
+ getLogger(ctx),
1174
1193
  "adminCancelSubscription"
1175
1194
  );
1176
1195
  return ctx.json(result);
@@ -1181,7 +1200,7 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1181
1200
  userMessage: "StreamPay subscription cancellation failed."
1182
1201
  },
1183
1202
  err,
1184
- ctx.context.logger
1203
+ getLogger(ctx)
1185
1204
  );
1186
1205
  }
1187
1206
  }
@@ -1208,7 +1227,7 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1208
1227
  client,
1209
1228
  getAdapter(ctx),
1210
1229
  subscriptionId,
1211
- ctx.context.logger,
1230
+ getLogger(ctx),
1212
1231
  "adminFreezeSubscription"
1213
1232
  );
1214
1233
  return ctx.json(freeze);
@@ -1219,7 +1238,7 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1219
1238
  userMessage: "StreamPay subscription freeze failed."
1220
1239
  },
1221
1240
  err,
1222
- ctx.context.logger
1241
+ getLogger(ctx)
1223
1242
  );
1224
1243
  }
1225
1244
  }
@@ -1245,7 +1264,7 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1245
1264
  toAPIError(
1246
1265
  `StreamPay listSubscriptionFreezes failed for subscription=${ctx.params.id}:`,
1247
1266
  err,
1248
- ctx.context.logger
1267
+ getLogger(ctx)
1249
1268
  );
1250
1269
  }
1251
1270
  }
@@ -1274,7 +1293,7 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1274
1293
  client,
1275
1294
  getAdapter(ctx),
1276
1295
  subscriptionId,
1277
- ctx.context.logger,
1296
+ getLogger(ctx),
1278
1297
  "adminUpdateSubscriptionFreeze"
1279
1298
  );
1280
1299
  return ctx.json(freeze);
@@ -1285,7 +1304,7 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1285
1304
  userMessage: "StreamPay freeze update failed."
1286
1305
  },
1287
1306
  err,
1288
- ctx.context.logger
1307
+ getLogger(ctx)
1289
1308
  );
1290
1309
  }
1291
1310
  }
@@ -1315,7 +1334,7 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1315
1334
  client,
1316
1335
  getAdapter(ctx),
1317
1336
  subscriptionId,
1318
- ctx.context.logger,
1337
+ getLogger(ctx),
1319
1338
  "adminDeleteSubscriptionFreeze"
1320
1339
  );
1321
1340
  return ctx.json({ deleted: true });
@@ -1326,7 +1345,7 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1326
1345
  userMessage: "StreamPay freeze delete failed."
1327
1346
  },
1328
1347
  err,
1329
- ctx.context.logger
1348
+ getLogger(ctx)
1330
1349
  );
1331
1350
  }
1332
1351
  }
@@ -1352,7 +1371,7 @@ function buildConsumersEndpoints(client, adminOptions) {
1352
1371
  const response = await client.listConsumers(params);
1353
1372
  return ctx.json(response);
1354
1373
  } catch (err) {
1355
- toAPIError("StreamPay listConsumers failed.", err, ctx.context.logger);
1374
+ toAPIError("StreamPay listConsumers failed.", err, getLogger(ctx));
1356
1375
  }
1357
1376
  }
1358
1377
  ),
@@ -1371,7 +1390,7 @@ function buildConsumersEndpoints(client, adminOptions) {
1371
1390
  toAPIError(
1372
1391
  `StreamPay getConsumer failed for consumer=${ctx.params.id}:`,
1373
1392
  err,
1374
- ctx.context.logger
1393
+ getLogger(ctx)
1375
1394
  );
1376
1395
  }
1377
1396
  }
@@ -1394,7 +1413,7 @@ function buildConsumersEndpoints(client, adminOptions) {
1394
1413
  toAPIError(
1395
1414
  `StreamPay updateConsumer failed for consumer=${consumerId}:`,
1396
1415
  err,
1397
- ctx.context.logger
1416
+ getLogger(ctx)
1398
1417
  );
1399
1418
  }
1400
1419
  }
@@ -1422,7 +1441,7 @@ function buildConsumersEndpoints(client, adminOptions) {
1422
1441
  toAPIError(
1423
1442
  `StreamPay getConsumer failed for consumer=${consumerId}:`,
1424
1443
  err,
1425
- ctx.context.logger
1444
+ getLogger(ctx)
1426
1445
  );
1427
1446
  }
1428
1447
  try {
@@ -1432,7 +1451,7 @@ function buildConsumersEndpoints(client, adminOptions) {
1432
1451
  toAPIError(
1433
1452
  `StreamPay deleteConsumer failed for consumer=${consumerId}:`,
1434
1453
  err,
1435
- ctx.context.logger
1454
+ getLogger(ctx)
1436
1455
  );
1437
1456
  }
1438
1457
  }
@@ -1442,7 +1461,7 @@ function buildConsumersEndpoints(client, adminOptions) {
1442
1461
  streampayConsumerId: null
1443
1462
  });
1444
1463
  } catch (err) {
1445
- ctx.context.logger.error(
1464
+ getLogger(ctx).error(
1446
1465
  `StreamPay admin delete: link clear failed for user=${externalId} consumer=${consumerId}: ${formatStreamPayError(err)}`
1447
1466
  );
1448
1467
  }
@@ -1470,7 +1489,7 @@ function buildInvoicesEndpoints(client, adminOptions) {
1470
1489
  const response = await client.listInvoices(params);
1471
1490
  return ctx.json(response);
1472
1491
  } catch (err) {
1473
- toAPIError("StreamPay listInvoices failed.", err, ctx.context.logger);
1492
+ toAPIError("StreamPay listInvoices failed.", err, getLogger(ctx));
1474
1493
  }
1475
1494
  }
1476
1495
  ),
@@ -1489,7 +1508,7 @@ function buildInvoicesEndpoints(client, adminOptions) {
1489
1508
  toAPIError(
1490
1509
  `StreamPay getInvoice failed for invoice=${ctx.params.id}:`,
1491
1510
  err,
1492
- ctx.context.logger
1511
+ getLogger(ctx)
1493
1512
  );
1494
1513
  }
1495
1514
  }
@@ -1512,7 +1531,7 @@ function buildProductsEndpoints(client, adminOptions) {
1512
1531
  const product = await client.createProduct(input);
1513
1532
  return ctx.json(product);
1514
1533
  } catch (err) {
1515
- toAPIError("StreamPay createProduct failed.", err, ctx.context.logger);
1534
+ toAPIError("StreamPay createProduct failed.", err, getLogger(ctx));
1516
1535
  }
1517
1536
  }
1518
1537
  ),
@@ -1532,7 +1551,7 @@ function buildProductsEndpoints(client, adminOptions) {
1532
1551
  const response = await client.listProducts(params);
1533
1552
  return ctx.json(response);
1534
1553
  } catch (err) {
1535
- toAPIError("StreamPay listProducts failed.", err, ctx.context.logger);
1554
+ toAPIError("StreamPay listProducts failed.", err, getLogger(ctx));
1536
1555
  }
1537
1556
  }
1538
1557
  ),
@@ -1551,7 +1570,7 @@ function buildProductsEndpoints(client, adminOptions) {
1551
1570
  toAPIError(
1552
1571
  `StreamPay getProduct failed for product=${ctx.params.id}:`,
1553
1572
  err,
1554
- ctx.context.logger
1573
+ getLogger(ctx)
1555
1574
  );
1556
1575
  }
1557
1576
  }
@@ -1574,7 +1593,7 @@ function buildProductsEndpoints(client, adminOptions) {
1574
1593
  toAPIError(
1575
1594
  `StreamPay updateProduct failed for product=${productId}:`,
1576
1595
  err,
1577
- ctx.context.logger
1596
+ getLogger(ctx)
1578
1597
  );
1579
1598
  }
1580
1599
  }
@@ -1595,7 +1614,7 @@ function buildProductsEndpoints(client, adminOptions) {
1595
1614
  toAPIError(
1596
1615
  `StreamPay deleteProduct failed for product=${ctx.params.id}:`,
1597
1616
  err,
1598
- ctx.context.logger
1617
+ getLogger(ctx)
1599
1618
  );
1600
1619
  }
1601
1620
  }
@@ -1618,7 +1637,7 @@ function buildCouponsEndpoints(client, adminOptions) {
1618
1637
  const coupon = await client.createCoupon(input);
1619
1638
  return ctx.json(coupon);
1620
1639
  } catch (err) {
1621
- toAPIError("StreamPay createCoupon failed.", err, ctx.context.logger);
1640
+ toAPIError("StreamPay createCoupon failed.", err, getLogger(ctx));
1622
1641
  }
1623
1642
  }
1624
1643
  ),
@@ -1638,7 +1657,7 @@ function buildCouponsEndpoints(client, adminOptions) {
1638
1657
  const response = await client.listCoupons(params);
1639
1658
  return ctx.json(response);
1640
1659
  } catch (err) {
1641
- toAPIError("StreamPay listCoupons failed.", err, ctx.context.logger);
1660
+ toAPIError("StreamPay listCoupons failed.", err, getLogger(ctx));
1642
1661
  }
1643
1662
  }
1644
1663
  ),
@@ -1657,7 +1676,7 @@ function buildCouponsEndpoints(client, adminOptions) {
1657
1676
  toAPIError(
1658
1677
  `StreamPay getCoupon failed for coupon=${ctx.params.id}:`,
1659
1678
  err,
1660
- ctx.context.logger
1679
+ getLogger(ctx)
1661
1680
  );
1662
1681
  }
1663
1682
  }
@@ -1677,11 +1696,7 @@ function buildCouponsEndpoints(client, adminOptions) {
1677
1696
  const coupon = await client.updateCoupon(couponId, patch);
1678
1697
  return ctx.json(coupon);
1679
1698
  } catch (err) {
1680
- toAPIError(
1681
- `StreamPay updateCoupon failed for coupon=${couponId}:`,
1682
- err,
1683
- ctx.context.logger
1684
- );
1699
+ toAPIError(`StreamPay updateCoupon failed for coupon=${couponId}:`, err, getLogger(ctx));
1685
1700
  }
1686
1701
  }
1687
1702
  ),
@@ -1701,7 +1716,7 @@ function buildCouponsEndpoints(client, adminOptions) {
1701
1716
  toAPIError(
1702
1717
  `StreamPay deleteCoupon failed for coupon=${ctx.params.id}:`,
1703
1718
  err,
1704
- ctx.context.logger
1719
+ getLogger(ctx)
1705
1720
  );
1706
1721
  }
1707
1722
  }
@@ -1726,7 +1741,7 @@ function buildPaymentLinksEndpoints(client, adminOptions) {
1726
1741
  const response = await client.listPaymentLinks(params);
1727
1742
  return ctx.json(response);
1728
1743
  } catch (err) {
1729
- toAPIError("StreamPay listPaymentLinks failed.", err, ctx.context.logger);
1744
+ toAPIError("StreamPay listPaymentLinks failed.", err, getLogger(ctx));
1730
1745
  }
1731
1746
  }
1732
1747
  ),
@@ -1745,7 +1760,7 @@ function buildPaymentLinksEndpoints(client, adminOptions) {
1745
1760
  toAPIError(
1746
1761
  `StreamPay getPaymentLink failed for payment_link=${ctx.params.id}:`,
1747
1762
  err,
1748
- ctx.context.logger
1763
+ getLogger(ctx)
1749
1764
  );
1750
1765
  }
1751
1766
  }
@@ -1835,7 +1850,7 @@ function buildWebhookEventsEndpoints(adminOptions, registry) {
1835
1850
  toAPIError(
1836
1851
  `StreamPay replayWebhookEvent failed for event=${ctx.params.eventId}:`,
1837
1852
  err,
1838
- ctx.context.logger
1853
+ getLogger(ctx)
1839
1854
  );
1840
1855
  }
1841
1856
  }
@@ -2027,11 +2042,11 @@ var checkout = (checkoutOptions = {}) => (options) => {
2027
2042
  } catch (err) {
2028
2043
  toAPIError(
2029
2044
  {
2030
- logPrefix: "StreamPay checkout creation failed:",
2045
+ logPrefix: "checkout creation failed:",
2031
2046
  userMessage: "StreamPay checkout creation failed."
2032
2047
  },
2033
2048
  err,
2034
- ctx.context.logger
2049
+ getLogger(ctx)
2035
2050
  );
2036
2051
  }
2037
2052
  }
@@ -2061,7 +2076,7 @@ var portal = ({ pageSize } = {}) => (options) => {
2061
2076
  const consumer = await client.getConsumer(consumerId);
2062
2077
  return ctx.json({ hasConsumer: true, consumer });
2063
2078
  } catch (err) {
2064
- toAPIError("StreamPay getConsumer failed.", err, ctx.context.logger);
2079
+ toAPIError("StreamPay getConsumer failed.", err, getLogger(ctx));
2065
2080
  }
2066
2081
  }
2067
2082
  ),
@@ -2080,7 +2095,7 @@ var portal = ({ pageSize } = {}) => (options) => {
2080
2095
  });
2081
2096
  return ctx.json({ hasConsumer: true, data: response.data ?? [] });
2082
2097
  } catch (err) {
2083
- toAPIError("StreamPay listSubscriptions failed.", err, ctx.context.logger);
2098
+ toAPIError("StreamPay listSubscriptions failed.", err, getLogger(ctx));
2084
2099
  }
2085
2100
  }
2086
2101
  ),
@@ -2099,7 +2114,7 @@ var portal = ({ pageSize } = {}) => (options) => {
2099
2114
  });
2100
2115
  return ctx.json({ hasConsumer: true, data: response.data ?? [] });
2101
2116
  } catch (err) {
2102
- toAPIError("StreamPay listInvoices failed.", err, ctx.context.logger);
2117
+ toAPIError("StreamPay listInvoices failed.", err, getLogger(ctx));
2103
2118
  }
2104
2119
  }
2105
2120
  )
@@ -2407,17 +2422,15 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2407
2422
  } catch (err) {
2408
2423
  toAPIError(
2409
2424
  {
2410
- logPrefix: `StreamPay upgradeSubscription failed for plan=${plan.name} ref=${referenceId}:`,
2425
+ logPrefix: `upgradeSubscription failed for plan=${plan.name} ref=${referenceId}:`,
2411
2426
  userMessage: "Failed to start subscription checkout."
2412
2427
  },
2413
2428
  err,
2414
- ctx.context.logger
2429
+ getLogger(ctx)
2415
2430
  );
2416
2431
  }
2417
2432
  if (!url) {
2418
- ctx.context.logger.error(
2419
- `StreamPay createPaymentLink returned link=${paymentLinkId} with no url.`
2420
- );
2433
+ getLogger(ctx).error(`createPaymentLink returned link=${paymentLinkId} with no url.`);
2421
2434
  throw new api.APIError("INTERNAL_SERVER_ERROR", {
2422
2435
  message: "Payment link was created but no URL was returned."
2423
2436
  });
@@ -2512,9 +2525,9 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2512
2525
  return ctx.json({ subscription: updated ?? row, synced: true });
2513
2526
  } catch (err) {
2514
2527
  toAPIError(
2515
- `StreamPay subscriptionSuccess fallback sync failed for row=${row.id}:`,
2528
+ `subscriptionSuccess fallback sync failed for row=${row.id}:`,
2516
2529
  err,
2517
- ctx.context.logger
2530
+ getLogger(ctx)
2518
2531
  );
2519
2532
  }
2520
2533
  }
@@ -2574,11 +2587,11 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2574
2587
  } catch (err) {
2575
2588
  toAPIError(
2576
2589
  {
2577
- logPrefix: `StreamPay cancelAtPeriodEnd failed for row=${row.id}:`,
2590
+ logPrefix: `cancelAtPeriodEnd failed for row=${row.id}:`,
2578
2591
  userMessage: "Subscription cancel-at-period-end failed."
2579
2592
  },
2580
2593
  err,
2581
- ctx.context.logger
2594
+ getLogger(ctx)
2582
2595
  );
2583
2596
  }
2584
2597
  }
@@ -2591,18 +2604,18 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2591
2604
  client,
2592
2605
  adapter,
2593
2606
  row.streampaySubscriptionId,
2594
- ctx.context.logger,
2607
+ getLogger(ctx),
2595
2608
  "cancelSubscription"
2596
2609
  );
2597
2610
  return ctx.json(result);
2598
2611
  } catch (err) {
2599
2612
  toAPIError(
2600
2613
  {
2601
- logPrefix: `StreamPay cancelSubscription failed for row=${row.id}:`,
2614
+ logPrefix: `cancelSubscription failed for row=${row.id}:`,
2602
2615
  userMessage: "Subscription cancellation failed."
2603
2616
  },
2604
2617
  err,
2605
- ctx.context.logger
2618
+ getLogger(ctx)
2606
2619
  );
2607
2620
  }
2608
2621
  }
@@ -2680,7 +2693,7 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2680
2693
  client,
2681
2694
  adapter,
2682
2695
  row.streampaySubscriptionId,
2683
- ctx.context.logger,
2696
+ getLogger(ctx),
2684
2697
  "changeSubscriptionPlan"
2685
2698
  );
2686
2699
  return ctx.json({
@@ -2691,11 +2704,11 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2691
2704
  } catch (err) {
2692
2705
  toAPIError(
2693
2706
  {
2694
- logPrefix: `StreamPay change-plan (immediate) failed for row=${row.id}:`,
2707
+ logPrefix: `change-plan (immediate) failed for row=${row.id}:`,
2695
2708
  userMessage: "Plan change failed."
2696
2709
  },
2697
2710
  err,
2698
- ctx.context.logger
2711
+ getLogger(ctx)
2699
2712
  );
2700
2713
  }
2701
2714
  }
@@ -2763,11 +2776,11 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2763
2776
  } catch (err) {
2764
2777
  toAPIError(
2765
2778
  {
2766
- logPrefix: `StreamPay change-plan (at_period_end) failed for row=${row.id}:`,
2779
+ logPrefix: `change-plan (at_period_end) failed for row=${row.id}:`,
2767
2780
  userMessage: "Plan change scheduling failed."
2768
2781
  },
2769
2782
  err,
2770
- ctx.context.logger
2783
+ getLogger(ctx)
2771
2784
  );
2772
2785
  }
2773
2786
  }
@@ -2816,18 +2829,18 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2816
2829
  client,
2817
2830
  adapter,
2818
2831
  row.streampaySubscriptionId,
2819
- ctx.context.logger,
2832
+ getLogger(ctx),
2820
2833
  "freezeSubscription"
2821
2834
  );
2822
2835
  return ctx.json(freeze);
2823
2836
  } catch (err) {
2824
2837
  toAPIError(
2825
2838
  {
2826
- logPrefix: `StreamPay freezeSubscription failed for row=${row.id}:`,
2839
+ logPrefix: `freezeSubscription failed for row=${row.id}:`,
2827
2840
  userMessage: "Subscription freeze failed."
2828
2841
  },
2829
2842
  err,
2830
- ctx.context.logger
2843
+ getLogger(ctx)
2831
2844
  );
2832
2845
  }
2833
2846
  }
@@ -2885,18 +2898,18 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2885
2898
  client,
2886
2899
  adapter,
2887
2900
  row.streampaySubscriptionId,
2888
- ctx.context.logger,
2901
+ getLogger(ctx),
2889
2902
  "unfreezeSubscription"
2890
2903
  );
2891
2904
  return ctx.json({ unfrozen: true });
2892
2905
  } catch (err) {
2893
2906
  toAPIError(
2894
2907
  {
2895
- logPrefix: `StreamPay unfreezeSubscription failed for row=${row.id}:`,
2908
+ logPrefix: `unfreezeSubscription failed for row=${row.id}:`,
2896
2909
  userMessage: "Subscription unfreeze failed."
2897
2910
  },
2898
2911
  err,
2899
- ctx.context.logger
2912
+ getLogger(ctx)
2900
2913
  );
2901
2914
  }
2902
2915
  }
@@ -2923,6 +2936,23 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2923
2936
  );
2924
2937
  }
2925
2938
  ),
2939
+ /**
2940
+ * Returns the user's current billable subscription, or `null` if
2941
+ * none. **Intentionally filters out `incomplete`, `canceled`,
2942
+ * `expired`, and `inactive` rows** — only `active | frozen |
2943
+ * past_due` are surfaced, since those are the statuses that
2944
+ * represent a *live* entitlement.
2945
+ *
2946
+ * Notable consequence: between `/subscription/upgrade` (creates
2947
+ * an `incomplete` row + payment link) and the
2948
+ * `SUBSCRIPTION_ACTIVATED` webhook landing, this endpoint
2949
+ * returns `null`. If you want to render "your subscription is
2950
+ * being activated" during that window, call `/subscription/list`
2951
+ * and filter for `status === "incomplete"` yourself.
2952
+ *
2953
+ * Pass `?group=<name>` to scope to a single plan group when the
2954
+ * app declares multiple concurrent subscriptions per user.
2955
+ */
2926
2956
  currentSubscription: api.createAuthEndpoint(
2927
2957
  "/subscription/current",
2928
2958
  {
@@ -3170,8 +3200,8 @@ function subscriptions(subsOptions) {
3170
3200
  } catch (err) {
3171
3201
  if (classifyWebhookFailure(err) === "PERMANENT") {
3172
3202
  const msg = err instanceof Error ? err.message : String(err);
3173
- ctx.context.logger.warn(
3174
- `StreamPay subscription sync: permanent failure on event=${payload.event_type} entity=${payload.entity_id}: ${msg}`
3203
+ getLogger(ctx).warn(
3204
+ `subscription sync: permanent failure on event=${payload.event_type} entity=${payload.entity_id}: ${msg}`
3175
3205
  );
3176
3206
  return;
3177
3207
  }
@@ -3384,9 +3414,10 @@ var webhooks = (webhooksOptions) => (_options, registry) => {
3384
3414
  cloneRequest: true
3385
3415
  },
3386
3416
  async (ctx) => {
3417
+ const logger2 = getLogger(ctx);
3387
3418
  const hasSecret = typeof secret === "string" ? secret.length > 0 : secret.some((s) => s.length > 0);
3388
3419
  if (!hasSecret) {
3389
- ctx.context.logger.error("StreamPay webhook secret is not configured.");
3420
+ logger2.error("webhook secret is not configured.");
3390
3421
  throw new api.APIError("INTERNAL_SERVER_ERROR", {
3391
3422
  message: "StreamPay webhook secret is not configured."
3392
3423
  });
@@ -3405,7 +3436,7 @@ var webhooks = (webhooksOptions) => (_options, registry) => {
3405
3436
  });
3406
3437
  } catch (err) {
3407
3438
  if (err instanceof StreamPayWebhookError) {
3408
- ctx.context.logger.warn(`StreamPay webhook rejected: ${err.reason}`);
3439
+ logger2.warn(`webhook rejected: ${err.reason}`);
3409
3440
  throw new api.APIError(toErrorCode(err.reason), {
3410
3441
  message: `Webhook verification failed: ${err.reason}`
3411
3442
  });
@@ -3434,7 +3465,7 @@ var webhooks = (webhooksOptions) => (_options, registry) => {
3434
3465
  });
3435
3466
  } catch (err) {
3436
3467
  const message = err instanceof Error ? err.message : String(err);
3437
- ctx.context.logger.error(`StreamPay subscription sync failed: ${message}`);
3468
+ logger2.error(`subscription sync failed: ${message}`);
3438
3469
  throw new api.APIError("INTERNAL_SERVER_ERROR", {
3439
3470
  message: "Webhook sync failed. See server logs."
3440
3471
  });
@@ -3444,7 +3475,7 @@ var webhooks = (webhooksOptions) => (_options, registry) => {
3444
3475
  await dispatchWebhook(payload, handlers);
3445
3476
  } catch (err) {
3446
3477
  const message = err instanceof Error ? err.message : String(err);
3447
- ctx.context.logger.error(`StreamPay webhook handler failed: ${message}`);
3478
+ logger2.error(`webhook handler failed: ${message}`);
3448
3479
  throw new api.APIError("INTERNAL_SERVER_ERROR", {
3449
3480
  message: "Webhook handler failed. See server logs."
3450
3481
  });
@@ -3489,8 +3520,8 @@ var onBeforeUserCreate = (options) => async (user, context) => {
3489
3520
  return { data: { streampayConsumerId: reusedId } };
3490
3521
  }
3491
3522
  }
3492
- context.context.logger.error(
3493
- `StreamPay consumer creation failed for user=${user.id ?? "<pre-insert>"}: ${formatStreamPayError(err)}`
3523
+ getLogger(context).error(
3524
+ `consumer creation failed for user=${user.id ?? "<pre-insert>"}: ${formatStreamPayError(err)}`
3494
3525
  );
3495
3526
  throw new api.APIError("INTERNAL_SERVER_ERROR", {
3496
3527
  message: "StreamPay consumer provisioning failed. Please try again."
@@ -3507,8 +3538,8 @@ var onAfterUserCreate = (options) => async (user, context) => {
3507
3538
  external_id: sessionUser.id
3508
3539
  });
3509
3540
  } catch (err) {
3510
- context.context.logger.error(
3511
- `StreamPay consumer external_id link failed for user=${sessionUser.id} consumer=${sessionUser.streampayConsumerId}: ${formatStreamPayError(err)}`
3541
+ getLogger(context).error(
3542
+ `consumer external_id link failed for user=${sessionUser.id} consumer=${sessionUser.streampayConsumerId}: ${formatStreamPayError(err)}`
3512
3543
  );
3513
3544
  }
3514
3545
  };
@@ -3531,8 +3562,8 @@ var onUserUpdate = (options) => async (user, context) => {
3531
3562
  await options.client.updateConsumer(sessionUser.streampayConsumerId, patch);
3532
3563
  } catch (err) {
3533
3564
  if (isNotFoundError(err)) {
3534
- context.context.logger.error(
3535
- `StreamPay consumer ${sessionUser.streampayConsumerId} not found for user=${sessionUser.id}; clearing stale link for re-provisioning.`
3565
+ getLogger(context).error(
3566
+ `consumer ${sessionUser.streampayConsumerId} not found for user=${sessionUser.id}; clearing stale link for re-provisioning.`
3536
3567
  );
3537
3568
  if (hasInternalAdapter(context)) {
3538
3569
  try {
@@ -3540,15 +3571,15 @@ var onUserUpdate = (options) => async (user, context) => {
3540
3571
  streampayConsumerId: null
3541
3572
  });
3542
3573
  } catch (clearErr) {
3543
- context.context.logger.error(
3544
- `StreamPay stale-link clear failed for user=${sessionUser.id}: ${formatStreamPayError(clearErr)}`
3574
+ getLogger(context).error(
3575
+ `stale-link clear failed for user=${sessionUser.id}: ${formatStreamPayError(clearErr)}`
3545
3576
  );
3546
3577
  }
3547
3578
  }
3548
3579
  return;
3549
3580
  }
3550
- context.context.logger.error(
3551
- `StreamPay consumer update failed for user=${sessionUser.id} consumer=${sessionUser.streampayConsumerId}: ${formatStreamPayError(err)}`
3581
+ getLogger(context).error(
3582
+ `consumer update failed for user=${sessionUser.id} consumer=${sessionUser.streampayConsumerId}: ${formatStreamPayError(err)}`
3552
3583
  );
3553
3584
  }
3554
3585
  };
@@ -3561,15 +3592,15 @@ var onUserDelete = (options) => async (user, context) => {
3561
3592
  await options.client.deleteConsumer(sessionUser.streampayConsumerId);
3562
3593
  } catch (err) {
3563
3594
  if (isNotFoundError(err)) return;
3564
- context.context.logger.error(
3565
- `StreamPay consumer delete failed for user=${sessionUser.id} consumer=${sessionUser.streampayConsumerId}: ${formatStreamPayError(err)}`
3595
+ getLogger(context).error(
3596
+ `consumer delete failed for user=${sessionUser.id} consumer=${sessionUser.streampayConsumerId}: ${formatStreamPayError(err)}`
3566
3597
  );
3567
3598
  }
3568
3599
  };
3569
3600
 
3570
3601
  // package.json
3571
3602
  var package_default = {
3572
- version: "1.2.0"};
3603
+ version: "1.2.1"};
3573
3604
 
3574
3605
  // src/version.ts
3575
3606
  var version = package_default.version;