better-auth-streampay 3.2.0 → 3.3.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.js CHANGED
@@ -656,6 +656,15 @@ function isTerminalSubscriptionStatus(status) {
656
656
  function isCheckoutSuccessStatus(status) {
657
657
  return status !== void 0 && CHECKOUT_SUCCESS_STATUSES.has(status);
658
658
  }
659
+ function subscriptionSlotKey(referenceType, referenceId, group) {
660
+ const tuple = JSON.stringify([referenceType, referenceId, group ?? null]);
661
+ return `sp_slot_v1_${createHash("sha256").update(tuple).digest("hex")}`;
662
+ }
663
+ var UPGRADE_IDEMPOTENCY_WINDOW_MS = 15 * 60 * 1e3;
664
+ var PLAN_NAME_METADATA_KEY = "streampay_plugin_plan_name";
665
+ var REFERENCE_ID_METADATA_KEY = "streampay_plugin_reference_id";
666
+ var REFERENCE_TYPE_METADATA_KEY = "streampay_plugin_reference_type";
667
+ var SUBSCRIPTION_ROW_ID_METADATA_KEY = "streampay_plugin_subscription_row_id";
659
668
 
660
669
  // src/plugins/subscriptions/reconcile.ts
661
670
  var SUBSCRIPTION_MODEL = "subscription";
@@ -677,25 +686,38 @@ function reconcileProjectionAgainstExisting(existing, projection, options = {})
677
686
  function projectSubscriptionAgainstExisting(existing, stream) {
678
687
  return reconcileProjectionAgainstExisting(existing, projectSubscriptionFields(stream, existing));
679
688
  }
689
+ function liveSlotKey(existing, projected) {
690
+ if (isTerminalSubscriptionStatus(projected.status ?? existing.status)) return null;
691
+ return subscriptionSlotKey(
692
+ existing.referenceType ?? "user",
693
+ existing.referenceId,
694
+ projected.group === void 0 ? existing.group : projected.group
695
+ );
696
+ }
680
697
  async function persistSubscriptionProjection(adapter, existing, projection, log, source) {
681
698
  const stale = existing.providerUpdatedAt instanceof Date && projection.providerUpdatedAt instanceof Date && projection.providerUpdatedAt.getTime() < existing.providerUpdatedAt.getTime();
682
- if (!stale) {
683
- const updated = await adapter.update({
684
- model: SUBSCRIPTION_MODEL,
685
- update: projection,
686
- where: [
687
- { field: "id", value: existing.id },
688
- { field: "providerUpdatedAt", value: existing.providerUpdatedAt ?? null },
689
- { field: "streampaySubscriptionId", value: existing.streampaySubscriptionId ?? null },
690
- { field: "streampayConsumerId", value: existing.streampayConsumerId ?? null },
691
- { field: "status", value: existing.status },
692
- { field: "billingStatus", value: existing.billingStatus }
693
- ]
694
- });
695
- if (updated) return updated;
696
- }
699
+ const slotKey = liveSlotKey(existing, projection);
700
+ const movesSlot = slotKey !== null && existing.activeSlotKey !== slotKey;
701
+ const slotHolder = movesSlot ? await adapter.findOne({
702
+ model: SUBSCRIPTION_MODEL,
703
+ where: [{ field: "activeSlotKey", value: slotKey }]
704
+ }) : null;
705
+ const updated = stale || slotHolder ? null : await adapter.update({
706
+ model: SUBSCRIPTION_MODEL,
707
+ update: movesSlot ? { ...projection, activeSlotKey: slotKey } : projection,
708
+ where: [
709
+ { field: "id", value: existing.id },
710
+ { field: "providerUpdatedAt", value: existing.providerUpdatedAt ?? null },
711
+ { field: "streampaySubscriptionId", value: existing.streampaySubscriptionId ?? null },
712
+ { field: "streampayConsumerId", value: existing.streampayConsumerId ?? null },
713
+ { field: "status", value: existing.status },
714
+ { field: "billingStatus", value: existing.billingStatus },
715
+ { field: "renewedCycleNumber", value: existing.renewedCycleNumber ?? null }
716
+ ]
717
+ });
718
+ if (updated) return updated;
697
719
  log.warn(
698
- `${source}: retained newer local subscription state for row=${existing.id}. The provider action is not rolled back.`
720
+ 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.`
699
721
  );
700
722
  return adapter.findOne({
701
723
  model: SUBSCRIPTION_MODEL,
@@ -758,6 +780,11 @@ function projectSubscriptionFields(sub, existing) {
758
780
  periodStart,
759
781
  periodEnd,
760
782
  currentCycleNumber: sub.current_cycle_number ?? null,
783
+ // Only renewal evidence advances the baseline. Other writers only initialize it, so they can
784
+ // neither absorb a renewal nor roll back one that was just delivered.
785
+ ...existing?.renewedCycleNumber == null ? {
786
+ renewedCycleNumber: existing?.currentCycleNumber ?? (existing?.streampaySubscriptionId ? sub.current_cycle_number ?? null : firstLinkRenewalBaseline(sub.current_cycle_number))
787
+ } : {},
761
788
  trialStart: (sub.trial_end ? parseDate(sub.started_at) ?? periodStart : null) ?? existing?.trialStart ?? null,
762
789
  trialEnd: parseDate(sub.trial_end),
763
790
  cancelAtPeriodEnd: Boolean(sub.cancel_at_period_end),
@@ -772,6 +799,9 @@ function projectSubscriptionFields(sub, existing) {
772
799
  updatedAt: /* @__PURE__ */ new Date()
773
800
  };
774
801
  }
802
+ function firstLinkRenewalBaseline(currentCycle) {
803
+ return typeof currentCycle === "number" ? Math.min(currentCycle, 1) : null;
804
+ }
775
805
  function parseDate(value) {
776
806
  if (!value) return null;
777
807
  const normalized = /[T ]/.test(value) && !/(?:Z|[+-]\d{2}:?\d{2})$/i.test(value) ? `${value}Z` : value;
@@ -991,15 +1021,6 @@ function freezePaginationConflict(message) {
991
1021
  message
992
1022
  });
993
1023
  }
994
- function subscriptionSlotKey(referenceType, referenceId, group) {
995
- const tuple = JSON.stringify([referenceType, referenceId, group ?? null]);
996
- return `sp_slot_v1_${createHash("sha256").update(tuple).digest("hex")}`;
997
- }
998
- var UPGRADE_IDEMPOTENCY_WINDOW_MS = 15 * 60 * 1e3;
999
- var PLAN_NAME_METADATA_KEY = "streampay_plugin_plan_name";
1000
- var REFERENCE_ID_METADATA_KEY = "streampay_plugin_reference_id";
1001
- var REFERENCE_TYPE_METADATA_KEY = "streampay_plugin_reference_type";
1002
- var SUBSCRIPTION_ROW_ID_METADATA_KEY = "streampay_plugin_subscription_row_id";
1003
1024
 
1004
1025
  // src/plugins/subscriptions/sync.ts
1005
1026
  var SUBSCRIPTION_MODEL2 = "subscription";
@@ -1027,6 +1048,9 @@ function isUniqueConstraintError(err) {
1027
1048
  }
1028
1049
  var WEBHOOK_PROCESSING_LEASE_MS = 2 * 60 * 1e3;
1029
1050
  var WEBHOOK_RETRY_DELAYS_MS = [5, 30, 120, 360, 720].map((minutes) => minutes * 60 * 1e3);
1051
+ function hasLiveLease(row, now) {
1052
+ return row.lockedAt instanceof Date && now.getTime() - row.lockedAt.getTime() < WEBHOOK_PROCESSING_LEASE_MS;
1053
+ }
1030
1054
  var WebhookEventInProgressError = class extends Error {
1031
1055
  constructor(eventType) {
1032
1056
  super(`Webhook ${eventType} is already being processed; retry later.`);
@@ -1111,7 +1135,7 @@ async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader
1111
1135
  );
1112
1136
  return { action: "skip", reason: "dead_letter" };
1113
1137
  }
1114
- if (existing.lockedAt instanceof Date && now.getTime() - existing.lockedAt.getTime() < WEBHOOK_PROCESSING_LEASE_MS) {
1138
+ if (hasLiveLease(existing, now)) {
1115
1139
  logger(ctx).info(
1116
1140
  `webhook ${payload.event_type} (${eventId}) is already being processed \u2014 skipping concurrent delivery.`
1117
1141
  );
@@ -1127,15 +1151,15 @@ async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader
1127
1151
  lastAttemptAt: now,
1128
1152
  deadLetteredAt: now,
1129
1153
  nextAttemptAt: null,
1130
- rawPayload: rawBody,
1131
- signatureHeader,
1154
+ ...rawBody !== null ? { rawPayload: rawBody, signatureHeader } : {},
1132
1155
  lockedAt: null,
1133
1156
  lockedBy: null
1134
1157
  },
1135
1158
  where: [
1136
1159
  { field: "id", value: existing.id },
1137
1160
  { field: "status", value: "pending" },
1138
- { field: "lockedAt", value: existing.lockedAt ?? null }
1161
+ { field: "lockedAt", value: existing.lockedAt ?? null },
1162
+ { field: "attemptCount", value: existing.attemptCount ?? null }
1139
1163
  ]
1140
1164
  });
1141
1165
  return updated2 ? { action: "dead_letter", row: updated2 } : { action: "skip", reason: "in_progress" };
@@ -1147,19 +1171,21 @@ async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader
1147
1171
  lastAttemptAt: now,
1148
1172
  nextAttemptAt: null,
1149
1173
  lockedAt: now,
1150
- lockedBy: lockId
1174
+ lockedBy: lockId,
1175
+ ...rawBody !== null ? { rawPayload: rawBody, signatureHeader } : {}
1151
1176
  },
1152
1177
  where: [
1153
1178
  { field: "id", value: existing.id },
1154
1179
  { field: "status", value: "pending" },
1155
- { field: "lockedAt", value: existing.lockedAt ?? null }
1180
+ { field: "lockedAt", value: existing.lockedAt ?? null },
1181
+ { field: "attemptCount", value: existing.attemptCount ?? null }
1156
1182
  ]
1157
1183
  });
1158
1184
  return updated ? { action: "process", row: updated } : { action: "skip", reason: "in_progress" };
1159
1185
  }
1160
1186
  async function claimWebhookEventForReplay(ctx, row) {
1161
1187
  const now = /* @__PURE__ */ new Date();
1162
- if (row.lockedAt instanceof Date && now.getTime() - row.lockedAt.getTime() < WEBHOOK_PROCESSING_LEASE_MS) {
1188
+ if (hasLiveLease(row, now)) {
1163
1189
  return null;
1164
1190
  }
1165
1191
  return ctx.context.adapter.update({
@@ -1177,30 +1203,71 @@ async function claimWebhookEventForReplay(ctx, row) {
1177
1203
  where: [
1178
1204
  { field: "id", value: row.id },
1179
1205
  { field: "status", value: row.status },
1180
- { field: "lockedAt", value: row.lockedAt ?? null }
1206
+ { field: "lockedAt", value: row.lockedAt ?? null },
1207
+ { field: "attemptCount", value: row.attemptCount ?? null }
1181
1208
  ]
1182
1209
  });
1183
1210
  }
1184
- async function markWebhookEventCompleted(ctx, rowId, lockId) {
1211
+ function isStillDueWebhookEvent(row, selectedAttemptCount, now) {
1212
+ const retryDue = row.nextAttemptAt instanceof Date && row.nextAttemptAt <= now;
1213
+ const leaseAbandoned = row.lockedAt instanceof Date && !hasLiveLease(row, now);
1214
+ return row.status === "pending" && row.attemptCount === selectedAttemptCount && (retryDue || leaseAbandoned);
1215
+ }
1216
+ async function parkUnreplayableWebhookEvent(ctx, row, reason) {
1217
+ if (row.status !== "pending" || hasLiveLease(row, /* @__PURE__ */ new Date())) return;
1185
1218
  await ctx.context.adapter.update({
1186
1219
  model: WEBHOOK_EVENT_MODEL,
1187
1220
  update: {
1188
- status: "completed",
1189
- completedAt: /* @__PURE__ */ new Date(),
1190
1221
  nextAttemptAt: null,
1191
1222
  lockedAt: null,
1192
1223
  lockedBy: null,
1193
- rawPayload: null,
1194
- signatureHeader: null,
1195
- lastError: null,
1196
- lastErrorCode: null
1224
+ lastError: reason,
1225
+ lastErrorCode: "UNREPLAYABLE_PAYLOAD"
1197
1226
  },
1227
+ where: [
1228
+ { field: "id", value: row.id },
1229
+ { field: "status", value: "pending" },
1230
+ { field: "lockedAt", value: row.lockedAt ?? null },
1231
+ { field: "attemptCount", value: row.attemptCount ?? null }
1232
+ ]
1233
+ });
1234
+ }
1235
+ function completedWebhookEventFields() {
1236
+ return {
1237
+ status: "completed",
1238
+ completedAt: /* @__PURE__ */ new Date(),
1239
+ nextAttemptAt: null,
1240
+ lockedAt: null,
1241
+ lockedBy: null,
1242
+ rawPayload: null,
1243
+ signatureHeader: null,
1244
+ lastError: null,
1245
+ lastErrorCode: null
1246
+ };
1247
+ }
1248
+ async function markWebhookEventCompleted(ctx, rowId, lockId) {
1249
+ await ctx.context.adapter.update({
1250
+ model: WEBHOOK_EVENT_MODEL,
1251
+ update: completedWebhookEventFields(),
1198
1252
  where: [
1199
1253
  { field: "id", value: rowId },
1200
1254
  ...lockId ? [{ field: "lockedBy", value: lockId }] : []
1201
1255
  ]
1202
1256
  });
1203
1257
  }
1258
+ async function completeUnchangedWebhookEvent(ctx, row) {
1259
+ const updated = await ctx.context.adapter.update({
1260
+ model: WEBHOOK_EVENT_MODEL,
1261
+ update: completedWebhookEventFields(),
1262
+ where: [
1263
+ { field: "id", value: row.id },
1264
+ { field: "status", value: row.status },
1265
+ { field: "lockedAt", value: row.lockedAt ?? null },
1266
+ { field: "attemptCount", value: row.attemptCount ?? null }
1267
+ ]
1268
+ });
1269
+ return updated !== null;
1270
+ }
1204
1271
  async function recordWebhookEventFailure(ctx, rowId, rawBody, signatureHeader, err, lockId, deadLetter = false) {
1205
1272
  const lastError = err instanceof Error ? err.message : String(err);
1206
1273
  const sdkError = readSdkErrorFields(err);
@@ -1319,12 +1386,41 @@ var SubscriptionCorrelationError = class extends Error {
1319
1386
  this.name = "SubscriptionCorrelationError";
1320
1387
  }
1321
1388
  };
1389
+ function providerStateConfirmsEvent(eventType, stream) {
1390
+ switch (eventType) {
1391
+ case "SUBSCRIPTION_CREATED":
1392
+ return true;
1393
+ case "SUBSCRIPTION_ACTIVATED":
1394
+ case "SUBSCRIPTION_UNFREEZE_NOW":
1395
+ return stream.status === "ACTIVE" || stream.status === "TRIALING";
1396
+ case "SUBSCRIPTION_CANCELED":
1397
+ return stream.status === "CANCELED";
1398
+ case "SUBSCRIPTION_INACTIVATED":
1399
+ return stream.status === "INACTIVE";
1400
+ case "SUBSCRIPTION_CANCEL_AT_PERIOD_END":
1401
+ return Boolean(stream.cancel_at_period_end) && !isTerminalSubscriptionStatus(toLocalStatus(stream.status));
1402
+ case "SUBSCRIPTION_FROZEN":
1403
+ case "SUBSCRIPTION_FREEZE_NOW":
1404
+ return stream.status === "FROZEN";
1405
+ case "SUBSCRIPTION_PLAN_CHANGE_SCHEDULED":
1406
+ return Boolean(stream.pending_change);
1407
+ case "SUBSCRIPTION_PLAN_CHANGE_CANCELED":
1408
+ return !stream.pending_change;
1409
+ default:
1410
+ return false;
1411
+ }
1412
+ }
1322
1413
  async function takeSlotFromReservation(ctx, client, slotKey, ownerRowId, streampaySubscriptionId) {
1323
1414
  const holder = await ctx.context.adapter.findOne({
1324
1415
  model: SUBSCRIPTION_MODEL2,
1325
1416
  where: [{ field: "activeSlotKey", value: slotKey }]
1326
1417
  });
1327
1418
  if (!holder || holder.id === ownerRowId) return;
1419
+ if (holder.streampaySubscriptionId === streampaySubscriptionId) {
1420
+ throw new Error(
1421
+ `StreamPay sub=${streampaySubscriptionId} was linked to row=${holder.id} concurrently. Retry delivery.`
1422
+ );
1423
+ }
1328
1424
  if (holder.status !== "incomplete" || holder.streampaySubscriptionId) {
1329
1425
  throw new SubscriptionCorrelationError(
1330
1426
  `StreamPay sub=${streampaySubscriptionId} needs the billing slot held by live row=${holder.id} (${holder.status}). Resolve the duplicate subscription, then replay.`
@@ -1399,7 +1495,8 @@ async function updateReconciledSubscription(ctx, client, existing, projected, st
1399
1495
  { field: "streampaySubscriptionId", value: existing.streampaySubscriptionId ?? null },
1400
1496
  { field: "streampayConsumerId", value: existing.streampayConsumerId ?? null },
1401
1497
  { field: "status", value: existing.status },
1402
- { field: "billingStatus", value: existing.billingStatus }
1498
+ { field: "billingStatus", value: existing.billingStatus },
1499
+ { field: "renewedCycleNumber", value: existing.renewedCycleNumber ?? null }
1403
1500
  ]
1404
1501
  });
1405
1502
  if (!updated) {
@@ -1409,7 +1506,7 @@ async function updateReconciledSubscription(ctx, client, existing, projected, st
1409
1506
  }
1410
1507
  return updated;
1411
1508
  }
1412
- async function reconcileFromStreamPay(ctx, payload, client, plans) {
1509
+ async function reconcileFromStreamPay(ctx, payload, client, plans, prefetched) {
1413
1510
  const streampaySubscriptionId = payload.entity_id;
1414
1511
  if (!streampaySubscriptionId) {
1415
1512
  logger(ctx).warn(`webhook ${payload.event_type} has no entity_id \u2014 cannot reconcile.`);
@@ -1417,7 +1514,7 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
1417
1514
  }
1418
1515
  let stream;
1419
1516
  try {
1420
- stream = await client.getSubscription(streampaySubscriptionId);
1517
+ stream = prefetched ?? await client.getSubscription(streampaySubscriptionId);
1421
1518
  } catch (err) {
1422
1519
  const msg = err instanceof Error ? err.message : String(err);
1423
1520
  logger(ctx).error(
@@ -1434,15 +1531,16 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
1434
1531
  const eventIsStale = Boolean(
1435
1532
  eventAt && existing?.providerUpdatedAt instanceof Date && eventAt.getTime() < existing.providerUpdatedAt.getTime()
1436
1533
  );
1437
- if (!eventIsStale && payload.event_type === "SUBSCRIPTION_CYCLE_RENEWAL_FAILED" && projected.status === "active") {
1534
+ const eventApplies = !eventIsStale || providerStateConfirmsEvent(payload.event_type, stream);
1535
+ if (eventApplies && payload.event_type === "SUBSCRIPTION_CYCLE_RENEWAL_FAILED" && projected.status === "active") {
1438
1536
  projected.status = "past_due";
1439
1537
  projected.billingStatus = "past_due";
1440
1538
  }
1441
- const schedulesCancellation = !eventIsStale && payload.event_type === "SUBSCRIPTION_CANCEL_AT_PERIOD_END" && Boolean(stream.cancel_at_period_end);
1539
+ const schedulesCancellation = eventApplies && payload.event_type === "SUBSCRIPTION_CANCEL_AT_PERIOD_END" && Boolean(stream.cancel_at_period_end);
1442
1540
  if (schedulesCancellation) {
1443
1541
  projected.cancelAt = parseDate(stream.current_period_end);
1444
1542
  }
1445
- const confirmsCancellation = !eventIsStale && payload.event_type === "SUBSCRIPTION_CANCELED" && projected.status === "canceled";
1543
+ const confirmsCancellation = eventApplies && payload.event_type === "SUBSCRIPTION_CANCELED" && projected.status === "canceled";
1446
1544
  if (confirmsCancellation) {
1447
1545
  projected.activeSlotKey = null;
1448
1546
  }
@@ -1451,17 +1549,13 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
1451
1549
  stampCancelScheduled: schedulesCancellation,
1452
1550
  stampCanceled: confirmsCancellation
1453
1551
  });
1552
+ if (schedulesCancellation && eventAt && existing?.cancelAtPeriodEnd && !existing.cancelScheduledAt) {
1553
+ projected.cancelScheduledAt = eventAt;
1554
+ }
1454
1555
  if (existing) {
1455
- const projectedStatus = projected.status ?? existing.status;
1456
- if (!isTerminalSubscriptionStatus(projectedStatus)) {
1457
- const desiredSlotKey = subscriptionSlotKey(
1458
- existing.referenceType ?? "user",
1459
- existing.referenceId,
1460
- projected.group === void 0 ? existing.group : projected.group
1461
- );
1462
- if (existing.activeSlotKey !== desiredSlotKey) {
1463
- projected.activeSlotKey = desiredSlotKey;
1464
- }
1556
+ const slotKey = liveSlotKey(existing, projected);
1557
+ if (slotKey && existing.activeSlotKey !== slotKey) {
1558
+ projected.activeSlotKey = slotKey;
1465
1559
  }
1466
1560
  const updated = await updateReconciledSubscription(
1467
1561
  ctx,
@@ -1470,7 +1564,7 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
1470
1564
  projected,
1471
1565
  streampaySubscriptionId
1472
1566
  );
1473
- if (eventIsStale) {
1567
+ if (!eventApplies) {
1474
1568
  logger(ctx).info(
1475
1569
  `webhook ${payload.event_type}: ignored stale lifecycle callback for sub=${streampaySubscriptionId}.`
1476
1570
  );
@@ -1599,7 +1693,8 @@ async function syncWebhookPayload(ctx, payload, client, plans, callbacks, option
1599
1693
  retryOnCallbackError,
1600
1694
  options.retryingRenewalCallback === true || claim.row?.lastError?.startsWith(
1601
1695
  "Subscription callback onSubscriptionRenewed failed:"
1602
- ) === true
1696
+ ) === true,
1697
+ options.inboxEnabled ?? dedupe
1603
1698
  );
1604
1699
  } else {
1605
1700
  const { row, stream } = await reconcileFromStreamPay(ctx, payload, client, plans);
@@ -1631,7 +1726,59 @@ async function syncWebhookPayload(ctx, payload, client, plans, callbacks, option
1631
1726
  throw err;
1632
1727
  }
1633
1728
  }
1634
- async function handleRenewalEvidence(ctx, payload, client, plans, callbacks, retryOnCallbackError, retryingRenewalCallback) {
1729
+ async function releaseLockOfCompletedRenewal(ctx, subscriptionRowId, lockEventId) {
1730
+ const owner = await ctx.context.adapter.findOne({
1731
+ model: WEBHOOK_EVENT_MODEL,
1732
+ where: [{ field: "eventId", value: lockEventId }]
1733
+ });
1734
+ if (owner?.status !== "completed") return false;
1735
+ const released = await ctx.context.adapter.update({
1736
+ model: SUBSCRIPTION_MODEL2,
1737
+ update: { renewalCallbackEventId: null },
1738
+ where: [
1739
+ { field: "id", value: subscriptionRowId },
1740
+ { field: "renewalCallbackEventId", value: lockEventId }
1741
+ ]
1742
+ });
1743
+ if (released) {
1744
+ logger(ctx).warn(
1745
+ `released renewal callback lock of completed event ${lockEventId} for row=${subscriptionRowId}.`
1746
+ );
1747
+ }
1748
+ return released !== null;
1749
+ }
1750
+ async function linkCheckoutFromRenewalEvidence(ctx, payload, client, plans, stream) {
1751
+ const paymentLinkId = stream.latest_invoice?.payment_link_id;
1752
+ if (!paymentLinkId || !stream.id) return null;
1753
+ const reservation = await ctx.context.adapter.findOne({
1754
+ model: SUBSCRIPTION_MODEL2,
1755
+ where: [{ field: "streampayPaymentLinkId", value: paymentLinkId }]
1756
+ });
1757
+ if (!reservation) return null;
1758
+ const link = await client.getPaymentLink(paymentLinkId);
1759
+ const { row } = await reconcileFromStreamPay(
1760
+ ctx,
1761
+ {
1762
+ ...payload,
1763
+ entity_id: stream.id,
1764
+ data: {
1765
+ metadata: link.custom_metadata ?? {},
1766
+ payment_link: { id: paymentLinkId, url: "" }
1767
+ }
1768
+ },
1769
+ client,
1770
+ plans,
1771
+ stream
1772
+ );
1773
+ if (row) {
1774
+ logger(ctx).warn(
1775
+ `webhook ${payload.event_type}: linked checkout row=${row.id} to StreamPay sub=${stream.id} from renewal evidence.`
1776
+ );
1777
+ return row;
1778
+ }
1779
+ return findSubscriptionByStreampayId(ctx, stream.id);
1780
+ }
1781
+ async function handleRenewalEvidence(ctx, payload, client, plans, callbacks, retryOnCallbackError, retryingRenewalCallback, inboxEnabled) {
1635
1782
  const invoiceId = payload.data?.invoice?.id ?? payload.entity_id;
1636
1783
  if (!invoiceId) return;
1637
1784
  let subscriptionId = payload.entity_type === "SUBSCRIPTION" ? payload.entity_id : null;
@@ -1657,33 +1804,61 @@ async function handleRenewalEvidence(ctx, payload, client, plans, callbacks, ret
1657
1804
  logger(ctx).error(`${payload.event_type}: getSubscription(${subscriptionId}) failed: ${msg}`);
1658
1805
  throw err;
1659
1806
  }
1660
- const existing = await findSubscriptionByStreampayId(ctx, subscriptionId);
1807
+ const existing = await findSubscriptionByStreampayId(ctx, subscriptionId) ?? await linkCheckoutFromRenewalEvidence(ctx, payload, client, plans, stream);
1661
1808
  if (!existing) return;
1662
1809
  const eventAt = parseDate(payload.timestamp);
1663
1810
  const eventIsStale = Boolean(
1664
1811
  eventAt && existing.providerUpdatedAt instanceof Date && eventAt.getTime() < existing.providerUpdatedAt.getTime()
1665
1812
  );
1813
+ const evidenceInvoiceId = payload.data?.invoice?.id ?? (payload.entity_type === "INVOICE" ? payload.entity_id : null);
1814
+ const settlesLatestInvoice = stream.latest_invoice?.status === "COMPLETED" && (evidenceInvoiceId === null || stream.latest_invoice.id === evidenceInvoiceId);
1815
+ const evidenceApplies = !eventIsStale || settlesLatestInvoice;
1666
1816
  const projected = {
1667
1817
  ...projectSubscriptionFields(stream, existing),
1668
1818
  ...projectPlanFields(stream, plans),
1669
- ...eventIsStale ? existing.billingStatus === "past_due" && toLocalStatus(stream.status) === "active" ? { status: "past_due", billingStatus: "past_due" } : {} : { billingStatus: "current" }
1819
+ ...evidenceApplies ? { billingStatus: "current" } : existing.billingStatus === "past_due" && toLocalStatus(stream.status) === "active" ? { status: "past_due", billingStatus: "past_due" } : {}
1670
1820
  };
1821
+ const slotKey = liveSlotKey(existing, projected);
1822
+ if (slotKey && existing.activeSlotKey !== slotKey) {
1823
+ projected.activeSlotKey = slotKey;
1824
+ }
1671
1825
  const previousPeriodEnd = existing.periodEnd?.getTime() ?? null;
1672
1826
  const projectedPeriodEnd = projected.periodEnd?.getTime() ?? null;
1673
1827
  const periodAdvanced = previousPeriodEnd !== null && projectedPeriodEnd !== null && projectedPeriodEnd > previousPeriodEnd;
1674
- const cycleAdvanced = existing.currentCycleNumber !== null && existing.currentCycleNumber !== void 0 && projected.currentCycleNumber !== null && projected.currentCycleNumber !== void 0 && projected.currentCycleNumber > existing.currentCycleNumber;
1828
+ const renewedCycle = existing.renewedCycleNumber ?? existing.currentCycleNumber ?? null;
1829
+ const projectedCycle = projected.currentCycleNumber ?? null;
1830
+ const tracksCycles = renewedCycle !== null && projectedCycle !== null;
1831
+ const renewalAdvanced = tracksCycles ? projectedCycle > renewedCycle : periodAdvanced;
1675
1832
  const eventId = extractEventId(payload);
1676
- const pendingCallback = existing.renewalCallbackEventId ?? null;
1833
+ let pendingCallback = existing.renewalCallbackEventId ?? null;
1834
+ if (pendingCallback && pendingCallback !== eventId) {
1835
+ const released = inboxEnabled && await releaseLockOfCompletedRenewal(ctx, existing.id, pendingCallback);
1836
+ if (!released) {
1837
+ throw new Error(
1838
+ `Subscription renewal callback ${pendingCallback} is pending; retry delivery.`
1839
+ );
1840
+ }
1841
+ pendingCallback = null;
1842
+ }
1677
1843
  if (!pendingCallback && existing.providerUpdatedAt instanceof Date && projected.providerUpdatedAt instanceof Date && projected.providerUpdatedAt.getTime() < existing.providerUpdatedAt.getTime()) {
1678
1844
  throw new Error(
1679
1845
  `StreamPay returned stale subscription state for sub=${subscriptionId}; retry delivery.`
1680
1846
  );
1681
1847
  }
1682
- if (pendingCallback && pendingCallback !== eventId) {
1683
- throw new Error(`Subscription renewal callback ${pendingCallback} is pending; retry delivery.`);
1848
+ if (!pendingCallback && projected.activeSlotKey && projected.activeSlotKey !== existing.activeSlotKey) {
1849
+ await takeSlotFromReservation(
1850
+ ctx,
1851
+ client,
1852
+ projected.activeSlotKey,
1853
+ existing.id,
1854
+ subscriptionId
1855
+ );
1684
1856
  }
1685
- const deliverCallback = pendingCallback === eventId && pendingCallback !== null || !eventIsStale && (periodAdvanced || cycleAdvanced || retryingRenewalCallback);
1857
+ const deliverCallback = pendingCallback === eventId && pendingCallback !== null || evidenceApplies && (renewalAdvanced || retryingRenewalCallback);
1686
1858
  const callbackOwner = deliverCallback && callbacks.onSubscriptionRenewed ? eventId : null;
1859
+ if (deliverCallback && renewalAdvanced && projectedCycle !== null) {
1860
+ projected.renewedCycleNumber = projectedCycle;
1861
+ }
1687
1862
  const updated = await ctx.context.adapter.update({
1688
1863
  model: SUBSCRIPTION_MODEL2,
1689
1864
  // Recovery must retain the pending cycle, even if Stream has already advanced again.
@@ -1692,6 +1867,7 @@ async function handleRenewalEvidence(ctx, payload, client, plans, callbacks, ret
1692
1867
  { field: "id", value: existing.id },
1693
1868
  { field: "periodEnd", value: existing.periodEnd ?? null },
1694
1869
  { field: "currentCycleNumber", value: existing.currentCycleNumber ?? null },
1870
+ { field: "renewedCycleNumber", value: existing.renewedCycleNumber ?? null },
1695
1871
  { field: "renewalCallbackEventId", value: pendingCallback },
1696
1872
  { field: "providerUpdatedAt", value: existing.providerUpdatedAt ?? null },
1697
1873
  { field: "status", value: existing.status },
@@ -1704,8 +1880,8 @@ async function handleRenewalEvidence(ctx, payload, client, plans, callbacks, ret
1704
1880
  }
1705
1881
  const latest = await findSubscriptionByStreampayId(ctx, subscriptionId);
1706
1882
  const anotherCallbackOwner = latest?.renewalCallbackEventId;
1707
- const desiredCycleAdvanced = (periodAdvanced || cycleAdvanced) && (!periodAdvanced || (latest?.periodEnd?.getTime() ?? 0) >= (projectedPeriodEnd ?? 0)) && (!cycleAdvanced || (latest?.currentCycleNumber ?? 0) >= (projected.currentCycleNumber ?? 0));
1708
- if (anotherCallbackOwner && anotherCallbackOwner !== eventId && desiredCycleAdvanced) return;
1883
+ const renewalClaimedElsewhere = renewalAdvanced && (tracksCycles ? (latest?.renewedCycleNumber ?? 0) >= projectedCycle : (latest?.periodEnd?.getTime() ?? 0) >= (projectedPeriodEnd ?? 0));
1884
+ if (anotherCallbackOwner && anotherCallbackOwner !== eventId && renewalClaimedElsewhere) return;
1709
1885
  throw new Error(`Subscription changed during renewal reconciliation; retry delivery.`);
1710
1886
  }
1711
1887
  const row = updated;
@@ -2793,6 +2969,12 @@ function buildWebhookEventsEndpoints(adminOptions, registry) {
2793
2969
  message: `Webhook event ${ctx.params.eventId} not found.`
2794
2970
  });
2795
2971
  }
2972
+ const inProgress = new APIError("CONFLICT", {
2973
+ code: $ERROR_CODES.WEBHOOK_REPLAY_IN_PROGRESS.code,
2974
+ message: `Webhook event ${ctx.params.eventId} is being processed. Retry after its lease expires.`
2975
+ });
2976
+ if (row.status === "pending" && hasLiveLease(row, /* @__PURE__ */ new Date())) throw inProgress;
2977
+ if (!await completeUnchangedWebhookEvent({ context: { adapter } }, row)) throw inProgress;
2796
2978
  if (registry?.subscriptionWebhookSync && !eventId.startsWith("handlers:") && (row.eventType === "INVOICE_COMPLETED" || row.eventType === "SUBSCRIPTION_CYCLE_RENEWED_SUCCESSFULLY")) {
2797
2979
  const subscription = await adapter.findOne({
2798
2980
  model: "subscription",
@@ -2809,7 +2991,6 @@ function buildWebhookEventsEndpoints(adminOptions, registry) {
2809
2991
  });
2810
2992
  }
2811
2993
  }
2812
- await markWebhookEventCompleted({ context: { adapter } }, row.id);
2813
2994
  return ctx.json({ discarded: true, eventId });
2814
2995
  }
2815
2996
  )
@@ -3394,7 +3575,8 @@ var SUBSCRIPTION_MODEL4 = "subscription";
3394
3575
  async function recoverCheckoutUrl(client, row) {
3395
3576
  if (!row.streampayPaymentLinkId) return { kind: "expired" };
3396
3577
  try {
3397
- const url = client.getPaymentUrl(await client.getPaymentLink(row.streampayPaymentLinkId));
3578
+ const link = await client.getPaymentLink(row.streampayPaymentLinkId);
3579
+ const url = link.status === "INACTIVE" ? null : client.getPaymentUrl(link);
3398
3580
  return url ? { kind: "recovered", url } : { kind: "expired" };
3399
3581
  } catch (err) {
3400
3582
  if (readSdkErrorFields(err).status === 404) return { kind: "expired" };
@@ -3475,7 +3657,9 @@ async function resumeOrReserveCheckoutSlot(args) {
3475
3657
  });
3476
3658
  if (!reserved) throw err;
3477
3659
  if (reserved.status !== "incomplete") throw subscriptionAlreadyActiveError();
3478
- if (matchesCheckout(reserved)) {
3660
+ const reservationIsStale = !(reserved.createdAt instanceof Date) || now - reserved.createdAt.getTime() >= UPGRADE_IDEMPOTENCY_WINDOW_MS;
3661
+ let linkExpired = false;
3662
+ if (!reservationIsStale && matchesCheckout(reserved)) {
3479
3663
  let recovery;
3480
3664
  try {
3481
3665
  recovery = await recoverCheckoutUrl(client, reserved);
@@ -3492,10 +3676,10 @@ async function resumeOrReserveCheckoutSlot(args) {
3492
3676
  if (recovery.kind === "recovered") {
3493
3677
  return { kind: "recovered", row: reserved, url: recovery.url };
3494
3678
  }
3679
+ linkExpired = Boolean(reserved.streampayPaymentLinkId);
3495
3680
  }
3496
- const reservationIsStale = !(reserved.createdAt instanceof Date) || now - reserved.createdAt.getTime() >= UPGRADE_IDEMPOTENCY_WINDOW_MS;
3497
- if (!reservationIsStale) throw checkoutInProgressError();
3498
- if (reserved.streampayPaymentLinkId) {
3681
+ if (!reservationIsStale && !linkExpired) throw checkoutInProgressError();
3682
+ if (reservationIsStale && reserved.streampayPaymentLinkId) {
3499
3683
  try {
3500
3684
  await deactivatePaymentLink(client, reserved.streampayPaymentLinkId, log);
3501
3685
  } catch (deactivationError) {
@@ -3515,7 +3699,8 @@ async function resumeOrReserveCheckoutSlot(args) {
3515
3699
  where: [
3516
3700
  { field: "id", value: reserved.id },
3517
3701
  { field: "status", value: "incomplete" },
3518
- { field: "activeSlotKey", value: activeSlotKey }
3702
+ { field: "activeSlotKey", value: activeSlotKey },
3703
+ { field: "streampayPaymentLinkId", value: reserved.streampayPaymentLinkId ?? null }
3519
3704
  ]
3520
3705
  });
3521
3706
  if (!released) throw checkoutInProgressError();
@@ -4992,6 +5177,11 @@ var subscriptionTable = {
4992
5177
  type: "number",
4993
5178
  required: false
4994
5179
  },
5180
+ renewedCycleNumber: {
5181
+ type: "number",
5182
+ required: false,
5183
+ input: false
5184
+ },
4995
5185
  renewalCallbackEventId: {
4996
5186
  type: "string",
4997
5187
  required: false,
@@ -5206,9 +5396,9 @@ function subscriptions(subsOptions) {
5206
5396
  }
5207
5397
  };
5208
5398
  if (dedupeEnabled) {
5209
- registry.replayWebhookEvent = async (ctx, eventId) => {
5399
+ registry.replayWebhookEvent = async (ctx, eventId, replayOptions) => {
5210
5400
  if (eventId.startsWith("handlers:") && registry.replayWebhookHandler) {
5211
- return registry.replayWebhookHandler(ctx, eventId);
5401
+ return registry.replayWebhookHandler(ctx, eventId, replayOptions);
5212
5402
  }
5213
5403
  const syncCtx = {
5214
5404
  context: ctx.context
@@ -5223,23 +5413,29 @@ function subscriptions(subsOptions) {
5223
5413
  message: `Webhook event ${eventId} not found.`
5224
5414
  });
5225
5415
  }
5226
- if (!row.rawPayload) {
5227
- throw new APIError("BAD_REQUEST", {
5228
- message: `Webhook event ${eventId} has no rawPayload \u2014 nothing to replay (already completed cleanly?).`
5416
+ if (replayOptions?.dueAttemptCount !== void 0 && !isStillDueWebhookEvent(row, replayOptions.dueAttemptCount, /* @__PURE__ */ new Date())) {
5417
+ throw new APIError("CONFLICT", {
5418
+ code: $ERROR_CODES.WEBHOOK_REPLAY_IN_PROGRESS.code,
5419
+ message: `Webhook event ${eventId} is no longer due.`
5229
5420
  });
5230
5421
  }
5422
+ const unreplayable = async (message) => {
5423
+ await parkUnreplayableWebhookEvent(syncCtx, row, message);
5424
+ throw new APIError("BAD_REQUEST", { message });
5425
+ };
5426
+ if (!row.rawPayload) {
5427
+ return unreplayable(
5428
+ `Webhook event ${eventId} has no rawPayload \u2014 nothing to replay (already completed cleanly?).`
5429
+ );
5430
+ }
5231
5431
  let parsedPayload;
5232
5432
  try {
5233
5433
  parsedPayload = JSON.parse(row.rawPayload);
5234
5434
  } catch {
5235
- throw new APIError("BAD_REQUEST", {
5236
- message: `Webhook event ${eventId} has malformed stored JSON.`
5237
- });
5435
+ return unreplayable(`Webhook event ${eventId} has malformed stored JSON.`);
5238
5436
  }
5239
5437
  if (!isStreamPayWebhookEnvelope(parsedPayload) || !isKnownStreamPayWebhookPayload(parsedPayload)) {
5240
- throw new APIError("BAD_REQUEST", {
5241
- message: `Webhook event ${eventId} has an invalid stored payload.`
5242
- });
5438
+ return unreplayable(`Webhook event ${eventId} has an invalid stored payload.`);
5243
5439
  }
5244
5440
  const payload = parsedPayload;
5245
5441
  const plans = await plansRef();
@@ -5254,6 +5450,7 @@ function subscriptions(subsOptions) {
5254
5450
  try {
5255
5451
  await syncWebhookPayload(syncCtx, payload, options.client, plans, subsOptions, {
5256
5452
  dedupe: false,
5453
+ inboxEnabled: true,
5257
5454
  retryOnCallbackError: subsOptions.retryOnCallbackError !== false,
5258
5455
  retryingRenewalCallback: claimed.lastError?.startsWith(
5259
5456
  "Subscription callback onSubscriptionRenewed failed:"
@@ -5470,7 +5667,7 @@ var webhooks = (webhooksOptions) => {
5470
5667
  return (_options, registry) => {
5471
5668
  const { secret, toleranceSeconds, deduplicate = false, ...handlers } = webhooksOptions;
5472
5669
  if (deduplicate && registry) {
5473
- registry.replayWebhookHandler = async (ctx, eventId) => {
5670
+ registry.replayWebhookHandler = async (ctx, eventId, replayOptions) => {
5474
5671
  const syncContext = { context: ctx.context };
5475
5672
  const row = await syncContext.context.adapter.findOne({
5476
5673
  model: WEBHOOK_EVENT_MODEL,
@@ -5478,20 +5675,21 @@ var webhooks = (webhooksOptions) => {
5478
5675
  });
5479
5676
  if (!eventId.startsWith("handlers:") || !row)
5480
5677
  throw new APIError("NOT_FOUND", { message: "Webhook callback event not found." });
5481
- if (!row.rawPayload)
5482
- throw new APIError("BAD_REQUEST", { message: "Webhook callback has no stored payload." });
5678
+ if (replayOptions?.dueAttemptCount !== void 0 && !isStillDueWebhookEvent(row, replayOptions.dueAttemptCount, /* @__PURE__ */ new Date()))
5679
+ throw new APIError("CONFLICT", { message: "Webhook callback is no longer due." });
5680
+ const unreplayable = async (message) => {
5681
+ await parkUnreplayableWebhookEvent(syncContext, row, message);
5682
+ throw new APIError("BAD_REQUEST", { message });
5683
+ };
5684
+ if (!row.rawPayload) return unreplayable("Webhook callback has no stored payload.");
5483
5685
  let payload;
5484
5686
  try {
5485
5687
  payload = JSON.parse(row.rawPayload);
5486
5688
  } catch {
5487
- throw new APIError("BAD_REQUEST", {
5488
- message: "Stored webhook payload is not valid JSON."
5489
- });
5689
+ return unreplayable("Stored webhook payload is not valid JSON.");
5490
5690
  }
5491
5691
  if (!isStreamPayWebhookEnvelope(payload))
5492
- throw new APIError("BAD_REQUEST", {
5493
- message: "Stored webhook payload is not a valid event envelope."
5494
- });
5692
+ return unreplayable("Stored webhook payload is not a valid event envelope.");
5495
5693
  const previousStatus = row.status;
5496
5694
  const claimed = await claimWebhookEventForReplay(syncContext, row);
5497
5695
  if (!claimed?.lockedBy)
@@ -5639,7 +5837,7 @@ var webhooks = (webhooksOptions) => {
5639
5837
  const failed = [];
5640
5838
  for (const row of due) {
5641
5839
  try {
5642
- await replay(ctx, row.eventId);
5840
+ await replay(ctx, row.eventId, { dueAttemptCount: row.attemptCount });
5643
5841
  succeeded.push(row.eventId);
5644
5842
  } catch (err) {
5645
5843
  if (err instanceof APIError && err.status === "CONFLICT") continue;
@@ -5780,7 +5978,7 @@ var onUserDelete = (options) => async (user, context) => {
5780
5978
 
5781
5979
  // package.json
5782
5980
  var package_default = {
5783
- version: "3.2.0"};
5981
+ version: "3.3.1"};
5784
5982
 
5785
5983
  // src/version.ts
5786
5984
  var version = package_default.version;