better-auth-streampay 2.0.0 → 2.2.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
@@ -20,6 +20,8 @@ var $ERROR_CODES = defineErrorCodes({
20
20
  FORBIDDEN: "You do not have permission to perform this action.",
21
21
  NOT_FOUND: "The requested resource was not found.",
22
22
  CONSUMER_DUPLICATE: "A consumer with one of the provided identifiers already exists.",
23
+ STREAMPAY_CONSUMER_LINK_CONFLICT: "This StreamPay consumer is already linked to another account.",
24
+ STREAMPAY_CONSUMER_LINK_WRITE_FAILED: "The StreamPay consumer link could not be saved.",
23
25
  CONSUMER_HAS_ONGOING_ACTIVITY: "The consumer has ongoing invoices or active subscriptions and cannot be modified.",
24
26
  INVOICE_INVALID_STATE: "The invoice is in a state that forbids this action.",
25
27
  PAYMENT_DUPLICATE: "A payment with the same information already exists.",
@@ -31,6 +33,7 @@ var $ERROR_CODES = defineErrorCodes({
31
33
  PAYMENT_METHOD_INVALID: "The supplied payment method is invalid for this flow.",
32
34
  PRODUCT_LOCKED: "The product is referenced by a finalized invoice and cannot be modified.",
33
35
  COUPON_LOCKED: "The coupon is referenced by a finalized invoice and cannot be modified.",
36
+ CHECKOUT_CLIENT_FIELDS_FORBIDDEN: "Checkout fields must be resolved by the server.",
34
37
  SUBSCRIPTION_NOT_FOUND: "The subscription does not exist.",
35
38
  SUBSCRIPTION_PLAN_NOT_FOUND: "The requested subscription plan is not configured.",
36
39
  SUBSCRIPTION_ALREADY_ACTIVE: "An active subscription already exists for this plan group.",
@@ -40,6 +43,8 @@ var $ERROR_CODES = defineErrorCodes({
40
43
  SUBSCRIPTION_EXPIRED: "The subscription has expired.",
41
44
  SUBSCRIPTION_ALREADY_SCHEDULED_CANCEL: "The subscription is already scheduled to cancel at period end.",
42
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.",
43
48
  SUBSCRIPTION_IMMEDIATE_CANCEL_UNSUPPORTED: "StreamPay does not support immediate cancellation for active subscriptions.",
44
49
  SUBSCRIPTION_PERIOD_END_CANCEL_UNSUPPORTED: "StreamPay only supports period-end cancellation for active subscriptions.",
45
50
  SUBSCRIPTION_PLAN_GROUP_MISMATCH: "Subscription plan changes must stay within the same configured plan group.",
@@ -342,12 +347,17 @@ async function ensureConsumerForUser(options, ctx, user) {
342
347
  if (isDuplicateConsumerError(err)) {
343
348
  const reusedId = await resolveDuplicateConsumer(options, payload, ctx);
344
349
  if (reusedId) {
350
+ await assertConsumerUnclaimed(ctx, reusedId, user.id);
345
351
  try {
346
352
  await options.client.updateConsumer(reusedId, { external_id: user.id });
347
353
  } catch (backfillErr) {
348
354
  getLogger(ctx).error(
349
355
  `consumer external_id backfill failed for user=${user.id} consumer=${reusedId}: ${formatStreamPayError(backfillErr)}`
350
356
  );
357
+ throw new APIError("INTERNAL_SERVER_ERROR", {
358
+ code: "STREAMPAY_CONSUMER_LINK_WRITE_FAILED",
359
+ message: "StreamPay consumer linking failed. Please try again."
360
+ });
351
361
  }
352
362
  await persistConsumerId(ctx, user.id, reusedId);
353
363
  return { consumerId: reusedId, created: false };
@@ -361,7 +371,40 @@ async function ensureConsumerForUser(options, ctx, user) {
361
371
  });
362
372
  }
363
373
  }
374
+ function consumerLinkUnavailable() {
375
+ return new APIError("INTERNAL_SERVER_ERROR", {
376
+ code: "STREAMPAY_CONSUMER_LINK_WRITE_FAILED",
377
+ message: "StreamPay consumer linking failed. Please try again."
378
+ });
379
+ }
380
+ async function findConsumerOwner(ctx, consumerId) {
381
+ try {
382
+ return await ctx.context.adapter.findOne({
383
+ model: "user",
384
+ where: [{ field: "streampayConsumerId", value: consumerId }]
385
+ });
386
+ } catch (err) {
387
+ getLogger(ctx).error(
388
+ `consumer ownership check failed for consumer=${consumerId}: ${formatStreamPayError(err)}`
389
+ );
390
+ throw consumerLinkUnavailable();
391
+ }
392
+ }
393
+ async function assertConsumerUnclaimed(ctx, consumerId, userId) {
394
+ const owner = await findConsumerOwner(ctx, consumerId);
395
+ if (!owner) return;
396
+ if (typeof owner.id !== "string") {
397
+ getLogger(ctx).error(`consumer ownership check returned a user without an id: ${consumerId}`);
398
+ throw consumerLinkUnavailable();
399
+ }
400
+ if (owner.id === userId) return;
401
+ throw new APIError("CONFLICT", {
402
+ code: "STREAMPAY_CONSUMER_LINK_CONFLICT",
403
+ message: "This StreamPay consumer is already linked to another account."
404
+ });
405
+ }
364
406
  async function persistConsumerId(ctx, userId, consumerId) {
407
+ await assertConsumerUnclaimed(ctx, consumerId, userId);
365
408
  try {
366
409
  await ctx.context.internalAdapter.updateUser(userId, {
367
410
  streampayConsumerId: consumerId
@@ -370,6 +413,8 @@ async function persistConsumerId(ctx, userId, consumerId) {
370
413
  getLogger(ctx).error(
371
414
  `consumer link write failed for user=${userId}: ${formatStreamPayError(err)}`
372
415
  );
416
+ await assertConsumerUnclaimed(ctx, consumerId, userId);
417
+ throw consumerLinkUnavailable();
373
418
  }
374
419
  }
375
420
 
@@ -627,7 +672,8 @@ function projectSubscriptionFields(sub) {
627
672
  }
628
673
  function parseDate(value) {
629
674
  if (!value) return null;
630
- 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);
631
677
  return Number.isNaN(date.getTime()) ? null : date;
632
678
  }
633
679
  function minorUnitExponent(currency) {
@@ -666,13 +712,19 @@ function amountToSmallestUnit(value, currency) {
666
712
  }
667
713
  var SubscriptionItemSchema = z.object({
668
714
  product: z.object({ id: z.string() }).passthrough().optional(),
669
- product_id: z.string().optional()
715
+ product_id: z.string().optional(),
716
+ quantity: z.number().optional()
670
717
  }).passthrough();
671
718
  function subscriptionItemProductId(item) {
672
719
  const parsed = SubscriptionItemSchema.safeParse(item);
673
720
  if (!parsed.success) return null;
674
721
  return parsed.data.product?.id ?? parsed.data.product_id ?? null;
675
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
+ }
676
728
  function inferPlanFromItems(sub, plans) {
677
729
  if (!Array.isArray(sub.items)) return null;
678
730
  return inferPlanFromItemList(sub.items, plans);
@@ -681,14 +733,32 @@ function inferPlanFromItemList(items, plans) {
681
733
  const productIds = new Set(
682
734
  items.map(subscriptionItemProductId).filter((id) => Boolean(id))
683
735
  );
684
- 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;
685
744
  }
686
745
  function projectPlanFields(sub, plans) {
687
746
  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
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);
692
762
  return {
693
763
  ...currentPlan ? {
694
764
  plan: currentPlan,
@@ -696,9 +766,12 @@ function projectPlanFields(sub, plans) {
696
766
  productId: currentProductId,
697
767
  group: configuredCurrent?.group ?? null
698
768
  } : currentProductId ? { productId: currentProductId } : {},
699
- pendingPlan,
700
- pendingProductId,
701
- 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
702
775
  };
703
776
  }
704
777
  function subscriptionSlotKey(referenceType, referenceId, group) {
@@ -2357,15 +2430,15 @@ var admin = (adminOptions = {}) => (options, registry) => {
2357
2430
  var RelativeOrAbsoluteUrl = z.string().refine((val) => val.startsWith("/") || URL.canParse(val), {
2358
2431
  message: "Must be a valid URL or a relative path starting with /"
2359
2432
  });
2360
- var CheckoutBody = z.object({
2433
+ var CheckoutRequestBody = z.object({
2361
2434
  products: z.union([
2362
2435
  z.array(
2363
2436
  z.object({
2364
2437
  productId: z.string().uuid(),
2365
2438
  quantity: z.number().int().positive().optional()
2366
2439
  })
2367
- ).nonempty("`products` must contain at least one item."),
2368
- z.array(z.string().uuid()).nonempty("`products` must contain at least one item."),
2440
+ ).min(1, "`products` must contain at least one item."),
2441
+ z.array(z.string().uuid()).min(1, "`products` must contain at least one item."),
2369
2442
  z.string().uuid()
2370
2443
  ]).optional(),
2371
2444
  slug: z.string().optional(),
@@ -2379,10 +2452,26 @@ var CheckoutBody = z.object({
2379
2452
  validUntil: z.string().datetime().optional(),
2380
2453
  couponIds: z.array(z.string().uuid()).optional(),
2381
2454
  redirect: z.coerce.boolean().optional()
2382
- }).refine((data) => data.slug !== void 0 || data.products !== void 0, {
2383
- message: "Either `slug` or `products` is required.",
2384
- path: ["products"]
2385
2455
  });
2456
+ var CheckoutBody = CheckoutRequestBody.refine(
2457
+ (data) => data.slug !== void 0 || data.products !== void 0,
2458
+ {
2459
+ message: "Either `slug` or `products` is required.",
2460
+ path: ["products"]
2461
+ }
2462
+ );
2463
+ var SERVER_ONLY_CHECKOUT_FIELDS = [
2464
+ "products",
2465
+ "slug",
2466
+ "name",
2467
+ "description",
2468
+ "metadata",
2469
+ "successUrl",
2470
+ "failureUrl",
2471
+ "maxNumberOfPayments",
2472
+ "validUntil",
2473
+ "couponIds"
2474
+ ];
2386
2475
  function buildItem(productId, quantity) {
2387
2476
  return {
2388
2477
  product_id: productId,
@@ -2407,6 +2496,69 @@ async function resolveProducts(body, options) {
2407
2496
  (entry) => typeof entry === "string" ? buildItem(entry, 1) : buildItem(entry.productId, entry.quantity ?? 1)
2408
2497
  );
2409
2498
  }
2499
+ function rejectUntrustedClientFields(body) {
2500
+ const supplied = SERVER_ONLY_CHECKOUT_FIELDS.filter(
2501
+ (field) => Object.hasOwn(body, field) && body[field] !== void 0
2502
+ );
2503
+ if (supplied.length === 0) return;
2504
+ throw new APIError("BAD_REQUEST", {
2505
+ code: "CHECKOUT_CLIENT_FIELDS_FORBIDDEN",
2506
+ message: "Checkout product and payment fields must be resolved by the server."
2507
+ });
2508
+ }
2509
+ function mergeCheckoutOverrides(body, overrides) {
2510
+ const effective = { ...body };
2511
+ if (overrides.products !== void 0) {
2512
+ effective.products = overrides.products;
2513
+ delete effective.slug;
2514
+ }
2515
+ if (overrides.name !== void 0) effective.name = overrides.name;
2516
+ if (overrides.description !== void 0) effective.description = overrides.description;
2517
+ if (overrides.successUrl !== void 0) effective.successUrl = overrides.successUrl;
2518
+ if (overrides.failureUrl !== void 0) effective.failureUrl = overrides.failureUrl;
2519
+ if (overrides.maxNumberOfPayments !== void 0) {
2520
+ effective.maxNumberOfPayments = overrides.maxNumberOfPayments;
2521
+ }
2522
+ if (overrides.validUntil !== void 0) effective.validUntil = overrides.validUntil;
2523
+ if (overrides.couponIds !== void 0) effective.couponIds = overrides.couponIds;
2524
+ if (overrides.referenceId !== void 0) effective.referenceId = overrides.referenceId;
2525
+ if (overrides.metadata !== void 0) {
2526
+ effective.metadata = { ...body.metadata ?? {}, ...overrides.metadata };
2527
+ }
2528
+ return effective;
2529
+ }
2530
+ function validateEffectiveCheckout(body, logger2) {
2531
+ const parsed = CheckoutBody.safeParse(body);
2532
+ if (parsed.success) return parsed.data;
2533
+ const invalidPaths = [
2534
+ ...new Set(
2535
+ parsed.error.issues.map((issue) => issue.path.length > 0 ? issue.path.join(".") : "<root>")
2536
+ )
2537
+ ].join(", ");
2538
+ logger2.error(`resolved checkout validation failed at: ${invalidPaths}`);
2539
+ throw new APIError("INTERNAL_SERVER_ERROR", {
2540
+ message: "Checkout resolution produced invalid parameters."
2541
+ });
2542
+ }
2543
+ function checkoutUser(rawUser, user) {
2544
+ if (!user || rawUser === null || typeof rawUser !== "object") return null;
2545
+ return { ...rawUser, ...user };
2546
+ }
2547
+ async function deactivatePaymentLinkBestEffort(client, paymentLinkId, logger2) {
2548
+ if (!client.updatePaymentLinkStatus) {
2549
+ logger2.error(
2550
+ `checkout compensation unavailable for payment_link=${paymentLinkId}: client does not implement updatePaymentLinkStatus`
2551
+ );
2552
+ return;
2553
+ }
2554
+ try {
2555
+ await client.updatePaymentLinkStatus(paymentLinkId, { status: "INACTIVE" });
2556
+ } catch (err) {
2557
+ logger2.error(
2558
+ `checkout compensation failed for payment_link=${paymentLinkId}: ${formatStreamPayError(err)}`
2559
+ );
2560
+ }
2561
+ }
2410
2562
  function resolveRedirectUrl(urlOrPath, request, baseURL) {
2411
2563
  if (!urlOrPath) return void 0;
2412
2564
  return new URL(urlOrPath, request?.url ?? baseURL).toString();
@@ -2416,99 +2568,157 @@ async function resolveConsumerId(options, ctx, user) {
2416
2568
  const { consumerId } = await ensureConsumerForUser(options, ctx, user);
2417
2569
  return consumerId;
2418
2570
  }
2419
- var checkout = (checkoutOptions = {}) => (options) => {
2420
- const client = options.client;
2421
- return {
2422
- endpoints: {
2423
- checkout: createAuthEndpoint(
2424
- "/checkout",
2425
- {
2426
- method: "POST",
2427
- body: CheckoutBody
2428
- },
2429
- async (ctx) => {
2430
- const session = await getSessionFromCtx(ctx);
2431
- const sessionUser = asSessionUser(session?.user);
2432
- if (checkoutOptions.authenticatedUsersOnly) {
2433
- if (!sessionUser) {
2434
- throw new APIError("UNAUTHORIZED", {
2435
- message: "You must be logged in to checkout."
2436
- });
2571
+ var checkout = (checkoutOptions = {}) => {
2572
+ return (options) => {
2573
+ const client = options.client;
2574
+ return {
2575
+ endpoints: {
2576
+ checkout: createAuthEndpoint(
2577
+ "/checkout",
2578
+ {
2579
+ method: "POST",
2580
+ body: checkoutOptions.resolveCheckout ? CheckoutRequestBody : CheckoutBody
2581
+ },
2582
+ async (ctx) => {
2583
+ const session = await getSessionFromCtx(ctx);
2584
+ const sessionUser = asSessionUser(session?.user);
2585
+ const user = checkoutUser(session?.user, sessionUser);
2586
+ if (checkoutOptions.authenticatedUsersOnly) {
2587
+ if (!sessionUser) {
2588
+ throw new APIError("UNAUTHORIZED", {
2589
+ message: "You must be logged in to checkout."
2590
+ });
2591
+ }
2592
+ if (sessionUser.isAnonymous) {
2593
+ throw new APIError("UNAUTHORIZED", {
2594
+ message: "Anonymous users cannot checkout."
2595
+ });
2596
+ }
2437
2597
  }
2438
- if (sessionUser.isAnonymous) {
2439
- throw new APIError("UNAUTHORIZED", {
2440
- message: "Anonymous users cannot checkout."
2441
- });
2598
+ if (checkoutOptions.resolveCheckout) {
2599
+ rejectUntrustedClientFields(ctx.body);
2442
2600
  }
2443
- }
2444
- const items = await resolveProducts(ctx.body, checkoutOptions);
2445
- const consumerId = await resolveConsumerId(options, ctx, sessionUser);
2446
- const successUrl = resolveRedirectUrl(
2447
- ctx.body.successUrl ?? checkoutOptions.successUrl,
2448
- ctx.request,
2449
- ctx.context.baseURL
2450
- );
2451
- const failureUrl = resolveRedirectUrl(
2452
- ctx.body.failureUrl ?? checkoutOptions.failureUrl,
2453
- ctx.request,
2454
- ctx.context.baseURL
2455
- );
2456
- const customMetadata = (() => {
2457
- const base = ctx.body.metadata ?? {};
2458
- const merged = ctx.body.referenceId ? { referenceId: ctx.body.referenceId, ...base } : base;
2459
- return Object.keys(merged).length > 0 ? merged : null;
2460
- })();
2461
- const payload = {
2462
- name: ctx.body.name ?? `Checkout ${(/* @__PURE__ */ new Date()).toISOString()}`,
2463
- description: ctx.body.description ?? null,
2464
- currency: checkoutOptions.currency ?? "SAR",
2465
- items
2466
- };
2467
- if (consumerId !== null) payload.organization_consumer_id = consumerId;
2468
- if (successUrl) payload.success_redirect_url = successUrl;
2469
- if (failureUrl) payload.failure_redirect_url = failureUrl;
2470
- if (ctx.body.maxNumberOfPayments !== void 0) {
2471
- payload.max_number_of_payments = ctx.body.maxNumberOfPayments;
2472
- }
2473
- if (ctx.body.validUntil !== void 0) {
2474
- payload.valid_until = ctx.body.validUntil;
2475
- }
2476
- if (ctx.body.couponIds && ctx.body.couponIds.length > 0) {
2477
- payload.coupons = ctx.body.couponIds;
2478
- }
2479
- if (customMetadata !== null) payload.custom_metadata = customMetadata;
2480
- if (checkoutOptions.customFields) {
2481
- payload.custom_fields = checkoutOptions.customFields;
2482
- }
2483
- if (checkoutOptions.contactInformationType) {
2484
- payload.contact_information_type = checkoutOptions.contactInformationType;
2485
- }
2486
- try {
2487
- const link = await client.createPaymentLink(payload);
2488
- const url = client.getPaymentUrl(link);
2489
- if (!url) {
2490
- throw new APIError("INTERNAL_SERVER_ERROR", {
2491
- message: "StreamPay payment link created but no URL was returned."
2492
- });
2601
+ let effective = ctx.body;
2602
+ if (checkoutOptions.resolveCheckout) {
2603
+ let overrides;
2604
+ try {
2605
+ overrides = await checkoutOptions.resolveCheckout({ user, body: ctx.body }, ctx);
2606
+ } catch (err) {
2607
+ if (err instanceof APIError) throw err;
2608
+ getLogger(ctx).error(`resolveCheckout failed: ${formatStreamPayError(err)}`);
2609
+ throw new APIError("INTERNAL_SERVER_ERROR", {
2610
+ message: "Checkout resolution failed."
2611
+ });
2612
+ }
2613
+ effective = mergeCheckoutOverrides(ctx.body, overrides);
2493
2614
  }
2494
- return ctx.json({
2495
- url,
2496
- id: link.id ?? null,
2497
- redirect: ctx.body.redirect ?? true
2498
- });
2499
- } catch (err) {
2500
- toAPIError(
2501
- {
2502
- logPrefix: "checkout creation failed:",
2503
- userMessage: "StreamPay checkout creation failed."
2504
- },
2505
- err,
2506
- getLogger(ctx)
2615
+ effective = validateEffectiveCheckout(effective, getLogger(ctx));
2616
+ const items = await resolveProducts(effective, checkoutOptions);
2617
+ const consumerId = await resolveConsumerId(options, ctx, sessionUser);
2618
+ const successUrl = resolveRedirectUrl(
2619
+ effective.successUrl ?? checkoutOptions.successUrl,
2620
+ ctx.request,
2621
+ ctx.context.baseURL
2622
+ );
2623
+ const failureUrl = resolveRedirectUrl(
2624
+ effective.failureUrl ?? checkoutOptions.failureUrl,
2625
+ ctx.request,
2626
+ ctx.context.baseURL
2507
2627
  );
2628
+ const customMetadata = (() => {
2629
+ const merged = { ...effective.metadata ?? {} };
2630
+ if (effective.referenceId !== void 0) {
2631
+ merged.referenceId = effective.referenceId;
2632
+ }
2633
+ return Object.keys(merged).length > 0 ? merged : null;
2634
+ })();
2635
+ const payload = {
2636
+ name: effective.name ?? `Checkout ${(/* @__PURE__ */ new Date()).toISOString()}`,
2637
+ description: effective.description ?? null,
2638
+ currency: checkoutOptions.currency ?? "SAR",
2639
+ items
2640
+ };
2641
+ if (consumerId !== null) payload.organization_consumer_id = consumerId;
2642
+ if (successUrl) payload.success_redirect_url = successUrl;
2643
+ if (failureUrl) payload.failure_redirect_url = failureUrl;
2644
+ if (effective.maxNumberOfPayments !== void 0) {
2645
+ payload.max_number_of_payments = effective.maxNumberOfPayments;
2646
+ }
2647
+ if (effective.validUntil !== void 0) {
2648
+ payload.valid_until = effective.validUntil;
2649
+ }
2650
+ if (effective.couponIds && effective.couponIds.length > 0) {
2651
+ payload.coupons = effective.couponIds;
2652
+ }
2653
+ if (customMetadata !== null) payload.custom_metadata = customMetadata;
2654
+ if (checkoutOptions.customFields) {
2655
+ payload.custom_fields = checkoutOptions.customFields;
2656
+ }
2657
+ if (checkoutOptions.contactInformationType) {
2658
+ payload.contact_information_type = checkoutOptions.contactInformationType;
2659
+ }
2660
+ try {
2661
+ const link = await client.createPaymentLink(payload);
2662
+ const paymentLinkId = typeof link.id === "string" && link.id.length > 0 ? link.id : null;
2663
+ let url;
2664
+ try {
2665
+ const resolvedUrl = client.getPaymentUrl(link);
2666
+ if (!resolvedUrl) {
2667
+ throw new APIError("INTERNAL_SERVER_ERROR", {
2668
+ message: "StreamPay payment link created but no URL was returned."
2669
+ });
2670
+ }
2671
+ url = resolvedUrl;
2672
+ if (checkoutOptions.onCheckoutCreated) {
2673
+ if (!paymentLinkId) {
2674
+ throw new APIError("INTERNAL_SERVER_ERROR", {
2675
+ message: "StreamPay payment link created but no id was returned."
2676
+ });
2677
+ }
2678
+ try {
2679
+ const callbackData = {
2680
+ user,
2681
+ paymentLinkId,
2682
+ url,
2683
+ payload
2684
+ };
2685
+ if (effective.referenceId !== void 0) {
2686
+ callbackData.referenceId = effective.referenceId;
2687
+ }
2688
+ await checkoutOptions.onCheckoutCreated(callbackData, ctx);
2689
+ } catch (err) {
2690
+ if (err instanceof APIError) throw err;
2691
+ getLogger(ctx).error(`onCheckoutCreated failed: ${formatStreamPayError(err)}`);
2692
+ throw new APIError("INTERNAL_SERVER_ERROR", {
2693
+ message: "Checkout persistence failed."
2694
+ });
2695
+ }
2696
+ }
2697
+ } catch (err) {
2698
+ if (paymentLinkId) {
2699
+ await deactivatePaymentLinkBestEffort(client, paymentLinkId, getLogger(ctx));
2700
+ }
2701
+ throw err;
2702
+ }
2703
+ return ctx.json({
2704
+ url,
2705
+ id: paymentLinkId,
2706
+ redirect: ctx.body.redirect ?? true
2707
+ });
2708
+ } catch (err) {
2709
+ toAPIError(
2710
+ {
2711
+ logPrefix: "checkout creation failed:",
2712
+ userMessage: "StreamPay checkout creation failed."
2713
+ },
2714
+ err,
2715
+ getLogger(ctx)
2716
+ );
2717
+ }
2508
2718
  }
2509
- }
2510
- )
2511
- }
2719
+ )
2720
+ }
2721
+ };
2512
2722
  };
2513
2723
  };
2514
2724
  var DEFAULT_PAGE_SIZE = 100;
@@ -2762,9 +2972,10 @@ function checkoutInProgressError() {
2762
2972
  });
2763
2973
  }
2764
2974
  async function resumeOrReserveCheckoutSlot(args) {
2765
- 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;
2766
2977
  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
2978
+ (row2) => matchesCheckout(row2) && row2.status === "incomplete" && Boolean(row2.streampayPaymentLinkId) && row2.createdAt instanceof Date && now - row2.createdAt.getTime() < UPGRADE_IDEMPOTENCY_WINDOW_MS
2768
2979
  );
2769
2980
  if (reuseCandidate) {
2770
2981
  let recovery;
@@ -2803,21 +3014,23 @@ async function resumeOrReserveCheckoutSlot(args) {
2803
3014
  where: [{ field: "activeSlotKey", value: activeSlotKey }]
2804
3015
  });
2805
3016
  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 };
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
+ }
2821
3034
  }
2822
3035
  const reservationIsStale = !(reserved.createdAt instanceof Date) || now - reserved.createdAt.getTime() >= UPGRADE_IDEMPOTENCY_WINDOW_MS;
2823
3036
  if (!reservationIsStale) throw checkoutInProgressError();
@@ -2843,24 +3056,67 @@ async function resumeOrReserveCheckoutSlot(args) {
2843
3056
  }
2844
3057
  return { kind: "reserved", row, consumerId };
2845
3058
  }
2846
-
2847
- // src/plugins/subscriptions/lifecycle.ts
2848
3059
  function isAlreadyCanceledFreezeError(err) {
2849
3060
  const sdkError = readSdkErrorFields(err);
2850
3061
  const envelope = readEnvelope(sdkError.body);
2851
3062
  return sdkError.status === 403 && envelope?.code === "STREAM_ERROR" && envelope.additionalInfo === "Cannot delete non-latest freeze entry.";
2852
3063
  }
2853
3064
  function subscriptionCouponIds(stream) {
3065
+ return couponIdsFromMetadata(stream.coupon_calculation_metadata);
3066
+ }
3067
+ function couponIdsFromMetadata(metadata) {
2854
3068
  const coupons = [];
2855
- for (const coupon of stream.coupon_calculation_metadata?.coupons ?? []) {
3069
+ for (const coupon of metadata?.coupons ?? []) {
2856
3070
  if (coupon.coupon_id) coupons.push(coupon.coupon_id);
2857
3071
  }
2858
3072
  return coupons;
2859
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
+ }
2860
3110
  function configuredPlanForSubscription(subscription, plans) {
2861
- return plans.list.find(
3111
+ const matches = plans.list.filter(
2862
3112
  (plan) => subscription.items?.some((item) => subscriptionItemProductId(item) === plan.productId)
2863
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];
2864
3120
  }
2865
3121
  var SUBSCRIPTION_INTERVALS = ["WEEK", "MONTH", "QUARTER", "YEAR"];
2866
3122
  var PlanSchema = z.object({
@@ -2883,7 +3139,46 @@ var PlanSchema = z.object({
2883
3139
  message: "has invalid `trialPeriodDays` \u2014 must be an integer from 1 to 365."
2884
3140
  }).optional(),
2885
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(),
2886
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
+ }
2887
3182
  });
2888
3183
  var PlansSchema = z.array(PlanSchema).nonempty("`plans` resolved to an empty list. Provide at least one plan.").superRefine((plans, ctx) => {
2889
3184
  const seenNames = /* @__PURE__ */ new Set();
@@ -2987,6 +3282,15 @@ var CheckLimitQuery = z.object({
2987
3282
  count: z.coerce.number().int().min(0),
2988
3283
  group: z.string().min(1).optional()
2989
3284
  });
3285
+ function presentSubscription(row, plans) {
3286
+ return {
3287
+ ...row,
3288
+ // The column is nullable during safe rolling migrations. Keep the public
3289
+ // contract stable while applications backfill legacy rows to one seat.
3290
+ seats: row.seats ?? 1,
3291
+ plan: plans.byName.get(row.plan) ?? null
3292
+ };
3293
+ }
2990
3294
  async function resolveLiveSubscription(ctx, query, subsOptions, accessStatuses) {
2991
3295
  const user = requireUser(ctx);
2992
3296
  const reference = resolveReference(user, query);
@@ -3037,12 +3341,7 @@ function buildSubscriptionReadEndpoints(subsOptions, plansRef) {
3037
3341
  ]
3038
3342
  });
3039
3343
  const plans = await plansRef();
3040
- return ctx.json(
3041
- rows.map((row) => ({
3042
- ...row,
3043
- plan: plans.byName.get(row.plan) ?? null
3044
- }))
3045
- );
3344
+ return ctx.json(rows.map((row) => presentSubscription(row, plans)));
3046
3345
  }
3047
3346
  ),
3048
3347
  currentSubscription: createAuthEndpoint(
@@ -3061,7 +3360,7 @@ function buildSubscriptionReadEndpoints(subsOptions, plansRef) {
3061
3360
  );
3062
3361
  if (!live) return ctx.json(null);
3063
3362
  const plans = await plansRef();
3064
- return ctx.json({ ...live, plan: plans.byName.get(live.plan) ?? null });
3363
+ return ctx.json(presentSubscription(live, plans));
3065
3364
  }
3066
3365
  ),
3067
3366
  hasSubscriptionFeature: createAuthEndpoint(
@@ -3096,16 +3395,63 @@ function buildSubscriptionReadEndpoints(subsOptions, plansRef) {
3096
3395
  )
3097
3396
  };
3098
3397
  }
3398
+ function resolveSeatCount(plan, requested) {
3399
+ const seats = requested ?? plan.seatBilling?.default ?? plan.seatBilling?.minimum ?? 1;
3400
+ const minimum = plan.seatBilling?.minimum ?? 1;
3401
+ const maximum = plan.seatBilling?.maximum;
3402
+ if (!Number.isSafeInteger(seats) || seats < minimum || maximum !== void 0 && seats > maximum) {
3403
+ const range = maximum === void 0 ? `${minimum} or more` : `${minimum}\u2013${maximum}`;
3404
+ throw new APIError("BAD_REQUEST", {
3405
+ code: $ERROR_CODES.SUBSCRIPTION_SEAT_COUNT_INVALID.code,
3406
+ message: `Plan "${plan.name}" requires a safe-integer seat count in the range ${range}.`
3407
+ });
3408
+ }
3409
+ return seats;
3410
+ }
3411
+ function quotedSeatTotal(plan, seats) {
3412
+ const total = plan.priceInSmallestUnit * seats;
3413
+ if (!Number.isSafeInteger(total)) {
3414
+ throw new APIError("BAD_REQUEST", {
3415
+ code: $ERROR_CODES.SUBSCRIPTION_SEAT_COUNT_INVALID.code,
3416
+ message: `The quoted total for ${seats} seats exceeds JavaScript's safe-integer range.`
3417
+ });
3418
+ }
3419
+ return total;
3420
+ }
3421
+ function buildSeatCheckoutItem(plan, seats) {
3422
+ if (!plan.seatBilling?.customerEditable) {
3423
+ return {
3424
+ product_id: plan.productId,
3425
+ quantity: seats,
3426
+ allow_custom_quantity: false
3427
+ };
3428
+ }
3429
+ const minimum = plan.seatBilling.minimum;
3430
+ const maximum = plan.seatBilling.maximum;
3431
+ if (minimum === void 0 || maximum === void 0) {
3432
+ throw new TypeError(
3433
+ `Plan "${plan.name}" must configure seatBilling.minimum and seatBilling.maximum when customerEditable is true.`
3434
+ );
3435
+ }
3436
+ return {
3437
+ product_id: plan.productId,
3438
+ quantity: seats,
3439
+ allow_custom_quantity: true,
3440
+ min_quantity: minimum,
3441
+ max_quantity: maximum
3442
+ };
3443
+ }
3099
3444
 
3100
3445
  // src/plugins/subscriptions/endpoints.ts
3101
3446
  var SUBSCRIPTION_MODEL6 = "subscription";
3102
3447
  var UpgradeBody = z.object({
3103
3448
  plan: z.string().min(1),
3449
+ seats: z.number().int().positive().safe().optional(),
3104
3450
  referenceId: z.string().min(1).optional(),
3105
3451
  referenceType: z.enum(["user", "organization", "custom"]).optional(),
3106
3452
  successUrl: z.string().url().optional(),
3107
3453
  failureUrl: z.string().url().optional()
3108
- });
3454
+ }).strict();
3109
3455
  var SuccessQuery = z.object({
3110
3456
  subscriptionId: z.string().min(1)
3111
3457
  });
@@ -3116,7 +3462,12 @@ var CancelBody = z.object({
3116
3462
  });
3117
3463
  var ChangePlanBody = z.object({
3118
3464
  subscriptionId: z.string().min(1),
3119
- plan: z.string().min(1)
3465
+ plan: z.string().min(1),
3466
+ seats: z.number().int().positive().safe().optional()
3467
+ }).strict();
3468
+ var UpdateSeatsBody = z.object({
3469
+ subscriptionId: z.string().min(1),
3470
+ seats: z.number().int().positive().safe()
3120
3471
  }).strict();
3121
3472
  var FreezeBody = z.object({
3122
3473
  subscriptionId: z.string().min(1),
@@ -3146,11 +3497,72 @@ function isCheckoutSubscriptionCandidate(subscription, row, productId) {
3146
3497
  return true;
3147
3498
  }
3148
3499
  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;
3500
+ const createdAt = parseDate(subscription.created_at)?.getTime();
3501
+ return createdAt !== void 0 && createdAt >= row.createdAt.getTime() - SUCCESS_RECONCILIATION_CLOCK_SKEW_MS;
3151
3502
  }
3152
3503
  function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3153
3504
  const client = options.client;
3505
+ const cancelPendingChangeEndpoint = (path) => createAuthEndpoint(
3506
+ path,
3507
+ {
3508
+ method: "POST",
3509
+ body: UnfreezeBody,
3510
+ use: [sessionMiddleware]
3511
+ },
3512
+ async (ctx) => {
3513
+ const { adapter, row } = await requireConfirmedOwnedSubscription(
3514
+ ctx,
3515
+ ctx.body.subscriptionId,
3516
+ subsOptions,
3517
+ "cancel-plan-change"
3518
+ );
3519
+ try {
3520
+ const plans = await plansRef();
3521
+ const current = await client.getSubscription(row.streampaySubscriptionId);
3522
+ if (!current.pending_change) {
3523
+ await adapter.update({
3524
+ model: SUBSCRIPTION_MODEL6,
3525
+ update: {
3526
+ ...projectSubscriptionAgainstExisting(row, current),
3527
+ ...projectPlanFields(current, plans),
3528
+ pendingPlan: null,
3529
+ pendingProductId: null,
3530
+ pendingPlanEffectiveAt: null,
3531
+ pendingSeats: null,
3532
+ pendingSeatsEffectiveAt: null
3533
+ },
3534
+ where: [{ field: "id", value: row.id }]
3535
+ });
3536
+ return ctx.json({ canceled: true, reused: true, subscription: current });
3537
+ }
3538
+ await client.deletePendingSubscriptionChange(row.streampaySubscriptionId);
3539
+ const stream = await client.getSubscription(row.streampaySubscriptionId);
3540
+ await adapter.update({
3541
+ model: SUBSCRIPTION_MODEL6,
3542
+ update: {
3543
+ ...projectSubscriptionAgainstExisting(row, stream),
3544
+ ...projectPlanFields(stream, plans),
3545
+ pendingPlan: null,
3546
+ pendingProductId: null,
3547
+ pendingPlanEffectiveAt: null,
3548
+ pendingSeats: null,
3549
+ pendingSeatsEffectiveAt: null
3550
+ },
3551
+ where: [{ field: "id", value: row.id }]
3552
+ });
3553
+ return ctx.json({ canceled: true, reused: false, subscription: stream });
3554
+ } catch (err) {
3555
+ toAPIError(
3556
+ {
3557
+ logPrefix: `cancel pending subscription change failed for row=${row.id}:`,
3558
+ userMessage: "Canceling the pending subscription change failed."
3559
+ },
3560
+ err,
3561
+ getLogger(ctx)
3562
+ );
3563
+ }
3564
+ }
3565
+ );
3154
3566
  return {
3155
3567
  ...buildSubscriptionReadEndpoints(subsOptions, plansRef),
3156
3568
  upgradeSubscription: createAuthEndpoint(
@@ -3173,6 +3585,8 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3173
3585
  message: `Plan "${ctx.body.plan}" is not configured.`
3174
3586
  });
3175
3587
  }
3588
+ const seats = resolveSeatCount(plan, ctx.body.seats);
3589
+ const quotedTotal = quotedSeatTotal(plan, seats);
3176
3590
  const adapter = getAdapter2(ctx);
3177
3591
  const existingActive = await adapter.findMany({
3178
3592
  model: SUBSCRIPTION_MODEL6,
@@ -3210,6 +3624,7 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3210
3624
  candidates: existingActive,
3211
3625
  activeSlotKey,
3212
3626
  planName: plan.name,
3627
+ seats,
3213
3628
  now: Date.now(),
3214
3629
  log: getLogger(ctx),
3215
3630
  createReservation: async () => {
@@ -3229,13 +3644,14 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3229
3644
  planVersion: plan.version ?? null,
3230
3645
  productId: plan.productId,
3231
3646
  group: plan.group ?? null,
3647
+ seats,
3232
3648
  streampayConsumerId: consumerId2,
3233
3649
  streampayPaymentLinkId: null,
3234
3650
  status: "incomplete",
3235
3651
  providerStatus: null,
3236
3652
  billingStatus: "current",
3237
- amountInSmallestUnit: plan.priceInSmallestUnit,
3238
- originalAmountInSmallestUnit: plan.priceInSmallestUnit,
3653
+ amountInSmallestUnit: quotedTotal,
3654
+ originalAmountInSmallestUnit: quotedTotal,
3239
3655
  currency: plan.currency ?? "SAR",
3240
3656
  billingInterval: plan.billingInterval,
3241
3657
  billingIntervalCount: plan.billingIntervalCount ?? 1,
@@ -3251,6 +3667,8 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3251
3667
  pendingPlan: null,
3252
3668
  pendingProductId: null,
3253
3669
  pendingPlanEffectiveAt: null,
3670
+ pendingSeats: null,
3671
+ pendingSeatsEffectiveAt: null,
3254
3672
  endedAt: null,
3255
3673
  frozenAt: null,
3256
3674
  freezeEndAt: null,
@@ -3269,14 +3687,15 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3269
3687
  redirect: true,
3270
3688
  reused: true,
3271
3689
  status: reservation.row.status,
3272
- plan: reservation.row.plan
3690
+ plan: reservation.row.plan,
3691
+ seats: reservation.row.seats ?? 1
3273
3692
  });
3274
3693
  }
3275
3694
  const { row, consumerId } = reservation;
3276
3695
  const linkInput = {
3277
3696
  name: `Subscription \u2014 ${plan.name}`,
3278
3697
  currency: plan.currency ?? "SAR",
3279
- items: [{ product_id: plan.productId, quantity: 1, allow_custom_quantity: false }],
3698
+ items: [buildSeatCheckoutItem(plan, seats)],
3280
3699
  max_number_of_payments: 1,
3281
3700
  organization_consumer_id: consumerId,
3282
3701
  custom_metadata: {
@@ -3369,7 +3788,8 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3369
3788
  redirect: true,
3370
3789
  reused: false,
3371
3790
  status: "incomplete",
3372
- plan: plan.name
3791
+ plan: plan.name,
3792
+ seats
3373
3793
  });
3374
3794
  }
3375
3795
  ),
@@ -3440,6 +3860,7 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3440
3860
  model: SUBSCRIPTION_MODEL6,
3441
3861
  update: {
3442
3862
  ...projectSubscriptionFields(match),
3863
+ ...projectPlanFields(match, plans),
3443
3864
  planVersion: plan.version ?? null,
3444
3865
  productId: plan.productId,
3445
3866
  billingStatus: "current",
@@ -3551,8 +3972,14 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3551
3972
  }
3552
3973
  try {
3553
3974
  const stream = await client.getSubscription(row.streampaySubscriptionId);
3554
- const currentPlan = configuredPlanForSubscription(stream, plans);
3555
- const currentGroup = currentPlan?.group ?? row.group;
3975
+ const currentPlan = configuredPlanForSubscription(stream, plans) ?? plans.byName.get(row.plan);
3976
+ if (!currentPlan) {
3977
+ throw new APIError("BAD_REQUEST", {
3978
+ code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
3979
+ message: "The current StreamPay product is not a configured subscription plan."
3980
+ });
3981
+ }
3982
+ const currentGroup = currentPlan.group ?? row.group;
3556
3983
  if (currentGroup !== (nextPlan.group ?? null)) {
3557
3984
  throw new APIError("BAD_REQUEST", {
3558
3985
  code: $ERROR_CODES.SUBSCRIPTION_PLAN_GROUP_MISMATCH.code,
@@ -3565,27 +3992,35 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3565
3992
  message: "The subscription is scheduled to cancel. Uncancel it before scheduling a plan change."
3566
3993
  });
3567
3994
  }
3568
- const currentProductIsRequestedPlan = stream.items?.some(
3569
- (item) => subscriptionItemProductId(item) === nextPlan.productId
3995
+ const currentItem = stream.items?.find(
3996
+ (item) => subscriptionItemProductId(item) === currentPlan.productId
3570
3997
  );
3571
- if (currentProductIsRequestedPlan && !stream.pending_change) {
3998
+ const currentSeats = currentItem ? subscriptionItemQuantity(currentItem) ?? 1 : row.seats;
3999
+ const nextSeats = resolveSeatCount(nextPlan, ctx.body.seats ?? currentSeats ?? 1);
4000
+ const currentProductIsRequestedPlan = currentPlan.productId === nextPlan.productId;
4001
+ if (currentProductIsRequestedPlan && currentSeats === nextSeats && !stream.pending_change) {
3572
4002
  throw new APIError("BAD_REQUEST", {
3573
4003
  code: $ERROR_CODES.SUBSCRIPTION_ALREADY_ON_PLAN.code,
3574
- message: `Already on plan "${nextPlan.name}".`
4004
+ message: `Already on plan "${nextPlan.name}" with ${nextSeats} seats.`
3575
4005
  });
3576
4006
  }
3577
4007
  const pendingTargets = stream.pending_change?.target_items ?? [];
3578
- const pendingTargetIsRequestedPlan = pendingTargets.some(
4008
+ const pendingTarget = pendingTargets.find(
3579
4009
  (item) => subscriptionItemProductId(item) === nextPlan.productId
3580
4010
  );
3581
- if (pendingTargetIsRequestedPlan) {
4011
+ const pendingTargetMatches = Boolean(pendingTarget) && (subscriptionItemQuantity(pendingTarget) ?? 1) === nextSeats;
4012
+ if (pendingTargetMatches) {
4013
+ const effectiveAt2 = stream.pending_change?.effective_at ?? null;
3582
4014
  await adapter.update({
3583
4015
  model: SUBSCRIPTION_MODEL6,
3584
4016
  update: {
3585
4017
  ...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
4018
+ ...projectPlanFields(stream, plans),
4019
+ pendingPlan: currentPlan.productId === nextPlan.productId ? null : nextPlan.name,
4020
+ pendingProductId: currentPlan.productId === nextPlan.productId ? null : nextPlan.productId,
4021
+ pendingPlanEffectiveAt: currentPlan.productId !== nextPlan.productId && effectiveAt2 ? parseDate(effectiveAt2) : null,
4022
+ pendingSeats: nextSeats,
4023
+ pendingSeatsEffectiveAt: parseDate(effectiveAt2)
3589
4024
  },
3590
4025
  where: [{ field: "id", value: row.id }]
3591
4026
  });
@@ -3593,7 +4028,8 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3593
4028
  mode: "at_period_end",
3594
4029
  subscriptionId: row.id,
3595
4030
  plan: nextPlan.name,
3596
- effectiveAt: stream.pending_change?.effective_at ?? null,
4031
+ seats: nextSeats,
4032
+ effectiveAt: effectiveAt2,
3597
4033
  pendingChange: stream.pending_change,
3598
4034
  reused: true
3599
4035
  });
@@ -3605,28 +4041,36 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3605
4041
  });
3606
4042
  }
3607
4043
  const patch = {
3608
- items: [{ product_id: nextPlan.productId, quantity: 1 }],
4044
+ items: subscriptionItemsForUpdate(
4045
+ stream,
4046
+ currentPlan.productId,
4047
+ nextPlan.productId,
4048
+ nextSeats
4049
+ ),
3609
4050
  coupons: subscriptionCouponIds(stream),
3610
4051
  recurring_interval: nextPlan.billingInterval,
3611
4052
  recurring_interval_count: nextPlan.billingIntervalCount ?? 1
3612
4053
  };
3613
4054
  const result = await client.updateSubscription(row.streampaySubscriptionId, patch);
3614
- const effectiveAt = result.pending_change?.effective_at ?? result.current_period_end ?? null;
4055
+ const pending = Boolean(result.pending_change);
4056
+ const effectiveAt = result.pending_change?.effective_at ?? null;
4057
+ const planProjection = projectPlanFields(result, plans);
3615
4058
  await adapter.update({
3616
4059
  model: SUBSCRIPTION_MODEL6,
3617
4060
  update: {
3618
4061
  ...projectSubscriptionAgainstExisting(row, result),
3619
- pendingPlan: nextPlan.name,
3620
- pendingProductId: nextPlan.productId,
3621
- pendingPlanEffectiveAt: effectiveAt ? new Date(effectiveAt) : null,
4062
+ ...planProjection,
3622
4063
  updatedAt: /* @__PURE__ */ new Date()
3623
4064
  },
3624
4065
  where: [{ field: "id", value: row.id }]
3625
4066
  });
4067
+ const providerPlan = pending ? planProjection.pendingPlan ?? planProjection.plan ?? row.plan : planProjection.plan ?? row.plan;
4068
+ const providerSeats = pending ? planProjection.pendingSeats ?? nextSeats : planProjection.seats ?? row.seats ?? nextSeats;
3626
4069
  return ctx.json({
3627
- mode: "at_period_end",
4070
+ mode: pending ? "at_period_end" : "immediate",
3628
4071
  subscriptionId: row.id,
3629
- plan: nextPlan.name,
4072
+ plan: providerPlan,
4073
+ seats: providerSeats,
3630
4074
  effectiveAt,
3631
4075
  pendingChange: result.pending_change ?? null,
3632
4076
  subscription: result,
@@ -3644,11 +4088,11 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3644
4088
  }
3645
4089
  }
3646
4090
  ),
3647
- cancelSubscriptionPlanChange: createAuthEndpoint(
3648
- "/subscription/change-plan/cancel",
4091
+ updateSubscriptionSeats: createAuthEndpoint(
4092
+ "/subscription/update-seats",
3649
4093
  {
3650
4094
  method: "POST",
3651
- body: UnfreezeBody,
4095
+ body: UpdateSeatsBody,
3652
4096
  use: [sessionMiddleware]
3653
4097
  },
3654
4098
  async (ctx) => {
@@ -3656,27 +4100,107 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3656
4100
  ctx,
3657
4101
  ctx.body.subscriptionId,
3658
4102
  subsOptions,
3659
- "cancel-plan-change"
4103
+ "update-seats"
3660
4104
  );
4105
+ const plans = await plansRef();
3661
4106
  try {
3662
- await client.deletePendingSubscriptionChange(row.streampaySubscriptionId);
3663
4107
  const stream = await client.getSubscription(row.streampaySubscriptionId);
4108
+ const plan = configuredPlanForSubscription(stream, plans) ?? plans.byName.get(row.plan);
4109
+ if (!plan) {
4110
+ throw new APIError("BAD_REQUEST", {
4111
+ code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
4112
+ message: "The current StreamPay product is not a configured subscription plan."
4113
+ });
4114
+ }
4115
+ if (stream.cancel_at_period_end) {
4116
+ throw new APIError("CONFLICT", {
4117
+ code: $ERROR_CODES.SUBSCRIPTION_ALREADY_SCHEDULED_CANCEL.code,
4118
+ message: "Uncancel the subscription before scheduling a seat change."
4119
+ });
4120
+ }
4121
+ const seats = resolveSeatCount(plan, ctx.body.seats);
4122
+ const currentItem = stream.items?.find(
4123
+ (item) => subscriptionItemProductId(item) === plan.productId
4124
+ );
4125
+ const currentSeats = currentItem ? subscriptionItemQuantity(currentItem) ?? 1 : row.seats;
4126
+ const pendingTarget = stream.pending_change?.target_items?.find(
4127
+ (item) => subscriptionItemProductId(item) === plan.productId
4128
+ );
4129
+ if (stream.pending_change) {
4130
+ if (pendingTarget && (subscriptionItemQuantity(pendingTarget) ?? 1) === seats) {
4131
+ const effectiveAt2 = stream.pending_change.effective_at ?? null;
4132
+ await adapter.update({
4133
+ model: SUBSCRIPTION_MODEL6,
4134
+ update: {
4135
+ ...projectSubscriptionAgainstExisting(row, stream),
4136
+ ...projectPlanFields(stream, plans)
4137
+ },
4138
+ where: [{ field: "id", value: row.id }]
4139
+ });
4140
+ return ctx.json({
4141
+ mode: "at_period_end",
4142
+ subscriptionId: row.id,
4143
+ seats,
4144
+ effectiveAt: effectiveAt2,
4145
+ pendingChange: stream.pending_change,
4146
+ reused: true
4147
+ });
4148
+ }
4149
+ throw new APIError("CONFLICT", {
4150
+ code: $ERROR_CODES.SUBSCRIPTION_SEAT_CHANGE_ALREADY_SCHEDULED.code,
4151
+ message: "A different subscription change is pending. Cancel it before scheduling this seat count."
4152
+ });
4153
+ }
4154
+ if (currentSeats === seats) {
4155
+ await adapter.update({
4156
+ model: SUBSCRIPTION_MODEL6,
4157
+ update: {
4158
+ ...projectSubscriptionAgainstExisting(row, stream),
4159
+ ...projectPlanFields(stream, plans)
4160
+ },
4161
+ where: [{ field: "id", value: row.id }]
4162
+ });
4163
+ return ctx.json({
4164
+ mode: "current",
4165
+ subscriptionId: row.id,
4166
+ seats,
4167
+ effectiveAt: null,
4168
+ pendingChange: null,
4169
+ reused: true
4170
+ });
4171
+ }
4172
+ const patch = {
4173
+ items: subscriptionItemsForUpdate(stream, plan.productId, plan.productId, seats),
4174
+ coupons: subscriptionCouponIds(stream)
4175
+ };
4176
+ const result = await client.updateSubscription(row.streampaySubscriptionId, patch);
4177
+ const pending = Boolean(result.pending_change);
4178
+ const effectiveAt = result.pending_change?.effective_at ?? null;
4179
+ const planProjection = projectPlanFields(result, plans);
3664
4180
  await adapter.update({
3665
4181
  model: SUBSCRIPTION_MODEL6,
3666
4182
  update: {
3667
- ...projectSubscriptionAgainstExisting(row, stream),
3668
- pendingPlan: null,
3669
- pendingProductId: null,
3670
- pendingPlanEffectiveAt: null
4183
+ ...projectSubscriptionAgainstExisting(row, result),
4184
+ ...planProjection,
4185
+ updatedAt: /* @__PURE__ */ new Date()
3671
4186
  },
3672
4187
  where: [{ field: "id", value: row.id }]
3673
4188
  });
3674
- return ctx.json({ canceled: true, subscription: stream });
4189
+ const providerSeats = pending ? planProjection.pendingSeats ?? seats : planProjection.seats ?? row.seats ?? seats;
4190
+ return ctx.json({
4191
+ mode: pending ? "at_period_end" : "immediate",
4192
+ subscriptionId: row.id,
4193
+ seats: providerSeats,
4194
+ effectiveAt,
4195
+ pendingChange: result.pending_change ?? null,
4196
+ subscription: result,
4197
+ reused: false
4198
+ });
3675
4199
  } catch (err) {
3676
4200
  toAPIError(
3677
4201
  {
3678
- logPrefix: `cancel plan change failed for row=${row.id}:`,
3679
- userMessage: "Canceling the scheduled plan change failed."
4202
+ logPrefix: `update-seats failed for row=${row.id}:`,
4203
+ userMessage: "Seat change scheduling failed."
3680
4204
  },
3681
4205
  err,
3682
4206
  getLogger(ctx)
@@ -3684,6 +4208,10 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3684
4208
  }
3685
4209
  }
3686
4210
  ),
4211
+ cancelSubscriptionPlanChange: cancelPendingChangeEndpoint("/subscription/change-plan/cancel"),
4212
+ cancelSubscriptionPendingChange: cancelPendingChangeEndpoint(
4213
+ "/subscription/pending-change/cancel"
4214
+ ),
3687
4215
  uncancelSubscription: createAuthEndpoint(
3688
4216
  "/subscription/uncancel",
3689
4217
  {
@@ -3783,9 +4311,9 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
3783
4311
  const freezes = await client.listSubscriptionFreezes(row.streampaySubscriptionId);
3784
4312
  const active = freezes.data?.find((freeze) => {
3785
4313
  if (!freeze.id || !freeze.freeze_start_datetime) return false;
3786
- const start = new Date(freeze.freeze_start_datetime).getTime();
3787
- const end = freeze.freeze_end_datetime ? new Date(freeze.freeze_end_datetime).getTime() : Number.POSITIVE_INFINITY;
3788
- return start <= nowMs && nowMs <= end;
4314
+ const start = parseDate(freeze.freeze_start_datetime)?.getTime();
4315
+ const end = freeze.freeze_end_datetime ? parseDate(freeze.freeze_end_datetime)?.getTime() : Number.POSITIVE_INFINITY;
4316
+ return start !== void 0 && end !== void 0 && start <= nowMs && nowMs <= end;
3789
4317
  });
3790
4318
  if (!active?.id || !active.freeze_start_datetime) {
3791
4319
  throw new APIError("BAD_REQUEST", {
@@ -3925,6 +4453,11 @@ var subscriptionTable = {
3925
4453
  required: false,
3926
4454
  index: true
3927
4455
  },
4456
+ seats: {
4457
+ type: "number",
4458
+ required: false,
4459
+ defaultValue: 1
4460
+ },
3928
4461
  amountInSmallestUnit: {
3929
4462
  type: "number",
3930
4463
  required: false
@@ -4013,6 +4546,14 @@ var subscriptionTable = {
4013
4546
  type: "date",
4014
4547
  required: false
4015
4548
  },
4549
+ pendingSeats: {
4550
+ type: "number",
4551
+ required: false
4552
+ },
4553
+ pendingSeatsEffectiveAt: {
4554
+ type: "date",
4555
+ required: false
4556
+ },
4016
4557
  endedAt: {
4017
4558
  type: "date",
4018
4559
  required: false
@@ -4611,7 +5152,7 @@ var onUserDelete = (options) => async (user, context) => {
4611
5152
 
4612
5153
  // package.json
4613
5154
  var package_default = {
4614
- version: "2.0.0"};
5155
+ version: "2.2.0"};
4615
5156
 
4616
5157
  // src/version.ts
4617
5158
  var version = package_default.version;
@@ -4638,7 +5179,8 @@ var streampay = (options) => {
4638
5179
  streampayConsumerId: {
4639
5180
  type: "string",
4640
5181
  required: false,
4641
- input: false
5182
+ input: false,
5183
+ unique: true
4642
5184
  }
4643
5185
  }
4644
5186
  },