better-auth-streampay 0.2.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -7,7 +7,11 @@ var crypto = require('crypto');
7
7
  // src/plugins/checkout.ts
8
8
 
9
9
  // src/utils/consumer.ts
10
- async function findConsumerByExternalId(client, { externalId, maxPages = 10, pageSize = 100 }) {
10
+ async function findConsumerByExternalId(client, {
11
+ externalId,
12
+ maxPages = DEFAULT_CONSUMER_LOOKUP_MAX_PAGES,
13
+ pageSize = 100
14
+ }) {
11
15
  const hit = await scanConsumers(
12
16
  client,
13
17
  { maxPages, pageSize },
@@ -16,7 +20,7 @@ async function findConsumerByExternalId(client, { externalId, maxPages = 10, pag
16
20
  return hit?.id ?? null;
17
21
  }
18
22
  async function findConsumerByIdentifiers(client, identifiers, opts = {}) {
19
- const { maxPages = 10, pageSize = 100 } = opts;
23
+ const { maxPages = DEFAULT_CONSUMER_LOOKUP_MAX_PAGES, pageSize = 100 } = opts;
20
24
  return scanConsumers(client, { maxPages, pageSize }, (c) => matchesAnyIdentifier(c, identifiers));
21
25
  }
22
26
  function matchesAnyIdentifier(consumer, identifiers) {
@@ -36,12 +40,213 @@ async function scanConsumers(client, { maxPages, pageSize }, predicate) {
36
40
  const items = response.data ?? [];
37
41
  const hit = items.find(predicate);
38
42
  if (hit) return hit;
39
- const total = response.pagination?.total_count ?? 0;
40
- if (items.length < pageSize || page * pageSize >= total) return null;
43
+ if (response.pagination?.has_next_page !== true) return null;
41
44
  }
42
45
  return null;
43
46
  }
44
47
 
48
+ // src/utils/format-error.ts
49
+ function formatStreamPayError(err) {
50
+ if (!(err instanceof Error)) return String(err);
51
+ if (!("body" in err)) return err.message;
52
+ const { body } = err;
53
+ if (!body || typeof body !== "object") return err.message;
54
+ const envelope = readEnvelopeMessage(body);
55
+ if (envelope !== null) return envelope;
56
+ const validation = readValidationMessage(body);
57
+ if (validation !== null) return validation;
58
+ try {
59
+ return JSON.stringify(body);
60
+ } catch {
61
+ return err.message;
62
+ }
63
+ }
64
+ function readEnvelopeMessage(body) {
65
+ if (!("error" in body) || !body.error || typeof body.error !== "object") {
66
+ return null;
67
+ }
68
+ const error = body.error;
69
+ if ("additional_info" in error && typeof error.additional_info === "string") {
70
+ return error.additional_info;
71
+ }
72
+ if ("message" in error && typeof error.message === "string") {
73
+ return error.message;
74
+ }
75
+ return null;
76
+ }
77
+ function readValidationMessage(body) {
78
+ if (!("detail" in body) || !Array.isArray(body.detail) || body.detail.length === 0) {
79
+ return null;
80
+ }
81
+ return body.detail.map(formatValidationEntry).join("; ");
82
+ }
83
+ function formatValidationEntry(entry) {
84
+ if (!entry || typeof entry !== "object") return String(entry);
85
+ const loc = "loc" in entry && Array.isArray(entry.loc) ? entry.loc.join(".") : "?";
86
+ const msg = "msg" in entry && typeof entry.msg === "string" ? entry.msg : "invalid";
87
+ return `${loc}: ${msg}`;
88
+ }
89
+
90
+ // src/utils/ensure-consumer.ts
91
+ var DEFAULT_CONSUMER_LOOKUP_MAX_PAGES = 100;
92
+ function resolveConsumerLookupMaxPages(options, override) {
93
+ const raw = override ?? options.consumerLookupMaxPages ?? DEFAULT_CONSUMER_LOOKUP_MAX_PAGES;
94
+ const coerced = Math.floor(Number(raw));
95
+ return Number.isFinite(coerced) ? Math.max(1, coerced) : DEFAULT_CONSUMER_LOOKUP_MAX_PAGES;
96
+ }
97
+ function sameEmail(a, b) {
98
+ if (!a || !b) return false;
99
+ return a.trim().toLowerCase() === b.trim().toLowerCase();
100
+ }
101
+ function samePhone(a, b) {
102
+ if (!a || !b) return false;
103
+ return a.trim() === b.trim();
104
+ }
105
+ function canClaimBy(mode, identifier) {
106
+ return mode?.includes(identifier) ?? false;
107
+ }
108
+ function isDuplicateConsumerError(err) {
109
+ if (!(err instanceof Error)) return false;
110
+ if (!("body" in err)) return false;
111
+ const { body } = err;
112
+ if (!body || typeof body !== "object") return false;
113
+ if (!("error" in body) || !body.error || typeof body.error !== "object") {
114
+ return false;
115
+ }
116
+ const error = body.error;
117
+ return "code" in error && typeof error.code === "string" && error.code === "DUPLICATE_CONSUMER";
118
+ }
119
+ function isNotFoundError(err) {
120
+ if (!(err instanceof Error)) return false;
121
+ if (!("status" in err)) return false;
122
+ return typeof err.status === "number" && err.status === 404;
123
+ }
124
+ async function resolveDuplicateConsumer(options, createPayload, context) {
125
+ const maxPages = resolveConsumerLookupMaxPages(options);
126
+ const emailMatch = createPayload.email ? await findConsumerByIdentifiers(
127
+ options.client,
128
+ { email: createPayload.email },
129
+ { maxPages }
130
+ ) : null;
131
+ const phoneMatch = !emailMatch && createPayload.phone_number ? await findConsumerByIdentifiers(
132
+ options.client,
133
+ { phone_number: createPayload.phone_number },
134
+ { maxPages }
135
+ ) : null;
136
+ const identifiers = {
137
+ email: createPayload.email ?? null,
138
+ phone_number: createPayload.phone_number ?? null,
139
+ external_id: createPayload.external_id ?? null,
140
+ iban: createPayload.iban ?? null
141
+ };
142
+ const existing = emailMatch ?? phoneMatch ?? await findConsumerByIdentifiers(options.client, identifiers, { maxPages });
143
+ if (!existing?.id) return null;
144
+ if (existing.external_id) {
145
+ if (createPayload.external_id && existing.external_id === createPayload.external_id) {
146
+ return existing.id;
147
+ }
148
+ if (canClaimBy(options.claimExistingConsumerBy, "email") && sameEmail(existing.email, createPayload.email)) {
149
+ return existing.id;
150
+ }
151
+ if (canClaimBy(options.claimExistingConsumerBy, "phone") && samePhone(existing.phone_number, createPayload.phone_number)) {
152
+ return existing.id;
153
+ }
154
+ context.context.logger.error(
155
+ `StreamPay duplicate: consumer ${existing.id} is already linked to external_id=${existing.external_id}`
156
+ );
157
+ throw new api.APIError("CONFLICT", {
158
+ message: "This account cannot be created at this time. Please contact support."
159
+ });
160
+ }
161
+ return existing.id;
162
+ }
163
+ async function ensureConsumerForUser(options, ctx, user) {
164
+ if (user.streampayConsumerId) {
165
+ return { consumerId: user.streampayConsumerId, created: false };
166
+ }
167
+ const maxPages = resolveConsumerLookupMaxPages(options);
168
+ const recovered = await findConsumerByExternalId(options.client, {
169
+ externalId: user.id,
170
+ maxPages
171
+ });
172
+ if (recovered) {
173
+ await persistConsumerId(ctx, user.id, recovered);
174
+ return { consumerId: recovered, created: false };
175
+ }
176
+ if (!user.email) {
177
+ throw new api.APIError("BAD_REQUEST", {
178
+ message: "StreamPay requires an email address to create a consumer."
179
+ });
180
+ }
181
+ const userForParams = { id: user.id, email: user.email };
182
+ if (user.name !== void 0) userForParams.name = user.name;
183
+ const extras = options.getConsumerCreateParams ? await options.getConsumerCreateParams({ user: userForParams }) : {};
184
+ const payload = {
185
+ name: user.name || user.email,
186
+ email: user.email,
187
+ external_id: user.id,
188
+ ...extras
189
+ };
190
+ try {
191
+ const consumer = await options.client.createConsumer(payload);
192
+ if (!consumer.id) {
193
+ throw new api.APIError("INTERNAL_SERVER_ERROR", {
194
+ message: "StreamPay consumer was created but did not return an id."
195
+ });
196
+ }
197
+ await persistConsumerId(ctx, user.id, consumer.id);
198
+ return { consumerId: consumer.id, created: true };
199
+ } catch (err) {
200
+ if (err instanceof api.APIError) throw err;
201
+ if (isDuplicateConsumerError(err)) {
202
+ const reusedId = await resolveDuplicateConsumer(options, payload, ctx);
203
+ if (reusedId) {
204
+ try {
205
+ await options.client.updateConsumer(reusedId, { external_id: user.id });
206
+ } catch (backfillErr) {
207
+ ctx.context.logger.error(
208
+ `StreamPay consumer external_id backfill failed for user=${user.id} consumer=${reusedId}: ${formatStreamPayError(backfillErr)}`
209
+ );
210
+ }
211
+ await persistConsumerId(ctx, user.id, reusedId);
212
+ return { consumerId: reusedId, created: false };
213
+ }
214
+ }
215
+ ctx.context.logger.error(
216
+ `StreamPay consumer creation failed for user=${user.id}: ${formatStreamPayError(err)}`
217
+ );
218
+ throw new api.APIError("INTERNAL_SERVER_ERROR", {
219
+ message: "StreamPay consumer provisioning failed. Please try again."
220
+ });
221
+ }
222
+ }
223
+ async function persistConsumerId(ctx, userId, consumerId) {
224
+ try {
225
+ await ctx.context.internalAdapter.updateUser(userId, {
226
+ streampayConsumerId: consumerId
227
+ });
228
+ } catch (err) {
229
+ ctx.context.logger.error(
230
+ `StreamPay consumer link write failed for user=${userId}: ${formatStreamPayError(err)}`
231
+ );
232
+ }
233
+ }
234
+ function toAPIError(messageOrConfig, err, logger) {
235
+ if (err instanceof api.APIError) throw err;
236
+ const { logPrefix, userMessage } = typeof messageOrConfig === "string" ? { logPrefix: messageOrConfig, userMessage: messageOrConfig } : messageOrConfig;
237
+ const detail = err instanceof Error ? err.message : String(err);
238
+ logger.error(`${logPrefix} ${detail}`);
239
+ throw new api.APIError("INTERNAL_SERVER_ERROR", { message: userMessage });
240
+ }
241
+ function rejectUnauthorized(user, anonymousMessage) {
242
+ if (!user) {
243
+ throw new api.APIError("UNAUTHORIZED", { message: "Session user is missing." });
244
+ }
245
+ if (user.isAnonymous) {
246
+ throw new api.APIError("UNAUTHORIZED", { message: anonymousMessage });
247
+ }
248
+ }
249
+
45
250
  // src/utils/session.ts
46
251
  function asSessionUser(user) {
47
252
  if (user === null || typeof user !== "object") return null;
@@ -139,13 +344,15 @@ function resolveRedirectUrl(urlOrPath, request, baseURL) {
139
344
  if (!urlOrPath) return void 0;
140
345
  return new URL(urlOrPath, request?.url ?? baseURL).toString();
141
346
  }
142
- async function resolveConsumerId(client, body, user) {
347
+ async function resolveConsumerId(options, ctx, body, user) {
143
348
  if (body.consumerId) return body.consumerId;
144
349
  if (!user) return null;
145
- if (user.streampayConsumerId) return user.streampayConsumerId;
146
- return findConsumerByExternalId(client, { externalId: user.id });
350
+ if (user.isAnonymous) return null;
351
+ const { consumerId } = await ensureConsumerForUser(options, ctx, user);
352
+ return consumerId;
147
353
  }
148
- var checkout = (checkoutOptions = {}) => (client) => {
354
+ var checkout = (checkoutOptions = {}) => (options) => {
355
+ const client = options.client;
149
356
  return {
150
357
  checkout: api.createAuthEndpoint(
151
358
  "/checkout",
@@ -169,7 +376,7 @@ var checkout = (checkoutOptions = {}) => (client) => {
169
376
  }
170
377
  }
171
378
  const items = await resolveProducts(ctx.body, checkoutOptions);
172
- const consumerId = await resolveConsumerId(client, ctx.body, sessionUser);
379
+ const consumerId = await resolveConsumerId(options, ctx, ctx.body, sessionUser);
173
380
  const successUrl = resolveRedirectUrl(
174
381
  ctx.body.successUrl ?? checkoutOptions.successUrl,
175
382
  ctx.request,
@@ -223,60 +430,52 @@ var checkout = (checkoutOptions = {}) => (client) => {
223
430
  redirect: ctx.body.redirect ?? true
224
431
  });
225
432
  } catch (err) {
226
- if (err instanceof api.APIError) throw err;
227
- const message = err instanceof Error ? err.message : String(err);
228
- ctx.context.logger.error(`StreamPay checkout creation failed: ${message}`);
229
- throw new api.APIError("INTERNAL_SERVER_ERROR", {
230
- message: "StreamPay checkout creation failed."
231
- });
433
+ toAPIError(
434
+ {
435
+ logPrefix: "StreamPay checkout creation failed:",
436
+ userMessage: "StreamPay checkout creation failed."
437
+ },
438
+ err,
439
+ ctx.context.logger
440
+ );
232
441
  }
233
442
  }
234
443
  )
235
444
  };
236
445
  };
237
- var PaginationQuery = zod.z.object({
238
- page: zod.z.coerce.number().int().positive().optional(),
239
- limit: zod.z.coerce.number().int().positive().max(200).optional()
240
- }).optional();
241
- async function requireConsumerId(client, user, maxPages) {
242
- if (!user) {
243
- throw new api.APIError("UNAUTHORIZED", { message: "Session user is missing." });
244
- }
446
+ async function getConsumerIdOrNull(client, user, maxPages) {
447
+ rejectUnauthorized(user, "Anonymous users cannot access the billing portal.");
245
448
  if (user.streampayConsumerId) return user.streampayConsumerId;
246
- const resolved = await findConsumerByExternalId(client, {
449
+ return findConsumerByExternalId(client, {
247
450
  externalId: user.id,
248
451
  maxPages
249
452
  });
250
- if (!resolved) {
251
- throw new api.APIError("NOT_FOUND", {
252
- message: "No StreamPay consumer is linked to this user."
253
- });
254
- }
255
- return resolved;
256
453
  }
257
- function toAPIError(message, err, logger) {
258
- if (err instanceof api.APIError) throw err;
259
- const detail = err instanceof Error ? err.message : String(err);
260
- logger.error(`${message} ${detail}`);
261
- throw new api.APIError("INTERNAL_SERVER_ERROR", { message });
262
- }
263
- function buildPagination(query) {
264
- const result = {};
265
- if (query?.page !== void 0) result.page = query.page;
266
- if (query?.limit !== void 0) result.size = query.limit;
267
- return result;
454
+ async function collectByConsumer(fetchPage, consumerId, maxPages) {
455
+ const out = [];
456
+ for (let page = 1; page <= maxPages; page++) {
457
+ const response = await fetchPage({ page, size: 100 });
458
+ for (const item of response.data ?? []) {
459
+ if (item.organization_consumer_id === consumerId) out.push(item);
460
+ }
461
+ if (response.pagination?.has_next_page !== true) break;
462
+ }
463
+ return out;
268
464
  }
269
- var portal = ({ consumerLookupMaxPages = 10 } = {}) => (client) => {
465
+ var portal = ({ consumerLookupMaxPages } = {}) => (options) => {
466
+ const client = options.client;
467
+ const maxPages = resolveConsumerLookupMaxPages(options, consumerLookupMaxPages);
270
468
  return {
271
469
  state: api.createAuthEndpoint(
272
470
  "/consumer/state",
273
471
  { method: "GET", use: [api.sessionMiddleware] },
274
472
  async (ctx) => {
275
473
  const user = asSessionUser(ctx.context.session?.user);
276
- const consumerId = await requireConsumerId(client, user, consumerLookupMaxPages);
474
+ const consumerId = await getConsumerIdOrNull(client, user, maxPages);
475
+ if (!consumerId) return ctx.json({ hasConsumer: false, consumer: null });
277
476
  try {
278
477
  const consumer = await client.getConsumer(consumerId);
279
- return ctx.json(consumer);
478
+ return ctx.json({ hasConsumer: true, consumer });
280
479
  } catch (err) {
281
480
  toAPIError("StreamPay getConsumer failed.", err, ctx.context.logger);
282
481
  }
@@ -284,22 +483,20 @@ var portal = ({ consumerLookupMaxPages = 10 } = {}) => (client) => {
284
483
  ),
285
484
  subscriptions: api.createAuthEndpoint(
286
485
  "/consumer/subscriptions/list",
287
- {
288
- method: "GET",
289
- query: PaginationQuery,
290
- use: [api.sessionMiddleware]
291
- },
486
+ { method: "GET", use: [api.sessionMiddleware] },
292
487
  async (ctx) => {
293
488
  const user = asSessionUser(ctx.context.session?.user);
294
- const consumerId = await requireConsumerId(client, user, consumerLookupMaxPages);
489
+ const consumerId = await getConsumerIdOrNull(client, user, maxPages);
490
+ if (!consumerId) {
491
+ return ctx.json({ hasConsumer: false, data: [] });
492
+ }
295
493
  try {
296
- const result = await client.listSubscriptions(buildPagination(ctx.query));
297
- const items = result.data ?? [];
298
- const filtered = items.filter((s) => s.organization_consumer_id === consumerId);
299
- return ctx.json({
300
- data: filtered,
301
- pagination: result.pagination
302
- });
494
+ const items = await collectByConsumer(
495
+ (params) => client.listSubscriptions(params),
496
+ consumerId,
497
+ maxPages
498
+ );
499
+ return ctx.json({ hasConsumer: true, data: items });
303
500
  } catch (err) {
304
501
  toAPIError("StreamPay listSubscriptions failed.", err, ctx.context.logger);
305
502
  }
@@ -307,50 +504,24 @@ var portal = ({ consumerLookupMaxPages = 10 } = {}) => (client) => {
307
504
  ),
308
505
  invoices: api.createAuthEndpoint(
309
506
  "/consumer/invoices/list",
310
- {
311
- method: "GET",
312
- query: PaginationQuery,
313
- use: [api.sessionMiddleware]
314
- },
507
+ { method: "GET", use: [api.sessionMiddleware] },
315
508
  async (ctx) => {
316
509
  const user = asSessionUser(ctx.context.session?.user);
317
- const consumerId = await requireConsumerId(client, user, consumerLookupMaxPages);
510
+ const consumerId = await getConsumerIdOrNull(client, user, maxPages);
511
+ if (!consumerId) {
512
+ return ctx.json({ hasConsumer: false, data: [] });
513
+ }
318
514
  try {
319
- const result = await client.listInvoices(buildPagination(ctx.query));
320
- const items = result.data ?? [];
321
- const filtered = items.filter(
322
- (invoice) => invoice.organization_consumer_id === consumerId
515
+ const items = await collectByConsumer(
516
+ (params) => client.listInvoices(params),
517
+ consumerId,
518
+ maxPages
323
519
  );
324
- return ctx.json({ data: filtered, pagination: result.pagination });
520
+ return ctx.json({ hasConsumer: true, data: items });
325
521
  } catch (err) {
326
522
  toAPIError("StreamPay listInvoices failed.", err, ctx.context.logger);
327
523
  }
328
524
  }
329
- ),
330
- payments: api.createAuthEndpoint(
331
- "/consumer/payments/list",
332
- {
333
- method: "GET",
334
- query: zod.z.object({
335
- page: zod.z.coerce.number().int().positive().optional(),
336
- limit: zod.z.coerce.number().int().positive().max(200).optional(),
337
- invoiceId: zod.z.string().uuid().optional()
338
- }).optional(),
339
- use: [api.sessionMiddleware]
340
- },
341
- async (ctx) => {
342
- const user = asSessionUser(ctx.context.session?.user);
343
- await requireConsumerId(client, user, consumerLookupMaxPages);
344
- const invoiceId = ctx.query?.invoiceId;
345
- try {
346
- const params = {};
347
- if (invoiceId) params.invoice_id = invoiceId;
348
- const result = await client.listPayments(params);
349
- return ctx.json(result);
350
- } catch (err) {
351
- toAPIError("StreamPay listPayments failed.", err, ctx.context.logger);
352
- }
353
- }
354
525
  )
355
526
  };
356
527
  };
@@ -364,24 +535,22 @@ var FreezeBody = zod.z.object({
364
535
  freezeEndDatetime: zod.z.string().datetime().nullable().optional(),
365
536
  notes: zod.z.string().optional()
366
537
  });
367
- async function assertOwnsSubscription(client, user, subscriptionId, maxPages) {
368
- if (!user) {
369
- throw new api.APIError("UNAUTHORIZED", { message: "Session user is missing." });
370
- }
371
- const consumerId = user.streampayConsumerId ?? await findConsumerByExternalId(client, { externalId: user.id, maxPages });
372
- if (!consumerId) {
373
- throw new api.APIError("NOT_FOUND", {
374
- message: "No StreamPay consumer is linked to this user."
538
+ async function assertOwnsSubscription(options, _ctx, user, subscriptionId) {
539
+ rejectUnauthorized(user, "Anonymous users cannot manage subscriptions.");
540
+ if (!user.streampayConsumerId) {
541
+ throw new api.APIError("FORBIDDEN", {
542
+ message: "Subscription does not belong to this user."
375
543
  });
376
544
  }
377
- const subscription = await client.getSubscription(subscriptionId);
378
- if (subscription.organization_consumer_id !== consumerId) {
545
+ const subscription = await options.client.getSubscription(subscriptionId);
546
+ if (subscription.organization_consumer_id !== user.streampayConsumerId) {
379
547
  throw new api.APIError("FORBIDDEN", {
380
548
  message: "Subscription does not belong to this user."
381
549
  });
382
550
  }
383
551
  }
384
- var subscriptions = ({ consumerLookupMaxPages = 10 } = {}) => (client) => {
552
+ var subscriptions = (_subscriptionsOptions = {}) => (options) => {
553
+ const client = options.client;
385
554
  return {
386
555
  cancelSubscription: api.createAuthEndpoint(
387
556
  "/consumer/subscriptions/cancel",
@@ -392,12 +561,7 @@ var subscriptions = ({ consumerLookupMaxPages = 10 } = {}) => (client) => {
392
561
  },
393
562
  async (ctx) => {
394
563
  const sessionUser = asSessionUser(ctx.context.session?.user);
395
- await assertOwnsSubscription(
396
- client,
397
- sessionUser,
398
- ctx.body.subscriptionId,
399
- consumerLookupMaxPages
400
- );
564
+ await assertOwnsSubscription(options, ctx, sessionUser, ctx.body.subscriptionId);
401
565
  const payload = {
402
566
  cancel_related_invoices: ctx.body.cancelRelatedInvoices ?? false
403
567
  };
@@ -405,12 +569,14 @@ var subscriptions = ({ consumerLookupMaxPages = 10 } = {}) => (client) => {
405
569
  const result = await client.cancelSubscription(ctx.body.subscriptionId, payload);
406
570
  return ctx.json(result);
407
571
  } catch (err) {
408
- if (err instanceof api.APIError) throw err;
409
- const message = err instanceof Error ? err.message : String(err);
410
- ctx.context.logger.error(`StreamPay cancelSubscription failed: ${message}`);
411
- throw new api.APIError("INTERNAL_SERVER_ERROR", {
412
- message: "Subscription cancellation failed."
413
- });
572
+ toAPIError(
573
+ {
574
+ logPrefix: "StreamPay cancelSubscription failed:",
575
+ userMessage: "Subscription cancellation failed."
576
+ },
577
+ err,
578
+ ctx.context.logger
579
+ );
414
580
  }
415
581
  }
416
582
  ),
@@ -423,12 +589,7 @@ var subscriptions = ({ consumerLookupMaxPages = 10 } = {}) => (client) => {
423
589
  },
424
590
  async (ctx) => {
425
591
  const sessionUser = asSessionUser(ctx.context.session?.user);
426
- await assertOwnsSubscription(
427
- client,
428
- sessionUser,
429
- ctx.body.subscriptionId,
430
- consumerLookupMaxPages
431
- );
592
+ await assertOwnsSubscription(options, ctx, sessionUser, ctx.body.subscriptionId);
432
593
  const payload = {
433
594
  freeze_start_datetime: ctx.body.freezeStartDatetime
434
595
  };
@@ -442,12 +603,14 @@ var subscriptions = ({ consumerLookupMaxPages = 10 } = {}) => (client) => {
442
603
  const result = await client.freezeSubscription(ctx.body.subscriptionId, payload);
443
604
  return ctx.json(result);
444
605
  } catch (err) {
445
- if (err instanceof api.APIError) throw err;
446
- const message = err instanceof Error ? err.message : String(err);
447
- ctx.context.logger.error(`StreamPay freezeSubscription failed: ${message}`);
448
- throw new api.APIError("INTERNAL_SERVER_ERROR", {
449
- message: "Subscription freeze failed."
450
- });
606
+ toAPIError(
607
+ {
608
+ logPrefix: "StreamPay freezeSubscription failed:",
609
+ userMessage: "Subscription freeze failed."
610
+ },
611
+ err,
612
+ ctx.context.logger
613
+ );
451
614
  }
452
615
  }
453
616
  )
@@ -455,38 +618,89 @@ var subscriptions = ({ consumerLookupMaxPages = 10 } = {}) => (client) => {
455
618
  };
456
619
 
457
620
  // src/webhooks/dispatcher.ts
458
- var HANDLER_BY_EVENT = {
459
- PAYMENT_SUCCEEDED: "onPaymentSucceeded",
460
- PAYMENT_FAILED: "onPaymentFailed",
461
- PAYMENT_CANCELED: "onPaymentCanceled",
462
- PAYMENT_REFUNDED: "onPaymentRefunded",
463
- PAYMENT_MARKED_AS_PAID: "onPaymentMarkedAsPaid",
464
- INVOICE_CREATED: "onInvoiceCreated",
465
- INVOICE_SENT: "onInvoiceSent",
466
- INVOICE_ACCEPTED: "onInvoiceAccepted",
467
- INVOICE_REJECTED: "onInvoiceRejected",
468
- INVOICE_COMPLETED: "onInvoiceCompleted",
469
- INVOICE_CANCELED: "onInvoiceCanceled",
470
- INVOICE_UPDATED: "onInvoiceUpdated",
471
- SUBSCRIPTION_CREATED: "onSubscriptionCreated",
472
- SUBSCRIPTION_ACTIVATED: "onSubscriptionActivated",
473
- SUBSCRIPTION_INACTIVATED: "onSubscriptionInactivated",
474
- SUBSCRIPTION_CANCELED: "onSubscriptionCanceled",
475
- SUBSCRIPTION_FROZEN: "onSubscriptionFrozen",
476
- SUBSCRIPTION_CYCLE_RENEWAL_FAILED: "onSubscriptionCycleRenewalFailed",
477
- SUBSCRIPTION_CANCEL_AT_PERIOD_END: "onSubscriptionCancelAtPeriodEnd",
478
- SUBSCRIPTION_FREEZE_NOW: "onSubscriptionFreezeNow",
479
- SUBSCRIPTION_UNFREEZE_NOW: "onSubscriptionUnfreezeNow",
480
- SUBSCRIPTION_UNFREEZE_FUTURE: "onSubscriptionUnfreezeFuture",
481
- SUBSCRIPTION_FREEZE_CANCEL: "onSubscriptionFreezeCancel",
482
- PAYMENT_LINK_PAY_ATTEMPT_FAILED: "onPaymentLinkPayAttemptFailed"
483
- };
484
621
  async function dispatchWebhook(payload, handlers) {
485
622
  if (handlers.onPayload) await handlers.onPayload(payload);
486
- const handlerKey = HANDLER_BY_EVENT[payload.event_type];
487
- if (!handlerKey) return;
488
- const handler = handlers[handlerKey];
489
- if (handler) await handler(payload);
623
+ switch (payload.event_type) {
624
+ // Payment
625
+ case "PAYMENT_SUCCEEDED":
626
+ await handlers.onPaymentSucceeded?.(payload);
627
+ return;
628
+ case "PAYMENT_FAILED":
629
+ await handlers.onPaymentFailed?.(payload);
630
+ return;
631
+ case "PAYMENT_CANCELED":
632
+ await handlers.onPaymentCanceled?.(payload);
633
+ return;
634
+ case "PAYMENT_REFUNDED":
635
+ await handlers.onPaymentRefunded?.(payload);
636
+ return;
637
+ case "PAYMENT_MARKED_AS_PAID":
638
+ await handlers.onPaymentMarkedAsPaid?.(payload);
639
+ return;
640
+ // Invoice
641
+ case "INVOICE_CREATED":
642
+ await handlers.onInvoiceCreated?.(payload);
643
+ return;
644
+ case "INVOICE_SENT":
645
+ await handlers.onInvoiceSent?.(payload);
646
+ return;
647
+ case "INVOICE_ACCEPTED":
648
+ await handlers.onInvoiceAccepted?.(payload);
649
+ return;
650
+ case "INVOICE_REJECTED":
651
+ await handlers.onInvoiceRejected?.(payload);
652
+ return;
653
+ case "INVOICE_COMPLETED":
654
+ await handlers.onInvoiceCompleted?.(payload);
655
+ return;
656
+ case "INVOICE_CANCELED":
657
+ await handlers.onInvoiceCanceled?.(payload);
658
+ return;
659
+ case "INVOICE_UPDATED":
660
+ await handlers.onInvoiceUpdated?.(payload);
661
+ return;
662
+ // Subscription
663
+ case "SUBSCRIPTION_CREATED":
664
+ await handlers.onSubscriptionCreated?.(payload);
665
+ return;
666
+ case "SUBSCRIPTION_ACTIVATED":
667
+ await handlers.onSubscriptionActivated?.(payload);
668
+ return;
669
+ case "SUBSCRIPTION_INACTIVATED":
670
+ await handlers.onSubscriptionInactivated?.(payload);
671
+ return;
672
+ case "SUBSCRIPTION_CANCELED":
673
+ await handlers.onSubscriptionCanceled?.(payload);
674
+ return;
675
+ case "SUBSCRIPTION_FROZEN":
676
+ await handlers.onSubscriptionFrozen?.(payload);
677
+ return;
678
+ case "SUBSCRIPTION_CYCLE_RENEWAL_FAILED":
679
+ await handlers.onSubscriptionCycleRenewalFailed?.(payload);
680
+ return;
681
+ case "SUBSCRIPTION_CANCEL_AT_PERIOD_END":
682
+ await handlers.onSubscriptionCancelAtPeriodEnd?.(payload);
683
+ return;
684
+ case "SUBSCRIPTION_FREEZE_NOW":
685
+ await handlers.onSubscriptionFreezeNow?.(payload);
686
+ return;
687
+ case "SUBSCRIPTION_UNFREEZE_NOW":
688
+ await handlers.onSubscriptionUnfreezeNow?.(payload);
689
+ return;
690
+ case "SUBSCRIPTION_UNFREEZE_FUTURE":
691
+ await handlers.onSubscriptionUnfreezeFuture?.(payload);
692
+ return;
693
+ case "SUBSCRIPTION_FREEZE_CANCEL":
694
+ await handlers.onSubscriptionFreezeCancel?.(payload);
695
+ return;
696
+ // Payment Link
697
+ case "PAYMENT_LINK_PAY_ATTEMPT_FAILED":
698
+ await handlers.onPaymentLinkPayAttemptFailed?.(payload);
699
+ return;
700
+ default: {
701
+ return;
702
+ }
703
+ }
490
704
  }
491
705
  var StreamPayWebhookError = class extends Error {
492
706
  reason;
@@ -554,8 +768,8 @@ function parseWebhookPayload(value) {
554
768
  function toErrorCode(reason) {
555
769
  return reason === "MISSING_HEADER" || reason === "INVALID_SIGNATURE" || reason === "EXPIRED" ? "UNAUTHORIZED" : "BAD_REQUEST";
556
770
  }
557
- var webhooks = (options) => (_client) => {
558
- const { secret, toleranceSeconds, ...handlers } = options;
771
+ var webhooks = (webhooksOptions) => (_options) => {
772
+ const { secret, toleranceSeconds, ...handlers } = webhooksOptions;
559
773
  return {
560
774
  streampayWebhooks: api.createAuthEndpoint(
561
775
  "/streampay/webhooks",
@@ -620,61 +834,9 @@ var webhooks = (options) => (_client) => {
620
834
  )
621
835
  };
622
836
  };
623
-
624
- // src/utils/format-error.ts
625
- function formatStreamPayError(err) {
626
- if (!(err instanceof Error)) return String(err);
627
- if (!("body" in err)) return err.message;
628
- const { body } = err;
629
- if (!body || typeof body !== "object") return err.message;
630
- const envelope = readEnvelopeMessage(body);
631
- if (envelope !== null) return envelope;
632
- const validation = readValidationMessage(body);
633
- if (validation !== null) return validation;
634
- try {
635
- return JSON.stringify(body);
636
- } catch {
637
- return err.message;
638
- }
639
- }
640
- function readEnvelopeMessage(body) {
641
- if (!("error" in body) || !body.error || typeof body.error !== "object") {
642
- return null;
643
- }
644
- const error = body.error;
645
- if ("additional_info" in error && typeof error.additional_info === "string") {
646
- return error.additional_info;
647
- }
648
- if ("message" in error && typeof error.message === "string") {
649
- return error.message;
650
- }
651
- return null;
652
- }
653
- function readValidationMessage(body) {
654
- if (!("detail" in body) || !Array.isArray(body.detail) || body.detail.length === 0) {
655
- return null;
656
- }
657
- return body.detail.map(formatValidationEntry).join("; ");
658
- }
659
- function formatValidationEntry(entry) {
660
- if (!entry || typeof entry !== "object") return String(entry);
661
- const loc = "loc" in entry && Array.isArray(entry.loc) ? entry.loc.join(".") : "?";
662
- const msg = "msg" in entry && typeof entry.msg === "string" ? entry.msg : "invalid";
663
- return `${loc}: ${msg}`;
664
- }
665
-
666
- // src/hooks/consumer.ts
667
837
  var isAnonymous = (user) => "isAnonymous" in user && user.isAnonymous === true;
668
- function sameEmail(a, b) {
669
- if (!a || !b) return false;
670
- return a.trim().toLowerCase() === b.trim().toLowerCase();
671
- }
672
- function samePhone(a, b) {
673
- if (!a || !b) return false;
674
- return a.trim() === b.trim();
675
- }
676
- function canClaimBy(mode, identifier) {
677
- return mode?.includes(identifier) ?? false;
838
+ function hasInternalAdapter(ctx) {
839
+ 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";
678
840
  }
679
841
  var onBeforeUserCreate = (options) => async (user, context) => {
680
842
  if (!context || !options.createConsumerOnSignUp) return void 0;
@@ -706,55 +868,14 @@ var onBeforeUserCreate = (options) => async (user, context) => {
706
868
  return { data: { streampayConsumerId: reusedId } };
707
869
  }
708
870
  }
709
- throw new api.APIError("INTERNAL_SERVER_ERROR", {
710
- message: `StreamPay consumer creation failed: ${formatStreamPayError(err)}`
711
- });
712
- }
713
- };
714
- function isDuplicateConsumerError(err) {
715
- if (!(err instanceof Error)) return false;
716
- if (!("body" in err)) return false;
717
- const { body } = err;
718
- if (!body || typeof body !== "object") return false;
719
- if (!("error" in body) || !body.error || typeof body.error !== "object") {
720
- return false;
721
- }
722
- const error = body.error;
723
- return "code" in error && typeof error.code === "string" && error.code === "DUPLICATE_CONSUMER";
724
- }
725
- async function resolveDuplicateConsumer(options, createPayload, context) {
726
- const emailMatch = createPayload.email ? await findConsumerByIdentifiers(options.client, {
727
- email: createPayload.email
728
- }) : null;
729
- const phoneMatch = !emailMatch && createPayload.phone_number ? await findConsumerByIdentifiers(options.client, {
730
- phone_number: createPayload.phone_number
731
- }) : null;
732
- const identifiers = {
733
- email: createPayload.email ?? null,
734
- phone_number: createPayload.phone_number ?? null,
735
- external_id: createPayload.external_id ?? null,
736
- iban: createPayload.iban ?? null
737
- };
738
- const existing = emailMatch ?? phoneMatch ?? await findConsumerByIdentifiers(options.client, identifiers);
739
- if (!existing?.id) {
740
- return null;
741
- }
742
- if (existing.external_id) {
743
- if (canClaimBy(options.claimExistingConsumerBy, "email") && sameEmail(existing.email, createPayload.email)) {
744
- return existing.id;
745
- }
746
- if (canClaimBy(options.claimExistingConsumerBy, "phone") && samePhone(existing.phone_number, createPayload.phone_number)) {
747
- return existing.id;
748
- }
749
871
  context.context.logger.error(
750
- `StreamPay duplicate: consumer ${existing.id} is already linked to external_id=${existing.external_id}`
872
+ `StreamPay consumer creation failed for user=${user.id ?? "<pre-insert>"}: ${formatStreamPayError(err)}`
751
873
  );
752
- throw new api.APIError("CONFLICT", {
753
- message: "This account cannot be created at this time. Please contact support."
874
+ throw new api.APIError("INTERNAL_SERVER_ERROR", {
875
+ message: "StreamPay consumer provisioning failed. Please try again."
754
876
  });
755
877
  }
756
- return existing.id;
757
- }
878
+ };
758
879
  var onAfterUserCreate = (options) => async (user, context) => {
759
880
  if (!context || !options.createConsumerOnSignUp) return;
760
881
  if (isAnonymous(user)) return;
@@ -766,51 +887,67 @@ var onAfterUserCreate = (options) => async (user, context) => {
766
887
  });
767
888
  } catch (err) {
768
889
  context.context.logger.error(
769
- `StreamPay consumer external_id link failed: ${formatStreamPayError(err)}`
890
+ `StreamPay consumer external_id link failed for user=${sessionUser.id} consumer=${sessionUser.streampayConsumerId}: ${formatStreamPayError(err)}`
770
891
  );
771
892
  }
772
893
  };
773
894
  var onUserUpdate = (options) => async (user, context) => {
774
- if (!context || !options.createConsumerOnSignUp) return;
895
+ if (!context) return;
775
896
  if (isAnonymous(user)) return;
776
897
  const sessionUser = asSessionUser(user);
777
- if (!sessionUser) return;
778
- const consumerId = await resolveConsumerId2(options, sessionUser);
779
- if (!consumerId) return;
780
- const update = {};
781
- if (sessionUser.name !== void 0) update.name = sessionUser.name;
782
- if (sessionUser.email !== void 0) update.email = sessionUser.email;
898
+ if (!sessionUser?.streampayConsumerId) return;
783
899
  try {
784
- await options.client.updateConsumer(consumerId, update);
900
+ const remote = await options.client.getConsumer(sessionUser.streampayConsumerId);
901
+ if (remote.is_deleted === true) return;
902
+ const patch = {};
903
+ if (sessionUser.name !== void 0 && remote.name !== sessionUser.name) {
904
+ patch.name = sessionUser.name;
905
+ }
906
+ if (sessionUser.email !== void 0 && remote.email !== sessionUser.email) {
907
+ patch.email = sessionUser.email;
908
+ }
909
+ if (Object.keys(patch).length === 0) return;
910
+ await options.client.updateConsumer(sessionUser.streampayConsumerId, patch);
785
911
  } catch (err) {
912
+ if (isNotFoundError(err)) {
913
+ context.context.logger.error(
914
+ `StreamPay consumer ${sessionUser.streampayConsumerId} not found for user=${sessionUser.id}; clearing stale link for re-provisioning.`
915
+ );
916
+ if (hasInternalAdapter(context)) {
917
+ try {
918
+ await context.context.internalAdapter.updateUser(sessionUser.id, {
919
+ streampayConsumerId: null
920
+ });
921
+ } catch (clearErr) {
922
+ context.context.logger.error(
923
+ `StreamPay stale-link clear failed for user=${sessionUser.id}: ${formatStreamPayError(clearErr)}`
924
+ );
925
+ }
926
+ }
927
+ return;
928
+ }
786
929
  context.context.logger.error(
787
- `StreamPay consumer update failed: ${formatStreamPayError(err)}`
930
+ `StreamPay consumer update failed for user=${sessionUser.id} consumer=${sessionUser.streampayConsumerId}: ${formatStreamPayError(err)}`
788
931
  );
789
932
  }
790
933
  };
791
934
  var onUserDelete = (options) => async (user, context) => {
792
- if (!context || !options.createConsumerOnSignUp) return;
935
+ if (!context) return;
793
936
  if (isAnonymous(user)) return;
794
937
  const sessionUser = asSessionUser(user);
795
- if (!sessionUser) return;
796
- const consumerId = await resolveConsumerId2(options, sessionUser);
797
- if (!consumerId) return;
938
+ if (!sessionUser?.streampayConsumerId) return;
798
939
  try {
799
- await options.client.deleteConsumer(consumerId);
940
+ await options.client.deleteConsumer(sessionUser.streampayConsumerId);
800
941
  } catch (err) {
801
942
  context.context.logger.error(
802
- `StreamPay consumer delete failed: ${formatStreamPayError(err)}`
943
+ `StreamPay consumer delete failed for user=${sessionUser.id} consumer=${sessionUser.streampayConsumerId}: ${formatStreamPayError(err)}`
803
944
  );
804
945
  }
805
946
  };
806
- async function resolveConsumerId2(options, user) {
807
- if (user.streampayConsumerId) return user.streampayConsumerId;
808
- return findConsumerByExternalId(options.client, { externalId: user.id });
809
- }
810
947
 
811
948
  // src/streampay.ts
812
949
  var streampay = (options) => {
813
- const endpoints = options.use.map((use) => use(options.client)).reduce((acc, plugin) => {
950
+ const endpoints = options.use.map((use) => use(options)).reduce((acc, plugin) => {
814
951
  Object.assign(acc, plugin);
815
952
  return acc;
816
953
  }, {});
@@ -852,22 +989,23 @@ var streampay = (options) => {
852
989
  };
853
990
 
854
991
  // src/webhooks/events.ts
855
- var STREAMPAY_EVENT_TYPES = [
856
- // Payment
992
+ var STREAMPAY_PAYMENT_EVENT_TYPES = [
857
993
  "PAYMENT_SUCCEEDED",
858
994
  "PAYMENT_FAILED",
859
995
  "PAYMENT_CANCELED",
860
996
  "PAYMENT_REFUNDED",
861
- "PAYMENT_MARKED_AS_PAID",
862
- // Invoice
997
+ "PAYMENT_MARKED_AS_PAID"
998
+ ];
999
+ var STREAMPAY_INVOICE_EVENT_TYPES = [
863
1000
  "INVOICE_CREATED",
864
1001
  "INVOICE_SENT",
865
1002
  "INVOICE_ACCEPTED",
866
1003
  "INVOICE_REJECTED",
867
1004
  "INVOICE_COMPLETED",
868
1005
  "INVOICE_CANCELED",
869
- "INVOICE_UPDATED",
870
- // Subscription
1006
+ "INVOICE_UPDATED"
1007
+ ];
1008
+ var STREAMPAY_SUBSCRIPTION_EVENT_TYPES = [
871
1009
  "SUBSCRIPTION_CREATED",
872
1010
  "SUBSCRIPTION_ACTIVATED",
873
1011
  "SUBSCRIPTION_INACTIVATED",
@@ -878,13 +1016,24 @@ var STREAMPAY_EVENT_TYPES = [
878
1016
  "SUBSCRIPTION_FREEZE_NOW",
879
1017
  "SUBSCRIPTION_UNFREEZE_NOW",
880
1018
  "SUBSCRIPTION_UNFREEZE_FUTURE",
881
- "SUBSCRIPTION_FREEZE_CANCEL",
882
- // Payment Link
1019
+ "SUBSCRIPTION_FREEZE_CANCEL"
1020
+ ];
1021
+ var STREAMPAY_PAYMENT_LINK_EVENT_TYPES = [
883
1022
  "PAYMENT_LINK_PAY_ATTEMPT_FAILED"
884
1023
  ];
1024
+ var STREAMPAY_EVENT_TYPES = [
1025
+ ...STREAMPAY_PAYMENT_EVENT_TYPES,
1026
+ ...STREAMPAY_INVOICE_EVENT_TYPES,
1027
+ ...STREAMPAY_SUBSCRIPTION_EVENT_TYPES,
1028
+ ...STREAMPAY_PAYMENT_LINK_EVENT_TYPES
1029
+ ];
885
1030
 
886
1031
  exports.CheckoutBody = CheckoutBody;
887
1032
  exports.STREAMPAY_EVENT_TYPES = STREAMPAY_EVENT_TYPES;
1033
+ exports.STREAMPAY_INVOICE_EVENT_TYPES = STREAMPAY_INVOICE_EVENT_TYPES;
1034
+ exports.STREAMPAY_PAYMENT_EVENT_TYPES = STREAMPAY_PAYMENT_EVENT_TYPES;
1035
+ exports.STREAMPAY_PAYMENT_LINK_EVENT_TYPES = STREAMPAY_PAYMENT_LINK_EVENT_TYPES;
1036
+ exports.STREAMPAY_SUBSCRIPTION_EVENT_TYPES = STREAMPAY_SUBSCRIPTION_EVENT_TYPES;
888
1037
  exports.StreamPayWebhookError = StreamPayWebhookError;
889
1038
  exports.checkout = checkout;
890
1039
  exports.dispatchWebhook = dispatchWebhook;