better-auth-streampay 2.2.0 → 3.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/README.md +172 -2
- package/dist/client.cjs +1 -0
- package/dist/client.cjs.map +1 -1
- package/dist/client.d.cts +6 -2
- package/dist/client.d.ts +6 -2
- package/dist/client.js +1 -0
- package/dist/client.js.map +1 -1
- package/dist/index.cjs +602 -229
- 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 +602 -229
- package/dist/index.js.map +1 -1
- package/dist/{streampay-B3vf7Hvq.d.cts → streampay-Cfl70SR_.d.cts} +413 -251
- package/dist/{streampay-B3vf7Hvq.d.ts → streampay-Cfl70SR_.d.ts} +413 -251
- package/package.json +11 -4
package/dist/index.cjs
CHANGED
|
@@ -164,13 +164,33 @@ async function findConsumerByIdentifiers(client, identifiers) {
|
|
|
164
164
|
return null;
|
|
165
165
|
}
|
|
166
166
|
async function searchExact(client, term, predicate) {
|
|
167
|
-
const
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
167
|
+
const seenIds = /* @__PURE__ */ new Set();
|
|
168
|
+
for (let page = 1; ; page++) {
|
|
169
|
+
const response = await client.listConsumers({
|
|
170
|
+
search_term: term,
|
|
171
|
+
page,
|
|
172
|
+
limit: SEARCH_PAGE_SIZE
|
|
173
|
+
});
|
|
174
|
+
const items = response.data ?? [];
|
|
175
|
+
const pagination = response.pagination;
|
|
176
|
+
if (pagination?.current_page !== void 0 && pagination.current_page !== page) {
|
|
177
|
+
throw new Error("Consumer search pagination did not advance to the requested page.");
|
|
178
|
+
}
|
|
179
|
+
const hit = items.find(predicate);
|
|
180
|
+
if (hit) return hit;
|
|
181
|
+
const hasNext = pagination?.has_next_page ?? (pagination?.max_page !== void 0 ? page < pagination.max_page : items.length === SEARCH_PAGE_SIZE);
|
|
182
|
+
if (!hasNext) return null;
|
|
183
|
+
let advanced = false;
|
|
184
|
+
for (const item of items) {
|
|
185
|
+
if (item.id && !seenIds.has(item.id)) {
|
|
186
|
+
seenIds.add(item.id);
|
|
187
|
+
advanced = true;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
if (!advanced || page === Number.MAX_SAFE_INTEGER) {
|
|
191
|
+
throw new Error("Consumer search pagination returned no new consumers.");
|
|
192
|
+
}
|
|
193
|
+
}
|
|
174
194
|
}
|
|
175
195
|
var ErrorShape = zod.z.object({
|
|
176
196
|
code: zod.z.string().optional(),
|
|
@@ -329,11 +349,11 @@ async function ensureConsumerForUser(options, ctx, user) {
|
|
|
329
349
|
if (user.name !== void 0) userForParams.name = user.name;
|
|
330
350
|
const extras = options.getConsumerCreateParams ? await options.getConsumerCreateParams({ user: userForParams }) : {};
|
|
331
351
|
const payload = {
|
|
352
|
+
consumer_type: "INDIVIDUAL",
|
|
353
|
+
...extras,
|
|
332
354
|
name: user.name || user.email,
|
|
333
355
|
email: user.email,
|
|
334
|
-
external_id: user.id
|
|
335
|
-
consumer_type: "INDIVIDUAL",
|
|
336
|
-
...extras
|
|
356
|
+
external_id: user.id
|
|
337
357
|
};
|
|
338
358
|
try {
|
|
339
359
|
const consumer = await options.client.createConsumer(payload);
|
|
@@ -602,7 +622,32 @@ function reconcileProjectionAgainstExisting(existing, projection, options = {})
|
|
|
602
622
|
return projected;
|
|
603
623
|
}
|
|
604
624
|
function projectSubscriptionAgainstExisting(existing, stream) {
|
|
605
|
-
return reconcileProjectionAgainstExisting(existing, projectSubscriptionFields(stream));
|
|
625
|
+
return reconcileProjectionAgainstExisting(existing, projectSubscriptionFields(stream, existing));
|
|
626
|
+
}
|
|
627
|
+
async function persistSubscriptionProjection(adapter, existing, projection, log, source) {
|
|
628
|
+
const stale = existing.providerUpdatedAt instanceof Date && projection.providerUpdatedAt instanceof Date && projection.providerUpdatedAt.getTime() < existing.providerUpdatedAt.getTime();
|
|
629
|
+
if (!stale) {
|
|
630
|
+
const updated = await adapter.update({
|
|
631
|
+
model: SUBSCRIPTION_MODEL,
|
|
632
|
+
update: projection,
|
|
633
|
+
where: [
|
|
634
|
+
{ field: "id", value: existing.id },
|
|
635
|
+
{ field: "providerUpdatedAt", value: existing.providerUpdatedAt ?? null },
|
|
636
|
+
{ field: "streampaySubscriptionId", value: existing.streampaySubscriptionId ?? null },
|
|
637
|
+
{ field: "streampayConsumerId", value: existing.streampayConsumerId ?? null },
|
|
638
|
+
{ field: "status", value: existing.status },
|
|
639
|
+
{ field: "billingStatus", value: existing.billingStatus }
|
|
640
|
+
]
|
|
641
|
+
});
|
|
642
|
+
if (updated) return updated;
|
|
643
|
+
}
|
|
644
|
+
log.warn(
|
|
645
|
+
`${source}: retained newer local subscription state for row=${existing.id}. The provider action is not rolled back.`
|
|
646
|
+
);
|
|
647
|
+
return adapter.findOne({
|
|
648
|
+
model: SUBSCRIPTION_MODEL,
|
|
649
|
+
where: [{ field: "id", value: existing.id }]
|
|
650
|
+
});
|
|
606
651
|
}
|
|
607
652
|
async function applySubscriptionProjection(adapter, stream, log, source) {
|
|
608
653
|
const streampaySubscriptionId = stream?.id;
|
|
@@ -613,11 +658,13 @@ async function applySubscriptionProjection(adapter, stream, log, source) {
|
|
|
613
658
|
where: [{ field: "streampaySubscriptionId", value: streampaySubscriptionId }]
|
|
614
659
|
});
|
|
615
660
|
if (!existing) return;
|
|
616
|
-
await
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
661
|
+
await persistSubscriptionProjection(
|
|
662
|
+
adapter,
|
|
663
|
+
existing,
|
|
664
|
+
projectSubscriptionAgainstExisting(existing, stream),
|
|
665
|
+
log,
|
|
666
|
+
source
|
|
667
|
+
);
|
|
621
668
|
} catch (err) {
|
|
622
669
|
const message = err instanceof Error ? err.message : String(err);
|
|
623
670
|
log.warn(
|
|
@@ -640,7 +687,7 @@ async function syncSubscriptionFromUpstream(client, adapter, streampaySubscripti
|
|
|
640
687
|
}
|
|
641
688
|
await applySubscriptionProjection(adapter, stream, log, source);
|
|
642
689
|
}
|
|
643
|
-
function projectSubscriptionFields(sub) {
|
|
690
|
+
function projectSubscriptionFields(sub, existing) {
|
|
644
691
|
const status = toLocalStatus(sub.status);
|
|
645
692
|
const terminal = isTerminalSubscriptionStatus(status);
|
|
646
693
|
const periodStart = parseDate(sub.current_period_start);
|
|
@@ -658,7 +705,7 @@ function projectSubscriptionFields(sub) {
|
|
|
658
705
|
periodStart,
|
|
659
706
|
periodEnd,
|
|
660
707
|
currentCycleNumber: sub.current_cycle_number ?? null,
|
|
661
|
-
trialStart: sub.trial_end ? parseDate(sub.started_at) ?? periodStart : null,
|
|
708
|
+
trialStart: (sub.trial_end ? parseDate(sub.started_at) ?? periodStart : null) ?? existing?.trialStart ?? null,
|
|
662
709
|
trialEnd: parseDate(sub.trial_end),
|
|
663
710
|
cancelAtPeriodEnd: Boolean(sub.cancel_at_period_end),
|
|
664
711
|
cancelAt: sub.cancel_at_period_end ? periodEnd : null,
|
|
@@ -762,6 +809,7 @@ function projectPlanFields(sub, plans) {
|
|
|
762
809
|
const pendingEffectiveAt = parseDate(sub.pending_change?.effective_at);
|
|
763
810
|
const planChanges = Boolean(inferredPendingPlan) && (inferredPendingPlan !== currentPlan || pendingProductId !== currentProductId);
|
|
764
811
|
return {
|
|
812
|
+
catalogMapped: Boolean(currentPlan),
|
|
765
813
|
...currentPlan ? {
|
|
766
814
|
plan: currentPlan,
|
|
767
815
|
planVersion: configuredCurrent?.version ?? null,
|
|
@@ -812,8 +860,9 @@ function isUniqueConstraintError(err) {
|
|
|
812
860
|
}
|
|
813
861
|
var WEBHOOK_PROCESSING_LEASE_MS = 2 * 60 * 1e3;
|
|
814
862
|
var WEBHOOK_RETRY_DELAYS_MS = [5, 30, 120, 360, 720].map((minutes) => minutes * 60 * 1e3);
|
|
815
|
-
async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader, maxAttempts) {
|
|
816
|
-
const
|
|
863
|
+
async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader, maxAttempts, scope) {
|
|
864
|
+
const sourceEventId = extractEventId(payload);
|
|
865
|
+
const eventId = sourceEventId && (scope ? `${scope}:${sourceEventId}` : sourceEventId);
|
|
817
866
|
if (!eventId) {
|
|
818
867
|
logger(ctx).warn(
|
|
819
868
|
`webhook ${payload.event_type}: missing entity_id/timestamp \u2014 processing without dedupe.`
|
|
@@ -833,7 +882,9 @@ async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader
|
|
|
833
882
|
receivedAt: now,
|
|
834
883
|
lastAttemptAt: now,
|
|
835
884
|
lockedAt: now,
|
|
836
|
-
lockedBy: lockId
|
|
885
|
+
lockedBy: lockId,
|
|
886
|
+
rawPayload: rawBody,
|
|
887
|
+
signatureHeader
|
|
837
888
|
}
|
|
838
889
|
});
|
|
839
890
|
return { action: "process", row: inserted };
|
|
@@ -845,10 +896,9 @@ async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader
|
|
|
845
896
|
where: [{ field: "eventId", value: eventId }]
|
|
846
897
|
});
|
|
847
898
|
if (!existing) {
|
|
848
|
-
|
|
849
|
-
`
|
|
899
|
+
throw new Error(
|
|
900
|
+
`Webhook inbox row missing after unique conflict for ${eventId}; retry delivery.`
|
|
850
901
|
);
|
|
851
|
-
return { action: "process", row: null };
|
|
852
902
|
}
|
|
853
903
|
if (existing.status === "completed") {
|
|
854
904
|
logger(ctx).info(`webhook ${payload.event_type} (${eventId}) already completed \u2014 skipping.`);
|
|
@@ -1002,7 +1052,7 @@ async function findSubscriptionByStreampayId(ctx, streampaySubscriptionId) {
|
|
|
1002
1052
|
where: [{ field: "streampaySubscriptionId", value: streampaySubscriptionId }]
|
|
1003
1053
|
});
|
|
1004
1054
|
}
|
|
1005
|
-
async function findIncompleteRow(ctx, referenceId, referenceType, plan, paymentLinkId) {
|
|
1055
|
+
async function findIncompleteRow(ctx, referenceId, referenceType, plan, paymentLinkId, consumerId) {
|
|
1006
1056
|
const candidates = await ctx.context.adapter.findMany({
|
|
1007
1057
|
model: SUBSCRIPTION_MODEL2,
|
|
1008
1058
|
where: [
|
|
@@ -1011,13 +1061,15 @@ async function findIncompleteRow(ctx, referenceId, referenceType, plan, paymentL
|
|
|
1011
1061
|
{ field: "status", value: "incomplete" }
|
|
1012
1062
|
]
|
|
1013
1063
|
});
|
|
1014
|
-
const scopedCandidates =
|
|
1064
|
+
const scopedCandidates = candidates.filter(
|
|
1065
|
+
(candidate) => (!referenceType || (candidate.referenceType ?? "user") === referenceType) && (!consumerId || !candidate.streampayConsumerId || candidate.streampayConsumerId === consumerId)
|
|
1066
|
+
);
|
|
1015
1067
|
if (scopedCandidates.length === 0) return null;
|
|
1016
1068
|
if (paymentLinkId) {
|
|
1017
1069
|
const exact = scopedCandidates.find(
|
|
1018
1070
|
(candidate) => candidate.streampayPaymentLinkId === paymentLinkId
|
|
1019
1071
|
);
|
|
1020
|
-
|
|
1072
|
+
return exact ?? null;
|
|
1021
1073
|
}
|
|
1022
1074
|
if (!referenceType && new Set(scopedCandidates.map((candidate) => candidate.referenceType ?? "user")).size > 1) {
|
|
1023
1075
|
return null;
|
|
@@ -1066,6 +1118,31 @@ var SubscriptionCorrelationError = class extends Error {
|
|
|
1066
1118
|
this.name = "SubscriptionCorrelationError";
|
|
1067
1119
|
}
|
|
1068
1120
|
};
|
|
1121
|
+
async function updateReconciledSubscription(ctx, existing, projected, streampaySubscriptionId) {
|
|
1122
|
+
if (existing.providerUpdatedAt instanceof Date && projected.providerUpdatedAt instanceof Date && projected.providerUpdatedAt.getTime() < existing.providerUpdatedAt.getTime()) {
|
|
1123
|
+
throw new Error(
|
|
1124
|
+
`StreamPay returned stale subscription state for sub=${streampaySubscriptionId}. Retry reconciliation.`
|
|
1125
|
+
);
|
|
1126
|
+
}
|
|
1127
|
+
const updated = await ctx.context.adapter.update({
|
|
1128
|
+
model: SUBSCRIPTION_MODEL2,
|
|
1129
|
+
update: projected,
|
|
1130
|
+
where: [
|
|
1131
|
+
{ field: "id", value: existing.id },
|
|
1132
|
+
{ field: "providerUpdatedAt", value: existing.providerUpdatedAt ?? null },
|
|
1133
|
+
{ field: "streampaySubscriptionId", value: existing.streampaySubscriptionId ?? null },
|
|
1134
|
+
{ field: "streampayConsumerId", value: existing.streampayConsumerId ?? null },
|
|
1135
|
+
{ field: "status", value: existing.status },
|
|
1136
|
+
{ field: "billingStatus", value: existing.billingStatus }
|
|
1137
|
+
]
|
|
1138
|
+
});
|
|
1139
|
+
if (!updated) {
|
|
1140
|
+
throw new Error(
|
|
1141
|
+
`Subscription state changed during reconciliation for sub=${streampaySubscriptionId}. Retry delivery.`
|
|
1142
|
+
);
|
|
1143
|
+
}
|
|
1144
|
+
return updated;
|
|
1145
|
+
}
|
|
1069
1146
|
async function reconcileFromStreamPay(ctx, payload, client, plans) {
|
|
1070
1147
|
const streampaySubscriptionId = payload.entity_id;
|
|
1071
1148
|
if (!streampaySubscriptionId) {
|
|
@@ -1084,7 +1161,7 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
|
|
|
1084
1161
|
}
|
|
1085
1162
|
const existing = await findSubscriptionByStreampayId(ctx, streampaySubscriptionId);
|
|
1086
1163
|
let projected = {
|
|
1087
|
-
...projectSubscriptionFields(stream),
|
|
1164
|
+
...projectSubscriptionFields(stream, existing),
|
|
1088
1165
|
...projectPlanFields(stream, plans)
|
|
1089
1166
|
};
|
|
1090
1167
|
const eventAt = parseDate(payload.timestamp);
|
|
@@ -1120,18 +1197,19 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
|
|
|
1120
1197
|
projected.activeSlotKey = desiredSlotKey;
|
|
1121
1198
|
}
|
|
1122
1199
|
}
|
|
1123
|
-
const updated = await
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1200
|
+
const updated = await updateReconciledSubscription(
|
|
1201
|
+
ctx,
|
|
1202
|
+
existing,
|
|
1203
|
+
projected,
|
|
1204
|
+
streampaySubscriptionId
|
|
1205
|
+
);
|
|
1128
1206
|
if (eventIsStale) {
|
|
1129
1207
|
logger(ctx).info(
|
|
1130
1208
|
`webhook ${payload.event_type}: ignored stale lifecycle callback for sub=${streampaySubscriptionId}.`
|
|
1131
1209
|
);
|
|
1132
1210
|
return { row: null, stream };
|
|
1133
1211
|
}
|
|
1134
|
-
return { row: updated
|
|
1212
|
+
return { row: updated, stream };
|
|
1135
1213
|
}
|
|
1136
1214
|
const planName = readMetadataString(payload.data, PLAN_NAME_METADATA_KEY) ?? inferPlanFromItems(stream, plans);
|
|
1137
1215
|
const referenceId = readMetadataString(payload.data, REFERENCE_ID_METADATA_KEY);
|
|
@@ -1153,7 +1231,7 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
|
|
|
1153
1231
|
logger(ctx).warn(
|
|
1154
1232
|
`webhook ${payload.event_type}: referenced subscription row=${localRowId} is missing; rebuilding from signed metadata.`
|
|
1155
1233
|
);
|
|
1156
|
-
} else if (metadataRow.referenceId === referenceId && (!metadataReferenceType || (metadataRow.referenceType ?? "user") === metadataReferenceType) && metadataRow.plan === planName && (!metadataRow.streampaySubscriptionId || metadataRow.streampaySubscriptionId === streampaySubscriptionId) && (!metadataRow.streampayPaymentLinkId || !paymentLinkId || metadataRow.streampayPaymentLinkId === paymentLinkId)) {
|
|
1234
|
+
} 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)) {
|
|
1157
1235
|
const projectedWithSlot = {
|
|
1158
1236
|
...projected,
|
|
1159
1237
|
billingStatus: metadataRow.billingStatus ?? "current",
|
|
@@ -1165,12 +1243,13 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
|
|
|
1165
1243
|
)
|
|
1166
1244
|
}
|
|
1167
1245
|
};
|
|
1168
|
-
const updated = await
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1246
|
+
const updated = await updateReconciledSubscription(
|
|
1247
|
+
ctx,
|
|
1248
|
+
metadataRow,
|
|
1249
|
+
projectedWithSlot,
|
|
1250
|
+
streampaySubscriptionId
|
|
1251
|
+
);
|
|
1252
|
+
return { row: updated, stream };
|
|
1174
1253
|
}
|
|
1175
1254
|
if (metadataRow) {
|
|
1176
1255
|
logger(ctx).warn(
|
|
@@ -1186,7 +1265,8 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
|
|
|
1186
1265
|
referenceId,
|
|
1187
1266
|
metadataReferenceType,
|
|
1188
1267
|
planName,
|
|
1189
|
-
paymentLinkId
|
|
1268
|
+
paymentLinkId,
|
|
1269
|
+
stream.organization_consumer_id ?? null
|
|
1190
1270
|
);
|
|
1191
1271
|
if (incomplete) {
|
|
1192
1272
|
const projectedWithSlot = {
|
|
@@ -1200,13 +1280,14 @@ async function reconcileFromStreamPay(ctx, payload, client, plans) {
|
|
|
1200
1280
|
)
|
|
1201
1281
|
}
|
|
1202
1282
|
};
|
|
1203
|
-
const updated = await
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1283
|
+
const updated = await updateReconciledSubscription(
|
|
1284
|
+
ctx,
|
|
1285
|
+
incomplete,
|
|
1286
|
+
projectedWithSlot,
|
|
1287
|
+
streampaySubscriptionId
|
|
1288
|
+
);
|
|
1208
1289
|
return {
|
|
1209
|
-
row: updated
|
|
1290
|
+
row: updated,
|
|
1210
1291
|
stream
|
|
1211
1292
|
};
|
|
1212
1293
|
}
|
|
@@ -1255,8 +1336,8 @@ async function syncWebhookPayload(ctx, payload, client, plans, callbacks, option
|
|
|
1255
1336
|
const trackedRowId = claim.row?.id ?? null;
|
|
1256
1337
|
const trackedLockId = claim.row?.lockedBy ?? void 0;
|
|
1257
1338
|
try {
|
|
1258
|
-
if (payload.event_type === "INVOICE_COMPLETED") {
|
|
1259
|
-
await
|
|
1339
|
+
if (payload.event_type === "INVOICE_COMPLETED" || payload.event_type === "SUBSCRIPTION_CYCLE_RENEWED_SUCCESSFULLY") {
|
|
1340
|
+
await handleRenewalEvidence(
|
|
1260
1341
|
ctx,
|
|
1261
1342
|
payload,
|
|
1262
1343
|
client,
|
|
@@ -1297,20 +1378,22 @@ async function syncWebhookPayload(ctx, payload, client, plans, callbacks, option
|
|
|
1297
1378
|
throw err;
|
|
1298
1379
|
}
|
|
1299
1380
|
}
|
|
1300
|
-
async function
|
|
1381
|
+
async function handleRenewalEvidence(ctx, payload, client, plans, callbacks, retryOnCallbackError, retryingRenewalCallback) {
|
|
1301
1382
|
const invoiceId = payload.data?.invoice?.id ?? payload.entity_id;
|
|
1302
1383
|
if (!invoiceId) return;
|
|
1303
|
-
let subscriptionId = null;
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1384
|
+
let subscriptionId = payload.entity_type === "SUBSCRIPTION" ? payload.entity_id : null;
|
|
1385
|
+
if (!subscriptionId) {
|
|
1386
|
+
try {
|
|
1387
|
+
const invoice = await client.getInvoice(invoiceId);
|
|
1388
|
+
if (invoice && typeof invoice === "object" && "subscription_id" in invoice) {
|
|
1389
|
+
const subId = invoice.subscription_id;
|
|
1390
|
+
if (typeof subId === "string" && subId.length > 0) subscriptionId = subId;
|
|
1391
|
+
}
|
|
1392
|
+
} catch (err) {
|
|
1393
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
1394
|
+
logger(ctx).error(`${payload.event_type}: getInvoice(${invoiceId}) failed: ${msg}`);
|
|
1395
|
+
throw err;
|
|
1309
1396
|
}
|
|
1310
|
-
} catch (err) {
|
|
1311
|
-
const msg = err instanceof Error ? err.message : String(err);
|
|
1312
|
-
logger(ctx).error(`INVOICE_COMPLETED: getInvoice(${invoiceId}) failed: ${msg}`);
|
|
1313
|
-
throw err;
|
|
1314
1397
|
}
|
|
1315
1398
|
if (!subscriptionId) return;
|
|
1316
1399
|
let stream;
|
|
@@ -1318,7 +1401,7 @@ async function handleInvoiceCompleted(ctx, payload, client, plans, callbacks, re
|
|
|
1318
1401
|
stream = await client.getSubscription(subscriptionId);
|
|
1319
1402
|
} catch (err) {
|
|
1320
1403
|
const msg = err instanceof Error ? err.message : String(err);
|
|
1321
|
-
logger(ctx).error(
|
|
1404
|
+
logger(ctx).error(`${payload.event_type}: getSubscription(${subscriptionId}) failed: ${msg}`);
|
|
1322
1405
|
throw err;
|
|
1323
1406
|
}
|
|
1324
1407
|
const existing = await findSubscriptionByStreampayId(ctx, subscriptionId);
|
|
@@ -1328,7 +1411,7 @@ async function handleInvoiceCompleted(ctx, payload, client, plans, callbacks, re
|
|
|
1328
1411
|
eventAt && existing.providerUpdatedAt instanceof Date && eventAt.getTime() < existing.providerUpdatedAt.getTime()
|
|
1329
1412
|
);
|
|
1330
1413
|
const projected = {
|
|
1331
|
-
...projectSubscriptionFields(stream),
|
|
1414
|
+
...projectSubscriptionFields(stream, existing),
|
|
1332
1415
|
...projectPlanFields(stream, plans),
|
|
1333
1416
|
...eventIsStale ? existing.billingStatus === "past_due" && toLocalStatus(stream.status) === "active" ? { status: "past_due", billingStatus: "past_due" } : {} : { billingStatus: "current" }
|
|
1334
1417
|
};
|
|
@@ -1336,14 +1419,45 @@ async function handleInvoiceCompleted(ctx, payload, client, plans, callbacks, re
|
|
|
1336
1419
|
const projectedPeriodEnd = projected.periodEnd?.getTime() ?? null;
|
|
1337
1420
|
const periodAdvanced = previousPeriodEnd !== null && projectedPeriodEnd !== null && projectedPeriodEnd > previousPeriodEnd;
|
|
1338
1421
|
const cycleAdvanced = existing.currentCycleNumber !== null && existing.currentCycleNumber !== void 0 && projected.currentCycleNumber !== null && projected.currentCycleNumber !== void 0 && projected.currentCycleNumber > existing.currentCycleNumber;
|
|
1422
|
+
const eventId = extractEventId(payload);
|
|
1423
|
+
const pendingCallback = existing.renewalCallbackEventId ?? null;
|
|
1424
|
+
if (!pendingCallback && existing.providerUpdatedAt instanceof Date && projected.providerUpdatedAt instanceof Date && projected.providerUpdatedAt.getTime() < existing.providerUpdatedAt.getTime()) {
|
|
1425
|
+
throw new Error(
|
|
1426
|
+
`StreamPay returned stale subscription state for sub=${subscriptionId}; retry delivery.`
|
|
1427
|
+
);
|
|
1428
|
+
}
|
|
1429
|
+
if (pendingCallback && pendingCallback !== eventId) {
|
|
1430
|
+
throw new Error(`Subscription renewal callback ${pendingCallback} is pending; retry delivery.`);
|
|
1431
|
+
}
|
|
1432
|
+
const deliverCallback = pendingCallback === eventId && pendingCallback !== null || !eventIsStale && (periodAdvanced || cycleAdvanced || retryingRenewalCallback);
|
|
1433
|
+
const callbackOwner = deliverCallback && callbacks.onSubscriptionRenewed ? eventId : null;
|
|
1339
1434
|
const updated = await ctx.context.adapter.update({
|
|
1340
1435
|
model: SUBSCRIPTION_MODEL2,
|
|
1341
|
-
|
|
1342
|
-
|
|
1436
|
+
// Recovery must retain the pending cycle, even if Stream has already advanced again.
|
|
1437
|
+
update: pendingCallback ? { renewalCallbackEventId: callbackOwner } : { ...projected, renewalCallbackEventId: callbackOwner },
|
|
1438
|
+
where: [
|
|
1439
|
+
{ field: "id", value: existing.id },
|
|
1440
|
+
{ field: "periodEnd", value: existing.periodEnd ?? null },
|
|
1441
|
+
{ field: "currentCycleNumber", value: existing.currentCycleNumber ?? null },
|
|
1442
|
+
{ field: "renewalCallbackEventId", value: pendingCallback },
|
|
1443
|
+
{ field: "providerUpdatedAt", value: existing.providerUpdatedAt ?? null },
|
|
1444
|
+
{ field: "status", value: existing.status },
|
|
1445
|
+
{ field: "billingStatus", value: existing.billingStatus }
|
|
1446
|
+
]
|
|
1343
1447
|
});
|
|
1344
|
-
|
|
1448
|
+
if (!updated) {
|
|
1449
|
+
if (pendingCallback && pendingCallback === eventId) {
|
|
1450
|
+
throw new Error(`Subscription cycle changed during callback recovery; retry delivery.`);
|
|
1451
|
+
}
|
|
1452
|
+
const latest = await findSubscriptionByStreampayId(ctx, subscriptionId);
|
|
1453
|
+
const anotherCallbackOwner = latest?.renewalCallbackEventId;
|
|
1454
|
+
const desiredCycleAdvanced = (periodAdvanced || cycleAdvanced) && (!periodAdvanced || (latest?.periodEnd?.getTime() ?? 0) >= (projectedPeriodEnd ?? 0)) && (!cycleAdvanced || (latest?.currentCycleNumber ?? 0) >= (projected.currentCycleNumber ?? 0));
|
|
1455
|
+
if (anotherCallbackOwner && anotherCallbackOwner !== eventId && desiredCycleAdvanced) return;
|
|
1456
|
+
throw new Error(`Subscription changed during renewal reconciliation; retry delivery.`);
|
|
1457
|
+
}
|
|
1458
|
+
const row = updated;
|
|
1345
1459
|
const user = await resolveRowUser(ctx, row);
|
|
1346
|
-
if (
|
|
1460
|
+
if (deliverCallback) {
|
|
1347
1461
|
await fireCallback(
|
|
1348
1462
|
ctx,
|
|
1349
1463
|
callbacks.onSubscriptionRenewed,
|
|
@@ -1351,6 +1465,16 @@ async function handleInvoiceCompleted(ctx, payload, client, plans, callbacks, re
|
|
|
1351
1465
|
"onSubscriptionRenewed",
|
|
1352
1466
|
retryOnCallbackError
|
|
1353
1467
|
);
|
|
1468
|
+
if (callbackOwner) {
|
|
1469
|
+
await ctx.context.adapter.update({
|
|
1470
|
+
model: SUBSCRIPTION_MODEL2,
|
|
1471
|
+
update: { renewalCallbackEventId: null },
|
|
1472
|
+
where: [
|
|
1473
|
+
{ field: "id", value: row.id },
|
|
1474
|
+
{ field: "renewalCallbackEventId", value: callbackOwner }
|
|
1475
|
+
]
|
|
1476
|
+
});
|
|
1477
|
+
}
|
|
1354
1478
|
}
|
|
1355
1479
|
}
|
|
1356
1480
|
async function dispatchSubscriptionCallback(ctx, payload, data, callbacks, retryOnCallbackError) {
|
|
@@ -1547,16 +1671,16 @@ function forwardedBody() {
|
|
|
1547
1671
|
);
|
|
1548
1672
|
}
|
|
1549
1673
|
var PaymentsListQuery = zod.z.object({
|
|
1550
|
-
page: zod.z.coerce.number().int().positive().optional(),
|
|
1674
|
+
page: zod.z.coerce.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional(),
|
|
1551
1675
|
size: zod.z.coerce.number().int().positive().max(100).optional(),
|
|
1552
1676
|
invoice_id: zod.z.string().uuid().optional()
|
|
1553
1677
|
}).passthrough();
|
|
1554
1678
|
var PaginationOnlyQuery = zod.z.object({
|
|
1555
|
-
page: zod.z.coerce.number().int().positive().optional(),
|
|
1679
|
+
page: zod.z.coerce.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional(),
|
|
1556
1680
|
size: zod.z.coerce.number().int().positive().max(100).optional()
|
|
1557
1681
|
}).passthrough();
|
|
1558
1682
|
var ConsumersListQuery = zod.z.object({
|
|
1559
|
-
page: zod.z.coerce.number().int().positive().optional(),
|
|
1683
|
+
page: zod.z.coerce.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional(),
|
|
1560
1684
|
size: zod.z.coerce.number().int().positive().max(100).optional(),
|
|
1561
1685
|
search_term: zod.z.string().optional()
|
|
1562
1686
|
}).passthrough();
|
|
@@ -1602,7 +1726,7 @@ function buildPaymentsEndpoints(client, adminOptions) {
|
|
|
1602
1726
|
await requireAdmin(ctx, adminOptions);
|
|
1603
1727
|
const params = {};
|
|
1604
1728
|
if (ctx.query.page !== void 0) params.page = ctx.query.page;
|
|
1605
|
-
if (ctx.query.size !== void 0) params.
|
|
1729
|
+
if (ctx.query.size !== void 0) params.limit = ctx.query.size;
|
|
1606
1730
|
if (ctx.query.invoice_id !== void 0) params.invoice_id = ctx.query.invoice_id;
|
|
1607
1731
|
try {
|
|
1608
1732
|
const response = await client.listPayments(params);
|
|
@@ -1707,7 +1831,7 @@ function buildSubscriptionsEndpoints(client, adminOptions) {
|
|
|
1707
1831
|
await requireAdmin(ctx, adminOptions);
|
|
1708
1832
|
const params = {};
|
|
1709
1833
|
if (ctx.query.page !== void 0) params.page = ctx.query.page;
|
|
1710
|
-
if (ctx.query.size !== void 0) params.
|
|
1834
|
+
if (ctx.query.size !== void 0) params.limit = ctx.query.size;
|
|
1711
1835
|
try {
|
|
1712
1836
|
const response = await client.listSubscriptions(params);
|
|
1713
1837
|
return ctx.json(response);
|
|
@@ -1901,7 +2025,7 @@ function buildConsumersEndpoints(client, adminOptions) {
|
|
|
1901
2025
|
await requireAdmin(ctx, adminOptions);
|
|
1902
2026
|
const params = {};
|
|
1903
2027
|
if (ctx.query.page !== void 0) params.page = ctx.query.page;
|
|
1904
|
-
if (ctx.query.size !== void 0) params.
|
|
2028
|
+
if (ctx.query.size !== void 0) params.limit = ctx.query.size;
|
|
1905
2029
|
if (ctx.query.search_term !== void 0) params.search_term = ctx.query.search_term;
|
|
1906
2030
|
try {
|
|
1907
2031
|
const response = await client.listConsumers(params);
|
|
@@ -1964,19 +2088,6 @@ function buildConsumersEndpoints(client, adminOptions) {
|
|
|
1964
2088
|
async (ctx) => {
|
|
1965
2089
|
await requireAdmin(ctx, adminOptions);
|
|
1966
2090
|
const consumerId = ctx.params.id;
|
|
1967
|
-
let externalId;
|
|
1968
|
-
try {
|
|
1969
|
-
const consumer = await client.getConsumer(consumerId);
|
|
1970
|
-
if (typeof consumer.external_id === "string" && consumer.external_id.length > 0) {
|
|
1971
|
-
externalId = consumer.external_id;
|
|
1972
|
-
}
|
|
1973
|
-
} catch (err) {
|
|
1974
|
-
toAPIError(
|
|
1975
|
-
`StreamPay getConsumer failed for consumer=${consumerId}:`,
|
|
1976
|
-
err,
|
|
1977
|
-
getLogger(ctx)
|
|
1978
|
-
);
|
|
1979
|
-
}
|
|
1980
2091
|
try {
|
|
1981
2092
|
await client.deleteConsumer(consumerId);
|
|
1982
2093
|
} catch (err) {
|
|
@@ -1988,16 +2099,26 @@ function buildConsumersEndpoints(client, adminOptions) {
|
|
|
1988
2099
|
);
|
|
1989
2100
|
}
|
|
1990
2101
|
}
|
|
1991
|
-
|
|
1992
|
-
|
|
1993
|
-
|
|
1994
|
-
|
|
2102
|
+
try {
|
|
2103
|
+
const adapter = getAdapter(ctx);
|
|
2104
|
+
const user = await adapter.findOne({
|
|
2105
|
+
model: "user",
|
|
2106
|
+
where: [{ field: "streampayConsumerId", value: consumerId }]
|
|
2107
|
+
});
|
|
2108
|
+
if (user) {
|
|
2109
|
+
await adapter.update({
|
|
2110
|
+
model: "user",
|
|
2111
|
+
update: { streampayConsumerId: null },
|
|
2112
|
+
where: [
|
|
2113
|
+
{ field: "id", value: user.id },
|
|
2114
|
+
{ field: "streampayConsumerId", value: consumerId }
|
|
2115
|
+
]
|
|
1995
2116
|
});
|
|
1996
|
-
} catch (err) {
|
|
1997
|
-
getLogger(ctx).error(
|
|
1998
|
-
`StreamPay admin delete: link clear failed for user=${externalId} consumer=${consumerId}: ${formatStreamPayError(err)}`
|
|
1999
|
-
);
|
|
2000
2117
|
}
|
|
2118
|
+
} catch (err) {
|
|
2119
|
+
getLogger(ctx).error(
|
|
2120
|
+
`StreamPay admin delete: link clear failed for consumer=${consumerId}: ${formatStreamPayError(err)}`
|
|
2121
|
+
);
|
|
2001
2122
|
}
|
|
2002
2123
|
return ctx.json({ deleted: true });
|
|
2003
2124
|
}
|
|
@@ -2017,7 +2138,7 @@ function buildInvoicesEndpoints(client, adminOptions) {
|
|
|
2017
2138
|
await requireAdmin(ctx, adminOptions);
|
|
2018
2139
|
const params = {};
|
|
2019
2140
|
if (ctx.query.page !== void 0) params.page = ctx.query.page;
|
|
2020
|
-
if (ctx.query.size !== void 0) params.
|
|
2141
|
+
if (ctx.query.size !== void 0) params.limit = ctx.query.size;
|
|
2021
2142
|
try {
|
|
2022
2143
|
const response = await client.listInvoices(params);
|
|
2023
2144
|
return ctx.json(response);
|
|
@@ -2079,7 +2200,7 @@ function buildProductsEndpoints(client, adminOptions) {
|
|
|
2079
2200
|
await requireAdmin(ctx, adminOptions);
|
|
2080
2201
|
const params = {};
|
|
2081
2202
|
if (ctx.query.page !== void 0) params.page = ctx.query.page;
|
|
2082
|
-
if (ctx.query.size !== void 0) params.
|
|
2203
|
+
if (ctx.query.size !== void 0) params.limit = ctx.query.size;
|
|
2083
2204
|
try {
|
|
2084
2205
|
const response = await client.listProducts(params);
|
|
2085
2206
|
return ctx.json(response);
|
|
@@ -2185,7 +2306,7 @@ function buildCouponsEndpoints(client, adminOptions) {
|
|
|
2185
2306
|
await requireAdmin(ctx, adminOptions);
|
|
2186
2307
|
const params = {};
|
|
2187
2308
|
if (ctx.query.page !== void 0) params.page = ctx.query.page;
|
|
2188
|
-
if (ctx.query.size !== void 0) params.
|
|
2309
|
+
if (ctx.query.size !== void 0) params.limit = ctx.query.size;
|
|
2189
2310
|
try {
|
|
2190
2311
|
const response = await client.listCoupons(params);
|
|
2191
2312
|
return ctx.json(response);
|
|
@@ -2269,7 +2390,7 @@ function buildPaymentLinksEndpoints(client, adminOptions) {
|
|
|
2269
2390
|
await requireAdmin(ctx, adminOptions);
|
|
2270
2391
|
const params = {};
|
|
2271
2392
|
if (ctx.query.page !== void 0) params.page = ctx.query.page;
|
|
2272
|
-
if (ctx.query.size !== void 0) params.
|
|
2393
|
+
if (ctx.query.size !== void 0) params.limit = ctx.query.size;
|
|
2273
2394
|
try {
|
|
2274
2395
|
const response = await client.listPaymentLinks(params);
|
|
2275
2396
|
return ctx.json(response);
|
|
@@ -2303,9 +2424,16 @@ function buildPaymentLinksEndpoints(client, adminOptions) {
|
|
|
2303
2424
|
var WebhookEventsListQuery = zod.z.object({
|
|
2304
2425
|
status: zod.z.enum(["pending", "completed", "dead_letter"]).optional(),
|
|
2305
2426
|
eventType: zod.z.string().optional(),
|
|
2306
|
-
page: zod.z.coerce.number().int().positive().optional(),
|
|
2427
|
+
page: zod.z.coerce.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional(),
|
|
2307
2428
|
size: zod.z.coerce.number().int().positive().max(100).optional()
|
|
2308
2429
|
}).passthrough();
|
|
2430
|
+
function decodeWebhookEventId(value) {
|
|
2431
|
+
try {
|
|
2432
|
+
return decodeURIComponent(value);
|
|
2433
|
+
} catch {
|
|
2434
|
+
throw new api.APIError("BAD_REQUEST", { message: "Invalid webhook event identifier." });
|
|
2435
|
+
}
|
|
2436
|
+
}
|
|
2309
2437
|
function buildWebhookEventsEndpoints(adminOptions, registry) {
|
|
2310
2438
|
return {
|
|
2311
2439
|
adminListWebhookEvents: api.createAuthEndpoint(
|
|
@@ -2350,7 +2478,7 @@ function buildWebhookEventsEndpoints(adminOptions, registry) {
|
|
|
2350
2478
|
const adapter = getAdapter(ctx);
|
|
2351
2479
|
const row = await adapter.findOne({
|
|
2352
2480
|
model: WEBHOOK_EVENT_MODEL,
|
|
2353
|
-
where: [{ field: "eventId", value: ctx.params.eventId }]
|
|
2481
|
+
where: [{ field: "eventId", value: decodeWebhookEventId(ctx.params.eventId) }]
|
|
2354
2482
|
});
|
|
2355
2483
|
if (!row) {
|
|
2356
2484
|
throw new api.APIError("NOT_FOUND", {
|
|
@@ -2372,11 +2500,14 @@ function buildWebhookEventsEndpoints(adminOptions, registry) {
|
|
|
2372
2500
|
await requireAdmin(ctx, adminOptions);
|
|
2373
2501
|
if (!registry?.replayWebhookEvent) {
|
|
2374
2502
|
throw new api.APIError("BAD_REQUEST", {
|
|
2375
|
-
message: "Replay unavailable \u2014
|
|
2503
|
+
message: "Replay unavailable \u2014 enable the subscriptions webhook inbox or webhooks({ deduplicate: true })."
|
|
2376
2504
|
});
|
|
2377
2505
|
}
|
|
2378
2506
|
try {
|
|
2379
|
-
const result = await registry.replayWebhookEvent(
|
|
2507
|
+
const result = await registry.replayWebhookEvent(
|
|
2508
|
+
ctx,
|
|
2509
|
+
decodeWebhookEventId(ctx.params.eventId)
|
|
2510
|
+
);
|
|
2380
2511
|
return ctx.json(result);
|
|
2381
2512
|
} catch (err) {
|
|
2382
2513
|
if (err instanceof api.APIError) throw err;
|
|
@@ -2398,9 +2529,10 @@ function buildWebhookEventsEndpoints(adminOptions, registry) {
|
|
|
2398
2529
|
async (ctx) => {
|
|
2399
2530
|
await requireAdmin(ctx, adminOptions);
|
|
2400
2531
|
const adapter = getAdapter(ctx);
|
|
2532
|
+
const eventId = decodeWebhookEventId(ctx.params.eventId);
|
|
2401
2533
|
const row = await adapter.findOne({
|
|
2402
2534
|
model: WEBHOOK_EVENT_MODEL,
|
|
2403
|
-
where: [{ field: "eventId", value:
|
|
2535
|
+
where: [{ field: "eventId", value: eventId }]
|
|
2404
2536
|
});
|
|
2405
2537
|
if (!row) {
|
|
2406
2538
|
throw new api.APIError("NOT_FOUND", {
|
|
@@ -2408,8 +2540,24 @@ function buildWebhookEventsEndpoints(adminOptions, registry) {
|
|
|
2408
2540
|
message: `Webhook event ${ctx.params.eventId} not found.`
|
|
2409
2541
|
});
|
|
2410
2542
|
}
|
|
2543
|
+
if (registry?.subscriptionWebhookSync && !eventId.startsWith("handlers:") && (row.eventType === "INVOICE_COMPLETED" || row.eventType === "SUBSCRIPTION_CYCLE_RENEWED_SUCCESSFULLY")) {
|
|
2544
|
+
const subscription = await adapter.findOne({
|
|
2545
|
+
model: "subscription",
|
|
2546
|
+
where: [{ field: "renewalCallbackEventId", value: eventId }]
|
|
2547
|
+
});
|
|
2548
|
+
if (subscription) {
|
|
2549
|
+
await adapter.update({
|
|
2550
|
+
model: "subscription",
|
|
2551
|
+
update: { renewalCallbackEventId: null },
|
|
2552
|
+
where: [
|
|
2553
|
+
{ field: "id", value: subscription.id },
|
|
2554
|
+
{ field: "renewalCallbackEventId", value: eventId }
|
|
2555
|
+
]
|
|
2556
|
+
});
|
|
2557
|
+
}
|
|
2558
|
+
}
|
|
2411
2559
|
await markWebhookEventCompleted({ context: { adapter } }, row.id);
|
|
2412
|
-
return ctx.json({ discarded: true, eventId
|
|
2560
|
+
return ctx.json({ discarded: true, eventId });
|
|
2413
2561
|
}
|
|
2414
2562
|
)
|
|
2415
2563
|
};
|
|
@@ -2437,21 +2585,21 @@ var CheckoutRequestBody = zod.z.object({
|
|
|
2437
2585
|
zod.z.array(
|
|
2438
2586
|
zod.z.object({
|
|
2439
2587
|
productId: zod.z.string().uuid(),
|
|
2440
|
-
quantity: zod.z.number().int().positive().optional()
|
|
2588
|
+
quantity: zod.z.number().int().positive().safe().optional()
|
|
2441
2589
|
})
|
|
2442
2590
|
).min(1, "`products` must contain at least one item."),
|
|
2443
2591
|
zod.z.array(zod.z.string().uuid()).min(1, "`products` must contain at least one item."),
|
|
2444
2592
|
zod.z.string().uuid()
|
|
2445
2593
|
]).optional(),
|
|
2446
|
-
slug: zod.z.string().optional(),
|
|
2594
|
+
slug: zod.z.string().min(1).optional(),
|
|
2447
2595
|
referenceId: zod.z.string().optional(),
|
|
2448
2596
|
name: zod.z.string().min(1).optional(),
|
|
2449
2597
|
description: zod.z.string().optional(),
|
|
2450
|
-
metadata: zod.z.record(zod.z.string(), zod.z.union([zod.z.string(), zod.z.number(), zod.z.boolean()])).optional(),
|
|
2598
|
+
metadata: zod.z.record(zod.z.string(), zod.z.union([zod.z.string(), zod.z.number().finite(), zod.z.boolean()])).optional(),
|
|
2451
2599
|
successUrl: RelativeOrAbsoluteUrl.optional(),
|
|
2452
2600
|
failureUrl: RelativeOrAbsoluteUrl.optional(),
|
|
2453
|
-
maxNumberOfPayments: zod.z.number().int().positive().optional(),
|
|
2454
|
-
validUntil: zod.z.string().datetime().optional(),
|
|
2601
|
+
maxNumberOfPayments: zod.z.number().int().positive().safe().optional(),
|
|
2602
|
+
validUntil: zod.z.string().datetime({ offset: true }).optional(),
|
|
2455
2603
|
couponIds: zod.z.array(zod.z.string().uuid()).optional(),
|
|
2456
2604
|
redirect: zod.z.coerce.boolean().optional()
|
|
2457
2605
|
});
|
|
@@ -2724,24 +2872,56 @@ var checkout = (checkoutOptions = {}) => {
|
|
|
2724
2872
|
};
|
|
2725
2873
|
};
|
|
2726
2874
|
var DEFAULT_PAGE_SIZE = 100;
|
|
2875
|
+
var paginationQuery = zod.z.object({
|
|
2876
|
+
page: zod.z.coerce.number().int().min(1).max(Number.MAX_SAFE_INTEGER).optional(),
|
|
2877
|
+
size: zod.z.coerce.number().int().min(1).max(100).optional()
|
|
2878
|
+
});
|
|
2727
2879
|
async function getConsumerIdOrNull(client, user) {
|
|
2728
2880
|
rejectUnauthorized(user, "Anonymous users cannot access the billing portal.");
|
|
2729
2881
|
if (user.streampayConsumerId) return user.streampayConsumerId;
|
|
2730
2882
|
return findConsumerByExternalId(client, { externalId: user.id });
|
|
2731
2883
|
}
|
|
2732
|
-
var portal = ({ pageSize } = {}) => (options) => {
|
|
2884
|
+
var portal = ({ pageSize, createSession } = {}) => (options) => {
|
|
2733
2885
|
const client = options.client;
|
|
2734
2886
|
const size = clampPageSize(pageSize);
|
|
2735
2887
|
return {
|
|
2736
2888
|
endpoints: {
|
|
2889
|
+
portalSession: api.createAuthEndpoint(
|
|
2890
|
+
"/consumer/portal/session",
|
|
2891
|
+
{ method: "POST", use: [api.sessionMiddleware] },
|
|
2892
|
+
async (ctx) => {
|
|
2893
|
+
ctx.setHeader("cache-control", "no-store");
|
|
2894
|
+
try {
|
|
2895
|
+
const consumerId = await getConsumerIdOrNull(
|
|
2896
|
+
client,
|
|
2897
|
+
asSessionUser(ctx.context.session?.user)
|
|
2898
|
+
);
|
|
2899
|
+
if (!consumerId)
|
|
2900
|
+
throw new api.APIError("NOT_FOUND", {
|
|
2901
|
+
message: "No StreamPay consumer is linked to this account."
|
|
2902
|
+
});
|
|
2903
|
+
if (!createSession)
|
|
2904
|
+
throw new api.APIError("NOT_FOUND", {
|
|
2905
|
+
message: "Hosted customer portal is not configured."
|
|
2906
|
+
});
|
|
2907
|
+
const session = await createSession({ organization_consumer_id: consumerId });
|
|
2908
|
+
const url = new URL(session.url);
|
|
2909
|
+
if (url.protocol !== "https:" || url.username || url.password)
|
|
2910
|
+
throw new Error("Invalid hosted portal URL.");
|
|
2911
|
+
return ctx.json({ url: url.href });
|
|
2912
|
+
} catch (err) {
|
|
2913
|
+
toAPIError("StreamPay createPortalSession failed.", err, getLogger(ctx));
|
|
2914
|
+
}
|
|
2915
|
+
}
|
|
2916
|
+
),
|
|
2737
2917
|
state: api.createAuthEndpoint(
|
|
2738
2918
|
"/consumer/state",
|
|
2739
2919
|
{ method: "GET", use: [api.sessionMiddleware] },
|
|
2740
2920
|
async (ctx) => {
|
|
2741
2921
|
const user = asSessionUser(ctx.context.session?.user);
|
|
2742
|
-
const consumerId = await getConsumerIdOrNull(client, user);
|
|
2743
|
-
if (!consumerId) return ctx.json({ hasConsumer: false, consumer: null });
|
|
2744
2922
|
try {
|
|
2923
|
+
const consumerId = await getConsumerIdOrNull(client, user);
|
|
2924
|
+
if (!consumerId) return ctx.json({ hasConsumer: false, consumer: null });
|
|
2745
2925
|
const consumer = await client.getConsumer(consumerId);
|
|
2746
2926
|
return ctx.json({ hasConsumer: true, consumer });
|
|
2747
2927
|
} catch (err) {
|
|
@@ -2751,18 +2931,22 @@ var portal = ({ pageSize } = {}) => (options) => {
|
|
|
2751
2931
|
),
|
|
2752
2932
|
subscriptions: api.createAuthEndpoint(
|
|
2753
2933
|
"/consumer/subscriptions/list",
|
|
2754
|
-
{ method: "GET", use: [api.sessionMiddleware] },
|
|
2934
|
+
{ method: "GET", use: [api.sessionMiddleware], query: paginationQuery },
|
|
2755
2935
|
async (ctx) => {
|
|
2756
2936
|
const user = asSessionUser(ctx.context.session?.user);
|
|
2757
|
-
const consumerId = await getConsumerIdOrNull(client, user);
|
|
2758
|
-
if (!consumerId) return ctx.json({ hasConsumer: false, data: [] });
|
|
2759
2937
|
try {
|
|
2938
|
+
const consumerId = await getConsumerIdOrNull(client, user);
|
|
2939
|
+
if (!consumerId) return ctx.json({ hasConsumer: false, data: [] });
|
|
2760
2940
|
const response = await client.listSubscriptions({
|
|
2761
2941
|
organization_consumer_id: consumerId,
|
|
2762
|
-
page: 1,
|
|
2763
|
-
size
|
|
2942
|
+
page: ctx.query?.page ?? 1,
|
|
2943
|
+
limit: ctx.query?.size ?? size
|
|
2944
|
+
});
|
|
2945
|
+
return ctx.json({
|
|
2946
|
+
hasConsumer: true,
|
|
2947
|
+
data: response.data ?? [],
|
|
2948
|
+
pagination: response.pagination
|
|
2764
2949
|
});
|
|
2765
|
-
return ctx.json({ hasConsumer: true, data: response.data ?? [] });
|
|
2766
2950
|
} catch (err) {
|
|
2767
2951
|
toAPIError("StreamPay listSubscriptions failed.", err, getLogger(ctx));
|
|
2768
2952
|
}
|
|
@@ -2770,18 +2954,22 @@ var portal = ({ pageSize } = {}) => (options) => {
|
|
|
2770
2954
|
),
|
|
2771
2955
|
invoices: api.createAuthEndpoint(
|
|
2772
2956
|
"/consumer/invoices/list",
|
|
2773
|
-
{ method: "GET", use: [api.sessionMiddleware] },
|
|
2957
|
+
{ method: "GET", use: [api.sessionMiddleware], query: paginationQuery },
|
|
2774
2958
|
async (ctx) => {
|
|
2775
2959
|
const user = asSessionUser(ctx.context.session?.user);
|
|
2776
|
-
const consumerId = await getConsumerIdOrNull(client, user);
|
|
2777
|
-
if (!consumerId) return ctx.json({ hasConsumer: false, data: [] });
|
|
2778
2960
|
try {
|
|
2961
|
+
const consumerId = await getConsumerIdOrNull(client, user);
|
|
2962
|
+
if (!consumerId) return ctx.json({ hasConsumer: false, data: [] });
|
|
2779
2963
|
const response = await client.listInvoices({
|
|
2780
2964
|
organization_consumer_id: consumerId,
|
|
2781
|
-
page: 1,
|
|
2782
|
-
size
|
|
2965
|
+
page: ctx.query?.page ?? 1,
|
|
2966
|
+
limit: ctx.query?.size ?? size
|
|
2967
|
+
});
|
|
2968
|
+
return ctx.json({
|
|
2969
|
+
hasConsumer: true,
|
|
2970
|
+
data: response.data ?? [],
|
|
2971
|
+
pagination: response.pagination
|
|
2783
2972
|
});
|
|
2784
|
-
return ctx.json({ hasConsumer: true, data: response.data ?? [] });
|
|
2785
2973
|
} catch (err) {
|
|
2786
2974
|
toAPIError("StreamPay listInvoices failed.", err, getLogger(ctx));
|
|
2787
2975
|
}
|
|
@@ -2799,6 +2987,7 @@ var STREAMPAY_EVENT_ENTITY_TYPES = {
|
|
|
2799
2987
|
PAYMENT_FAILED: "PAYMENT",
|
|
2800
2988
|
PAYMENT_CANCELED: "PAYMENT",
|
|
2801
2989
|
PAYMENT_REFUNDED: "PAYMENT",
|
|
2990
|
+
PAYMENT_PARTIALLY_REFUNDED: "PAYMENT",
|
|
2802
2991
|
PAYMENT_MARKED_AS_PAID: "PAYMENT",
|
|
2803
2992
|
INVOICE_CREATED: "INVOICE",
|
|
2804
2993
|
INVOICE_SENT: "INVOICE",
|
|
@@ -2813,6 +3002,7 @@ var STREAMPAY_EVENT_ENTITY_TYPES = {
|
|
|
2813
3002
|
SUBSCRIPTION_CANCELED: "SUBSCRIPTION",
|
|
2814
3003
|
SUBSCRIPTION_FROZEN: "SUBSCRIPTION",
|
|
2815
3004
|
SUBSCRIPTION_CYCLE_RENEWAL_FAILED: "SUBSCRIPTION",
|
|
3005
|
+
SUBSCRIPTION_CYCLE_RENEWED_SUCCESSFULLY: "SUBSCRIPTION",
|
|
2816
3006
|
SUBSCRIPTION_CANCEL_AT_PERIOD_END: "SUBSCRIPTION",
|
|
2817
3007
|
SUBSCRIPTION_FREEZE_NOW: "SUBSCRIPTION",
|
|
2818
3008
|
SUBSCRIPTION_UNFREEZE_NOW: "SUBSCRIPTION",
|
|
@@ -2960,7 +3150,10 @@ async function deleteReservedSubscription(adapter, rowId, log, reason) {
|
|
|
2960
3150
|
try {
|
|
2961
3151
|
await adapter.delete({
|
|
2962
3152
|
model: SUBSCRIPTION_MODEL4,
|
|
2963
|
-
where: [
|
|
3153
|
+
where: [
|
|
3154
|
+
{ field: "id", value: rowId },
|
|
3155
|
+
{ field: "status", value: "incomplete" }
|
|
3156
|
+
]
|
|
2964
3157
|
});
|
|
2965
3158
|
} catch (err) {
|
|
2966
3159
|
const message = err instanceof Error ? err.message : String(err);
|
|
@@ -2996,11 +3189,15 @@ async function resumeOrReserveCheckoutSlot(args) {
|
|
|
2996
3189
|
if (recovery.kind === "recovered") {
|
|
2997
3190
|
return { kind: "recovered", row: reuseCandidate, url: recovery.url };
|
|
2998
3191
|
}
|
|
2999
|
-
await adapter.update({
|
|
3192
|
+
const released = await adapter.update({
|
|
3000
3193
|
model: SUBSCRIPTION_MODEL4,
|
|
3001
3194
|
update: { status: "incomplete_expired", activeSlotKey: null, updatedAt: /* @__PURE__ */ new Date() },
|
|
3002
|
-
where: [
|
|
3195
|
+
where: [
|
|
3196
|
+
{ field: "id", value: reuseCandidate.id },
|
|
3197
|
+
{ field: "status", value: "incomplete" }
|
|
3198
|
+
]
|
|
3003
3199
|
});
|
|
3200
|
+
if (!released) throw checkoutInProgressError();
|
|
3004
3201
|
}
|
|
3005
3202
|
const { data: reservationData, consumerId } = await args.createReservation();
|
|
3006
3203
|
let row;
|
|
@@ -3041,6 +3238,7 @@ async function resumeOrReserveCheckoutSlot(args) {
|
|
|
3041
3238
|
update: { status: "incomplete_expired", activeSlotKey: null, updatedAt: /* @__PURE__ */ new Date() },
|
|
3042
3239
|
where: [
|
|
3043
3240
|
{ field: "id", value: reserved.id },
|
|
3241
|
+
{ field: "status", value: "incomplete" },
|
|
3044
3242
|
{ field: "activeSlotKey", value: activeSlotKey }
|
|
3045
3243
|
]
|
|
3046
3244
|
});
|
|
@@ -3120,6 +3318,43 @@ function configuredPlanForSubscription(subscription, plans) {
|
|
|
3120
3318
|
}
|
|
3121
3319
|
return matches[0];
|
|
3122
3320
|
}
|
|
3321
|
+
async function findSubscriptionFreeze(client, options, subscriptionId, matches) {
|
|
3322
|
+
const listPage = options.listSubscriptionFreezes;
|
|
3323
|
+
if (!listPage) {
|
|
3324
|
+
const response = await client.listSubscriptionFreezes(subscriptionId);
|
|
3325
|
+
return {
|
|
3326
|
+
freeze: response.data?.find(matches),
|
|
3327
|
+
hasMore: response.pagination?.has_next_page ?? false
|
|
3328
|
+
};
|
|
3329
|
+
}
|
|
3330
|
+
const seenIds = /* @__PURE__ */ new Set();
|
|
3331
|
+
for (let page = 1; page <= 100; page++) {
|
|
3332
|
+
const response = await listPage(subscriptionId, { page, limit: 100 });
|
|
3333
|
+
const pagination = response.pagination;
|
|
3334
|
+
if (!Array.isArray(response.data) || !pagination || pagination.current_page !== page || typeof pagination.has_next_page !== "boolean") {
|
|
3335
|
+
throw freezePaginationConflict("StreamPay returned invalid freeze pagination.");
|
|
3336
|
+
}
|
|
3337
|
+
let advanced = false;
|
|
3338
|
+
for (const freeze2 of response.data) {
|
|
3339
|
+
if (freeze2.id && !seenIds.has(freeze2.id)) {
|
|
3340
|
+
seenIds.add(freeze2.id);
|
|
3341
|
+
advanced = true;
|
|
3342
|
+
}
|
|
3343
|
+
}
|
|
3344
|
+
if (!advanced && (pagination.has_next_page || response.data.length > 0)) {
|
|
3345
|
+
throw freezePaginationConflict("StreamPay freeze pagination returned no new entries.");
|
|
3346
|
+
}
|
|
3347
|
+
const freeze = response.data.find(matches);
|
|
3348
|
+
if (freeze || !pagination.has_next_page) return { freeze, hasMore: false };
|
|
3349
|
+
}
|
|
3350
|
+
throw freezePaginationConflict("StreamPay freeze pagination exceeded 100 pages.");
|
|
3351
|
+
}
|
|
3352
|
+
function freezePaginationConflict(message) {
|
|
3353
|
+
return new api.APIError("CONFLICT", {
|
|
3354
|
+
code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
|
|
3355
|
+
message
|
|
3356
|
+
});
|
|
3357
|
+
}
|
|
3123
3358
|
var SUBSCRIPTION_INTERVALS = ["WEEK", "MONTH", "QUARTER", "YEAR"];
|
|
3124
3359
|
var PlanSchema = zod.z.object({
|
|
3125
3360
|
name: zod.z.string().min(1, "every plan must have a non-empty `name`."),
|
|
@@ -3218,29 +3453,13 @@ function buildIndex(list) {
|
|
|
3218
3453
|
for (const plan of list) byName.set(plan.name, plan);
|
|
3219
3454
|
return { list, byName };
|
|
3220
3455
|
}
|
|
3221
|
-
function
|
|
3222
|
-
|
|
3223
|
-
|
|
3224
|
-
return
|
|
3225
|
-
if (cached) return cached;
|
|
3226
|
-
if (inFlight) return inFlight;
|
|
3227
|
-
if (!plans) throw new TypeError("subscriptions(): `plans` is required.");
|
|
3228
|
-
inFlight = (async () => {
|
|
3229
|
-
const list = typeof plans === "function" ? await plans() : plans;
|
|
3230
|
-
validatePlansShape(list);
|
|
3231
|
-
const resolved = buildIndex(list);
|
|
3232
|
-
cached = resolved;
|
|
3233
|
-
return resolved;
|
|
3234
|
-
})();
|
|
3235
|
-
try {
|
|
3236
|
-
return await inFlight;
|
|
3237
|
-
} finally {
|
|
3238
|
-
inFlight = null;
|
|
3239
|
-
}
|
|
3240
|
-
};
|
|
3456
|
+
async function resolvePlans(plans) {
|
|
3457
|
+
const list = typeof plans === "function" ? await plans() : plans;
|
|
3458
|
+
validatePlansShape(list);
|
|
3459
|
+
return buildIndex(list);
|
|
3241
3460
|
}
|
|
3242
3461
|
function hasSubscriptionAccess(subscription, accessStatuses = DEFAULT_ACCESS_STATUSES) {
|
|
3243
|
-
return accessStatuses.includes(subscription.status);
|
|
3462
|
+
return subscription.catalogMapped !== false && accessStatuses.includes(subscription.status);
|
|
3244
3463
|
}
|
|
3245
3464
|
function hasFeature(subscription, plan, feature, accessStatuses = DEFAULT_ACCESS_STATUSES) {
|
|
3246
3465
|
if (!plan?.limits) return false;
|
|
@@ -3256,9 +3475,11 @@ function checkLimit(subscription, plan, feature, requested, accessStatuses = DEF
|
|
|
3256
3475
|
}
|
|
3257
3476
|
const raw = plan.limits[feature];
|
|
3258
3477
|
const limit = typeof raw === "number" && Number.isFinite(raw) ? raw : 0;
|
|
3259
|
-
|
|
3260
|
-
|
|
3261
|
-
|
|
3478
|
+
if (!Number.isSafeInteger(requested) || requested < 0) {
|
|
3479
|
+
return { allowed: false, limit, remaining: 0 };
|
|
3480
|
+
}
|
|
3481
|
+
const allowed = requested <= limit;
|
|
3482
|
+
const remaining = Math.max(0, limit - requested);
|
|
3262
3483
|
return { allowed, limit, remaining };
|
|
3263
3484
|
}
|
|
3264
3485
|
|
|
@@ -3281,7 +3502,7 @@ var HasFeatureQuery = zod.z.object({
|
|
|
3281
3502
|
var CheckLimitQuery = zod.z.object({
|
|
3282
3503
|
...ReferenceQueryFields,
|
|
3283
3504
|
feature: zod.z.string().min(1),
|
|
3284
|
-
count: zod.z.coerce.number().int().min(0),
|
|
3505
|
+
count: zod.z.coerce.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
|
|
3285
3506
|
group: zod.z.string().min(1).optional()
|
|
3286
3507
|
});
|
|
3287
3508
|
function presentSubscription(row, plans) {
|
|
@@ -3290,7 +3511,7 @@ function presentSubscription(row, plans) {
|
|
|
3290
3511
|
// The column is nullable during safe rolling migrations. Keep the public
|
|
3291
3512
|
// contract stable while applications backfill legacy rows to one seat.
|
|
3292
3513
|
seats: row.seats ?? 1,
|
|
3293
|
-
plan: plans.byName.get(row.plan) ?? null
|
|
3514
|
+
plan: row.catalogMapped === false ? null : plans.byName.get(row.plan) ?? null
|
|
3294
3515
|
};
|
|
3295
3516
|
}
|
|
3296
3517
|
async function resolveLiveSubscription(ctx, query, subsOptions, accessStatuses) {
|
|
@@ -3473,8 +3694,8 @@ var UpdateSeatsBody = zod.z.object({
|
|
|
3473
3694
|
}).strict();
|
|
3474
3695
|
var FreezeBody = zod.z.object({
|
|
3475
3696
|
subscriptionId: zod.z.string().min(1),
|
|
3476
|
-
freezeStartDatetime: zod.z.string().datetime(),
|
|
3477
|
-
freezeEndDatetime: zod.z.string().datetime().nullable().optional(),
|
|
3697
|
+
freezeStartDatetime: zod.z.string().datetime({ offset: true }),
|
|
3698
|
+
freezeEndDatetime: zod.z.string().datetime({ offset: true }).nullable().optional(),
|
|
3478
3699
|
notes: zod.z.string().optional()
|
|
3479
3700
|
});
|
|
3480
3701
|
var UnfreezeBody = zod.z.object({
|
|
@@ -3522,9 +3743,10 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
3522
3743
|
const plans = await plansRef();
|
|
3523
3744
|
const current = await client.getSubscription(row.streampaySubscriptionId);
|
|
3524
3745
|
if (!current.pending_change) {
|
|
3525
|
-
await
|
|
3526
|
-
|
|
3527
|
-
|
|
3746
|
+
await persistSubscriptionProjection(
|
|
3747
|
+
adapter,
|
|
3748
|
+
row,
|
|
3749
|
+
{
|
|
3528
3750
|
...projectSubscriptionAgainstExisting(row, current),
|
|
3529
3751
|
...projectPlanFields(current, plans),
|
|
3530
3752
|
pendingPlan: null,
|
|
@@ -3533,15 +3755,17 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
3533
3755
|
pendingSeats: null,
|
|
3534
3756
|
pendingSeatsEffectiveAt: null
|
|
3535
3757
|
},
|
|
3536
|
-
|
|
3537
|
-
|
|
3758
|
+
getLogger(ctx),
|
|
3759
|
+
"subscription endpoint"
|
|
3760
|
+
);
|
|
3538
3761
|
return ctx.json({ canceled: true, reused: true, subscription: current });
|
|
3539
3762
|
}
|
|
3540
3763
|
await client.deletePendingSubscriptionChange(row.streampaySubscriptionId);
|
|
3541
3764
|
const stream = await client.getSubscription(row.streampaySubscriptionId);
|
|
3542
|
-
await
|
|
3543
|
-
|
|
3544
|
-
|
|
3765
|
+
await persistSubscriptionProjection(
|
|
3766
|
+
adapter,
|
|
3767
|
+
row,
|
|
3768
|
+
{
|
|
3545
3769
|
...projectSubscriptionAgainstExisting(row, stream),
|
|
3546
3770
|
...projectPlanFields(stream, plans),
|
|
3547
3771
|
pendingPlan: null,
|
|
@@ -3550,8 +3774,9 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
3550
3774
|
pendingSeats: null,
|
|
3551
3775
|
pendingSeatsEffectiveAt: null
|
|
3552
3776
|
},
|
|
3553
|
-
|
|
3554
|
-
|
|
3777
|
+
getLogger(ctx),
|
|
3778
|
+
"subscription endpoint"
|
|
3779
|
+
);
|
|
3555
3780
|
return ctx.json({ canceled: true, reused: false, subscription: stream });
|
|
3556
3781
|
} catch (err) {
|
|
3557
3782
|
toAPIError(
|
|
@@ -3750,7 +3975,11 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
3750
3975
|
activeSlotKey: null,
|
|
3751
3976
|
updatedAt: /* @__PURE__ */ new Date()
|
|
3752
3977
|
},
|
|
3753
|
-
where: [
|
|
3978
|
+
where: [
|
|
3979
|
+
{ field: "id", value: row.id },
|
|
3980
|
+
{ field: "status", value: "incomplete" },
|
|
3981
|
+
{ field: "streampayConsumerId", value: consumerId }
|
|
3982
|
+
]
|
|
3754
3983
|
});
|
|
3755
3984
|
} catch (persistenceError) {
|
|
3756
3985
|
const message = persistenceError instanceof Error ? persistenceError.message : String(persistenceError);
|
|
@@ -3776,7 +4005,13 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
3776
4005
|
streampayPaymentLinkId: paymentLinkId,
|
|
3777
4006
|
updatedAt: /* @__PURE__ */ new Date()
|
|
3778
4007
|
},
|
|
3779
|
-
where: [
|
|
4008
|
+
where: [
|
|
4009
|
+
{ field: "id", value: row.id },
|
|
4010
|
+
{ field: "referenceId", value: referenceId },
|
|
4011
|
+
{ field: "referenceType", value: referenceType },
|
|
4012
|
+
{ field: "streampayConsumerId", value: consumerId },
|
|
4013
|
+
{ field: "streampayPaymentLinkId", value: null }
|
|
4014
|
+
]
|
|
3780
4015
|
});
|
|
3781
4016
|
} catch (persistenceError) {
|
|
3782
4017
|
const message = persistenceError instanceof Error ? persistenceError.message : String(persistenceError);
|
|
@@ -3858,10 +4093,11 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
3858
4093
|
if (!match?.id) {
|
|
3859
4094
|
return ctx.json({ subscription: row, synced: false });
|
|
3860
4095
|
}
|
|
3861
|
-
const updated = await
|
|
3862
|
-
|
|
3863
|
-
|
|
3864
|
-
|
|
4096
|
+
const updated = await persistSubscriptionProjection(
|
|
4097
|
+
adapter,
|
|
4098
|
+
row,
|
|
4099
|
+
{
|
|
4100
|
+
...projectSubscriptionFields(match, row),
|
|
3865
4101
|
...projectPlanFields(match, plans),
|
|
3866
4102
|
planVersion: plan.version ?? null,
|
|
3867
4103
|
productId: plan.productId,
|
|
@@ -3869,9 +4105,10 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
3869
4105
|
activeSlotKey: row.activeSlotKey ?? subscriptionSlotKey(row.referenceType ?? "user", row.referenceId, row.group),
|
|
3870
4106
|
updatedAt: /* @__PURE__ */ new Date()
|
|
3871
4107
|
},
|
|
3872
|
-
|
|
3873
|
-
|
|
3874
|
-
|
|
4108
|
+
getLogger(ctx),
|
|
4109
|
+
"subscription endpoint"
|
|
4110
|
+
);
|
|
4111
|
+
return ctx.json({ subscription: updated, synced: updated !== null });
|
|
3875
4112
|
} catch (err) {
|
|
3876
4113
|
toAPIError(
|
|
3877
4114
|
`subscriptionSuccess fallback sync failed for row=${row.id}:`,
|
|
@@ -3901,11 +4138,13 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
3901
4138
|
try {
|
|
3902
4139
|
const stream = await client.getSubscription(row.streampaySubscriptionId);
|
|
3903
4140
|
if (stream.status === "CANCELED") {
|
|
3904
|
-
await
|
|
3905
|
-
|
|
3906
|
-
|
|
3907
|
-
|
|
3908
|
-
|
|
4141
|
+
await persistSubscriptionProjection(
|
|
4142
|
+
adapter,
|
|
4143
|
+
row,
|
|
4144
|
+
projectSubscriptionAgainstExisting(row, stream),
|
|
4145
|
+
getLogger(ctx),
|
|
4146
|
+
"subscription endpoint"
|
|
4147
|
+
);
|
|
3909
4148
|
return ctx.json(stream);
|
|
3910
4149
|
}
|
|
3911
4150
|
if (ctx.body.cancelAtPeriodEnd === false && stream.status === "ACTIVE") {
|
|
@@ -3915,11 +4154,13 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
3915
4154
|
});
|
|
3916
4155
|
}
|
|
3917
4156
|
if (stream.cancel_at_period_end && !ctx.body.cancelRelatedInvoices) {
|
|
3918
|
-
await
|
|
3919
|
-
|
|
3920
|
-
|
|
3921
|
-
|
|
3922
|
-
|
|
4157
|
+
await persistSubscriptionProjection(
|
|
4158
|
+
adapter,
|
|
4159
|
+
row,
|
|
4160
|
+
projectSubscriptionAgainstExisting(row, stream),
|
|
4161
|
+
getLogger(ctx),
|
|
4162
|
+
"subscription endpoint"
|
|
4163
|
+
);
|
|
3923
4164
|
return ctx.json(stream);
|
|
3924
4165
|
}
|
|
3925
4166
|
if (ctx.body.cancelAtPeriodEnd === true && stream.status !== "ACTIVE") {
|
|
@@ -4013,9 +4254,10 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
4013
4254
|
const pendingTargetMatches = Boolean(pendingTarget) && (subscriptionItemQuantity(pendingTarget) ?? 1) === nextSeats;
|
|
4014
4255
|
if (pendingTargetMatches) {
|
|
4015
4256
|
const effectiveAt2 = stream.pending_change?.effective_at ?? null;
|
|
4016
|
-
await
|
|
4017
|
-
|
|
4018
|
-
|
|
4257
|
+
await persistSubscriptionProjection(
|
|
4258
|
+
adapter,
|
|
4259
|
+
row,
|
|
4260
|
+
{
|
|
4019
4261
|
...projectSubscriptionAgainstExisting(row, stream),
|
|
4020
4262
|
...projectPlanFields(stream, plans),
|
|
4021
4263
|
pendingPlan: currentPlan.productId === nextPlan.productId ? null : nextPlan.name,
|
|
@@ -4024,8 +4266,9 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
4024
4266
|
pendingSeats: nextSeats,
|
|
4025
4267
|
pendingSeatsEffectiveAt: parseDate(effectiveAt2)
|
|
4026
4268
|
},
|
|
4027
|
-
|
|
4028
|
-
|
|
4269
|
+
getLogger(ctx),
|
|
4270
|
+
"subscription endpoint"
|
|
4271
|
+
);
|
|
4029
4272
|
return ctx.json({
|
|
4030
4273
|
mode: "at_period_end",
|
|
4031
4274
|
subscriptionId: row.id,
|
|
@@ -4057,15 +4300,17 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
4057
4300
|
const pending = Boolean(result.pending_change);
|
|
4058
4301
|
const effectiveAt = result.pending_change?.effective_at ?? null;
|
|
4059
4302
|
const planProjection = projectPlanFields(result, plans);
|
|
4060
|
-
await
|
|
4061
|
-
|
|
4062
|
-
|
|
4303
|
+
await persistSubscriptionProjection(
|
|
4304
|
+
adapter,
|
|
4305
|
+
row,
|
|
4306
|
+
{
|
|
4063
4307
|
...projectSubscriptionAgainstExisting(row, result),
|
|
4064
4308
|
...planProjection,
|
|
4065
4309
|
updatedAt: /* @__PURE__ */ new Date()
|
|
4066
4310
|
},
|
|
4067
|
-
|
|
4068
|
-
|
|
4311
|
+
getLogger(ctx),
|
|
4312
|
+
"subscription endpoint"
|
|
4313
|
+
);
|
|
4069
4314
|
const providerPlan = pending ? planProjection.pendingPlan ?? planProjection.plan ?? row.plan : planProjection.plan ?? row.plan;
|
|
4070
4315
|
const providerSeats = pending ? planProjection.pendingSeats ?? nextSeats : planProjection.seats ?? row.seats ?? nextSeats;
|
|
4071
4316
|
return ctx.json({
|
|
@@ -4131,14 +4376,16 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
4131
4376
|
if (stream.pending_change) {
|
|
4132
4377
|
if (pendingTarget && (subscriptionItemQuantity(pendingTarget) ?? 1) === seats) {
|
|
4133
4378
|
const effectiveAt2 = stream.pending_change.effective_at ?? null;
|
|
4134
|
-
await
|
|
4135
|
-
|
|
4136
|
-
|
|
4379
|
+
await persistSubscriptionProjection(
|
|
4380
|
+
adapter,
|
|
4381
|
+
row,
|
|
4382
|
+
{
|
|
4137
4383
|
...projectSubscriptionAgainstExisting(row, stream),
|
|
4138
4384
|
...projectPlanFields(stream, plans)
|
|
4139
4385
|
},
|
|
4140
|
-
|
|
4141
|
-
|
|
4386
|
+
getLogger(ctx),
|
|
4387
|
+
"subscription endpoint"
|
|
4388
|
+
);
|
|
4142
4389
|
return ctx.json({
|
|
4143
4390
|
mode: "at_period_end",
|
|
4144
4391
|
subscriptionId: row.id,
|
|
@@ -4154,14 +4401,16 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
4154
4401
|
});
|
|
4155
4402
|
}
|
|
4156
4403
|
if (currentSeats === seats) {
|
|
4157
|
-
await
|
|
4158
|
-
|
|
4159
|
-
|
|
4404
|
+
await persistSubscriptionProjection(
|
|
4405
|
+
adapter,
|
|
4406
|
+
row,
|
|
4407
|
+
{
|
|
4160
4408
|
...projectSubscriptionAgainstExisting(row, stream),
|
|
4161
4409
|
...projectPlanFields(stream, plans)
|
|
4162
4410
|
},
|
|
4163
|
-
|
|
4164
|
-
|
|
4411
|
+
getLogger(ctx),
|
|
4412
|
+
"subscription endpoint"
|
|
4413
|
+
);
|
|
4165
4414
|
return ctx.json({
|
|
4166
4415
|
mode: "current",
|
|
4167
4416
|
subscriptionId: row.id,
|
|
@@ -4179,15 +4428,17 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
4179
4428
|
const pending = Boolean(result.pending_change);
|
|
4180
4429
|
const effectiveAt = result.pending_change?.effective_at ?? null;
|
|
4181
4430
|
const planProjection = projectPlanFields(result, plans);
|
|
4182
|
-
await
|
|
4183
|
-
|
|
4184
|
-
|
|
4431
|
+
await persistSubscriptionProjection(
|
|
4432
|
+
adapter,
|
|
4433
|
+
row,
|
|
4434
|
+
{
|
|
4185
4435
|
...projectSubscriptionAgainstExisting(row, result),
|
|
4186
4436
|
...planProjection,
|
|
4187
4437
|
updatedAt: /* @__PURE__ */ new Date()
|
|
4188
4438
|
},
|
|
4189
|
-
|
|
4190
|
-
|
|
4439
|
+
getLogger(ctx),
|
|
4440
|
+
"subscription endpoint"
|
|
4441
|
+
);
|
|
4191
4442
|
const providerSeats = pending ? planProjection.pendingSeats ?? seats : planProjection.seats ?? row.seats ?? seats;
|
|
4192
4443
|
return ctx.json({
|
|
4193
4444
|
mode: pending ? "at_period_end" : "immediate",
|
|
@@ -4231,11 +4482,13 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
4231
4482
|
try {
|
|
4232
4483
|
await client.uncancelSubscription(row.streampaySubscriptionId);
|
|
4233
4484
|
const stream = await client.getSubscription(row.streampaySubscriptionId);
|
|
4234
|
-
await
|
|
4235
|
-
|
|
4236
|
-
|
|
4237
|
-
|
|
4238
|
-
|
|
4485
|
+
await persistSubscriptionProjection(
|
|
4486
|
+
adapter,
|
|
4487
|
+
row,
|
|
4488
|
+
projectSubscriptionAgainstExisting(row, stream),
|
|
4489
|
+
getLogger(ctx),
|
|
4490
|
+
"subscription endpoint"
|
|
4491
|
+
);
|
|
4239
4492
|
return ctx.json({ uncanceled: true, subscription: stream });
|
|
4240
4493
|
} catch (err) {
|
|
4241
4494
|
toAPIError(
|
|
@@ -4310,13 +4563,30 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
4310
4563
|
);
|
|
4311
4564
|
const nowMs = Date.now();
|
|
4312
4565
|
try {
|
|
4313
|
-
const
|
|
4314
|
-
const active = freezes.data?.find((freeze) => {
|
|
4566
|
+
const isActiveFreeze = (freeze) => {
|
|
4315
4567
|
if (!freeze.id || !freeze.freeze_start_datetime) return false;
|
|
4316
4568
|
const start = parseDate(freeze.freeze_start_datetime)?.getTime();
|
|
4317
4569
|
const end = freeze.freeze_end_datetime ? parseDate(freeze.freeze_end_datetime)?.getTime() : Number.POSITIVE_INFINITY;
|
|
4318
|
-
return start !== void 0 && end !== void 0 && start <= nowMs && nowMs
|
|
4319
|
-
}
|
|
4570
|
+
return start !== void 0 && end !== void 0 && start <= nowMs && nowMs < end;
|
|
4571
|
+
};
|
|
4572
|
+
const result = await findSubscriptionFreeze(
|
|
4573
|
+
client,
|
|
4574
|
+
subsOptions,
|
|
4575
|
+
row.streampaySubscriptionId,
|
|
4576
|
+
isActiveFreeze
|
|
4577
|
+
);
|
|
4578
|
+
let active = result.freeze;
|
|
4579
|
+
if (!active && result.hasMore) {
|
|
4580
|
+
const stream = await client.getSubscription(row.streampaySubscriptionId);
|
|
4581
|
+
if (stream.status === "FROZEN" && stream.latest_freeze && isActiveFreeze(stream.latest_freeze)) {
|
|
4582
|
+
active = stream.latest_freeze;
|
|
4583
|
+
} else {
|
|
4584
|
+
throw new api.APIError("CONFLICT", {
|
|
4585
|
+
code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
|
|
4586
|
+
message: "StreamPay returned more freeze pages than the SDK can read. Unable to verify the active freeze."
|
|
4587
|
+
});
|
|
4588
|
+
}
|
|
4589
|
+
}
|
|
4320
4590
|
if (!active?.id || !active.freeze_start_datetime) {
|
|
4321
4591
|
throw new api.APIError("BAD_REQUEST", {
|
|
4322
4592
|
code: $ERROR_CODES.SUBSCRIPTION_FREEZE_NOT_ACTIVE.code,
|
|
@@ -4363,8 +4633,19 @@ function buildSubscriptionEndpoints(options, subsOptions, plansRef) {
|
|
|
4363
4633
|
"cancel-freeze"
|
|
4364
4634
|
);
|
|
4365
4635
|
try {
|
|
4366
|
-
const
|
|
4367
|
-
|
|
4636
|
+
const result = await findSubscriptionFreeze(
|
|
4637
|
+
client,
|
|
4638
|
+
subsOptions,
|
|
4639
|
+
row.streampaySubscriptionId,
|
|
4640
|
+
(freeze) => freeze.id === ctx.body.freezeId
|
|
4641
|
+
);
|
|
4642
|
+
if (!result.freeze) {
|
|
4643
|
+
if (result.hasMore) {
|
|
4644
|
+
throw new api.APIError("CONFLICT", {
|
|
4645
|
+
code: $ERROR_CODES.SUBSCRIPTION_INVALID_STATE.code,
|
|
4646
|
+
message: "StreamPay returned more freeze pages than the SDK can read. Unable to verify whether this freeze was canceled."
|
|
4647
|
+
});
|
|
4648
|
+
}
|
|
4368
4649
|
return ctx.json({ canceled: true, freezeId: ctx.body.freezeId, reused: true });
|
|
4369
4650
|
}
|
|
4370
4651
|
await client.deleteSubscriptionFreeze(row.streampaySubscriptionId, ctx.body.freezeId);
|
|
@@ -4441,6 +4722,12 @@ var subscriptionTable = {
|
|
|
4441
4722
|
type: "string",
|
|
4442
4723
|
required: true
|
|
4443
4724
|
},
|
|
4725
|
+
catalogMapped: {
|
|
4726
|
+
type: "boolean",
|
|
4727
|
+
required: false,
|
|
4728
|
+
defaultValue: true,
|
|
4729
|
+
input: false
|
|
4730
|
+
},
|
|
4444
4731
|
planVersion: {
|
|
4445
4732
|
type: "string",
|
|
4446
4733
|
required: false
|
|
@@ -4510,6 +4797,11 @@ var subscriptionTable = {
|
|
|
4510
4797
|
type: "number",
|
|
4511
4798
|
required: false
|
|
4512
4799
|
},
|
|
4800
|
+
renewalCallbackEventId: {
|
|
4801
|
+
type: "string",
|
|
4802
|
+
required: false,
|
|
4803
|
+
input: false
|
|
4804
|
+
},
|
|
4513
4805
|
trialStart: {
|
|
4514
4806
|
type: "date",
|
|
4515
4807
|
required: false
|
|
@@ -4690,13 +4982,13 @@ function subscriptions(subsOptions) {
|
|
|
4690
4982
|
}
|
|
4691
4983
|
const dedupeEnabled = subsOptions.enableWebhookEventTable !== false;
|
|
4692
4984
|
return (options, registry) => {
|
|
4693
|
-
const
|
|
4985
|
+
const plansRef = () => resolvePlans(subsOptions.plans);
|
|
4694
4986
|
if (registry) {
|
|
4695
4987
|
registry.subscriptionWebhookSync = async (ctx, payload, meta) => {
|
|
4696
4988
|
const syncCtx = {
|
|
4697
4989
|
context: ctx.context
|
|
4698
4990
|
};
|
|
4699
|
-
const plans = await
|
|
4991
|
+
const plans = await plansRef();
|
|
4700
4992
|
try {
|
|
4701
4993
|
await syncWebhookPayload(syncCtx, payload, options.client, plans, subsOptions, {
|
|
4702
4994
|
dedupe: dedupeEnabled,
|
|
@@ -4720,6 +5012,9 @@ function subscriptions(subsOptions) {
|
|
|
4720
5012
|
};
|
|
4721
5013
|
if (dedupeEnabled) {
|
|
4722
5014
|
registry.replayWebhookEvent = async (ctx, eventId) => {
|
|
5015
|
+
if (eventId.startsWith("handlers:") && registry.replayWebhookHandler) {
|
|
5016
|
+
return registry.replayWebhookHandler(ctx, eventId);
|
|
5017
|
+
}
|
|
4723
5018
|
const syncCtx = {
|
|
4724
5019
|
context: ctx.context
|
|
4725
5020
|
};
|
|
@@ -4752,7 +5047,7 @@ function subscriptions(subsOptions) {
|
|
|
4752
5047
|
});
|
|
4753
5048
|
}
|
|
4754
5049
|
const payload = parsedPayload;
|
|
4755
|
-
const plans = await
|
|
5050
|
+
const plans = await plansRef();
|
|
4756
5051
|
const claimed = await claimWebhookEventForReplay(syncCtx, row);
|
|
4757
5052
|
if (!claimed?.lockedBy) {
|
|
4758
5053
|
throw new api.APIError("CONFLICT", {
|
|
@@ -4789,7 +5084,7 @@ function subscriptions(subsOptions) {
|
|
|
4789
5084
|
...dedupeEnabled ? webhookEventTable : {}
|
|
4790
5085
|
};
|
|
4791
5086
|
return {
|
|
4792
|
-
endpoints: buildSubscriptionEndpoints(options, subsOptions,
|
|
5087
|
+
endpoints: buildSubscriptionEndpoints(options, subsOptions, plansRef),
|
|
4793
5088
|
schema
|
|
4794
5089
|
};
|
|
4795
5090
|
};
|
|
@@ -4812,6 +5107,9 @@ async function dispatchWebhook(payload, handlers) {
|
|
|
4812
5107
|
case "PAYMENT_REFUNDED":
|
|
4813
5108
|
await handlers.onPaymentRefunded?.(payload);
|
|
4814
5109
|
return;
|
|
5110
|
+
case "PAYMENT_PARTIALLY_REFUNDED":
|
|
5111
|
+
await handlers.onPaymentPartiallyRefunded?.(payload);
|
|
5112
|
+
return;
|
|
4815
5113
|
case "PAYMENT_MARKED_AS_PAID":
|
|
4816
5114
|
await handlers.onPaymentMarkedAsPaid?.(payload);
|
|
4817
5115
|
return;
|
|
@@ -4854,6 +5152,9 @@ async function dispatchWebhook(payload, handlers) {
|
|
|
4854
5152
|
case "SUBSCRIPTION_CYCLE_RENEWAL_FAILED":
|
|
4855
5153
|
await handlers.onSubscriptionCycleRenewalFailed?.(payload);
|
|
4856
5154
|
return;
|
|
5155
|
+
case "SUBSCRIPTION_CYCLE_RENEWED_SUCCESSFULLY":
|
|
5156
|
+
await handlers.onSubscriptionCycleRenewedSuccessfully?.(payload);
|
|
5157
|
+
return;
|
|
4857
5158
|
case "SUBSCRIPTION_CANCEL_AT_PERIOD_END":
|
|
4858
5159
|
await handlers.onSubscriptionCancelAtPeriodEnd?.(payload);
|
|
4859
5160
|
return;
|
|
@@ -4962,8 +5263,56 @@ var webhooks = (webhooksOptions) => {
|
|
|
4962
5263
|
throw new TypeError("webhooks(): `toleranceSeconds` must be a non-negative number.");
|
|
4963
5264
|
}
|
|
4964
5265
|
return (_options, registry) => {
|
|
4965
|
-
const { secret, toleranceSeconds, ...handlers } = webhooksOptions;
|
|
5266
|
+
const { secret, toleranceSeconds, deduplicate = false, ...handlers } = webhooksOptions;
|
|
5267
|
+
if (deduplicate && registry) {
|
|
5268
|
+
registry.replayWebhookHandler = async (ctx, eventId) => {
|
|
5269
|
+
const syncContext = { context: ctx.context };
|
|
5270
|
+
const row = await syncContext.context.adapter.findOne({
|
|
5271
|
+
model: WEBHOOK_EVENT_MODEL,
|
|
5272
|
+
where: [{ field: "eventId", value: eventId }]
|
|
5273
|
+
});
|
|
5274
|
+
if (!eventId.startsWith("handlers:") || !row)
|
|
5275
|
+
throw new api.APIError("NOT_FOUND", { message: "Webhook callback event not found." });
|
|
5276
|
+
if (!row.rawPayload)
|
|
5277
|
+
throw new api.APIError("BAD_REQUEST", { message: "Webhook callback has no stored payload." });
|
|
5278
|
+
let payload;
|
|
5279
|
+
try {
|
|
5280
|
+
payload = JSON.parse(row.rawPayload);
|
|
5281
|
+
} catch {
|
|
5282
|
+
throw new api.APIError("BAD_REQUEST", {
|
|
5283
|
+
message: "Stored webhook payload is not valid JSON."
|
|
5284
|
+
});
|
|
5285
|
+
}
|
|
5286
|
+
if (!isStreamPayWebhookEnvelope(payload))
|
|
5287
|
+
throw new api.APIError("BAD_REQUEST", {
|
|
5288
|
+
message: "Stored webhook payload is not a valid event envelope."
|
|
5289
|
+
});
|
|
5290
|
+
const claimed = await claimWebhookEventForReplay(syncContext, row);
|
|
5291
|
+
if (!claimed?.lockedBy)
|
|
5292
|
+
throw new api.APIError("CONFLICT", {
|
|
5293
|
+
message: "Webhook callback is already being processed."
|
|
5294
|
+
});
|
|
5295
|
+
try {
|
|
5296
|
+
await dispatchWebhook(payload, handlers);
|
|
5297
|
+
await markWebhookEventCompleted(syncContext, claimed.id, claimed.lockedBy);
|
|
5298
|
+
} catch (err) {
|
|
5299
|
+
await recordWebhookEventFailure(
|
|
5300
|
+
syncContext,
|
|
5301
|
+
claimed.id,
|
|
5302
|
+
row.rawPayload,
|
|
5303
|
+
row.signatureHeader,
|
|
5304
|
+
err,
|
|
5305
|
+
claimed.lockedBy,
|
|
5306
|
+
true
|
|
5307
|
+
);
|
|
5308
|
+
throw err;
|
|
5309
|
+
}
|
|
5310
|
+
return { replayed: true, eventId };
|
|
5311
|
+
};
|
|
5312
|
+
registry.replayWebhookEvent ??= registry.replayWebhookHandler;
|
|
5313
|
+
}
|
|
4966
5314
|
return {
|
|
5315
|
+
schema: deduplicate ? webhookEventTable : {},
|
|
4967
5316
|
endpoints: {
|
|
4968
5317
|
streampayWebhooks: api.createAuthEndpoint(
|
|
4969
5318
|
"/streampay/webhooks",
|
|
@@ -5023,9 +5372,32 @@ var webhooks = (webhooksOptions) => {
|
|
|
5023
5372
|
});
|
|
5024
5373
|
}
|
|
5025
5374
|
}
|
|
5375
|
+
const syncContext = { context: ctx.context };
|
|
5376
|
+
const claim = deduplicate ? await claimOrAdvanceWebhookEvent(
|
|
5377
|
+
syncContext,
|
|
5378
|
+
payload,
|
|
5379
|
+
rawBody,
|
|
5380
|
+
signatureHeader,
|
|
5381
|
+
DEFAULT_MAX_WEBHOOK_ATTEMPTS,
|
|
5382
|
+
"handlers"
|
|
5383
|
+
) : null;
|
|
5384
|
+
if (claim && claim.action !== "process") return ctx.json({ received: true });
|
|
5385
|
+
const row = claim?.action === "process" ? claim.row : null;
|
|
5026
5386
|
try {
|
|
5027
5387
|
await dispatchWebhook(payload, handlers);
|
|
5388
|
+
if (row)
|
|
5389
|
+
await markWebhookEventCompleted(syncContext, row.id, row.lockedBy ?? void 0);
|
|
5028
5390
|
} catch (err) {
|
|
5391
|
+
if (row)
|
|
5392
|
+
await recordWebhookEventFailure(
|
|
5393
|
+
syncContext,
|
|
5394
|
+
row.id,
|
|
5395
|
+
rawBody,
|
|
5396
|
+
signatureHeader,
|
|
5397
|
+
err,
|
|
5398
|
+
row.lockedBy ?? void 0,
|
|
5399
|
+
row.attemptCount >= DEFAULT_MAX_WEBHOOK_ATTEMPTS
|
|
5400
|
+
);
|
|
5029
5401
|
const message = err instanceof Error ? err.message : String(err);
|
|
5030
5402
|
logger2.error(`webhook handler failed: ${message}`);
|
|
5031
5403
|
throw new api.APIError("INTERNAL_SERVER_ERROR", {
|
|
@@ -5053,11 +5425,12 @@ var onBeforeUserCreate = (options) => async (user, context) => {
|
|
|
5053
5425
|
}
|
|
5054
5426
|
const extras = options.getConsumerCreateParams ? await options.getConsumerCreateParams({ user }) : {};
|
|
5055
5427
|
const createPayload = {
|
|
5056
|
-
name: user.name || user.email,
|
|
5057
|
-
email: user.email,
|
|
5058
5428
|
consumer_type: "INDIVIDUAL",
|
|
5059
|
-
...extras
|
|
5429
|
+
...extras,
|
|
5430
|
+
name: user.name || user.email,
|
|
5431
|
+
email: user.email
|
|
5060
5432
|
};
|
|
5433
|
+
delete createPayload.external_id;
|
|
5061
5434
|
try {
|
|
5062
5435
|
const consumer = await options.client.createConsumer(createPayload);
|
|
5063
5436
|
if (!consumer.id) {
|
|
@@ -5154,7 +5527,7 @@ var onUserDelete = (options) => async (user, context) => {
|
|
|
5154
5527
|
|
|
5155
5528
|
// package.json
|
|
5156
5529
|
var package_default = {
|
|
5157
|
-
version: "
|
|
5530
|
+
version: "3.0.0"};
|
|
5158
5531
|
|
|
5159
5532
|
// src/version.ts
|
|
5160
5533
|
var version = package_default.version;
|