better-auth-streampay 3.1.0 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -658,6 +658,15 @@ function isTerminalSubscriptionStatus(status) {
658
658
  function isCheckoutSuccessStatus(status) {
659
659
  return status !== void 0 && CHECKOUT_SUCCESS_STATUSES.has(status);
660
660
  }
661
+ function subscriptionSlotKey(referenceType, referenceId, group) {
662
+ const tuple = JSON.stringify([referenceType, referenceId, group ?? null]);
663
+ return `sp_slot_v1_${crypto.createHash("sha256").update(tuple).digest("hex")}`;
664
+ }
665
+ var UPGRADE_IDEMPOTENCY_WINDOW_MS = 15 * 60 * 1e3;
666
+ var PLAN_NAME_METADATA_KEY = "streampay_plugin_plan_name";
667
+ var REFERENCE_ID_METADATA_KEY = "streampay_plugin_reference_id";
668
+ var REFERENCE_TYPE_METADATA_KEY = "streampay_plugin_reference_type";
669
+ var SUBSCRIPTION_ROW_ID_METADATA_KEY = "streampay_plugin_subscription_row_id";
661
670
 
662
671
  // src/plugins/subscriptions/reconcile.ts
663
672
  var SUBSCRIPTION_MODEL = "subscription";
@@ -679,25 +688,38 @@ function reconcileProjectionAgainstExisting(existing, projection, options = {})
679
688
  function projectSubscriptionAgainstExisting(existing, stream) {
680
689
  return reconcileProjectionAgainstExisting(existing, projectSubscriptionFields(stream, existing));
681
690
  }
691
+ function liveSlotKey(existing, projected) {
692
+ if (isTerminalSubscriptionStatus(projected.status ?? existing.status)) return null;
693
+ return subscriptionSlotKey(
694
+ existing.referenceType ?? "user",
695
+ existing.referenceId,
696
+ projected.group === void 0 ? existing.group : projected.group
697
+ );
698
+ }
682
699
  async function persistSubscriptionProjection(adapter, existing, projection, log, source) {
683
700
  const stale = existing.providerUpdatedAt instanceof Date && projection.providerUpdatedAt instanceof Date && projection.providerUpdatedAt.getTime() < existing.providerUpdatedAt.getTime();
684
- if (!stale) {
685
- const updated = await adapter.update({
686
- model: SUBSCRIPTION_MODEL,
687
- update: projection,
688
- where: [
689
- { field: "id", value: existing.id },
690
- { field: "providerUpdatedAt", value: existing.providerUpdatedAt ?? null },
691
- { field: "streampaySubscriptionId", value: existing.streampaySubscriptionId ?? null },
692
- { field: "streampayConsumerId", value: existing.streampayConsumerId ?? null },
693
- { field: "status", value: existing.status },
694
- { field: "billingStatus", value: existing.billingStatus }
695
- ]
696
- });
697
- if (updated) return updated;
698
- }
701
+ const slotKey = liveSlotKey(existing, projection);
702
+ const movesSlot = slotKey !== null && existing.activeSlotKey !== slotKey;
703
+ const slotHolder = movesSlot ? await adapter.findOne({
704
+ model: SUBSCRIPTION_MODEL,
705
+ where: [{ field: "activeSlotKey", value: slotKey }]
706
+ }) : null;
707
+ const updated = stale || slotHolder ? null : await adapter.update({
708
+ model: SUBSCRIPTION_MODEL,
709
+ update: movesSlot ? { ...projection, activeSlotKey: slotKey } : projection,
710
+ where: [
711
+ { field: "id", value: existing.id },
712
+ { field: "providerUpdatedAt", value: existing.providerUpdatedAt ?? null },
713
+ { field: "streampaySubscriptionId", value: existing.streampaySubscriptionId ?? null },
714
+ { field: "streampayConsumerId", value: existing.streampayConsumerId ?? null },
715
+ { field: "status", value: existing.status },
716
+ { field: "billingStatus", value: existing.billingStatus },
717
+ { field: "renewedCycleNumber", value: existing.renewedCycleNumber ?? null }
718
+ ]
719
+ });
720
+ if (updated) return updated;
699
721
  log.warn(
700
- `${source}: retained newer local subscription state for row=${existing.id}. The provider action is not rolled back.`
722
+ slotHolder ? `${source}: StreamPay reports row=${existing.id} live, but row=${slotHolder.id} holds its billing slot. The next webhook reconciles it.` : `${source}: retained newer local subscription state for row=${existing.id}. The provider action is not rolled back.`
701
723
  );
702
724
  return adapter.findOne({
703
725
  model: SUBSCRIPTION_MODEL,
@@ -760,6 +782,9 @@ function projectSubscriptionFields(sub, existing) {
760
782
  periodStart,
761
783
  periodEnd,
762
784
  currentCycleNumber: sub.current_cycle_number ?? null,
785
+ // Only renewal evidence advances the baseline. Other writers only initialize it, so they can
786
+ // neither absorb a renewal nor roll back one that was just delivered.
787
+ ...existing?.renewedCycleNumber == null ? { renewedCycleNumber: existing?.currentCycleNumber ?? sub.current_cycle_number ?? null } : {},
763
788
  trialStart: (sub.trial_end ? parseDate(sub.started_at) ?? periodStart : null) ?? existing?.trialStart ?? null,
764
789
  trialEnd: parseDate(sub.trial_end),
765
790
  cancelAtPeriodEnd: Boolean(sub.cancel_at_period_end),
@@ -879,15 +904,120 @@ function projectPlanFields(sub, plans) {
879
904
  pendingSeatsEffectiveAt: pendingSeats === null ? null : pendingEffectiveAt
880
905
  };
881
906
  }
882
- function subscriptionSlotKey(referenceType, referenceId, group) {
883
- const tuple = JSON.stringify([referenceType, referenceId, group ?? null]);
884
- return `sp_slot_v1_${crypto.createHash("sha256").update(tuple).digest("hex")}`;
907
+
908
+ // src/plugins/subscriptions/lifecycle.ts
909
+ function isAlreadyCanceledFreezeError(err) {
910
+ const sdkError = readSdkErrorFields(err);
911
+ const envelope = readEnvelope(sdkError.body);
912
+ return sdkError.status === 403 && envelope?.code === "STREAM_ERROR" && envelope.additionalInfo === "Cannot delete non-latest freeze entry.";
913
+ }
914
+ async function deactivatePaymentLink(client, paymentLinkId, log) {
915
+ if (!client.updatePaymentLinkStatus) {
916
+ log.warn(
917
+ `payment link=${paymentLinkId} stays payable: client does not implement updatePaymentLinkStatus.`
918
+ );
919
+ return;
920
+ }
921
+ try {
922
+ await client.updatePaymentLinkStatus(paymentLinkId, { status: "INACTIVE" });
923
+ } catch (err) {
924
+ if (readSdkErrorFields(err).status !== 404) throw err;
925
+ }
926
+ }
927
+ function subscriptionCouponIds(stream) {
928
+ return couponIdsFromMetadata(stream.coupon_calculation_metadata);
929
+ }
930
+ function couponIdsFromMetadata(metadata) {
931
+ const coupons = [];
932
+ for (const coupon of metadata?.coupons ?? []) {
933
+ if (coupon.coupon_id) coupons.push(coupon.coupon_id);
934
+ }
935
+ return coupons;
936
+ }
937
+ function subscriptionItemsForUpdate(stream, currentProductId, targetProductId, targetSeats) {
938
+ if (!stream.items?.length) {
939
+ throw invalidProviderItems("StreamPay returned a subscription without any items.");
940
+ }
941
+ const subscriptionCoupons = new Set(subscriptionCouponIds(stream));
942
+ let matches = 0;
943
+ const items = stream.items.map((item) => {
944
+ const productId = subscriptionItemProductId(item);
945
+ const quantity = item.quantity ?? 1;
946
+ if (!productId || !Number.isSafeInteger(quantity) || quantity < 1) {
947
+ throw invalidProviderItems("StreamPay returned an invalid subscription item.");
948
+ }
949
+ const isPlanItem = productId === currentProductId;
950
+ if (isPlanItem) matches += 1;
951
+ const itemCoupons = couponIdsFromMetadata(item.coupon_calculation_metadata).filter(
952
+ (couponId) => !subscriptionCoupons.has(couponId)
953
+ );
954
+ return {
955
+ product_id: isPlanItem ? targetProductId : productId,
956
+ quantity: isPlanItem ? targetSeats : quantity,
957
+ ...itemCoupons.length > 0 ? { coupons: itemCoupons } : {}
958
+ };
959
+ });
960
+ if (matches !== 1) {
961
+ throw invalidProviderItems(
962
+ `Expected exactly one plan item for product "${currentProductId}", received ${matches}.`
963
+ );
964
+ }
965
+ return items;
966
+ }
967
+ function invalidProviderItems(message) {
968
+ return new api.APIError("INTERNAL_SERVER_ERROR", {
969
+ code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
970
+ message
971
+ });
972
+ }
973
+ function configuredPlanForSubscription(subscription, plans) {
974
+ const matches = plans.list.filter(
975
+ (plan) => subscription.items?.some((item) => subscriptionItemProductId(item) === plan.productId)
976
+ );
977
+ if (matches.length > 1) {
978
+ throw invalidProviderItems(
979
+ "StreamPay returned a subscription containing multiple configured plan products."
980
+ );
981
+ }
982
+ return matches[0];
983
+ }
984
+ async function findSubscriptionFreeze(client, options, subscriptionId, matches) {
985
+ const listPage = options.listSubscriptionFreezes;
986
+ if (!listPage) {
987
+ const response = await client.listSubscriptionFreezes(subscriptionId);
988
+ return {
989
+ freeze: response.data?.find(matches),
990
+ hasMore: response.pagination?.has_next_page ?? false
991
+ };
992
+ }
993
+ const seenIds = /* @__PURE__ */ new Set();
994
+ for (let page = 1; page <= 100; page++) {
995
+ const response = await listPage(subscriptionId, { page, limit: 100 });
996
+ const pagination = response.pagination;
997
+ if (!Array.isArray(response.data) || !pagination || pagination.current_page !== page || typeof pagination.has_next_page !== "boolean") {
998
+ throw freezePaginationConflict("StreamPay returned invalid freeze pagination.");
999
+ }
1000
+ let advanced = false;
1001
+ for (const freeze2 of response.data) {
1002
+ if (freeze2.id && !seenIds.has(freeze2.id)) {
1003
+ seenIds.add(freeze2.id);
1004
+ advanced = true;
1005
+ }
1006
+ }
1007
+ if (!advanced && (pagination.has_next_page || response.data.length > 0)) {
1008
+ throw freezePaginationConflict("StreamPay freeze pagination returned no new entries.");
1009
+ }
1010
+ const freeze = response.data.find(matches);
1011
+ if (freeze || !pagination.has_next_page) return { freeze, hasMore: false };
1012
+ }
1013
+ throw freezePaginationConflict("StreamPay freeze pagination exceeded 100 pages.");
1014
+ }
1015
+ function freezePaginationConflict(message) {
1016
+ return new api.APIError("CONFLICT", {
1017
+ code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
1018
+ message
1019
+ });
885
1020
  }
886
- var UPGRADE_IDEMPOTENCY_WINDOW_MS = 15 * 60 * 1e3;
887
- var PLAN_NAME_METADATA_KEY = "streampay_plugin_plan_name";
888
- var REFERENCE_ID_METADATA_KEY = "streampay_plugin_reference_id";
889
- var REFERENCE_TYPE_METADATA_KEY = "streampay_plugin_reference_type";
890
- var SUBSCRIPTION_ROW_ID_METADATA_KEY = "streampay_plugin_subscription_row_id";
891
1021
 
892
1022
  // src/plugins/subscriptions/sync.ts
893
1023
  var SUBSCRIPTION_MODEL2 = "subscription";
@@ -915,6 +1045,9 @@ function isUniqueConstraintError(err) {
915
1045
  }
916
1046
  var WEBHOOK_PROCESSING_LEASE_MS = 2 * 60 * 1e3;
917
1047
  var WEBHOOK_RETRY_DELAYS_MS = [5, 30, 120, 360, 720].map((minutes) => minutes * 60 * 1e3);
1048
+ function hasLiveLease(row, now) {
1049
+ return row.lockedAt instanceof Date && now.getTime() - row.lockedAt.getTime() < WEBHOOK_PROCESSING_LEASE_MS;
1050
+ }
918
1051
  var WebhookEventInProgressError = class extends Error {
919
1052
  constructor(eventType) {
920
1053
  super(`Webhook ${eventType} is already being processed; retry later.`);
@@ -999,7 +1132,7 @@ async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader
999
1132
  );
1000
1133
  return { action: "skip", reason: "dead_letter" };
1001
1134
  }
1002
- if (existing.lockedAt instanceof Date && now.getTime() - existing.lockedAt.getTime() < WEBHOOK_PROCESSING_LEASE_MS) {
1135
+ if (hasLiveLease(existing, now)) {
1003
1136
  logger(ctx).info(
1004
1137
  `webhook ${payload.event_type} (${eventId}) is already being processed \u2014 skipping concurrent delivery.`
1005
1138
  );
@@ -1015,15 +1148,15 @@ async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader
1015
1148
  lastAttemptAt: now,
1016
1149
  deadLetteredAt: now,
1017
1150
  nextAttemptAt: null,
1018
- rawPayload: rawBody,
1019
- signatureHeader,
1151
+ ...rawBody !== null ? { rawPayload: rawBody, signatureHeader } : {},
1020
1152
  lockedAt: null,
1021
1153
  lockedBy: null
1022
1154
  },
1023
1155
  where: [
1024
1156
  { field: "id", value: existing.id },
1025
1157
  { field: "status", value: "pending" },
1026
- { field: "lockedAt", value: existing.lockedAt ?? null }
1158
+ { field: "lockedAt", value: existing.lockedAt ?? null },
1159
+ { field: "attemptCount", value: existing.attemptCount ?? null }
1027
1160
  ]
1028
1161
  });
1029
1162
  return updated2 ? { action: "dead_letter", row: updated2 } : { action: "skip", reason: "in_progress" };
@@ -1035,19 +1168,21 @@ async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader
1035
1168
  lastAttemptAt: now,
1036
1169
  nextAttemptAt: null,
1037
1170
  lockedAt: now,
1038
- lockedBy: lockId
1171
+ lockedBy: lockId,
1172
+ ...rawBody !== null ? { rawPayload: rawBody, signatureHeader } : {}
1039
1173
  },
1040
1174
  where: [
1041
1175
  { field: "id", value: existing.id },
1042
1176
  { field: "status", value: "pending" },
1043
- { field: "lockedAt", value: existing.lockedAt ?? null }
1177
+ { field: "lockedAt", value: existing.lockedAt ?? null },
1178
+ { field: "attemptCount", value: existing.attemptCount ?? null }
1044
1179
  ]
1045
1180
  });
1046
1181
  return updated ? { action: "process", row: updated } : { action: "skip", reason: "in_progress" };
1047
1182
  }
