better-auth-streampay 3.0.0 → 3.0.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.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { a as StreamPayClient } from './streampay-Cfl70SR_.cjs';
2
- export { $ as $ERROR_CODES, A as AdminOptions, b as AuthorizeReferenceContext, C as CheckoutBody, c as CheckoutCreatedContext, d as CheckoutOptions, e as CheckoutOverrides, f as CheckoutParams, g as CheckoutResolutionContext, h as ClaimExistingConsumerBy, i as ClaimExistingConsumerIdentifier, j as ConsumerCreateOverrides, D as DEFAULT_ACCESS_STATUSES, F as FeatureKey, L as LimitCheckResult, P as PLAN_NAME_METADATA_KEY, k as PluginAdapter, l as PortalOptions, R as REFERENCE_ID_METADATA_KEY, m as REFERENCE_TYPE_METADATA_KEY, n as ResolvedPlans, o as STREAMPAY_EVENT_TYPES, p as STREAMPAY_INVOICE_EVENT_TYPES, q as STREAMPAY_PAYMENT_EVENT_TYPES, r as STREAMPAY_PAYMENT_LINK_EVENT_TYPES, t as STREAMPAY_SUBSCRIPTION_EVENT_TYPES, u as SUBSCRIPTION_ROW_ID_METADATA_KEY, v as StreamPayCustomFieldDefinition, w as StreamPayCustomFieldsSchema, x as StreamPayEndpoints, y as StreamPayEntityType, S as StreamPayErrorCode, z as StreamPayEventType, B as StreamPayHookContext, G as StreamPayInvoiceEventType, H as StreamPayOptions, I as StreamPayPaymentEventType, J as StreamPayPaymentLinkEventType, K as StreamPayPlan, M as StreamPayPlanLike, N as StreamPayPlugin, O as StreamPayPluginRegistry, Q as StreamPayPlugins, T as StreamPayProduct, U as StreamPaySeatBilling, V as StreamPaySubscriptionEventType, W as StreamPayWebhookData, X as StreamPayWebhookEnvelope, Y as StreamPayWebhookPayload, Z as Subscription, _ as SubscriptionBillingStatus, a0 as SubscriptionCallback, a1 as SubscriptionCallbackData, a2 as SubscriptionCallbacks, a3 as SubscriptionReferenceType, a4 as SubscriptionStatus, a5 as SubscriptionsOptions, a6 as SyncContext, a7 as TrialEligibilityContext, a8 as WebhookEnvelopeHandler, a9 as WebhookHandler, aa as WebhookHandlers, ab as WebhookSyncFailure, ac as WebhooksOptions, ad as admin, ae as checkLimit, af as checkout, ag as classifyWebhookFailure, ah as dispatchWebhook, ai as hasFeature, aj as hasSubscriptionAccess, ak as isKnownStreamPayWebhookPayload, al as isStreamPayWebhookEnvelope, am as mapToErrorCode, an as portal, s as streampay, ao as subscriptionSlotKey, ap as subscriptions, aq as syncWebhookPayload, ar as webhooks } from './streampay-Cfl70SR_.cjs';
1
+ import { a as StreamPayClient } from './streampay-uhs67tYl.cjs';
2
+ export { $ as $ERROR_CODES, A as AdminOptions, b as AuthorizeReferenceContext, C as CheckoutBody, c as CheckoutCreatedContext, d as CheckoutOptions, e as CheckoutOverrides, f as CheckoutParams, g as CheckoutResolutionContext, h as ClaimExistingConsumerBy, i as ClaimExistingConsumerIdentifier, j as ConsumerCreateOverrides, D as DEFAULT_ACCESS_STATUSES, F as FeatureKey, L as LimitCheckResult, P as PLAN_NAME_METADATA_KEY, k as PluginAdapter, l as PortalOptions, R as REFERENCE_ID_METADATA_KEY, m as REFERENCE_TYPE_METADATA_KEY, n as ResolvedPlans, o as STREAMPAY_EVENT_TYPES, p as STREAMPAY_INVOICE_EVENT_TYPES, q as STREAMPAY_PAYMENT_EVENT_TYPES, r as STREAMPAY_PAYMENT_LINK_EVENT_TYPES, t as STREAMPAY_SUBSCRIPTION_EVENT_TYPES, u as SUBSCRIPTION_ROW_ID_METADATA_KEY, v as StreamPayCustomFieldDefinition, w as StreamPayCustomFieldsSchema, x as StreamPayEndpoints, y as StreamPayEntityType, S as StreamPayErrorCode, z as StreamPayEventType, B as StreamPayHookContext, G as StreamPayInvoiceEventType, H as StreamPayOptions, I as StreamPayPaymentEventType, J as StreamPayPaymentLinkEventType, K as StreamPayPlan, M as StreamPayPlanLike, N as StreamPayPlugin, O as StreamPayPluginRegistry, Q as StreamPayPlugins, T as StreamPayProduct, U as StreamPaySeatBilling, V as StreamPaySubscriptionEventType, W as StreamPayWebhookData, X as StreamPayWebhookEnvelope, Y as StreamPayWebhookPayload, Z as Subscription, _ as SubscriptionBillingStatus, a0 as SubscriptionCallback, a1 as SubscriptionCallbackData, a2 as SubscriptionCallbacks, a3 as SubscriptionReferenceType, a4 as SubscriptionStatus, a5 as SubscriptionsOptions, a6 as SyncContext, a7 as TrialEligibilityContext, a8 as WebhookEnvelopeHandler, a9 as WebhookHandler, aa as WebhookHandlers, ab as WebhookSyncFailure, ac as WebhooksOptions, ad as admin, ae as checkLimit, af as checkout, ag as classifyWebhookFailure, ah as dispatchWebhook, ai as hasFeature, aj as hasSubscriptionAccess, ak as isKnownStreamPayWebhookPayload, al as isStreamPayWebhookEnvelope, am as mapToErrorCode, an as portal, s as streampay, ao as subscriptionSlotKey, ap as subscriptions, aq as syncWebhookPayload, ar as webhooks } from './streampay-uhs67tYl.cjs';
3
3
  import { InvoiceDetailed, PaymentResponse, ConsumerResponse } from '@streamsdk/typescript';
