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