1048
1183
  async function claimWebhookEventForReplay(ctx, row) {
1049
1184
  const now = /* @__PURE__ */ new Date();
1050
- if (row.lockedAt instanceof Date && now.getTime() - row.lockedAt.getTime() < WEBHOOK_PROCESSING_LEASE_MS) {
1185
+ if (hasLiveLease(row, now)) {
1051
1186
  return null;
1052
1187
  }
1053
1188
  return ctx.context.adapter.update({
@@ -1065,30 +1200,71 @@ async function claimWebhookEventForReplay(ctx, row) {
1065
1200
  where: [
1066
1201
  { field: "id", value: row.id },
1067
1202
  { field: "status", value: row.status },
1068
- { field: "lockedAt", value: row.lockedAt ?? null }
1203
+ { field: "lockedAt", value: row.lockedAt ?? null },
1204
+ { field: "attemptCount", value: row.attemptCount ?? null }
1069
1205
  ]
1070
1206
  });
1071
1207
  }
1072
- async function markWebhookEventCompleted(ctx, rowId, lockId) {
1208
+ function isStillDueWebhookEvent(row, selectedAttemptCount, now) {
1209
+ const retryDue = row.nextAttemptAt instanceof Date && row.nextAttemptAt <= now;
1210
+ const leaseAbandoned = row.lockedAt instanceof Date && !hasLiveLease(row, now);
1211
+ return row.status === "pending" && row.attemptCount === selectedAttemptCount && (retryDue || leaseAbandoned);
1212
+ }
1213
+ async function parkUnreplayableWebhookEvent(ctx, row, reason) {
1214
+ if (row.status !== "pending" || hasLiveLease(row, /* @__PURE__ */ new Date())) return;
1073
1215
  await ctx.context.adapter.update({
1074
1216
  model: WEBHOOK_EVENT_MODEL,
1075
1217
  update: {
1076
- status: "completed",
1077
- completedAt: /* @__PURE__ */ new Date(),
1078
1218
  nextAttemptAt: null,
1079
1219
  lockedAt: null,
1080
1220
  lockedBy: null,
1081
- rawPayload: null,
1082
- signatureHeader: null,
1083
- lastError: null,
1084
- lastErrorCode: null
1221
+ lastError: reason,
1222
+ lastErrorCode: "UNREPLAYABLE_PAYLOAD"
1085
1223
  },
1224
+ where: [
1225
+ { field: "id", value: row.id },
1226
+ { field: "status", value: "pending" },
1227
+ { field: "lockedAt", value: row.lockedAt ?? null },
1228
+ { field: "attemptCount", value: row.attemptCount ?? null }
1229
+ ]
1230
+ });
1231
+ }
1232
+ function completedWebhookEventFields() {
1233
+ return {
1234
+ status: "completed",
1235
+ completedAt: /* @__PURE__ */ new Date(),
1236
+ nextAttemptAt: null,
1237
+ lockedAt: null,
1238
+ lockedBy: null,
1239
+ rawPayload: null,
1240
+ signatureHeader: null,
1241
+ lastError: null,
1242
+ lastErrorCode: null
1243
+ };
1244
+ }
1245
+ async function markWebhookEventCompleted(ctx, rowId, lockId) {
1246
+ await ctx.context.adapter.update({
1247
+ model: WEBHOOK_EVENT_MODEL,
1248
+ update: completedWebhookEventFields(),
1086
1249
  where: [
1087
1250
  { field: "id", value: rowId },
1088
1251
  ...lockId ? [{ field: "lockedBy", value: lockId }] : []
1089
1252
  ]
1090
1253
  });
1091
1254
  }
1255
+ async function completeUnchangedWebhookEvent(ctx, row) {
1256
+ const updated = await ctx.context.adapter.update({
1257
+ model: WEBHOOK_EVENT_MODEL,
1258
+ update: completedWebhookEventFields(),
1259
+ where: [
1260
+ { field: "id", value: row.id },
1261
+ { field: "status", value: row.status },
1262
+ { field: "lockedAt", value: row.lockedAt ?? null },
1263
+ { field: "attemptCount", value: row.attemptCount ?? null }
1264
+ ]
1265
+ });
1266
+ return updated !== null;
1267
+ }
1092
1268
  async function recordWebhookEventFailure(ctx, rowId, rawBody, signatureHeader, err, lockId, deadLetter = false) {
1093
1269
  const lastError = err instanceof Error ? err.message : String(err);
1094
1270
  const sdkError = readSdkErrorFields(err);
@@ -1207,12 +1383,106 @@ var SubscriptionCorrelationError = class extends Error {
1207
1383
  this.name = "SubscriptionCorrelationError";
1208
1384
  }
1209
1385
  };
1210
- async function updateReconciledSubscription(ctx, existing, projected, streampaySubscriptionId) {
1386
+ function providerStateConfirmsEvent(eventType, stream) {
1387
+ switch (eventType) {
1388
+ case "SUBSCRIPTION_CREATED":
1389
+ return true;
1390
+ case "SUBSCRIPTION_ACTIVATED":
1391
+ case "SUBSCRIPTION_UNFREEZE_NOW":
1392
+ return stream.status === "ACTIVE" || stream.status === "TRIALING";
1393
+ case "SUBSCRIPTION_CANCELED":
1394
+ return stream.status === "CANCELED";
1395
+ case "SUBSCRIPTION_INACTIVATED":
1396
+ return stream.status === "INACTIVE";
1397
+ case "SUBSCRIPTION_CANCEL_AT_PERIOD_END":
1398
+ return Boolean(stream.cancel_at_period_end) && !isTerminalSubscriptionStatus(toLocalStatus(stream.status));
1399
+ case "SUBSCRIPTION_FROZEN":
1400
+ case "SUBSCRIPTION_FREEZE_NOW":
1401
+ return stream.status === "FROZEN";
1402
+ case "SUBSCRIPTION_PLAN_CHANGE_SCHEDULED":
1403
+ return Boolean(stream.pending_change);
1404
+ case "SUBSCRIPTION_PLAN_CHANGE_CANCELED":
1405
+ return !stream.pending_change;
1406
+ default:
1407
+ return false;
1408
+ }
1409
+ }
1410
+ async function takeSlotFromReservation(ctx, client, slotKey, ownerRowId, streampaySubscriptionId) {
1411
+ const holder = await ctx.context.adapter.findOne({
1412
+ model: SUBSCRIPTION_MODEL2,
1413
+ where: [{ field: "activeSlotKey", value: slotKey }]
1414
+ });
1415
+ if (!holder || holder.id === ownerRowId) return;
1416
+ if (holder.streampaySubscriptionId === streampaySubscriptionId) {
1417
+ throw new Error(
1418
+ `StreamPay sub=${streampaySubscriptionId} was linked to row=${holder.id} concurrently. Retry delivery.`
1419
+ );
1420
+ }
1421
+ if (holder.status !== "incomplete" || holder.streampaySubscriptionId) {
1422
+ throw new SubscriptionCorrelationError(
1423
+ `StreamPay sub=${streampaySubscriptionId} needs the billing slot held by live row=${holder.id} (${holder.status}). Resolve the duplicate subscription, then replay.`
1424
+ );
1425
+ }
1426
+ if (holder.streampayPaymentLinkId) {
1427
+ try {
1428
+ await deactivatePaymentLink(client, holder.streampayPaymentLinkId, logger(ctx));
1429
+ } catch (err) {
1430
+ const message = err instanceof Error ? err.message : String(err);
1431
+ logger(ctx).error(
1432
+ `payment link=${holder.streampayPaymentLinkId} of released row=${holder.id} could not be deactivated and may still be paid; deactivate it manually: ${message}`
1433
+ );
1434
+ }
1435
+ }
1436
+ const released = await ctx.context.adapter.update({
1437
+ model: SUBSCRIPTION_MODEL2,
1438
+ update: { status: "incomplete_expired", activeSlotKey: null, updatedAt: /* @__PURE__ */ new Date() },
1439
+ where: [
1440
+ { field: "id", value: holder.id },
1441
+ { field: "status", value: "incomplete" },
1442
+ { field: "activeSlotKey", value: slotKey },
1443
+ { field: "streampayPaymentLinkId", value: holder.streampayPaymentLinkId ?? null }
1444
+ ]
1445
+ });
1446
+ if (!released) {
1447
+ throw new Error(`Checkout reservation row=${holder.id} changed while releasing its slot.`);
1448
+ }
1449
+ logger(ctx).warn(
1450
+ `released checkout reservation row=${holder.id} for paid StreamPay sub=${streampaySubscriptionId}.`
1451
+ );
1452
+ }
1453
+ async function linkReservedRow(ctx, client, row, projected, metadataReferenceType, streampaySubscriptionId) {
1454
+ const activeSlotKey = projected.activeSlotKey === null ? null : row.activeSlotKey ?? subscriptionSlotKey(
1455
+ row.referenceType ?? metadataReferenceType ?? "user",
1456
+ row.referenceId,
1457
+ projected.group === void 0 ? row.group : projected.group
1458
+ );
1459
+ return updateReconciledSubscription(
1460
+ ctx,
1461
+ client,
1462
+ row,
1463
+ {
1464
+ ...projected,
1465
+ billingStatus: row.billingStatus ?? "current",
1466
+ ...activeSlotKey === null ? {} : { activeSlotKey }
1467
+ },
1468
+ streampaySubscriptionId
1469
+ );
1470
+ }
1471
+ async function updateReconciledSubscription(ctx, client, existing, projected, streampaySubscriptionId) {
1211
1472
  if (existing.providerUpdatedAt instanceof Date && projected.providerUpdatedAt instanceof Date && projected.providerUpdatedAt.getTime() < existing.providerUpdatedAt.getTime()) {
1212
1473
  throw new Error(
1213
1474
  `StreamPay returned stale subscription state for sub=${streampaySubscriptionId}. Retry reconciliation.`
1214
1475
  );
1215
1476
  }
1477
+ if (projected.activeSlotKey && projected.activeSlotKey !== existing.activeSlotKey) {
1478
+ await takeSlotFromReservation(
1479
+ ctx,
1480
+ client,
1481
+ projected.activeSlotKey,
1482
+ existing.id,
1483
+ streampaySubscriptionId
1484
+ );
1485
+ }
1216
1486
  const updated = await ctx.context.adapter.update({
1217
1487
  model: SUBSCRIPTION_MODEL2,
1218
1488
  update: projected,
@@ -1222,7 +1492,8 @@ async function updateReconciledSubscription(ctx, existing, projected, streampayS
1222
1492
  { field: "streampaySubscriptionId", value: existing.streampaySubscriptionId ?? null },
1223
1493
  { field: "streampayConsumerId", value: existing.streampayConsumerId ?? null },
1224
1494
  { field: "status", value: existing.status },
1225
- { field: "billingStatus", value: existing.billingStatus }
1495
+ { field: "billingStatus", value: existing.billingStatus },
1496
+ { field: "renewedCycleNumber", value: existing.renewedCycleNumber ?? null }
1226
1497
  ]
1227
1498
  });
1228
1499
  if (!updated) {
@@ -1257,15 +1528,16 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
1257
1528
  const eventIsStale = Boolean(
1258
1529
  eventAt && existing?.providerUpdatedAt instanceof Date && eventAt.getTime() < existing.providerUpdatedAt.getTime()
1259
1530
  );
1260
- if (!eventIsStale && payload.event_type === "SUBSCRIPTION_CYCLE_RENEWAL_FAILED" && projected.status === "active") {
1531
+ const eventApplies = !eventIsStale || providerStateConfirmsEvent(payload.event_type, stream);
1532
+ if (eventApplies && payload.event_type === "SUBSCRIPTION_CYCLE_RENEWAL_FAILED" && projected.status === "active") {
1261
1533
  projected.status = "past_due";
1262
1534
  projected.billingStatus = "past_due";
1263
1535
  }
1264
- const schedulesCancellation = !eventIsStale && payload.event_type === "SUBSCRIPTION_CANCEL_AT_PERIOD_END" && Boolean(stream.cancel_at_period_end);
1536
+ const schedulesCancellation = eventApplies && payload.event_type === "SUBSCRIPTION_CANCEL_AT_PERIOD_END" && Boolean(stream.cancel_at_period_end);
1265
1537
  if (schedulesCancellation) {
1266
1538
  projected.cancelAt = parseDate(stream.current_period_end);
1267
1539
  }
1268
- const confirmsCancellation = !eventIsStale && payload.event_type === "SUBSCRIPTION_CANCELED" && projected.status === "canceled";
1540
+ const confirmsCancellation = eventApplies && payload.event_type === "SUBSCRIPTION_CANCELED" && projected.status === "canceled";
1269
1541
  if (confirmsCancellation) {
1270
1542
  projected.activeSlotKey = null;
1271
1543
  }
@@ -1274,25 +1546,22 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
1274
1546
  stampCancelScheduled: schedulesCancellation,
1275
1547
  stampCanceled: confirmsCancellation
1276
1548
  });
1549
+ if (schedulesCancellation && eventAt && existing?.cancelAtPeriodEnd && !existing.cancelScheduledAt) {
1550
+ projected.cancelScheduledAt = eventAt;
1551
+ }
1277
1552
  if (existing) {
1278
- const projectedStatus = projected.status ?? existing.status;
1279
- if (!isTerminalSubscriptionStatus(projectedStatus)) {
1280
- const desiredSlotKey = subscriptionSlotKey(
1281
- existing.referenceType ?? "user",
1282
- existing.referenceId,
1283
- projected.group === void 0 ? existing.group : projected.group
1284
- );
1285
- if (existing.activeSlotKey !== desiredSlotKey) {
1286
- projected.activeSlotKey = desiredSlotKey;
1287
- }
1553
+ const slotKey = liveSlotKey(existing, projected);
1554
+ if (slotKey && existing.activeSlotKey !== slotKey) {
1555
+ projected.activeSlotKey = slotKey;
1288
1556
  }
1289
1557
  const updated = await updateReconciledSubscription(
1290
1558
  ctx,
1559
+ client,
1291
1560
  existing,
1292
1561
  projected,
1293
1562
  streampaySubscriptionId
1294
1563
  );
1295
- if (eventIsStale) {
1564
+ if (!eventApplies) {
1296
1565
  logger(ctx).info(
1297
1566
  `webhook ${payload.event_type}: ignored stale lifecycle callback for sub=${streampaySubscriptionId}.`
1298
1567
  );
@@ -1321,21 +1590,12 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
1321
1590
  `webhook ${payload.event_type}: referenced subscription row=${localRowId} is missing; rebuilding from signed metadata.`
1322
1591
  );
1323
1592
  } else if (metadataRow.referenceId === referenceId && (!metadataReferenceType || (metadataRow.referenceType ?? "user") === metadataReferenceType) && metadataRow.plan === planName && (!metadataRow.streampayConsumerId || !stream.organization_consumer_id || metadataRow.streampayConsumerId === stream.organization_consumer_id) && (!metadataRow.streampaySubscriptionId || metadataRow.streampaySubscriptionId === streampaySubscriptionId) && (!metadataRow.streampayPaymentLinkId || !paymentLinkId || metadataRow.streampayPaymentLinkId === paymentLinkId)) {
1324
- const projectedWithSlot = {
1325
- ...projected,
1326
- billingStatus: metadataRow.billingStatus ?? "current",
1327
- ...projected.activeSlotKey === null ? {} : {
1328
- activeSlotKey: metadataRow.activeSlotKey ?? subscriptionSlotKey(
1329
- metadataRow.referenceType ?? metadataReferenceType ?? "user",
1330
- metadataRow.referenceId,
1331
- projected.group === void 0 ? metadataRow.group : projected.group
1332
- )
1333
- }
1334
- };
1335
- const updated = await updateReconciledSubscription(
1593
+ const updated = await linkReservedRow(
1336
1594
  ctx,
1595
+ client,
1337
1596
  metadataRow,
1338
- projectedWithSlot,
1597
+ projected,
1598
+ metadataReferenceType,
1339
1599
  streampaySubscriptionId
1340
1600
  );
1341
1601
  return { row: updated, stream };
@@ -1358,30 +1618,22 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
1358
1618
  stream.organization_consumer_id ?? null
1359
1619
  );
1360
1620
  if (incomplete) {
1361
- const projectedWithSlot = {
1362
- ...projected,
1363
- billingStatus: incomplete.billingStatus ?? "current",
1364
- ...projected.activeSlotKey === null ? {} : {
1365
- activeSlotKey: incomplete.activeSlotKey ?? subscriptionSlotKey(
1366
- incomplete.referenceType ?? metadataReferenceType ?? "user",
1367
- incomplete.referenceId,
1368
- projected.group === void 0 ? incomplete.group : projected.group
1369
- )
1370
- }
1371
- };
1372
- const updated = await updateReconciledSubscription(
1621
+ const updated = await linkReservedRow(
1373
1622
  ctx,
1623
+ client,
1374
1624
  incomplete,
1375
- projectedWithSlot,
1625
+ projected,
1626
+ metadataReferenceType,
1376
1627
  streampaySubscriptionId
1377
1628
  );
1378
- return {
1379
- row: updated,
1380
- stream
1381
- };
1629
+ return { row: updated, stream };
1382
1630
  }
1383
1631
  const plan = plans.byName.get(planName);
1384
1632
  const referenceType = metadataReferenceType ?? "custom";
1633
+ const activeSlotKey = isTerminalSubscriptionStatus(projected.status) ? null : subscriptionSlotKey(referenceType, referenceId, plan?.group);
1634
+ if (activeSlotKey) {
1635
+ await takeSlotFromReservation(ctx, client, activeSlotKey, null, streampaySubscriptionId);
1636
+ }
1385
1637
  const row = await ctx.context.adapter.create({
1386
1638
  model: SUBSCRIPTION_MODEL2,
1387
1639
  data: {
@@ -1390,7 +1642,7 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
1390
1642
  ...projected,
1391
1643
  referenceId,
1392
1644
  referenceType,
1393
- activeSlotKey: isTerminalSubscriptionStatus(projected.status) ? null : subscriptionSlotKey(referenceType, referenceId, plan?.group),
1645
+ activeSlotKey,
1394
1646
  streampayPaymentLinkId: paymentLinkId,
1395
1647
  plan: planName,
1396
1648
  planVersion: plan?.version ?? null,
@@ -1438,7 +1690,8 @@ async function syncWebhookPayload(ctx, payload, client, plans, callbacks, option
1438
1690
  retryOnCallbackError,
1439
1691
  options.retryingRenewalCallback === true || claim.row?.lastError?.startsWith(
1440
1692
  "Subscription callback onSubscriptionRenewed failed:"
1441
- ) === true
1693
+ ) === true,
1694
+ options.inboxEnabled ?? dedupe
1442
1695
  );
1443
1696
  } else {
1444
1697
  const { row, stream } = await reconcileFromStreamPay(ctx, payload, client, plans);
@@ -1470,7 +1723,28 @@ async function syncWebhookPayload(ctx, payload, client, plans, callbacks, option
1470
1723
  throw err;
1471
1724
  }
1472
1725
  }
1473
- async function handleRenewalEvidence(ctx, payload, client, plans, callbacks, retryOnCallbackError, retryingRenewalCallback) {
1726
+ async function releaseLockOfCompletedRenewal(ctx, subscriptionRowId, lockEventId) {
1727
+ const owner = await ctx.context.adapter.findOne({
1728
+ model: WEBHOOK_EVENT_MODEL,
1729
+ where: [{ field: "eventId", value: lockEventId }]
1730
+ });
1731
+ if (owner?.status !== "completed") return false;
1732
+ const released = await ctx.context.adapter.update({
1733
+ model: SUBSCRIPTION_MODEL2,
1734
+ update: { renewalCallbackEventId: null },
1735
+ where: [
1736
+ { field: "id", value: subscriptionRowId },
1737
+ { field: "renewalCallbackEventId", value: lockEventId }
1738
+ ]
1739
+ });
1740
+ if (released) {
1741
+ logger(ctx).warn(
1742
+ `released renewal callback lock of completed event ${lockEventId} for row=${subscriptionRowId}.`
1743
+ );
1744
+ }
1745
+ return released !== null;
1746
+ }
1747
+ async function handleRenewalEvidence(ctx, payload, client, plans, callbacks, retryOnCallbackError, retryingRenewalCallback, inboxEnabled) {
1474
1748
  const invoiceId = payload.data?.invoice?.id ?? payload.entity_id;
1475
1749
  if (!invoiceId) return;
1476
1750
  let subscriptionId = payload.entity_type === "SUBSCRIPTION" ? payload.entity_id : null;
@@ -1502,27 +1776,55 @@ async function handleRenewalEvidence(ctx, payload, client, plans, callbacks, ret
1502
1776
  const eventIsStale = Boolean(
1503
1777
  eventAt && existing.providerUpdatedAt instanceof Date && eventAt.getTime() < existing.providerUpdatedAt.getTime()
1504
1778
  );
1779
+ const evidenceInvoiceId = payload.data?.invoice?.id ?? (payload.entity_type === "INVOICE" ? payload.entity_id : null);
1780
+ const settlesLatestInvoice = stream.latest_invoice?.status === "COMPLETED" && (evidenceInvoiceId === null || stream.latest_invoice.id === evidenceInvoiceId);
1781
+ const evidenceApplies = !eventIsStale || settlesLatestInvoice;
1505
1782
  const projected = {
1506
1783
  ...projectSubscriptionFields(stream, existing),
1507
1784
  ...projectPlanFields(stream, plans),
1508
- ...eventIsStale ? existing.billingStatus === "past_due" && toLocalStatus(stream.status) === "active" ? { status: "past_due", billingStatus: "past_due" } : {} : { billingStatus: "current" }
1785
+ ...evidenceApplies ? { billingStatus: "current" } : existing.billingStatus === "past_due" && toLocalStatus(stream.status) === "active" ? { status: "past_due", billingStatus: "past_due" } : {}
1509
1786
  };
1787
+ const slotKey = liveSlotKey(existing, projected);
1788
+ if (slotKey && existing.activeSlotKey !== slotKey) {
1789
+ projected.activeSlotKey = slotKey;
1790
+ }
1510
1791
  const previousPeriodEnd = existing.periodEnd?.getTime() ?? null;
1511
1792
  const projectedPeriodEnd = projected.periodEnd?.getTime() ?? null;
1512
1793
  const periodAdvanced = previousPeriodEnd !== null && projectedPeriodEnd !== null && projectedPeriodEnd > previousPeriodEnd;
1513
- const cycleAdvanced = existing.currentCycleNumber !== null && existing.currentCycleNumber !== void 0 && projected.currentCycleNumber !== null && projected.currentCycleNumber !== void 0 && projected.currentCycleNumber > existing.currentCycleNumber;
1794
+ const renewedCycle = existing.renewedCycleNumber ?? existing.currentCycleNumber ?? null;
1795
+ const projectedCycle = projected.currentCycleNumber ?? null;
1796
+ const tracksCycles = renewedCycle !== null && projectedCycle !== null;
1797
+ const renewalAdvanced = tracksCycles ? projectedCycle > renewedCycle : periodAdvanced;
1514
1798
  const eventId = extractEventId(payload);
1515
- const pendingCallback = existing.renewalCallbackEventId ?? null;
1799
+ let pendingCallback = existing.renewalCallbackEventId ?? null;
1800
+ if (pendingCallback && pendingCallback !== eventId) {
1801
+ const released = inboxEnabled && await releaseLockOfCompletedRenewal(ctx, existing.id, pendingCallback);
1802
+ if (!released) {
1803
+ throw new Error(
1804
+ `Subscription renewal callback ${pendingCallback} is pending; retry delivery.`
1805
+ );
1806
+ }
1807
+ pendingCallback = null;
1808
+ }
1516
1809
  if (!pendingCallback && existing.providerUpdatedAt instanceof Date && projected.providerUpdatedAt instanceof Date && projected.providerUpdatedAt.getTime() < existing.providerUpdatedAt.getTime()) {
1517
1810
  throw new Error(
1518
1811
  `StreamPay returned stale subscription state for sub=${subscriptionId}; retry delivery.`
1519
1812
  );
1520
1813
  }
1521
- if (pendingCallback && pendingCallback !== eventId) {
1522
- throw new Error(`Subscription renewal callback ${pendingCallback} is pending; retry delivery.`);
1814
+ if (!pendingCallback && projected.activeSlotKey && projected.activeSlotKey !== existing.activeSlotKey) {
1815
+ await takeSlotFromReservation(
1816
+ ctx,
1817
+ client,
1818
+ projected.activeSlotKey,
1819
+ existing.id,
1820
+ subscriptionId
1821
+ );
1523
1822
  }
1524
- const deliverCallback = pendingCallback === eventId && pendingCallback !== null || !eventIsStale && (periodAdvanced || cycleAdvanced || retryingRenewalCallback);
1823
+ const deliverCallback = pendingCallback === eventId && pendingCallback !== null || evidenceApplies && (renewalAdvanced || retryingRenewalCallback);
1525
1824
  const callbackOwner = deliverCallback && callbacks.onSubscriptionRenewed ? eventId : null;
1825
+ if (deliverCallback && renewalAdvanced && projectedCycle !== null) {
1826
+ projected.renewedCycleNumber = projectedCycle;
1827
+ }
1526
1828
  const updated = await ctx.context.adapter.update({
1527
1829
  model: SUBSCRIPTION_MODEL2,
1528
1830
  // Recovery must retain the pending cycle, even if Stream has already advanced again.
@@ -1531,6 +1833,7 @@ async function handleRenewalEvidence(ctx, payload, client, plans, callbacks, ret
1531
1833
  { field: "id", value: existing.id },
1532
1834
  { field: "periodEnd", value: existing.periodEnd ?? null },
1533
1835
  { field: "currentCycleNumber", value: existing.currentCycleNumber ?? null },
1836
+ { field: "renewedCycleNumber", value: existing.renewedCycleNumber ?? null },
1534
1837
  { field: "renewalCallbackEventId", value: pendingCallback },
1535
1838
  { field: "providerUpdatedAt", value: existing.providerUpdatedAt ?? null },
1536
1839
  { field: "status", value: existing.status },
@@ -1543,8 +1846,8 @@ async function handleRenewalEvidence(ctx, payload, client, plans, callbacks, ret
1543
1846
  }
1544
1847
  const latest = await findSubscriptionByStreampayId(ctx, subscriptionId);
1545
1848
  const anotherCallbackOwner = latest?.renewalCallbackEventId;
1546
- const desiredCycleAdvanced = (periodAdvanced || cycleAdvanced) && (!periodAdvanced || (latest?.periodEnd?.getTime() ?? 0) >= (projectedPeriodEnd ?? 0)) && (!cycleAdvanced || (latest?.currentCycleNumber ?? 0) >= (projected.currentCycleNumber ?? 0));
1547
- if (anotherCallbackOwner && anotherCallbackOwner !== eventId && desiredCycleAdvanced) return;
1849
+ const renewalClaimedElsewhere = renewalAdvanced && (tracksCycles ? (latest?.renewedCycleNumber ?? 0) >= projectedCycle : (latest?.periodEnd?.getTime() ?? 0) >= (projectedPeriodEnd ?? 0));
1850
+ if (anotherCallbackOwner && anotherCallbackOwner !== eventId && renewalClaimedElsewhere) return;
1548
1851
  throw new Error(`Subscription changed during renewal reconciliation; retry delivery.`);
1549
1852
  }
1550
1853
  const row = updated;
@@ -2632,6 +2935,12 @@ function buildWebhookEventsEndpoints(adminOptions, registry) {
2632
2935
  message: `Webhook event ${ctx.params.eventId} not found.`
2633
2936
  });
2634
2937
  }
2938
+ const inProgress = new api.APIError("CONFLICT", {
2939
+ code: $ERROR_CODES.WEBHOOK_REPLAY_IN_PROGRESS.code,
2940
+ message: `Webhook event ${ctx.params.eventId} is being processed. Retry after its lease expires.`
2941
+ });
2942
+ if (row.status === "pending" && hasLiveLease(row, /* @__PURE__ */ new Date())) throw inProgress;
2943
+ if (!await completeUnchangedWebhookEvent({ context: { adapter } }, row)) throw inProgress;
2635
2944
  if (registry?.subscriptionWebhookSync && !eventId.startsWith("handlers:") && (row.eventType === "INVOICE_COMPLETED" || row.eventType === "SUBSCRIPTION_CYCLE_RENEWED_SUCCESSFULLY")) {
2636
2945
  const subscription = await adapter.findOne({
2637
2946
  model: "subscription",
@@ -2648,7 +2957,6 @@ function buildWebhookEventsEndpoints(adminOptions, registry) {
2648
2957
  });
2649
2958
  }
2650
2959
  }
2651
- await markWebhookEventCompleted({ context: { adapter } }, row.id);
2652
2960
  return ctx.json({ discarded: true, eventId });
2653
2961
  }
2654
2962
  )
@@ -3233,7 +3541,8 @@ var SUBSCRIPTION_MODEL4 = "subscription";
3233
3541
  async function recoverCheckoutUrl(client, row) {
3234
3542
  if (!row.streampayPaymentLinkId) return { kind: "expired" };
3235
3543
  try {
3236
- const url = client.getPaymentUrl(await client.getPaymentLink(row.streampayPaymentLinkId));
3544
+ const link = await client.getPaymentLink(row.streampayPaymentLinkId);
3545
+ const url = link.status === "INACTIVE" ? null : client.getPaymentUrl(link);
3237
3546
  return url ? { kind: "recovered", url } : { kind: "expired" };
3238
3547
  } catch (err) {
3239
3548
  if (readSdkErrorFields(err).status === 404) return { kind: "expired" };
@@ -3260,6 +3569,12 @@ function checkoutInProgressError() {
3260
3569
  message: "A subscription checkout is already being created for this plan group."
3261
3570
  });
3262
3571
  }
3572
+ function subscriptionAlreadyActiveError() {
3573
+ return new api.APIError("CONFLICT", {
3574
+ code: $ERROR_CODES.SUBSCRIPTION_ALREADY_ACTIVE.code,
3575
+ message: "An active subscription already exists for this plan group."
3576
+ });
3577
+ }
3263
3578
  async function resumeOrReserveCheckoutSlot(args) {
3264
3579
  const { client, adapter, candidates, activeSlotKey, planName, seats, now, log } = args;
3265
3580
  const matchesCheckout = (row2) => row2.plan === planName && (row2.seats ?? 1) === seats;
@@ -3306,8 +3621,11 @@ async function resumeOrReserveCheckoutSlot(args) {
3306
3621
  model: SUBSCRIPTION_MODEL4,
3307
3622
  where: [{ field: "activeSlotKey", value: activeSlotKey }]
3308
3623
  });
3309
- if (reserved?.status !== "incomplete") throw err;
3310
- if (matchesCheckout(reserved)) {
3624
+ if (!reserved) throw err;
3625
+ if (reserved.status !== "incomplete") throw subscriptionAlreadyActiveError();
3626
+ const reservationIsStale = !(reserved.createdAt instanceof Date) || now - reserved.createdAt.getTime() >= UPGRADE_IDEMPOTENCY_WINDOW_MS;
3627
+ let linkExpired = false;
3628
+ if (!reservationIsStale && matchesCheckout(reserved)) {
3311
3629
  let recovery;
3312
3630
  try {
3313
3631
  recovery = await recoverCheckoutUrl(client, reserved);
@@ -3324,16 +3642,31 @@ async function resumeOrReserveCheckoutSlot(args) {
3324
3642
  if (recovery.kind === "recovered") {
3325
3643
  return { kind: "recovered", row: reserved, url: recovery.url };
3326
3644
  }
3645
+ linkExpired = Boolean(reserved.streampayPaymentLinkId);
3646
+ }
3647
+ if (!reservationIsStale && !linkExpired) throw checkoutInProgressError();
3648
+ if (reservationIsStale && reserved.streampayPaymentLinkId) {
3649
+ try {
3650
+ await deactivatePaymentLink(client, reserved.streampayPaymentLinkId, log);
3651
+ } catch (deactivationError) {
3652
+ toAPIError(
3653
+ {
3654
+ logPrefix: `deactivate stale checkout link=${reserved.streampayPaymentLinkId} failed for row=${reserved.id}:`,
3655
+ userMessage: "Unable to replace the previous subscription checkout."
3656
+ },
3657
+ deactivationError,
3658
+ log
3659
+ );
3660
+ }
3327
3661
  }
3328
- const reservationIsStale = !(reserved.createdAt instanceof Date) || now - reserved.createdAt.getTime() >= UPGRADE_IDEMPOTENCY_WINDOW_MS;
3329
- if (!reservationIsStale) throw checkoutInProgressError();
3330
3662
  const released = await adapter.update({
3331
3663
  model: SUBSCRIPTION_MODEL4,
3332
3664
  update: { status: "incomplete_expired", activeSlotKey: null, updatedAt: /* @__PURE__ */ new Date() },
3333
3665
  where: [
3334
3666
  { field: "id", value: reserved.id },
3335
3667
  { field: "status", value: "incomplete" },
3336
- { field: "activeSlotKey", value: activeSlotKey }
3668
+ { field: "activeSlotKey", value: activeSlotKey },
3669
+ { field: "streampayPaymentLinkId", value: reserved.streampayPaymentLinkId ?? null }
3337
3670
  ]
3338
3671
  });
3339
3672
  if (!released) throw checkoutInProgressError();
@@ -3350,105 +3683,6 @@ async function resumeOrReserveCheckoutSlot(args) {
3350
3683
  }
3351
3684
  return { kind: "reserved", row, consumerId };
3352
3685
  }
3353
- function isAlreadyCanceledFreezeError(err) {
3354
- const sdkError = readSdkErrorFields(err);
3355
- const envelope = readEnvelope(sdkError.body);
3356
- return sdkError.status === 403 && envelope?.code === "STREAM_ERROR" && envelope.additionalInfo === "Cannot delete non-latest freeze entry.";
3357
- }
3358
- function subscriptionCouponIds(stream) {
3359
- return couponIdsFromMetadata(stream.coupon_calculation_metadata);
3360
- }
3361
- function couponIdsFromMetadata(metadata) {
3362
- const coupons = [];
3363
- for (const coupon of metadata?.coupons ?? []) {
3364
- if (coupon.coupon_id) coupons.push(coupon.coupon_id);
3365
- }
3366
- return coupons;
3367
- }
3368
- function subscriptionItemsForUpdate(stream, currentProductId, targetProductId, targetSeats) {
3369
- if (!stream.items?.length) {
3370
- throw invalidProviderItems("StreamPay returned a subscription without any items.");
3371
- }
3372
- const subscriptionCoupons = new Set(subscriptionCouponIds(stream));
3373
- let matches = 0;
3374
- const items = stream.items.map((item) => {
3375
- const productId = subscriptionItemProductId(item);
3376
- const quantity = item.quantity ?? 1;
3377
- if (!productId || !Number.isSafeInteger(quantity) || quantity < 1) {
3378
- throw invalidProviderItems("StreamPay returned an invalid subscription item.");
3379
- }
3380
- const isPlanItem = productId === currentProductId;
3381
- if (isPlanItem) matches += 1;
3382
- const itemCoupons = couponIdsFromMetadata(item.coupon_calculation_metadata).filter(
3383
- (couponId) => !subscriptionCoupons.has(couponId)
3384
- );
3385
- return {
3386
- product_id: isPlanItem ? targetProductId : productId,
3387
- quantity: isPlanItem ? targetSeats : quantity,
3388
- ...itemCoupons.length > 0 ? { coupons: itemCoupons } : {}
3389
- };
3390
- });
3391
- if (matches !== 1) {
3392
- throw invalidProviderItems(
3393
- `Expected exactly one plan item for product "${currentProductId}", received ${matches}.`
3394
- );
3395
- }
3396
- return items;
3397
- }
3398
- function invalidProviderItems(message) {
3399
- return new api.APIError("INTERNAL_SERVER_ERROR", {
3400
- code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
3401
- message
3402
- });
3403
- }
3404
- function configuredPlanForSubscription(subscription, plans) {
3405
- const matches = plans.list.filter(
3406
- (plan) => subscription.items?.some((item) => subscriptionItemProductId(item) === plan.productId)
3407
- );
3408
- if (matches.length > 1) {
3409
- throw invalidProviderItems(
3410
- "StreamPay returned a subscription containing multiple configured plan products."
3411
- );
3412
- }
3413
- return matches[0];
3414
- }
3415
- async function findSubscriptionFreeze(client, options, subscriptionId, matches) {
3416
- const listPage = options.listSubscriptionFreezes;
3417
- if (!listPage) {
3418
- const response = await client.listSubscriptionFreezes(subscriptionId);
3419
- return {
3420
- freeze: response.data?.find(matches),
3421
- hasMore: response.pagination?.has_next_page ?? false
3422
- };
3423
- }
3424
- const seenIds = /* @__PURE__ */ new Set();
3425
- for (let page = 1; page <= 100; page++) {
3426
- const response = await listPage(subscriptionId, { page, limit: 100 });
3427
- const pagination = response.pagination;
3428
- if (!Array.isArray(response.data) || !pagination || pagination.current_page !== page || typeof pagination.has_next_page !== "boolean") {
3429
- throw freezePaginationConflict("StreamPay returned invalid freeze pagination.");
3430
- }
3431
- let advanced = false;
3432
- for (const freeze2 of response.data) {
3433
- if (freeze2.id && !seenIds.has(freeze2.id)) {
3434
- seenIds.add(freeze2.id);
3435
- advanced = true;
3436
- }
3437
- }
3438
- if (!advanced && (pagination.has_next_page || response.data.length > 0)) {
3439
- throw freezePaginationConflict("StreamPay freeze pagination returned no new entries.");
3440
- }
3441
- const freeze = response.data.find(matches);
3442
- if (freeze || !pagination.has_next_page) return { freeze, hasMore: false };
3443
- }
3444
- throw freezePaginationConflict("StreamPay freeze pagination exceeded 100 pages.");
3445
- }
3446
- function freezePaginationConflict(message) {
3447
- return new api.APIError("CONFLICT", {
3448
- code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
3449
- message
3450
- });
3451
- }
3452
3686
  var SUBSCRIPTION_INTERVALS = ["WEEK", "MONTH", "QUARTER", "YEAR"];
3453
3687
  var PlanSchema = zod.z.object({
3454
3688
  name: zod.z.string().min(1, "every plan must have a non-empty `name`."),
@@ -4113,6 +4347,24 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
4113
4347
  `failed to persist payment link=${paymentLinkId} for row=${row.id}: ${message}. Protected checkout metadata will reconcile the row from the webhook.`
4114
4348
  );
4115
4349
  }
4350
+ if (updatedRow?.status === "incomplete_expired") {
4351
+ getLogger(ctx).warn(
4352
+ `checkout reservation row=${row.id} was released while payment link=${paymentLinkId} was created; deactivating the link.`
4353
+ );
4354
+ try {
4355
+ await deactivatePaymentLink(client, paymentLinkId, getLogger(ctx));
4356
+ } catch (deactivationError) {
4357
+ toAPIError(
4358
+ {
4359
+ logPrefix: `deactivate orphaned checkout link=${paymentLinkId} failed for row=${row.id}:`,
4360
+ userMessage: "Failed to start subscription checkout."
4361
+ },
4362
+ deactivationError,
4363
+ getLogger(ctx)
4364
+ );
4365
+ }
4366
+ throw checkoutInProgressError();
4367
+ }
4116
4368
  return ctx.json({
4117
4369
  subscriptionId: updatedRow?.id ?? row.id,
4118
4370
  url,
@@ -4891,6 +5143,11 @@ var subscriptionTable = {
4891
5143
  type: "number",
4892
5144
  required: false
4893
5145
  },
5146
+ renewedCycleNumber: {
5147
+ type: "number",
5148
+ required: false,
5149
+ input: false
5150
+ },
4894
5151
  renewalCallbackEventId: {
4895
5152
  type: "string",
4896
5153
  required: false,
@@ -5122,26 +5379,33 @@ function subscriptions(subsOptions) {
5122
5379
  message: `Webhook event ${eventId} not found.`
5123
5380
  });
5124
5381
  }
5125
- if (!row.rawPayload) {
5126
- throw new api.APIError("BAD_REQUEST", {
5127
- message: `Webhook event ${eventId} has no rawPayload \u2014 nothing to replay (already completed cleanly?).`
5382
+ if (replayOptions?.dueAttemptCount !== void 0 && !isStillDueWebhookEvent(row, replayOptions.dueAttemptCount, /* @__PURE__ */ new Date())) {
5383
+ throw new api.APIError("CONFLICT", {
5384
+ code: $ERROR_CODES.WEBHOOK_REPLAY_IN_PROGRESS.code,
5385
+ message: `Webhook event ${eventId} is no longer due.`
5128
5386
  });
5129
5387
  }
5388
+ const unreplayable = async (message) => {
5389
+ await parkUnreplayableWebhookEvent(syncCtx, row, message);
5390
+ throw new api.APIError("BAD_REQUEST", { message });
5391
+ };
5392
+ if (!row.rawPayload) {
5393
+ return unreplayable(
5394
+ `Webhook event ${eventId} has no rawPayload \u2014 nothing to replay (already completed cleanly?).`
5395
+ );
5396
+ }
5130
5397
  let parsedPayload;
5131
5398
  try {
5132
5399
  parsedPayload = JSON.parse(row.rawPayload);
5133
5400
  } catch {
5134
- throw new api.APIError("BAD_REQUEST", {
5135
- message: `Webhook event ${eventId} has malformed stored JSON.`
5136
- });
5401
+ return unreplayable(`Webhook event ${eventId} has malformed stored JSON.`);
5137
5402
  }
5138
5403
  if (!isStreamPayWebhookEnvelope(parsedPayload) || !isKnownStreamPayWebhookPayload(parsedPayload)) {
5139
- throw new api.APIError("BAD_REQUEST", {
5140
- message: `Webhook event ${eventId} has an invalid stored payload.`
5141
- });
5404
+ return unreplayable(`Webhook event ${eventId} has an invalid stored payload.`);
5142
5405
  }
5143
5406
  const payload = parsedPayload;
5144
5407
  const plans = await plansRef();
5408
+ const previousStatus = row.status;
5145
5409
  const claimed = await claimWebhookEventForReplay(syncCtx, row);
5146
5410
  if (!claimed?.lockedBy) {
5147
5411
  throw new api.APIError("CONFLICT", {
@@ -5152,6 +5416,8 @@ function subscriptions(subsOptions) {
5152
5416
  try {
5153
5417
  await syncWebhookPayload(syncCtx, payload, options.client, plans, subsOptions, {
5154
5418
  dedupe: false,
5419
+ inboxEnabled: true,
5420
+ retryOnCallbackError: subsOptions.retryOnCallbackError !== false,
5155
5421
  retryingRenewalCallback: claimed.lastError?.startsWith(
5156
5422
  "Subscription callback onSubscriptionRenewed failed:"
5157
5423
  ) === true
@@ -5167,7 +5433,7 @@ function subscriptions(subsOptions) {
5167
5433
  null,
5168
5434
  err,
5169
5435
  claimed.lockedBy,
5170
- !replayOptions?.retryUntilExhausted || classifyWebhookFailure(err) === "PERMANENT" || claimed.attemptCount >= maxAttempts
5436
+ previousStatus === "dead_letter" || classifyWebhookFailure(err) === "PERMANENT" || claimed.attemptCount >= maxAttempts
5171
5437
  );
5172
5438
  throw err;
5173
5439
  }
@@ -5375,20 +5641,22 @@ var webhooks = (webhooksOptions) => {
5375
5641
  });
5376
5642
  if (!eventId.startsWith("handlers:") || !row)
5377
5643
  throw new api.APIError("NOT_FOUND", { message: "Webhook callback event not found." });
5378
- if (!row.rawPayload)
5379
- throw new api.APIError("BAD_REQUEST", { message: "Webhook callback has no stored payload." });
5644
+ if (replayOptions?.dueAttemptCount !== void 0 && !isStillDueWebhookEvent(row, replayOptions.dueAttemptCount, /* @__PURE__ */ new Date()))
5645
+ throw new api.APIError("CONFLICT", { message: "Webhook callback is no longer due." });
5646
+ const unreplayable = async (message) => {
5647
+ await parkUnreplayableWebhookEvent(syncContext, row, message);
5648
+ throw new api.APIError("BAD_REQUEST", { message });
5649
+ };
5650
+ if (!row.rawPayload) return unreplayable("Webhook callback has no stored payload.");
5380
5651
  let payload;
5381
5652
  try {
5382
5653
  payload = JSON.parse(row.rawPayload);
5383
5654
  } catch {
5384
- throw new api.APIError("BAD_REQUEST", {
5385
- message: "Stored webhook payload is not valid JSON."
5386
- });
5655
+ return unreplayable("Stored webhook payload is not valid JSON.");
5387
5656
  }
5388
5657
  if (!isStreamPayWebhookEnvelope(payload))
5389
- throw new api.APIError("BAD_REQUEST", {
5390
- message: "Stored webhook payload is not a valid event envelope."
5391
- });
5658
+ return unreplayable("Stored webhook payload is not a valid event envelope.");
5659
+ const previousStatus = row.status;
5392
5660
  const claimed = await claimWebhookEventForReplay(syncContext, row);
5393
5661
  if (!claimed?.lockedBy)
5394
5662
  throw new api.APIError("CONFLICT", {
@@ -5405,7 +5673,7 @@ var webhooks = (webhooksOptions) => {
5405
5673
  row.signatureHeader,
5406
5674
  err,
5407
5675
  claimed.lockedBy,
5408
- !replayOptions?.retryUntilExhausted || claimed.attemptCount >= DEFAULT_MAX_WEBHOOK_ATTEMPTS
5676
+ previousStatus === "dead_letter" || claimed.attemptCount >= DEFAULT_MAX_WEBHOOK_ATTEMPTS
5409
5677
  );
5410
5678
  throw err;
5411
5679
  }
@@ -5535,7 +5803,7 @@ var webhooks = (webhooksOptions) => {
5535
5803
  const failed = [];
5536
5804
  for (const row of due) {
5537
5805
  try {
5538
- await replay(ctx, row.eventId, { retryUntilExhausted: true });
5806
+ await replay(ctx, row.eventId, { dueAttemptCount: row.attemptCount });
5539
5807
  succeeded.push(row.eventId);
5540
5808
  } catch (err) {
5541
5809
  if (err instanceof api.APIError && err.status === "CONFLICT") continue;
@@ -5676,7 +5944,7 @@ var onUserDelete = (options) => async (user, context) => {
5676
5944
 
5677
5945
  // package.json
5678
5946
  var package_default = {
5679
- version: "3.1.0"};
5947
+ version: "3.3.0"};
5680
5948
 
5681
5949
  // src/version.ts
5682
5950
  var version = package_default.version;