better-auth-streampay 1.3.0 → 2.0.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
@@ -36,9 +36,20 @@ var $ERROR_CODES = defineErrorCodes({
36
36
  SUBSCRIPTION_NOT_FOUND: "The subscription does not exist.",
37
37
  SUBSCRIPTION_PLAN_NOT_FOUND: "The requested subscription plan is not configured.",
38
38
  SUBSCRIPTION_ALREADY_ACTIVE: "An active subscription already exists for this plan group.",
39
+ SUBSCRIPTION_CHECKOUT_IN_PROGRESS: "A subscription checkout is already being created for this plan group.",
40
+ SUBSCRIPTION_ALREADY_CANCELED: "The subscription is already canceled.",
41
+ SUBSCRIPTION_ALREADY_FROZEN: "The subscription is already frozen.",
42
+ SUBSCRIPTION_EXPIRED: "The subscription has expired.",
43
+ SUBSCRIPTION_ALREADY_SCHEDULED_CANCEL: "The subscription is already scheduled to cancel at period end.",
44
+ SUBSCRIPTION_ALREADY_ON_PLAN: "The subscription is already on the requested plan.",
45
+ SUBSCRIPTION_IMMEDIATE_CANCEL_UNSUPPORTED: "StreamPay does not support immediate cancellation for active subscriptions.",
46
+ SUBSCRIPTION_PERIOD_END_CANCEL_UNSUPPORTED: "StreamPay only supports period-end cancellation for active subscriptions.",
47
+ SUBSCRIPTION_PLAN_GROUP_MISMATCH: "Subscription plan changes must stay within the same configured plan group.",
48
+ SUBSCRIPTION_PLAN_CHANGE_ALREADY_SCHEDULED: "A different plan change is already scheduled for this subscription.",
39
49
  SUBSCRIPTION_INVALID_STATE: "The subscription is in a state that forbids this action.",
40
50
  SUBSCRIPTION_FREEZE_NOT_ACTIVE: "No active freeze period was found for this subscription.",
41
51
  SUBSCRIPTION_REFERENCE_NOT_AUTHORIZED: "You are not authorized to act on this subscription reference.",
52
+ WEBHOOK_REPLAY_IN_PROGRESS: "This webhook event is already being replayed.",
42
53
  UNKNOWN: "An unexpected error occurred."
43
54
  });
