better-auth-streampay 2.2.1 → 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/README.md +69 -482
- package/dist/client.cjs +1 -0
- package/dist/client.cjs.map +1 -1
- package/dist/client.d.cts +7 -3
- package/dist/client.d.ts +7 -3
- package/dist/client.js +1 -0
- package/dist/client.js.map +1 -1
- package/dist/index.cjs +671 -241
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +13 -2
- package/dist/index.d.ts +13 -2
- package/dist/index.js +671 -241
- package/dist/index.js.map +1 -1
- package/dist/{streampay-B3vf7Hvq.d.cts → streampay-uhs67tYl.d.cts} +441 -264
- package/dist/{streampay-B3vf7Hvq.d.ts → streampay-uhs67tYl.d.ts} +441 -264
- package/docs/integration.md +716 -0
- package/docs/staging-validation.md +159 -0
- package/docs/subscriptions.md +271 -0
- package/package.json +12 -4
package/dist/index.js
CHANGED
|
@@ -162,13 +162,33 @@ async function findConsumerByIdentifiers(client, identifiers) {
|
|
|
162
162
|
return null;
|
|
163
163
|
}
|
|
164
164
|
async function searchExact(client, term, predicate) {
|
|
165
|
-
const
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
165
|
+
const seenIds = /* @__PURE__ */ new Set();
|
|
166
|
+
for (let page = 1; ; page++) {
|
|
167
|
+
const response = await client.listConsumers({
|
|
168
|
+
search_term: term,
|
|
169
|
+
page,
|
|
170
|
+
limit: SEARCH_PAGE_SIZE
|
|
171
|
+
});
|
|
172
|
+
const items = response.data ?? [];
|
|
173
|
+
const pagination = response.pagination;
|
|
174
|
+
if (pagination?.current_page !== void 0 && pagination.current_page !== page) {
|
|
175
|
+
throw new Error("Consumer search pagination did not advance to the requested page.");
|
|
176
|
+
}
|
|
177
|
+
const hit = items.find(predicate);
|
|
178
|
+
if (hit) return hit;
|
|
179
|
+
const hasNext = pagination?.has_next_page ?? (pagination?.max_page !== void 0 ? page < pagination.max_page : items.length === SEARCH_PAGE_SIZE);
|
|
180
|
+
if (!hasNext) return null;
|
|
181
|
+
let advanced = false;
|
|
182
|
+
for (const item of items) {
|
|
183
|
+
if (item.id && !seenIds.has(item.id)) {
|
|
184
|
+
seenIds.add(item.id);
|
|
185
|
+
advanced = true;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
if (!advanced || page === Number.MAX_SAFE_INTEGER) {
|
|
189
|
+
throw new Error("Consumer search pagination returned no new consumers.");
|
|
190
|
+
}
|
|
191
|
+
}
|
|
172
192
|
}
|
|
173
193
|
var ErrorShape = z.object({
|
|
174
194
|
code: z.string().optional(),
|
|
@@ -266,6 +286,46 @@ function scopedLogger(logger2) {
|
|
|
266
286
|
function getLogger(ctx) {
|
|
267
287
|
return scopedLogger(ctx.context.logger);
|
|
268
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
|
+
}
|
|
269
329
|
|
|
270
330
|
// src/utils/ensure-consumer.ts
|
|
271
331
|
function canClaimBy(mode, identifier) {
|
|
@@ -308,6 +368,7 @@ async function resolveDuplicateConsumer(options, createPayload, context) {
|
|
|
308
368
|
return existing.id;
|
|
309
369
|
}
|
|
310
370
|
async function ensureConsumerForUser(options, ctx, user) {
|
|
371
|
+
user = await getCurrentConsumerUser(ctx, user);
|
|
311
372
|
if (user.streampayConsumerId) {
|
|
312
373
|
return { consumerId: user.streampayConsumerId, created: false };
|
|
313
374
|
}
|
|
@@ -327,11 +388,11 @@ async function ensureConsumerForUser(options, ctx, user) {
|
|
|
327
388
|
if (user.name !== void 0) userForParams.name = user.name;
|
|
328
389
|
const extras = options.getConsumerCreateParams ? await options.getConsumerCreateParams({ user: userForParams }) : {};
|
|
329
390
|
const payload = {
|
|
391
|
+
consumer_type: "INDIVIDUAL",
|
|
392
|
+
...extras,
|
|
330
393
|
name: user.name || user.email,
|
|
331
394
|
email: user.email,
|
|
332
|
-
external_id: user.id
|
|
333
|
-
consumer_type: "INDIVIDUAL",
|
|
334
|
-
...extras
|
|
395
|
+
external_id: user.id
|
|
335
396
|
};
|
|
336
397
|
try {
|
|
337
398
|
const consumer = await options.client.createConsumer(payload);
|
|
@@ -347,10 +408,25 @@ async function ensureConsumerForUser(options, ctx, user) {
|
|
|
347
408
|
if (isDuplicateConsumerError(err)) {
|
|
348
409
|
const reusedId = await resolveDuplicateConsumer(options, payload, ctx);
|
|
349
410
|
if (reusedId) {
|
|
350
|
-
await
|
|
411
|
+
await persistConsumerId(ctx, user.id, reusedId);
|
|
351
412
|
try {
|
|
352
413
|
await options.client.updateConsumer(reusedId, { external_id: user.id });
|
|
353
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
|
+
}
|
|
354
430
|
getLogger(ctx).error(
|
|
355
431
|
`consumer external_id backfill failed for user=${user.id} consumer=${reusedId}: ${formatStreamPayError(backfillErr)}`
|
|
356
432
|
);
|
|
@@ -359,7 +435,6 @@ async function ensureConsumerForUser(options, ctx, user) {
|
|
|
359
435
|
message: "StreamPay consumer linking failed. Please try again."
|
|
360
436
|
});
|
|
361
437
|
}
|
|
362
|
-
await persistConsumerId(ctx, user.id, reusedId);
|
|
363
438
|
return { consumerId: reusedId, created: false };
|
|
364
439
|
}
|
|
365
440
|
}
|
|
@@ -379,9 +454,15 @@ function consumerLinkUnavailable() {
|
|
|
379
454
|
}
|
|
380
455
|
async function findConsumerOwner(ctx, consumerId) {
|
|
381
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();
|
|
382
463
|
return await ctx.context.adapter.findOne({
|
|
383
464
|
model: "user",
|
|
384
|
-
where
|
|
465
|
+
where
|
|
385
466
|
});
|
|
386
467
|
} catch (err) {
|
|
387
468
|
getLogger(ctx).error(
|
|
@@ -494,31 +575,6 @@ function rejectUnauthorized(user, anonymousMessage) {
|
|
|
494
575
|
}
|
|
495
576
|
}
|
|
496
577
|
|
|
497
|
-
// src/utils/session.ts
|
|
498
|
-
function asSessionUser(user) {
|
|
499
|
-
if (user === null || typeof user !== "object") return null;
|
|
500
|
-
if (!("id" in user) || typeof user.id !== "string") return null;
|
|
501
|
-
const result = { id: user.id };
|
|
502
|
-
if ("email" in user && typeof user.email === "string") {
|
|
503
|
-
result.email = user.email;
|
|
504
|
-
}
|
|
505
|
-
if ("name" in user && typeof user.name === "string") {
|
|
506
|
-
result.name = user.name;
|
|
507
|
-
}
|
|
508
|
-
if ("isAnonymous" in user && user.isAnonymous === true) {
|
|
509
|
-
result.isAnonymous = true;
|
|
510
|
-
}
|
|
511
|
-
if ("streampayConsumerId" in user) {
|
|
512
|
-
const value = user.streampayConsumerId;
|
|
513
|
-
if (typeof value === "string") {
|
|
514
|
-
result.streampayConsumerId = value;
|
|
515
|
-
} else if (value === null) {
|
|
516
|
-
result.streampayConsumerId = null;
|
|
517
|
-
}
|
|
518
|
-
}
|
|
519
|
-
return result;
|
|
520
|
-
}
|
|
521
|
-
|
|
522
578
|
// src/plugins/subscriptions/status.ts
|
|
523
579
|
var SUBSCRIPTION_STATUSES = [
|
|
524
580
|
"incomplete",
|
|
@@ -600,7 +656,32 @@ function reconcileProjectionAgainstExisting(existing, projection, options = {})
|
|
|
600
656
|
return projected;
|
|
601
657
|
}
|
|
602
658
|
function projectSubscriptionAgainstExisting(existing, stream) {
|
|
603
|
-
return reconcileProjectionAgainstExisting(existing, projectSubscriptionFields(stream));
|
|
659
|
+
return reconcileProjectionAgainstExisting(existing, projectSubscriptionFields(stream, existing));
|
|
660
|
+
}
|
|
661
|
+
async function persistSubscriptionProjection(adapter, existing, projection, log, source) {
|
|
662
|
+
const stale = existing.providerUpdatedAt instanceof Date && projection.providerUpdatedAt instanceof Date && projection.providerUpdatedAt.getTime() < existing.providerUpdatedAt.getTime();
|
|
663
|
+
if (!stale) {
|
|
664
|
+
const updated = await adapter.update({
|
|
665
|
+
model: SUBSCRIPTION_MODEL,
|
|
666
|
+
update: projection,
|
|
667
|
+
where: [
|
|
668
|
+
{ field: "id", value: existing.id },
|
|
669
|
+
{ field: "providerUpdatedAt", value: existing.providerUpdatedAt ?? null },
|
|
670
|
+
{ field: "streampaySubscriptionId", value: existing.streampaySubscriptionId ?? null },
|
|
671
|
+
{ field: "streampayConsumerId", value: existing.streampayConsumerId ?? null },
|
|
672
|
+
{ field: "status", value: existing.status },
|
|
673
|
+
{ field: "billingStatus", value: existing.billingStatus }
|
|
674
|
+
]
|
|
675
|
+
});
|
|
676
|
+
if (updated) return updated;
|
|
677
|
+
}
|
|
678
|
+
log.warn(
|
|
679
|
+
`${source}: retained newer local subscription state for row=${existing.id}. The provider action is not rolled back.`
|
|
680
|
+
);
|
|
681
|
+
return adapter.findOne({
|
|
682
|
+
model: SUBSCRIPTION_MODEL,
|
|
683
|
+
where: [{ field: "id", value: existing.id }]
|
|
684
|
+
});
|
|
604
685
|
}
|
|
605
686
|
async function applySubscriptionProjection(adapter, stream, log, source) {
|
|
606
687
|
const streampaySubscriptionId = stream?.id;
|
|
@@ -611,11 +692,13 @@ async function applySubscriptionProjection(adapter, stream, log, source) {
|
|
|
611
692
|
where: [{ field: "streampaySubscriptionId", value: streampaySubscriptionId }]
|
|
612
693
|
});
|
|
613
694
|
if (!existing) return;
|
|
614
|
-
await
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
695
|
+
await persistSubscriptionProjection(
|
|
696
|
+
adapter,
|
|
697
|
+
existing,
|
|
698
|
+
projectSubscriptionAgainstExisting(existing, stream),
|
|
699
|
+
log,
|
|
700
|
+
source
|
|
701
|
+
);
|
|
619
702
|
} catch (err) {
|
|
620
703
|
const message = err instanceof Error ? err.message : String(err);
|
|
621
704
|
log.warn(
|
|
@@ -638,7 +721,7 @@ async function syncSubscriptionFromUpstream(client, adapter, streampaySubscripti
|
|
|
638
721
|
}
|
|
639
722
|
await applySubscriptionProjection(adapter, stream, log, source);
|
|
640
723
|
}
|
|
641
|
-
function projectSubscriptionFields(sub) {
|
|
724
|
+
function projectSubscriptionFields(sub, existing) {
|
|
642
725
|
const status = toLocalStatus(sub.status);
|
|
643
726
|
const terminal = isTerminalSubscriptionStatus(status);
|
|
644
727
|
const periodStart = parseDate(sub.current_period_start);
|
|
@@ -656,7 +739,7 @@ function projectSubscriptionFields(sub) {
|
|
|
656
739
|
periodStart,
|
|
657
740
|
periodEnd,
|
|
658
741
|
currentCycleNumber: sub.current_cycle_number ?? null,
|
|
659
|
-
trialStart: sub.trial_end ? parseDate(sub.started_at) ?? periodStart : null,
|
|
742
|
+
trialStart: (sub.trial_end ? parseDate(sub.started_at) ?? periodStart : null) ?? existing?.trialStart ?? null,
|
|
660
743
|
trialEnd: parseDate(sub.trial_end),
|
|
661
744
|
cancelAtPeriodEnd: Boolean(sub.cancel_at_period_end),
|
|
662
745
|
cancelAt: sub.cancel_at_period_end ? periodEnd : null,
|
|
@@ -760,6 +843,7 @@ function projectPlanFields(sub, plans) {
|
|
|
760
843
|
const pendingEffectiveAt = parseDate(sub.pending_change?.effective_at);
|
|
761
844
|
const planChanges = Boolean(inferredPendingPlan) && (inferredPendingPlan !== currentPlan || pendingProductId !== currentProductId);
|
|
762
845
|
return {
|
|
846
|
+
catalogMapped: Boolean(currentPlan),
|
|
763
847
|
...currentPlan ? {
|
|
764
848
|
plan: currentPlan,
|
|
765
849
|
planVersion: configuredCurrent?.version ?? null,
|
|
@@ -810,8 +894,9 @@ function isUniqueConstraintError(err) {
|
|
|
810
894
|
}
|
|
811
895
|
var WEBHOOK_PROCESSING_LEASE_MS = 2 * 60 * 1e3;
|
|
812
896
|
var WEBHOOK_RETRY_DELAYS_MS = [5, 30, 120, 360, 720].map((minutes) => minutes * 60 * 1e3);
|
|
813
|
-
async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader, maxAttempts) {
|
|
814
|
-
const
|
|
897
|
+
async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader, maxAttempts, scope) {
|
|
898
|
+
const sourceEventId = extractEventId(payload);
|
|
899
|
+
const eventId = sourceEventId && (scope ? `${scope}:${sourceEventId}` : sourceEventId);
|
|
815
900
|
if (!eventId) {
|
|
816
901
|
logger(ctx).warn(
|
|
817
902
|
`webhook ${payload.event_type}: missing entity_id/timestamp \u2014 processing without dedupe.`
|
|
@@ -831,7 +916,9 @@ async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader
|
|
|
831
916
|
receivedAt: now,
|
|
832
917
|
lastAttemptAt: now,
|
|
833
918
|
lockedAt: now,
|
|
834
|
-
lockedBy: lockId
|
|
919
|
+
lockedBy: lockId,
|
|
920
|
+
rawPayload: rawBody,
|
|
921
|
+
signatureHeader
|
|
835
922
|
}
|
|
836
923
|
});
|
|
837
924
|
return { action: "process", row: inserted };
|
|
@@ -843,10 +930,9 @@ async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader
|
|
|
843
930
|
where: [{ field: "eventId", value: eventId }]
|
|
844
931
|
});
|
|
845
932
|
if (!existing) {
|
|
846
|
-
|
|
847
|
-
`
|
|
933
|
+
throw new Error(
|
|
934
|
+
`Webhook inbox row missing after unique conflict for ${eventId}; retry delivery.`
|
|
848
935
|
);
|
|
849
|
-
return { action: "process", row: null };
|
|
850
936
|
}
|
|
851
937
|
if (existing.status === "completed") {
|
|
852
938
|
logger(ctx).info(`webhook ${payload.event_type} (${eventId}) already completed \u2014 skipping.`);
|
|
@@ -1000,7 +1086,7 @@ async function findSubscriptionByStreampayId(ctx, streampaySubscriptionId) {
|
|
|
1000
1086
|
where: [{ field: "streampaySubscriptionId", value: streampaySubscriptionId }]
|
|
1001
1087
|
});
|
|
1002
1088
|
}
|
|
1003
|
-
async function findIncompleteRow(ctx, referenceId, referenceType, plan, paymentLinkId) {
|
|
1089
|
+
async function findIncompleteRow(ctx, referenceId, referenceType, plan, paymentLinkId, consumerId) {
|
|
1004
1090
|
const candidates = await ctx.context.adapter.findMany({
|
|
1005
1091
|
model: SUBSCRIPTION_MODEL2,
|
|
1006
1092
|
where: [
|
|
@@ -1009,13 +1095,15 @@ async function findIncompleteRow(ctx, referenceId, referenceType, plan, paymentL
|
|
|
1009
1095
|
{ field: "status", value: "incomplete" }
|
|
1010
1096
|
]
|
|
1011
1097
|
});
|
|
1012
|
-
const scopedCandidates =
|
|
1098
|
+
const scopedCandidates = candidates.filter(
|
|
1099
|
+
(candidate) => (!referenceType || (candidate.referenceType ?? "user") === referenceType) && (!consumerId || !candidate.streampayConsumerId || candidate.streampayConsumerId === consumerId)
|
|
1100
|
+
);
|
|
1013
1101
|
if (scopedCandidates.length === 0) return null;
|
|
1014
1102
|
if (paymentLinkId) {
|
|
1015
1103
|
const exact = scopedCandidates.find(
|
|
1016
1104
|
(candidate) => candidate.streampayPaymentLinkId === paymentLinkId
|
|
1017
1105
|
);
|
|
1018
|
-
|
|
1106
|
+
return exact ?? null;
|
|
1019
1107
|
}
|
|
1020
1108
|
if (!referenceType && new Set(scopedCandidates.map((candidate) => candidate.referenceType ?? "user")).size > 1) {
|
|
1021
1109
|
return null;
|
|
@@ -1064,6 +1152,31 @@ var SubscriptionCorrelationError = class extends Error {
|
|
|
1064
1152
|
this.name = "SubscriptionCorrelationError";
|
|
1065
1153
|
}
|
|
1066
1154
|
};
|
|
1155
|
+
async function updateReconciledSubscription(ctx, existing, projected, streampaySubscriptionId) {
|
|
1156
|
+
if (existing.providerUpdatedAt instanceof Date && projected.providerUpdatedAt instanceof Date && projected.providerUpdatedAt.getTime() < existing.providerUpdatedAt.getTime()) {
|
|
1157
|
+
throw new Error(
|
|
1158
|
+
`StreamPay returned stale subscription state for sub=${streampaySubscriptionId}. Retry reconciliation.`
|
|
1159
|
+
);
|
|
1160
|
+
}
|
|
1161
|
+
const updated = await ctx.context.adapter.update({
|
|
1162
|
+
model: SUBSCRIPTION_MODEL2,
|
|
1163
|
+
update: projected,
|
|
1164
|
+
where: [
|
|
1165
|
+
{ field: "id", value: existing.id },
|
|
1166
|
+
{ field: "providerUpdatedAt", value: existing.providerUpdatedAt ?? null },
|
|
1167
|
+
{ field: "streampaySubscriptionId", value: existing.streampaySubscriptionId ?? null },
|
|
1168
|
+
{ field: "streampayConsumerId", value: existing.streampayConsumerId ?? null },
|
|
1169
|
+
{ field: "status", value: existing.status },
|
|
1170
|
+
{ field: "billingStatus", value: existing.billingStatus }
|
|
1171
|
+
]
|
|
1172
|
+
});
|
|
1173
|
+
if (!updated) {
|
|
1174
|
+
throw new Error(
|
|
1175
|
+
`Subscription state changed during reconciliation for sub=${streampaySubscriptionId}. Retry delivery.`
|
|
1176
|
+
);
|
|
1177
|
+
}
|
|
1178
|
+
return updated;
|
|
1179
|
+
}
|
|
1067
1180
|
async function reconcileFromStreamPay(ctx, payload, client, plans) {
|
|
1068
1181
|
const streampaySubscriptionId = payload.entity_id;
|
|
1069
1182
|
if (!streampaySubscriptionId) {
|
|
@@ -1082,7 +1195,7 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
|
|
|
1082
1195
|
}
|
|
1083
1196
|
const existing = await findSubscriptionByStreampayId(ctx, streampaySubscriptionId);
|
|
1084
1197
|
let projected = {
|
|
1085
|
-
...projectSubscriptionFields(stream),
|
|
1198
|
+
...projectSubscriptionFields(stream, existing),
|
|
1086
1199
|
...projectPlanFields(stream, plans)
|
|
1087
1200
|
};
|
|
1088
1201
|
const eventAt = parseDate(payload.timestamp);
|
|
@@ -1118,18 +1231,19 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
|
|
|
1118
1231
|
projected.activeSlotKey = desiredSlotKey;
|
|
1119
1232
|
}
|
|
1120
1233
|
}
|
|
1121
|
-
const updated = await
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1234
|
+
const updated = await updateReconciledSubscription(
|
|
1235
|
+
ctx,
|
|
1236
|
+
existing,
|
|
1237
|
+
projected,
|
|
1238
|
+
streampaySubscriptionId
|
|
1239
|
+
);
|
|
1126
1240
|
if (eventIsStale) {
|
|
1127
1241
|
logger(ctx).info(
|
|
1128
1242
|
`webhook ${payload.event_type}: ignored stale lifecycle callback for sub=${streampaySubscriptionId}.`
|
|
1129
1243
|
);
|
|
1130
1244
|
return { row: null, stream };
|
|
1131
1245
|
}
|
|
1132
|
-
return { row: updated
|
|
1246
|
+
return { row: updated, stream };
|
|
1133
1247
|
}
|
|
1134
1248
|
const planName = readMetadataString(payload.data, PLAN_NAME_METADATA_KEY) ?? inferPlanFromItems(stream, plans);
|
|
1135
1249
|
const referenceId = readMetadataString(payload.data, REFERENCE_ID_METADATA_KEY);
|
|
@@ -1151,7 +1265,7 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
|
|
|
1151
1265
|
logger(ctx).warn(
|
|
1152
1266
|
`webhook ${payload.event_type}: referenced subscription row=${localRowId} is missing; rebuilding from signed metadata.`
|
|
1153
1267
|
);
|
|
1154
|
-
} else if (metadataRow.referenceId === referenceId && (!metadataReferenceType || (metadataRow.referenceType ?? "user") === metadataReferenceType) && metadataRow.plan === planName && (!metadataRow.streampaySubscriptionId || metadataRow.streampaySubscriptionId === streampaySubscriptionId) && (!metadataRow.streampayPaymentLinkId || !paymentLinkId || metadataRow.streampayPaymentLinkId === paymentLinkId)) {
|
|
1268
|
+
} else if (metadataRow.referenceId === referenceId && (!metadataReferenceType || (metadataRow.referenceType ?? "user") === metadataReferenceType) && metadataRow.plan === planName && (!metadataRow.streampayConsumerId || !stream.organization_consumer_id || metadataRow.streampayConsumerId === stream.organization_consumer_id) && (!metadataRow.streampaySubscriptionId || metadataRow.streampaySubscriptionId === streampaySubscriptionId) && (!metadataRow.streampayPaymentLinkId || !paymentLinkId || metadataRow.streampayPaymentLinkId === paymentLinkId)) {
|
|
1155
1269
|
const projectedWithSlot = {
|
|
1156
1270
|
...projected,
|
|
1157
1271
|
billingStatus: metadataRow.billingStatus ?? "current",
|
|
@@ -1163,12 +1277,13 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
|
|
|
1163
1277
|
)
|
|
1164
1278
|
}
|
|
1165
1279
|
};
|
|
1166
|
-
const updated = await
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1280
|
+
const updated = await updateReconciledSubscription(
|
|
1281
|
+
ctx,
|
|
1282
|
+
metadataRow,
|
|
1283
|
+
projectedWithSlot,
|
|
1284
|
+
streampaySubscriptionId
|
|
1285
|
+
);
|
|
1286
|
+
return { row: updated, stream };
|
|
1172
1287
|
}
|
|
1173
1288
|
if (metadataRow) {
|
|
1174
1289
|
logger(ctx).warn(
|
|
@@ -1184,7 +1299,8 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
|
|
|
1184
1299
|
referenceId,
|
|
1185
1300
|
metadataReferenceType,
|
|
1186
1301
|
planName,
|
|
1187
|
-
paymentLinkId
|
|
1302
|
+
paymentLinkId,
|
|
1303
|
+
stream.organization_consumer_id ?? null
|
|
1188
1304
|
);
|
|
1189
1305
|
if (incomplete) {
|
|
1190
1306
|
const projectedWithSlot = {
|
|
@@ -1198,13 +1314,14 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
|
|
|
1198
1314
|
)
|
|
1199
1315
|
}
|
|
1200
1316
|
};
|
|
1201
|
-
const updated = await
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1317
|
+
const updated = await updateReconciledSubscription(
|
|
1318
|
+
ctx,
|
|
1319
|
+
incomplete,
|
|
1320
|
+
projectedWithSlot,
|
|
1321
|
+
streampaySubscriptionId
|
|
1322
|
+
);
|
|
1206
1323
|
return {
|
|
1207
|
-
row: updated
|
|
1324
|
+
row: updated,
|
|
1208
1325
|
stream
|
|
1209
1326
|
};
|
|
1210
1327
|
}
|
|
@@ -1253,8 +1370,8 @@ async function syncWebhookPayload(ctx, payload, client, plans, callbacks, option
|
|
|
1253
1370
|
const trackedRowId = claim.row?.id ?? null;
|
|
1254
1371
|
const trackedLockId = claim.row?.lockedBy ?? void 0;
|
|
1255
1372
|
try {
|
|
1256
|
-
if (payload.event_type === "INVOICE_COMPLETED") {
|
|
1257
|
-
await
|
|
1373
|
+
if (payload.event_type === "INVOICE_COMPLETED" || payload.event_type === "SUBSCRIPTION_CYCLE_RENEWED_SUCCESSFULLY") {
|
|
1374
|
+
await handleRenewalEvidence(
|
|
1258
1375
|
ctx,
|
|
1259
1376
|
payload,
|
|
1260
1377
|
client,
|
|
@@ -1295,20 +1412,22 @@ async function syncWebhookPayload(ctx, payload, client, plans, callbacks, option
|
|
|
1295
1412
|
throw err;
|
|
1296
1413
|
}
|
|
1297
1414
|
}
|
|
1298
|
-
async function
|
|
1415
|
+
async function handleRenewalEvidence(ctx, payload, client, plans, callbacks, retryOnCallbackError, retryingRenewalCallback) {
|
|
1299
1416
|
const invoiceId = payload.data?.invoice?.id ?? payload.entity_id;
|
|
1300
1417
|
if (!invoiceId) return;
|
|
1301
|
-
let subscriptionId = null;
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1418
|
+
let subscriptionId = payload.entity_type === "SUBSCRIPTION" ? payload.entity_id : null;
|
|
1419
|
+
if (!subscriptionId) {
|
|
1420
|
+
try {
|
|
1421
|
+
const invoice = await client.getInvoice(invoiceId);
|
|
1422
|
+
if (invoice && typeof invoice === "object" && "subscription_id" in invoice) {
|
|
1423
|
+
const subId = invoice.subscription_id;
|
|
1424
|
+
if (typeof subId === "string" && subId.length > 0) subscriptionId = subId;
|
|
1425
|
+
}
|
|
1426
|
+
} catch (err) {
|
|
1427
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
1428
|
+
logger(ctx).error(`${payload.event_type}: getInvoice(${invoiceId}) failed: ${msg}`);
|
|
1429
|
+
throw err;
|
|
1307
1430
|
}
|
|
1308
|
-
} catch (err) {
|
|
1309
|
-
const msg = err instanceof Error ? err.message : String(err);
|
|
1310
|
-
logger(ctx).error(`INVOICE_COMPLETED: getInvoice(${invoiceId}) failed: ${msg}`);
|
|
1311
|
-
throw err;
|
|
1312
1431
|
}
|
|
1313
1432
|
if (!subscriptionId) return;
|
|
1314
1433
|
let stream;
|
|
@@ -1316,7 +1435,7 @@ async function handleInvoiceCompleted(ctx, payload, client, plans, callbacks, re
|
|
|
1316
1435
|
stream = await client.getSubscription(subscriptionId);
|
|
1317
1436
|
} catch (err) {
|
|
1318
1437
|
const msg = err instanceof Error ? err.message : String(err);
|
|
1319
|
-
logger(ctx).error(
|
|
1438
|
+
logger(ctx).error(`${payload.event_type}: getSubscription(${subscriptionId}) failed: ${msg}`);
|
|
1320
1439
|
throw err;
|
|
1321
1440
|
}
|
|
1322
1441
|
const existing = await findSubscriptionByStreampayId(ctx, subscriptionId);
|
|
@@ -1326,7 +1445,7 @@ async function handleInvoiceCompleted(ctx, payload, client, plans, callbacks, re
|
|
|
1326
1445
|
eventAt && existing.providerUpdatedAt instanceof Date && eventAt.getTime() < existing.providerUpdatedAt.getTime()
|
|
1327
1446
|
);
|
|
1328
1447
|
const projected = {
|
|
1329
|
-
...projectSubscriptionFields(stream),
|
|
1448
|
+
...projectSubscriptionFields(stream, existing),
|
|
1330
1449
|
...projectPlanFields(stream, plans),
|
|
1331
1450
|
...eventIsStale ? existing.billingStatus === "past_due" && toLocalStatus(stream.status) === "active" ? { status: "past_due", billingStatus: "past_due" } : {} : { billingStatus: "current" }
|
|
1332
1451
|
};
|
|
@@ -1334,14 +1453,45 @@ async function handleInvoiceCompleted(ctx, payload, client, plans, callbacks, re
|
|
|
1334
1453
|
const projectedPeriodEnd = projected.periodEnd?.getTime() ?? null;
|
|
1335
1454
|
const periodAdvanced = previousPeriodEnd !== null && projectedPeriodEnd !== null && projectedPeriodEnd > previousPeriodEnd;
|
|
1336
1455
|
const cycleAdvanced = existing.currentCycleNumber !== null && existing.currentCycleNumber !== void 0 && projected.currentCycleNumber !== null && projected.currentCycleNumber !== void 0 && projected.currentCycleNumber > existing.currentCycleNumber;
|
|
1456
|
+
const eventId = extractEventId(payload);
|
|
1457
|
+
const pendingCallback = existing.renewalCallbackEventId ?? null;
|
|
1458
|
+
if (!pendingCallback && existing.providerUpdatedAt instanceof Date && projected.providerUpdatedAt instanceof Date && projected.providerUpdatedAt.getTime() < existing.providerUpdatedAt.getTime()) {
|
|
1459
|
+
throw new Error(
|
|
1460
|
+
`StreamPay returned stale subscription state for sub=${subscriptionId}; retry delivery.`
|
|
1461
|
+
);
|
|
1462
|
+
}
|
|
1463
|
+
if (pendingCallback && pendingCallback !== eventId) {
|
|
1464
|
+
throw new Error(`Subscription renewal callback ${pendingCallback} is pending; retry delivery.`);
|
|
1465
|
+
}
|
|
1466
|
+
const deliverCallback = pendingCallback === eventId && pendingCallback !== null || !eventIsStale && (periodAdvanced || cycleAdvanced || retryingRenewalCallback);
|
|
1467
|
+
const callbackOwner = deliverCallback && callbacks.onSubscriptionRenewed ? eventId : null;
|
|
1337
1468
|
const updated = await ctx.context.adapter.update({
|
|
1338
1469
|
model: SUBSCRIPTION_MODEL2,
|
|
1339
|
-
|
|
1340
|
-
|
|
1470
|
+
// Recovery must retain the pending cycle, even if Stream has already advanced again.
|
|
1471
|
+
update: pendingCallback ? { renewalCallbackEventId: callbackOwner } : { ...projected, renewalCallbackEventId: callbackOwner },
|
|
1472
|
+
where: [
|
|
1473
|
+
{ field: "id", value: existing.id },
|
|
1474
|
+
{ field: "periodEnd", value: existing.periodEnd ?? null },
|
|
1475
|
+
{ field: "currentCycleNumber", value: existing.currentCycleNumber ?? null },
|
|
1476
|
+
{ field: "renewalCallbackEventId", value: pendingCallback },
|
|
1477
|
+
{ field: "providerUpdatedAt", value: existing.providerUpdatedAt ?? null },
|
|
1478
|
+
{ field: "status", value: existing.status },
|
|
1479
|
+
{ field: "billingStatus", value: existing.billingStatus }
|
|
1480
|
+
]
|
|
1341
1481
|
});
|
|
1342
|
-
|
|
1482
|
+
if (!updated) {
|
|
1483
|
+
if (pendingCallback && pendingCallback === eventId) {
|
|
1484
|
+
throw new Error(`Subscription cycle changed during callback recovery; retry delivery.`);
|
|
1485
|
+
}
|
|
1486
|
+
const latest = await findSubscriptionByStreampayId(ctx, subscriptionId);
|
|
1487
|
+
const anotherCallbackOwner = latest?.renewalCallbackEventId;
|
|
1488
|
+
const desiredCycleAdvanced = (periodAdvanced || cycleAdvanced) && (!periodAdvanced || (latest?.periodEnd?.getTime() ?? 0) >= (projectedPeriodEnd ?? 0)) && (!cycleAdvanced || (latest?.currentCycleNumber ?? 0) >= (projected.currentCycleNumber ?? 0));
|
|
1489
|
+
if (anotherCallbackOwner && anotherCallbackOwner !== eventId && desiredCycleAdvanced) return;
|
|
1490
|
+
throw new Error(`Subscription changed during renewal reconciliation; retry delivery.`);
|
|
1491
|
+
}
|
|
1492
|
+
const row = updated;
|
|
1343
1493
|
const user = await resolveRowUser(ctx, row);
|
|
1344
|
-
if (
|
|
1494
|
+
if (deliverCallback) {
|
|
1345
1495
|
await fireCallback(
|
|
1346
1496
|
ctx,
|
|
1347
1497
|
callbacks.onSubscriptionRenewed,
|
|
@@ -1349,6 +1499,16 @@ async function handleInvoiceCompleted(ctx, payload, client, plans, callbacks, re
|
|
|
1349
1499
|
"onSubscriptionRenewed",
|
|
1350
1500
|
retryOnCallbackError
|
|
1351
1501
|
);
|
|
1502
|
+
if (callbackOwner) {
|
|
1503
|
+
await ctx.context.adapter.update({
|
|
1504
|
+
model: SUBSCRIPTION_MODEL2,
|
|
1505
|
+
update: { renewalCallbackEventId: null },
|
|
1506
|
+
where: [
|
|
1507
|
+
{ field: "id", value: row.id },
|
|
1508
|
+
{ field: "renewalCallbackEventId", value: callbackOwner }
|
|
1509
|
+
]
|
|
1510
|
+
});
|
|
1511
|
+
}
|
|
1352
1512
|
}
|
|
1353
1513
|
}
|
|
1354
1514
|
async function dispatchSubscriptionCallback(ctx, payload, data, callbacks, retryOnCallbackError) {
|
|
@@ -1545,16 +1705,16 @@ function forwardedBody() {
|
|
|
1545
1705
|
);
|
|
1546
1706
|
}
|
|
1547
1707
|
var PaymentsListQuery = z.object({
|
|
1548
|
-
page: z.coerce.number().int().positive().optional(),
|
|
1708
|
+
page: z.coerce.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional(),
|
|
1549
1709
|
size: z.coerce.number().int().positive().max(100).optional(),
|
|
1550
1710
|
invoice_id: z.string().uuid().optional()
|
|
1551
1711
|
}).passthrough();
|
|
1552
1712
|
var PaginationOnlyQuery = z.object({
|
|
1553
|
-
page: z.coerce.number().int().positive().optional(),
|
|
1713
|
+
page: z.coerce.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional(),
|
|
1554
1714
|
size: z.coerce.number().int().positive().max(100).optional()
|
|
1555
1715
|
}).passthrough();
|
|
1556
1716
|
var ConsumersListQuery = z.object({
|
|
1557
|
-
page: z.coerce.number().int().positive().optional(),
|
|
1717
|
+
page: z.coerce.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional(),
|
|
1558
1718
|
size: z.coerce.number().int().positive().max(100).optional(),
|
|
1559
1719
|
search_term: z.string().optional()
|
|
1560
1720
|
}).passthrough();
|
|
@@ -1600,7 +1760,7 @@ function buildPaymentsEndpoints(client, adminOptions) {
|
|
|
1600
1760
|
await requireAdmin(ctx, adminOptions);
|
|
1601
1761
|
const params = {};
|
|
1602
1762
|
if (ctx.query.page !== void 0) params.page = ctx.query.page;
|
|
1603
|
-
if (ctx.query.size !== void 0) params.
|
|
1763
|
+
if (ctx.query.size !== void 0) params.limit = ctx.query.size;
|
|
1604
1764
|
if (ctx.query.invoice_id !== void 0) params.invoice_id = ctx.query.invoice_id;
|
|
1605
1765
|
try {
|
|
1606
1766
|
const response = await client.listPayments(params);
|
|
@@ -1705,7 +1865,7 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
|
|
|
1705
1865
|
await requireAdmin(ctx, adminOptions);
|
|
1706
1866
|
const params = {};
|
|
1707
1867
|
if (ctx.query.page !== void 0) params.page = ctx.query.page;
|
|
1708
|
-
if (ctx.query.size !== void 0) params.
|
|
1868
|
+
if (ctx.query.size !== void 0) params.limit = ctx.query.size;
|
|
1709
1869
|
try {
|
|
1710
1870
|
const response = await client.listSubscriptions(params);
|
|
1711
1871
|
return ctx.json(response);
|
|
@@ -1899,7 +2059,7 @@ function buildConsumersEndpoints(client, adminOptions) {
|
|
|
1899
2059
|
await requireAdmin(ctx, adminOptions);
|
|
1900
2060
|
const params = {};
|
|
1901
2061
|
if (ctx.query.page !== void 0) params.page = ctx.query.page;
|
|
1902
|
-
if (ctx.query.size !== void 0) params.
|
|
2062
|
+
if (ctx.query.size !== void 0) params.limit = ctx.query.size;
|
|
1903
2063
|
if (ctx.query.search_term !== void 0) params.search_term = ctx.query.search_term;
|
|
1904
2064
|
try {
|
|
1905
2065
|
const response = await client.listConsumers(params);
|
|
@@ -1962,19 +2122,6 @@ function buildConsumersEndpoints(client, adminOptions) {
|
|
|
1962
2122
|
async (ctx) => {
|
|
1963
2123
|
await requireAdmin(ctx, adminOptions);
|
|
1964
2124
|
const consumerId = ctx.params.id;
|
|
1965
|
-
let externalId;
|
|
1966
|
-
try {
|
|
1967
|
-
const consumer = await client.getConsumer(consumerId);
|
|
1968
|
-
if (typeof consumer.external_id === "string" && consumer.external_id.length > 0) {
|
|
1969
|
-
externalId = consumer.external_id;
|
|
1970
|
-
}
|
|
1971
|
-
} catch (err) {
|
|
1972
|
-
toAPIError(
|
|
1973
|
-
`StreamPay getConsumer failed for consumer=${consumerId}:`,
|
|
1974
|
-
err,
|
|
1975
|
-
getLogger(ctx)
|
|
1976
|
-
);
|
|
1977
|
-
}
|
|
1978
2125
|
try {
|
|
1979
2126
|
await client.deleteConsumer(consumerId);
|
|
1980
2127
|
} catch (err) {
|
|
@@ -1986,16 +2133,26 @@ function buildConsumersEndpoints(client, adminOptions) {
|
|
|
1986
2133
|
);
|
|
1987
2134
|
}
|
|
1988
2135
|
}
|
|
1989
|
-
|
|
1990
|
-
|
|
1991
|
-
|
|
1992
|
-
|
|
2136
|
+
try {
|
|
2137
|
+
const adapter = getAdapter(ctx);
|
|
2138
|
+
const user = await adapter.findOne({
|
|
2139
|
+
model: "user",
|
|
2140
|
+
where: [{ field: "streampayConsumerId", value: consumerId }]
|
|
2141
|
+
});
|
|
2142
|
+
if (user) {
|
|
2143
|
+
await adapter.update({
|
|
2144
|
+
model: "user",
|
|
2145
|
+
update: { streampayConsumerId: null },
|
|
2146
|
+
where: [
|
|
2147
|
+
{ field: "id", value: user.id },
|
|
2148
|
+
{ field: "streampayConsumerId", value: consumerId }
|
|
2149
|
+
]
|
|
1993
2150
|
});
|
|
1994
|
-
} catch (err) {
|
|
1995
|
-
getLogger(ctx).error(
|
|
1996
|
-
`StreamPay admin delete: link clear failed for user=${externalId} consumer=${consumerId}: ${formatStreamPayError(err)}`
|
|
1997
|
-
);
|
|
1998
2151
|
}
|
|
2152
|
+
} catch (err) {
|
|
2153
|
+
getLogger(ctx).error(
|
|
2154
|
+
`StreamPay admin delete: link clear failed for consumer=${consumerId}: ${formatStreamPayError(err)}`
|
|
2155
|
+
);
|
|
1999
2156
|
}
|
|
2000
2157
|
return ctx.json({ deleted: true });
|
|
2001
2158
|
}
|
|
@@ -2015,7 +2172,7 @@ function buildInvoicesEndpoints(client, adminOptions) {
|
|
|
2015
2172
|
await requireAdmin(ctx, adminOptions);
|
|
2016
2173
|
const params = {};
|
|
2017
2174
|
if (ctx.query.page !== void 0) params.page = ctx.query.page;
|
|
2018
|
-
if (ctx.query.size !== void 0) params.
|
|
2175
|
+
if (ctx.query.size !== void 0) params.limit = ctx.query.size;
|
|
2019
2176
|
try {
|
|
2020
2177
|
const response = await client.listInvoices(params);
|
|
2021
2178
|
return ctx.json(response);
|
|
@@ -2077,7 +2234,7 @@ function buildProductsEndpoints(client, adminOptions) {
|
|
|
2077
2234
|
await requireAdmin(ctx, adminOptions);
|
|
2078
2235
|
const params = {};
|
|
2079
2236
|
if (ctx.query.page !== void 0) params.page = ctx.query.page;
|
|
2080
|
-
if (ctx.query.size !== void 0) params.
|
|
2237
|
+
if (ctx.query.size !== void 0) params.limit = ctx.query.size;
|
|
2081
2238
|
try {
|
|
2082
2239
|
const response = await client.listProducts(params);
|
|
2083
2240
|
return ctx.json(response);
|
|
@@ -2183,7 +2340,7 @@ function buildCouponsEndpoints(client, adminOptions) {
|
|
|
2183
2340
|
await requireAdmin(ctx, adminOptions);
|
|
2184
2341
|
const params = {};
|
|
2185
2342
|
if (ctx.query.page !== void 0) params.page = ctx.query.page;
|
|
2186
|
-
if (ctx.query.size !== void 0) params.
|
|
2343
|
+
if (ctx.query.size !== void 0) params.limit = ctx.query.size;
|
|
2187
2344
|
try {
|
|
2188
2345
|
const response = await client.listCoupons(params);
|
|
2189
2346
|
return ctx.json(response);
|
|
@@ -2267,7 +2424,7 @@ function buildPaymentLinksEndpoints(client, adminOptions) {
|
|
|
2267
2424
|
await requireAdmin(ctx, adminOptions);
|
|
2268
2425
|
const params = {};
|
|
2269
2426
|
if (ctx.query.page !== void 0) params.page = ctx.query.page;
|
|
2270
|
-
if (ctx.query.size !== void 0) params.
|
|
2427
|
+
if (ctx.query.size !== void 0) params.limit = ctx.query.size;
|
|
2271
2428
|
try {
|
|
2272
2429
|
const response = await client.listPaymentLinks(params);
|
|
2273
2430
|
return ctx.json(response);
|
|
@@ -2301,9 +2458,16 @@ function buildPaymentLinksEndpoints(client, adminOptions) {
|
|
|
2301
2458
|
var WebhookEventsListQuery = z.object({
|
|
2302
2459
|
status: z.enum(["pending", "completed", "dead_letter"]).optional(),
|
|
2303
2460
|
eventType: z.string().optional(),
|
|
2304
|
-
page: z.coerce.number().int().positive().optional(),
|
|
2461
|
+
page: z.coerce.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional(),
|
|
2305
2462
|
size: z.coerce.number().int().positive().max(100).optional()
|
|
2306
2463
|
}).passthrough();
|
|
2464
|
+
function decodeWebhookEventId(value) {
|
|
2465
|
+
try {
|
|
2466
|
+
return decodeURIComponent(value);
|
|
2467
|
+
} catch {
|
|
2468
|
+
throw new APIError("BAD_REQUEST", { message: "Invalid webhook event identifier." });
|
|
2469
|
+
}
|
|
2470
|
+
}
|
|
2307
2471
|
function buildWebhookEventsEndpoints(adminOptions, registry) {
|
|
2308
2472
|
return {
|
|
2309
2473
|
adminListWebhookEvents: createAuthEndpoint(
|
|
@@ -2348,7 +2512,7 @@ function buildWebhookEventsEndpoints(adminOptions, registry) {
|
|
|
2348
2512
|
const adapter = getAdapter(ctx);
|
|
2349
2513
|
const row = await adapter.findOne({
|
|
2350
2514
|
model: WEBHOOK_EVENT_MODEL,
|
|
2351
|
-
where: [{ field: "eventId", value: ctx.params.eventId }]
|
|
2515
|
+
where: [{ field: "eventId", value: decodeWebhookEventId(ctx.params.eventId) }]
|
|
2352
2516
|
});
|
|
2353
2517
|
if (!row) {
|
|
2354
2518
|
throw new APIError("NOT_FOUND", {
|
|
@@ -2370,11 +2534,14 @@ function buildWebhookEventsEndpoints(adminOptions, registry) {
|
|
|
2370
2534
|
await requireAdmin(ctx, adminOptions);
|
|
2371
2535
|
if (!registry?.replayWebhookEvent) {
|
|
2372
2536
|
throw new APIError("BAD_REQUEST", {
|
|
2373
|
-
message: "Replay unavailable \u2014
|
|
2537
|
+
message: "Replay unavailable \u2014 enable the subscriptions webhook inbox or webhooks({ deduplicate: true })."
|
|
2374
2538
|
});
|
|
2375
2539
|
}
|
|
2376
2540
|
try {
|
|
2377
|
-
const result = await registry.replayWebhookEvent(
|
|
2541
|
+
const result = await registry.replayWebhookEvent(
|
|
2542
|
+
ctx,
|
|
2543
|
+
decodeWebhookEventId(ctx.params.eventId)
|
|
2544
|
+
);
|
|
2378
2545
|
return ctx.json(result);
|
|
2379
2546
|
} catch (err) {
|
|
2380
2547
|
if (err instanceof APIError) throw err;
|
|
@@ -2396,9 +2563,10 @@ function buildWebhookEventsEndpoints(adminOptions, registry) {
|
|
|
2396
2563
|
async (ctx) => {
|
|
2397
2564
|
await requireAdmin(ctx, adminOptions);
|
|
2398
2565
|
const adapter = getAdapter(ctx);
|
|
2566
|
+
const eventId = decodeWebhookEventId(ctx.params.eventId);
|
|
2399
2567
|
const row = await adapter.findOne({
|
|
2400
2568
|
model: WEBHOOK_EVENT_MODEL,
|
|
2401
|
-
where: [{ field: "eventId", value:
|
|
2569
|
+
where: [{ field: "eventId", value: eventId }]
|
|
2402
2570
|
});
|
|
2403
2571
|
if (!row) {
|
|
2404
2572
|
throw new APIError("NOT_FOUND", {
|
|
@@ -2406,8 +2574,24 @@ function buildWebhookEventsEndpoints(adminOptions, registry) {
|
|
|
2406
2574
|
message: `Webhook event ${ctx.params.eventId} not found.`
|
|
2407
2575
|
});
|
|
2408
2576
|
}
|
|
2577
|
+
if (registry?.subscriptionWebhookSync && !eventId.startsWith("handlers:") && (row.eventType === "INVOICE_COMPLETED" || row.eventType === "SUBSCRIPTION_CYCLE_RENEWED_SUCCESSFULLY")) {
|
|
2578
|
+
const subscription = await adapter.findOne({
|
|
2579
|
+
model: "subscription",
|
|
2580
|
+
where: [{ field: "renewalCallbackEventId", value: eventId }]
|
|
2581
|
+
});
|
|
2582
|
+
if (subscription) {
|
|
2583
|
+
await adapter.update({
|
|
2584
|
+
model: "subscription",
|
|
2585
|
+
update: { renewalCallbackEventId: null },
|
|
2586
|
+
where: [
|
|
2587
|
+
{ field: "id", value: subscription.id },
|
|
2588
|
+
{ field: "renewalCallbackEventId", value: eventId }
|
|
2589
|
+
]
|
|
2590
|
+
});
|
|
2591
|
+
}
|
|
2592
|
+
}
|
|
2409
2593
|
await markWebhookEventCompleted({ context: { adapter } }, row.id);
|
|
2410
|
-
return ctx.json({ discarded: true, eventId
|
|
2594
|
+
return ctx.json({ discarded: true, eventId });
|
|
2411
2595
|
}
|
|
2412
2596
|
)
|
|
2413
2597
|
};
|
|
@@ -2435,21 +2619,21 @@ var CheckoutRequestBody = z.object({
|
|
|
2435
2619
|
z.array(
|
|
2436
2620
|
z.object({
|
|
2437
2621
|
productId: z.string().uuid(),
|
|
2438
|
-
quantity: z.number().int().positive().optional()
|
|
2622
|
+
quantity: z.number().int().positive().safe().optional()
|
|
2439
2623
|
})
|
|
2440
2624
|
).min(1, "`products` must contain at least one item."),
|
|
2441
2625
|
z.array(z.string().uuid()).min(1, "`products` must contain at least one item."),
|
|
2442
2626
|
z.string().uuid()
|
|
2443
2627
|
]).optional(),
|
|
2444
|
-
slug: z.string().optional(),
|
|
2628
|
+
slug: z.string().min(1).optional(),
|
|
2445
2629
|
referenceId: z.string().optional(),
|
|
2446
2630
|
name: z.string().min(1).optional(),
|
|
2447
2631
|
description: z.string().optional(),
|
|
2448
|
-
metadata: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()])).optional(),
|
|
2632
|
+
metadata: z.record(z.string(), z.union([z.string(), z.number().finite(), z.boolean()])).optional(),
|
|
2449
2633
|
successUrl: RelativeOrAbsoluteUrl.optional(),
|
|
2450
2634
|
failureUrl: RelativeOrAbsoluteUrl.optional(),
|
|
2451
|
-
maxNumberOfPayments: z.number().int().positive().optional(),
|
|
2452
|
-
validUntil: z.string().datetime().optional(),
|
|
2635
|
+
maxNumberOfPayments: z.number().int().positive().safe().optional(),
|
|
2636
|
+
validUntil: z.string().datetime({ offset: true }).optional(),
|
|
2453
2637
|
couponIds: z.array(z.string().uuid()).optional(),
|
|
2454
2638
|
redirect: z.coerce.boolean().optional()
|
|
2455
2639
|
});
|
|
@@ -2722,24 +2906,58 @@ var checkout = (checkoutOptions = {}) => {
|
|
|
2722
2906
|
};
|
|
2723
2907
|
};
|
|
2724
2908
|
var DEFAULT_PAGE_SIZE = 100;
|
|
2725
|
-
|
|
2909
|
+
var paginationQuery = z.object({
|
|
2910
|
+
page: z.coerce.number().int().min(1).max(Number.MAX_SAFE_INTEGER).optional(),
|
|
2911
|
+
size: z.coerce.number().int().min(1).max(100).optional()
|
|
2912
|
+
});
|
|
2913
|
+
async function getConsumerIdOrNull(ctx, client, user) {
|
|
2726
2914
|
rejectUnauthorized(user, "Anonymous users cannot access the billing portal.");
|
|
2727
|
-
|
|
2915
|
+
const current = await getCurrentConsumerUser(ctx, user);
|
|
2916
|
+
if (current.streampayConsumerId) return current.streampayConsumerId;
|
|
2728
2917
|
return findConsumerByExternalId(client, { externalId: user.id });
|
|
2729
2918
|
}
|
|
2730
|
-
var portal = ({ pageSize } = {}) => (options) => {
|
|
2919
|
+
var portal = ({ pageSize, createSession } = {}) => (options) => {
|
|
2731
2920
|
const client = options.client;
|
|
2732
2921
|
const size = clampPageSize(pageSize);
|
|
2733
2922
|
return {
|
|
2734
2923
|
endpoints: {
|
|
2924
|
+
portalSession: createAuthEndpoint(
|
|
2925
|
+
"/consumer/portal/session",
|
|
2926
|
+
{ method: "POST", use: [sessionMiddleware] },
|
|
2927
|
+
async (ctx) => {
|
|
2928
|
+
ctx.setHeader("cache-control", "no-store");
|
|
2929
|
+
try {
|
|
2930
|
+
const consumerId = await getConsumerIdOrNull(
|
|
2931
|
+
ctx,
|
|
2932
|
+
client,
|
|
2933
|
+
asSessionUser(ctx.context.session?.user)
|
|
2934
|
+
);
|
|
2935
|
+
if (!consumerId)
|
|
2936
|
+
throw new APIError("NOT_FOUND", {
|
|
2937
|
+
message: "No StreamPay consumer is linked to this account."
|
|
2938
|
+
});
|
|
2939
|
+
if (!createSession)
|
|
2940
|
+
throw new APIError("NOT_FOUND", {
|
|
2941
|
+
message: "Hosted customer portal is not configured."
|
|
2942
|
+
});
|
|
2943
|
+
const session = await createSession({ organization_consumer_id: consumerId });
|
|
2944
|
+
const url = new URL(session.url);
|
|
2945
|
+
if (url.protocol !== "https:" || url.username || url.password)
|
|
2946
|
+
throw new Error("Invalid hosted portal URL.");
|
|
2947
|
+
return ctx.json({ url: url.href });
|
|
2948
|
+
} catch (err) {
|
|
2949
|
+
toAPIError("StreamPay createPortalSession failed.", err, getLogger(ctx));
|
|
2950
|
+
}
|
|
2951
|
+
}
|
|
2952
|
+
),
|
|
2735
2953
|
state: createAuthEndpoint(
|
|
2736
2954
|
"/consumer/state",
|
|
2737
2955
|
{ method: "GET", use: [sessionMiddleware] },
|
|
2738
2956
|
async (ctx) => {
|
|
2739
2957
|
const user = asSessionUser(ctx.context.session?.user);
|
|
2740
|
-
const consumerId = await getConsumerIdOrNull(client, user);
|
|
2741
|
-
if (!consumerId) return ctx.json({ hasConsumer: false, consumer: null });
|
|
2742
2958
|
try {
|
|
2959
|
+
const consumerId = await getConsumerIdOrNull(ctx, client, user);
|
|
2960
|
+
if (!consumerId) return ctx.json({ hasConsumer: false, consumer: null });
|
|
2743
2961
|
const consumer = await client.getConsumer(consumerId);
|
|
2744
2962
|
return ctx.json({ hasConsumer: true, consumer });
|
|
2745
2963
|
} catch (err) {
|
|
@@ -2749,18 +2967,22 @@ var portal = ({ pageSize } = {}) => (options) => {
|
|
|
2749
2967
|
),
|
|
2750
2968
|
subscriptions: createAuthEndpoint(
|
|
2751
2969
|
"/consumer/subscriptions/list",
|
|
2752
|
-
{ method: "GET", use: [sessionMiddleware] },
|
|
2970
|
+
{ method: "GET", use: [sessionMiddleware], query: paginationQuery },
|
|
2753
2971
|
async (ctx) => {
|
|
2754
2972
|
const user = asSessionUser(ctx.context.session?.user);
|
|
2755
|
-
const consumerId = await getConsumerIdOrNull(client, user);
|
|
2756
|
-
if (!consumerId) return ctx.json({ hasConsumer: false, data: [] });
|
|
2757
2973
|
try {
|
|
2974
|
+
const consumerId = await getConsumerIdOrNull(ctx, client, user);
|
|
2975
|
+
if (!consumerId) return ctx.json({ hasConsumer: false, data: [] });
|
|
2758
2976
|
const response = await client.listSubscriptions({
|
|
2759
2977
|
organization_consumer_id: consumerId,
|
|
2760
|
-
page: 1,
|
|
2761
|
-
size
|
|
2978
|
+
page: ctx.query?.page ?? 1,
|
|
2979
|
+
limit: ctx.query?.size ?? size
|
|
2980
|
+
});
|
|
2981
|
+
return ctx.json({
|
|
2982
|
+
hasConsumer: true,
|
|
2983
|
+
data: response.data ?? [],
|
|
2984
|
+
pagination: response.pagination
|
|
2762
2985
|
});
|
|
2763
|
-
return ctx.json({ hasConsumer: true, data: response.data ?? [] });
|
|
2764
2986
|
} catch (err) {
|
|
2765
2987
|
toAPIError("StreamPay listSubscriptions failed.", err, getLogger(ctx));
|
|
2766
2988
|
}
|
|
@@ -2768,18 +2990,22 @@ var portal = ({ pageSize } = {}) => (options) => {
|
|
|
2768
2990
|
),
|
|
2769
2991
|
invoices: createAuthEndpoint(
|
|
2770
2992
|
"/consumer/invoices/list",
|
|
2771
|
-
{ method: "GET", use: [sessionMiddleware] },
|
|
2993
|
+
{ method: "GET", use: [sessionMiddleware], query: paginationQuery },
|
|
2772
2994
|
async (ctx) => {
|
|
2773
2995
|
const user = asSessionUser(ctx.context.session?.user);
|
|
2774
|
-
const consumerId = await getConsumerIdOrNull(client, user);
|
|
2775
|
-
if (!consumerId) return ctx.json({ hasConsumer: false, data: [] });
|
|
2776
2996
|
try {
|
|
2997
|
+
const consumerId = await getConsumerIdOrNull(ctx, client, user);
|
|
2998
|
+
if (!consumerId) return ctx.json({ hasConsumer: false, data: [] });
|
|
2777
2999
|
const response = await client.listInvoices({
|
|
2778
3000
|
organization_consumer_id: consumerId,
|
|
2779
|
-
page: 1,
|
|
2780
|
-
size
|
|
3001
|
+
page: ctx.query?.page ?? 1,
|
|
3002
|
+
limit: ctx.query?.size ?? size
|
|
3003
|
+
});
|
|
3004
|
+
return ctx.json({
|
|
3005
|
+
hasConsumer: true,
|
|
3006
|
+
data: response.data ?? [],
|
|
3007
|
+
pagination: response.pagination
|
|
2781
3008
|
});
|
|
2782
|
-
return ctx.json({ hasConsumer: true, data: response.data ?? [] });
|
|
2783
3009
|
} catch (err) {
|
|
2784
3010
|
toAPIError("StreamPay listInvoices failed.", err, getLogger(ctx));
|
|
2785
3011
|
}
|
|
@@ -2797,6 +3023,7 @@ var STREAMPAY_EVENT_ENTITY_TYPES = {
|
|
|
2797
3023
|
PAYMENT_FAILED: "PAYMENT",
|
|
2798
3024
|
PAYMENT_CANCELED: "PAYMENT",
|
|
2799
3025
|
PAYMENT_REFUNDED: "PAYMENT",
|
|
3026
|
+
PAYMENT_PARTIALLY_REFUNDED: "PAYMENT",
|
|
2800
3027
|
PAYMENT_MARKED_AS_PAID: "PAYMENT",
|
|
2801
3028
|
INVOICE_CREATED: "INVOICE",
|
|
2802
3029
|
INVOICE_SENT: "INVOICE",
|
|
@@ -2811,6 +3038,7 @@ var STREAMPAY_EVENT_ENTITY_TYPES = {
|
|
|
2811
3038
|
SUBSCRIPTION_CANCELED: "SUBSCRIPTION",
|
|
2812
3039
|
SUBSCRIPTION_FROZEN: "SUBSCRIPTION",
|
|
2813
3040
|
SUBSCRIPTION_CYCLE_RENEWAL_FAILED: "SUBSCRIPTION",
|
|
3041
|
+
SUBSCRIPTION_CYCLE_RENEWED_SUCCESSFULLY: "SUBSCRIPTION",
|
|
2814
3042
|
SUBSCRIPTION_CANCEL_AT_PERIOD_END: "SUBSCRIPTION",
|
|
2815
3043
|
SUBSCRIPTION_FREEZE_NOW: "SUBSCRIPTION",
|
|
2816
3044
|
SUBSCRIPTION_UNFREEZE_NOW: "SUBSCRIPTION",
|
|
@@ -2958,7 +3186,10 @@ async function deleteReservedSubscription(adapter, rowId, log, reason) {
|
|
|
2958
3186
|
try {
|
|
2959
3187
|
await adapter.delete({
|
|
2960
3188
|
model: SUBSCRIPTION_MODEL4,
|
|
2961
|
-
where: [
|
|
3189
|
+
where: [
|
|
3190
|
+
{ field: "id", value: rowId },
|
|
3191
|
+
{ field: "status", value: "incomplete" }
|
|
3192
|
+
]
|
|
2962
3193
|
});
|
|
2963
3194
|
} catch (err) {
|
|
2964
3195
|
const message = err instanceof Error ? err.message : String(err);
|
|
@@ -2994,11 +3225,15 @@ async function resumeOrReserveCheckoutSlot(args) {
|
|
|
2994
3225
|
if (recovery.kind === "recovered") {
|
|
2995
3226
|
return { kind: "recovered", row: reuseCandidate, url: recovery.url };
|
|
2996
3227
|
}
|
|
2997
|
-
await adapter.update({
|
|
3228
|
+
const released = await adapter.update({
|
|
2998
3229
|
model: SUBSCRIPTION_MODEL4,
|
|
2999
3230
|
update: { status: "incomplete_expired", activeSlotKey: null, updatedAt: /* @__PURE__ */ new Date() },
|
|
3000
|
-
where: [
|
|
3231
|
+
where: [
|
|
3232
|
+
{ field: "id", value: reuseCandidate.id },
|
|
3233
|
+
{ field: "status", value: "incomplete" }
|
|
3234
|
+
]
|
|
3001
3235
|
});
|
|
3236
|
+
if (!released) throw checkoutInProgressError();
|
|
3002
3237
|
}
|
|
3003
3238
|
const { data: reservationData, consumerId } = await args.createReservation();
|
|
3004
3239
|
let row;
|
|
@@ -3039,6 +3274,7 @@ async function resumeOrReserveCheckoutSlot(args) {
|
|
|
3039
3274
|
update: { status: "incomplete_expired", activeSlotKey: null, updatedAt: /* @__PURE__ */ new Date() },
|
|
3040
3275
|
where: [
|
|
3041
3276
|
{ field: "id", value: reserved.id },
|
|
3277
|
+
{ field: "status", value: "incomplete" },
|
|
3042
3278
|
{ field: "activeSlotKey", value: activeSlotKey }
|
|
3043
3279
|
]
|
|
3044
3280
|
});
|
|
@@ -3118,6 +3354,43 @@ function configuredPlanForSubscription(subscription, plans) {
|
|
|
3118
3354
|
}
|
|
3119
3355
|
return matches[0];
|
|
3120
3356
|
}
|
|
3357
|
+
async function findSubscriptionFreeze(client, options, subscriptionId, matches) {
|
|
3358
|
+
const listPage = options.listSubscriptionFreezes;
|
|
3359
|
+
if (!listPage) {
|
|
3360
|
+
const response = await client.listSubscriptionFreezes(subscriptionId);
|
|
3361
|
+
return {
|
|
3362
|
+
freeze: response.data?.find(matches),
|
|
3363
|
+
hasMore: response.pagination?.has_next_page ?? false
|
|
3364
|
+
};
|
|
3365
|
+
}
|
|
3366
|
+
const seenIds = /* @__PURE__ */ new Set();
|
|
3367
|
+
for (let page = 1; page <= 100; page++) {
|
|
3368
|
+
const response = await listPage(subscriptionId, { page, limit: 100 });
|
|
3369
|
+
const pagination = response.pagination;
|
|
3370
|
+
if (!Array.isArray(response.data) || !pagination || pagination.current_page !== page || typeof pagination.has_next_page !== "boolean") {
|
|
3371
|
+
throw freezePaginationConflict("StreamPay returned invalid freeze pagination.");
|
|
3372
|
+
}
|
|
3373
|
+
let advanced = false;
|
|
3374
|
+
for (const freeze2 of response.data) {
|
|
3375
|
+
if (freeze2.id && !seenIds.has(freeze2.id)) {
|
|
3376
|
+
seenIds.add(freeze2.id);
|
|
3377
|
+
advanced = true;
|
|
3378
|
+
}
|
|
3379
|
+
}
|
|
3380
|
+
if (!advanced && (pagination.has_next_page || response.data.length > 0)) {
|
|
3381
|
+
throw freezePaginationConflict("StreamPay freeze pagination returned no new entries.");
|
|
3382
|
+
}
|
|
3383
|
+
const freeze = response.data.find(matches);
|
|
3384
|
+
if (freeze || !pagination.has_next_page) return { freeze, hasMore: false };
|
|
3385
|
+
}
|
|
3386
|
+
throw freezePaginationConflict("StreamPay freeze pagination exceeded 100 pages.");
|
|
3387
|
+
}
|
|
3388
|
+
function freezePaginationConflict(message) {
|
|
3389
|
+
return new APIError("CONFLICT", {
|
|
3390
|
+
code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
|
|
3391
|
+
message
|
|
3392
|
+
});
|
|
3393
|
+
}
|
|
3121
3394
|
var SUBSCRIPTION_INTERVALS = ["WEEK", "MONTH", "QUARTER", "YEAR"];
|
|
3122
3395
|
var PlanSchema = z.object({
|
|
3123
3396
|
name: z.string().min(1, "every plan must have a non-empty `name`."),
|
|
@@ -3222,7 +3495,7 @@ async function resolvePlans(plans) {
|
|
|
3222
3495
|
return buildIndex(list);
|
|
3223
3496
|
}
|
|
3224
3497
|
function hasSubscriptionAccess(subscription, accessStatuses = DEFAULT_ACCESS_STATUSES) {
|
|
3225
|
-
return accessStatuses.includes(subscription.status);
|
|
3498
|
+
return subscription.catalogMapped !== false && accessStatuses.includes(subscription.status);
|
|
3226
3499
|
}
|
|
3227
3500
|
function hasFeature(subscription, plan, feature, accessStatuses = DEFAULT_ACCESS_STATUSES) {
|
|
3228
3501
|
if (!plan?.limits) return false;
|
|
@@ -3238,9 +3511,11 @@ function checkLimit(subscription, plan, feature, requested, accessStatuses = DEF
|
|
|
3238
3511
|
}
|
|
3239
3512
|
const raw = plan.limits[feature];
|
|
3240
3513
|
const limit = typeof raw === "number" && Number.isFinite(raw) ? raw : 0;
|
|
3241
|
-
|
|
3242
|
-
|
|
3243
|
-
|
|
3514
|
+
if (!Number.isSafeInteger(requested) || requested < 0) {
|
|
3515
|
+
return { allowed: false, limit, remaining: 0 };
|
|
3516
|
+
}
|
|
3517
|
+
const allowed = requested <= limit;
|
|
3518
|
+
const remaining = Math.max(0, limit - requested);
|
|
3244
3519
|
return { allowed, limit, remaining };
|
|
3245
3520
|
}
|
|
3246
3521
|
|
|
@@ -3263,7 +3538,7 @@ var HasFeatureQuery = z.object({
|
|
|
3263
3538
|
var CheckLimitQuery = z.object({
|
|
3264
3539
|
...ReferenceQueryFields,
|
|
3265
3540
|
feature: z.string().min(1),
|
|
3266
|
-
count: z.coerce.number().int().min(0),
|
|
3541
|
+
count: z.coerce.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
|
|
3267
3542
|
group: z.string().min(1).optional()
|
|
3268
3543
|
});
|
|
3269
3544
|
function presentSubscription(row, plans) {
|
|
@@ -3272,7 +3547,7 @@ function presentSubscription(row, plans) {
|
|
|
3272
3547
|
// The column is nullable during safe rolling migrations. Keep the public
|
|
3273
3548
|
// contract stable while applications backfill legacy rows to one seat.
|
|
3274
3549
|
seats: row.seats ?? 1,
|
|
3275
|
-
plan: plans.byName.get(row.plan) ?? null
|
|
3550
|
+
plan: row.catalogMapped === false ? null : plans.byName.get(row.plan) ?? null
|
|
3276
3551
|
};
|
|
3277
3552
|
}
|
|
3278
3553
|
async function resolveLiveSubscription(ctx, query, subsOptions, accessStatuses) {
|
|
@@ -3455,8 +3730,8 @@ var UpdateSeatsBody = z.object({
|
|
|
3455
3730
|
}).strict();
|
|
3456
3731
|
var FreezeBody = z.object({
|
|
3457
3732
|
subscriptionId: z.string().min(1),
|
|
3458
|
-
freezeStartDatetime: z.string().datetime(),
|
|
3459
|
-
freezeEndDatetime: z.string().datetime().nullable().optional(),
|
|
3733
|
+
freezeStartDatetime: z.string().datetime({ offset: true }),
|
|
3734
|
+
freezeEndDatetime: z.string().datetime({ offset: true }).nullable().optional(),
|
|
3460
3735
|
notes: z.string().optional()
|
|
3461
3736
|
});
|
|
3462
3737
|
var UnfreezeBody = z.object({
|
|
@@ -3504,9 +3779,10 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
3504
3779
|
const plans = await plansRef();
|
|
3505
3780
|
const current = await client.getSubscription(row.streampaySubscriptionId);
|
|
3506
3781
|
if (!current.pending_change) {
|
|
3507
|
-
await
|
|
3508
|
-
|
|
3509
|
-
|
|
3782
|
+
await persistSubscriptionProjection(
|
|
3783
|
+
adapter,
|
|
3784
|
+
row,
|
|
3785
|
+
{
|
|
3510
3786
|
...projectSubscriptionAgainstExisting(row, current),
|
|
3511
3787
|
...projectPlanFields(current, plans),
|
|
3512
3788
|
pendingPlan: null,
|
|
@@ -3515,15 +3791,17 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
3515
3791
|
pendingSeats: null,
|
|
3516
3792
|
pendingSeatsEffectiveAt: null
|
|
3517
3793
|
},
|
|
3518
|
-
|
|
3519
|
-
|
|
3794
|
+
getLogger(ctx),
|
|
3795
|
+
"subscription endpoint"
|
|
3796
|
+
);
|
|
3520
3797
|
return ctx.json({ canceled: true, reused: true, subscription: current });
|
|
3521
3798
|
}
|
|
3522
3799
|
await client.deletePendingSubscriptionChange(row.streampaySubscriptionId);
|
|
3523
3800
|
const stream = await client.getSubscription(row.streampaySubscriptionId);
|
|
3524
|
-
await
|
|
3525
|
-
|
|
3526
|
-
|
|
3801
|
+
await persistSubscriptionProjection(
|
|
3802
|
+
adapter,
|
|
3803
|
+
row,
|
|
3804
|
+
{
|
|
3527
3805
|
...projectSubscriptionAgainstExisting(row, stream),
|
|
3528
3806
|
...projectPlanFields(stream, plans),
|
|
3529
3807
|
pendingPlan: null,
|
|
@@ -3532,8 +3810,9 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
3532
3810
|
pendingSeats: null,
|
|
3533
3811
|
pendingSeatsEffectiveAt: null
|
|
3534
3812
|
},
|
|
3535
|
-
|
|
3536
|
-
|
|
3813
|
+
getLogger(ctx),
|
|
3814
|
+
"subscription endpoint"
|
|
3815
|
+
);
|
|
3537
3816
|
return ctx.json({ canceled: true, reused: false, subscription: stream });
|
|
3538
3817
|
} catch (err) {
|
|
3539
3818
|
toAPIError(
|
|
@@ -3732,7 +4011,11 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
3732
4011
|
activeSlotKey: null,
|
|
3733
4012
|
updatedAt: /* @__PURE__ */ new Date()
|
|
3734
4013
|
},
|
|
3735
|
-
where: [
|
|
4014
|
+
where: [
|
|
4015
|
+
{ field: "id", value: row.id },
|
|
4016
|
+
{ field: "status", value: "incomplete" },
|
|
4017
|
+
{ field: "streampayConsumerId", value: consumerId }
|
|
4018
|
+
]
|
|
3736
4019
|
});
|
|
3737
4020
|
} catch (persistenceError) {
|
|
3738
4021
|
const message = persistenceError instanceof Error ? persistenceError.message : String(persistenceError);
|
|
@@ -3758,7 +4041,13 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
3758
4041
|
streampayPaymentLinkId: paymentLinkId,
|
|
3759
4042
|
updatedAt: /* @__PURE__ */ new Date()
|
|
3760
4043
|
},
|
|
3761
|
-
where: [
|
|
4044
|
+
where: [
|
|
4045
|
+
{ field: "id", value: row.id },
|
|
4046
|
+
{ field: "referenceId", value: referenceId },
|
|
4047
|
+
{ field: "referenceType", value: referenceType },
|
|
4048
|
+
{ field: "streampayConsumerId", value: consumerId },
|
|
4049
|
+
{ field: "streampayPaymentLinkId", value: null }
|
|
4050
|
+
]
|
|
3762
4051
|
});
|
|
3763
4052
|
} catch (persistenceError) {
|
|
3764
4053
|
const message = persistenceError instanceof Error ? persistenceError.message : String(persistenceError);
|
|
@@ -3840,10 +4129,11 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
3840
4129
|
if (!match?.id) {
|
|
3841
4130
|
return ctx.json({ subscription: row, synced: false });
|
|
3842
4131
|
}
|
|
3843
|
-
const updated = await
|
|
3844
|
-
|
|
3845
|
-
|
|
3846
|
-
|
|
4132
|
+
const updated = await persistSubscriptionProjection(
|
|
4133
|
+
adapter,
|
|
4134
|
+
row,
|
|
4135
|
+
{
|
|
4136
|
+
...projectSubscriptionFields(match, row),
|
|
3847
4137
|
...projectPlanFields(match, plans),
|
|
3848
4138
|
planVersion: plan.version ?? null,
|
|
3849
4139
|
productId: plan.productId,
|
|
@@ -3851,9 +4141,10 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
3851
4141
|
activeSlotKey: row.activeSlotKey ?? subscriptionSlotKey(row.referenceType ?? "user", row.referenceId, row.group),
|
|
3852
4142
|
updatedAt: /* @__PURE__ */ new Date()
|
|
3853
4143
|
},
|
|
3854
|
-
|
|
3855
|
-
|
|
3856
|
-
|
|
4144
|
+
getLogger(ctx),
|
|
4145
|
+
"subscription endpoint"
|
|
4146
|
+
);
|
|
4147
|
+
return ctx.json({ subscription: updated, synced: updated !== null });
|
|
3857
4148
|
} catch (err) {
|
|
3858
4149
|
toAPIError(
|
|
3859
4150
|
`subscriptionSuccess fallback sync failed for row=${row.id}:`,
|
|
@@ -3883,11 +4174,13 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
3883
4174
|
try {
|
|
3884
4175
|
const stream = await client.getSubscription(row.streampaySubscriptionId);
|
|
3885
4176
|
if (stream.status === "CANCELED") {
|
|
3886
|
-
await
|
|
3887
|
-
|
|
3888
|
-
|
|
3889
|
-
|
|
3890
|
-
|
|
4177
|
+
await persistSubscriptionProjection(
|
|
4178
|
+
adapter,
|
|
4179
|
+
row,
|
|
4180
|
+
projectSubscriptionAgainstExisting(row, stream),
|
|
4181
|
+
getLogger(ctx),
|
|
4182
|
+
"subscription endpoint"
|
|
4183
|
+
);
|
|
3891
4184
|
return ctx.json(stream);
|
|
3892
4185
|
}
|
|
3893
4186
|
if (ctx.body.cancelAtPeriodEnd === false && stream.status === "ACTIVE") {
|
|
@@ -3897,11 +4190,13 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
3897
4190
|
});
|
|
3898
4191
|
}
|
|
3899
4192
|
if (stream.cancel_at_period_end && !ctx.body.cancelRelatedInvoices) {
|
|
3900
|
-
await
|
|
3901
|
-
|
|
3902
|
-
|
|
3903
|
-
|
|
3904
|
-
|
|
4193
|
+
await persistSubscriptionProjection(
|
|
4194
|
+
adapter,
|
|
4195
|
+
row,
|
|
4196
|
+
projectSubscriptionAgainstExisting(row, stream),
|
|
4197
|
+
getLogger(ctx),
|
|
4198
|
+
"subscription endpoint"
|
|
4199
|
+
);
|
|
3905
4200
|
return ctx.json(stream);
|
|
3906
4201
|
}
|
|
3907
4202
|
if (ctx.body.cancelAtPeriodEnd === true && stream.status !== "ACTIVE") {
|
|
@@ -3995,9 +4290,10 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
3995
4290
|
const pendingTargetMatches = Boolean(pendingTarget) && (subscriptionItemQuantity(pendingTarget) ?? 1) === nextSeats;
|
|
3996
4291
|
if (pendingTargetMatches) {
|
|
3997
4292
|
const effectiveAt2 = stream.pending_change?.effective_at ?? null;
|
|
3998
|
-
await
|
|
3999
|
-
|
|
4000
|
-
|
|
4293
|
+
await persistSubscriptionProjection(
|
|
4294
|
+
adapter,
|
|
4295
|
+
row,
|
|
4296
|
+
{
|
|
4001
4297
|
...projectSubscriptionAgainstExisting(row, stream),
|
|
4002
4298
|
...projectPlanFields(stream, plans),
|
|
4003
4299
|
pendingPlan: currentPlan.productId === nextPlan.productId ? null : nextPlan.name,
|
|
@@ -4006,8 +4302,9 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
4006
4302
|
pendingSeats: nextSeats,
|
|
4007
4303
|
pendingSeatsEffectiveAt: parseDate(effectiveAt2)
|
|
4008
4304
|
},
|
|
4009
|
-
|
|
4010
|
-
|
|
4305
|
+
getLogger(ctx),
|
|
4306
|
+
"subscription endpoint"
|
|
4307
|
+
);
|
|
4011
4308
|
return ctx.json({
|
|
4012
4309
|
mode: "at_period_end",
|
|
4013
4310
|
subscriptionId: row.id,
|
|
@@ -4039,15 +4336,17 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
4039
4336
|
const pending = Boolean(result.pending_change);
|
|
4040
4337
|
const effectiveAt = result.pending_change?.effective_at ?? null;
|
|
4041
4338
|
const planProjection = projectPlanFields(result, plans);
|
|
4042
|
-
await
|
|
4043
|
-
|
|
4044
|
-
|
|
4339
|
+
await persistSubscriptionProjection(
|
|
4340
|
+
adapter,
|
|
4341
|
+
row,
|
|
4342
|
+
{
|
|
4045
4343
|
...projectSubscriptionAgainstExisting(row, result),
|
|
4046
4344
|
...planProjection,
|
|
4047
4345
|
updatedAt: /* @__PURE__ */ new Date()
|
|
4048
4346
|
},
|
|
4049
|
-
|
|
4050
|
-
|
|
4347
|
+
getLogger(ctx),
|
|
4348
|
+
"subscription endpoint"
|
|
4349
|
+
);
|
|
4051
4350
|
const providerPlan = pending ? planProjection.pendingPlan ?? planProjection.plan ?? row.plan : planProjection.plan ?? row.plan;
|
|
4052
4351
|
const providerSeats = pending ? planProjection.pendingSeats ?? nextSeats : planProjection.seats ?? row.seats ?? nextSeats;
|
|
4053
4352
|
return ctx.json({
|
|
@@ -4113,14 +4412,16 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
4113
4412
|
if (stream.pending_change) {
|
|
4114
4413
|
if (pendingTarget && (subscriptionItemQuantity(pendingTarget) ?? 1) === seats) {
|
|
4115
4414
|
const effectiveAt2 = stream.pending_change.effective_at ?? null;
|
|
4116
|
-
await
|
|
4117
|
-
|
|
4118
|
-
|
|
4415
|
+
await persistSubscriptionProjection(
|
|
4416
|
+
adapter,
|
|
4417
|
+
row,
|
|
4418
|
+
{
|
|
4119
4419
|
...projectSubscriptionAgainstExisting(row, stream),
|
|
4120
4420
|
...projectPlanFields(stream, plans)
|
|
4121
4421
|
},
|
|
4122
|
-
|
|
4123
|
-
|
|
4422
|
+
getLogger(ctx),
|
|
4423
|
+
"subscription endpoint"
|
|
4424
|
+
);
|
|
4124
4425
|
return ctx.json({
|
|
4125
4426
|
mode: "at_period_end",
|
|
4126
4427
|
subscriptionId: row.id,
|
|
@@ -4136,14 +4437,16 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
4136
4437
|
});
|
|
4137
4438
|
}
|
|
4138
4439
|
if (currentSeats === seats) {
|
|
4139
|
-
await
|
|
4140
|
-
|
|
4141
|
-
|
|
4440
|
+
await persistSubscriptionProjection(
|
|
4441
|
+
adapter,
|
|
4442
|
+
row,
|
|
4443
|
+
{
|
|
4142
4444
|
...projectSubscriptionAgainstExisting(row, stream),
|
|
4143
4445
|
...projectPlanFields(stream, plans)
|
|
4144
4446
|
},
|
|
4145
|
-
|
|
4146
|
-
|
|
4447
|
+
getLogger(ctx),
|
|
4448
|
+
"subscription endpoint"
|
|
4449
|
+
);
|
|
4147
4450
|
return ctx.json({
|
|
4148
4451
|
mode: "current",
|
|
4149
4452
|
subscriptionId: row.id,
|
|
@@ -4161,15 +4464,17 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
4161
4464
|
const pending = Boolean(result.pending_change);
|
|
4162
4465
|
const effectiveAt = result.pending_change?.effective_at ?? null;
|
|
4163
4466
|
const planProjection = projectPlanFields(result, plans);
|
|
4164
|
-
await
|
|
4165
|
-
|
|
4166
|
-
|
|
4467
|
+
await persistSubscriptionProjection(
|
|
4468
|
+
adapter,
|
|
4469
|
+
row,
|
|
4470
|
+
{
|
|
4167
4471
|
...projectSubscriptionAgainstExisting(row, result),
|
|
4168
4472
|
...planProjection,
|
|
4169
4473
|
updatedAt: /* @__PURE__ */ new Date()
|
|
4170
4474
|
},
|
|
4171
|
-
|
|
4172
|
-
|
|
4475
|
+
getLogger(ctx),
|
|
4476
|
+
"subscription endpoint"
|
|
4477
|
+
);
|
|
4173
4478
|
const providerSeats = pending ? planProjection.pendingSeats ?? seats : planProjection.seats ?? row.seats ?? seats;
|
|
4174
4479
|
return ctx.json({
|
|
4175
4480
|
mode: pending ? "at_period_end" : "immediate",
|
|
@@ -4213,11 +4518,13 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
4213
4518
|
try {
|
|
4214
4519
|
await client.uncancelSubscription(row.streampaySubscriptionId);
|
|
4215
4520
|
const stream = await client.getSubscription(row.streampaySubscriptionId);
|
|
4216
|
-
await
|
|
4217
|
-
|
|
4218
|
-
|
|
4219
|
-
|
|
4220
|
-
|
|
4521
|
+
await persistSubscriptionProjection(
|
|
4522
|
+
adapter,
|
|
4523
|
+
row,
|
|
4524
|
+
projectSubscriptionAgainstExisting(row, stream),
|
|
4525
|
+
getLogger(ctx),
|
|
4526
|
+
"subscription endpoint"
|
|
4527
|
+
);
|
|
4221
4528
|
return ctx.json({ uncanceled: true, subscription: stream });
|
|
4222
4529
|
} catch (err) {
|
|
4223
4530
|
toAPIError(
|
|
@@ -4292,13 +4599,30 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
4292
4599
|
);
|
|
4293
4600
|
const nowMs = Date.now();
|
|
4294
4601
|
try {
|
|
4295
|
-
const
|
|
4296
|
-
const active = freezes.data?.find((freeze) => {
|
|
4602
|
+
const isActiveFreeze = (freeze) => {
|
|
4297
4603
|
if (!freeze.id || !freeze.freeze_start_datetime) return false;
|
|
4298
4604
|
const start = parseDate(freeze.freeze_start_datetime)?.getTime();
|
|
4299
4605
|
const end = freeze.freeze_end_datetime ? parseDate(freeze.freeze_end_datetime)?.getTime() : Number.POSITIVE_INFINITY;
|
|
4300
|
-
return start !== void 0 && end !== void 0 && start <= nowMs && nowMs
|
|
4301
|
-
}
|
|
4606
|
+
return start !== void 0 && end !== void 0 && start <= nowMs && nowMs < end;
|
|
4607
|
+
};
|
|
4608
|
+
const result = await findSubscriptionFreeze(
|
|
4609
|
+
client,
|
|
4610
|
+
subsOptions,
|
|
4611
|
+
row.streampaySubscriptionId,
|
|
4612
|
+
isActiveFreeze
|
|
4613
|
+
);
|
|
4614
|
+
let active = result.freeze;
|
|
4615
|
+
if (!active && result.hasMore) {
|
|
4616
|
+
const stream = await client.getSubscription(row.streampaySubscriptionId);
|
|
4617
|
+
if (stream.status === "FROZEN" && stream.latest_freeze && isActiveFreeze(stream.latest_freeze)) {
|
|
4618
|
+
active = stream.latest_freeze;
|
|
4619
|
+
} else {
|
|
4620
|
+
throw new APIError("CONFLICT", {
|
|
4621
|
+
code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
|
|
4622
|
+
message: "StreamPay returned more freeze pages than the SDK can read. Unable to verify the active freeze."
|
|
4623
|
+
});
|
|
4624
|
+
}
|
|
4625
|
+
}
|
|
4302
4626
|
if (!active?.id || !active.freeze_start_datetime) {
|
|
4303
4627
|
throw new APIError("BAD_REQUEST", {
|
|
4304
4628
|
code: $ERROR_CODES.SUBSCRIPTION_FREEZE_NOT_ACTIVE.code,
|
|
@@ -4345,8 +4669,19 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
4345
4669
|
"cancel-freeze"
|
|
4346
4670
|
);
|
|
4347
4671
|
try {
|
|
4348
|
-
const
|
|
4349
|
-
|
|
4672
|
+
const result = await findSubscriptionFreeze(
|
|
4673
|
+
client,
|
|
4674
|
+
subsOptions,
|
|
4675
|
+
row.streampaySubscriptionId,
|
|
4676
|
+
(freeze) => freeze.id === ctx.body.freezeId
|
|
4677
|
+
);
|
|
4678
|
+
if (!result.freeze) {
|
|
4679
|
+
if (result.hasMore) {
|
|
4680
|
+
throw new APIError("CONFLICT", {
|
|
4681
|
+
code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
|
|
4682
|
+
message: "StreamPay returned more freeze pages than the SDK can read. Unable to verify whether this freeze was canceled."
|
|
4683
|
+
});
|
|
4684
|
+
}
|
|
4350
4685
|
return ctx.json({ canceled: true, freezeId: ctx.body.freezeId, reused: true });
|
|
4351
4686
|
}
|
|
4352
4687
|
await client.deleteSubscriptionFreeze(row.streampaySubscriptionId, ctx.body.freezeId);
|
|
@@ -4423,6 +4758,12 @@ var subscriptionTable = {
|
|
|
4423
4758
|
type: "string",
|
|
4424
4759
|
required: true
|
|
4425
4760
|
},
|
|
4761
|
+
catalogMapped: {
|
|
4762
|
+
type: "boolean",
|
|
4763
|
+
required: false,
|
|
4764
|
+
defaultValue: true,
|
|
4765
|
+
input: false
|
|
4766
|
+
},
|
|
4426
4767
|
planVersion: {
|
|
4427
4768
|
type: "string",
|
|
4428
4769
|
required: false
|
|
@@ -4492,6 +4833,11 @@ var subscriptionTable = {
|
|
|
4492
4833
|
type: "number",
|
|
4493
4834
|
required: false
|
|
4494
4835
|
},
|
|
4836
|
+
renewalCallbackEventId: {
|
|
4837
|
+
type: "string",
|
|
4838
|
+
required: false,
|
|
4839
|
+
input: false
|
|
4840
|
+
},
|
|
4495
4841
|
trialStart: {
|
|
4496
4842
|
type: "date",
|
|
4497
4843
|
required: false
|
|
@@ -4702,6 +5048,9 @@ function subscriptions(subsOptions) {
|
|
|
4702
5048
|
};
|
|
4703
5049
|
if (dedupeEnabled) {
|
|
4704
5050
|
registry.replayWebhookEvent = async (ctx, eventId) => {
|
|
5051
|
+
if (eventId.startsWith("handlers:") && registry.replayWebhookHandler) {
|
|
5052
|
+
return registry.replayWebhookHandler(ctx, eventId);
|
|
5053
|
+
}
|
|
4705
5054
|
const syncCtx = {
|
|
4706
5055
|
context: ctx.context
|
|
4707
5056
|
};
|
|
@@ -4794,6 +5143,9 @@ async function dispatchWebhook(payload, handlers) {
|
|
|
4794
5143
|
case "PAYMENT_REFUNDED":
|
|
4795
5144
|
await handlers.onPaymentRefunded?.(payload);
|
|
4796
5145
|
return;
|
|
5146
|
+
case "PAYMENT_PARTIALLY_REFUNDED":
|
|
5147
|
+
await handlers.onPaymentPartiallyRefunded?.(payload);
|
|
5148
|
+
return;
|
|
4797
5149
|
case "PAYMENT_MARKED_AS_PAID":
|
|
4798
5150
|
await handlers.onPaymentMarkedAsPaid?.(payload);
|
|
4799
5151
|
return;
|
|
@@ -4836,6 +5188,9 @@ async function dispatchWebhook(payload, handlers) {
|
|
|
4836
5188
|
case "SUBSCRIPTION_CYCLE_RENEWAL_FAILED":
|
|
4837
5189
|
await handlers.onSubscriptionCycleRenewalFailed?.(payload);
|
|
4838
5190
|
return;
|
|
5191
|
+
case "SUBSCRIPTION_CYCLE_RENEWED_SUCCESSFULLY":
|
|
5192
|
+
await handlers.onSubscriptionCycleRenewedSuccessfully?.(payload);
|
|
5193
|
+
return;
|
|
4839
5194
|
case "SUBSCRIPTION_CANCEL_AT_PERIOD_END":
|
|
4840
5195
|
await handlers.onSubscriptionCancelAtPeriodEnd?.(payload);
|
|
4841
5196
|
return;
|
|
@@ -4944,8 +5299,56 @@ var webhooks = (webhooksOptions) => {
|
|
|
4944
5299
|
throw new TypeError("webhooks(): `toleranceSeconds` must be a non-negative number.");
|
|
4945
5300
|
}
|
|
4946
5301
|
return (_options, registry) => {
|
|
4947
|
-
const { secret, toleranceSeconds, ...handlers } = webhooksOptions;
|
|
5302
|
+
const { secret, toleranceSeconds, deduplicate = false, ...handlers } = webhooksOptions;
|
|
5303
|
+
if (deduplicate && registry) {
|
|
5304
|
+
registry.replayWebhookHandler = async (ctx, eventId) => {
|
|
5305
|
+
const syncContext = { context: ctx.context };
|
|
5306
|
+
const row = await syncContext.context.adapter.findOne({
|
|
5307
|
+
model: WEBHOOK_EVENT_MODEL,
|
|
5308
|
+
where: [{ field: "eventId", value: eventId }]
|
|
5309
|
+
});
|
|
5310
|
+
if (!eventId.startsWith("handlers:") || !row)
|
|
5311
|
+
throw new APIError("NOT_FOUND", { message: "Webhook callback event not found." });
|
|
5312
|
+
if (!row.rawPayload)
|
|
5313
|
+
throw new APIError("BAD_REQUEST", { message: "Webhook callback has no stored payload." });
|
|
5314
|
+
let payload;
|
|
5315
|
+
try {
|
|
5316
|
+
payload = JSON.parse(row.rawPayload);
|
|
5317
|
+
} catch {
|
|
5318
|
+
throw new APIError("BAD_REQUEST", {
|
|
5319
|
+
message: "Stored webhook payload is not valid JSON."
|
|
5320
|
+
});
|
|
5321
|
+
}
|
|
5322
|
+
if (!isStreamPayWebhookEnvelope(payload))
|
|
5323
|
+
throw new APIError("BAD_REQUEST", {
|
|
5324
|
+
message: "Stored webhook payload is not a valid event envelope."
|
|
5325
|
+
});
|
|
5326
|
+
const claimed = await claimWebhookEventForReplay(syncContext, row);
|
|
5327
|
+
if (!claimed?.lockedBy)
|
|
5328
|
+
throw new APIError("CONFLICT", {
|
|
5329
|
+
message: "Webhook callback is already being processed."
|
|
5330
|
+
});
|
|
5331
|
+
try {
|
|
5332
|
+
await dispatchWebhook(payload, handlers);
|
|
5333
|
+
await markWebhookEventCompleted(syncContext, claimed.id, claimed.lockedBy);
|
|
5334
|
+
} catch (err) {
|
|
5335
|
+
await recordWebhookEventFailure(
|
|
5336
|
+
syncContext,
|
|
5337
|
+
claimed.id,
|
|
5338
|
+
row.rawPayload,
|
|
5339
|
+
row.signatureHeader,
|
|
5340
|
+
err,
|
|
5341
|
+
claimed.lockedBy,
|
|
5342
|
+
true
|
|
5343
|
+
);
|
|
5344
|
+
throw err;
|
|
5345
|
+
}
|
|
5346
|
+
return { replayed: true, eventId };
|
|
5347
|
+
};
|
|
5348
|
+
registry.replayWebhookEvent ??= registry.replayWebhookHandler;
|
|
5349
|
+
}
|
|
4948
5350
|
return {
|
|
5351
|
+
schema: deduplicate ? webhookEventTable : {},
|
|
4949
5352
|
endpoints: {
|
|
4950
5353
|
streampayWebhooks: createAuthEndpoint(
|
|
4951
5354
|
"/streampay/webhooks",
|
|
@@ -5005,9 +5408,32 @@ var webhooks = (webhooksOptions) => {
|
|
|
5005
5408
|
});
|
|
5006
5409
|
}
|
|
5007
5410
|
}
|
|
5411
|
+
const syncContext = { context: ctx.context };
|
|
5412
|
+
const claim = deduplicate ? await claimOrAdvanceWebhookEvent(
|
|
5413
|
+
syncContext,
|
|
5414
|
+
payload,
|
|
5415
|
+
rawBody,
|
|
5416
|
+
signatureHeader,
|
|
5417
|
+
DEFAULT_MAX_WEBHOOK_ATTEMPTS,
|
|
5418
|
+
"handlers"
|
|
5419
|
+
) : null;
|
|
5420
|
+
if (claim && claim.action !== "process") return ctx.json({ received: true });
|
|
5421
|
+
const row = claim?.action === "process" ? claim.row : null;
|
|
5008
5422
|
try {
|
|
5009
5423
|
await dispatchWebhook(payload, handlers);
|
|
5424
|
+
if (row)
|
|
5425
|
+
await markWebhookEventCompleted(syncContext, row.id, row.lockedBy ?? void 0);
|
|
5010
5426
|
} catch (err) {
|
|
5427
|
+
if (row)
|
|
5428
|
+
await recordWebhookEventFailure(
|
|
5429
|
+
syncContext,
|
|
5430
|
+
row.id,
|
|
5431
|
+
rawBody,
|
|
5432
|
+
signatureHeader,
|
|
5433
|
+
err,
|
|
5434
|
+
row.lockedBy ?? void 0,
|
|
5435
|
+
row.attemptCount >= DEFAULT_MAX_WEBHOOK_ATTEMPTS
|
|
5436
|
+
);
|
|
5011
5437
|
const message = err instanceof Error ? err.message : String(err);
|
|
5012
5438
|
logger2.error(`webhook handler failed: ${message}`);
|
|
5013
5439
|
throw new APIError("INTERNAL_SERVER_ERROR", {
|
|
@@ -5022,9 +5448,6 @@ var webhooks = (webhooksOptions) => {
|
|
|
5022
5448
|
};
|
|
5023
5449
|
};
|
|
5024
5450
|
var isAnonymous = (user) => "isAnonymous" in user && user.isAnonymous === true;
|
|
5025
|
-
function hasInternalAdapter(ctx) {
|
|
5026
|
-
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";
|
|
5027
|
-
}
|
|
5028
5451
|
var onBeforeUserCreate = (options) => async (user, context) => {
|
|
5029
5452
|
if (!context || !options.createConsumerOnSignUp) return void 0;
|
|
5030
5453
|
if (isAnonymous(user)) return void 0;
|
|
@@ -5035,11 +5458,12 @@ var onBeforeUserCreate = (options) => async (user, context) => {
|
|
|
5035
5458
|
}
|
|
5036
5459
|
const extras = options.getConsumerCreateParams ? await options.getConsumerCreateParams({ user }) : {};
|
|
5037
5460
|
const createPayload = {
|
|
5038
|
-
name: user.name || user.email,
|
|
5039
|
-
email: user.email,
|
|
5040
5461
|
consumer_type: "INDIVIDUAL",
|
|
5041
|
-
...extras
|
|
5462
|
+
...extras,
|
|
5463
|
+
name: user.name || user.email,
|
|
5464
|
+
email: user.email
|
|
5042
5465
|
};
|
|
5466
|
+
delete createPayload.external_id;
|
|
5043
5467
|
try {
|
|
5044
5468
|
const consumer = await options.client.createConsumer(createPayload);
|
|
5045
5469
|
if (!consumer.id) {
|
|
@@ -5053,6 +5477,7 @@ var onBeforeUserCreate = (options) => async (user, context) => {
|
|
|
5053
5477
|
if (isDuplicateConsumerError(err)) {
|
|
5054
5478
|
const reusedId = await resolveDuplicateConsumer(options, createPayload, context);
|
|
5055
5479
|
if (reusedId) {
|
|
5480
|
+
await assertConsumerUnclaimed(context, reusedId);
|
|
5056
5481
|
return { data: { streampayConsumerId: reusedId } };
|
|
5057
5482
|
}
|
|
5058
5483
|
}
|
|
@@ -5101,10 +5526,15 @@ var onUserUpdate = (options) => async (user, context) => {
|
|
|
5101
5526
|
getLogger(context).error(
|
|
5102
5527
|
`consumer ${sessionUser.streampayConsumerId} not found for user=${sessionUser.id}; clearing stale link for re-provisioning.`
|
|
5103
5528
|
);
|
|
5104
|
-
if (
|
|
5529
|
+
if (typeof context.context.adapter?.update === "function") {
|
|
5105
5530
|
try {
|
|
5106
|
-
await context.context.
|
|
5107
|
-
|
|
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 }
|
|
5108
5538
|
});
|
|
5109
5539
|
} catch (clearErr) {
|
|
5110
5540
|
getLogger(context).error(
|
|
@@ -5136,7 +5566,7 @@ var onUserDelete = (options) => async (user, context) => {
|
|
|
5136
5566
|
|
|
5137
5567
|
// package.json
|
|
5138
5568
|
var package_default = {
|
|
5139
|
-
version: "
|
|
5569
|
+
version: "3.0.1"};
|
|
5140
5570
|
|
|
5141
5571
|
// src/version.ts
|
|
5142
5572
|
var version = package_default.version;
|