better-auth-streampay 2.1.0 → 2.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -43,6 +43,8 @@ var $ERROR_CODES = defineErrorCodes({
43
43
  SUBSCRIPTION_EXPIRED: "The subscription has expired.",
44
44
  SUBSCRIPTION_ALREADY_SCHEDULED_CANCEL: "The subscription is already scheduled to cancel at period end.",
45
45
  SUBSCRIPTION_ALREADY_ON_PLAN: "The subscription is already on the requested plan.",
46
+ SUBSCRIPTION_SEAT_COUNT_INVALID: "The requested seat count is invalid for this plan.",
47
+ SUBSCRIPTION_SEAT_CHANGE_ALREADY_SCHEDULED: "A different subscription change is already scheduled.",
46
48
  SUBSCRIPTION_IMMEDIATE_CANCEL_UNSUPPORTED: "StreamPay does not support immediate cancellation for active subscriptions.",
47
49
  SUBSCRIPTION_PERIOD_END_CANCEL_UNSUPPORTED: "StreamPay only supports period-end cancellation for active subscriptions.",
48
50
  SUBSCRIPTION_PLAN_GROUP_MISMATCH: "Subscription plan changes must stay within the same configured plan group.",
@@ -670,7 +672,8 @@ function projectSubscriptionFields(sub) {
670
672
  }
671
673
  function parseDate(value) {
672
674
  if (!value) return null;
673
- const date = new Date(value);
675
+ const normalized = /[T ]/.test(value) && !/(?:Z|[+-]\d{2}:?\d{2})$/i.test(value) ? `${value}Z` : value;
676
+ const date = new Date(normalized);
674
677
  return Number.isNaN(date.getTime()) ? null : date;
675
678
  }
676
679
  function minorUnitExponent(currency) {
@@ -709,13 +712,19 @@ function amountToSmallestUnit(value, currency) {
709
712
  }
710
713
  var SubscriptionItemSchema = z.object({
711
714
  product: z.object({ id: z.string() }).passthrough().optional(),
712
- product_id: z.string().optional()
715
+ product_id: z.string().optional(),
716
+ quantity: z.number().optional()
713
717
  }).passthrough();
714
718
  function subscriptionItemProductId(item) {
715
719
  const parsed = SubscriptionItemSchema.safeParse(item);
716
720
  if (!parsed.success) return null;
717
721
  return parsed.data.product?.id ?? parsed.data.product_id ?? null;
718
722
  }
723
+ function subscriptionItemQuantity(item) {
724
+ const parsed = SubscriptionItemSchema.safeParse(item);
725
+ if (!parsed.success || parsed.data.quantity === void 0) return null;
726
+ return Number.isSafeInteger(parsed.data.quantity) && parsed.data.quantity > 0 ? parsed.data.quantity : null;
727
+ }
719
728
  function inferPlanFromItems(sub, plans) {
720
729
  if (!Array.isArray(sub.items)) return null;
721
730
  return inferPlanFromItemList(sub.items, plans);
@@ -724,14 +733,32 @@ function inferPlanFromItemList(items, plans) {
724
733
  const productIds = new Set(
725
734
  items.map(subscriptionItemProductId).filter((id) => Boolean(id))
726
735
  );
727
- return plans.list.find((plan) => productIds.has(plan.productId))?.name ?? null;
736
+ const matches = plans.list.filter((plan) => productIds.has(plan.productId));
737
+ if (matches.length > 1) {
738
+ throw new APIError("INTERNAL_SERVER_ERROR", {
739
+ code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
740
+ message: "StreamPay returned a subscription containing multiple configured plan products."
741
+ });
742
+ }
743
+ return matches[0]?.name ?? null;
728
744
  }
729
745
  function projectPlanFields(sub, plans) {
730
746
  const currentPlan = inferPlanFromItems(sub, plans);
731
- const currentProductId = subscriptionItemProductId(sub.items?.[0]);
732
- const pendingPlan = Array.isArray(sub.pending_change?.target_items) ? inferPlanFromItemList(sub.pending_change.target_items, plans) : null;
733
- const pendingProductId = subscriptionItemProductId(sub.pending_change?.target_items?.[0]);
734
747
  const configuredCurrent = currentPlan ? plans.byName.get(currentPlan) : void 0;
748
+ const currentItem = configuredCurrent ? sub.items?.find((item) => subscriptionItemProductId(item) === configuredCurrent.productId) : sub.items?.[0];
749
+ const currentProductId = subscriptionItemProductId(currentItem);
750
+ const currentSeats = currentItem ? subscriptionItemQuantity(currentItem) ?? 1 : null;
751
+ const inferredPendingPlan = Array.isArray(sub.pending_change?.target_items) ? inferPlanFromItemList(sub.pending_change.target_items, plans) : null;
752
+ const configuredPending = inferredPendingPlan ? plans.byName.get(inferredPendingPlan) : void 0;
753
+ const pendingItem = configuredPending ? sub.pending_change?.target_items?.find(
754
+ (item) => subscriptionItemProductId(item) === configuredPending.productId
755
+ ) : currentProductId ? sub.pending_change?.target_items?.find(
756
+ (item) => subscriptionItemProductId(item) === currentProductId
757
+ ) : sub.pending_change?.target_items?.[0];
758
+ const pendingProductId = subscriptionItemProductId(pendingItem);
759
+ const pendingSeats = pendingItem ? subscriptionItemQuantity(pendingItem) ?? 1 : null;
760
+ const pendingEffectiveAt = parseDate(sub.pending_change?.effective_at);
761
+ const planChanges = Boolean(inferredPendingPlan) && (inferredPendingPlan !== currentPlan || pendingProductId !== currentProductId);
735
762
  return {
736
763
  ...currentPlan ? {
737
764
  plan: currentPlan,
@@ -739,9 +766,12 @@ function projectPlanFields(sub, plans) {
739
766
  productId: currentProductId,
740
767
  group: configuredCurrent?.group ?? null
741
768
  } : currentProductId ? { productId: currentProductId } : {},
742
- pendingPlan,
743
- pendingProductId,
744
- pendingPlanEffectiveAt: parseDate(sub.pending_change?.effective_at)
769
+ ...currentSeats === null ? {} : { seats: currentSeats },
770
+ pendingPlan: planChanges ? inferredPendingPlan : null,
771
+ pendingProductId: planChanges ? pendingProductId : null,
772
+ pendingPlanEffectiveAt: planChanges ? pendingEffectiveAt : null,
773
+ pendingSeats,
774
+ pendingSeatsEffectiveAt: pendingSeats === null ? null : pendingEffectiveAt
745
775
  };
746
776
  }
747
777
  function subscriptionSlotKey(referenceType, referenceId, group) {
@@ -2942,9 +2972,10 @@ function checkoutInProgressError() {
2942
2972
  });
2943
2973
  }
2944
2974
  async function resumeOrReserveCheckoutSlot(args) {
2945
- const { client, adapter, candidates, activeSlotKey, planName, now, log } = args;
2975
+ const { client, adapter, candidates, activeSlotKey, planName, seats, now, log } = args;
2976
+ const matchesCheckout = (row2) => row2.plan === planName && (row2.seats ?? 1) === seats;
2946
2977
  const reuseCandidate = candidates.find(
2947
- (row2) => row2.plan === planName && row2.status === "incomplete" && Boolean(row2.streampayPaymentLinkId) && row2.createdAt instanceof Date && now - row2.createdAt.getTime() < UPGRADE_IDEMPOTENCY_WINDOW_MS
2978
+ (row2) => matchesCheckout(row2) && row2.status === "incomplete" && Boolean(row2.streampayPaymentLinkId) && row2.createdAt instanceof Date && now - row2.createdAt.getTime() < UPGRADE_IDEMPOTENCY_WINDOW_MS
2948
2979
  );
2949
2980
  if (reuseCandidate) {
2950
2981
  let recovery;
@@ -2983,21 +3014,23 @@ async function resumeOrReserveCheckoutSlot(args) {
2983
3014
  where: [{ field: "activeSlotKey", value: activeSlotKey }]
2984
3015
  });
2985
3016
  if (reserved?.status !== "incomplete") throw err;
2986
- let recovery;
2987
- try {
2988
- recovery = await recoverCheckoutUrl(client, reserved);
2989
- } catch (recoveryError) {
2990
- toAPIError(
2991
- {
2992
- logPrefix: `resume concurrent subscription checkout failed for row=${reserved.id}:`,
2993
- userMessage: "Unable to resume subscription checkout."
2994
- },
2995
- recoveryError,
2996
- log
2997
- );
2998
- }
2999
- if (recovery.kind === "recovered") {
3000
- return { kind: "recovered", row: reserved, url: recovery.url };
3017
+ if (matchesCheckout(reserved)) {
3018
+ let recovery;
3019
+ try {
3020
+ recovery = await recoverCheckoutUrl(client, reserved);
3021
+ } catch (recoveryError) {
3022
+ toAPIError(
3023
+ {
3024
+ logPrefix: `resume concurrent subscription checkout failed for row=${reserved.id}:`,
3025
+ userMessage: "Unable to resume subscription checkout."
3026
+ },
3027
+ recoveryError,
3028
+ log
3029
+ );
3030
+ }
3031
+ if (recovery.kind === "recovered") {
3032
+ return { kind: "recovered", row: reserved, url: recovery.url };
3033
+ }
3001
3034
  }
3002
3035
  const reservationIsStale = !(reserved.createdAt instanceof Date) || now - reserved.createdAt.getTime() >= UPGRADE_IDEMPOTENCY_WINDOW_MS;
3003
3036
  if (!reservationIsStale) throw checkoutInProgressError();
@@ -3023,24 +3056,67 @@ async function resumeOrReserveCheckoutSlot(args) {
3023
3056
  }
3024
3057
  return { kind: "reserved", row, consumerId };
3025
3058
  }
3026
-
3027
- // src/plugins/subscriptions/lifecycle.ts
3028
3059
  function isAlreadyCanceledFreezeError(err) {
3029
3060
  const sdkError = readSdkErrorFields(err);
3030
3061
  const envelope = readEnvelope(sdkError.body);
3031
3062
  return sdkError.status === 403 && envelope?.code === "STREAM_ERROR" && envelope.additionalInfo === "Cannot delete non-latest freeze entry.";
3032
3063
  }
3033
3064
  function subscriptionCouponIds(stream) {
3065
+ return couponIdsFromMetadata(stream.coupon_calculation_metadata);
3066
+ }
3067
+ function couponIdsFromMetadata(metadata) {
3034
3068
  const coupons = [];
3035
- for (const coupon of stream.coupon_calculation_metadata?.coupons ?? []) {
3069
+ for (const coupon of metadata?.coupons ?? []) {
3036
3070
  if (coupon.coupon_id) coupons.push(coupon.coupon_id);
3037
3071
  }
3038
3072
  return coupons;
3039
3073
  }
3074
+ function subscriptionItemsForUpdate(stream, currentProductId, targetProductId, targetSeats) {
3075
+ if (!stream.items?.length) {
3076
+ throw invalidProviderItems("StreamPay returned a subscription without any items.");
3077
+ }
3078
+ const subscriptionCoupons = new Set(subscriptionCouponIds(stream));
3079
+ let matches = 0;
3080
+ const items = stream.items.map((item) => {
3081
+ const productId = subscriptionItemProductId(item);
3082
+ const quantity = item.quantity ?? 1;
3083
+ if (!productId || !Number.isSafeInteger(quantity) || quantity < 1) {
3084
+ throw invalidProviderItems("StreamPay returned an invalid subscription item.");
3085
+ }
3086
+ const isPlanItem = productId === currentProductId;
3087
+ if (isPlanItem) matches += 1;
3088
+ const itemCoupons = couponIdsFromMetadata(item.coupon_calculation_metadata).filter(
3089
+ (couponId) => !subscriptionCoupons.has(couponId)
3090
+ );
3091
+ return {
3092
+ product_id: isPlanItem ? targetProductId : productId,
3093
+ quantity: isPlanItem ? targetSeats : quantity,
3094
+ ...itemCoupons.length > 0 ? { coupons: itemCoupons } : {}
3095
+ };
3096
+ });
3097
+ if (matches !== 1) {
3098
+ throw invalidProviderItems(
3099
+ `Expected exactly one plan item for product "${currentProductId}", received ${matches}.`
3100
+ );
3101
+ }
3102
+ return items;
3103
+ }
3104
+ function invalidProviderItems(message) {
3105
+ return new APIError("INTERNAL_SERVER_ERROR", {
3106
+ code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
3107
+ message
3108
+ });
3109
+ }
3040
3110
  function configuredPlanForSubscription(subscription, plans) {
3041
- return plans.list.find(
3111
+ const matches = plans.list.filter(
3042
3112
  (plan) => subscription.items?.some((item) => subscriptionItemProductId(item) === plan.productId)
3043
3113
  );
3114
+ if (matches.length > 1) {
3115
+ throw invalidProviderItems(
3116
+ "StreamPay returned a subscription containing multiple configured plan products."
3117
+ );
3118
+ }
3119
+ return matches[0];
3044
3120
  }
3045
3121
  var SUBSCRIPTION_INTERVALS = ["WEEK", "MONTH", "QUARTER", "YEAR"];
3046
3122
  var PlanSchema = z.object({
@@ -3063,7 +3139,46 @@ var PlanSchema = z.object({
3063
3139
  message: "has invalid `trialPeriodDays` \u2014 must be an integer from 1 to 365."
3064
3140
  }).optional(),
3065
3141
  group: z.string().min(1, "has an empty `group`.").optional(),
3142
+ seatBilling: z.object({
3143
+ default: z.number().safe().int().positive().optional(),
3144
+ minimum: z.number().safe().int().positive().optional(),
3145
+ maximum: z.number().safe().int().positive().optional(),
3146
+ customerEditable: z.boolean().optional()
3147
+ }).optional(),
3066
3148
  limits: z.record(z.string(), z.unknown()).optional()
3149
+ }).superRefine((plan, ctx) => {
3150
+ const seats = plan.seatBilling;
3151
+ if (!seats) return;
3152
+ const minimum = seats.minimum ?? 1;
3153
+ const defaultSeats = seats.default ?? minimum;
3154
+ if (seats.maximum !== void 0 && seats.maximum < minimum) {
3155
+ ctx.addIssue({
3156
+ code: "custom",
3157
+ path: ["seatBilling", "maximum"],
3158
+ message: "must be greater than or equal to `minimum`."
3159
+ });
3160
+ }
3161
+ if (defaultSeats < minimum || seats.maximum !== void 0 && defaultSeats > seats.maximum) {
3162
+ ctx.addIssue({
3163
+ code: "custom",
3164
+ path: ["seatBilling", "default"],
3165
+ message: "must be within the configured minimum and maximum."
3166
+ });
3167
+ }
3168
+ if (seats.customerEditable && (seats.minimum === void 0 || seats.maximum === void 0)) {
3169
+ ctx.addIssue({
3170
+ code: "custom",
3171
+ path: ["seatBilling", "customerEditable"],
3172
+ message: "requires explicit `minimum` and `maximum` bounds for hosted checkout editing."
3173
+ });
3174
+ }
3175
+ if (seats.maximum !== void 0 && !Number.isSafeInteger(plan.priceInSmallestUnit * seats.maximum)) {
3176
+ ctx.addIssue({
3177
+ code: "custom",
3178
+ path: ["seatBilling", "maximum"],
3179
+ message: "produces an unsafe total with `priceInSmallestUnit`."
3180
+ });
3181
+ }
3067
3182
  });
3068
3183
  var PlansSchema = z.array(PlanSchema).nonempty("`plans` resolved to an empty list. Provide at least one plan.").superRefine((plans, ctx) => {
3069
3184
  const seenNames = /* @__PURE__ */ new Set();
@@ -3101,26 +3216,10 @@ function buildIndex(list) {
3101
3216
  for (const plan of list) byName.set(plan.name, plan);
3102
3217
  return { list, byName };
3103
3218
  }
3104
- function createPlanResolver(plans) {
3105
- let cached = null;
3106
- let inFlight = null;
3107
- return async function getPlans() {
3108
- if (cached) return cached;
3109
- if (inFlight) return inFlight;
3110
- if (!plans) throw new TypeError("subscriptions(): `plans` is required.");
3111
- inFlight = (async () => {
3112
- const list = typeof plans === "function" ? await plans() : plans;
3113
- validatePlansShape(list);
3114
- const resolved = buildIndex(list);
3115
- cached = resolved;
3116
- return resolved;
3117
- })();
3118
- try {
3119
- return await inFlight;
3120
- } finally {
3121
- inFlight = null;
3122
- }
3123
- };
3219
+ async function resolvePlans(plans) {
3220
+ const list = typeof plans === "function" ? await plans() : plans;
3221
+ validatePlansShape(list);
3222
+ return buildIndex(list);
3124
3223
  }
3125
3224
  function hasSubscriptionAccess(subscription, accessStatuses = DEFAULT_ACCESS_STATUSES) {
3126
3225
  return accessStatuses.includes(subscription.status);
@@ -3167,6 +3266,15 @@ var CheckLimitQuery = z.object({
3167
3266
  count: z.coerce.number().int().min(0),
3168
3267
  group: z.string().min(1).optional()
3169
3268
  });
3269
+ function presentSubscription(row, plans) {
3270
+ return {
3271
+ ...row,
3272
+ // The column is nullable during safe rolling migrations. Keep the public
3273
+ // contract stable while applications backfill legacy rows to one seat.
3274
+ seats: row.seats ?? 1,
3275
+ plan: plans.byName.get(row.plan) ?? null
3276
+ };
3277
+ }
3170
3278
  async function resolveLiveSubscription(ctx, query, subsOptions, accessStatuses) {
3171
3279
  const user = requireUser(ctx);
3172
3280
  const reference = resolveReference(user, query);
@@ -3217,12 +3325,7 @@ function buildSubscriptionReadEndpoints(subsOptions, plansRef) {
3217
3325
  ]
3218
3326
  });
3219
3327
  const plans = await plansRef();
3220
- return ctx.json(
3221
- rows.map((row) => ({
3222
- ...row,
3223
- plan: plans.byName.get(row.plan) ?? null
3224
- }))
3225
- );
3328
+ return ctx.json(rows.map((row) => presentSubscription(row, plans)));
3226
3329
  }
3227
3330
  ),
3228
3331
  currentSubscription: createAuthEndpoint(
@@ -3241,7 +3344,7 @@ function buildSubscriptionReadEndpoints(subsOptions, plansRef) {
3241
3344
  );
3242
3345
  if (!live) return ctx.json(null);
3243
3346
  const plans = await plansRef();
3244
- return ctx.json({ ...live, plan: plans.byName.get(live.plan) ?? null });
3347
+ return ctx.json(presentSubscription(live, plans));
3245
3348
  }
3246
3349
  ),
3247
3350
  hasSubscriptionFeature: createAuthEndpoint(
@@ -3276,16 +3379,63 @@ function buildSubscriptionReadEndpoints(subsOptions, plansRef) {
3276
3379
  )
3277
3380
  };
3278
3381
  }
3382
+ function resolveSeatCount(plan, requested) {
3383
+ const seats = requested ?? plan.seatBilling?.default ?? plan.seatBilling?.minimum ?? 1;
3384
+ const minimum = plan.seatBilling?.minimum ?? 1;
3385
+ const maximum = plan.seatBilling?.maximum;
3386
+ if (!Number.isSafeInteger(seats) || seats < minimum || maximum !== void 0 && seats > maximum) {
3387
+ const range = maximum === void 0 ? `${minimum} or more` : `${minimum}\u2013${maximum}`;
3388
+ throw new APIError("BAD_REQUEST", {
3389
+ code: $ERROR_CODES.SUBSCRIPTION_SEAT_COUNT_INVALID.code,
3390
+ message: `Plan "${plan.name}" requires a safe-integer seat count in the range ${range}.`
3391
+ });
3392
+ }
3393
+ return seats;
3394
+ }
3395
+ function quotedSeatTotal(plan, seats) {
3396
+ const total = plan.priceInSmallestUnit * seats;
3397
+ if (!Number.isSafeInteger(total)) {
3398
+ throw new APIError("BAD_REQUEST", {
3399
+ code: $ERROR_CODES.SUBSCRIPTION_SEAT_COUNT_INVALID.code,
3400
+ message: `The quoted total for ${seats} seats exceeds JavaScript's safe-integer range.`
3401
+ });
3402
+ }
3403
+ return total;
3404
+ }
3405
+ function buildSeatCheckoutItem(plan, seats) {
3406
+ if (!plan.seatBilling?.customerEditable) {
3407
+ return {
3408
+ product_id: plan.productId,
3409
+ quantity: seats,
3410
+ allow_custom_quantity: false
3411
+ };
3412
+ }
3413
+ const minimum = plan.seatBilling.minimum;
3414
+ const maximum = plan.seatBilling.maximum;
3415
+ if (minimum === void 0 || maximum === void 0) {
3416
+ throw new TypeError(
3417
+ `Plan "${plan.name}" must configure seatBilling.minimum and seatBilling.maximum when customerEditable is true.`
3418
+ );
3419
+ }
3420
+ return {
3421
+ product_id: plan.productId,
3422
+ quantity: seats,
3423
+ allow_custom_quantity: true,
3424
+ min_quantity: minimum,
3425
+ max_quantity: maximum
3426
+ };
3427
+ }
3279
3428
 
3280
3429
  // src/plugins/subscriptions/endpoints.ts
3281
3430
  var SUBSCRIPTION_MODEL6 = "subscription";
3282
3431
  var UpgradeBody = z.object({
3283
3432
  plan: z.string().min(1),
3433
+ seats: z.number().int().positive().safe().optional(),
3284
3434
  referenceId: z.string().min(1).optional(),
3285
3435
  referenceType: z.enum(["user", "organization", "custom"]).optional(),
3286
3436
  successUrl: z.string().url().optional(),
3287
3437
  failureUrl: z.string().url().optional()
3288
- });
3438
+ }).strict();
3289
3439
  var SuccessQuery = z.object({
3290
3440
  subscriptionId: z.string().min(1)
3291
3441
  });
@@ -3296,7 +3446,12 @@ var CancelBody = z.object({
3296
3446
  });
3297
3447
  var ChangePlanBody = z.object({
3298
3448
  subscriptionId: z.string().min(1),
3299
- plan: z.string().min(1)
3449
+ plan: z.string().min(1),
3450
+ seats: z.number().int().positive().safe().optional()
3451
+ }).strict();
3452
+ var UpdateSeatsBody = z.object({
3453
+ subscriptionId: z.string().min(1),
3454
+ seats: z.number().int().positive().safe()
3300
3455
  }).strict();
3301
3456
  var FreezeBody = z.object({
3302
3457
  subscriptionId: z.string().min(1),
@@ -3326,11 +3481,72 @@ function isCheckoutSubscriptionCandidate(subscription, row, productId) {
3326
3481
  return true;
3327
3482
  }
3328
3483
  if (!subscription.created_at || !(row.createdAt instanceof Date)) return false;
3329
- const createdAt = new Date(subscription.created_at).getTime();
3330
- return Number.isFinite(createdAt) && createdAt >= row.createdAt.getTime() - SUCCESS_RECONCILIATION_CLOCK_SKEW_MS;
3484
+ const createdAt = parseDate(subscription.created_at)?.getTime();
3485
+ return createdAt !== void 0 && createdAt >= row.createdAt.getTime() - SUCCESS_RECONCILIATION_CLOCK_SKEW_MS;
3331
3486
  }
3332
3487
  function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3333
3488
  const client = options.client;
3489
+ const cancelPendingChangeEndpoint = (path) => createAuthEndpoint(
3490
+ path,
3491
+ {
3492
+ method: "POST",
3493
+ body: UnfreezeBody,
3494
+ use: [sessionMiddleware]
3495
+ },
3496
+ async (ctx) => {
3497
+ const { adapter, row } = await requireConfirmedOwnedSubscription(
3498
+ ctx,
3499
+ ctx.body.subscriptionId,
3500
+ subsOptions,
3501
+ "cancel-plan-change"
3502
+ );
3503
+ try {
3504
+ const plans = await plansRef();
3505
+ const current = await client.getSubscription(row.streampaySubscriptionId);
3506
+ if (!current.pending_change) {
3507
+ await adapter.update({
3508
+ model: SUBSCRIPTION_MODEL6,
3509
+ update: {
3510
+ ...projectSubscriptionAgainstExisting(row, current),
3511
+ ...projectPlanFields(current, plans),
3512
+ pendingPlan: null,
3513
+ pendingProductId: null,
3514
+ pendingPlanEffectiveAt: null,
3515
+ pendingSeats: null,
3516
+ pendingSeatsEffectiveAt: null
3517
+ },
3518
+ where: [{ field: "id", value: row.id }]
3519
+ });
3520
+ return ctx.json({ canceled: true, reused: true, subscription: current });
3521
+ }
3522
+ await client.deletePendingSubscriptionChange(row.streampaySubscriptionId);
3523
+ const stream = await client.getSubscription(row.streampaySubscriptionId);
3524
+ await adapter.update({
3525
+ model: SUBSCRIPTION_MODEL6,
3526
+ update: {
3527
+ ...projectSubscriptionAgainstExisting(row, stream),
3528
+ ...projectPlanFields(stream, plans),
3529
+ pendingPlan: null,
3530
+ pendingProductId: null,
3531
+ pendingPlanEffectiveAt: null,
3532
+ pendingSeats: null,
3533
+ pendingSeatsEffectiveAt: null
3534
+ },
3535
+ where: [{ field: "id", value: row.id }]
3536
+ });
3537
+ return ctx.json({ canceled: true, reused: false, subscription: stream });
3538
+ } catch (err) {
3539
+ toAPIError(
3540
+ {
3541
+ logPrefix: `cancel pending subscription change failed for row=${row.id}:`,
3542
+ userMessage: "Canceling the pending subscription change failed."
3543
+ },
3544
+ err,
3545
+ getLogger(ctx)
3546
+ );
3547
+ }
3548
+ }
3549
+ );
3334
3550
  return {
3335
3551
  ...buildSubscriptionReadEndpoints(subsOptions, plansRef),
3336
3552
  upgradeSubscription: createAuthEndpoint(
@@ -3353,6 +3569,8 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3353
3569
  message: `Plan "${ctx.body.plan}" is not configured.`
3354
3570
  });
3355
3571
  }
3572
+ const seats = resolveSeatCount(plan, ctx.body.seats);
3573
+ const quotedTotal = quotedSeatTotal(plan, seats);
3356
3574
  const adapter = getAdapter2(ctx);
3357
3575
  const existingActive = await adapter.findMany({
3358
3576
  model: SUBSCRIPTION_MODEL6,
@@ -3390,6 +3608,7 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3390
3608
  candidates: existingActive,
3391
3609
  activeSlotKey,
3392
3610
  planName: plan.name,
3611
+ seats,
3393
3612
  now: Date.now(),
3394
3613
  log: getLogger(ctx),
3395
3614
  createReservation: async () => {
@@ -3409,13 +3628,14 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3409
3628
  planVersion: plan.version ?? null,
3410
3629
  productId: plan.productId,
3411
3630
  group: plan.group ?? null,
3631
+ seats,
3412
3632
  streampayConsumerId: consumerId2,
3413
3633
  streampayPaymentLinkId: null,
3414
3634
  status: "incomplete",
3415
3635
  providerStatus: null,
3416
3636
  billingStatus: "current",
3417
- amountInSmallestUnit: plan.priceInSmallestUnit,
3418
- originalAmountInSmallestUnit: plan.priceInSmallestUnit,
3637
+ amountInSmallestUnit: quotedTotal,
3638
+ originalAmountInSmallestUnit: quotedTotal,
3419
3639
  currency: plan.currency ?? "SAR",
3420
3640
  billingInterval: plan.billingInterval,
3421
3641
  billingIntervalCount: plan.billingIntervalCount ?? 1,
@@ -3431,6 +3651,8 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3431
3651
  pendingPlan: null,
3432
3652
  pendingProductId: null,
3433
3653
  pendingPlanEffectiveAt: null,
3654
+ pendingSeats: null,
3655
+ pendingSeatsEffectiveAt: null,
3434
3656
  endedAt: null,
3435
3657
  frozenAt: null,
3436
3658
  freezeEndAt: null,
@@ -3449,14 +3671,15 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3449
3671
  redirect: true,
3450
3672
  reused: true,
3451
3673
  status: reservation.row.status,
3452
- plan: reservation.row.plan
3674
+ plan: reservation.row.plan,
3675
+ seats: reservation.row.seats ?? 1
3453
3676
  });
3454
3677
  }
3455
3678
  const { row, consumerId } = reservation;
3456
3679
  const linkInput = {
3457
3680
  name: `Subscription \u2014 ${plan.name}`,
3458
3681
  currency: plan.currency ?? "SAR",
3459
- items: [{ product_id: plan.productId, quantity: 1, allow_custom_quantity: false }],
3682
+ items: [buildSeatCheckoutItem(plan, seats)],
3460
3683
  max_number_of_payments: 1,
3461
3684
  organization_consumer_id: consumerId,
3462
3685
  custom_metadata: {
@@ -3549,7 +3772,8 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3549
3772
  redirect: true,
3550
3773
  reused: false,
3551
3774
  status: "incomplete",
3552
- plan: plan.name
3775
+ plan: plan.name,
3776
+ seats
3553
3777
  });
3554
3778
  }
3555
3779
  ),
@@ -3620,6 +3844,7 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3620
3844
  model: SUBSCRIPTION_MODEL6,
3621
3845
  update: {
3622
3846
  ...projectSubscriptionFields(match),
3847
+ ...projectPlanFields(match, plans),
3623
3848
  planVersion: plan.version ?? null,
3624
3849
  productId: plan.productId,
3625
3850
  billingStatus: "current",
@@ -3731,8 +3956,14 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3731
3956
  }
3732
3957
  try {
3733
3958
  const stream = await client.getSubscription(row.streampaySubscriptionId);
3734
- const currentPlan = configuredPlanForSubscription(stream, plans);
3735
- const currentGroup = currentPlan?.group ?? row.group;
3959
+ const currentPlan = configuredPlanForSubscription(stream, plans) ?? plans.byName.get(row.plan);
3960
+ if (!currentPlan) {
3961
+ throw new APIError("BAD_REQUEST", {
3962
+ code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
3963
+ message: "The current StreamPay product is not a configured subscription plan."
3964
+ });
3965
+ }
3966
+ const currentGroup = currentPlan.group ?? row.group;
3736
3967
  if (currentGroup !== (nextPlan.group ?? null)) {
3737
3968
  throw new APIError("BAD_REQUEST", {
3738
3969
  code: $ERROR_CODES.SUBSCRIPTION_PLAN_GROUP_MISMATCH.code,
@@ -3745,27 +3976,35 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3745
3976
  message: "The subscription is scheduled to cancel. Uncancel it before scheduling a plan change."
3746
3977
  });
3747
3978
  }
3748
- const currentProductIsRequestedPlan = stream.items?.some(
3749
- (item) => subscriptionItemProductId(item) === nextPlan.productId
3979
+ const currentItem = stream.items?.find(
3980
+ (item) => subscriptionItemProductId(item) === currentPlan.productId
3750
3981
  );
3751
- if (currentProductIsRequestedPlan && !stream.pending_change) {
3982
+ const currentSeats = currentItem ? subscriptionItemQuantity(currentItem) ?? 1 : row.seats;
3983
+ const nextSeats = resolveSeatCount(nextPlan, ctx.body.seats ?? currentSeats ?? 1);
3984
+ const currentProductIsRequestedPlan = currentPlan.productId === nextPlan.productId;
3985
+ if (currentProductIsRequestedPlan && currentSeats === nextSeats && !stream.pending_change) {
3752
3986
  throw new APIError("BAD_REQUEST", {
3753
3987
  code: $ERROR_CODES.SUBSCRIPTION_ALREADY_ON_PLAN.code,
3754
- message: `Already on plan "${nextPlan.name}".`
3988
+ message: `Already on plan "${nextPlan.name}" with ${nextSeats} seats.`
3755
3989
  });
3756
3990
  }
3757
3991
  const pendingTargets = stream.pending_change?.target_items ?? [];
3758
- const pendingTargetIsRequestedPlan = pendingTargets.some(
3992
+ const pendingTarget = pendingTargets.find(
3759
3993
  (item) => subscriptionItemProductId(item) === nextPlan.productId
3760
3994
  );
3761
- if (pendingTargetIsRequestedPlan) {
3995
+ const pendingTargetMatches = Boolean(pendingTarget) && (subscriptionItemQuantity(pendingTarget) ?? 1) === nextSeats;
3996
+ if (pendingTargetMatches) {
3997
+ const effectiveAt2 = stream.pending_change?.effective_at ?? null;
3762
3998
  await adapter.update({
3763
3999
  model: SUBSCRIPTION_MODEL6,
3764
4000
  update: {
3765
4001
  ...projectSubscriptionAgainstExisting(row, stream),
3766
- pendingPlan: nextPlan.name,
3767
- pendingProductId: nextPlan.productId,
3768
- pendingPlanEffectiveAt: stream.pending_change?.effective_at ? new Date(stream.pending_change.effective_at) : null
4002
+ ...projectPlanFields(stream, plans),
4003
+ pendingPlan: currentPlan.productId === nextPlan.productId ? null : nextPlan.name,
4004
+ pendingProductId: currentPlan.productId === nextPlan.productId ? null : nextPlan.productId,
4005
+ pendingPlanEffectiveAt: currentPlan.productId !== nextPlan.productId && effectiveAt2 ? parseDate(effectiveAt2) : null,
4006
+ pendingSeats: nextSeats,
4007
+ pendingSeatsEffectiveAt: parseDate(effectiveAt2)
3769
4008
  },
3770
4009
  where: [{ field: "id", value: row.id }]
3771
4010
  });
@@ -3773,7 +4012,8 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3773
4012
  mode: "at_period_end",
3774
4013
  subscriptionId: row.id,
3775
4014
  plan: nextPlan.name,
3776
- effectiveAt: stream.pending_change?.effective_at ?? null,
4015
+ seats: nextSeats,
4016
+ effectiveAt: effectiveAt2,
3777
4017
  pendingChange: stream.pending_change,
3778
4018
  reused: true
3779
4019
  });
@@ -3785,28 +4025,36 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3785
4025
  });
3786
4026
  }
3787
4027
  const patch = {
3788
- items: [{ product_id: nextPlan.productId, quantity: 1 }],
4028
+ items: subscriptionItemsForUpdate(
4029
+ stream,
4030
+ currentPlan.productId,
4031
+ nextPlan.productId,
4032
+ nextSeats
4033
+ ),
3789
4034
  coupons: subscriptionCouponIds(stream),
3790
4035
  recurring_interval: nextPlan.billingInterval,
3791
4036
  recurring_interval_count: nextPlan.billingIntervalCount ?? 1
3792
4037
  };
3793
4038
  const result = await client.updateSubscription(row.streampaySubscriptionId, patch);
3794
- const effectiveAt = result.pending_change?.effective_at ?? result.current_period_end ?? null;
4039
+ const pending = Boolean(result.pending_change);
4040
+ const effectiveAt = result.pending_change?.effective_at ?? null;
4041
+ const planProjection = projectPlanFields(result, plans);
3795
4042
  await adapter.update({
3796
4043
  model: SUBSCRIPTION_MODEL6,
3797
4044
  update: {
3798
4045
  ...projectSubscriptionAgainstExisting(row, result),
3799
- pendingPlan: nextPlan.name,
3800
- pendingProductId: nextPlan.productId,
3801
- pendingPlanEffectiveAt: effectiveAt ? new Date(effectiveAt) : null,
4046
+ ...planProjection,
3802
4047
  updatedAt: /* @__PURE__ */ new Date()
3803
4048
  },
3804
4049
  where: [{ field: "id", value: row.id }]
3805
4050
  });
4051
+ const providerPlan = pending ? planProjection.pendingPlan ?? planProjection.plan ?? row.plan : planProjection.plan ?? row.plan;
4052
+ const providerSeats = pending ? planProjection.pendingSeats ?? nextSeats : planProjection.seats ?? row.seats ?? nextSeats;
3806
4053
  return ctx.json({
3807
- mode: "at_period_end",
4054
+ mode: pending ? "at_period_end" : "immediate",
3808
4055
  subscriptionId: row.id,
3809
- plan: nextPlan.name,
4056
+ plan: providerPlan,
4057
+ seats: providerSeats,
3810
4058
  effectiveAt,
3811
4059
  pendingChange: result.pending_change ?? null,
3812
4060
  subscription: result,
@@ -3824,11 +4072,11 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3824
4072
  }
3825
4073
  }
3826
4074
  ),
3827
- cancelSubscriptionPlanChange: createAuthEndpoint(
3828
- "/subscription/change-plan/cancel",
4075
+ updateSubscriptionSeats: createAuthEndpoint(
4076
+ "/subscription/update-seats",
3829
4077
  {
3830
4078
  method: "POST",
3831
- body: UnfreezeBody,
4079
+ body: UpdateSeatsBody,
3832
4080
  use: [sessionMiddleware]
3833
4081
  },
3834
4082
  async (ctx) => {
@@ -3836,27 +4084,107 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3836
4084
  ctx,
3837
4085
  ctx.body.subscriptionId,
3838
4086
  subsOptions,
3839
- "cancel-plan-change"
4087
+ "update-seats"
3840
4088
  );
4089
+ const plans = await plansRef();
3841
4090
  try {
3842
- await client.deletePendingSubscriptionChange(row.streampaySubscriptionId);
3843
4091
  const stream = await client.getSubscription(row.streampaySubscriptionId);
4092
+ const plan = configuredPlanForSubscription(stream, plans) ?? plans.byName.get(row.plan);
4093
+ if (!plan) {
4094
+ throw new APIError("BAD_REQUEST", {
4095
+ code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
4096
+ message: "The current StreamPay product is not a configured subscription plan."
4097
+ });
4098
+ }
4099
+ if (stream.cancel_at_period_end) {
4100
+ throw new APIError("CONFLICT", {
4101
+ code: $ERROR_CODES.SUBSCRIPTION_ALREADY_SCHEDULED_CANCEL.code,
4102
+ message: "Uncancel the subscription before scheduling a seat change."
4103
+ });
4104
+ }
4105
+ const seats = resolveSeatCount(plan, ctx.body.seats);
4106
+ const currentItem = stream.items?.find(
4107
+ (item) => subscriptionItemProductId(item) === plan.productId
4108
+ );
4109
+ const currentSeats = currentItem ? subscriptionItemQuantity(currentItem) ?? 1 : row.seats;
4110
+ const pendingTarget = stream.pending_change?.target_items?.find(
4111
+ (item) => subscriptionItemProductId(item) === plan.productId
4112
+ );
4113
+ if (stream.pending_change) {
4114
+ if (pendingTarget && (subscriptionItemQuantity(pendingTarget) ?? 1) === seats) {
4115
+ const effectiveAt2 = stream.pending_change.effective_at ?? null;
4116
+ await adapter.update({
4117
+ model: SUBSCRIPTION_MODEL6,
4118
+ update: {
4119
+ ...projectSubscriptionAgainstExisting(row, stream),
4120
+ ...projectPlanFields(stream, plans)
4121
+ },
4122
+ where: [{ field: "id", value: row.id }]
4123
+ });
4124
+ return ctx.json({
4125
+ mode: "at_period_end",
4126
+ subscriptionId: row.id,
4127
+ seats,
4128
+ effectiveAt: effectiveAt2,
4129
+ pendingChange: stream.pending_change,
4130
+ reused: true
4131
+ });
4132
+ }
4133
+ throw new APIError("CONFLICT", {
4134
+ code: $ERROR_CODES.SUBSCRIPTION_SEAT_CHANGE_ALREADY_SCHEDULED.code,
4135
+ message: "A different subscription change is pending. Cancel it before scheduling this seat count."
4136
+ });
4137
+ }
4138
+ if (currentSeats === seats) {
4139
+ await adapter.update({
4140
+ model: SUBSCRIPTION_MODEL6,
4141
+ update: {
4142
+ ...projectSubscriptionAgainstExisting(row, stream),
4143
+ ...projectPlanFields(stream, plans)
4144
+ },
4145
+ where: [{ field: "id", value: row.id }]
4146
+ });
4147
+ return ctx.json({
4148
+ mode: "current",
4149
+ subscriptionId: row.id,
4150
+ seats,
4151
+ effectiveAt: null,
4152
+ pendingChange: null,
4153
+ reused: true
4154
+ });
4155
+ }
4156
+ const patch = {
4157
+ items: subscriptionItemsForUpdate(stream, plan.productId, plan.productId, seats),
4158
+ coupons: subscriptionCouponIds(stream)
4159
+ };
4160
+ const result = await client.updateSubscription(row.streampaySubscriptionId, patch);
4161
+ const pending = Boolean(result.pending_change);
4162
+ const effectiveAt = result.pending_change?.effective_at ?? null;
4163
+ const planProjection = projectPlanFields(result, plans);
3844
4164
  await adapter.update({
3845
4165
  model: SUBSCRIPTION_MODEL6,
3846
4166
  update: {
3847
- ...projectSubscriptionAgainstExisting(row, stream),
3848
- pendingPlan: null,
3849
- pendingProductId: null,
3850
- pendingPlanEffectiveAt: null
4167
+ ...projectSubscriptionAgainstExisting(row, result),
4168
+ ...planProjection,
4169
+ updatedAt: /* @__PURE__ */ new Date()
3851
4170
  },
3852
4171
  where: [{ field: "id", value: row.id }]
3853
4172
  });
3854
- return ctx.json({ canceled: true, subscription: stream });
4173
+ const providerSeats = pending ? planProjection.pendingSeats ?? seats : planProjection.seats ?? row.seats ?? seats;
4174
+ return ctx.json({
4175
+ mode: pending ? "at_period_end" : "immediate",
4176
+ subscriptionId: row.id,
4177
+ seats: providerSeats,
4178
+ effectiveAt,
4179
+ pendingChange: result.pending_change ?? null,
4180
+ subscription: result,
4181
+ reused: false
4182
+ });
3855
4183
  } catch (err) {
3856
4184
  toAPIError(
3857
4185
  {
3858
- logPrefix: `cancel plan change failed for row=${row.id}:`,
3859
- userMessage: "Canceling the scheduled plan change failed."
4186
+ logPrefix: `update-seats failed for row=${row.id}:`,
4187
+ userMessage: "Seat change scheduling failed."
3860
4188
  },
3861
4189
  err,
3862
4190
  getLogger(ctx)
@@ -3864,6 +4192,10 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3864
4192
  }
3865
4193
  }
3866
4194
  ),
4195
+ cancelSubscriptionPlanChange: cancelPendingChangeEndpoint("/subscription/change-plan/cancel"),
4196
+ cancelSubscriptionPendingChange: cancelPendingChangeEndpoint(
4197
+ "/subscription/pending-change/cancel"
4198
+ ),
3867
4199
  uncancelSubscription: createAuthEndpoint(
3868
4200
  "/subscription/uncancel",
3869
4201
  {
@@ -3963,9 +4295,9 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3963
4295
  const freezes = await client.listSubscriptionFreezes(row.streampaySubscriptionId);
3964
4296
  const active = freezes.data?.find((freeze) => {
3965
4297
  if (!freeze.id || !freeze.freeze_start_datetime) return false;
3966
- const start = new Date(freeze.freeze_start_datetime).getTime();
3967
- const end = freeze.freeze_end_datetime ? new Date(freeze.freeze_end_datetime).getTime() : Number.POSITIVE_INFINITY;
3968
- return start <= nowMs && nowMs <= end;
4298
+ const start = parseDate(freeze.freeze_start_datetime)?.getTime();
4299
+ const end = freeze.freeze_end_datetime ? parseDate(freeze.freeze_end_datetime)?.getTime() : Number.POSITIVE_INFINITY;
4300
+ return start !== void 0 && end !== void 0 && start <= nowMs && nowMs <= end;
3969
4301
  });
3970
4302
  if (!active?.id || !active.freeze_start_datetime) {
3971
4303
  throw new APIError("BAD_REQUEST", {
@@ -4105,6 +4437,11 @@ var subscriptionTable = {
4105
4437
  required: false,
4106
4438
  index: true
4107
4439
  },
4440
+ seats: {
4441
+ type: "number",
4442
+ required: false,
4443
+ defaultValue: 1
4444
+ },
4108
4445
  amountInSmallestUnit: {
4109
4446
  type: "number",
4110
4447
  required: false
@@ -4193,6 +4530,14 @@ var subscriptionTable = {
4193
4530
  type: "date",
4194
4531
  required: false
4195
4532
  },
4533
+ pendingSeats: {
4534
+ type: "number",
4535
+ required: false
4536
+ },
4537
+ pendingSeatsEffectiveAt: {
4538
+ type: "date",
4539
+ required: false
4540
+ },
4196
4541
  endedAt: {
4197
4542
  type: "date",
4198
4543
  required: false
@@ -4327,13 +4672,13 @@ function subscriptions(subsOptions) {
4327
4672
  }
4328
4673
  const dedupeEnabled = subsOptions.enableWebhookEventTable !== false;
4329
4674
  return (options, registry) => {
4330
- const resolvePlans = createPlanResolver(subsOptions.plans);
4675
+ const plansRef = () => resolvePlans(subsOptions.plans);
4331
4676
  if (registry) {
4332
4677
  registry.subscriptionWebhookSync = async (ctx, payload, meta) => {
4333
4678
  const syncCtx = {
4334
4679
  context: ctx.context
4335
4680
  };
4336
- const plans = await resolvePlans();
4681
+ const plans = await plansRef();
4337
4682
  try {
4338
4683
  await syncWebhookPayload(syncCtx, payload, options.client, plans, subsOptions, {
4339
4684
  dedupe: dedupeEnabled,
@@ -4389,7 +4734,7 @@ function subscriptions(subsOptions) {
4389
4734
  });
4390
4735
  }
4391
4736
  const payload = parsedPayload;
4392
- const plans = await resolvePlans();
4737
+ const plans = await plansRef();
4393
4738
  const claimed = await claimWebhookEventForReplay(syncCtx, row);
4394
4739
  if (!claimed?.lockedBy) {
4395
4740
  throw new APIError("CONFLICT", {
@@ -4426,7 +4771,7 @@ function subscriptions(subsOptions) {
4426
4771
  ...dedupeEnabled ? webhookEventTable : {}
4427
4772
  };
4428
4773
  return {
4429
- endpoints: buildSubscriptionEndpoints(options, subsOptions, resolvePlans),
4774
+ endpoints: buildSubscriptionEndpoints(options, subsOptions, plansRef),
4430
4775
  schema
4431
4776
  };
4432
4777
  };
@@ -4791,7 +5136,7 @@ var onUserDelete = (options) => async (user, context) => {
4791
5136
 
4792
5137
  // package.json
4793
5138
  var package_default = {
4794
- version: "2.1.0"};
5139
+ version: "2.2.1"};
4795
5140
 
4796
5141
  // src/version.ts
4797
5142
  var version = package_default.version;