44
55
  var RAW_CODE_MAP = {
@@ -85,10 +96,10 @@ var RAW_CODE_MAP = {
85
96
  COUPON_USED_IN_FINALIZED_INVOICE: "COUPON_LOCKED",
86
97
  SUBSCRIPTION_ALREADY_ACTIVE: "SUBSCRIPTION_ALREADY_ACTIVE",
87
98
  SUBSCRIPTION_NOT_FOUND: "SUBSCRIPTION_NOT_FOUND",
88
- SUBSCRIPTION_ALREADY_CANCELED: "SUBSCRIPTION_INVALID_STATE",
89
- SUBSCRIPTION_ALREADY_FROZEN: "SUBSCRIPTION_INVALID_STATE",
99
+ SUBSCRIPTION_ALREADY_CANCELED: "SUBSCRIPTION_ALREADY_CANCELED",
100
+ SUBSCRIPTION_ALREADY_FROZEN: "SUBSCRIPTION_ALREADY_FROZEN",
90
101
  SUBSCRIPTION_NOT_FROZEN: "SUBSCRIPTION_FREEZE_NOT_ACTIVE",
91
- SUBSCRIPTION_EXPIRED: "SUBSCRIPTION_INVALID_STATE"
102
+ SUBSCRIPTION_EXPIRED: "SUBSCRIPTION_EXPIRED"
92
103
  };
93
104
  function mapToErrorCode(rawCode, status) {
94
105
  if (rawCode && rawCode in RAW_CODE_MAP) {
@@ -316,6 +327,7 @@ async function ensureConsumerForUser(options, ctx, user) {
316
327
  name: user.name || user.email,
317
328
  email: user.email,
318
329
  external_id: user.id,
330
+ consumer_type: "INDIVIDUAL",
319
331
  ...extras
320
332
  };
321
333
  try {
@@ -464,24 +476,39 @@ function asSessionUser(user) {
464
476
  return result;
465
477
  }
466
478
 
467
- // src/utils/amount.ts
468
- var StreamPayAmount = {
469
- toHalalat(sar) {
470
- const asNumber = typeof sar === "string" ? Number(sar) : sar;
471
- if (!Number.isFinite(asNumber)) {
472
- throw new RangeError(`StreamPayAmount.toHalalat: invalid SAR value ${String(sar)}`);
473
- }
474
- return Math.round(asNumber * 100);
475
- },
476
- toSAR(halalat) {
477
- if (!Number.isFinite(halalat) || !Number.isInteger(halalat)) {
478
- throw new RangeError(`StreamPayAmount.toSAR: expected integer halalat, got ${halalat}`);
479
- }
480
- return (halalat / 100).toFixed(2);
481
- }
482
- };
483
-
484
- // src/plugins/subscriptions/types.ts
479
+ // src/plugins/subscriptions/status.ts
480
+ var SUBSCRIPTION_STATUSES = [
481
+ "incomplete",
482
+ "incomplete_expired",
483
+ "trial_pending",
484
+ "trialing",
485
+ "active",
486
+ "inactive",
487
+ "expired",
488
+ "canceled",
489
+ "frozen",
490
+ "past_due"
491
+ ];
492
+ var DEFAULT_ACCESS_STATUSES = ["active", "trialing", "frozen", "past_due"];
493
+ var MANAGEABLE_STATUSES = /* @__PURE__ */ new Set([
494
+ "active",
495
+ "trial_pending",
496
+ "trialing",
497
+ "frozen",
498
+ "past_due"
499
+ ]);
500
+ var TERMINAL_STATUSES = /* @__PURE__ */ new Set([
501
+ "incomplete_expired",
502
+ "inactive",
503
+ "expired",
504
+ "canceled"
505
+ ]);
506
+ var CHECKOUT_SUCCESS_STATUSES = /* @__PURE__ */ new Set([
507
+ "ACTIVE",
508
+ "TRIALING",
509
+ "TRIAL_PENDING",
510
+ "FROZEN"
511
+ ]);
485
512
  function toLocalStatus(status) {
486
513
  switch (status) {
487
514
  case "ACTIVE":
@@ -494,16 +521,200 @@ function toLocalStatus(status) {
494
521
  return "canceled";
495
522
  case "FROZEN":
496
523
  return "frozen";
524
+ case "TRIALING":
525
+ return "trialing";
526
+ case "TRIAL_PENDING":
527
+ return "trial_pending";
497
528
  default:
498
529
  return "incomplete";
499
530
  }
500
531
  }
532
+ function isManageableSubscriptionStatus(status) {
533
+ return MANAGEABLE_STATUSES.has(status);
534
+ }
535
+ function isTerminalSubscriptionStatus(status) {
536
+ return status !== void 0 && TERMINAL_STATUSES.has(status);
537
+ }
538
+ function isCheckoutSuccessStatus(status) {
539
+ return status !== void 0 && CHECKOUT_SUCCESS_STATUSES.has(status);
540
+ }
541
+
542
+ // src/plugins/subscriptions/reconcile.ts
543
+ var SUBSCRIPTION_MODEL = "subscription";
544
+ function reconcileProjectionAgainstExisting(existing, projection, options = {}) {
545
+ const projected = { ...projection };
546
+ if (existing?.billingStatus === "past_due" && projected.status === "active") {
547
+ projected.status = "past_due";
548
+ projected.billingStatus = "past_due";
549
+ }
550
+ const lifecycleAt = options.lifecycleAt === void 0 ? /* @__PURE__ */ new Date() : options.lifecycleAt;
551
+ if (options.stampCancelScheduled !== false && !existing?.cancelAtPeriodEnd && projected.cancelAtPeriodEnd && lifecycleAt) {
552
+ projected.cancelScheduledAt = lifecycleAt;
553
+ }
554
+ if (options.stampCanceled !== false && projected.status === "canceled" && !existing?.canceledAt && lifecycleAt) {
555
+ projected.canceledAt = lifecycleAt;
556
+ }
557
+ return projected;
558
+ }
559
+ function projectSubscriptionAgainstExisting(existing, stream) {
560
+ return reconcileProjectionAgainstExisting(existing, projectSubscriptionFields(stream));
561
+ }
562
+ async function applySubscriptionProjection(adapter, stream, log, source) {
563
+ const streampaySubscriptionId = stream?.id;
564
+ if (!stream || !streampaySubscriptionId) return;
565
+ try {
566
+ const existing = await adapter.findOne({
567
+ model: SUBSCRIPTION_MODEL,
568
+ where: [{ field: "streampaySubscriptionId", value: streampaySubscriptionId }]
569
+ });
570
+ if (!existing) return;
571
+ await adapter.update({
572
+ model: SUBSCRIPTION_MODEL,
573
+ update: projectSubscriptionAgainstExisting(existing, stream),
574
+ where: [{ field: "id", value: existing.id }]
575
+ });
576
+ } catch (err) {
577
+ const message = err instanceof Error ? err.message : String(err);
578
+ log.warn(
579
+ `${source}: project for sub=${streampaySubscriptionId} failed (${message}). Local row will reconcile on next webhook.`
580
+ );
581
+ }
582
+ }
583
+ async function syncSubscriptionFromUpstream(client, adapter, streampaySubscriptionId, log, source, prefetched) {
584
+ let stream = prefetched;
585
+ if (!stream) {
586
+ try {
587
+ stream = await client.getSubscription(streampaySubscriptionId);
588
+ } catch (err) {
589
+ const message = err instanceof Error ? err.message : String(err);
590
+ log.warn(
591
+ `${source}: getSubscription(${streampaySubscriptionId}) failed (${message}). Local row will reconcile on next webhook.`
592
+ );
593
+ return;
594
+ }
595
+ }
596
+ await applySubscriptionProjection(adapter, stream, log, source);
597
+ }
598
+ function projectSubscriptionFields(sub) {
599
+ const status = toLocalStatus(sub.status);
600
+ const terminal = isTerminalSubscriptionStatus(status);
601
+ const periodStart = parseDate(sub.current_period_start);
602
+ const periodEnd = parseDate(sub.current_period_end);
603
+ return {
604
+ streampaySubscriptionId: sub.id ?? null,
605
+ streampayConsumerId: sub.organization_consumer_id ?? null,
606
+ amountInSmallestUnit: typeof sub.amount_in_smallest_unit === "number" ? sub.amount_in_smallest_unit : amountToSmallestUnit(sub.amount, sub.currency),
607
+ originalAmountInSmallestUnit: typeof sub.original_amount_in_smallest_unit === "number" ? sub.original_amount_in_smallest_unit : amountToSmallestUnit(sub.original_amount, sub.currency),
608
+ currency: sub.currency ?? null,
609
+ billingInterval: sub.recurring_interval ?? null,
610
+ billingIntervalCount: sub.recurring_interval_count ?? null,
611
+ status,
612
+ providerStatus: sub.status ?? null,
613
+ periodStart,
614
+ periodEnd,
615
+ currentCycleNumber: sub.current_cycle_number ?? null,
616
+ trialStart: sub.trial_end ? parseDate(sub.started_at) ?? periodStart : null,
617
+ trialEnd: parseDate(sub.trial_end),
618
+ cancelAtPeriodEnd: Boolean(sub.cancel_at_period_end),
619
+ cancelAt: sub.cancel_at_period_end ? periodEnd : null,
620
+ ...sub.cancel_at_period_end ? {} : { cancelScheduledAt: null },
621
+ endedAt: parseDate(sub.ended_at),
622
+ frozenAt: sub.status === "FROZEN" ? parseDate(sub.latest_freeze?.freeze_start_datetime) : null,
623
+ freezeEndAt: sub.status === "FROZEN" ? parseDate(sub.latest_freeze?.freeze_end_datetime) : null,
624
+ providerUpdatedAt: parseDate(sub.updated_at),
625
+ syncedAt: /* @__PURE__ */ new Date(),
626
+ ...terminal ? { activeSlotKey: null } : {},
627
+ updatedAt: /* @__PURE__ */ new Date()
628
+ };
629
+ }
630
+ function parseDate(value) {
631
+ if (!value) return null;
632
+ const date = new Date(value);
633
+ return Number.isNaN(date.getTime()) ? null : date;
634
+ }
635
+ function minorUnitExponent(currency) {
636
+ switch (currency) {
637
+ case "BHD":
638
+ case "KWD":
639
+ case "OMR":
640
+ return 3;
641
+ case "SAR":
642
+ case "USD":
643
+ case "EUR":
644
+ case "GBP":
645
+ case "AED":
646
+ case "QAR":
647
+ return 2;
648
+ default:
649
+ return null;
650
+ }
651
+ }
652
+ function amountToSmallestUnit(value, currency) {
653
+ if (!value) return null;
654
+ const exponent = minorUnitExponent(currency);
655
+ if (exponent === null) return null;
656
+ const match = /^([+-]?)(\d+)(?:\.(\d+))?$/.exec(value);
657
+ if (!match) return null;
658
+ const [, sign, integer, fraction = ""] = match;
659
+ if (!integer) return null;
660
+ const excessFraction = fraction.slice(exponent);
661
+ if (excessFraction && !/^0+$/.test(excessFraction)) return null;
662
+ const normalizedFraction = fraction.slice(0, exponent).padEnd(exponent, "0");
663
+ const factor = 10n ** BigInt(exponent);
664
+ const unsigned = BigInt(integer) * factor + BigInt(normalizedFraction || "0");
665
+ const signed = sign === "-" ? -unsigned : unsigned;
666
+ const numeric = Number(signed);
667
+ return Number.isSafeInteger(numeric) ? numeric : null;
668
+ }
669
+ var SubscriptionItemSchema = zod.z.object({
670
+ product: zod.z.object({ id: zod.z.string() }).passthrough().optional(),
671
+ product_id: zod.z.string().optional()
672
+ }).passthrough();
673
+ function subscriptionItemProductId(item) {
674
+ const parsed = SubscriptionItemSchema.safeParse(item);
675
+ if (!parsed.success) return null;
676
+ return parsed.data.product?.id ?? parsed.data.product_id ?? null;
677
+ }
678
+ function inferPlanFromItems(sub, plans) {
679
+ if (!Array.isArray(sub.items)) return null;
680
+ return inferPlanFromItemList(sub.items, plans);
681
+ }
682
+ function inferPlanFromItemList(items, plans) {
683
+ const productIds = new Set(
684
+ items.map(subscriptionItemProductId).filter((id) => Boolean(id))
685
+ );
686
+ return plans.list.find((plan) => productIds.has(plan.productId))?.name ?? null;
687
+ }
688
+ function projectPlanFields(sub, plans) {
689
+ const currentPlan = inferPlanFromItems(sub, plans);
690
+ const currentProductId = subscriptionItemProductId(sub.items?.[0]);
691
+ const pendingPlan = Array.isArray(sub.pending_change?.target_items) ? inferPlanFromItemList(sub.pending_change.target_items, plans) : null;
692
+ const pendingProductId = subscriptionItemProductId(sub.pending_change?.target_items?.[0]);
693
+ const configuredCurrent = currentPlan ? plans.byName.get(currentPlan) : void 0;
694
+ return {
695
+ ...currentPlan ? {
696
+ plan: currentPlan,
697
+ planVersion: configuredCurrent?.version ?? null,
698
+ productId: currentProductId,
699
+ group: configuredCurrent?.group ?? null
700
+ } : currentProductId ? { productId: currentProductId } : {},
701
+ pendingPlan,
702
+ pendingProductId,
703
+ pendingPlanEffectiveAt: parseDate(sub.pending_change?.effective_at)
704
+ };
705
+ }
706
+ function subscriptionSlotKey(referenceType, referenceId, group) {
707
+ const tuple = JSON.stringify([referenceType, referenceId, group ?? null]);
708
+ return `sp_slot_v1_${crypto.createHash("sha256").update(tuple).digest("hex")}`;
709
+ }
501
710
  var UPGRADE_IDEMPOTENCY_WINDOW_MS = 15 * 60 * 1e3;
502
711
  var PLAN_NAME_METADATA_KEY = "streampay_plugin_plan_name";
503
712
  var REFERENCE_ID_METADATA_KEY = "streampay_plugin_reference_id";
713
+ var REFERENCE_TYPE_METADATA_KEY = "streampay_plugin_reference_type";
714
+ var SUBSCRIPTION_ROW_ID_METADATA_KEY = "streampay_plugin_subscription_row_id";
504
715
 
505
716
  // src/plugins/subscriptions/sync.ts
506
- var SUBSCRIPTION_MODEL = "subscription";
717
+ var SUBSCRIPTION_MODEL2 = "subscription";
507
718
  var WEBHOOK_EVENT_MODEL = "streampayWebhookEvent";
508
719
  function logger(ctx) {
509
720
  return scopedLogger(ctx.context.logger);
@@ -526,6 +737,8 @@ function isUniqueConstraintError(err) {
526
737
  }
527
738
  return false;
528
739
  }
740
+ var WEBHOOK_PROCESSING_LEASE_MS = 2 * 60 * 1e3;
741
+ var WEBHOOK_RETRY_DELAYS_MS = [5, 30, 120, 360, 720].map((minutes) => minutes * 60 * 1e3);
529
742
  async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader, maxAttempts) {
530
743
  const eventId = extractEventId(payload);
531
744
  if (!eventId) {
@@ -535,6 +748,7 @@ async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader
535
748
  return { action: "process", row: null };
536
749
  }
537
750
  const now = /* @__PURE__ */ new Date();
751
+ const lockId = crypto.randomUUID();
538
752
  try {
539
753
  const inserted = await ctx.context.adapter.create({
540
754
  model: WEBHOOK_EVENT_MODEL,
@@ -543,8 +757,10 @@ async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader
543
757
  eventType: payload.event_type,
544
758
  status: "pending",
545
759
  attemptCount: 1,
546
- processedAt: now,
547
- firstSeenAt: now
760
+ receivedAt: now,
761
+ lastAttemptAt: now,
762
+ lockedAt: now,
763
+ lockedBy: lockId
548
764
  }
549
765
  });
550
766
  return { action: "process", row: inserted };
@@ -571,6 +787,12 @@ async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader
571
787
  );
572
788
  return { action: "skip", reason: "dead_letter" };
573
789
  }
790
+ if (existing.lockedAt instanceof Date && now.getTime() - existing.lockedAt.getTime() < WEBHOOK_PROCESSING_LEASE_MS) {
791
+ logger(ctx).info(
792
+ `webhook ${payload.event_type} (${eventId}) is already being processed \u2014 skipping concurrent delivery.`
793
+ );
794
+ return { action: "skip", reason: "in_progress" };
795
+ }
574
796
  const nextAttempt = (existing.attemptCount ?? 0) + 1;
575
797
  if (nextAttempt > maxAttempts) {
576
798
  const updated2 = await ctx.context.adapter.update({
@@ -578,48 +800,114 @@ async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader
578
800
  update: {
579
801
  status: "dead_letter",
580
802
  attemptCount: nextAttempt,
581
- processedAt: now,
803
+ lastAttemptAt: now,
804
+ deadLetteredAt: now,
805
+ nextAttemptAt: null,
582
806
  rawPayload: rawBody,
583
- signatureHeader
807
+ signatureHeader,
808
+ lockedAt: null,
809
+ lockedBy: null
584
810
  },
585
- where: [{ field: "id", value: existing.id }]
811
+ where: [
812
+ { field: "id", value: existing.id },
813
+ { field: "status", value: "pending" },
814
+ { field: "lockedAt", value: existing.lockedAt ?? null }
815
+ ]
586
816
  });
587
- return { action: "dead_letter", row: updated2 ?? existing };
817
+ return updated2 ? { action: "dead_letter", row: updated2 } : { action: "skip", reason: "in_progress" };
588
818
  }
589
819
  const updated = await ctx.context.adapter.update({
590
820
  model: WEBHOOK_EVENT_MODEL,
591
821
  update: {
592
822
  attemptCount: nextAttempt,
593
- processedAt: now
823
+ lastAttemptAt: now,
824
+ nextAttemptAt: null,
825
+ lockedAt: now,
826
+ lockedBy: lockId
594
827
  },
595
- where: [{ field: "id", value: existing.id }]
828
+ where: [
829
+ { field: "id", value: existing.id },
830
+ { field: "status", value: "pending" },
831
+ { field: "lockedAt", value: existing.lockedAt ?? null }
832
+ ]
833
+ });
834
+ return updated ? { action: "process", row: updated } : { action: "skip", reason: "in_progress" };
835
+ }
836
+ async function claimWebhookEventForReplay(ctx, row) {
837
+ const now = /* @__PURE__ */ new Date();
838
+ if (row.lockedAt instanceof Date && now.getTime() - row.lockedAt.getTime() < WEBHOOK_PROCESSING_LEASE_MS) {
839
+ return null;
840
+ }
841
+ return ctx.context.adapter.update({
842
+ model: WEBHOOK_EVENT_MODEL,
843
+ update: {
844
+ status: "pending",
845
+ attemptCount: (row.attemptCount ?? 0) + 1,
846
+ lastAttemptAt: now,
847
+ nextAttemptAt: null,
848
+ completedAt: null,
849
+ deadLetteredAt: null,
850
+ lockedAt: now,
851
+ lockedBy: crypto.randomUUID()
852
+ },
853
+ where: [
854
+ { field: "id", value: row.id },
855
+ { field: "status", value: row.status },
856
+ { field: "lockedAt", value: row.lockedAt ?? null }
857
+ ]
596
858
  });
597
- return { action: "process", row: updated ?? existing };
598
859
  }
599
- async function markWebhookEventCompleted(ctx, rowId) {
860
+ async function markWebhookEventCompleted(ctx, rowId, lockId) {
600
861
  await ctx.context.adapter.update({
601
862
  model: WEBHOOK_EVENT_MODEL,
602
863
  update: {
603
864
  status: "completed",
604
- processedAt: /* @__PURE__ */ new Date(),
865
+ completedAt: /* @__PURE__ */ new Date(),
866
+ nextAttemptAt: null,
867
+ lockedAt: null,
868
+ lockedBy: null,
605
869
  rawPayload: null,
606
870
  signatureHeader: null,
607
- lastError: null
871
+ lastError: null,
872
+ lastErrorCode: null
608
873
  },
609
- where: [{ field: "id", value: rowId }]
874
+ where: [
875
+ { field: "id", value: rowId },
876
+ ...lockId ? [{ field: "lockedBy", value: lockId }] : []
877
+ ]
610
878
  });
611
879
  }
612
- async function recordWebhookEventFailure(ctx, rowId, rawBody, signatureHeader, err) {
880
+ async function recordWebhookEventFailure(ctx, rowId, rawBody, signatureHeader, err, lockId, deadLetter = false) {
613
881
  const lastError = err instanceof Error ? err.message : String(err);
882
+ const sdkError = readSdkErrorFields(err);
883
+ const lastErrorCode = readEnvelope(sdkError.body)?.code ?? (sdkError.status !== void 0 ? `HTTP_${sdkError.status}` : err instanceof Error ? err.name : "UNKNOWN");
884
+ const row = await ctx.context.adapter.findOne({
885
+ model: WEBHOOK_EVENT_MODEL,
886
+ where: [
887
+ { field: "id", value: rowId },
888
+ ...lockId ? [{ field: "lockedBy", value: lockId }] : []
889
+ ]
890
+ });
891
+ const attemptCount = row?.attemptCount ?? 1;
892
+ const retryDelay = WEBHOOK_RETRY_DELAYS_MS[Math.min(attemptCount - 1, WEBHOOK_RETRY_DELAYS_MS.length - 1)];
893
+ const now = /* @__PURE__ */ new Date();
614
894
  await ctx.context.adapter.update({
615
895
  model: WEBHOOK_EVENT_MODEL,
616
896
  update: {
617
- processedAt: /* @__PURE__ */ new Date(),
897
+ ...deadLetter ? { status: "dead_letter", deadLetteredAt: now } : {},
898
+ lastAttemptAt: now,
899
+ nextAttemptAt: deadLetter || retryDelay === void 0 ? null : new Date(now.getTime() + retryDelay),
900
+ lockedAt: null,
901
+ lockedBy: null,
618
902
  lastError,
903
+ lastErrorCode,
619
904
  ...rawBody !== null ? { rawPayload: rawBody } : {},
620
905
  ...signatureHeader !== null ? { signatureHeader } : {}
621
906
  },
622
- where: [{ field: "id", value: rowId }]
907
+ where: [
908
+ { field: "id", value: rowId },
909
+ ...lockId ? [{ field: "lockedBy", value: lockId }] : []
910
+ ]
623
911
  });
624
912
  }
625
913
  function extractEventId(payload) {
@@ -631,92 +919,44 @@ function readMetadataString(data, key) {
631
919
  const value = data.metadata[key];
632
920
  return typeof value === "string" && value.length > 0 ? value : null;
633
921
  }
922
+ function readReferenceType(data) {
923
+ const value = readMetadataString(data, REFERENCE_TYPE_METADATA_KEY);
924
+ return value === "user" || value === "organization" || value === "custom" ? value : null;
925
+ }
634
926
  async function findSubscriptionByStreampayId(ctx, streampaySubscriptionId) {
635
927
  return ctx.context.adapter.findOne({
636
- model: SUBSCRIPTION_MODEL,
928
+ model: SUBSCRIPTION_MODEL2,
637
929
  where: [{ field: "streampaySubscriptionId", value: streampaySubscriptionId }]
638
930
  });
639
931
  }
640
- async function applySubscriptionProjection(adapter, stream, log, source) {
641
- const streampaySubscriptionId = stream?.id;
642
- if (!stream || !streampaySubscriptionId) return;
643
- try {
644
- const existing = await adapter.findOne({
645
- model: SUBSCRIPTION_MODEL,
646
- where: [{ field: "streampaySubscriptionId", value: streampaySubscriptionId }]
647
- });
648
- if (!existing) return;
649
- await adapter.update({
650
- model: SUBSCRIPTION_MODEL,
651
- update: projectSubscriptionFields(stream),
652
- where: [{ field: "id", value: existing.id }]
653
- });
654
- } catch (err) {
655
- const msg = err instanceof Error ? err.message : String(err);
656
- log.warn(
657
- `${source}: project for sub=${streampaySubscriptionId} failed (${msg}). Local row will reconcile on next webhook.`
658
- );
659
- }
660
- }
661
- async function syncSubscriptionFromUpstream(client, adapter, streampaySubscriptionId, log, source) {
662
- let stream;
663
- try {
664
- stream = await client.getSubscription(streampaySubscriptionId);
665
- } catch (err) {
666
- const msg = err instanceof Error ? err.message : String(err);
667
- log.warn(
668
- `${source}: getSubscription(${streampaySubscriptionId}) failed (${msg}). Local row will reconcile on next webhook.`
669
- );
670
- return;
671
- }
672
- await applySubscriptionProjection(adapter, stream, log, source);
673
- }
674
- async function findIncompleteRow(ctx, referenceId, plan) {
932
+ async function findIncompleteRow(ctx, referenceId, referenceType, plan, paymentLinkId) {
675
933
  const candidates = await ctx.context.adapter.findMany({
676
- model: SUBSCRIPTION_MODEL,
934
+ model: SUBSCRIPTION_MODEL2,
677
935
  where: [
678
936
  { field: "referenceId", value: referenceId },
679
937
  { field: "plan", value: plan },
680
938
  { field: "status", value: "incomplete" }
681
939
  ]
682
940
  });
683
- if (candidates.length === 0) return null;
684
- return candidates.reduce(
685
- (newest, candidate) => candidate.createdAt > newest.createdAt ? candidate : newest
686
- );
687
- }
688
- function projectSubscriptionFields(sub) {
689
- return {
690
- streampaySubscriptionId: sub.id ?? null,
691
- streampayConsumerId: sub.organization_consumer_id ?? null,
692
- amountHalalat: amountToHalalat(sub.amount),
693
- currency: sub.currency ?? null,
694
- billingInterval: sub.recurring_interval ?? null,
695
- billingIntervalCount: sub.recurring_interval_count ?? null,
696
- status: toLocalStatus(sub.status),
697
- periodStart: parseDate(sub.current_period_start),
698
- periodEnd: parseDate(sub.current_period_end),
699
- cancelAtPeriodEnd: Boolean(sub.cancel_at_period_end),
700
- endedAt: parseDate(sub.ended_at),
701
- frozenAt: sub.status === "FROZEN" ? parseDate(sub.latest_freeze?.freeze_start_datetime) : null,
702
- freezeEndAt: sub.status === "FROZEN" ? parseDate(sub.latest_freeze?.freeze_end_datetime) : null,
703
- updatedAt: /* @__PURE__ */ new Date()
704
- };
705
- }
706
- function parseDate(value) {
707
- if (!value) return null;
708
- const d = new Date(value);
709
- return Number.isNaN(d.getTime()) ? null : d;
710
- }
711
- function amountToHalalat(value) {
712
- if (!value) return null;
713
- try {
714
- return StreamPayAmount.toHalalat(value);
715
- } catch {
941
+ const scopedCandidates = referenceType ? candidates.filter((candidate) => (candidate.referenceType ?? "user") === referenceType) : candidates;
942
+ if (scopedCandidates.length === 0) return null;
943
+ if (paymentLinkId) {
944
+ const exact = scopedCandidates.find(
945
+ (candidate) => candidate.streampayPaymentLinkId === paymentLinkId
946
+ );
947
+ if (exact) return exact;
948
+ }
949
+ if (!referenceType && new Set(scopedCandidates.map((candidate) => candidate.referenceType ?? "user")).size > 1) {
716
950
  return null;
717
951
  }
952
+ return scopedCandidates.reduce((newest, candidate) => {
953
+ const candidateTime = candidate.createdAt?.getTime() ?? Number.NEGATIVE_INFINITY;
954
+ const newestTime = newest.createdAt?.getTime() ?? Number.NEGATIVE_INFINITY;
955
+ return candidateTime > newestTime ? candidate : newest;
956
+ });
718
957
  }
719
958
  async function resolveRowUser(ctx, row) {
959
+ if ((row.referenceType ?? "user") !== "user") return null;
720
960
  const findUserById = ctx.context.internalAdapter?.findUserById;
721
961
  if (!findUserById) return null;
722
962
  try {
@@ -726,15 +966,33 @@ async function resolveRowUser(ctx, row) {
726
966
  return null;
727
967
  }
728
968
  }
729
- async function fireCallback(ctx, callback, data, callbackName) {
969
+ async function fireCallback(ctx, callback, data, callbackName, retryOnError) {
730
970
  if (!callback) return;
731
971
  try {
732
972
  await callback(data);
733
973
  } catch (err) {
734
974
  const msg = err instanceof Error ? err.message : String(err);
735
975
  logger(ctx).error(`subscription callback ${callbackName} failed: ${msg}`);
976
+ if (retryOnError) {
977
+ throw new SubscriptionCallbackDeliveryError(callbackName, err);
978
+ }
736
979
  }
737
980
  }
981
+ var SubscriptionCallbackDeliveryError = class extends Error {
982
+ callbackName;
983
+ constructor(callbackName, cause) {
984
+ const message = cause instanceof Error ? cause.message : String(cause);
985
+ super(`Subscription callback ${callbackName} failed: ${message}`);
986
+ this.name = "SubscriptionCallbackDeliveryError";
987
+ this.callbackName = callbackName;
988
+ }
989
+ };
990
+ var SubscriptionCorrelationError = class extends Error {
991
+ constructor(message) {
992
+ super(message);
993
+ this.name = "SubscriptionCorrelationError";
994
+ }
995
+ };
738
996
  async function reconcileFromStreamPay(ctx, payload, client, plans) {
739
997
  const streampaySubscriptionId = payload.entity_id;
740
998
  if (!streampaySubscriptionId) {
@@ -752,66 +1010,155 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
752
1010
  throw err;
753
1011
  }
754
1012
  const existing = await findSubscriptionByStreampayId(ctx, streampaySubscriptionId);
755
- const projected = projectSubscriptionFields(stream);
756
- if (payload.event_type === "SUBSCRIPTION_CYCLE_RENEWAL_FAILED" && projected.status === "active") {
1013
+ let projected = {
1014
+ ...projectSubscriptionFields(stream),
1015
+ ...projectPlanFields(stream, plans)
1016
+ };
1017
+ const eventAt = parseDate(payload.timestamp);
1018
+ const eventIsStale = Boolean(
1019
+ eventAt && existing?.providerUpdatedAt instanceof Date && eventAt.getTime() < existing.providerUpdatedAt.getTime()
1020
+ );
1021
+ if (!eventIsStale && payload.event_type === "SUBSCRIPTION_CYCLE_RENEWAL_FAILED" && projected.status === "active") {
757
1022
  projected.status = "past_due";
1023
+ projected.billingStatus = "past_due";
1024
+ }
1025
+ const schedulesCancellation = !eventIsStale && payload.event_type === "SUBSCRIPTION_CANCEL_AT_PERIOD_END" && Boolean(stream.cancel_at_period_end);
1026
+ if (schedulesCancellation) {
1027
+ projected.cancelAt = parseDate(stream.current_period_end);
758
1028
  }
1029
+ const confirmsCancellation = !eventIsStale && payload.event_type === "SUBSCRIPTION_CANCELED" && projected.status === "canceled";
1030
+ if (confirmsCancellation) {
1031
+ projected.activeSlotKey = null;
1032
+ }
1033
+ projected = reconcileProjectionAgainstExisting(existing, projected, {
1034
+ lifecycleAt: eventAt,
1035
+ stampCancelScheduled: schedulesCancellation,
1036
+ stampCanceled: confirmsCancellation
1037
+ });
759
1038
  if (existing) {
1039
+ const projectedStatus = projected.status ?? existing.status;
1040
+ if (!isTerminalSubscriptionStatus(projectedStatus)) {
1041
+ const desiredSlotKey = subscriptionSlotKey(
1042
+ existing.referenceType ?? "user",
1043
+ existing.referenceId,
1044
+ projected.group === void 0 ? existing.group : projected.group
1045
+ );
1046
+ if (existing.activeSlotKey !== desiredSlotKey) {
1047
+ projected.activeSlotKey = desiredSlotKey;
1048
+ }
1049
+ }
760
1050
  const updated = await ctx.context.adapter.update({
761
- model: SUBSCRIPTION_MODEL,
1051
+ model: SUBSCRIPTION_MODEL2,
762
1052
  update: projected,
763
1053
  where: [{ field: "id", value: existing.id }]
764
1054
  });
1055
+ if (eventIsStale) {
1056
+ logger(ctx).info(
1057
+ `webhook ${payload.event_type}: ignored stale lifecycle callback for sub=${streampaySubscriptionId}.`
1058
+ );
1059
+ return { row: null, stream };
1060
+ }
765
1061
  return { row: updated ?? { ...existing, ...projected }, stream };
766
1062
  }
767
1063
  const planName = readMetadataString(payload.data, PLAN_NAME_METADATA_KEY) ?? inferPlanFromItems(stream, plans);
768
1064
  const referenceId = readMetadataString(payload.data, REFERENCE_ID_METADATA_KEY);
1065
+ const metadataReferenceType = readReferenceType(payload.data);
769
1066
  if (!planName || !referenceId) {
770
1067
  logger(ctx).warn(
771
1068
  `webhook ${payload.event_type}: cannot link sub=${streampaySubscriptionId} \u2014 missing plan_name (${planName}) or reference_id (${referenceId}) metadata.`
772
1069
  );
773
1070
  return { row: null, stream };
774
1071
  }
775
- const incomplete = await findIncompleteRow(ctx, referenceId, planName);
1072
+ const paymentLinkId = stream.latest_invoice?.payment_link_id ?? payload.data?.payment_link?.id ?? null;
1073
+ const localRowId = readMetadataString(payload.data, SUBSCRIPTION_ROW_ID_METADATA_KEY);
1074
+ if (localRowId) {
1075
+ const metadataRow = await ctx.context.adapter.findOne({
1076
+ model: SUBSCRIPTION_MODEL2,
1077
+ where: [{ field: "id", value: localRowId }]
1078
+ });
1079
+ if (!metadataRow) {
1080
+ logger(ctx).warn(
1081
+ `webhook ${payload.event_type}: referenced subscription row=${localRowId} is missing; rebuilding from signed metadata.`
1082
+ );
1083
+ } else if (metadataRow.referenceId === referenceId && (!metadataReferenceType || (metadataRow.referenceType ?? "user") === metadataReferenceType) && metadataRow.plan === planName && (!metadataRow.streampaySubscriptionId || metadataRow.streampaySubscriptionId === streampaySubscriptionId) && (!metadataRow.streampayPaymentLinkId || !paymentLinkId || metadataRow.streampayPaymentLinkId === paymentLinkId)) {
1084
+ const projectedWithSlot = {
1085
+ ...projected,
1086
+ billingStatus: metadataRow.billingStatus ?? "current",
1087
+ ...projected.activeSlotKey === null ? {} : {
1088
+ activeSlotKey: metadataRow.activeSlotKey ?? subscriptionSlotKey(
1089
+ metadataRow.referenceType ?? metadataReferenceType ?? "user",
1090
+ metadataRow.referenceId,
1091
+ projected.group === void 0 ? metadataRow.group : projected.group
1092
+ )
1093
+ }
1094
+ };
1095
+ const updated = await ctx.context.adapter.update({
1096
+ model: SUBSCRIPTION_MODEL2,
1097
+ update: projectedWithSlot,
1098
+ where: [{ field: "id", value: metadataRow.id }]
1099
+ });
1100
+ return { row: updated ?? { ...metadataRow, ...projectedWithSlot }, stream };
1101
+ }
1102
+ if (metadataRow) {
1103
+ logger(ctx).warn(
1104
+ `webhook ${payload.event_type}: ignored unsafe subscription row correlation for row=${localRowId}.`
1105
+ );
1106
+ throw new SubscriptionCorrelationError(
1107
+ `Webhook ${payload.event_type} failed protected subscription correlation for row=${localRowId}.`
1108
+ );
1109
+ }
1110
+ }
1111
+ const incomplete = await findIncompleteRow(
1112
+ ctx,
1113
+ referenceId,
1114
+ metadataReferenceType,
1115
+ planName,
1116
+ paymentLinkId
1117
+ );
776
1118
  if (incomplete) {
1119
+ const projectedWithSlot = {
1120
+ ...projected,
1121
+ billingStatus: incomplete.billingStatus ?? "current",
1122
+ ...projected.activeSlotKey === null ? {} : {
1123
+ activeSlotKey: incomplete.activeSlotKey ?? subscriptionSlotKey(
1124
+ incomplete.referenceType ?? metadataReferenceType ?? "user",
1125
+ incomplete.referenceId,
1126
+ projected.group === void 0 ? incomplete.group : projected.group
1127
+ )
1128
+ }
1129
+ };
777
1130
  const updated = await ctx.context.adapter.update({
778
- model: SUBSCRIPTION_MODEL,
779
- update: projected,
1131
+ model: SUBSCRIPTION_MODEL2,
1132
+ update: projectedWithSlot,
780
1133
  where: [{ field: "id", value: incomplete.id }]
781
1134
  });
782
1135
  return {
783
- row: updated ?? { ...incomplete, ...projected },
1136
+ row: updated ?? { ...incomplete, ...projectedWithSlot },
784
1137
  stream
785
1138
  };
786
1139
  }
787
1140
  const plan = plans.byName.get(planName);
1141
+ const referenceType = metadataReferenceType ?? "custom";
788
1142
  const row = await ctx.context.adapter.create({
789
- model: SUBSCRIPTION_MODEL,
1143
+ model: SUBSCRIPTION_MODEL2,
790
1144
  data: {
1145
+ cancelScheduledAt: null,
1146
+ canceledAt: null,
791
1147
  ...projected,
792
1148
  referenceId,
1149
+ referenceType,
1150
+ activeSlotKey: isTerminalSubscriptionStatus(projected.status) ? null : subscriptionSlotKey(referenceType, referenceId, plan?.group),
1151
+ streampayPaymentLinkId: paymentLinkId,
793
1152
  plan: planName,
1153
+ planVersion: plan?.version ?? null,
1154
+ productId: plan?.productId ?? subscriptionItemProductId(stream.items?.[0]),
794
1155
  group: plan?.group ?? null,
1156
+ billingStatus: "current",
795
1157
  createdAt: /* @__PURE__ */ new Date()
796
1158
  }
797
1159
  });
798
1160
  return { row, stream };
799
1161
  }
800
- var SubscriptionItemSchema = zod.z.object({
801
- product: zod.z.object({ id: zod.z.string() }).passthrough().optional(),
802
- product_id: zod.z.string().optional()
803
- }).passthrough();
804
- function subscriptionItemProductId(item) {
805
- const parsed = SubscriptionItemSchema.safeParse(item);
806
- if (!parsed.success) return null;
807
- return parsed.data.product?.id ?? parsed.data.product_id ?? null;
808
- }
809
- function inferPlanFromItems(sub, plans) {
810
- const first = Array.isArray(sub.items) ? sub.items[0] : void 0;
811
- const productId = subscriptionItemProductId(first);
812
- if (!productId) return null;
813
- return plans.list.find((plan) => plan.productId === productId)?.name ?? null;
814
- }
815
1162
  async function syncWebhookPayload(ctx, payload, client, plans, callbacks, options = {}) {
816
1163
  if (payload.entity_type !== "SUBSCRIPTION" && payload.event_type !== "INVOICE_COMPLETED") {
817
1164
  return;
@@ -820,6 +1167,7 @@ async function syncWebhookPayload(ctx, payload, client, plans, callbacks, option
820
1167
  const rawBody = options.rawBody ?? null;
821
1168
  const signatureHeader = options.signatureHeader ?? null;
822
1169
  const maxAttempts = Math.max(1, options.maxAttempts ?? DEFAULT_MAX_WEBHOOK_ATTEMPTS);
1170
+ const retryOnCallbackError = options.retryOnCallbackError !== false;
823
1171
  let claim = { action: "process", row: null };
824
1172
  if (dedupe) {
825
1173
  claim = await claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader, maxAttempts);
@@ -832,9 +1180,20 @@ async function syncWebhookPayload(ctx, payload, client, plans, callbacks, option
832
1180
  }
833
1181
  }
834
1182
  const trackedRowId = claim.row?.id ?? null;
1183
+ const trackedLockId = claim.row?.lockedBy ?? void 0;
835
1184
  try {
836
1185
  if (payload.event_type === "INVOICE_COMPLETED") {
837
- await handleInvoiceCompleted(ctx, payload, client, plans, callbacks);
1186
+ await handleInvoiceCompleted(
1187
+ ctx,
1188
+ payload,
1189
+ client,
1190
+ plans,
1191
+ callbacks,
1192
+ retryOnCallbackError,
1193
+ options.retryingRenewalCallback === true || claim.row?.lastError?.startsWith(
1194
+ "Subscription callback onSubscriptionRenewed failed:"
1195
+ ) === true
1196
+ );
838
1197
  } else {
839
1198
  const { row, stream } = await reconcileFromStreamPay(ctx, payload, client, plans);
840
1199
  if (row) {
@@ -845,18 +1204,27 @@ async function syncWebhookPayload(ctx, payload, client, plans, callbacks, option
845
1204
  user,
846
1205
  event: payload
847
1206
  };
848
- await dispatchSubscriptionCallback(ctx, payload, data, callbacks);
1207
+ await dispatchSubscriptionCallback(ctx, payload, data, callbacks, retryOnCallbackError);
849
1208
  }
850
1209
  }
851
- if (trackedRowId) await markWebhookEventCompleted(ctx, trackedRowId);
1210
+ if (trackedRowId) await markWebhookEventCompleted(ctx, trackedRowId, trackedLockId);
852
1211
  } catch (err) {
853
1212
  if (trackedRowId) {
854
- await recordWebhookEventFailure(ctx, trackedRowId, rawBody, signatureHeader, err);
1213
+ const deadLetter = classifyWebhookFailure(err) === "PERMANENT" || (claim.row?.attemptCount ?? 0) >= maxAttempts;
1214
+ await recordWebhookEventFailure(
1215
+ ctx,
1216
+ trackedRowId,
1217
+ rawBody,
1218
+ signatureHeader,
1219
+ err,
1220
+ trackedLockId,
1221
+ deadLetter
1222
+ );
855
1223
  }
856
1224
  throw err;
857
1225
  }
858
1226
  }
859
- async function handleInvoiceCompleted(ctx, payload, client, _plans, callbacks) {
1227
+ async function handleInvoiceCompleted(ctx, payload, client, plans, callbacks, retryOnCallbackError, retryingRenewalCallback) {
860
1228
  const invoiceId = payload.data?.invoice?.id ?? payload.entity_id;
861
1229
  if (!invoiceId) return;
862
1230
  let subscriptionId = null;
@@ -882,53 +1250,180 @@ async function handleInvoiceCompleted(ctx, payload, client, _plans, callbacks) {
882
1250
  }
883
1251
  const existing = await findSubscriptionByStreampayId(ctx, subscriptionId);
884
1252
  if (!existing) return;
885
- const projected = projectSubscriptionFields(stream);
1253
+ const eventAt = parseDate(payload.timestamp);
1254
+ const eventIsStale = Boolean(
1255
+ eventAt && existing.providerUpdatedAt instanceof Date && eventAt.getTime() < existing.providerUpdatedAt.getTime()
1256
+ );
1257
+ const projected = {
1258
+ ...projectSubscriptionFields(stream),
1259
+ ...projectPlanFields(stream, plans),
1260
+ ...eventIsStale ? existing.billingStatus === "past_due" && toLocalStatus(stream.status) === "active" ? { status: "past_due", billingStatus: "past_due" } : {} : { billingStatus: "current" }
1261
+ };
1262
+ const previousPeriodEnd = existing.periodEnd?.getTime() ?? null;
1263
+ const projectedPeriodEnd = projected.periodEnd?.getTime() ?? null;
1264
+ const periodAdvanced = previousPeriodEnd !== null && projectedPeriodEnd !== null && projectedPeriodEnd > previousPeriodEnd;
1265
+ const cycleAdvanced = existing.currentCycleNumber !== null && existing.currentCycleNumber !== void 0 && projected.currentCycleNumber !== null && projected.currentCycleNumber !== void 0 && projected.currentCycleNumber > existing.currentCycleNumber;
886
1266
  const updated = await ctx.context.adapter.update({
887
- model: SUBSCRIPTION_MODEL,
1267
+ model: SUBSCRIPTION_MODEL2,
888
1268
  update: projected,
889
1269
  where: [{ field: "id", value: existing.id }]
890
1270
  });
891
1271
  const row = updated ?? { ...existing, ...projected };
892
1272
  const user = await resolveRowUser(ctx, row);
893
- await fireCallback(
894
- ctx,
895
- callbacks.onSubscriptionRenewed,
896
- { subscription: row, streampaySubscription: stream, user, event: payload },
897
- "onSubscriptionRenewed"
898
- );
1273
+ if (!eventIsStale && (periodAdvanced || cycleAdvanced || retryingRenewalCallback)) {
1274
+ await fireCallback(
1275
+ ctx,
1276
+ callbacks.onSubscriptionRenewed,
1277
+ { subscription: row, streampaySubscription: stream, user, event: payload },
1278
+ "onSubscriptionRenewed",
1279
+ retryOnCallbackError
1280
+ );
1281
+ }
899
1282
  }
900
- async function dispatchSubscriptionCallback(ctx, payload, data, callbacks) {
1283
+ async function dispatchSubscriptionCallback(ctx, payload, data, callbacks, retryOnCallbackError) {
901
1284
  switch (payload.event_type) {
902
1285
  case "SUBSCRIPTION_CREATED":
903
- await fireCallback(ctx, callbacks.onSubscriptionCreated, data, "onSubscriptionCreated");
1286
+ await fireCallback(
1287
+ ctx,
1288
+ callbacks.onSubscriptionCreated,
1289
+ data,
1290
+ "onSubscriptionCreated",
1291
+ retryOnCallbackError
1292
+ );
904
1293
  return;
905
1294
  case "SUBSCRIPTION_ACTIVATED":
906
- await fireCallback(ctx, callbacks.onSubscriptionActivated, data, "onSubscriptionActivated");
1295
+ await fireCallback(
1296
+ ctx,
1297
+ callbacks.onSubscriptionActivated,
1298
+ data,
1299
+ "onSubscriptionActivated",
1300
+ retryOnCallbackError
1301
+ );
907
1302
  return;
908
1303
  case "SUBSCRIPTION_CANCELED":
909
- await fireCallback(ctx, callbacks.onSubscriptionCanceled, data, "onSubscriptionCanceled");
910
- return;
911
- case "SUBSCRIPTION_FROZEN":
912
- case "SUBSCRIPTION_FREEZE_NOW":
913
- await fireCallback(ctx, callbacks.onSubscriptionFrozen, data, "onSubscriptionFrozen");
914
- return;
915
- case "SUBSCRIPTION_UNFREEZE_NOW":
916
- case "SUBSCRIPTION_FREEZE_CANCEL":
917
- await fireCallback(ctx, callbacks.onSubscriptionResumed, data, "onSubscriptionResumed");
918
- return;
919
- case "SUBSCRIPTION_CYCLE_RENEWAL_FAILED":
920
1304
  await fireCallback(
921
1305
  ctx,
922
- callbacks.onSubscriptionPaymentFailed,
1306
+ callbacks.onSubscriptionCanceled,
923
1307
  data,
924
- "onSubscriptionPaymentFailed"
1308
+ "onSubscriptionCanceled",
1309
+ retryOnCallbackError
925
1310
  );
926
1311
  return;
927
- default:
928
- return;
929
- }
1312
+ case "SUBSCRIPTION_INACTIVATED":
1313
+ await fireCallback(
1314
+ ctx,
1315
+ callbacks.onSubscriptionInactivated,
1316
+ data,
1317
+ "onSubscriptionInactivated",
1318
+ retryOnCallbackError
1319
+ );
1320
+ return;
1321
+ case "SUBSCRIPTION_CANCEL_AT_PERIOD_END":
1322
+ await fireCallback(
1323
+ ctx,
1324
+ callbacks.onSubscriptionCancelScheduled,
1325
+ data,
1326
+ "onSubscriptionCancelScheduled",
1327
+ retryOnCallbackError
1328
+ );
1329
+ return;
1330
+ case "SUBSCRIPTION_FROZEN":
1331
+ case "SUBSCRIPTION_FREEZE_NOW":
1332
+ await fireCallback(
1333
+ ctx,
1334
+ callbacks.onSubscriptionFrozen,
1335
+ data,
1336
+ "onSubscriptionFrozen",
1337
+ retryOnCallbackError
1338
+ );
1339
+ return;
1340
+ case "SUBSCRIPTION_UNFREEZE_NOW":
1341
+ await fireCallback(
1342
+ ctx,
1343
+ callbacks.onSubscriptionResumed,
1344
+ data,
1345
+ "onSubscriptionResumed",
1346
+ retryOnCallbackError
1347
+ );
1348
+ return;
1349
+ case "SUBSCRIPTION_UNFREEZE_FUTURE":
1350
+ await fireCallback(
1351
+ ctx,
1352
+ callbacks.onSubscriptionUnfreezeScheduled,
1353
+ data,
1354
+ "onSubscriptionUnfreezeScheduled",
1355
+ retryOnCallbackError
1356
+ );
1357
+ return;
1358
+ case "SUBSCRIPTION_FREEZE_CANCEL":
1359
+ await fireCallback(
1360
+ ctx,
1361
+ callbacks.onSubscriptionFreezeCanceled,
1362
+ data,
1363
+ "onSubscriptionFreezeCanceled",
1364
+ retryOnCallbackError
1365
+ );
1366
+ return;
1367
+ case "SUBSCRIPTION_CYCLE_RENEWAL_FAILED":
1368
+ await fireCallback(
1369
+ ctx,
1370
+ callbacks.onSubscriptionPaymentFailed,
1371
+ data,
1372
+ "onSubscriptionPaymentFailed",
1373
+ retryOnCallbackError
1374
+ );
1375
+ return;
1376
+ case "SUBSCRIPTION_PLAN_CHANGE_SCHEDULED":
1377
+ await fireCallback(
1378
+ ctx,
1379
+ callbacks.onSubscriptionPlanChangeScheduled,
1380
+ data,
1381
+ "onSubscriptionPlanChangeScheduled",
1382
+ retryOnCallbackError
1383
+ );
1384
+ return;
1385
+ case "SUBSCRIPTION_PLAN_CHANGE_CANCELED":
1386
+ await fireCallback(
1387
+ ctx,
1388
+ callbacks.onSubscriptionPlanChangeCanceled,
1389
+ data,
1390
+ "onSubscriptionPlanChangeCanceled",
1391
+ retryOnCallbackError
1392
+ );
1393
+ return;
1394
+ case "SUBSCRIPTION_PLAN_CHANGED":
1395
+ await fireCallback(
1396
+ ctx,
1397
+ callbacks.onSubscriptionPlanChanged,
1398
+ data,
1399
+ "onSubscriptionPlanChanged",
1400
+ retryOnCallbackError
1401
+ );
1402
+ return;
1403
+ case "SUBSCRIPTION_PLAN_CHANGE_INVOICE_REISSUED":
1404
+ await fireCallback(
1405
+ ctx,
1406
+ callbacks.onSubscriptionPlanChangeInvoiceReissued,
1407
+ data,
1408
+ "onSubscriptionPlanChangeInvoiceReissued",
1409
+ retryOnCallbackError
1410
+ );
1411
+ return;
1412
+ case "SUBSCRIPTION_PLAN_UPDATED":
1413
+ await fireCallback(
1414
+ ctx,
1415
+ callbacks.onSubscriptionPlanUpdated,
1416
+ data,
1417
+ "onSubscriptionPlanUpdated",
1418
+ retryOnCallbackError
1419
+ );
1420
+ return;
1421
+ default:
1422
+ return;
1423
+ }
930
1424
  }
931
1425
  function classifyWebhookFailure(err) {
1426
+ if (err instanceof SubscriptionCorrelationError) return "PERMANENT";
932
1427
  const { status } = readSdkErrorFields(err);
933
1428
  if (status === void 0) return "TRANSIENT";
934
1429
  if (status === 404 || status === 429) return "TRANSIENT";
@@ -972,7 +1467,12 @@ function getAdapter(ctx) {
972
1467
  }
973
1468
  return adapter;
974
1469
  }
975
- var ForwardedBody = zod.z.object({}).passthrough();
1470
+ function forwardedBody() {
1471
+ return zod.z.custom(
1472
+ (value) => value !== null && typeof value === "object" && !Array.isArray(value),
1473
+ "Expected an object body."
1474
+ );
1475
+ }
976
1476
  var PaymentsListQuery = zod.z.object({
977
1477
  page: zod.z.coerce.number().int().positive().optional(),
978
1478
  size: zod.z.coerce.number().int().positive().max(100).optional(),
@@ -993,7 +1493,7 @@ function buildPaymentsEndpoints(client, adminOptions) {
993
1493
  "/admin/streampay/payments/:id/refund",
994
1494
  {
995
1495
  method: "POST",
996
- body: ForwardedBody,
1496
+ body: forwardedBody(),
997
1497
  use: [api.sessionMiddleware]
998
1498
  },
999
1499
  async (ctx) => {
@@ -1067,7 +1567,7 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1067
1567
  "/admin/streampay/subscriptions",
1068
1568
  {
1069
1569
  method: "POST",
1070
- body: ForwardedBody,
1570
+ body: forwardedBody(),
1071
1571
  use: [api.sessionMiddleware]
1072
1572
  },
1073
1573
  async (ctx) => {
@@ -1085,7 +1585,7 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1085
1585
  "/admin/streampay/subscriptions/:id",
1086
1586
  {
1087
1587
  method: "PATCH",
1088
- body: ForwardedBody,
1588
+ body: forwardedBody(),
1089
1589
  use: [api.sessionMiddleware]
1090
1590
  },
1091
1591
  async (ctx) => {
@@ -1167,7 +1667,7 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1167
1667
  "/admin/streampay/subscriptions/:id/cancel",
1168
1668
  {
1169
1669
  method: "POST",
1170
- body: ForwardedBody,
1670
+ body: forwardedBody(),
1171
1671
  use: [api.sessionMiddleware]
1172
1672
  },
1173
1673
  async (ctx) => {
@@ -1199,7 +1699,7 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1199
1699
  "/admin/streampay/subscriptions/:id/freeze",
1200
1700
  {
1201
1701
  method: "POST",
1202
- body: ForwardedBody,
1702
+ body: forwardedBody(),
1203
1703
  use: [api.sessionMiddleware]
1204
1704
  },
1205
1705
  async (ctx) => {
@@ -1252,7 +1752,7 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
1252
1752
  "/admin/streampay/subscriptions/:id/freeze/:freezeId",
1253
1753
  {
1254
1754
  method: "PUT",
1255
- body: ForwardedBody,
1755
+ body: forwardedBody(),
1256
1756
  use: [api.sessionMiddleware]
1257
1757
  },
1258
1758
  async (ctx) => {
@@ -1362,7 +1862,7 @@ function buildConsumersEndpoints(client, adminOptions) {
1362
1862
  "/admin/streampay/consumers/:id",
1363
1863
  {
1364
1864
  method: "PATCH",
1365
- body: ForwardedBody,
1865
+ body: forwardedBody(),
1366
1866
  use: [api.sessionMiddleware]
1367
1867
  },
1368
1868
  async (ctx) => {
@@ -1481,7 +1981,7 @@ function buildProductsEndpoints(client, adminOptions) {
1481
1981
  "/admin/streampay/products",
1482
1982
  {
1483
1983
  method: "POST",
1484
- body: ForwardedBody,
1984
+ body: forwardedBody(),
1485
1985
  use: [api.sessionMiddleware]
1486
1986
  },
1487
1987
  async (ctx) => {
@@ -1539,7 +2039,7 @@ function buildProductsEndpoints(client, adminOptions) {
1539
2039
  "/admin/streampay/products/:id",
1540
2040
  {
1541
2041
  method: "PUT",
1542
- body: ForwardedBody,
2042
+ body: forwardedBody(),
1543
2043
  use: [api.sessionMiddleware]
1544
2044
  },
1545
2045
  async (ctx) => {
@@ -1587,7 +2087,7 @@ function buildCouponsEndpoints(client, adminOptions) {
1587
2087
  "/admin/streampay/coupons",
1588
2088
  {
1589
2089
  method: "POST",
1590
- body: ForwardedBody,
2090
+ body: forwardedBody(),
1591
2091
  use: [api.sessionMiddleware]
1592
2092
  },
1593
2093
  async (ctx) => {
@@ -1645,7 +2145,7 @@ function buildCouponsEndpoints(client, adminOptions) {
1645
2145
  "/admin/streampay/coupons/:id",
1646
2146
  {
1647
2147
  method: "PUT",
1648
- body: ForwardedBody,
2148
+ body: forwardedBody(),
1649
2149
  use: [api.sessionMiddleware]
1650
2150
  },
1651
2151
  async (ctx) => {
@@ -1756,7 +2256,7 @@ function buildWebhookEventsEndpoints(adminOptions, registry) {
1756
2256
  ...where.length > 0 ? { where } : {},
1757
2257
  limit: size,
1758
2258
  offset: (page - 1) * size,
1759
- sortBy: { field: "processedAt", direction: "desc" }
2259
+ sortBy: { field: "receivedAt", direction: "desc" }
1760
2260
  }),
1761
2261
  adapter.count({
1762
2262
  model: WEBHOOK_EVENT_MODEL,
@@ -1963,6 +2463,7 @@ var checkout = (checkoutOptions = {}) => (options) => {
1963
2463
  const payload = {
1964
2464
  name: ctx.body.name ?? `Checkout ${(/* @__PURE__ */ new Date()).toISOString()}`,
1965
2465
  description: ctx.body.description ?? null,
2466
+ currency: checkoutOptions.currency ?? "SAR",
1966
2467
  items
1967
2468
  };
1968
2469
  if (consumerId !== null) payload.organization_consumer_id = consumerId;
@@ -2083,32 +2584,329 @@ function clampPageSize(size) {
2083
2584
  if (!size || !Number.isFinite(size) || size < 1) return DEFAULT_PAGE_SIZE;
2084
2585
  return Math.min(Math.floor(size), 100);
2085
2586
  }
2587
+ var STREAMPAY_EVENT_ENTITY_TYPES = {
2588
+ PAYMENT_SUCCEEDED: "PAYMENT",
2589
+ PAYMENT_FAILED: "PAYMENT",
2590
+ PAYMENT_CANCELED: "PAYMENT",
2591
+ PAYMENT_REFUNDED: "PAYMENT",
2592
+ PAYMENT_MARKED_AS_PAID: "PAYMENT",
2593
+ INVOICE_CREATED: "INVOICE",
2594
+ INVOICE_SENT: "INVOICE",
2595
+ INVOICE_ACCEPTED: "INVOICE",
2596
+ INVOICE_REJECTED: "INVOICE",
2597
+ INVOICE_COMPLETED: "INVOICE",
2598
+ INVOICE_CANCELED: "INVOICE",
2599
+ INVOICE_UPDATED: "INVOICE",
2600
+ SUBSCRIPTION_CREATED: "SUBSCRIPTION",
2601
+ SUBSCRIPTION_ACTIVATED: "SUBSCRIPTION",
2602
+ SUBSCRIPTION_INACTIVATED: "SUBSCRIPTION",
2603
+ SUBSCRIPTION_CANCELED: "SUBSCRIPTION",
2604
+ SUBSCRIPTION_FROZEN: "SUBSCRIPTION",
2605
+ SUBSCRIPTION_CYCLE_RENEWAL_FAILED: "SUBSCRIPTION",
2606
+ SUBSCRIPTION_CANCEL_AT_PERIOD_END: "SUBSCRIPTION",
2607
+ SUBSCRIPTION_FREEZE_NOW: "SUBSCRIPTION",
2608
+ SUBSCRIPTION_UNFREEZE_NOW: "SUBSCRIPTION",
2609
+ SUBSCRIPTION_UNFREEZE_FUTURE: "SUBSCRIPTION",
2610
+ SUBSCRIPTION_FREEZE_CANCEL: "SUBSCRIPTION",
2611
+ SUBSCRIPTION_PLAN_CHANGE_SCHEDULED: "SUBSCRIPTION",
2612
+ SUBSCRIPTION_PLAN_CHANGE_CANCELED: "SUBSCRIPTION",
2613
+ SUBSCRIPTION_PLAN_CHANGED: "SUBSCRIPTION",
2614
+ SUBSCRIPTION_PLAN_CHANGE_INVOICE_REISSUED: "SUBSCRIPTION",
2615
+ SUBSCRIPTION_PLAN_UPDATED: "SUBSCRIPTION",
2616
+ PAYMENT_LINK_PAY_ATTEMPT_FAILED: "PAYMENT_LINK"
2617
+ };
2618
+ function eventTypesForEntity(entityType) {
2619
+ return Object.entries(STREAMPAY_EVENT_ENTITY_TYPES).filter(([, entity]) => entity === entityType).map(([event]) => event);
2620
+ }
2621
+ var STREAMPAY_PAYMENT_EVENT_TYPES = eventTypesForEntity("PAYMENT");
2622
+ var STREAMPAY_INVOICE_EVENT_TYPES = eventTypesForEntity("INVOICE");
2623
+ var STREAMPAY_SUBSCRIPTION_EVENT_TYPES = eventTypesForEntity("SUBSCRIPTION");
2624
+ var STREAMPAY_PAYMENT_LINK_EVENT_TYPES = eventTypesForEntity("PAYMENT_LINK");
2625
+ var STREAMPAY_EVENT_TYPES = Object.keys(
2626
+ STREAMPAY_EVENT_ENTITY_TYPES
2627
+ );
2628
+ var StreamPayWebhookEnvelopeSchema = zod.z.object({
2629
+ event_type: zod.z.string().min(1),
2630
+ entity_type: zod.z.string().min(1),
2631
+ entity_id: zod.z.string().min(1),
2632
+ entity_url: zod.z.string(),
2633
+ status: zod.z.string(),
2634
+ timestamp: zod.z.string().min(1),
2635
+ data: zod.z.record(zod.z.string(), zod.z.unknown())
2636
+ });
2637
+ function isStreamPayWebhookEnvelope(value) {
2638
+ return StreamPayWebhookEnvelopeSchema.safeParse(value).success;
2639
+ }
2640
+ function isStreamPayEventType(value) {
2641
+ return Object.hasOwn(STREAMPAY_EVENT_ENTITY_TYPES, value);
2642
+ }
2643
+ function isKnownStreamPayWebhookPayload(payload) {
2644
+ return isStreamPayEventType(payload.event_type) && payload.entity_type === STREAMPAY_EVENT_ENTITY_TYPES[payload.event_type];
2645
+ }
2646
+ var SUBSCRIPTION_MODEL3 = "subscription";
2647
+ function requireUser(ctx) {
2648
+ const user = asSessionUser(ctx.context.session?.user);
2649
+ if (!user) {
2650
+ throw new api.APIError("UNAUTHORIZED", {
2651
+ message: "Subscription endpoints require an authenticated session."
2652
+ });
2653
+ }
2654
+ if (user.isAnonymous) {
2655
+ throw new api.APIError("UNAUTHORIZED", {
2656
+ message: "Anonymous users cannot manage subscriptions."
2657
+ });
2658
+ }
2659
+ return user;
2660
+ }
2661
+ function resolveReference(user, query) {
2662
+ const referenceId = query?.referenceId ?? user.id;
2663
+ return {
2664
+ referenceId,
2665
+ referenceType: query?.referenceType ?? (referenceId === user.id ? "user" : "custom")
2666
+ };
2667
+ }
2668
+ async function authorizeReference(ctx, user, referenceId, referenceType, action, subsOptions) {
2669
+ if (referenceType === "user" && referenceId === user.id) return;
2670
+ if (!subsOptions.authorizeReference) {
2671
+ throw new api.APIError("FORBIDDEN", {
2672
+ code: $ERROR_CODES.FORBIDDEN.code,
2673
+ message: "Cross-account subscription actions require an `authorizeReference` callback."
2674
+ });
2675
+ }
2676
+ const authorized = await subsOptions.authorizeReference(
2677
+ { user, referenceId, referenceType, action },
2678
+ ctx
2679
+ );
2680
+ if (!authorized) {
2681
+ throw new api.APIError("FORBIDDEN", {
2682
+ code: $ERROR_CODES.SUBSCRIPTION_REFERENCE_NOT_AUTHORIZED.code,
2683
+ message: "Not authorized for this subscription reference."
2684
+ });
2685
+ }
2686
+ }
2687
+ function getAdapter2(ctx) {
2688
+ const adapter = ctx.context.adapter;
2689
+ if (!adapter) {
2690
+ throw new api.APIError("INTERNAL_SERVER_ERROR", {
2691
+ message: "Better Auth adapter is not available on the request context."
2692
+ });
2693
+ }
2694
+ return adapter;
2695
+ }
2696
+ async function findOwnedSubscription(ctx, user, subscriptionId, subsOptions, action) {
2697
+ const adapter = getAdapter2(ctx);
2698
+ const localRow = await adapter.findOne({
2699
+ model: SUBSCRIPTION_MODEL3,
2700
+ where: [{ field: "id", value: subscriptionId }]
2701
+ });
2702
+ const row = localRow ?? await adapter.findOne({
2703
+ model: SUBSCRIPTION_MODEL3,
2704
+ where: [{ field: "streampaySubscriptionId", value: subscriptionId }]
2705
+ });
2706
+ if (!row) {
2707
+ throw new api.APIError("NOT_FOUND", {
2708
+ code: $ERROR_CODES.SUBSCRIPTION_NOT_FOUND.code,
2709
+ message: "Subscription not found."
2710
+ });
2711
+ }
2712
+ await authorizeReference(
2713
+ ctx,
2714
+ user,
2715
+ row.referenceId,
2716
+ row.referenceType ?? "user",
2717
+ action,
2718
+ subsOptions
2719
+ );
2720
+ return row;
2721
+ }
2722
+ async function requireConfirmedOwnedSubscription(ctx, subscriptionId, subsOptions, action) {
2723
+ const user = requireUser(ctx);
2724
+ const adapter = getAdapter2(ctx);
2725
+ const row = await findOwnedSubscription(ctx, user, subscriptionId, subsOptions, action);
2726
+ if (!row.streampaySubscriptionId) {
2727
+ throw new api.APIError("BAD_REQUEST", {
2728
+ code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
2729
+ message: "Subscription has not been confirmed by StreamPay yet."
2730
+ });
2731
+ }
2732
+ return {
2733
+ adapter,
2734
+ row,
2735
+ streampaySubscriptionId: row.streampaySubscriptionId
2736
+ };
2737
+ }
2738
+ var SUBSCRIPTION_MODEL4 = "subscription";
2739
+ async function recoverCheckoutUrl(client, row) {
2740
+ if (!row.streampayPaymentLinkId) return { kind: "expired" };
2741
+ try {
2742
+ const url = client.getPaymentUrl(await client.getPaymentLink(row.streampayPaymentLinkId));
2743
+ return url ? { kind: "recovered", url } : { kind: "expired" };
2744
+ } catch (err) {
2745
+ if (readSdkErrorFields(err).status === 404) return { kind: "expired" };
2746
+ throw err;
2747
+ }
2748
+ }
2749
+ async function deleteReservedSubscription(adapter, rowId, log, reason) {
2750
+ try {
2751
+ await adapter.delete({
2752
+ model: SUBSCRIPTION_MODEL4,
2753
+ where: [{ field: "id", value: rowId }]
2754
+ });
2755
+ } catch (err) {
2756
+ const message = err instanceof Error ? err.message : String(err);
2757
+ log.error(`${reason}: failed to release reserved subscription row=${rowId}: ${message}`);
2758
+ }
2759
+ }
2760
+ function checkoutInProgressError() {
2761
+ return new api.APIError("CONFLICT", {
2762
+ code: $ERROR_CODES.SUBSCRIPTION_CHECKOUT_IN_PROGRESS.code,
2763
+ message: "A subscription checkout is already being created for this plan group."
2764
+ });
2765
+ }
2766
+ async function resumeOrReserveCheckoutSlot(args) {
2767
+ const { client, adapter, candidates, activeSlotKey, planName, now, log } = args;
2768
+ const reuseCandidate = candidates.find(
2769
+ (row2) => row2.plan === planName && row2.status === "incomplete" && Boolean(row2.streampayPaymentLinkId) && row2.createdAt instanceof Date && now - row2.createdAt.getTime() < UPGRADE_IDEMPOTENCY_WINDOW_MS
2770
+ );
2771
+ if (reuseCandidate) {
2772
+ let recovery;
2773
+ try {
2774
+ recovery = await recoverCheckoutUrl(client, reuseCandidate);
2775
+ } catch (err) {
2776
+ toAPIError(
2777
+ {
2778
+ logPrefix: `resume subscription checkout failed for row=${reuseCandidate.id}:`,
2779
+ userMessage: "Unable to resume subscription checkout."
2780
+ },
2781
+ err,
2782
+ log
2783
+ );
2784
+ }
2785
+ if (recovery.kind === "recovered") {
2786
+ return { kind: "recovered", row: reuseCandidate, url: recovery.url };
2787
+ }
2788
+ await adapter.update({
2789
+ model: SUBSCRIPTION_MODEL4,
2790
+ update: { status: "incomplete_expired", activeSlotKey: null, updatedAt: /* @__PURE__ */ new Date() },
2791
+ where: [{ field: "id", value: reuseCandidate.id }]
2792
+ });
2793
+ }
2794
+ const { data: reservationData, consumerId } = await args.createReservation();
2795
+ let row;
2796
+ try {
2797
+ row = await adapter.create({
2798
+ model: SUBSCRIPTION_MODEL4,
2799
+ data: reservationData
2800
+ });
2801
+ } catch (err) {
2802
+ if (!isUniqueConstraintError(err)) throw err;
2803
+ const reserved = await adapter.findOne({
2804
+ model: SUBSCRIPTION_MODEL4,
2805
+ where: [{ field: "activeSlotKey", value: activeSlotKey }]
2806
+ });
2807
+ if (reserved?.status !== "incomplete") throw err;
2808
+ let recovery;
2809
+ try {
2810
+ recovery = await recoverCheckoutUrl(client, reserved);
2811
+ } catch (recoveryError) {
2812
+ toAPIError(
2813
+ {
2814
+ logPrefix: `resume concurrent subscription checkout failed for row=${reserved.id}:`,
2815
+ userMessage: "Unable to resume subscription checkout."
2816
+ },
2817
+ recoveryError,
2818
+ log
2819
+ );
2820
+ }
2821
+ if (recovery.kind === "recovered") {
2822
+ return { kind: "recovered", row: reserved, url: recovery.url };
2823
+ }
2824
+ const reservationIsStale = !(reserved.createdAt instanceof Date) || now - reserved.createdAt.getTime() >= UPGRADE_IDEMPOTENCY_WINDOW_MS;
2825
+ if (!reservationIsStale) throw checkoutInProgressError();
2826
+ const released = await adapter.update({
2827
+ model: SUBSCRIPTION_MODEL4,
2828
+ update: { status: "incomplete_expired", activeSlotKey: null, updatedAt: /* @__PURE__ */ new Date() },
2829
+ where: [
2830
+ { field: "id", value: reserved.id },
2831
+ { field: "activeSlotKey", value: activeSlotKey }
2832
+ ]
2833
+ });
2834
+ if (!released) throw checkoutInProgressError();
2835
+ try {
2836
+ row = await adapter.create({
2837
+ model: SUBSCRIPTION_MODEL4,
2838
+ data: reservationData
2839
+ });
2840
+ } catch (retryError) {
2841
+ if (!isUniqueConstraintError(retryError)) throw retryError;
2842
+ throw checkoutInProgressError();
2843
+ }
2844
+ log.warn(`released stale checkout reservation row=${reserved.id} for plan=${planName}.`);
2845
+ }
2846
+ return { kind: "reserved", row, consumerId };
2847
+ }
2848
+
2849
+ // src/plugins/subscriptions/lifecycle.ts
2850
+ function isAlreadyCanceledFreezeError(err) {
2851
+ const sdkError = readSdkErrorFields(err);
2852
+ const envelope = readEnvelope(sdkError.body);
2853
+ return sdkError.status === 403 && envelope?.code === "STREAM_ERROR" && envelope.additionalInfo === "Cannot delete non-latest freeze entry.";
2854
+ }
2855
+ function subscriptionCouponIds(stream) {
2856
+ const coupons = [];
2857
+ for (const coupon of stream.coupon_calculation_metadata?.coupons ?? []) {
2858
+ if (coupon.coupon_id) coupons.push(coupon.coupon_id);
2859
+ }
2860
+ return coupons;
2861
+ }
2862
+ function configuredPlanForSubscription(subscription, plans) {
2863
+ return plans.list.find(
2864
+ (plan) => subscription.items?.some((item) => subscriptionItemProductId(item) === plan.productId)
2865
+ );
2866
+ }
2867
+ var SUBSCRIPTION_INTERVALS = ["WEEK", "MONTH", "QUARTER", "YEAR"];
2086
2868
  var PlanSchema = zod.z.object({
2087
2869
  name: zod.z.string().min(1, "every plan must have a non-empty `name`."),
2088
2870
  productId: zod.z.string().min(1, "missing a non-empty `productId`."),
2089
- priceHalalat: zod.z.number({ error: "must have a non-negative numeric `priceHalalat`." }).refine((n) => Number.isFinite(n) && n >= 0, {
2090
- message: "must have a non-negative numeric `priceHalalat`."
2091
- }),
2092
- billingInterval: zod.z.enum(["WEEK", "MONTH", "QUARTER", "YEAR"], {
2093
- error: () => "has invalid `billingInterval`. Expected one of: WEEK, MONTH, QUARTER, YEAR."
2094
- }),
2871
+ priceInSmallestUnit: zod.z.custom(
2872
+ (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0,
2873
+ "must have a non-negative safe-integer `priceInSmallestUnit`."
2874
+ ),
2875
+ currency: zod.z.enum(["SAR", "USD", "EUR", "GBP", "AED", "BHD", "KWD", "OMR", "QAR"]).optional(),
2876
+ version: zod.z.string().min(1, "has an empty `version`.").optional(),
2877
+ billingInterval: zod.z.custom(
2878
+ (value) => typeof value === "string" && SUBSCRIPTION_INTERVALS.some((interval) => interval === value),
2879
+ "has invalid `billingInterval`. Expected one of: WEEK, MONTH, QUARTER, YEAR."
2880
+ ),
2095
2881
  billingIntervalCount: zod.z.number().refine((n) => Number.isInteger(n) && n >= 1, {
2096
2882
  message: "has invalid `billingIntervalCount` \u2014 must be a positive integer."
2097
2883
  }).optional(),
2098
- group: zod.z.string().optional(),
2884
+ trialPeriodDays: zod.z.number().refine((n) => Number.isInteger(n) && n >= 1 && n <= 365, {
2885
+ message: "has invalid `trialPeriodDays` \u2014 must be an integer from 1 to 365."
2886
+ }).optional(),
2887
+ group: zod.z.string().min(1, "has an empty `group`.").optional(),
2099
2888
  limits: zod.z.record(zod.z.string(), zod.z.unknown()).optional()
2100
2889
  });
2101
2890
  var PlansSchema = zod.z.array(PlanSchema).nonempty("`plans` resolved to an empty list. Provide at least one plan.").superRefine((plans, ctx) => {
2102
- const seen = /* @__PURE__ */ new Set();
2891
+ const seenNames = /* @__PURE__ */ new Set();
2892
+ const seenProductIds = /* @__PURE__ */ new Set();
2103
2893
  for (const [index, plan] of plans.entries()) {
2104
- if (seen.has(plan.name)) {
2894
+ if (seenNames.has(plan.name)) {
2105
2895
  ctx.addIssue({
2106
2896
  code: "custom",
2107
2897
  path: [index, "name"],
2108
2898
  message: `duplicate plan name "${plan.name}" \u2014 plan names must be unique.`
2109
2899
  });
2110
2900
  }
2111
- seen.add(plan.name);
2901
+ seenNames.add(plan.name);
2902
+ if (seenProductIds.has(plan.productId)) {
2903
+ ctx.addIssue({
2904
+ code: "custom",
2905
+ path: [index, "productId"],
2906
+ message: `duplicate productId "${plan.productId}" \u2014 webhook plan inference requires unique product IDs.`
2907
+ });
2908
+ }
2909
+ seenProductIds.add(plan.productId);
2112
2910
  }
2113
2911
  });
2114
2912
  function validatePlansShape(plans) {
@@ -2146,16 +2944,19 @@ function createPlanResolver(plans) {
2146
2944
  }
2147
2945
  };
2148
2946
  }
2149
- function hasFeature(subscription, plan, feature) {
2947
+ function hasSubscriptionAccess(subscription, accessStatuses = DEFAULT_ACCESS_STATUSES) {
2948
+ return accessStatuses.includes(subscription.status);
2949
+ }
2950
+ function hasFeature(subscription, plan, feature, accessStatuses = DEFAULT_ACCESS_STATUSES) {
2150
2951
  if (!plan?.limits) return false;
2151
- if (subscription.status !== "active" && subscription.status !== "frozen") return false;
2952
+ if (!hasSubscriptionAccess(subscription, accessStatuses)) return false;
2152
2953
  const value = plan.limits[feature];
2153
2954
  if (typeof value === "boolean") return value;
2154
2955
  if (typeof value === "number") return value > 0;
2155
2956
  return Boolean(value);
2156
2957
  }
2157
- function checkLimit(subscription, plan, feature, requested) {
2158
- if (!plan?.limits || subscription.status !== "active" && subscription.status !== "frozen") {
2958
+ function checkLimit(subscription, plan, feature, requested, accessStatuses = DEFAULT_ACCESS_STATUSES) {
2959
+ if (!plan?.limits || !hasSubscriptionAccess(subscription, accessStatuses)) {
2159
2960
  return { allowed: false, limit: 0, remaining: 0 };
2160
2961
  }
2161
2962
  const raw = plan.limits[feature];
@@ -2166,121 +2967,194 @@ function checkLimit(subscription, plan, feature, requested) {
2166
2967
  return { allowed, limit, remaining };
2167
2968
  }
2168
2969
 
2169
- // src/plugins/subscriptions/endpoints.ts
2170
- var SUBSCRIPTION_MODEL2 = "subscription";
2171
- var UpgradeBody = zod.z.object({
2172
- plan: zod.z.string().min(1),
2970
+ // src/plugins/subscriptions/reads.ts
2971
+ var SUBSCRIPTION_MODEL5 = "subscription";
2972
+ var ReferenceQueryFields = {
2173
2973
  referenceId: zod.z.string().min(1).optional(),
2174
- successUrl: zod.z.string().url().optional(),
2175
- failureUrl: zod.z.string().url().optional()
2176
- });
2177
- var SuccessQuery = zod.z.object({
2178
- subscriptionId: zod.z.string().uuid(),
2179
- callbackURL: zod.z.string().url().optional()
2180
- });
2181
- var CancelBody = zod.z.object({
2182
- subscriptionId: zod.z.string().uuid(),
2183
- cancelRelatedInvoices: zod.z.boolean().optional(),
2184
- cancelAtPeriodEnd: zod.z.boolean().optional()
2185
- });
2186
- var ChangePlanBody = zod.z.object({
2187
- plan: zod.z.string().min(1),
2188
- mode: zod.z.enum(["at_period_end", "immediate"]).optional(),
2189
- successUrl: zod.z.string().url().optional(),
2190
- failureUrl: zod.z.string().url().optional()
2191
- });
2192
- var FreezeBody = zod.z.object({
2193
- subscriptionId: zod.z.string().uuid(),
2194
- freezeStartDatetime: zod.z.string().datetime(),
2195
- freezeEndDatetime: zod.z.string().datetime().nullable().optional(),
2196
- notes: zod.z.string().optional()
2197
- });
2198
- var UnfreezeBody = zod.z.object({
2199
- subscriptionId: zod.z.string().uuid()
2200
- });
2974
+ referenceType: zod.z.enum(["user", "organization", "custom"]).optional()
2975
+ };
2976
+ var ListQuery = zod.z.object(ReferenceQueryFields).optional();
2201
2977
  var CurrentQuery = zod.z.object({
2978
+ ...ReferenceQueryFields,
2202
2979
  group: zod.z.string().min(1).optional()
2203
2980
  }).optional();
2204
2981
  var HasFeatureQuery = zod.z.object({
2982
+ ...ReferenceQueryFields,
2205
2983
  feature: zod.z.string().min(1),
2206
2984
  group: zod.z.string().min(1).optional()
2207
2985
  });
2208
2986
  var CheckLimitQuery = zod.z.object({
2987
+ ...ReferenceQueryFields,
2209
2988
  feature: zod.z.string().min(1),
2210
2989
  count: zod.z.coerce.number().int().min(0),
2211
2990
  group: zod.z.string().min(1).optional()
2212
2991
  });
2213
- function requireUser(ctx) {
2214
- const user = asSessionUser(ctx.context.session?.user);
2215
- if (!user) {
2216
- throw new api.APIError("UNAUTHORIZED", {
2217
- message: "Subscription endpoints require an authenticated session."
2218
- });
2219
- }
2220
- if (user.isAnonymous) {
2221
- throw new api.APIError("UNAUTHORIZED", {
2222
- message: "Anonymous users cannot manage subscriptions."
2223
- });
2224
- }
2225
- return user;
2226
- }
2227
- async function authorizeReference(ctx, user, referenceId, action, subsOptions) {
2228
- if (referenceId === user.id) return;
2229
- if (!subsOptions.authorizeReference) {
2230
- throw new api.APIError("FORBIDDEN", {
2231
- code: $ERROR_CODES.FORBIDDEN.code,
2232
- message: "Cross-account subscription actions require an `authorizeReference` callback."
2233
- });
2234
- }
2235
- const ok = await subsOptions.authorizeReference({ user, referenceId, action }, ctx);
2236
- if (!ok) {
2237
- throw new api.APIError("FORBIDDEN", {
2238
- code: "SUBSCRIPTION_REFERENCE_NOT_AUTHORIZED",
2239
- message: "Not authorized for this subscription reference."
2240
- });
2241
- }
2242
- }
2243
- function getAdapter2(ctx) {
2244
- const adapter = ctx.context.adapter;
2245
- if (!adapter) {
2246
- throw new api.APIError("INTERNAL_SERVER_ERROR", {
2247
- message: "Better Auth adapter is not available on the request context."
2248
- });
2249
- }
2250
- return adapter;
2992
+ async function resolveLiveSubscription(ctx, query, subsOptions, accessStatuses) {
2993
+ const user = requireUser(ctx);
2994
+ const reference = resolveReference(user, query);
2995
+ await authorizeReference(
2996
+ ctx,
2997
+ user,
2998
+ reference.referenceId,
2999
+ reference.referenceType,
3000
+ "read",
3001
+ subsOptions
3002
+ );
3003
+ const rows = await getAdapter2(ctx).findMany({
3004
+ model: SUBSCRIPTION_MODEL5,
3005
+ where: [
3006
+ { field: "referenceId", value: reference.referenceId },
3007
+ { field: "referenceType", value: reference.referenceType },
3008
+ { field: "group", value: query.group ?? null }
3009
+ ]
3010
+ });
3011
+ return rows.find((row) => hasSubscriptionAccess(row, accessStatuses)) ?? null;
2251
3012
  }
2252
- function echoSubscriptionPatch(stream) {
2253
- const items = [];
2254
- for (const item of stream.items ?? []) {
2255
- const productId = item.product?.id;
2256
- const quantity = item.quantity;
2257
- if (!productId || quantity === void 0) continue;
2258
- items.push({ product_id: productId, quantity });
2259
- }
2260
- const coupons = [];
2261
- for (const c of stream.coupon_calculation_metadata?.coupons ?? []) {
2262
- if (c.coupon_id) coupons.push(c.coupon_id);
2263
- }
2264
- return { items, coupons };
3013
+ function buildSubscriptionReadEndpoints(subsOptions, plansRef) {
3014
+ const accessStatuses = subsOptions.accessStatuses ?? DEFAULT_ACCESS_STATUSES;
3015
+ return {
3016
+ listSubscriptions: api.createAuthEndpoint(
3017
+ "/subscription/list",
3018
+ {
3019
+ method: "GET",
3020
+ query: ListQuery,
3021
+ use: [api.sessionMiddleware]
3022
+ },
3023
+ async (ctx) => {
3024
+ const user = requireUser(ctx);
3025
+ const reference = resolveReference(user, ctx.query);
3026
+ await authorizeReference(
3027
+ ctx,
3028
+ user,
3029
+ reference.referenceId,
3030
+ reference.referenceType,
3031
+ "read",
3032
+ subsOptions
3033
+ );
3034
+ const rows = await getAdapter2(ctx).findMany({
3035
+ model: SUBSCRIPTION_MODEL5,
3036
+ where: [
3037
+ { field: "referenceId", value: reference.referenceId },
3038
+ { field: "referenceType", value: reference.referenceType }
3039
+ ]
3040
+ });
3041
+ const plans = await plansRef();
3042
+ return ctx.json(
3043
+ rows.map((row) => ({
3044
+ ...row,
3045
+ plan: plans.byName.get(row.plan) ?? null
3046
+ }))
3047
+ );
3048
+ }
3049
+ ),
3050
+ currentSubscription: api.createAuthEndpoint(
3051
+ "/subscription/current",
3052
+ {
3053
+ method: "GET",
3054
+ query: CurrentQuery,
3055
+ use: [api.sessionMiddleware]
3056
+ },
3057
+ async (ctx) => {
3058
+ const live = await resolveLiveSubscription(
3059
+ ctx,
3060
+ ctx.query ?? {},
3061
+ subsOptions,
3062
+ accessStatuses
3063
+ );
3064
+ if (!live) return ctx.json(null);
3065
+ const plans = await plansRef();
3066
+ return ctx.json({ ...live, plan: plans.byName.get(live.plan) ?? null });
3067
+ }
3068
+ ),
3069
+ hasSubscriptionFeature: api.createAuthEndpoint(
3070
+ "/subscription/has-feature",
3071
+ {
3072
+ method: "GET",
3073
+ query: HasFeatureQuery,
3074
+ use: [api.sessionMiddleware]
3075
+ },
3076
+ async (ctx) => {
3077
+ const live = await resolveLiveSubscription(ctx, ctx.query, subsOptions, accessStatuses);
3078
+ if (!live) return ctx.json({ hasFeature: false });
3079
+ const plan = (await plansRef()).byName.get(live.plan);
3080
+ return ctx.json({
3081
+ hasFeature: hasFeature(live, plan, ctx.query.feature, accessStatuses)
3082
+ });
3083
+ }
3084
+ ),
3085
+ checkSubscriptionLimit: api.createAuthEndpoint(
3086
+ "/subscription/check-limit",
3087
+ {
3088
+ method: "GET",
3089
+ query: CheckLimitQuery,
3090
+ use: [api.sessionMiddleware]
3091
+ },
3092
+ async (ctx) => {
3093
+ const live = await resolveLiveSubscription(ctx, ctx.query, subsOptions, accessStatuses);
3094
+ if (!live) return ctx.json({ allowed: false, limit: 0, remaining: 0 });
3095
+ const plan = (await plansRef()).byName.get(live.plan);
3096
+ return ctx.json(checkLimit(live, plan, ctx.query.feature, ctx.query.count, accessStatuses));
3097
+ }
3098
+ )
3099
+ };
2265
3100
  }
2266
- async function findOwnedSubscription(ctx, user, streampaySubscriptionId, subsOptions, action) {
2267
- const adapter = getAdapter2(ctx);
2268
- const row = await adapter.findOne({
2269
- model: SUBSCRIPTION_MODEL2,
2270
- where: [{ field: "streampaySubscriptionId", value: streampaySubscriptionId }]
2271
- });
2272
- if (!row) {
2273
- throw new api.APIError("NOT_FOUND", {
2274
- code: "SUBSCRIPTION_NOT_FOUND",
2275
- message: "Subscription not found."
2276
- });
3101
+
3102
+ // src/plugins/subscriptions/endpoints.ts
3103
+ var SUBSCRIPTION_MODEL6 = "subscription";
3104
+ var UpgradeBody = zod.z.object({
3105
+ plan: zod.z.string().min(1),
3106
+ referenceId: zod.z.string().min(1).optional(),
3107
+ referenceType: zod.z.enum(["user", "organization", "custom"]).optional(),
3108
+ successUrl: zod.z.string().url().optional(),
3109
+ failureUrl: zod.z.string().url().optional()
3110
+ });
3111
+ var SuccessQuery = zod.z.object({
3112
+ subscriptionId: zod.z.string().min(1)
3113
+ });
3114
+ var CancelBody = zod.z.object({
3115
+ subscriptionId: zod.z.string().min(1),
3116
+ cancelRelatedInvoices: zod.z.boolean().optional(),
3117
+ cancelAtPeriodEnd: zod.z.boolean().optional()
3118
+ });
3119
+ var ChangePlanBody = zod.z.object({
3120
+ subscriptionId: zod.z.string().min(1),
3121
+ plan: zod.z.string().min(1)
3122
+ }).strict();
3123
+ var FreezeBody = zod.z.object({
3124
+ subscriptionId: zod.z.string().min(1),
3125
+ freezeStartDatetime: zod.z.string().datetime(),
3126
+ freezeEndDatetime: zod.z.string().datetime().nullable().optional(),
3127
+ notes: zod.z.string().optional()
3128
+ });
3129
+ var UnfreezeBody = zod.z.object({
3130
+ subscriptionId: zod.z.string().min(1)
3131
+ });
3132
+ var CancelFreezeBody = zod.z.object({
3133
+ subscriptionId: zod.z.string().min(1),
3134
+ freezeId: zod.z.string().min(1)
3135
+ });
3136
+ var SUCCESS_RECONCILIATION_CLOCK_SKEW_MS = 5 * 60 * 1e3;
3137
+ function isCheckoutSubscriptionCandidate(subscription, row, productId) {
3138
+ if (subscription.organization_consumer_id !== row.streampayConsumerId) return false;
3139
+ if (!isCheckoutSuccessStatus(subscription.status)) return false;
3140
+ if (!subscription.items?.some((item) => subscriptionItemProductId(item) === productId)) {
3141
+ return false;
2277
3142
  }
2278
- await authorizeReference(ctx, user, row.referenceId, action, subsOptions);
2279
- return row;
3143
+ const upstreamPaymentLinkId = subscription.latest_invoice?.payment_link_id;
3144
+ if (row.streampayPaymentLinkId && upstreamPaymentLinkId && upstreamPaymentLinkId !== row.streampayPaymentLinkId) {
3145
+ return false;
3146
+ }
3147
+ if (row.streampayPaymentLinkId && upstreamPaymentLinkId === row.streampayPaymentLinkId) {
3148
+ return true;
3149
+ }
3150
+ if (!subscription.created_at || !(row.createdAt instanceof Date)) return false;
3151
+ const createdAt = new Date(subscription.created_at).getTime();
3152
+ return Number.isFinite(createdAt) && createdAt >= row.createdAt.getTime() - SUCCESS_RECONCILIATION_CLOCK_SKEW_MS;
2280
3153
  }
2281
3154
  function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2282
3155
  const client = options.client;
2283
3156
  return {
3157
+ ...buildSubscriptionReadEndpoints(subsOptions, plansRef),
2284
3158
  upgradeSubscription: api.createAuthEndpoint(
2285
3159
  "/subscription/upgrade",
2286
3160
  {
@@ -2291,58 +3165,134 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2291
3165
  async (ctx) => {
2292
3166
  const user = requireUser(ctx);
2293
3167
  const referenceId = ctx.body.referenceId ?? user.id;
2294
- await authorizeReference(ctx, user, referenceId, "upgrade", subsOptions);
3168
+ const referenceType = ctx.body.referenceType ?? (referenceId === user.id ? "user" : "custom");
3169
+ await authorizeReference(ctx, user, referenceId, referenceType, "upgrade", subsOptions);
2295
3170
  const plans = await plansRef();
2296
3171
  const plan = plans.byName.get(ctx.body.plan);
2297
3172
  if (!plan) {
2298
3173
  throw new api.APIError("NOT_FOUND", {
2299
- code: "SUBSCRIPTION_PLAN_NOT_FOUND",
3174
+ code: $ERROR_CODES.SUBSCRIPTION_PLAN_NOT_FOUND.code,
2300
3175
  message: `Plan "${ctx.body.plan}" is not configured.`
2301
3176
  });
2302
3177
  }
2303
3178
  const adapter = getAdapter2(ctx);
2304
3179
  const existingActive = await adapter.findMany({
2305
- model: SUBSCRIPTION_MODEL2,
3180
+ model: SUBSCRIPTION_MODEL6,
2306
3181
  where: [
2307
3182
  { field: "referenceId", value: referenceId },
2308
- ...plan.group ? [{ field: "group", value: plan.group }] : []
3183
+ { field: "referenceType", value: referenceType },
3184
+ { field: "group", value: plan.group ?? null }
2309
3185
  ]
2310
3186
  });
2311
- const liveActive = existingActive.find(
2312
- (row2) => row2.status === "active" || row2.status === "frozen" || row2.status === "past_due"
3187
+ const defaultTrialEligible = !existingActive.some(
3188
+ (row2) => row2.trialStart instanceof Date || row2.trialEnd instanceof Date || row2.status === "trial_pending" || row2.status === "trialing"
2313
3189
  );
3190
+ const trialEligible = plan.trialPeriodDays === void 0 ? false : subsOptions.isTrialEligible ? await subsOptions.isTrialEligible(
3191
+ {
3192
+ user,
3193
+ referenceId,
3194
+ referenceType,
3195
+ plan,
3196
+ previousSubscriptions: existingActive,
3197
+ defaultEligible: defaultTrialEligible
3198
+ },
3199
+ ctx
3200
+ ) : defaultTrialEligible;
3201
+ const liveActive = existingActive.find((row2) => isManageableSubscriptionStatus(row2.status));
2314
3202
  if (liveActive) {
2315
3203
  throw new api.APIError("CONFLICT", {
2316
- code: "SUBSCRIPTION_ALREADY_ACTIVE",
2317
- message: plan.group ? `An active subscription already exists in plan group "${plan.group}". Cancel it before upgrading.` : "An active subscription already exists. Cancel it before upgrading."
3204
+ code: $ERROR_CODES.SUBSCRIPTION_ALREADY_ACTIVE.code,
3205
+ message: plan.group ? `An active subscription already exists in plan group "${plan.group}". Use the change-plan endpoint to move it.` : "An active subscription already exists. Use the change-plan endpoint to move it."
2318
3206
  });
2319
3207
  }
2320
- const now = Date.now();
2321
- const reuseCandidate = existingActive.find(
2322
- (row2) => row2.plan === plan.name && row2.status === "incomplete" && row2.createdAt instanceof Date && now - row2.createdAt.getTime() < UPGRADE_IDEMPOTENCY_WINDOW_MS
2323
- );
2324
- if (reuseCandidate) {
3208
+ const activeSlotKey = subscriptionSlotKey(referenceType, referenceId, plan.group);
3209
+ const reservation = await resumeOrReserveCheckoutSlot({
3210
+ client,
3211
+ adapter,
3212
+ candidates: existingActive,
3213
+ activeSlotKey,
3214
+ planName: plan.name,
3215
+ now: Date.now(),
3216
+ log: getLogger(ctx),
3217
+ createReservation: async () => {
3218
+ const { consumerId: consumerId2 } = await ensureConsumerForUser(
3219
+ options,
3220
+ { context: ctx.context },
3221
+ user
3222
+ );
3223
+ return {
3224
+ consumerId: consumerId2,
3225
+ data: {
3226
+ referenceId,
3227
+ referenceType,
3228
+ activeSlotKey,
3229
+ streampaySubscriptionId: null,
3230
+ plan: plan.name,
3231
+ planVersion: plan.version ?? null,
3232
+ productId: plan.productId,
3233
+ group: plan.group ?? null,
3234
+ streampayConsumerId: consumerId2,
3235
+ streampayPaymentLinkId: null,
3236
+ status: "incomplete",
3237
+ providerStatus: null,
3238
+ billingStatus: "current",
3239
+ amountInSmallestUnit: plan.priceInSmallestUnit,
3240
+ originalAmountInSmallestUnit: plan.priceInSmallestUnit,
3241
+ currency: plan.currency ?? "SAR",
3242
+ billingInterval: plan.billingInterval,
3243
+ billingIntervalCount: plan.billingIntervalCount ?? 1,
3244
+ periodStart: null,
3245
+ periodEnd: null,
3246
+ currentCycleNumber: null,
3247
+ trialStart: null,
3248
+ trialEnd: null,
3249
+ cancelAtPeriodEnd: false,
3250
+ cancelAt: null,
3251
+ cancelScheduledAt: null,
3252
+ canceledAt: null,
3253
+ pendingPlan: null,
3254
+ pendingProductId: null,
3255
+ pendingPlanEffectiveAt: null,
3256
+ endedAt: null,
3257
+ frozenAt: null,
3258
+ freezeEndAt: null,
3259
+ providerUpdatedAt: null,
3260
+ syncedAt: null,
3261
+ createdAt: /* @__PURE__ */ new Date(),
3262
+ updatedAt: /* @__PURE__ */ new Date()
3263
+ }
3264
+ };
3265
+ }
3266
+ });
3267
+ if (reservation.kind === "recovered") {
2325
3268
  return ctx.json({
2326
- subscriptionId: reuseCandidate.id,
3269
+ subscriptionId: reservation.row.id,
3270
+ url: reservation.url,
3271
+ redirect: true,
2327
3272
  reused: true,
2328
- status: reuseCandidate.status,
2329
- plan: reuseCandidate.plan
3273
+ status: reservation.row.status,
3274
+ plan: reservation.row.plan
2330
3275
  });
2331
3276
  }
2332
- const ensureCtx = { context: ctx.context };
2333
- const { consumerId } = await ensureConsumerForUser(options, ensureCtx, user);
3277
+ const { row, consumerId } = reservation;
2334
3278
  const linkInput = {
2335
3279
  name: `Subscription \u2014 ${plan.name}`,
3280
+ currency: plan.currency ?? "SAR",
2336
3281
  items: [{ product_id: plan.productId, quantity: 1, allow_custom_quantity: false }],
2337
3282
  max_number_of_payments: 1,
2338
3283
  organization_consumer_id: consumerId,
2339
3284
  custom_metadata: {
2340
3285
  [PLAN_NAME_METADATA_KEY]: plan.name,
2341
- [REFERENCE_ID_METADATA_KEY]: referenceId
3286
+ [REFERENCE_ID_METADATA_KEY]: referenceId,
3287
+ [REFERENCE_TYPE_METADATA_KEY]: referenceType,
3288
+ [SUBSCRIPTION_ROW_ID_METADATA_KEY]: row.id
2342
3289
  }
2343
3290
  };
2344
3291
  if (ctx.body.successUrl) linkInput.success_redirect_url = ctx.body.successUrl;
2345
3292
  if (ctx.body.failureUrl) linkInput.failure_redirect_url = ctx.body.failureUrl;
3293
+ if (plan.trialPeriodDays !== void 0 && trialEligible) {
3294
+ linkInput.trial_period_days = plan.trialPeriodDays;
3295
+ }
2346
3296
  let url;
2347
3297
  let paymentLinkId;
2348
3298
  try {
@@ -2355,6 +3305,12 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2355
3305
  paymentLinkId = link.id;
2356
3306
  url = client.getPaymentUrl(link);
2357
3307
  } catch (err) {
3308
+ await deleteReservedSubscription(
3309
+ adapter,
3310
+ row.id,
3311
+ getLogger(ctx),
3312
+ "createPaymentLink cleanup"
3313
+ );
2358
3314
  toAPIError(
2359
3315
  {
2360
3316
  logPrefix: `upgradeSubscription failed for plan=${plan.name} ref=${referenceId}:`,
@@ -2366,29 +3322,51 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2366
3322
  }
2367
3323
  if (!url) {
2368
3324
  getLogger(ctx).error(`createPaymentLink returned link=${paymentLinkId} with no url.`);
3325
+ try {
3326
+ await adapter.update({
3327
+ model: SUBSCRIPTION_MODEL6,
3328
+ update: {
3329
+ streampayPaymentLinkId: paymentLinkId,
3330
+ status: "incomplete_expired",
3331
+ activeSlotKey: null,
3332
+ updatedAt: /* @__PURE__ */ new Date()
3333
+ },
3334
+ where: [{ field: "id", value: row.id }]
3335
+ });
3336
+ } catch (persistenceError) {
3337
+ const message = persistenceError instanceof Error ? persistenceError.message : String(persistenceError);
3338
+ getLogger(ctx).error(
3339
+ `failed to mark unusable payment link=${paymentLinkId} expired for row=${row.id}: ${message}`
3340
+ );
3341
+ await deleteReservedSubscription(
3342
+ adapter,
3343
+ row.id,
3344
+ getLogger(ctx),
3345
+ "unusable payment link cleanup"
3346
+ );
3347
+ }
2369
3348
  throw new api.APIError("INTERNAL_SERVER_ERROR", {
2370
3349
  message: "Payment link was created but no URL was returned."
2371
3350
  });
2372
3351
  }
2373
- const row = await adapter.create({
2374
- model: SUBSCRIPTION_MODEL2,
2375
- data: {
2376
- referenceId,
2377
- plan: plan.name,
2378
- group: plan.group ?? null,
2379
- streampayConsumerId: consumerId,
2380
- status: "incomplete",
2381
- amountHalalat: plan.priceHalalat,
2382
- currency: "SAR",
2383
- billingInterval: plan.billingInterval,
2384
- billingIntervalCount: plan.billingIntervalCount ?? 1,
2385
- cancelAtPeriodEnd: false,
2386
- createdAt: /* @__PURE__ */ new Date(),
2387
- updatedAt: /* @__PURE__ */ new Date()
2388
- }
2389
- });
3352
+ let updatedRow = null;
3353
+ try {
3354
+ updatedRow = await adapter.update({
3355
+ model: SUBSCRIPTION_MODEL6,
3356
+ update: {
3357
+ streampayPaymentLinkId: paymentLinkId,
3358
+ updatedAt: /* @__PURE__ */ new Date()
3359
+ },
3360
+ where: [{ field: "id", value: row.id }]
3361
+ });
3362
+ } catch (persistenceError) {
3363
+ const message = persistenceError instanceof Error ? persistenceError.message : String(persistenceError);
3364
+ getLogger(ctx).error(
3365
+ `failed to persist payment link=${paymentLinkId} for row=${row.id}: ${message}. Protected checkout metadata will reconcile the row from the webhook.`
3366
+ );
3367
+ }
2390
3368
  return ctx.json({
2391
- subscriptionId: row.id,
3369
+ subscriptionId: updatedRow?.id ?? row.id,
2392
3370
  url,
2393
3371
  redirect: true,
2394
3372
  reused: false,
@@ -2408,16 +3386,23 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2408
3386
  const user = requireUser(ctx);
2409
3387
  const adapter = getAdapter2(ctx);
2410
3388
  const row = await adapter.findOne({
2411
- model: SUBSCRIPTION_MODEL2,
3389
+ model: SUBSCRIPTION_MODEL6,
2412
3390
  where: [{ field: "id", value: ctx.query.subscriptionId }]
2413
3391
  });
2414
3392
  if (!row) {
2415
3393
  throw new api.APIError("NOT_FOUND", {
2416
- code: "SUBSCRIPTION_NOT_FOUND",
3394
+ code: $ERROR_CODES.SUBSCRIPTION_NOT_FOUND.code,
2417
3395
  message: "Subscription not found."
2418
3396
  });
2419
3397
  }
2420
- await authorizeReference(ctx, user, row.referenceId, "read", subsOptions);
3398
+ await authorizeReference(
3399
+ ctx,
3400
+ user,
3401
+ row.referenceId,
3402
+ row.referenceType ?? "user",
3403
+ "read",
3404
+ subsOptions
3405
+ );
2421
3406
  if (row.status !== "incomplete") {
2422
3407
  return ctx.json({
2423
3408
  subscription: row,
@@ -2436,28 +3421,31 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2436
3421
  );
2437
3422
  return ctx.json({ subscription: row, synced: false });
2438
3423
  }
2439
- const list = await client.listSubscriptions({ page: 1, size: 100 });
2440
- const match = list.data?.find(
2441
- (sub) => sub.organization_consumer_id === row.streampayConsumerId && sub.status !== "CANCELED" && Array.isArray(sub.items) && sub.items.some((item) => subscriptionItemProductId(item) === plan.productId)
2442
- );
3424
+ let page = 1;
3425
+ let match;
3426
+ do {
3427
+ const list = await client.listSubscriptions({
3428
+ page,
3429
+ size: 100,
3430
+ organization_consumer_id: row.streampayConsumerId
3431
+ });
3432
+ match = list.data?.find(
3433
+ (sub) => isCheckoutSubscriptionCandidate(sub, row, plan.productId)
3434
+ );
3435
+ if (match || !list.pagination?.has_next_page) break;
3436
+ page += 1;
3437
+ } while (page <= 1e3);
2443
3438
  if (!match?.id) {
2444
3439
  return ctx.json({ subscription: row, synced: false });
2445
3440
  }
2446
3441
  const updated = await adapter.update({
2447
- model: SUBSCRIPTION_MODEL2,
3442
+ model: SUBSCRIPTION_MODEL6,
2448
3443
  update: {
2449
- streampaySubscriptionId: match.id,
2450
- status: match.status === "ACTIVE" ? "active" : "incomplete",
2451
- periodStart: match.current_period_start ? new Date(match.current_period_start) : null,
2452
- periodEnd: match.current_period_end ? new Date(match.current_period_end) : null,
2453
- amountHalalat: (() => {
2454
- if (!match.amount) return row.amountHalalat;
2455
- try {
2456
- return StreamPayAmount.toHalalat(match.amount);
2457
- } catch {
2458
- return row.amountHalalat;
2459
- }
2460
- })(),
3444
+ ...projectSubscriptionFields(match),
3445
+ planVersion: plan.version ?? null,
3446
+ productId: plan.productId,
3447
+ billingStatus: "current",
3448
+ activeSlotKey: row.activeSlotKey ?? subscriptionSlotKey(row.referenceType ?? "user", row.referenceId, row.group),
2461
3449
  updatedAt: /* @__PURE__ */ new Date()
2462
3450
  },
2463
3451
  where: [{ field: "id", value: row.id }]
@@ -2480,72 +3468,53 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2480
3468
  use: [api.sessionMiddleware]
2481
3469
  },
2482
3470
  async (ctx) => {
2483
- const user = requireUser(ctx);
2484
- const adapter = getAdapter2(ctx);
2485
- const row = await findOwnedSubscription(
3471
+ const { adapter, row } = await requireConfirmedOwnedSubscription(
2486
3472
  ctx,
2487
- user,
2488
3473
  ctx.body.subscriptionId,
2489
3474
  subsOptions,
2490
3475
  "cancel"
2491
3476
  );
2492
- if (row.status === "canceled") {
2493
- throw new api.APIError("BAD_REQUEST", {
2494
- code: "SUBSCRIPTION_ALREADY_CANCELED",
2495
- message: "Subscription is already canceled."
2496
- });
2497
- }
2498
- if (row.cancelAtPeriodEnd) {
2499
- throw new api.APIError("BAD_REQUEST", {
2500
- code: "SUBSCRIPTION_ALREADY_SCHEDULED_CANCEL",
2501
- message: "Subscription is already scheduled to cancel at period end."
2502
- });
2503
- }
2504
- if (!row.streampaySubscriptionId) {
2505
- throw new api.APIError("BAD_REQUEST", {
2506
- code: "SUBSCRIPTION_INVALID_STATE",
2507
- message: "Subscription has not been confirmed by StreamPay yet."
2508
- });
2509
- }
2510
- if (ctx.body.cancelAtPeriodEnd) {
2511
- try {
2512
- const stream = await client.getSubscription(row.streampaySubscriptionId);
2513
- const patch = {
2514
- ...echoSubscriptionPatch(stream),
2515
- until_cycle_number: stream.current_cycle_number ?? 1
2516
- };
2517
- const result = await client.updateSubscription(row.streampaySubscriptionId, patch);
2518
- await adapter.update({
2519
- model: SUBSCRIPTION_MODEL2,
2520
- update: {
2521
- cancelAtPeriodEnd: true,
2522
- updatedAt: /* @__PURE__ */ new Date()
2523
- },
2524
- where: [{ field: "id", value: row.id }]
2525
- });
2526
- return ctx.json(result);
2527
- } catch (err) {
2528
- toAPIError(
2529
- {
2530
- logPrefix: `cancelAtPeriodEnd failed for row=${row.id}:`,
2531
- userMessage: "Subscription cancel-at-period-end failed."
2532
- },
2533
- err,
2534
- getLogger(ctx)
2535
- );
2536
- }
2537
- }
2538
3477
  const payload = {
2539
3478
  cancel_related_invoices: ctx.body.cancelRelatedInvoices ?? false
2540
3479
  };
2541
3480
  try {
3481
+ const stream = await client.getSubscription(row.streampaySubscriptionId);
3482
+ if (stream.status === "CANCELED") {
3483
+ await adapter.update({
3484
+ model: SUBSCRIPTION_MODEL6,
3485
+ update: projectSubscriptionAgainstExisting(row, stream),
3486
+ where: [{ field: "id", value: row.id }]
3487
+ });
3488
+ return ctx.json(stream);
3489
+ }
3490
+ if (ctx.body.cancelAtPeriodEnd === false && stream.status === "ACTIVE") {
3491
+ throw new api.APIError("BAD_REQUEST", {
3492
+ code: $ERROR_CODES.SUBSCRIPTION_IMMEDIATE_CANCEL_UNSUPPORTED.code,
3493
+ message: "StreamPay cancels active subscriptions at period end. Immediate cancellation is only available for inactive or trial subscriptions."
3494
+ });
3495
+ }
3496
+ if (stream.cancel_at_period_end && !ctx.body.cancelRelatedInvoices) {
3497
+ await adapter.update({
3498
+ model: SUBSCRIPTION_MODEL6,
3499
+ update: projectSubscriptionAgainstExisting(row, stream),
3500
+ where: [{ field: "id", value: row.id }]
3501
+ });
3502
+ return ctx.json(stream);
3503
+ }
3504
+ if (ctx.body.cancelAtPeriodEnd === true && stream.status !== "ACTIVE") {
3505
+ throw new api.APIError("BAD_REQUEST", {
3506
+ code: $ERROR_CODES.SUBSCRIPTION_PERIOD_END_CANCEL_UNSUPPORTED.code,
3507
+ message: "StreamPay only schedules period-end cancellation for active subscriptions. This subscription would be canceled immediately."
3508
+ });
3509
+ }
2542
3510
  const result = await client.cancelSubscription(row.streampaySubscriptionId, payload);
2543
3511
  await syncSubscriptionFromUpstream(
2544
3512
  client,
2545
3513
  adapter,
2546
3514
  row.streampaySubscriptionId,
2547
3515
  getLogger(ctx),
2548
- "cancelSubscription"
3516
+ "cancelSubscription",
3517
+ result
2549
3518
  );
2550
3519
  return ctx.json(result);
2551
3520
  } catch (err) {
@@ -2568,150 +3537,102 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2568
3537
  use: [api.sessionMiddleware]
2569
3538
  },
2570
3539
  async (ctx) => {
2571
- const user = requireUser(ctx);
2572
- const adapter = getAdapter2(ctx);
3540
+ const { adapter, row } = await requireConfirmedOwnedSubscription(
3541
+ ctx,
3542
+ ctx.body.subscriptionId,
3543
+ subsOptions,
3544
+ "change-plan"
3545
+ );
2573
3546
  const plans = await plansRef();
2574
3547
  const nextPlan = plans.byName.get(ctx.body.plan);
2575
3548
  if (!nextPlan) {
2576
3549
  throw new api.APIError("NOT_FOUND", {
2577
- code: "SUBSCRIPTION_PLAN_NOT_FOUND",
3550
+ code: $ERROR_CODES.SUBSCRIPTION_PLAN_NOT_FOUND.code,
2578
3551
  message: `Plan "${ctx.body.plan}" is not configured.`
2579
3552
  });
2580
3553
  }
2581
- const existing = await adapter.findMany({
2582
- model: SUBSCRIPTION_MODEL2,
2583
- where: [
2584
- { field: "referenceId", value: user.id },
2585
- ...nextPlan.group ? [{ field: "group", value: nextPlan.group }] : []
2586
- ]
2587
- });
2588
- const row = existing.find(
2589
- (r) => r.status === "active" || r.status === "frozen" || r.status === "past_due"
2590
- );
2591
- if (!row) {
2592
- throw new api.APIError("NOT_FOUND", {
2593
- code: "SUBSCRIPTION_NOT_FOUND",
2594
- message: "No active subscription to change plan from."
2595
- });
2596
- }
2597
- await authorizeReference(ctx, user, row.referenceId, "change-plan", subsOptions);
2598
- if (!row.streampaySubscriptionId) {
2599
- throw new api.APIError("BAD_REQUEST", {
2600
- code: "SUBSCRIPTION_INVALID_STATE",
2601
- message: "Subscription has not been confirmed by StreamPay yet."
2602
- });
2603
- }
2604
- if (row.plan === nextPlan.name) {
2605
- throw new api.APIError("BAD_REQUEST", {
2606
- code: "SUBSCRIPTION_ALREADY_ON_PLAN",
2607
- message: `Already on plan "${nextPlan.name}".`
2608
- });
2609
- }
2610
- const mode = ctx.body.mode ?? "at_period_end";
2611
- if (mode === "immediate") {
2612
- try {
2613
- const stream = await client.getSubscription(row.streampaySubscriptionId);
2614
- const existingCoupons = [];
2615
- for (const c of stream.coupon_calculation_metadata?.coupons ?? []) {
2616
- if (c.coupon_id) existingCoupons.push(c.coupon_id);
2617
- }
2618
- const patch = {
2619
- items: [{ product_id: nextPlan.productId, quantity: 1 }],
2620
- coupons: existingCoupons
2621
- };
2622
- const result = await client.updateSubscription(row.streampaySubscriptionId, patch);
3554
+ try {
3555
+ const stream = await client.getSubscription(row.streampaySubscriptionId);
3556
+ const currentPlan = configuredPlanForSubscription(stream, plans);
3557
+ const currentGroup = currentPlan?.group ?? row.group;
3558
+ if (currentGroup !== (nextPlan.group ?? null)) {
3559
+ throw new api.APIError("BAD_REQUEST", {
3560
+ code: $ERROR_CODES.SUBSCRIPTION_PLAN_GROUP_MISMATCH.code,
3561
+ message: "A subscription can only change to another plan in the same configured group."
3562
+ });
3563
+ }
3564
+ if (stream.cancel_at_period_end) {
3565
+ throw new api.APIError("CONFLICT", {
3566
+ code: $ERROR_CODES.SUBSCRIPTION_ALREADY_SCHEDULED_CANCEL.code,
3567
+ message: "The subscription is scheduled to cancel. Uncancel it before scheduling a plan change."
3568
+ });
3569
+ }
3570
+ const currentProductIsRequestedPlan = stream.items?.some(
3571
+ (item) => subscriptionItemProductId(item) === nextPlan.productId
3572
+ );
3573
+ if (currentProductIsRequestedPlan && !stream.pending_change) {
3574
+ throw new api.APIError("BAD_REQUEST", {
3575
+ code: $ERROR_CODES.SUBSCRIPTION_ALREADY_ON_PLAN.code,
3576
+ message: `Already on plan "${nextPlan.name}".`
3577
+ });
3578
+ }
3579
+ const pendingTargets = stream.pending_change?.target_items ?? [];
3580
+ const pendingTargetIsRequestedPlan = pendingTargets.some(
3581
+ (item) => subscriptionItemProductId(item) === nextPlan.productId
3582
+ );
3583
+ if (pendingTargetIsRequestedPlan) {
2623
3584
  await adapter.update({
2624
- model: SUBSCRIPTION_MODEL2,
3585
+ model: SUBSCRIPTION_MODEL6,
2625
3586
  update: {
2626
- plan: nextPlan.name,
2627
- group: nextPlan.group ?? null,
2628
- updatedAt: /* @__PURE__ */ new Date()
3587
+ ...projectSubscriptionAgainstExisting(row, stream),
3588
+ pendingPlan: nextPlan.name,
3589
+ pendingProductId: nextPlan.productId,
3590
+ pendingPlanEffectiveAt: stream.pending_change?.effective_at ? new Date(stream.pending_change.effective_at) : null
2629
3591
  },
2630
3592
  where: [{ field: "id", value: row.id }]
2631
3593
  });
2632
- await syncSubscriptionFromUpstream(
2633
- client,
2634
- adapter,
2635
- row.streampaySubscriptionId,
2636
- getLogger(ctx),
2637
- "changeSubscriptionPlan"
2638
- );
2639
3594
  return ctx.json({
2640
- mode: "immediate",
2641
- subscription: result,
2642
- plan: nextPlan.name
3595
+ mode: "at_period_end",
3596
+ subscriptionId: row.id,
3597
+ plan: nextPlan.name,
3598
+ effectiveAt: stream.pending_change?.effective_at ?? null,
3599
+ pendingChange: stream.pending_change,
3600
+ reused: true
3601
+ });
3602
+ }
3603
+ if (stream.pending_change) {
3604
+ throw new api.APIError("CONFLICT", {
3605
+ code: $ERROR_CODES.SUBSCRIPTION_PLAN_CHANGE_ALREADY_SCHEDULED.code,
3606
+ message: "A different plan change is already scheduled. Cancel it before scheduling another."
2643
3607
  });
2644
- } catch (err) {
2645
- toAPIError(
2646
- {
2647
- logPrefix: `change-plan (immediate) failed for row=${row.id}:`,
2648
- userMessage: "Plan change failed."
2649
- },
2650
- err,
2651
- getLogger(ctx)
2652
- );
2653
3608
  }
2654
- }
2655
- try {
2656
- const stream = await client.getSubscription(row.streampaySubscriptionId);
2657
3609
  const patch = {
2658
- ...echoSubscriptionPatch(stream),
2659
- until_cycle_number: stream.current_cycle_number ?? 1
3610
+ items: [{ product_id: nextPlan.productId, quantity: 1 }],
3611
+ coupons: subscriptionCouponIds(stream),
3612
+ recurring_interval: nextPlan.billingInterval,
3613
+ recurring_interval_count: nextPlan.billingIntervalCount ?? 1
2660
3614
  };
2661
- await client.updateSubscription(row.streampaySubscriptionId, patch);
3615
+ const result = await client.updateSubscription(row.streampaySubscriptionId, patch);
3616
+ const effectiveAt = result.pending_change?.effective_at ?? result.current_period_end ?? null;
2662
3617
  await adapter.update({
2663
- model: SUBSCRIPTION_MODEL2,
3618
+ model: SUBSCRIPTION_MODEL6,
2664
3619
  update: {
2665
- cancelAtPeriodEnd: true,
3620
+ ...projectSubscriptionAgainstExisting(row, result),
3621
+ pendingPlan: nextPlan.name,
3622
+ pendingProductId: nextPlan.productId,
3623
+ pendingPlanEffectiveAt: effectiveAt ? new Date(effectiveAt) : null,
2666
3624
  updatedAt: /* @__PURE__ */ new Date()
2667
3625
  },
2668
3626
  where: [{ field: "id", value: row.id }]
2669
3627
  });
2670
- const ensureCtx = { context: ctx.context };
2671
- const { consumerId } = await ensureConsumerForUser(options, ensureCtx, user);
2672
- const linkInput = {
2673
- name: `Plan change \u2014 ${nextPlan.name}`,
2674
- items: [
2675
- {
2676
- product_id: nextPlan.productId,
2677
- quantity: 1,
2678
- allow_custom_quantity: false
2679
- }
2680
- ],
2681
- max_number_of_payments: 1,
2682
- organization_consumer_id: consumerId,
2683
- custom_metadata: {
2684
- [PLAN_NAME_METADATA_KEY]: nextPlan.name,
2685
- [REFERENCE_ID_METADATA_KEY]: user.id
2686
- }
2687
- };
2688
- if (ctx.body.successUrl) linkInput.success_redirect_url = ctx.body.successUrl;
2689
- if (ctx.body.failureUrl) linkInput.failure_redirect_url = ctx.body.failureUrl;
2690
- const link = await client.createPaymentLink(linkInput);
2691
- const url = client.getPaymentUrl(link);
2692
- const nextRow = await adapter.create({
2693
- model: SUBSCRIPTION_MODEL2,
2694
- data: {
2695
- referenceId: user.id,
2696
- plan: nextPlan.name,
2697
- group: nextPlan.group ?? null,
2698
- streampayConsumerId: consumerId,
2699
- status: "incomplete",
2700
- amountHalalat: nextPlan.priceHalalat,
2701
- currency: "SAR",
2702
- billingInterval: nextPlan.billingInterval,
2703
- billingIntervalCount: nextPlan.billingIntervalCount ?? 1,
2704
- cancelAtPeriodEnd: false,
2705
- createdAt: /* @__PURE__ */ new Date(),
2706
- updatedAt: /* @__PURE__ */ new Date()
2707
- }
2708
- });
2709
3628
  return ctx.json({
2710
3629
  mode: "at_period_end",
2711
- currentSubscriptionId: row.id,
2712
- nextSubscriptionId: nextRow.id,
2713
- url,
2714
- plan: nextPlan.name
3630
+ subscriptionId: row.id,
3631
+ plan: nextPlan.name,
3632
+ effectiveAt,
3633
+ pendingChange: result.pending_change ?? null,
3634
+ subscription: result,
3635
+ reused: false
2715
3636
  });
2716
3637
  } catch (err) {
2717
3638
  toAPIError(
@@ -2725,35 +3646,95 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2725
3646
  }
2726
3647
  }
2727
3648
  ),
2728
- freezeSubscription: api.createAuthEndpoint(
2729
- "/subscription/freeze",
3649
+ cancelSubscriptionPlanChange: api.createAuthEndpoint(
3650
+ "/subscription/change-plan/cancel",
2730
3651
  {
2731
3652
  method: "POST",
2732
- body: FreezeBody,
3653
+ body: UnfreezeBody,
2733
3654
  use: [api.sessionMiddleware]
2734
3655
  },
2735
3656
  async (ctx) => {
2736
- const user = requireUser(ctx);
2737
- const adapter = getAdapter2(ctx);
2738
- const row = await findOwnedSubscription(
3657
+ const { adapter, row } = await requireConfirmedOwnedSubscription(
2739
3658
  ctx,
2740
- user,
2741
3659
  ctx.body.subscriptionId,
2742
3660
  subsOptions,
2743
- "freeze"
3661
+ "cancel-plan-change"
2744
3662
  );
2745
- if (row.status !== "active") {
2746
- throw new api.APIError("BAD_REQUEST", {
2747
- code: "SUBSCRIPTION_INVALID_STATE",
2748
- message: "Only active subscriptions can be frozen."
3663
+ try {
3664
+ await client.deletePendingSubscriptionChange(row.streampaySubscriptionId);
3665
+ const stream = await client.getSubscription(row.streampaySubscriptionId);
3666
+ await adapter.update({
3667
+ model: SUBSCRIPTION_MODEL6,
3668
+ update: {
3669
+ ...projectSubscriptionAgainstExisting(row, stream),
3670
+ pendingPlan: null,
3671
+ pendingProductId: null,
3672
+ pendingPlanEffectiveAt: null
3673
+ },
3674
+ where: [{ field: "id", value: row.id }]
2749
3675
  });
3676
+ return ctx.json({ canceled: true, subscription: stream });
3677
+ } catch (err) {
3678
+ toAPIError(
3679
+ {
3680
+ logPrefix: `cancel plan change failed for row=${row.id}:`,
3681
+ userMessage: "Canceling the scheduled plan change failed."
3682
+ },
3683
+ err,
3684
+ getLogger(ctx)
3685
+ );
2750
3686
  }
2751
- if (!row.streampaySubscriptionId) {
2752
- throw new api.APIError("BAD_REQUEST", {
2753
- code: "SUBSCRIPTION_INVALID_STATE",
2754
- message: "Subscription has not been confirmed by StreamPay yet."
3687
+ }
3688
+ ),
3689
+ uncancelSubscription: api.createAuthEndpoint(
3690
+ "/subscription/uncancel",
3691
+ {
3692
+ method: "POST",
3693
+ body: UnfreezeBody,
3694
+ use: [api.sessionMiddleware]
3695
+ },
3696
+ async (ctx) => {
3697
+ const { adapter, row } = await requireConfirmedOwnedSubscription(
3698
+ ctx,
3699
+ ctx.body.subscriptionId,
3700
+ subsOptions,
3701
+ "uncancel"
3702
+ );
3703
+ try {
3704
+ await client.uncancelSubscription(row.streampaySubscriptionId);
3705
+ const stream = await client.getSubscription(row.streampaySubscriptionId);
3706
+ await adapter.update({
3707
+ model: SUBSCRIPTION_MODEL6,
3708
+ update: projectSubscriptionAgainstExisting(row, stream),
3709
+ where: [{ field: "id", value: row.id }]
2755
3710
  });
3711
+ return ctx.json({ uncanceled: true, subscription: stream });
3712
+ } catch (err) {
3713
+ toAPIError(
3714
+ {
3715
+ logPrefix: `uncancel subscription failed for row=${row.id}:`,
3716
+ userMessage: "Restoring subscription renewal failed."
3717
+ },
3718
+ err,
3719
+ getLogger(ctx)
3720
+ );
2756
3721
  }
3722
+ }
3723
+ ),
3724
+ freezeSubscription: api.createAuthEndpoint(
3725
+ "/subscription/freeze",
3726
+ {
3727
+ method: "POST",
3728
+ body: FreezeBody,
3729
+ use: [api.sessionMiddleware]
3730
+ },
3731
+ async (ctx) => {
3732
+ const { adapter, row } = await requireConfirmedOwnedSubscription(
3733
+ ctx,
3734
+ ctx.body.subscriptionId,
3735
+ subsOptions,
3736
+ "freeze"
3737
+ );
2757
3738
  const payload = {
2758
3739
  freeze_start_datetime: ctx.body.freezeStartDatetime
2759
3740
  };
@@ -2793,27 +3774,12 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2793
3774
  use: [api.sessionMiddleware]
2794
3775
  },
2795
3776
  async (ctx) => {
2796
- const user = requireUser(ctx);
2797
- const adapter = getAdapter2(ctx);
2798
- const row = await findOwnedSubscription(
3777
+ const { adapter, row } = await requireConfirmedOwnedSubscription(
2799
3778
  ctx,
2800
- user,
2801
3779
  ctx.body.subscriptionId,
2802
3780
  subsOptions,
2803
3781
  "unfreeze"
2804
3782
  );
2805
- if (row.status !== "frozen") {
2806
- throw new api.APIError("BAD_REQUEST", {
2807
- code: "SUBSCRIPTION_NOT_FROZEN",
2808
- message: "Subscription is not currently frozen."
2809
- });
2810
- }
2811
- if (!row.streampaySubscriptionId) {
2812
- throw new api.APIError("BAD_REQUEST", {
2813
- code: "SUBSCRIPTION_INVALID_STATE",
2814
- message: "Subscription has not been confirmed by StreamPay yet."
2815
- });
2816
- }
2817
3783
  const nowMs = Date.now();
2818
3784
  try {
2819
3785
  const freezes = await client.listSubscriptionFreezes(row.streampaySubscriptionId);
@@ -2825,130 +3791,79 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
2825
3791
  });
2826
3792
  if (!active?.id || !active.freeze_start_datetime) {
2827
3793
  throw new api.APIError("BAD_REQUEST", {
2828
- code: "SUBSCRIPTION_NOT_FROZEN",
3794
+ code: $ERROR_CODES.SUBSCRIPTION_FREEZE_NOT_ACTIVE.code,
2829
3795
  message: "No active freeze period found to cancel."
2830
- });
2831
- }
2832
- await client.updateSubscriptionFreeze(row.streampaySubscriptionId, active.id, {
2833
- freeze_start_datetime: active.freeze_start_datetime,
2834
- freeze_end_datetime: new Date(nowMs).toISOString(),
2835
- notes: active.notes ?? null
2836
- });
2837
- await syncSubscriptionFromUpstream(
2838
- client,
2839
- adapter,
2840
- row.streampaySubscriptionId,
2841
- getLogger(ctx),
2842
- "unfreezeSubscription"
2843
- );
2844
- return ctx.json({ unfrozen: true });
2845
- } catch (err) {
2846
- toAPIError(
2847
- {
2848
- logPrefix: `unfreezeSubscription failed for row=${row.id}:`,
2849
- userMessage: "Subscription unfreeze failed."
2850
- },
2851
- err,
2852
- getLogger(ctx)
2853
- );
2854
- }
2855
- }
2856
- ),
2857
- listSubscriptions: api.createAuthEndpoint(
2858
- "/subscription/list",
2859
- {
2860
- method: "GET",
2861
- use: [api.sessionMiddleware]
2862
- },
2863
- async (ctx) => {
2864
- const user = requireUser(ctx);
2865
- const adapter = getAdapter2(ctx);
2866
- const rows = await adapter.findMany({
2867
- model: SUBSCRIPTION_MODEL2,
2868
- where: [{ field: "referenceId", value: user.id }]
2869
- });
2870
- const plans = await plansRef();
2871
- return ctx.json(
2872
- rows.map((row) => ({
2873
- ...row,
2874
- plan: plans.byName.get(row.plan) ?? null
2875
- }))
2876
- );
2877
- }
2878
- ),
2879
- currentSubscription: api.createAuthEndpoint(
2880
- "/subscription/current",
2881
- {
2882
- method: "GET",
2883
- query: CurrentQuery,
2884
- use: [api.sessionMiddleware]
2885
- },
2886
- async (ctx) => {
2887
- const user = requireUser(ctx);
2888
- const adapter = getAdapter2(ctx);
2889
- const where = [
2890
- { field: "referenceId", value: user.id }
2891
- ];
2892
- if (ctx.query?.group) {
2893
- where.push({ field: "group", value: ctx.query.group });
2894
- }
2895
- const rows = await adapter.findMany({
2896
- model: SUBSCRIPTION_MODEL2,
2897
- where
2898
- });
2899
- const live = rows.find(
2900
- (row) => row.status === "active" || row.status === "frozen" || row.status === "past_due"
2901
- );
2902
- if (!live) return ctx.json(null);
2903
- const plans = await plansRef();
2904
- return ctx.json({
2905
- ...live,
2906
- plan: plans.byName.get(live.plan) ?? null
2907
- });
2908
- }
2909
- ),
2910
- hasSubscriptionFeature: api.createAuthEndpoint(
2911
- "/subscription/has-feature",
2912
- {
2913
- method: "GET",
2914
- query: HasFeatureQuery,
2915
- use: [api.sessionMiddleware]
2916
- },
2917
- async (ctx) => {
2918
- const user = requireUser(ctx);
2919
- const adapter = getAdapter2(ctx);
2920
- const where = [
2921
- { field: "referenceId", value: user.id }
2922
- ];
2923
- if (ctx.query.group) where.push({ field: "group", value: ctx.query.group });
2924
- const rows = await adapter.findMany({ model: SUBSCRIPTION_MODEL2, where });
2925
- const plans = await plansRef();
2926
- const live = rows.find((row) => row.status === "active" || row.status === "frozen");
2927
- if (!live) return ctx.json({ hasFeature: false });
2928
- const plan = plans.byName.get(live.plan);
2929
- return ctx.json({ hasFeature: hasFeature(live, plan, ctx.query.feature) });
3796
+ });
3797
+ }
3798
+ await client.updateSubscriptionFreeze(row.streampaySubscriptionId, active.id, {
3799
+ freeze_start_datetime: active.freeze_start_datetime,
3800
+ freeze_end_datetime: new Date(nowMs).toISOString(),
3801
+ notes: active.notes ?? null
3802
+ });
3803
+ await syncSubscriptionFromUpstream(
3804
+ client,
3805
+ adapter,
3806
+ row.streampaySubscriptionId,
3807
+ getLogger(ctx),
3808
+ "unfreezeSubscription"
3809
+ );
3810
+ return ctx.json({ unfrozen: true });
3811
+ } catch (err) {
3812
+ toAPIError(
3813
+ {
3814
+ logPrefix: `unfreezeSubscription failed for row=${row.id}:`,
3815
+ userMessage: "Subscription unfreeze failed."
3816
+ },
3817
+ err,
3818
+ getLogger(ctx)
3819
+ );
3820
+ }
2930
3821
  }
2931
3822
  ),
2932
- checkSubscriptionLimit: api.createAuthEndpoint(
2933
- "/subscription/check-limit",
3823
+ cancelSubscriptionFreeze: api.createAuthEndpoint(
3824
+ "/subscription/freeze/cancel",
2934
3825
  {
2935
- method: "GET",
2936
- query: CheckLimitQuery,
3826
+ method: "POST",
3827
+ body: CancelFreezeBody,
2937
3828
  use: [api.sessionMiddleware]
2938
3829
  },
2939
3830
  async (ctx) => {
2940
- const user = requireUser(ctx);
2941
- const adapter = getAdapter2(ctx);
2942
- const where = [
2943
- { field: "referenceId", value: user.id }
2944
- ];
2945
- if (ctx.query.group) where.push({ field: "group", value: ctx.query.group });
2946
- const rows = await adapter.findMany({ model: SUBSCRIPTION_MODEL2, where });
2947
- const plans = await plansRef();
2948
- const live = rows.find((row) => row.status === "active" || row.status === "frozen");
2949
- if (!live) return ctx.json({ allowed: false, limit: 0, remaining: 0 });
2950
- const plan = plans.byName.get(live.plan);
2951
- return ctx.json(checkLimit(live, plan, ctx.query.feature, ctx.query.count));
3831
+ const { adapter, row } = await requireConfirmedOwnedSubscription(
3832
+ ctx,
3833
+ ctx.body.subscriptionId,
3834
+ subsOptions,
3835
+ "cancel-freeze"
3836
+ );
3837
+ try {
3838
+ const freezes = await client.listSubscriptionFreezes(row.streampaySubscriptionId);
3839
+ if (!freezes.data?.some((freeze) => freeze.id === ctx.body.freezeId)) {
3840
+ return ctx.json({ canceled: true, freezeId: ctx.body.freezeId, reused: true });
3841
+ }
3842
+ await client.deleteSubscriptionFreeze(row.streampaySubscriptionId, ctx.body.freezeId);
3843
+ await syncSubscriptionFromUpstream(
3844
+ client,
3845
+ adapter,
3846
+ row.streampaySubscriptionId,
3847
+ getLogger(ctx),
3848
+ "cancelSubscriptionFreeze"
3849
+ );
3850
+ return ctx.json({ canceled: true, freezeId: ctx.body.freezeId, reused: false });
3851
+ } catch (err) {
3852
+ if (isAlreadyCanceledFreezeError(err)) {
3853
+ getLogger(ctx).info(
3854
+ `cancel subscription freeze reused provider tombstone for row=${row.id} freeze=${ctx.body.freezeId}.`
3855
+ );
3856
+ return ctx.json({ canceled: true, freezeId: ctx.body.freezeId, reused: true });
3857
+ }
3858
+ toAPIError(
3859
+ {
3860
+ logPrefix: `cancel subscription freeze failed for row=${row.id}:`,
3861
+ userMessage: "Canceling the subscription freeze failed."
3862
+ },
3863
+ err,
3864
+ getLogger(ctx)
3865
+ );
3866
+ }
2952
3867
  }
2953
3868
  )
2954
3869
  };
@@ -2961,6 +3876,19 @@ var subscriptionTable = {
2961
3876
  referenceId: {
2962
3877
  type: "string",
2963
3878
  required: true,
3879
+ input: false,
3880
+ index: true
3881
+ },
3882
+ referenceType: {
3883
+ type: "string",
3884
+ required: false,
3885
+ defaultValue: "user",
3886
+ input: false
3887
+ },
3888
+ activeSlotKey: {
3889
+ type: "string",
3890
+ required: false,
3891
+ unique: true,
2964
3892
  input: false
2965
3893
  },
2966
3894
  streampaySubscriptionId: {
@@ -2972,17 +3900,38 @@ var subscriptionTable = {
2972
3900
  streampayConsumerId: {
2973
3901
  type: "string",
2974
3902
  required: false,
3903
+ input: false,
3904
+ index: true
3905
+ },
3906
+ streampayPaymentLinkId: {
3907
+ type: "string",
3908
+ required: false,
3909
+ unique: true,
2975
3910
  input: false
2976
3911
  },
2977
3912
  plan: {
2978
3913
  type: "string",
2979
3914
  required: true
2980
3915
  },
3916
+ planVersion: {
3917
+ type: "string",
3918
+ required: false
3919
+ },
3920
+ productId: {
3921
+ type: "string",
3922
+ required: false,
3923
+ index: true
3924
+ },
2981
3925
  group: {
2982
3926
  type: "string",
3927
+ required: false,
3928
+ index: true
3929
+ },
3930
+ amountInSmallestUnit: {
3931
+ type: "number",
2983
3932
  required: false
2984
3933
  },
2985
- amountHalalat: {
3934
+ originalAmountInSmallestUnit: {
2986
3935
  type: "number",
2987
3936
  required: false
2988
3937
  },
@@ -3003,7 +3952,18 @@ var subscriptionTable = {
3003
3952
  status: {
3004
3953
  type: "string",
3005
3954
  required: false,
3006
- defaultValue: "incomplete"
3955
+ defaultValue: "incomplete",
3956
+ index: true
3957
+ },
3958
+ providerStatus: {
3959
+ type: "string",
3960
+ required: false
3961
+ },
3962
+ billingStatus: {
3963
+ type: "string",
3964
+ required: false,
3965
+ defaultValue: "current",
3966
+ index: true
3007
3967
  },
3008
3968
  periodStart: {
3009
3969
  type: "date",
@@ -3013,11 +3973,48 @@ var subscriptionTable = {
3013
3973
  type: "date",
3014
3974
  required: false
3015
3975
  },
3976
+ currentCycleNumber: {
3977
+ type: "number",
3978
+ required: false
3979
+ },
3980
+ trialStart: {
3981
+ type: "date",
3982
+ required: false
3983
+ },
3984
+ trialEnd: {
3985
+ type: "date",
3986
+ required: false
3987
+ },
3016
3988
  cancelAtPeriodEnd: {
3017
3989
  type: "boolean",
3018
3990
  required: false,
3019
3991
  defaultValue: false
3020
3992
  },
3993
+ cancelAt: {
3994
+ type: "date",
3995
+ required: false
3996
+ },
3997
+ cancelScheduledAt: {
3998
+ type: "date",
3999
+ required: false
4000
+ },
4001
+ canceledAt: {
4002
+ type: "date",
4003
+ required: false
4004
+ },
4005
+ pendingPlan: {
4006
+ type: "string",
4007
+ required: false
4008
+ },
4009
+ pendingProductId: {
4010
+ type: "string",
4011
+ required: false,
4012
+ index: true
4013
+ },
4014
+ pendingPlanEffectiveAt: {
4015
+ type: "date",
4016
+ required: false
4017
+ },
3021
4018
  endedAt: {
3022
4019
  type: "date",
3023
4020
  required: false
@@ -3029,6 +4026,26 @@ var subscriptionTable = {
3029
4026
  freezeEndAt: {
3030
4027
  type: "date",
3031
4028
  required: false
4029
+ },
4030
+ providerUpdatedAt: {
4031
+ type: "date",
4032
+ required: false
4033
+ },
4034
+ syncedAt: {
4035
+ type: "date",
4036
+ required: false,
4037
+ index: true
4038
+ },
4039
+ createdAt: {
4040
+ type: "date",
4041
+ required: false,
4042
+ input: false
4043
+ },
4044
+ updatedAt: {
4045
+ type: "date",
4046
+ required: false,
4047
+ input: false,
4048
+ index: true
3032
4049
  }
3033
4050
  }
3034
4051
  }
@@ -3045,15 +4062,44 @@ var webhookEventTable = {
3045
4062
  type: "string",
3046
4063
  required: true
3047
4064
  },
3048
- processedAt: {
4065
+ receivedAt: {
3049
4066
  type: "date",
3050
4067
  required: true,
3051
4068
  index: true
3052
4069
  },
4070
+ lastAttemptAt: {
4071
+ type: "date",
4072
+ required: false,
4073
+ index: true
4074
+ },
4075
+ nextAttemptAt: {
4076
+ type: "date",
4077
+ required: false,
4078
+ index: true
4079
+ },
4080
+ completedAt: {
4081
+ type: "date",
4082
+ required: false,
4083
+ index: true
4084
+ },
4085
+ deadLetteredAt: {
4086
+ type: "date",
4087
+ required: false,
4088
+ index: true
4089
+ },
4090
+ lockedAt: {
4091
+ type: "date",
4092
+ required: false,
4093
+ index: true
4094
+ },
4095
+ lockedBy: {
4096
+ type: "string",
4097
+ required: false
4098
+ },
3053
4099
  status: {
3054
4100
  type: "string",
3055
4101
  required: false,
3056
- defaultValue: "completed",
4102
+ defaultValue: "pending",
3057
4103
  index: true
3058
4104
  },
3059
4105
  attemptCount: {
@@ -3061,10 +4107,6 @@ var webhookEventTable = {
3061
4107
  required: false,
3062
4108
  defaultValue: 1
3063
4109
  },
3064
- firstSeenAt: {
3065
- type: "date",
3066
- required: false
3067
- },
3068
4110
  rawPayload: {
3069
4111
  type: "string",
3070
4112
  required: false
@@ -3076,6 +4118,11 @@ var webhookEventTable = {
3076
4118
  lastError: {
3077
4119
  type: "string",
3078
4120
  required: false
4121
+ },
4122
+ lastErrorCode: {
4123
+ type: "string",
4124
+ required: false,
4125
+ index: true
3079
4126
  }
3080
4127
  }
3081
4128
  }
@@ -3092,17 +4139,18 @@ function subscriptions(subsOptions) {
3092
4139
  } else if (typeof subsOptions.plans !== "function") {
3093
4140
  throw new TypeError("subscriptions(): `plans` must be an array or an async factory function.");
3094
4141
  }
3095
- const flags = subsOptions;
3096
- if (flags.enableSubscriptionTable === false && flags.enableWebhookEventTable === true) {
3097
- throw new TypeError(
3098
- "subscriptions(): `enableWebhookEventTable: true` requires `enableSubscriptionTable: true` \u2014 the event lifecycle table is part of the subscription sync pipeline."
3099
- );
4142
+ if (subsOptions.maxWebhookAttempts !== void 0 && (!Number.isInteger(subsOptions.maxWebhookAttempts) || subsOptions.maxWebhookAttempts < 1)) {
4143
+ throw new TypeError("subscriptions(): `maxWebhookAttempts` must be a positive integer.");
4144
+ }
4145
+ for (const status of subsOptions.accessStatuses ?? []) {
4146
+ if (!SUBSCRIPTION_STATUSES.includes(status)) {
4147
+ throw new TypeError(`subscriptions(): invalid access status "${status}".`);
4148
+ }
3100
4149
  }
3101
- const tableEnabled = subsOptions.enableSubscriptionTable !== false;
3102
4150
  const dedupeEnabled = subsOptions.enableWebhookEventTable !== false;
3103
4151
  return (options, registry) => {
3104
4152
  const resolvePlans = createPlanResolver(subsOptions.plans);
3105
- if (registry && tableEnabled) {
4153
+ if (registry) {
3106
4154
  registry.subscriptionWebhookSync = async (ctx, payload, meta) => {
3107
4155
  const syncCtx = {
3108
4156
  context: ctx.context
@@ -3115,7 +4163,8 @@ function subscriptions(subsOptions) {
3115
4163
  signatureHeader: meta?.signatureHeader ?? null,
3116
4164
  ...subsOptions.maxWebhookAttempts !== void 0 && {
3117
4165
  maxAttempts: subsOptions.maxWebhookAttempts
3118
- }
4166
+ },
4167
+ retryOnCallbackError: subsOptions.retryOnCallbackError !== false
3119
4168
  });
3120
4169
  } catch (err) {
3121
4170
  if (classifyWebhookFailure(err) === "PERMANENT") {
@@ -3148,28 +4197,59 @@ function subscriptions(subsOptions) {
3148
4197
  message: `Webhook event ${eventId} has no rawPayload \u2014 nothing to replay (already completed cleanly?).`
3149
4198
  });
3150
4199
  }
3151
- const payload = JSON.parse(row.rawPayload);
4200
+ let parsedPayload;
4201
+ try {
4202
+ parsedPayload = JSON.parse(row.rawPayload);
4203
+ } catch {
4204
+ throw new api.APIError("BAD_REQUEST", {
4205
+ message: `Webhook event ${eventId} has malformed stored JSON.`
4206
+ });
4207
+ }
4208
+ if (!isStreamPayWebhookEnvelope(parsedPayload) || !isKnownStreamPayWebhookPayload(parsedPayload)) {
4209
+ throw new api.APIError("BAD_REQUEST", {
4210
+ message: `Webhook event ${eventId} has an invalid stored payload.`
4211
+ });
4212
+ }
4213
+ const payload = parsedPayload;
3152
4214
  const plans = await resolvePlans();
4215
+ const claimed = await claimWebhookEventForReplay(syncCtx, row);
4216
+ if (!claimed?.lockedBy) {
4217
+ throw new api.APIError("CONFLICT", {
4218
+ code: $ERROR_CODES.WEBHOOK_REPLAY_IN_PROGRESS.code,
4219
+ message: `Webhook event ${eventId} is already being replayed.`
4220
+ });
4221
+ }
3153
4222
  try {
3154
4223
  await syncWebhookPayload(syncCtx, payload, options.client, plans, subsOptions, {
3155
- dedupe: false
4224
+ dedupe: false,
4225
+ retryingRenewalCallback: claimed.lastError?.startsWith(
4226
+ "Subscription callback onSubscriptionRenewed failed:"
4227
+ ) === true
3156
4228
  });
3157
- await markWebhookEventCompleted(syncCtx, row.id);
4229
+ await markWebhookEventCompleted(syncCtx, claimed.id, claimed.lockedBy);
3158
4230
  return { replayed: true, eventId };
3159
4231
  } catch (err) {
3160
- await recordWebhookEventFailure(syncCtx, row.id, null, null, err);
4232
+ await recordWebhookEventFailure(
4233
+ syncCtx,
4234
+ claimed.id,
4235
+ null,
4236
+ null,
4237
+ err,
4238
+ claimed.lockedBy,
4239
+ true
4240
+ );
3161
4241
  throw err;
3162
4242
  }
3163
4243
  };
3164
4244
  }
3165
4245
  }
3166
4246
  const schema = {
3167
- ...tableEnabled ? subscriptionTable : {},
3168
- ...tableEnabled && dedupeEnabled ? webhookEventTable : {}
4247
+ ...subscriptionTable,
4248
+ ...dedupeEnabled ? webhookEventTable : {}
3169
4249
  };
3170
4250
  return {
3171
4251
  endpoints: buildSubscriptionEndpoints(options, subsOptions, resolvePlans),
3172
- ...Object.keys(schema).length > 0 ? { schema } : {}
4252
+ schema
3173
4253
  };
3174
4254
  };
3175
4255
  }
@@ -3177,6 +4257,7 @@ function subscriptions(subsOptions) {
3177
4257
  // src/webhooks/dispatcher.ts
3178
4258
  async function dispatchWebhook(payload, handlers) {
3179
4259
  if (handlers.onPayload) await handlers.onPayload(payload);
4260
+ if (!isKnownStreamPayWebhookPayload(payload)) return;
3180
4261
  switch (payload.event_type) {
3181
4262
  case "PAYMENT_SUCCEEDED":
3182
4263
  await handlers.onPaymentSucceeded?.(payload);
@@ -3247,6 +4328,21 @@ async function dispatchWebhook(payload, handlers) {
3247
4328
  case "SUBSCRIPTION_FREEZE_CANCEL":
3248
4329
  await handlers.onSubscriptionFreezeCancel?.(payload);
3249
4330
  return;
4331
+ case "SUBSCRIPTION_PLAN_CHANGE_SCHEDULED":
4332
+ await handlers.onSubscriptionPlanChangeScheduled?.(payload);
4333
+ return;
4334
+ case "SUBSCRIPTION_PLAN_CHANGE_CANCELED":
4335
+ await handlers.onSubscriptionPlanChangeCanceled?.(payload);
4336
+ return;
4337
+ case "SUBSCRIPTION_PLAN_CHANGED":
4338
+ await handlers.onSubscriptionPlanChanged?.(payload);
4339
+ return;
4340
+ case "SUBSCRIPTION_PLAN_CHANGE_INVOICE_REISSUED":
4341
+ await handlers.onSubscriptionPlanChangeInvoiceReissued?.(payload);
4342
+ return;
4343
+ case "SUBSCRIPTION_PLAN_UPDATED":
4344
+ await handlers.onSubscriptionPlanUpdated?.(payload);
4345
+ return;
3250
4346
  case "PAYMENT_LINK_PAY_ATTEMPT_FAILED":
3251
4347
  await handlers.onPaymentLinkPayAttemptFailed?.(payload);
3252
4348
  return;
@@ -3285,7 +4381,9 @@ function verifyWebhook(input) {
3285
4381
  const { rawBody, signatureHeader } = input;
3286
4382
  const toleranceSeconds = input.toleranceSeconds ?? 300;
3287
4383
  const now = input.now ?? (() => Math.floor(Date.now() / 1e3));
3288
- const secrets = typeof input.secret === "string" ? [input.secret] : input.secret;
4384
+ const secrets = (typeof input.secret === "string" ? [input.secret] : input.secret).filter(
4385
+ (secret) => secret.length > 0
4386
+ );
3289
4387
  if (!signatureHeader) return { ok: false, reason: "MISSING_HEADER" };
3290
4388
  const parsed = parseSignatureHeader(signatureHeader);
3291
4389
  if (!parsed) return { ok: false, reason: "MALFORMED_HEADER" };
@@ -3311,95 +4409,93 @@ function verifyWebhookOrThrow(input) {
3311
4409
  }
3312
4410
 
3313
4411
  // src/plugins/webhooks.ts
3314
- function isStreamPayWebhookPayload(value) {
3315
- if (!value || typeof value !== "object") return false;
3316
- return "event_type" in value && typeof value.event_type === "string";
3317
- }
3318
4412
  function toErrorCode(reason) {
3319
4413
  return reason === "MISSING_HEADER" || reason === "INVALID_SIGNATURE" || reason === "EXPIRED" ? "UNAUTHORIZED" : "BAD_REQUEST";
3320
4414
  }
3321
- var webhooks = (webhooksOptions) => (_options, registry) => {
3322
- const { secret, toleranceSeconds, ...handlers } = webhooksOptions;
3323
- return {
3324
- endpoints: {
3325
- streampayWebhooks: api.createAuthEndpoint(
3326
- "/streampay/webhooks",
3327
- {
3328
- method: "POST",
3329
- metadata: { isAction: false },
3330
- cloneRequest: true
3331
- },
3332
- async (ctx) => {
3333
- const logger2 = getLogger(ctx);
3334
- const hasSecret = typeof secret === "string" ? secret.length > 0 : secret.some((s) => s.length > 0);
3335
- if (!hasSecret) {
3336
- logger2.error("webhook secret is not configured.");
3337
- throw new api.APIError("INTERNAL_SERVER_ERROR", {
3338
- message: "StreamPay webhook secret is not configured."
3339
- });
3340
- }
3341
- if (!ctx.request) {
3342
- throw new api.APIError("BAD_REQUEST", { message: "Missing request body." });
3343
- }
3344
- const rawBody = await ctx.request.text();
3345
- const signatureHeader = ctx.request.headers.get("x-webhook-signature");
3346
- try {
3347
- verifyWebhookOrThrow({
3348
- secret,
3349
- rawBody,
3350
- signatureHeader,
3351
- toleranceSeconds: toleranceSeconds ?? 300
3352
- });
3353
- } catch (err) {
3354
- if (err instanceof StreamPayWebhookError) {
3355
- logger2.warn(`webhook rejected: ${err.reason}`);
3356
- throw new api.APIError(toErrorCode(err.reason), {
3357
- message: `Webhook verification failed: ${err.reason}`
3358
- });
4415
+ var webhooks = (webhooksOptions) => {
4416
+ const configuredSecrets = typeof webhooksOptions.secret === "string" ? [webhooksOptions.secret] : webhooksOptions.secret;
4417
+ if (configuredSecrets.length === 0 || configuredSecrets.some((secret) => secret.length === 0)) {
4418
+ throw new TypeError("webhooks(): `secret` must contain only non-empty values.");
4419
+ }
4420
+ if (webhooksOptions.toleranceSeconds !== void 0 && (!Number.isFinite(webhooksOptions.toleranceSeconds) || webhooksOptions.toleranceSeconds < 0)) {
4421
+ throw new TypeError("webhooks(): `toleranceSeconds` must be a non-negative number.");
4422
+ }
4423
+ return (_options, registry) => {
4424
+ const { secret, toleranceSeconds, ...handlers } = webhooksOptions;
4425
+ return {
4426
+ endpoints: {
4427
+ streampayWebhooks: api.createAuthEndpoint(
4428
+ "/streampay/webhooks",
4429
+ {
4430
+ method: "POST",
4431
+ metadata: { isAction: false },
4432
+ cloneRequest: true
4433
+ },
4434
+ async (ctx) => {
4435
+ const logger2 = getLogger(ctx);
4436
+ if (!ctx.request) {
4437
+ throw new api.APIError("BAD_REQUEST", { message: "Missing request body." });
3359
4438
  }
3360
- throw err;
3361
- }
3362
- let parsed;
3363
- try {
3364
- parsed = JSON.parse(rawBody);
3365
- } catch {
3366
- throw new api.APIError("BAD_REQUEST", {
3367
- message: "Webhook body is not valid JSON."
3368
- });
3369
- }
3370
- if (!isStreamPayWebhookPayload(parsed)) {
3371
- throw new api.APIError("BAD_REQUEST", {
3372
- message: "Webhook body is missing `event_type`."
3373
- });
3374
- }
3375
- const payload = parsed;
3376
- if (registry?.subscriptionWebhookSync) {
4439
+ const rawBody = await ctx.request.text();
4440
+ const signatureHeader = ctx.request.headers.get("x-webhook-signature");
3377
4441
  try {
3378
- await registry.subscriptionWebhookSync(ctx, payload, {
4442
+ verifyWebhookOrThrow({
4443
+ secret,
3379
4444
  rawBody,
3380
- signatureHeader
4445
+ signatureHeader,
4446
+ toleranceSeconds: toleranceSeconds ?? 300
4447
+ });
4448
+ } catch (err) {
4449
+ if (err instanceof StreamPayWebhookError) {
4450
+ logger2.warn(`webhook rejected: ${err.reason}`);
4451
+ throw new api.APIError(toErrorCode(err.reason), {
4452
+ message: `Webhook verification failed: ${err.reason}`
4453
+ });
4454
+ }
4455
+ throw err;
4456
+ }
4457
+ let parsed;
4458
+ try {
4459
+ parsed = JSON.parse(rawBody);
4460
+ } catch {
4461
+ throw new api.APIError("BAD_REQUEST", {
4462
+ message: "Webhook body is not valid JSON."
3381
4463
  });
4464
+ }
4465
+ if (!isStreamPayWebhookEnvelope(parsed)) {
4466
+ throw new api.APIError("BAD_REQUEST", {
4467
+ message: "Webhook body is not a valid StreamPay event envelope."
4468
+ });
4469
+ }
4470
+ const payload = parsed;
4471
+ if (registry?.subscriptionWebhookSync && isKnownStreamPayWebhookPayload(payload)) {
4472
+ try {
4473
+ await registry.subscriptionWebhookSync(ctx, payload, {
4474
+ rawBody,
4475
+ signatureHeader
4476
+ });
4477
+ } catch (err) {
4478
+ const message = err instanceof Error ? err.message : String(err);
4479
+ logger2.error(`subscription sync failed: ${message}`);
4480
+ throw new api.APIError("INTERNAL_SERVER_ERROR", {
4481
+ message: "Webhook sync failed. See server logs."
4482
+ });
4483
+ }
4484
+ }
4485
+ try {
4486
+ await dispatchWebhook(payload, handlers);
3382
4487
  } catch (err) {
3383
4488
  const message = err instanceof Error ? err.message : String(err);
3384
- logger2.error(`subscription sync failed: ${message}`);
4489
+ logger2.error(`webhook handler failed: ${message}`);
3385
4490
  throw new api.APIError("INTERNAL_SERVER_ERROR", {
3386
- message: "Webhook sync failed. See server logs."
4491
+ message: "Webhook handler failed. See server logs."
3387
4492
  });
3388
4493
  }
4494
+ return ctx.json({ received: true });
3389
4495
  }
3390
- try {
3391
- await dispatchWebhook(payload, handlers);
3392
- } catch (err) {
3393
- const message = err instanceof Error ? err.message : String(err);
3394
- logger2.error(`webhook handler failed: ${message}`);
3395
- throw new api.APIError("INTERNAL_SERVER_ERROR", {
3396
- message: "Webhook handler failed. See server logs."
3397
- });
3398
- }
3399
- return ctx.json({ received: true });
3400
- }
3401
- )
3402
- }
4496
+ )
4497
+ }
4498
+ };
3403
4499
  };
3404
4500
  };
3405
4501
  var isAnonymous = (user) => "isAnonymous" in user && user.isAnonymous === true;
@@ -3418,6 +4514,7 @@ var onBeforeUserCreate = (options) => async (user, context) => {
3418
4514
  const createPayload = {
3419
4515
  name: user.name || user.email,
3420
4516
  email: user.email,
4517
+ consumer_type: "INDIVIDUAL",
3421
4518
  ...extras
3422
4519
  };
3423
4520
  try {
@@ -3516,7 +4613,7 @@ var onUserDelete = (options) => async (user, context) => {
3516
4613
 
3517
4614
  // package.json
3518
4615
  var package_default = {
3519
- version: "1.3.0"};
4616
+ version: "2.0.0"};
3520
4617
 
3521
4618
  // src/version.ts
3522
4619
  var version = package_default.version;
@@ -3572,53 +4669,40 @@ var streampay = (options) => {
3572
4669
  };
3573
4670
  };
3574
4671
 
3575
- // src/webhooks/events.ts
3576
- var STREAMPAY_PAYMENT_EVENT_TYPES = [
3577
- "PAYMENT_SUCCEEDED",
3578
- "PAYMENT_FAILED",
3579
- "PAYMENT_CANCELED",
3580
- "PAYMENT_REFUNDED",
3581
- "PAYMENT_MARKED_AS_PAID"
3582
- ];
3583
- var STREAMPAY_INVOICE_EVENT_TYPES = [
3584
- "INVOICE_CREATED",
3585
- "INVOICE_SENT",
3586
- "INVOICE_ACCEPTED",
3587
- "INVOICE_REJECTED",
3588
- "INVOICE_COMPLETED",
3589
- "INVOICE_CANCELED",
3590
- "INVOICE_UPDATED"
3591
- ];
3592
- var STREAMPAY_SUBSCRIPTION_EVENT_TYPES = [
3593
- "SUBSCRIPTION_CREATED",
3594
- "SUBSCRIPTION_ACTIVATED",
3595
- "SUBSCRIPTION_INACTIVATED",
3596
- "SUBSCRIPTION_CANCELED",
3597
- "SUBSCRIPTION_FROZEN",
3598
- "SUBSCRIPTION_CYCLE_RENEWAL_FAILED",
3599
- "SUBSCRIPTION_CANCEL_AT_PERIOD_END",
3600
- "SUBSCRIPTION_FREEZE_NOW",
3601
- "SUBSCRIPTION_UNFREEZE_NOW",
3602
- "SUBSCRIPTION_UNFREEZE_FUTURE",
3603
- "SUBSCRIPTION_FREEZE_CANCEL"
3604
- ];
3605
- var STREAMPAY_PAYMENT_LINK_EVENT_TYPES = ["PAYMENT_LINK_PAY_ATTEMPT_FAILED"];
3606
- var STREAMPAY_EVENT_TYPES = [
3607
- ...STREAMPAY_PAYMENT_EVENT_TYPES,
3608
- ...STREAMPAY_INVOICE_EVENT_TYPES,
3609
- ...STREAMPAY_SUBSCRIPTION_EVENT_TYPES,
3610
- ...STREAMPAY_PAYMENT_LINK_EVENT_TYPES
3611
- ];
4672
+ // src/utils/amount.ts
4673
+ var StreamPayAmount = {
4674
+ toHalalat(sar) {
4675
+ const asNumber = typeof sar === "string" ? Number(sar) : sar;
4676
+ if (!Number.isFinite(asNumber)) {
4677
+ throw new RangeError(`StreamPayAmount.toHalalat: invalid SAR value ${String(sar)}`);
4678
+ }
4679
+ const absoluteHalalat = Math.round(Number(`${Math.abs(asNumber)}e2`));
4680
+ const halalat = Math.sign(asNumber) * absoluteHalalat;
4681
+ if (!Number.isSafeInteger(halalat)) {
4682
+ throw new RangeError(`StreamPayAmount.toHalalat: SAR value is outside the safe range`);
4683
+ }
4684
+ return halalat;
4685
+ },
4686
+ toSAR(halalat) {
4687
+ if (!Number.isFinite(halalat) || !Number.isInteger(halalat)) {
4688
+ throw new RangeError(`StreamPayAmount.toSAR: expected integer halalat, got ${halalat}`);
4689
+ }
4690
+ return (halalat / 100).toFixed(2);
4691
+ }
4692
+ };
3612
4693
 
3613
4694
  exports.$ERROR_CODES = $ERROR_CODES;
3614
4695
  exports.CheckoutBody = CheckoutBody;
4696
+ exports.DEFAULT_ACCESS_STATUSES = DEFAULT_ACCESS_STATUSES;
3615
4697
  exports.PLAN_NAME_METADATA_KEY = PLAN_NAME_METADATA_KEY;
3616
4698
  exports.REFERENCE_ID_METADATA_KEY = REFERENCE_ID_METADATA_KEY;
4699
+ exports.REFERENCE_TYPE_METADATA_KEY = REFERENCE_TYPE_METADATA_KEY;
3617
4700
  exports.STREAMPAY_EVENT_TYPES = STREAMPAY_EVENT_TYPES;
3618
4701
  exports.STREAMPAY_INVOICE_EVENT_TYPES = STREAMPAY_INVOICE_EVENT_TYPES;
3619
4702
  exports.STREAMPAY_PAYMENT_EVENT_TYPES = STREAMPAY_PAYMENT_EVENT_TYPES;
3620
4703
  exports.STREAMPAY_PAYMENT_LINK_EVENT_TYPES = STREAMPAY_PAYMENT_LINK_EVENT_TYPES;
3621
4704
  exports.STREAMPAY_SUBSCRIPTION_EVENT_TYPES = STREAMPAY_SUBSCRIPTION_EVENT_TYPES;
4705
+ exports.SUBSCRIPTION_ROW_ID_METADATA_KEY = SUBSCRIPTION_ROW_ID_METADATA_KEY;
3622
4706
  exports.StreamPayAmount = StreamPayAmount;
3623
4707
  exports.StreamPayWebhookError = StreamPayWebhookError;
3624
4708
  exports.admin = admin;
@@ -3630,11 +4714,15 @@ exports.findConsumerByExternalId = findConsumerByExternalId;
3630
4714
  exports.findConsumerByIdentifiers = findConsumerByIdentifiers;
3631
4715
  exports.formatStreamPayError = formatStreamPayError;
3632
4716
  exports.hasFeature = hasFeature;
4717
+ exports.hasSubscriptionAccess = hasSubscriptionAccess;
4718
+ exports.isKnownStreamPayWebhookPayload = isKnownStreamPayWebhookPayload;
4719
+ exports.isStreamPayWebhookEnvelope = isStreamPayWebhookEnvelope;
3633
4720
  exports.mapToErrorCode = mapToErrorCode;
3634
4721
  exports.parseStreamPayError = parseStreamPayError;
3635
4722
  exports.portal = portal;
3636
4723
  exports.streampay = streampay;
3637
4724
  exports.subscriptionSchema = subscriptionSchema;
4725
+ exports.subscriptionSlotKey = subscriptionSlotKey;
3638
4726
  exports.subscriptions = subscriptions;
3639
4727
  exports.syncWebhookPayload = syncWebhookPayload;
3640
4728
  exports.verifyWebhook = verifyWebhook;