4
4
  import 'better-auth';
5
5
  import 'zod';
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { a as StreamPayClient } from './streampay-Cfl70SR_.js';
2
- export { $ as $ERROR_CODES, A as AdminOptions, b as AuthorizeReferenceContext, C as CheckoutBody, c as CheckoutCreatedContext, d as CheckoutOptions, e as CheckoutOverrides, f as CheckoutParams, g as CheckoutResolutionContext, h as ClaimExistingConsumerBy, i as ClaimExistingConsumerIdentifier, j as ConsumerCreateOverrides, D as DEFAULT_ACCESS_STATUSES, F as FeatureKey, L as LimitCheckResult, P as PLAN_NAME_METADATA_KEY, k as PluginAdapter, l as PortalOptions, R as REFERENCE_ID_METADATA_KEY, m as REFERENCE_TYPE_METADATA_KEY, n as ResolvedPlans, o as STREAMPAY_EVENT_TYPES, p as STREAMPAY_INVOICE_EVENT_TYPES, q as STREAMPAY_PAYMENT_EVENT_TYPES, r as STREAMPAY_PAYMENT_LINK_EVENT_TYPES, t as STREAMPAY_SUBSCRIPTION_EVENT_TYPES, u as SUBSCRIPTION_ROW_ID_METADATA_KEY, v as StreamPayCustomFieldDefinition, w as StreamPayCustomFieldsSchema, x as StreamPayEndpoints, y as StreamPayEntityType, S as StreamPayErrorCode, z as StreamPayEventType, B as StreamPayHookContext, G as StreamPayInvoiceEventType, H as StreamPayOptions, I as StreamPayPaymentEventType, J as StreamPayPaymentLinkEventType, K as StreamPayPlan, M as StreamPayPlanLike, N as StreamPayPlugin, O as StreamPayPluginRegistry, Q as StreamPayPlugins, T as StreamPayProduct, U as StreamPaySeatBilling, V as StreamPaySubscriptionEventType, W as StreamPayWebhookData, X as StreamPayWebhookEnvelope, Y as StreamPayWebhookPayload, Z as Subscription, _ as SubscriptionBillingStatus, a0 as SubscriptionCallback, a1 as SubscriptionCallbackData, a2 as SubscriptionCallbacks, a3 as SubscriptionReferenceType, a4 as SubscriptionStatus, a5 as SubscriptionsOptions, a6 as SyncContext, a7 as TrialEligibilityContext, a8 as WebhookEnvelopeHandler, a9 as WebhookHandler, aa as WebhookHandlers, ab as WebhookSyncFailure, ac as WebhooksOptions, ad as admin, ae as checkLimit, af as checkout, ag as classifyWebhookFailure, ah as dispatchWebhook, ai as hasFeature, aj as hasSubscriptionAccess, ak as isKnownStreamPayWebhookPayload, al as isStreamPayWebhookEnvelope, am as mapToErrorCode, an as portal, s as streampay, ao as subscriptionSlotKey, ap as subscriptions, aq as syncWebhookPayload, ar as webhooks } from './streampay-Cfl70SR_.js';
1
+ import { a as StreamPayClient } from './streampay-uhs67tYl.js';
2
+ export { $ as $ERROR_CODES, A as AdminOptions, b as AuthorizeReferenceContext, C as CheckoutBody, c as CheckoutCreatedContext, d as CheckoutOptions, e as CheckoutOverrides, f as CheckoutParams, g as CheckoutResolutionContext, h as ClaimExistingConsumerBy, i as ClaimExistingConsumerIdentifier, j as ConsumerCreateOverrides, D as DEFAULT_ACCESS_STATUSES, F as FeatureKey, L as LimitCheckResult, P as PLAN_NAME_METADATA_KEY, k as PluginAdapter, l as PortalOptions, R as REFERENCE_ID_METADATA_KEY, m as REFERENCE_TYPE_METADATA_KEY, n as ResolvedPlans, o as STREAMPAY_EVENT_TYPES, p as STREAMPAY_INVOICE_EVENT_TYPES, q as STREAMPAY_PAYMENT_EVENT_TYPES, r as STREAMPAY_PAYMENT_LINK_EVENT_TYPES, t as STREAMPAY_SUBSCRIPTION_EVENT_TYPES, u as SUBSCRIPTION_ROW_ID_METADATA_KEY, v as StreamPayCustomFieldDefinition, w as StreamPayCustomFieldsSchema, x as StreamPayEndpoints, y as StreamPayEntityType, S as StreamPayErrorCode, z as StreamPayEventType, B as StreamPayHookContext, G as StreamPayInvoiceEventType, H as StreamPayOptions, I as StreamPayPaymentEventType, J as StreamPayPaymentLinkEventType, K as StreamPayPlan, M as StreamPayPlanLike, N as StreamPayPlugin, O as StreamPayPluginRegistry, Q as StreamPayPlugins, T as StreamPayProduct, U as StreamPaySeatBilling, V as StreamPaySubscriptionEventType, W as StreamPayWebhookData, X as StreamPayWebhookEnvelope, Y as StreamPayWebhookPayload, Z as Subscription, _ as SubscriptionBillingStatus, a0 as SubscriptionCallback, a1 as SubscriptionCallbackData, a2 as SubscriptionCallbacks, a3 as SubscriptionReferenceType, a4 as SubscriptionStatus, a5 as SubscriptionsOptions, a6 as SyncContext, a7 as TrialEligibilityContext, a8 as WebhookEnvelopeHandler, a9 as WebhookHandler, aa as WebhookHandlers, ab as WebhookSyncFailure, ac as WebhooksOptions, ad as admin, ae as checkLimit, af as checkout, ag as classifyWebhookFailure, ah as dispatchWebhook, ai as hasFeature, aj as hasSubscriptionAccess, ak as isKnownStreamPayWebhookPayload, al as isStreamPayWebhookEnvelope, am as mapToErrorCode, an as portal, s as streampay, ao as subscriptionSlotKey, ap as subscriptions, aq as syncWebhookPayload, ar as webhooks } from './streampay-uhs67tYl.js';
3
3
  import { InvoiceDetailed, PaymentResponse, ConsumerResponse } from '@streamsdk/typescript';
