@apexara/stripe 1.0.5 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +465 -28
- package/dist/apex-stripe.d.ts.map +1 -1
- package/dist/apex-stripe.js +10 -8
- package/dist/errors/http-error.d.ts +5 -1
- package/dist/errors/http-error.d.ts.map +1 -1
- package/dist/errors/http-error.js +6 -1
- package/dist/errors/stripe-error-status.d.ts +16 -0
- package/dist/errors/stripe-error-status.d.ts.map +1 -0
- package/dist/errors/stripe-error-status.js +60 -0
- package/dist/models/config.model.d.ts +2 -0
- package/dist/models/config.model.d.ts.map +1 -1
- package/dist/models/stripe.model.d.ts +16 -0
- package/dist/models/stripe.model.d.ts.map +1 -1
- package/dist/models/subscription.model.d.ts +1 -0
- package/dist/models/subscription.model.d.ts.map +1 -1
- package/dist/models/webhook.model.d.ts +16 -0
- package/dist/models/webhook.model.d.ts.map +1 -1
- package/dist/services/checkout/checkout.service.d.ts +8 -5
- package/dist/services/checkout/checkout.service.d.ts.map +1 -1
- package/dist/services/checkout/checkout.service.js +26 -13
- package/dist/services/connected-account/connected-account.service.d.ts +2 -1
- package/dist/services/connected-account/connected-account.service.d.ts.map +1 -1
- package/dist/services/connected-account/connected-account.service.js +4 -3
- package/dist/services/customer/customer.service.d.ts +2 -1
- package/dist/services/customer/customer.service.d.ts.map +1 -1
- package/dist/services/customer/customer.service.js +3 -2
- package/dist/services/invoice/invoice.service.d.ts +27 -3
- package/dist/services/invoice/invoice.service.d.ts.map +1 -1
- package/dist/services/invoice/invoice.service.js +108 -12
- package/dist/services/payment-link/payment-link.service.d.ts +2 -2
- package/dist/services/payment-link/payment-link.service.d.ts.map +1 -1
- package/dist/services/payment-link/payment-link.service.js +5 -4
- package/dist/services/payment-method/payment-method.service.d.ts +5 -4
- package/dist/services/payment-method/payment-method.service.d.ts.map +1 -1
- package/dist/services/payment-method/payment-method.service.js +35 -9
- package/dist/services/price/price.service.d.ts +2 -2
- package/dist/services/price/price.service.d.ts.map +1 -1
- package/dist/services/price/price.service.js +4 -3
- package/dist/services/subscription/subscription.service.d.ts +79 -12
- package/dist/services/subscription/subscription.service.d.ts.map +1 -1
- package/dist/services/subscription/subscription.service.js +337 -49
- package/dist/utils/idempotency.d.ts +29 -0
- package/dist/utils/idempotency.d.ts.map +1 -0
- package/dist/utils/idempotency.js +62 -0
- package/dist/webhooks/report-error.d.ts +7 -0
- package/dist/webhooks/report-error.d.ts.map +1 -0
- package/dist/webhooks/report-error.js +15 -0
- package/dist/webhooks/webhook.dispatcher.d.ts +15 -2
- package/dist/webhooks/webhook.dispatcher.d.ts.map +1 -1
- package/dist/webhooks/webhook.dispatcher.js +52 -9
- package/dist/webhooks/webhook.handler.d.ts +20 -1
- package/dist/webhooks/webhook.handler.d.ts.map +1 -1
- package/dist/webhooks/webhook.handler.js +94 -18
- package/package.json +5 -4
- package/dist/tests/helpers.d.ts +0 -5
- package/dist/tests/helpers.d.ts.map +0 -1
- package/dist/tests/helpers.js +0 -96
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.SubscriptionService = void 0;
|
|
4
4
|
const http_error_1 = require("./../../errors/http-error");
|
|
5
|
+
const idempotency_1 = require("./../../utils/idempotency");
|
|
5
6
|
class SubscriptionService {
|
|
6
7
|
constructor(stripe, config) {
|
|
7
8
|
this.stripe = stripe;
|
|
@@ -15,25 +16,33 @@ class SubscriptionService {
|
|
|
15
16
|
return this.stripe.subscriptions.retrieve(subscriptionId, { expand: ['items.data.price'] });
|
|
16
17
|
}
|
|
17
18
|
/**
|
|
18
|
-
*
|
|
19
|
+
* Retrieves a subscription with its discounts and the promotion codes behind them expanded, the form
|
|
20
|
+
* getSubscriptionDiscount reads. expand adds other fields to expand, each once (e.g. ['latest_invoice']); none by
|
|
21
|
+
* default. A Stripe error, such as no such subscription, is thrown as it is.
|
|
22
|
+
*/
|
|
23
|
+
async getSubscriptionWithDiscounts(subscriptionId, expand = []) {
|
|
24
|
+
return this.stripe.subscriptions.retrieve(subscriptionId, { expand: [...new Set([...SubscriptionService.discountExpands, ...expand])] });
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Lists all subscriptions for a customer across all statuses, reading every page Stripe returns.
|
|
19
28
|
* Returns an empty array if no customerId is provided.
|
|
20
29
|
*/
|
|
21
30
|
async getAllUserSubscriptions(customerId) {
|
|
22
31
|
if (!customerId) {
|
|
23
32
|
return [];
|
|
24
33
|
}
|
|
25
|
-
|
|
34
|
+
return this.stripe.subscriptions.list({
|
|
26
35
|
customer: customerId,
|
|
27
36
|
status: 'all',
|
|
28
37
|
expand: ['data.default_payment_method'],
|
|
29
|
-
|
|
30
|
-
|
|
38
|
+
limit: 100,
|
|
39
|
+
}).autoPagingToArray({ limit: 1000 });
|
|
31
40
|
}
|
|
32
41
|
/**
|
|
33
42
|
* Updates a subscription with arbitrary Stripe params.
|
|
34
43
|
*/
|
|
35
|
-
async updateSubscription(subscriptionId, params) {
|
|
36
|
-
return this.stripe.subscriptions.update(subscriptionId, params);
|
|
44
|
+
async updateSubscription(subscriptionId, params, idempotency) {
|
|
45
|
+
return (0, idempotency_1.withIdempotencyKey)(idempotency, idempotency_1.IdempotencyStep.SubscriptionUpdate, (...requestOptions) => this.stripe.subscriptions.update(subscriptionId, params, ...requestOptions));
|
|
37
46
|
}
|
|
38
47
|
/**
|
|
39
48
|
* Immediately cancels a subscription.
|
|
@@ -43,28 +52,35 @@ class SubscriptionService {
|
|
|
43
52
|
}
|
|
44
53
|
// Subscription lifecycle
|
|
45
54
|
/**
|
|
46
|
-
* Schedules a subscription to cancel at the end of the current billing period.
|
|
47
|
-
*
|
|
55
|
+
* Schedules a subscription to cancel at the end of the current billing period, which for a trial is the trial's end.
|
|
56
|
+
* A schedule attached to it, such as a booked downgrade, is released first, since Stripe refuses the cancel while
|
|
57
|
+
* one is attached. Throws if the subscription is not active, past_due or trialing.
|
|
48
58
|
*/
|
|
49
59
|
async cancelSubscriptionAtPeriodEnd(subscriptionId) {
|
|
50
60
|
const subscription = await this.stripe.subscriptions.retrieve(subscriptionId);
|
|
51
|
-
if (
|
|
61
|
+
if (!SubscriptionService.runningStatuses.includes(subscription.status)) {
|
|
52
62
|
throw new http_error_1.HttpError(400, `Subscription ${subscriptionId} cannot be cancelled (status: ${subscription.status})`);
|
|
53
63
|
}
|
|
64
|
+
await this.releaseAttachedSchedule(subscription);
|
|
54
65
|
return this.stripe.subscriptions.update(subscriptionId, { cancel_at_period_end: true });
|
|
55
66
|
}
|
|
56
67
|
/**
|
|
57
|
-
* Resumes a subscription that has cancel_at_period_end set.
|
|
58
|
-
*
|
|
68
|
+
* Resumes a subscription that has cancel_at_period_end set, or whose attached schedule ends it. That schedule is
|
|
69
|
+
* released first, since Stripe refuses the change while one is attached.
|
|
70
|
+
* Throws if neither is the case or the subscription is not active, past_due or trialing.
|
|
59
71
|
*/
|
|
60
72
|
async resumeSubscription(subscriptionId) {
|
|
61
73
|
const subscription = await this.stripe.subscriptions.retrieve(subscriptionId);
|
|
62
|
-
|
|
63
|
-
|
|
74
|
+
// A schedule that ends the plan holds the cancel itself: the plan shows cancel_at, and cancel_at_period_end false.
|
|
75
|
+
const isEndedBySchedule = Boolean(subscription.schedule) && Boolean(subscription.cancel_at);
|
|
76
|
+
const canResume = (subscription.cancel_at_period_end || isEndedBySchedule) &&
|
|
77
|
+
SubscriptionService.runningStatuses.includes(subscription.status);
|
|
64
78
|
if (!canResume) {
|
|
65
79
|
throw new http_error_1.HttpError(400, `Subscription ${subscriptionId} cannot be resumed (status: ${subscription.status}, cancelAtPeriodEnd: ${subscription.cancel_at_period_end})`);
|
|
66
80
|
}
|
|
67
|
-
|
|
81
|
+
await this.releaseAttachedSchedule(subscription);
|
|
82
|
+
// A release keeps an end date the plan had before its schedule, and only cancel_at clears that one.
|
|
83
|
+
return this.stripe.subscriptions.update(subscriptionId, subscription.cancel_at_period_end ? { cancel_at_period_end: false } : { cancel_at: '' });
|
|
68
84
|
}
|
|
69
85
|
// Subscription schedules
|
|
70
86
|
/**
|
|
@@ -82,17 +98,32 @@ class SubscriptionService {
|
|
|
82
98
|
* and released later by releaseScheduleIfDowngrade.
|
|
83
99
|
*/
|
|
84
100
|
async scheduleDowngrade(subscription, newPriceId, options) {
|
|
101
|
+
const isNewSchedule = !subscription.schedule;
|
|
85
102
|
const schedule = await this.getOrCreateSubscriptionSchedule(subscription);
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
103
|
+
try {
|
|
104
|
+
// A phase reports a discount by its coupon; sending that back makes a new discount, which restarts a
|
|
105
|
+
// limited one and drops its promotion code. Reusing the live discount by id keeps both.
|
|
106
|
+
const live = await this.stripe.subscriptions.retrieve(subscription.id, { expand: ['discounts', 'items.data.discounts'] });
|
|
107
|
+
const phases = await this.buildDowngradePhases(schedule, newPriceId, SubscriptionService.liveDiscountsOf(live), {
|
|
108
|
+
quantity: options?.quantity,
|
|
109
|
+
transferData: options?.transferData,
|
|
110
|
+
phaseMetadata: options?.phaseMetadata,
|
|
111
|
+
discounts: options?.discounts,
|
|
112
|
+
});
|
|
113
|
+
return await this.stripe.subscriptionSchedules.update(schedule.id, {
|
|
114
|
+
end_behavior: 'release',
|
|
115
|
+
metadata: { type: SubscriptionService.phaseTypeDowngrade, ...options?.scheduleMetadata },
|
|
116
|
+
phases,
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
catch (err) {
|
|
120
|
+
// A schedule made here and left half built keeps holding the subscription, and Stripe refuses a cancel
|
|
121
|
+
// while it does; releaseScheduleIfDowngrade cannot find it, as it has no downgrade tag yet.
|
|
122
|
+
if (isNewSchedule) {
|
|
123
|
+
await this.stripe.subscriptionSchedules.release(schedule.id).catch(() => undefined);
|
|
124
|
+
}
|
|
125
|
+
throw err;
|
|
126
|
+
}
|
|
96
127
|
}
|
|
97
128
|
/**
|
|
98
129
|
* Returns the downgrade schedule for a subscription, or null if none exists or it is not tagged as a downgrade.
|
|
@@ -129,35 +160,55 @@ class SubscriptionService {
|
|
|
129
160
|
* Pass a positive amount — it is stored as negative automatically.
|
|
130
161
|
* Call this before switchSubscriptionPlan when managing billing credits manually.
|
|
131
162
|
*/
|
|
132
|
-
async applyPlanCredit(customerId, subscriptionId, amount, currency, description, metadata) {
|
|
133
|
-
await this.stripe.invoiceItems.create({
|
|
163
|
+
async applyPlanCredit(customerId, subscriptionId, amount, currency, description, metadata, idempotency) {
|
|
164
|
+
await (0, idempotency_1.withIdempotencyKey)(idempotency, idempotency_1.IdempotencyStep.PlanCredit, (...requestOptions) => this.stripe.invoiceItems.create({
|
|
134
165
|
customer: customerId,
|
|
135
166
|
subscription: subscriptionId,
|
|
136
167
|
amount: -Math.abs(amount),
|
|
137
168
|
currency,
|
|
138
169
|
description: description ?? 'Plan credit',
|
|
139
170
|
metadata,
|
|
140
|
-
});
|
|
171
|
+
}, ...requestOptions));
|
|
141
172
|
}
|
|
142
173
|
/**
|
|
143
174
|
* Switches a subscription to a new price immediately, resetting the billing cycle anchor to now.
|
|
144
175
|
* Defaults to proration_behavior: 'none' — pair with applyPlanCredit for manual credits,
|
|
145
176
|
* or pass proration: 'create_prorations' to let Stripe calculate what's owed.
|
|
177
|
+
* Throws 402 with the decline reason when the charge fails; the subscription then stays on its old price
|
|
178
|
+
* and the switch's bill is voided.
|
|
179
|
+
* A schedule attached to the subscription, such as a booked downgrade, is released once the switch has gone through,
|
|
180
|
+
* so it cannot move the plan back when the current phase ends. A declined or refused switch leaves it attached.
|
|
181
|
+
* If that release fails, it throws although the plan has switched and been charged. Repeat with the same key to
|
|
182
|
+
* finish the release; a repeat without a key switches and charges again.
|
|
146
183
|
*/
|
|
147
|
-
async switchSubscriptionPlan(subscriptionId, itemId, newPriceId, options) {
|
|
148
|
-
|
|
184
|
+
async switchSubscriptionPlan(subscriptionId, itemId, newPriceId, options, idempotency) {
|
|
185
|
+
const subscription = await (0, idempotency_1.withIdempotencyKey)(idempotency, idempotency_1.IdempotencyStep.PlanSwitch, (...requestOptions) => this.stripe.subscriptions.update(subscriptionId, {
|
|
149
186
|
items: [{ id: itemId, price: newPriceId, quantity: options?.quantity ?? 1 }],
|
|
150
187
|
proration_behavior: options?.proration ?? 'none',
|
|
151
188
|
billing_cycle_anchor: 'now',
|
|
152
189
|
payment_behavior: 'pending_if_incomplete',
|
|
153
|
-
expand: ['latest_invoice.
|
|
154
|
-
});
|
|
190
|
+
expand: ['latest_invoice.payments', 'pending_update'],
|
|
191
|
+
}, ...requestOptions));
|
|
192
|
+
// With pending_if_incomplete a failed charge keeps the old price, holds the change as pending_update and
|
|
193
|
+
// leaves the switch's bill open, while the call itself succeeds.
|
|
194
|
+
if (subscription.pending_update) {
|
|
195
|
+
const invoice = subscription.latest_invoice;
|
|
196
|
+
const reason = invoice ? await this.discardSwitchInvoice(invoice) : null;
|
|
197
|
+
throw new http_error_1.HttpError(402, reason ?? 'The payment for this plan change did not go through.');
|
|
198
|
+
}
|
|
199
|
+
// The answer names the schedule attached when the switch ran, and a repeat with the key gets that answer back,
|
|
200
|
+
// so a downgrade booked after the first call stays. The answer then names no schedule, even when such a booking
|
|
201
|
+
// is attached, so a caller reads the plan again before acting on its schedule.
|
|
202
|
+
await this.releaseAttachedSchedule(subscription);
|
|
203
|
+
subscription.schedule = null;
|
|
204
|
+
return subscription;
|
|
155
205
|
}
|
|
156
206
|
// Invoice-based subscriptions
|
|
157
207
|
/**
|
|
158
|
-
* Creates a subscription with send_invoice collection and
|
|
208
|
+
* Creates a subscription with send_invoice collection, finalizes its first invoice and emails it at once, and
|
|
209
|
+
* answers that invoice with its payment link.
|
|
159
210
|
*/
|
|
160
|
-
async createInvoiceBasedSubscription(customerId, priceId, options) {
|
|
211
|
+
async createInvoiceBasedSubscription(customerId, priceId, options, idempotency) {
|
|
161
212
|
const subscriptionParams = {
|
|
162
213
|
customer: customerId,
|
|
163
214
|
collection_method: 'send_invoice',
|
|
@@ -173,24 +224,29 @@ class SubscriptionService {
|
|
|
173
224
|
if (options?.transferData) {
|
|
174
225
|
subscriptionParams.transfer_data = options.transferData;
|
|
175
226
|
}
|
|
176
|
-
const subscription = await this.stripe.subscriptions.create(subscriptionParams);
|
|
227
|
+
const subscription = await (0, idempotency_1.withIdempotencyKey)(idempotency, idempotency_1.IdempotencyStep.InvoiceSubscription, (...requestOptions) => this.stripe.subscriptions.create(subscriptionParams, ...requestOptions));
|
|
177
228
|
const latestInvoice = subscription.latest_invoice;
|
|
178
229
|
if (!latestInvoice) {
|
|
179
230
|
throw new http_error_1.HttpError(500, `Stripe did not return the latest invoice for subscription ${subscription.id}. ` +
|
|
180
231
|
'Ensure latest_invoice is expanded.');
|
|
181
232
|
}
|
|
182
233
|
const invoiceId = typeof latestInvoice === 'string' ? latestInvoice : latestInvoice.id;
|
|
183
|
-
|
|
234
|
+
// The first invoice is born a draft, and Stripe answers a send of a draft with the draft as it was, without its
|
|
235
|
+
// link. Finalizing first gives the link; the send then emails the open invoice.
|
|
236
|
+
const finalizedInvoice = await (0, idempotency_1.withIdempotencyKey)(idempotency, idempotency_1.IdempotencyStep.InvoiceSubscriptionFinalize, (...requestOptions) => this.stripe.invoices.finalizeInvoice(invoiceId, ...requestOptions))
|
|
237
|
+
.catch(err => this.invoiceFinalizedMeanwhile(invoiceId, err));
|
|
238
|
+
await (0, idempotency_1.withIdempotencyKey)(idempotency, idempotency_1.IdempotencyStep.InvoiceSubscriptionSend, (...requestOptions) => this.stripe.invoices.sendInvoice(invoiceId, ...requestOptions));
|
|
184
239
|
return {
|
|
185
240
|
subscription,
|
|
186
|
-
invoiceId:
|
|
187
|
-
invoiceUrl:
|
|
241
|
+
invoiceId: finalizedInvoice.id,
|
|
242
|
+
invoiceUrl: finalizedInvoice.hosted_invoice_url ?? null,
|
|
188
243
|
};
|
|
189
244
|
}
|
|
190
245
|
// Utilities
|
|
191
246
|
/**
|
|
192
247
|
* Extracts the fields needed to keep a local subscription document in sync with Stripe.
|
|
193
|
-
* Falls back to the provided values if the subscription has no items.
|
|
248
|
+
* Falls back to the provided values if the subscription has no items. An end date picked in the dashboard, which
|
|
249
|
+
* can fall after the period's end, shows in cancelAt and isEnding; cancelAtPeriodEnd stays Stripe's own flag.
|
|
194
250
|
*/
|
|
195
251
|
buildSubscriptionSyncFields(subscription, fallback = {}) {
|
|
196
252
|
const periodStarts = subscription.items.data.map(item => item.current_period_start);
|
|
@@ -208,6 +264,8 @@ class SubscriptionService {
|
|
|
208
264
|
return {
|
|
209
265
|
status: subscription.status,
|
|
210
266
|
cancelAtPeriodEnd: subscription.cancel_at_period_end,
|
|
267
|
+
cancelAt: subscription.cancel_at ? new Date(subscription.cancel_at * 1000) : null,
|
|
268
|
+
isEnding: subscription.cancel_at_period_end || !!subscription.cancel_at,
|
|
211
269
|
currentPeriodStart,
|
|
212
270
|
currentPeriodEnd,
|
|
213
271
|
itemId,
|
|
@@ -228,9 +286,43 @@ class SubscriptionService {
|
|
|
228
286
|
}
|
|
229
287
|
return subscription.items.data[0] ?? null;
|
|
230
288
|
}
|
|
289
|
+
/**
|
|
290
|
+
* Returns the discount a subscription carries (its promotion code, coupon name, percent or amount off and end), or
|
|
291
|
+
* null without one. Pass a subscription from getSubscriptionWithDiscounts: discounts that are only ids are skipped,
|
|
292
|
+
* and of several the first expanded one is read, as a checkout takes one code. Reads the basil Discount.coupon.
|
|
293
|
+
*/
|
|
294
|
+
getSubscriptionDiscount(subscription) {
|
|
295
|
+
const discount = (subscription.discounts ?? []).find((entry) => typeof entry !== 'string');
|
|
296
|
+
if (!discount) {
|
|
297
|
+
return null;
|
|
298
|
+
}
|
|
299
|
+
const promotionCode = discount.promotion_code;
|
|
300
|
+
return {
|
|
301
|
+
code: promotionCode && typeof promotionCode !== 'string' ? promotionCode.code : null,
|
|
302
|
+
name: discount.coupon.name ?? null,
|
|
303
|
+
percentOff: discount.coupon.percent_off ?? null,
|
|
304
|
+
amountOff: discount.coupon.amount_off ?? null,
|
|
305
|
+
endsAt: discount.end ? new Date(discount.end * 1000) : null,
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
/**
|
|
309
|
+
* Returns what a charge of cost (in cents) on chargedAt comes to with the discount off: the percent's cut rounded
|
|
310
|
+
* to the cent, or the amount off, never below 0. A null discount, or one that ends on or before chargedAt, returns
|
|
311
|
+
* cost as it is; a chargedAt of null keeps the discount.
|
|
312
|
+
*/
|
|
313
|
+
getCostWithDiscount(cost, discount, chargedAt) {
|
|
314
|
+
if (!discount || (discount.endsAt && chargedAt && discount.endsAt <= chargedAt)) {
|
|
315
|
+
return cost;
|
|
316
|
+
}
|
|
317
|
+
if (discount.percentOff) {
|
|
318
|
+
return cost - Math.round(cost * discount.percentOff / 100);
|
|
319
|
+
}
|
|
320
|
+
return Math.max(0, cost - (discount.amountOff ?? 0));
|
|
321
|
+
}
|
|
231
322
|
// Private helpers
|
|
232
|
-
async buildDowngradePhases(schedule, newPriceId, options) {
|
|
323
|
+
async buildDowngradePhases(schedule, newPriceId, liveDiscounts, options) {
|
|
233
324
|
const phases = [];
|
|
325
|
+
let carriedDiscounts = [];
|
|
234
326
|
if (schedule.phases && schedule.current_phase) {
|
|
235
327
|
const currentPhaseStart = schedule.current_phase.start_date;
|
|
236
328
|
const currentPhaseIndex = schedule.phases.findIndex(phase => phase.start_date === currentPhaseStart);
|
|
@@ -238,16 +330,13 @@ class SubscriptionService {
|
|
|
238
330
|
throw new http_error_1.HttpError(500, 'Unable to determine the current subscription phase: ' +
|
|
239
331
|
'current_phase.start_date does not match any phase start_date.');
|
|
240
332
|
}
|
|
241
|
-
const
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
end_date: currentPhase.end_date || undefined,
|
|
249
|
-
metadata: currentPhase.metadata || undefined,
|
|
250
|
-
proration_behavior: currentPhase.proration_behavior,
|
|
333
|
+
const runningPhase = schedule.phases[currentPhaseIndex];
|
|
334
|
+
const currentPhase = this.buildCurrentPhase(runningPhase, liveDiscounts);
|
|
335
|
+
phases.push(currentPhase);
|
|
336
|
+
// Stripe refuses a phase holding a discount that has ended by the time it starts.
|
|
337
|
+
carriedDiscounts = (currentPhase.discounts || []).filter(entry => {
|
|
338
|
+
const end = liveDiscounts.subscription.find(discount => discount.id === entry.discount)?.end;
|
|
339
|
+
return !end || !runningPhase.end_date || end > runningPhase.end_date;
|
|
251
340
|
});
|
|
252
341
|
}
|
|
253
342
|
const newPrice = await this.stripe.prices.retrieve(newPriceId);
|
|
@@ -260,13 +349,212 @@ class SubscriptionService {
|
|
|
260
349
|
billing_cycle_anchor: 'phase_start',
|
|
261
350
|
duration: { interval, interval_count: intervalCount },
|
|
262
351
|
};
|
|
352
|
+
// Stripe drops an empty array from the request and a phase without discounts takes the customer's, so none
|
|
353
|
+
// is sent as ''.
|
|
354
|
+
if (options?.discounts) {
|
|
355
|
+
newPhase.discounts = options.discounts.length ? options.discounts : '';
|
|
356
|
+
}
|
|
357
|
+
else if (carriedDiscounts.length) {
|
|
358
|
+
newPhase.discounts = carriedDiscounts;
|
|
359
|
+
}
|
|
263
360
|
if (options?.transferData) {
|
|
264
361
|
newPhase.transfer_data = options.transferData;
|
|
265
362
|
}
|
|
266
363
|
phases.push(newPhase);
|
|
267
364
|
return phases;
|
|
268
365
|
}
|
|
366
|
+
/**
|
|
367
|
+
* Releases the schedule attached to a subscription, if any: the plan stays on its current price and the schedule's
|
|
368
|
+
* later phases are dropped. A schedule that another call released or that ended meanwhile is passed over.
|
|
369
|
+
*/
|
|
370
|
+
async releaseAttachedSchedule(subscription) {
|
|
371
|
+
if (!subscription.schedule) {
|
|
372
|
+
return;
|
|
373
|
+
}
|
|
374
|
+
const scheduleId = SubscriptionService.idOf(subscription.schedule);
|
|
375
|
+
await this.stripe.subscriptionSchedules.release(scheduleId).catch(async (err) => {
|
|
376
|
+
const schedule = await this.stripe.subscriptionSchedules.retrieve(scheduleId).catch(() => null);
|
|
377
|
+
if (!schedule || SubscriptionService.holdingScheduleStatuses.includes(schedule.status)) {
|
|
378
|
+
throw err;
|
|
379
|
+
}
|
|
380
|
+
});
|
|
381
|
+
}
|
|
382
|
+
/**
|
|
383
|
+
* Voids a declined switch's bill, which also drops the pending update, and returns the decline reason.
|
|
384
|
+
* A failed void is left alone: the decline is still the answer, and the pending update expires by itself.
|
|
385
|
+
*/
|
|
386
|
+
async discardSwitchInvoice(invoice) {
|
|
387
|
+
const intent = invoice.payments?.data[0]?.payment.payment_intent;
|
|
388
|
+
const intentId = intent ? SubscriptionService.idOf(intent) : null;
|
|
389
|
+
const reason = intentId
|
|
390
|
+
? await this.stripe.paymentIntents.retrieve(intentId)
|
|
391
|
+
.then(paymentIntent => paymentIntent.last_payment_error?.message ?? this.chargeDeclineReason(paymentIntent))
|
|
392
|
+
.catch(() => null)
|
|
393
|
+
: null;
|
|
394
|
+
if (invoice.id) {
|
|
395
|
+
await this.stripe.invoices.voidInvoice(invoice.id).catch(() => undefined);
|
|
396
|
+
}
|
|
397
|
+
return reason;
|
|
398
|
+
}
|
|
399
|
+
/**
|
|
400
|
+
* A repeat with the first call's key comes after that call's void, which cancels the payment and clears its error.
|
|
401
|
+
* The declined charge still holds the reason.
|
|
402
|
+
*/
|
|
403
|
+
async chargeDeclineReason(paymentIntent) {
|
|
404
|
+
if (paymentIntent.status !== 'canceled' || !paymentIntent.latest_charge) {
|
|
405
|
+
return null;
|
|
406
|
+
}
|
|
407
|
+
const charge = await this.stripe.charges.retrieve(SubscriptionService.idOf(paymentIntent.latest_charge));
|
|
408
|
+
return charge.failure_message ?? null;
|
|
409
|
+
}
|
|
410
|
+
/**
|
|
411
|
+
* Answers the invoice when its finalize failed but it is final already: Stripe finalizes and emails a draft itself
|
|
412
|
+
* about an hour after the plan is made, so a late repeat gets here. A draft, or one that cannot be read, throws err.
|
|
413
|
+
*/
|
|
414
|
+
async invoiceFinalizedMeanwhile(invoiceId, err) {
|
|
415
|
+
const invoice = await this.stripe.invoices.retrieve(invoiceId).catch(() => null);
|
|
416
|
+
if (!invoice || invoice.status === 'draft') {
|
|
417
|
+
throw err;
|
|
418
|
+
}
|
|
419
|
+
return invoice;
|
|
420
|
+
}
|
|
421
|
+
/**
|
|
422
|
+
* Sends the running phase back as Stripe holds it. A schedule update replaces every phase, and whatever the
|
|
423
|
+
* phase leaves out is dropped from the subscription at once: its discount, its free trial (ended and charged),
|
|
424
|
+
* its own card, its affiliate payout. Fields left null inherit the schedule's default_settings, as before.
|
|
425
|
+
*/
|
|
426
|
+
buildCurrentPhase(phase, liveDiscounts) {
|
|
427
|
+
const params = {
|
|
428
|
+
items: phase.items.map(item => SubscriptionService.buildPhaseItem(item, [...liveDiscounts.items.get(SubscriptionService.idOf(item.price)) ?? []])),
|
|
429
|
+
start_date: phase.start_date,
|
|
430
|
+
end_date: phase.end_date || undefined,
|
|
431
|
+
metadata: phase.metadata || undefined,
|
|
432
|
+
proration_behavior: phase.proration_behavior,
|
|
433
|
+
};
|
|
434
|
+
const discounts = SubscriptionService.toDiscountParams(phase.discounts, [...liveDiscounts.subscription]);
|
|
435
|
+
if (discounts.length) {
|
|
436
|
+
params.discounts = discounts;
|
|
437
|
+
}
|
|
438
|
+
// Stripe takes trial_end only before the phase ends, so a trial filling the whole phase goes back as trial.
|
|
439
|
+
if (phase.trial_end) {
|
|
440
|
+
if (phase.end_date && phase.trial_end >= phase.end_date) {
|
|
441
|
+
params.trial = true;
|
|
442
|
+
}
|
|
443
|
+
else {
|
|
444
|
+
params.trial_end = phase.trial_end;
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
if (phase.default_payment_method) {
|
|
448
|
+
params.default_payment_method = SubscriptionService.idOf(phase.default_payment_method);
|
|
449
|
+
}
|
|
450
|
+
if (phase.transfer_data) {
|
|
451
|
+
params.transfer_data = {
|
|
452
|
+
destination: SubscriptionService.idOf(phase.transfer_data.destination),
|
|
453
|
+
amount_percent: phase.transfer_data.amount_percent ?? undefined,
|
|
454
|
+
};
|
|
455
|
+
}
|
|
456
|
+
if (phase.application_fee_percent !== null) {
|
|
457
|
+
params.application_fee_percent = phase.application_fee_percent;
|
|
458
|
+
}
|
|
459
|
+
if (phase.on_behalf_of) {
|
|
460
|
+
params.on_behalf_of = SubscriptionService.idOf(phase.on_behalf_of);
|
|
461
|
+
}
|
|
462
|
+
if (phase.collection_method) {
|
|
463
|
+
params.collection_method = phase.collection_method;
|
|
464
|
+
}
|
|
465
|
+
if (phase.description) {
|
|
466
|
+
params.description = phase.description;
|
|
467
|
+
}
|
|
468
|
+
if (phase.default_tax_rates?.length) {
|
|
469
|
+
params.default_tax_rates = phase.default_tax_rates.map(rate => rate.id);
|
|
470
|
+
}
|
|
471
|
+
if (phase.invoice_settings) {
|
|
472
|
+
const { account_tax_ids, days_until_due, issuer } = phase.invoice_settings;
|
|
473
|
+
params.invoice_settings = {
|
|
474
|
+
account_tax_ids: account_tax_ids?.map(taxId => SubscriptionService.idOf(taxId)),
|
|
475
|
+
days_until_due: days_until_due ?? undefined,
|
|
476
|
+
issuer: issuer ? { type: issuer.type, account: issuer.account ? SubscriptionService.idOf(issuer.account) : undefined } : undefined,
|
|
477
|
+
};
|
|
478
|
+
}
|
|
479
|
+
if (phase.billing_thresholds) {
|
|
480
|
+
params.billing_thresholds = {
|
|
481
|
+
amount_gte: phase.billing_thresholds.amount_gte ?? undefined,
|
|
482
|
+
reset_billing_cycle_anchor: phase.billing_thresholds.reset_billing_cycle_anchor ?? undefined,
|
|
483
|
+
};
|
|
484
|
+
}
|
|
485
|
+
if (phase.automatic_tax?.enabled) {
|
|
486
|
+
const liability = phase.automatic_tax.liability;
|
|
487
|
+
params.automatic_tax = {
|
|
488
|
+
enabled: true,
|
|
489
|
+
liability: liability ? { type: liability.type, account: liability.account ? SubscriptionService.idOf(liability.account) : undefined } : undefined,
|
|
490
|
+
};
|
|
491
|
+
}
|
|
492
|
+
return params;
|
|
493
|
+
}
|
|
494
|
+
static buildPhaseItem(item, liveDiscounts) {
|
|
495
|
+
const params = {
|
|
496
|
+
price: SubscriptionService.idOf(item.price),
|
|
497
|
+
quantity: item.quantity,
|
|
498
|
+
};
|
|
499
|
+
const discounts = SubscriptionService.toDiscountParams(item.discounts, liveDiscounts);
|
|
500
|
+
if (discounts.length) {
|
|
501
|
+
params.discounts = discounts;
|
|
502
|
+
}
|
|
503
|
+
if (item.tax_rates?.length) {
|
|
504
|
+
params.tax_rates = item.tax_rates.map(rate => rate.id);
|
|
505
|
+
}
|
|
506
|
+
if (item.metadata && Object.keys(item.metadata).length) {
|
|
507
|
+
params.metadata = item.metadata;
|
|
508
|
+
}
|
|
509
|
+
if (item.billing_thresholds?.usage_gte != null) {
|
|
510
|
+
params.billing_thresholds = { usage_gte: item.billing_thresholds.usage_gte };
|
|
511
|
+
}
|
|
512
|
+
return params;
|
|
513
|
+
}
|
|
514
|
+
/**
|
|
515
|
+
* Maps the discounts Stripe reports on a phase to the form an update takes, one of discount, promotion code or
|
|
516
|
+
* coupon each. A coupon that a live discount carries is sent as that discount, so it runs on with its own end
|
|
517
|
+
* date; each live discount is used once, taken out of liveDiscounts as it is matched. A discount id that is no
|
|
518
|
+
* longer live has ended or been removed, and Stripe refuses any phase that still holds it, so it is left out.
|
|
519
|
+
*/
|
|
520
|
+
static toDiscountParams(discounts, liveDiscounts) {
|
|
521
|
+
return (discounts ?? []).flatMap(entry => {
|
|
522
|
+
const discountId = entry.discount ? SubscriptionService.idOf(entry.discount) : null;
|
|
523
|
+
const couponId = entry.coupon ? SubscriptionService.idOf(entry.coupon) : null;
|
|
524
|
+
const liveIndex = discountId
|
|
525
|
+
? liveDiscounts.findIndex(discount => discount.id === discountId)
|
|
526
|
+
: liveDiscounts.findIndex(discount => discount.coupon?.id === couponId);
|
|
527
|
+
if (liveIndex !== -1 && (discountId || couponId)) {
|
|
528
|
+
return [{ discount: liveDiscounts.splice(liveIndex, 1)[0].id }];
|
|
529
|
+
}
|
|
530
|
+
if (discountId) {
|
|
531
|
+
return [];
|
|
532
|
+
}
|
|
533
|
+
if (entry.promotion_code) {
|
|
534
|
+
return [{ promotion_code: SubscriptionService.idOf(entry.promotion_code) }];
|
|
535
|
+
}
|
|
536
|
+
return couponId ? [{ coupon: couponId }] : [];
|
|
537
|
+
});
|
|
538
|
+
}
|
|
539
|
+
static liveDiscountsOf(subscription) {
|
|
540
|
+
const expanded = (discounts) => discounts.filter((discount) => typeof discount !== 'string');
|
|
541
|
+
const items = new Map();
|
|
542
|
+
for (const item of subscription.items.data) {
|
|
543
|
+
const priceId = item.price.id;
|
|
544
|
+
items.set(priceId, [...items.get(priceId) ?? [], ...expanded(item.discounts)]);
|
|
545
|
+
}
|
|
546
|
+
return { subscription: expanded(subscription.discounts), items };
|
|
547
|
+
}
|
|
548
|
+
static idOf(value) {
|
|
549
|
+
return typeof value === 'string' ? value : value.id;
|
|
550
|
+
}
|
|
269
551
|
}
|
|
270
552
|
exports.SubscriptionService = SubscriptionService;
|
|
271
553
|
SubscriptionService.phaseTypeNew = 'new';
|
|
272
554
|
SubscriptionService.phaseTypeDowngrade = 'downgrade';
|
|
555
|
+
// A plan that runs on to the end of its period, which for a free trial is the trial's end.
|
|
556
|
+
SubscriptionService.runningStatuses = ['active', 'past_due', 'trialing'];
|
|
557
|
+
// A schedule that still holds its subscription; Stripe releases only these.
|
|
558
|
+
SubscriptionService.holdingScheduleStatuses = ['active', 'not_started'];
|
|
559
|
+
// What getSubscriptionDiscount reads: the discounts, and the promotion code behind each.
|
|
560
|
+
SubscriptionService.discountExpands = ['discounts', 'discounts.promotion_code'];
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import Stripe from 'stripe';
|
|
2
|
+
import { IdempotencyOptions } from './../models/stripe.model';
|
|
3
|
+
export declare enum IdempotencyStep {
|
|
4
|
+
Checkout = "checkout",
|
|
5
|
+
SetupIntent = "setup-intent",
|
|
6
|
+
Customer = "customer",
|
|
7
|
+
Invoice = "invoice",
|
|
8
|
+
InvoiceLine = "invoice-line",
|
|
9
|
+
InvoiceSend = "invoice-send",
|
|
10
|
+
InvoiceFinalize = "invoice-finalize",
|
|
11
|
+
InvoicePay = "invoice-pay",
|
|
12
|
+
PaymentLinkPrice = "payment-link-price",
|
|
13
|
+
PaymentLink = "payment-link",
|
|
14
|
+
Price = "price",
|
|
15
|
+
ConnectedAccount = "connected-account",
|
|
16
|
+
PlanCredit = "plan-credit",
|
|
17
|
+
PlanSwitch = "plan-switch",
|
|
18
|
+
InvoiceSubscription = "invoice-subscription",
|
|
19
|
+
InvoiceSubscriptionFinalize = "invoice-subscription-finalize",
|
|
20
|
+
InvoiceSubscriptionSend = "invoice-subscription-send",
|
|
21
|
+
SubscriptionUpdate = "subscription-update"
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Sends one Stripe write with the caller's key plus the step's name (unique in the library), so a repeat gets the
|
|
25
|
+
* first answer back and one key can cover a whole user action. Without a key the write goes as before. Throws 400
|
|
26
|
+
* for a key over 200 characters or outside visible ASCII, 422 when Stripe saw it with other details, 409 while it runs.
|
|
27
|
+
*/
|
|
28
|
+
export declare function withIdempotencyKey<T>(idempotency: IdempotencyOptions | undefined, step: IdempotencyStep, write: (...options: [] | [Stripe.RequestOptions]) => Promise<T>): Promise<T>;
|
|
29
|
+
//# sourceMappingURL=idempotency.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"idempotency.d.ts","sourceRoot":"","sources":["../../src/utils/idempotency.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,QAAQ,CAAC;AAI5B,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAc9D,oBAAY,eAAe;IACzB,QAAQ,aAAa;IACrB,WAAW,iBAAiB;IAC5B,QAAQ,aAAa;IACrB,OAAO,YAAY;IACnB,WAAW,iBAAiB;IAC5B,WAAW,iBAAiB;IAC5B,eAAe,qBAAqB;IACpC,UAAU,gBAAgB;IAC1B,gBAAgB,uBAAuB;IACvC,WAAW,iBAAiB;IAC5B,KAAK,UAAU;IACf,gBAAgB,sBAAsB;IACtC,UAAU,gBAAgB;IAC1B,UAAU,gBAAgB;IAC1B,mBAAmB,yBAAyB;IAC5C,2BAA2B,kCAAkC;IAC7D,uBAAuB,8BAA8B;IACrD,kBAAkB,wBAAwB;CAC3C;AAED;;;;GAIG;AACH,wBAAsB,kBAAkB,CAAC,CAAC,EAAE,WAAW,EAAE,kBAAkB,GAAG,SAAS,EAAE,IAAI,EAAE,eAAe,EAAE,KAAK,EAAE,CAAC,GAAG,OAAO,EAAE,EAAE,GAAG,CAAC,MAAM,CAAC,cAAc,CAAC,KAAK,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CA2B3L"}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.IdempotencyStep = void 0;
|
|
4
|
+
exports.withIdempotencyKey = withIdempotencyKey;
|
|
5
|
+
const http_error_1 = require("./../errors/http-error");
|
|
6
|
+
// Stripe takes keys of up to 255 characters; the rest is room for the step's name.
|
|
7
|
+
const MAX_KEY_LENGTH = 200;
|
|
8
|
+
// Stripe gets the key in a request header: Node refuses a newline or any sign past Latin-1 there (an em dash,
|
|
9
|
+
// Cyrillic), and a space at either end is dropped, so only visible ASCII arrives as it was sent.
|
|
10
|
+
const KEY_CHARACTERS = /^[\x21-\x7E]+$/;
|
|
11
|
+
// Stripe's code when the first request with a key is still running.
|
|
12
|
+
const KEY_IN_USE_CODE = 'idempotency_key_in_use';
|
|
13
|
+
// The name each Stripe write adds to the caller's key, one per write. Keys at Stripe already end in these values,
|
|
14
|
+
// so a changed value lets a repeat that spans the upgrade run again.
|
|
15
|
+
var IdempotencyStep;
|
|
16
|
+
(function (IdempotencyStep) {
|
|
17
|
+
IdempotencyStep["Checkout"] = "checkout";
|
|
18
|
+
IdempotencyStep["SetupIntent"] = "setup-intent";
|
|
19
|
+
IdempotencyStep["Customer"] = "customer";
|
|
20
|
+
IdempotencyStep["Invoice"] = "invoice";
|
|
21
|
+
IdempotencyStep["InvoiceLine"] = "invoice-line";
|
|
22
|
+
IdempotencyStep["InvoiceSend"] = "invoice-send";
|
|
23
|
+
IdempotencyStep["InvoiceFinalize"] = "invoice-finalize";
|
|
24
|
+
IdempotencyStep["InvoicePay"] = "invoice-pay";
|
|
25
|
+
IdempotencyStep["PaymentLinkPrice"] = "payment-link-price";
|
|
26
|
+
IdempotencyStep["PaymentLink"] = "payment-link";
|
|
27
|
+
IdempotencyStep["Price"] = "price";
|
|
28
|
+
IdempotencyStep["ConnectedAccount"] = "connected-account";
|
|
29
|
+
IdempotencyStep["PlanCredit"] = "plan-credit";
|
|
30
|
+
IdempotencyStep["PlanSwitch"] = "plan-switch";
|
|
31
|
+
IdempotencyStep["InvoiceSubscription"] = "invoice-subscription";
|
|
32
|
+
IdempotencyStep["InvoiceSubscriptionFinalize"] = "invoice-subscription-finalize";
|
|
33
|
+
IdempotencyStep["InvoiceSubscriptionSend"] = "invoice-subscription-send";
|
|
34
|
+
IdempotencyStep["SubscriptionUpdate"] = "subscription-update";
|
|
35
|
+
})(IdempotencyStep || (exports.IdempotencyStep = IdempotencyStep = {}));
|
|
36
|
+
/**
|
|
37
|
+
* Sends one Stripe write with the caller's key plus the step's name (unique in the library), so a repeat gets the
|
|
38
|
+
* first answer back and one key can cover a whole user action. Without a key the write goes as before. Throws 400
|
|
39
|
+
* for a key over 200 characters or outside visible ASCII, 422 when Stripe saw it with other details, 409 while it runs.
|
|
40
|
+
*/
|
|
41
|
+
async function withIdempotencyKey(idempotency, step, write) {
|
|
42
|
+
const key = idempotency?.idempotencyKey;
|
|
43
|
+
if (!key) {
|
|
44
|
+
return write();
|
|
45
|
+
}
|
|
46
|
+
if (key.length > MAX_KEY_LENGTH) {
|
|
47
|
+
throw new http_error_1.HttpError(400, `An idempotency key can be at most ${MAX_KEY_LENGTH} characters.`);
|
|
48
|
+
}
|
|
49
|
+
if (!KEY_CHARACTERS.test(key)) {
|
|
50
|
+
throw new http_error_1.HttpError(400, 'An idempotency key can hold only ASCII letters, digits and symbols, with no spaces.');
|
|
51
|
+
}
|
|
52
|
+
return write({ idempotencyKey: `${key}:${step}` })
|
|
53
|
+
.catch(err => {
|
|
54
|
+
if (err?.type === 'StripeIdempotencyError') {
|
|
55
|
+
throw new http_error_1.HttpError(422, 'This idempotency key was already used for a different request.');
|
|
56
|
+
}
|
|
57
|
+
if (err?.code === KEY_IN_USE_CODE) {
|
|
58
|
+
throw new http_error_1.HttpError(409, 'A request with this idempotency key is still running. Try again in a moment.', true);
|
|
59
|
+
}
|
|
60
|
+
throw err;
|
|
61
|
+
});
|
|
62
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { WebhookHooks } from './../models/webhook.model';
|
|
2
|
+
/**
|
|
3
|
+
* Gives an error to the app's onError and drops a throw or a rejection from it, which would otherwise stop the process
|
|
4
|
+
* (Node's unhandledRejection) or replace the answer an event gets. Resolves once onError has finished; never rejects.
|
|
5
|
+
*/
|
|
6
|
+
export declare function reportError(hooks: WebhookHooks, context: string, error: unknown): Promise<void>;
|
|
7
|
+
//# sourceMappingURL=report-error.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"report-error.d.ts","sourceRoot":"","sources":["../../src/webhooks/report-error.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AAEzD;;;GAGG;AACH,wBAAsB,WAAW,CAAC,KAAK,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAMrG"}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.reportError = reportError;
|
|
4
|
+
/**
|
|
5
|
+
* Gives an error to the app's onError and drops a throw or a rejection from it, which would otherwise stop the process
|
|
6
|
+
* (Node's unhandledRejection) or replace the answer an event gets. Resolves once onError has finished; never rejects.
|
|
7
|
+
*/
|
|
8
|
+
async function reportError(hooks, context, error) {
|
|
9
|
+
try {
|
|
10
|
+
await hooks.onError?.(context, error);
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
return;
|
|
14
|
+
}
|
|
15
|
+
}
|