-
Notifications
You must be signed in to change notification settings - Fork 119
/
stripe.js
794 lines (746 loc) · 24 KB
/
stripe.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
/* eslint-disable no-void */
import Stripe from 'stripe'
import { CustomerNotFound, isStoragePriceName, randomString, storagePriceNames } from './billing.js'
/**
* @typedef {import('./billing-types').StoragePriceName} StoragePriceName
*/
/**
* @typedef {import('stripe').Stripe} StripeInterface
*/
/**
* @typedef {import("./billing-types").BillingService} BillingService
* @typedef {import("./billing-types").PaymentMethod} PaymentMethod
*/
/**
* @typedef {object} StripeComForBillingService
* @property {Pick<StripeInterface['paymentMethods'], 'attach'>} paymentMethods
* @property {Pick<StripeInterface['setupIntents'], 'create'>} setupIntents
* @property {Pick<StripeInterface['customers'], 'retrieve'|'update'>} customers
*/
/**
* A BillingService that uses stripe.com
*/
export class StripeBillingService {
/**
* @param {StripeComForBillingService} stripe
*/
static create (stripe) {
return new StripeBillingService(stripe)
}
/**
* @protected
* @param {StripeComForBillingService} stripe
*/
constructor (stripe) {
/** @type {StripeComForBillingService} */
this.stripe = stripe
void /** @type {BillingService} */ (this)
}
/**
* @param {string} customerId
* @returns {Promise<null | CustomerNotFound | PaymentMethod>}
*/
async getPaymentMethod (customerId) {
const response = await this.stripe.customers.retrieve(customerId, {
expand: ['invoice_settings.default_payment_method']
})
if (response.deleted) {
return new CustomerNotFound('customer retrieved from stripe has been unexpectedly deleted')
}
const defaultPaymentMethod = response.invoice_settings.default_payment_method
const defaultPaymentMethodObject = (typeof defaultPaymentMethod === 'string') ? { id: defaultPaymentMethod } : defaultPaymentMethod ?? {}
const defaultPaymentMethodId = (typeof defaultPaymentMethod === 'string') ? defaultPaymentMethod : defaultPaymentMethod?.id
if (!defaultPaymentMethodId) {
return null
}
/** @type {import('./billing-types').PaymentMethod} */
const paymentMethod = ('card' in defaultPaymentMethodObject)
? stripeToStripeCardPaymentMethod(defaultPaymentMethodObject)
: {
id: defaultPaymentMethodId
}
return paymentMethod
}
/**
* @param {import('./billing-types').CustomerId} customer
* @param {import('./billing-types').PaymentMethod['id']} method
* @returns {Promise<void>}
*/
async savePaymentMethod (customer, method) {
const setupIntent = await this.stripe.setupIntents.create({
payment_method: method,
confirm: true,
customer
})
if (setupIntent.status !== 'succeeded') {
console.warn('setupIntent created, but status is not yet succeeded', setupIntent)
}
const desiredDefaultPaymentMethod = setupIntent.payment_method
if (!desiredDefaultPaymentMethod) {
throw new Error('unable to determine desiredDefaultPaymentMethod')
}
// set default_payment_method to this method
await this.stripe.customers.update(customer, {
invoice_settings: {
default_payment_method: desiredDefaultPaymentMethod.toString()
}
})
}
}
/**
* @param {Stripe.PaymentMethod} paymentMethod
* @returns {import('./billing-types').StripeCardPaymentMethod}
*/
export function stripeToStripeCardPaymentMethod (paymentMethod) {
const stripeCard = ('card' in paymentMethod)
? paymentMethod.card
: undefined
if (!stripeCard) {
throw new Error('failed to get stripeCard from paymentMethod')
}
return {
// @ts-ignore
id: paymentMethod.id,
card: {
'@type': 'https://stripe.com/docs/api/cards/object',
brand: stripeCard.brand,
country: stripeCard.country,
exp_month: stripeCard.exp_month,
exp_year: stripeCard.exp_year,
funding: stripeCard.funding,
last4: stripeCard.last4
}
}
}
/**
* @typedef {import("./billing-types").CustomersService} CustomersService
*/
/**
* @typedef {import("./billing-types").Customer} Customer
*/
/**
* @typedef {import('stripe').Stripe['customers']} StripeComCustomers
*/
/**
* @typedef {object} StripeComCustomersForGetOrCreate
* @property {StripeComCustomers['create']} create
*/
/**
* @typedef {object} StripeComForCustomersService
* @property {StripeComCustomersForGetOrCreate} customers
*/
/**
* @typedef {import('@web3-storage/db').DBClient} DBClient
*/
/**
* @typedef {Pick<DBClient, 'getUserCustomer'>} DBClientForStripeCustomersService
*/
/**
* @typedef {import('./billing-types').UserCustomerService} UserCustomerService
*/
/**
* A CustomersService that uses stripe.com for storage
*/
export class StripeCustomersService {
/**
* @param {StripeComForCustomersService} stripe
* @param {UserCustomerService} userCustomerService
*/
static create (stripe, userCustomerService) {
return new StripeCustomersService(stripe, userCustomerService)
}
/**
* @param {StripeComForCustomersService} stripe
* @param {UserCustomerService} userCustomerService
* @protected
*/
constructor (stripe, userCustomerService) {
/** @type {UserCustomerService} */
this.userCustomerService = userCustomerService
/** @type {StripeComForCustomersService} */
this.stripe = stripe
void /** @type {CustomersService} */ (this)
}
/**
* @param {import('./billing-types').BillingUser} user
* @param {import('./billing-types').UserCreationOptions} [options]
* @returns {Promise<Customer>}
*/
async getOrCreateForUser (user, options) {
const existingCustomer = await this.userCustomerService.getUserCustomer(user.id.toString())
if (existingCustomer) return existingCustomer
const createdCustomer = await this.stripe.customers.create({
metadata: {
'web3.storage/user.id': user.id
},
name: options?.name,
email: options?.email
})
await this.userCustomerService.upsertUserCustomer(user.id.toString(), createdCustomer.id)
return createdCustomer
}
}
/**
* @param {string} secretKey
* @returns {StripeInterface}
*/
export function createStripe (secretKey) {
return new Stripe(secretKey, {
apiVersion: '2022-08-01',
httpClient: Stripe.createFetchHttpClient()
})
}
/**
* Create a mock StripeCard paymentMethod
* @returns
*/
export function createMockStripeCardPaymentMethod () {
return {
id: `pm_${randomString()}`,
card: {
'@type': 'https://stripe.com/docs/api/cards/object',
brand: 'visa',
country: 'US',
exp_month: 9,
exp_year: 2023,
funding: 'credit',
last4: '4242'
}
}
}
/** @returns {StripeComForCustomersService} */
export function createMockStripeForCustomersService () {
return {
customers: {
create: async () => {
const customer = createMockStripeCustomer()
/** @type {Stripe.Response<Stripe.Customer>} */
const response = {
// @ts-ignore
lastResponse: {},
...customer
}
return response
}
}
}
}
/**
* @param {object} [options]
* @param {(id: string) => Promise<undefined|Stripe.Customer|Stripe.DeletedCustomer>} [options.retrieveCustomer]
* @param {() => void} [options.onCreateSetupintent]
* @returns {StripeComForBillingService}
*/
export function createMockStripeForBilling (options = {}) {
const retrieveCustomer = options.retrieveCustomer || async function (id) {
throw new Error(`no customer found with id=${id}`)
}
const paymentMethods = {
/**
* @param {string} paymentMethodId
* @param {Stripe.PaymentMethodAttachParams} customerId
* @returns {Promise<Stripe.Response<Stripe.PaymentMethod>>}
*/
attach: async (paymentMethodId, params) => {
/** @type {Stripe.PaymentMethod} */
const method = {
...createMockStripePaymentMethod(),
id: paymentMethodId
}
/** @type {Stripe.Response<Stripe.PaymentMethod>} */
const response = {
// @ts-ignore
lastResponse: undefined,
...method
}
return response
}
}
/** @type {StripeComForBillingService['customers']} */
const customers = {
async retrieve (id, params) {
const customer = await retrieveCustomer(id)
/** @type {Stripe.Response<Stripe.Customer>} */
const response = {
...customer,
// @ts-ignore
lastResponse: undefined
}
return response
},
async update (id, params) {
/** @type {Stripe.Response<Stripe.Customer>} */
const updatedCustomer = {
// @ts-ignore
lastResponse: undefined,
...createMockStripeCustomer(),
params
}
return updatedCustomer
}
}
/** @type {StripeComForBillingService['setupIntents']} */
const setupIntents = {
async create (params) {
/** @type {Stripe.SetupIntent} */
// @ts-ignore
const setupIntent = {
object: 'setup_intent',
description: 'mock setup_intent',
status: 'succeeded',
payment_method: params.payment_method
}
options?.onCreateSetupintent?.()
/** @type {Stripe.Response<Stripe.SetupIntent>} */
const response = {
// @ts-ignore
lastResponse: {},
...setupIntent
}
return response
}
}
return { paymentMethods, customers, setupIntents }
}
/**
* @returns {Stripe.PaymentMethod}
*/
function createMockStripePaymentMethod () {
return {
id: `pm_${randomString()}`,
object: 'payment_method',
billing_details: {
name: [randomString(), randomString()].join(' '),
address: {
city: randomString(),
country: randomString(),
line1: randomString(),
line2: randomString(),
postal_code: randomString(),
state: 'KS'
},
email: `${randomString()}@example.com`,
phone: randomString()
},
created: Number(new Date()),
livemode: false,
type: 'card',
metadata: {},
customer: createMockStripeCustomer()
}
}
/**
* @param {object} [options]
* @param {string} [options.defaultPaymentMethodId]
* @returns {Stripe.Customer}
*/
export function createMockStripeCustomer (options = {}) {
return {
id: `customer-${randomString()}`,
object: 'customer',
balance: 0,
created: Number(new Date()),
email: `${randomString()}@example.com`,
default_source: null,
description: randomString(),
livemode: false,
metadata: {},
// @ts-ignore
invoice_settings: {
...(options.defaultPaymentMethodId
? { default_payment_method: options.defaultPaymentMethodId }
: {}
)
},
subscriptions: {
data: [],
object: 'list',
has_more: false,
url: ''
}
}
}
/**
* Create some billing services based on the provided environment vars.
* If there is a stripe.com secret, the implementations will use the stripe.com APIs.
* Otherwise the mock implementations will be used.
* @param {object} env
* @param {string} env.STRIPE_SECRET_KEY
* @param {Pick<DBClient, 'upsertUserCustomer'|'getUserCustomer'>} env.db
* @returns {import('./billing-types').BillingEnv}
*/
export function createStripeBillingContext (env) {
const stripeSecretKey = env.STRIPE_SECRET_KEY
if (!stripeSecretKey) {
throw new Error('Please set the required STRIPE_SECRET_KEY environment variable')
}
const stripe = new Stripe(stripeSecretKey, {
apiVersion: '2022-08-01',
httpClient: Stripe.createFetchHttpClient()
})
const billing = StripeBillingService.create(stripe)
/** @type {UserCustomerService} */
const userCustomerService = {
upsertUserCustomer: env.db.upsertUserCustomer.bind(env.db),
getUserCustomer: env.db.getUserCustomer.bind(env.db)
}
const customers = StripeCustomersService.create(stripe, userCustomerService)
// attempt to get stripe price IDs from env vars
let stripePrices
try {
stripePrices = createStripeStoragePricesFromEnv(env)
} catch (error) {
if (error instanceof EnvVarMissingError) {
console.error('env var missing, defaulting to stagingStripePrices', error)
// default prices to use staging values if we cannot set them from the env
stripePrices = stagingStripePrices
} else {
throw error
}
}
const subscriptions = StripeSubscriptionsService.create(stripe, stripePrices)
return {
billing,
customers,
subscriptions
}
}
export class NamedStripePrices {
/**
* @param {Record<import('./billing-types').StoragePriceName, string>} namedPrices
*/
constructor (namedPrices) {
this.namedPrices = namedPrices
void /** @type {import('./billing-types').NamedStripePrices} */ (this)
}
/**
* @param {StoragePriceName} name
* @returns {StripePriceId|undefined}
*/
nameToPrice (name) {
const priceId = this.namedPrices[name]
if (priceId) {
return /** @type {StripePriceId} */ (priceId)
}
}
/**
* @param {StripePriceId} priceId
* @returns {StoragePriceName|undefined}
*/
priceToName (priceId) {
const priceName = Object.keys(this.namedPrices).find(name => this.namedPrices[name] === priceId)
if (isStoragePriceName(priceName)) {
return priceName
}
}
}
// https://dashboard.stripe.com/test/prices/price_1Li2ISIfErzTm2rEg4wD9BR2
export const testPriceForStorageFree = 'price_1Li2ISIfErzTm2rEg4wD9BR2'
// https://dashboard.stripe.com/test/prices/price_1LhdqgIfErzTm2rEqfl6EgnT
export const testPriceForStorageLite = 'price_1LhdqgIfErzTm2rEqfl6EgnT'
// https://dashboard.stripe.com/test/prices/price_1Li1upIfErzTm2rEIDcI6scF
export const testPriceForStoragePro = 'price_1Li1upIfErzTm2rEIDcI6scF'
export const stagingStripePrices = new NamedStripePrices({
free: testPriceForStorageFree,
lite: testPriceForStorageLite,
pro: testPriceForStoragePro
})
/**
* @typedef {object} StripeApiForSubscriptionsService
* @property {Pick<Stripe['subscriptions'], 'cancel'|'create'>} subscriptions
* @property {Pick<Stripe['subscriptionItems'], 'update'|'del'>} subscriptionItems
* @property {Pick<Stripe['customers'], 'retrieve'>} customers
*/
/**
* @param {object} [options]
* @param {(...args: Parameters<Stripe['subscriptions']['create']>) => void} [options.onSubscriptionCreate]
* @param {(id: string) => Promise<undefined|Stripe.Customer|Stripe.DeletedCustomer>} [options.retrieveCustomer]
* @returns {StripeApiForSubscriptionsService}
*/
export function createMockStripeForSubscriptions (options = {}) {
return {
...createMockStripeForBilling({
retrieveCustomer: options.retrieveCustomer
}),
subscriptions: {
async cancel (id, params) {
return {
id,
object: 'subscription',
status: 'canceled',
cancel_at_period_end: false,
canceled_at: Number(new Date()),
...params
}
},
async create (...args) {
options?.onSubscriptionCreate?.(...args)
/** @type {Stripe.Response<Stripe.Subscription>} */
const subscription = {
id: `sub_${randomString()}`,
object: 'subscription',
// @ts-ignore
lastResponse: undefined
}
return subscription
}
},
subscriptionItems: {
async del (id, options) {
/** @type {Stripe.Response<Stripe.DeletedSubscriptionItem>} */
const response = {
// @ts-ignore
lastResponse: undefined
}
return response
},
async update (id, params, options) {
/** @type {Stripe.SubscriptionItem} */
// @ts-ignore
const item = {
id,
object: 'subscription_item',
...params,
created: Number(new Date())
}
/** @type {Stripe.Response<Stripe.SubscriptionItem>} */
const response = {
...item,
// @ts-ignore
lastResponse: undefined
}
return response
}
}
}
}
/**
* @param {object} [options]
* @param {Stripe.SubscriptionItem[]} [options.items]
* @returns
*/
export function createMockStripeSubscription (options = {}) {
/** @type {Stripe.Subscription} */
// @ts-ignore
const subscription = {
id: `sub_${randomString()}`,
object: 'subscription',
items: {
object: 'list',
has_more: false,
url: '',
data: [
...options.items ?? []
]
}
}
return subscription
}
/**
* A SubscriptionsService that uses stripe.com for storage
*/
export class StripeSubscriptionsService {
/**
* @param {StripeApiForSubscriptionsService} stripe
* @param {import('./billing-types').NamedStripePrices} prices
*/
static create (stripe, prices) {
return new StripeSubscriptionsService(
stripe,
prices
)
}
/**
* @param {StripeApiForSubscriptionsService} stripe
* @param {import('./billing-types').NamedStripePrices} priceNamer
* @protected
*/
constructor (stripe, priceNamer) {
/** @type {StripeApiForSubscriptionsService} */
this.stripe = stripe
/** @type {import('./billing-types').NamedStripePrices} */
this.priceNamer = priceNamer
void /** @type {import('./billing-types').SubscriptionsService} */ (this)
}
/**
* @param {string} customerId
* @returns {Promise<import('./billing-types').W3PlatformSubscription|CustomerNotFound>}
*/
async getSubscription (customerId) {
const storageStripeSubscription = await this.getStorageStripeSubscription(customerId)
if (storageStripeSubscription instanceof CustomerNotFound) { return storageStripeSubscription }
/** @returns {import('./billing-types').W3PlatformSubscription} */
const subscription = {
storage: createW3StorageSubscription(storageStripeSubscription, this.priceNamer)
}
return subscription
}
async getStorageStripeSubscription (customerId) {
const customer = await this.stripe.customers.retrieve(customerId, {
expand: ['subscriptions']
})
if (customer.deleted) {
return new CustomerNotFound('customer retrieved from stripe has been unexpectedly deleted')
}
const { subscriptions: stripeSubscriptions } = customer
if (!stripeSubscriptions) {
// this is unexpected, since we requested expand=subscriptions above
throw new Error('expected subscriptions to be expanded, but got falsy value')
}
const storageStripeSubscription = selectStorageStripeSubscription(customerId, stripeSubscriptions)
return storageStripeSubscription
}
/**
*
* @param {import('./billing-types').CustomerId} customerId
* @param {import('./billing-types').W3PlatformSubscription} subscription
* @returns {Promise<CustomerNotFound|void>}
*/
async saveSubscription (customerId, subscription) {
const storageStripeSubscription = await this.getStorageStripeSubscription(customerId)
if (storageStripeSubscription instanceof Error) { return storageStripeSubscription }
await this.saveStorageSubscription(customerId, subscription.storage, storageStripeSubscription ?? undefined)
}
/**
* @param {import('./billing-types').CustomerId} customerId
* @param {import('./billing-types').W3PlatformSubscription['storage']} storageSubscription
* @param {Stripe.Subscription} [existingStripeSubscription]
* @returns {Promise<import('./billing-types').W3StorageStripeSubscription|null>}
*/
async saveStorageSubscription (customerId, storageSubscription, existingStripeSubscription = undefined) {
const existingStorageStripeSubscriptionItem = existingStripeSubscription && selectStorageStripeSubscriptionItem(existingStripeSubscription)
if (!storageSubscription) {
if (existingStorageStripeSubscriptionItem) {
await this.stripe.subscriptions.cancel(existingStripeSubscription.id)
}
return null
}
const priceName = storageSubscription.price
const desiredPriceId = this.priceNamer.nameToPrice(priceName)
if (!desiredPriceId) {
throw new Error(`invalid price name: ${priceName}`)
}
const desiredSubscriptionItem = {
price: desiredPriceId
}
/** @type {string|undefined} */
let subscriptionId
// if there's an existing subscription, modify it
if (existingStorageStripeSubscriptionItem && existingStripeSubscription) {
if (!storageSubscription) {
// delete
await this.stripe.subscriptions.cancel(existingStripeSubscription.id)
return null
}
// update
const updatedSubItem = await this.stripe.subscriptionItems.update(
existingStorageStripeSubscriptionItem.id,
desiredSubscriptionItem
)
subscriptionId = updatedSubItem.subscription
} else {
// create subscription with item
const created = await this.stripe.subscriptions.create({
customer: customerId,
items: [
desiredSubscriptionItem
],
payment_behavior: 'error_if_incomplete'
})
subscriptionId = created.id
}
/** @type {import('./billing-types').W3StorageStripeSubscription} */
const subscription = { id: subscriptionId }
return subscription
}
}
/**
* @param {string} customerId
* @param {Stripe.ApiList<Stripe.Subscription>} stripeSubscriptions
* @returns {Stripe.Subscription | null}
*/
function selectStorageStripeSubscription (customerId, stripeSubscriptions) {
if (stripeSubscriptions.data.length === 0) {
return null
}
if (stripeSubscriptions.data.length > 1) {
throw new Error(`customer ${customerId} has ${stripeSubscriptions?.data?.length} subscriptions, but we only expect to ever see one.`)
}
// @todo - this isn't very clever. We should be more clever, or maybe throw when there are >1 subscriptions
const stripeSubscription = stripeSubscriptions.data[0]
return stripeSubscription
}
/**
* @param {Stripe.Subscription} stripeSubscription
* @returns {Stripe.SubscriptionItem}
*/
function selectStorageStripeSubscriptionItem (stripeSubscription) {
const { items } = stripeSubscription
if (items.data.length !== 1) {
throw new Error(`unexpected number of subscription items: ${items.data.length}`)
}
const item = items.data[0]
return item
}
/**
* @param {null|Stripe.Subscription} stripeSubscription
* @param {import('./billing-types').NamedStripePrices} priceNamer
* @returns {import('./billing-types').W3PlatformSubscription['storage']}
*/
function createW3StorageSubscription (stripeSubscription, priceNamer) {
if (!stripeSubscription) {
return null
}
if (stripeSubscription.items.data.length > 1) {
throw new Error(`subscription ${stripeSubscription.id} has ${stripeSubscription.items.data?.length} items, but we only expect to ever see one.`)
}
// @todo - be more clever in ensuring this came from correct subscription item
// or consider throwing if there is more than one subscription item
const storagePrice = /** @type {StripePriceId} */ (stripeSubscription.items.data[0].price.id)
const storagePriceName = priceNamer.priceToName(storagePrice)
if (!storagePriceName) {
throw new Error(`unable to determien price name for stripe price ${storagePrice}`)
}
/** @type {import('./billing-types').W3PlatformSubscription['storage']} */
const storageSubscription = {
price: storagePriceName
}
return storageSubscription
}
/**
* @typedef {`price_${string}`} StripePriceId
*/
/**
* Get the environment variable that may hold the price id for a
* given storage price name
* @param {StoragePriceName} priceName
*/
export function createStripeStorageEnvVar (priceName) {
return `STRIPE_STORAGE_PRICE_${priceName.toUpperCase()}`
}
class EnvVarMissingError extends Error {}
/**
* @param {Record<string,any>} env
*/
export function createStripeStoragePricesFromEnv (env) {
/**
* @param {StoragePriceName} priceName
* @returns {StripePriceId}
*/
const readPriceNameVar = (priceName) => {
const varName = createStripeStorageEnvVar(priceName)
if (!(varName in env)) {
throw new EnvVarMissingError(`missing env var ${varName}`)
}
const priceId = /** @type {unknown} */ (env[varName])
if (typeof priceId !== 'string') {
throw new Error(`unable to read string value for env.${varName} for storage price name ${priceName}`)
}
return /** @type {StripePriceId} */ (priceId)
}
return new NamedStripePrices(/** @type {Record<StoragePriceName, string>} */ ({
[storagePriceNames.free]: readPriceNameVar(storagePriceNames.free),
[storagePriceNames.lite]: readPriceNameVar(storagePriceNames.lite),
[storagePriceNames.pro]: readPriceNameVar(storagePriceNames.pro)
}))
}