4
4
  import 'better-auth';
5
5
  import 'zod';
package/dist/index.js CHANGED
@@ -286,6 +286,46 @@ function scopedLogger(logger2) {
286
286
  function getLogger(ctx) {
287
287
  return scopedLogger(ctx.context.logger);
288
288
  }
289
+ async function getCurrentConsumerUser(ctx, user) {
290
+ if (!user.streampayConsumerId) return user;
291
+ if (!ctx.context.adapter) {
292
+ throw new APIError("INTERNAL_SERVER_ERROR", { message: "Consumer storage is unavailable." });
293
+ }
294
+ const current = await ctx.context.adapter.findOne({
295
+ model: "user",
296
+ where: [{ field: "id", value: user.id }]
297
+ });
298
+ if (!current || current.id !== user.id) {
299
+ throw new APIError("UNAUTHORIZED", { message: "The account no longer exists." });
300
+ }
301
+ if (current.streampayConsumerId != null && typeof current.streampayConsumerId !== "string") {
302
+ throw new APIError("INTERNAL_SERVER_ERROR", { message: "Invalid stored consumer link." });
303
+ }
304
+ return { ...user, streampayConsumerId: current.streampayConsumerId ?? null };
305
+ }
306
+ function asSessionUser(user) {
307
+ if (user === null || typeof user !== "object") return null;
308
+ if (!("id" in user) || typeof user.id !== "string") return null;
309
+ const result = { id: user.id };
310
+ if ("email" in user && typeof user.email === "string") {
311
+ result.email = user.email;
312
+ }
313
+ if ("name" in user && typeof user.name === "string") {
314
+ result.name = user.name;
315
+ }
316
+ if ("isAnonymous" in user && user.isAnonymous === true) {
317
+ result.isAnonymous = true;
318
+ }
319
+ if ("streampayConsumerId" in user) {
320
+ const value = user.streampayConsumerId;
321
+ if (typeof value === "string") {
322
+ result.streampayConsumerId = value;
323
+ } else if (value === null) {
324
+ result.streampayConsumerId = null;
325
+ }
326
+ }
327
+ return result;
328
+ }
289
329
 
290
330
  // src/utils/ensure-consumer.ts
291
331
  function canClaimBy(mode, identifier) {
@@ -328,6 +368,7 @@ async function resolveDuplicateConsumer(options, createPayload, context) {
328
368
  return existing.id;
329
369
  }
330
370
  async function ensureConsumerForUser(options, ctx, user) {
371
+ user = await getCurrentConsumerUser(ctx, user);
331
372
  if (user.streampayConsumerId) {
332
373
  return { consumerId: user.streampayConsumerId, created: false };
333
374
  }
@@ -367,10 +408,25 @@ async function ensureConsumerForUser(options, ctx, user) {
367
408
  if (isDuplicateConsumerError(err)) {
368
409
  const reusedId = await resolveDuplicateConsumer(options, payload, ctx);
369
410
  if (reusedId) {
370
- await assertConsumerUnclaimed(ctx, reusedId, user.id);
411
+ await persistConsumerId(ctx, user.id, reusedId);
371
412
  try {
372
413
  await options.client.updateConsumer(reusedId, { external_id: user.id });
373
414
  } catch (backfillErr) {
415
+ try {
416
+ if (!ctx.context.adapter.update) throw consumerLinkUnavailable();
417
+ await ctx.context.adapter.update({
418
+ model: "user",
419
+ where: [
420
+ { field: "id", value: user.id },
421
+ { field: "streampayConsumerId", value: reusedId }
422
+ ],
423
+ update: { streampayConsumerId: null }
424
+ });
425
+ } catch (clearErr) {
426
+ getLogger(ctx).error(
427
+ `consumer claim cleanup failed for user=${user.id} consumer=${reusedId}: ${formatStreamPayError(clearErr)}`
428
+ );
429
+ }
374
430
  getLogger(ctx).error(
375
431
  `consumer external_id backfill failed for user=${user.id} consumer=${reusedId}: ${formatStreamPayError(backfillErr)}`
376
432
  );
@@ -379,7 +435,6 @@ async function ensureConsumerForUser(options, ctx, user) {
379
435
  message: "StreamPay consumer linking failed. Please try again."
380
436
  });
381
437
  }
382
- await persistConsumerId(ctx, user.id, reusedId);
383
438
  return { consumerId: reusedId, created: false };
384
439
  }
385
440
  }
@@ -399,9 +454,15 @@ function consumerLinkUnavailable() {
399
454
  }
400
455
  async function findConsumerOwner(ctx, consumerId) {
401
456
  try {
457
+ const where = [{ field: "streampayConsumerId", value: consumerId }];
458
+ if (ctx.context.internalAdapter?.listUsers) {
459
+ const owners = await ctx.context.internalAdapter.listUsers(1, 0, void 0, where);
460
+ return owners[0] ?? null;
461
+ }
462
+ if (!ctx.context.adapter) throw consumerLinkUnavailable();
402
463
  return await ctx.context.adapter.findOne({
403
464
  model: "user",
404
- where: [{ field: "streampayConsumerId", value: consumerId }]
465
+ where
405
466
  });
406
467
  } catch (err) {
407
468
  getLogger(ctx).error(
@@ -514,31 +575,6 @@ function rejectUnauthorized(user, anonymousMessage) {
514
575
  }
515
576
  }
516
577
 
517
- // src/utils/session.ts
518
- function asSessionUser(user) {
519
- if (user === null || typeof user !== "object") return null;
520
- if (!("id" in user) || typeof user.id !== "string") return null;
521
- const result = { id: user.id };
522
- if ("email" in user && typeof user.email === "string") {
523
- result.email = user.email;
524
- }
525
- if ("name" in user && typeof user.name === "string") {
526
- result.name = user.name;
527
- }
528
- if ("isAnonymous" in user && user.isAnonymous === true) {
529
- result.isAnonymous = true;
530
- }
531
- if ("streampayConsumerId" in user) {
532
- const value = user.streampayConsumerId;
533
- if (typeof value === "string") {
534
- result.streampayConsumerId = value;
535
- } else if (value === null) {
536
- result.streampayConsumerId = null;
537
- }
538
- }
539
- return result;
540
- }
541
-
542
578
  // src/plugins/subscriptions/status.ts
543
579
  var SUBSCRIPTION_STATUSES = [
544
580
  "incomplete",
@@ -2874,9 +2910,10 @@ var paginationQuery = z.object({
2874
2910
  page: z.coerce.number().int().min(1).max(Number.MAX_SAFE_INTEGER).optional(),
2875
2911
  size: z.coerce.number().int().min(1).max(100).optional()
2876
2912
  });
2877
- async function getConsumerIdOrNull(client, user) {
2913
+ async function getConsumerIdOrNull(ctx, client, user) {
2878
2914
  rejectUnauthorized(user, "Anonymous users cannot access the billing portal.");
2879
- if (user.streampayConsumerId) return user.streampayConsumerId;
2915
+ const current = await getCurrentConsumerUser(ctx, user);
2916
+ if (current.streampayConsumerId) return current.streampayConsumerId;
2880
2917
  return findConsumerByExternalId(client, { externalId: user.id });
2881
2918
  }
2882
2919
  var portal = ({ pageSize, createSession } = {}) => (options) => {
@@ -2891,6 +2928,7 @@ var portal = ({ pageSize, createSession } = {}) => (options) => {
2891
2928
  ctx.setHeader("cache-control", "no-store");
2892
2929
  try {
2893
2930
  const consumerId = await getConsumerIdOrNull(
2931
+ ctx,
2894
2932
  client,
2895
2933
  asSessionUser(ctx.context.session?.user)
2896
2934
  );
@@ -2918,7 +2956,7 @@ var portal = ({ pageSize, createSession } = {}) => (options) => {
2918
2956
  async (ctx) => {
2919
2957
  const user = asSessionUser(ctx.context.session?.user);
2920
2958
  try {
2921
- const consumerId = await getConsumerIdOrNull(client, user);
2959
+ const consumerId = await getConsumerIdOrNull(ctx, client, user);
2922
2960
  if (!consumerId) return ctx.json({ hasConsumer: false, consumer: null });
2923
2961
  const consumer = await client.getConsumer(consumerId);
2924
2962
  return ctx.json({ hasConsumer: true, consumer });
@@ -2933,7 +2971,7 @@ var portal = ({ pageSize, createSession } = {}) => (options) => {
2933
2971
  async (ctx) => {
2934
2972
  const user = asSessionUser(ctx.context.session?.user);
2935
2973
  try {
2936
- const consumerId = await getConsumerIdOrNull(client, user);
2974
+ const consumerId = await getConsumerIdOrNull(ctx, client, user);
2937
2975
  if (!consumerId) return ctx.json({ hasConsumer: false, data: [] });
2938
2976
  const response = await client.listSubscriptions({
2939
2977
  organization_consumer_id: consumerId,
@@ -2956,7 +2994,7 @@ var portal = ({ pageSize, createSession } = {}) => (options) => {
2956
2994
  async (ctx) => {
2957
2995
  const user = asSessionUser(ctx.context.session?.user);
2958
2996
  try {
2959
- const consumerId = await getConsumerIdOrNull(client, user);
2997
+ const consumerId = await getConsumerIdOrNull(ctx, client, user);
2960
2998
  if (!consumerId) return ctx.json({ hasConsumer: false, data: [] });
2961
2999
  const response = await client.listInvoices({
2962
3000
  organization_consumer_id: consumerId,
@@ -5410,9 +5448,6 @@ var webhooks = (webhooksOptions) => {
5410
5448
  };
5411
5449
  };
5412
5450
  var isAnonymous = (user) => "isAnonymous" in user && user.isAnonymous === true;
5413
- function hasInternalAdapter(ctx) {
5414
- return "internalAdapter" in ctx.context && ctx.context.internalAdapter !== null && typeof ctx.context.internalAdapter === "object" && "updateUser" in ctx.context.internalAdapter && typeof ctx.context.internalAdapter.updateUser === "function";
5415
- }
5416
5451
  var onBeforeUserCreate = (options) => async (user, context) => {
5417
5452
  if (!context || !options.createConsumerOnSignUp) return void 0;
5418
5453
  if (isAnonymous(user)) return void 0;
@@ -5442,6 +5477,7 @@ var onBeforeUserCreate = (options) => async (user, context) => {
5442
5477
  if (isDuplicateConsumerError(err)) {
5443
5478
  const reusedId = await resolveDuplicateConsumer(options, createPayload, context);
5444
5479
  if (reusedId) {
5480
+ await assertConsumerUnclaimed(context, reusedId);
5445
5481
  return { data: { streampayConsumerId: reusedId } };
5446
5482
  }
5447
5483
  }
@@ -5490,10 +5526,15 @@ var onUserUpdate = (options) => async (user, context) => {
5490
5526
  getLogger(context).error(
5491
5527
  `consumer ${sessionUser.streampayConsumerId} not found for user=${sessionUser.id}; clearing stale link for re-provisioning.`
5492
5528
  );
5493
- if (hasInternalAdapter(context)) {
5529
+ if (typeof context.context.adapter?.update === "function") {
5494
5530
  try {
5495
- await context.context.internalAdapter.updateUser(sessionUser.id, {
5496
- streampayConsumerId: null
5531
+ await context.context.adapter.update({
5532
+ model: "user",
5533
+ where: [
5534
+ { field: "id", value: sessionUser.id },
5535
+ { field: "streampayConsumerId", value: sessionUser.streampayConsumerId }
5536
+ ],
5537
+ update: { streampayConsumerId: null }
5497
5538
  });
5498
5539
  } catch (clearErr) {
5499
5540
  getLogger(context).error(
@@ -5525,7 +5566,7 @@ var onUserDelete = (options) => async (user, context) => {
5525
5566
 
5526
5567
  // package.json
5527
5568
  var package_default = {
5528
- version: "3.0.0"};
5569
+ version: "3.0.1"};
5529
5570
 
5530
5571
  // src/version.ts
5531
5572
  var version = package_default.version;