@yaks/stripe 0.0.0-stage → 0.2.36

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/plans.ts ADDED
@@ -0,0 +1,617 @@
1
+ // What Stripe sells a party as @yaks/host's `Plans`: a customer minted once,
2
+ // a subscription bought through Checkout and managed in the customer portal,
3
+ // its trial moved to give time free, a one-off Checkout in payment mode for
4
+ // something paid for once, and the events Stripe posts about either read into
5
+ // the host's words (`changed`, which ./doors.ts hears them with).
6
+ //
7
+ // Checkout runs under Managed Payments: Stripe is the merchant of record, so
8
+ // it sells, collects and remits the tax, and the parameters it controls
9
+ // (automatic_tax, payment_method_types, tax_id_collection, customer_update,
10
+ // invoice_creation) must not be sent at all, so none of them appear below.
11
+ // A plan paid by invoice (`invoice`) cannot be: Managed Payments covers no
12
+ // subscription made outside Checkout, so on those the account itself is the
13
+ // seller. Its invoices take whatever the account's invoice settings allow
14
+ // (card, bank transfer), and a check is marked paid in the Dashboard. Stripe
15
+ // calls such a subscription `active` before anything is paid, so its status is
16
+ // read with its latest invoice (`statusOf`), and it holds no plan until its
17
+ // first period is paid for.
18
+ //
19
+ // Which tier a subscription buys is read off its price, never off metadata a
20
+ // checkout wrote: a plan changed in the portal moves the price and nothing
21
+ // else. A price a tier no longer sells but keeps (`kept`), because a raise
22
+ // leaves its subscribers on what they signed up for, still buys that tier. A
23
+ // paying price no tier lists buys the first tier the options name, so a
24
+ // subscription made before a later tier existed reads as it did.
25
+ import type {
26
+ Bought,
27
+ Changed,
28
+ Per,
29
+ Plans,
30
+ Standing,
31
+ Subscription,
32
+ Tags,
33
+ } from 'jsr:@yaks/host@0.2.36/payments'
34
+ import { ask, found, idOf, type Keyed, list, minimum } from './mod.js'
35
+ import { checkout } from './checkout.js'
36
+ import { addOnPrice, invoiceMethods, invoiceOnce } from './invoices.js'
37
+ import { refund } from './refunds.js'
38
+
39
+ /** What a config gives the plans: the key and clock every call is made with
40
+ * (`Keyed`), each tier's price ids by how often it is paid for, in the order
41
+ * a price none lists falls back to the first of, and each tier's price ids it
42
+ * no longer sells but whose subscriptions are still on it. */
43
+ export type Options = Keyed & {
44
+ invoiceKey?: string
45
+ prices?: Record<string, Partial<Record<Per, string>>>
46
+ kept?: Record<string, string[] | undefined>
47
+ }
48
+
49
+ /** What a subscription's tier is read with. */
50
+ export type Pricing = Pick<Options, 'prices' | 'kept'>
51
+
52
+ // The slice of a Stripe invoice read here: whether it is paid, and whether
53
+ // it was for anything, which a trial's opening invoice is not.
54
+ export type Bill = { status?: string; total?: number }
55
+
56
+ // The slice of a Stripe subscription read here. Everything is optional: the
57
+ // shape is Stripe's to move, and a field that went missing must leave a
58
+ // readable row rather than a throw in the middle of somebody's billing.
59
+ export type Sub = {
60
+ id?: string
61
+ customer?: string | { id?: string }
62
+ status?: string
63
+ collection_method?: string
64
+ created?: number
65
+ start_date?: number
66
+ metadata?: Record<string, string>
67
+ cancel_at?: number | null
68
+ cancel_at_period_end?: boolean
69
+ canceled_at?: number | null
70
+ ended_at?: number | null
71
+ trial_end?: number | null
72
+ current_period_start?: number | null
73
+ current_period_end?: number | null
74
+ billing_cycle_anchor?: number
75
+ /** expanded where it is asked for; an id otherwise */
76
+ latest_invoice?: string | Bill | null
77
+ items?: {
78
+ data?: {
79
+ id?: string
80
+ metadata?: Tags
81
+ current_period_start?: number | null
82
+ current_period_end?: number | null
83
+ price?: string | {
84
+ id?: string
85
+ unit_amount?: number
86
+ recurring?: { interval?: string }
87
+ } | null
88
+ }[]
89
+ }
90
+ }
91
+
92
+ // `past_due` keeps the plan on purpose: Stripe retries a failed card for days
93
+ // before it gives up, and taking somebody's apps away on the first decline is
94
+ // the wall T-32756 says not to build. When Stripe does give up the status
95
+ // becomes `canceled` or `unpaid`. `incomplete` is a subscription whose first
96
+ // payment has not come. Stripe never moves a subscription out of `canceled`
97
+ // or `incomplete_expired`, which is what makes `ended` final.
98
+ let STANDING: Record<string, Standing> = {
99
+ active: 'paying',
100
+ trialing: 'paying',
101
+ past_due: 'owing',
102
+ incomplete: 'awaiting',
103
+ canceled: 'ended',
104
+ incomplete_expired: 'ended',
105
+ }
106
+
107
+ /// standing('trialing') -> 'paying'
108
+ /// standing('incomplete') -> 'awaiting'
109
+ /// standing('unpaid') -> 'lapsed'
110
+ /** Where a subscription with this status stands. */
111
+ export let standing = (status: string): Standing =>
112
+ Object.hasOwn(STANDING, status) ? STANDING[status] : 'lapsed'
113
+
114
+ /// when(0) -> '1970-01-01T00:00:00.000Z'
115
+ /// when(null) -> null
116
+ /** A Stripe time, in seconds, as an ISO date. */
117
+ export let when = (unix?: number | null): string | null =>
118
+ unix == null ? null : new Date(unix * 1000).toISOString()
119
+
120
+ /** When the paid-for period runs out. The field moved off the subscription
121
+ * onto each of its items in API version 2025-03-31.basil, and the webhook
122
+ * endpoint pins no version of its own, so the version it sends can move under
123
+ * us. Either shape is read: the latest item wins, since a subscription of
124
+ * these has one item. */
125
+ export let periodEnd = (sub: Sub): number | null => {
126
+ if (sub.current_period_end != null) return sub.current_period_end
127
+ let ends = (sub.items?.data ?? [])
128
+ .map((i) => i.current_period_end)
129
+ .filter((n): n is number => typeof n == 'number')
130
+ return ends.length ? Math.max(...ends) : null
131
+ }
132
+
133
+ /** When the current period began, read off either shape as `periodEnd`
134
+ * reads its end. */
135
+ export let periodStart = (sub: Sub): number | null => {
136
+ if (sub.current_period_start != null) return sub.current_period_start
137
+ let starts = (sub.items?.data ?? [])
138
+ .map((i) => i.current_period_start)
139
+ .filter((n): n is number => typeof n == 'number')
140
+ return starts.length ? Math.max(...starts) : null
141
+ }
142
+
143
+ /** Stripe's status for a subscription, with an invoiced one's invoice read
144
+ * into it. Stripe calls a subscription sent its invoices `active` the moment
145
+ * it is made and `past_due` once an invoice is late, and neither is a plan
146
+ * paid for. Its first billed period, the one starting when it was made or
147
+ * when its trial ends, holds once that period's invoice is paid: until then
148
+ * it is `incomplete`, as Stripe says of a charged subscription whose first
149
+ * payment has not come, and a trial given free (`trialFor`) is no payment.
150
+ * A later period holds while its invoice is not yet due, and one past due is
151
+ * `unpaid`: nothing retries a check. The latest invoice is read only where it
152
+ * was expanded, and one that was not is taken as unpaid. */
153
+ export let statusOf = (sub: Sub): string => {
154
+ let status = sub.status ?? ''
155
+ if (sub.collection_method != 'send_invoice') return status
156
+ if (status == 'past_due') return 'unpaid'
157
+ if (status != 'active' && status != 'trialing') return status
158
+ let bill = typeof sub.latest_invoice == 'object' ? sub.latest_invoice : null
159
+ let paid = bill?.status == 'paid' && (bill.total ?? 0) > 0
160
+ let first = (periodStart(sub) ?? 0) <=
161
+ (sub.trial_end ?? sub.start_date ?? sub.created ?? 0)
162
+ return first && !paid ? 'incomplete' : status
163
+ }
164
+
165
+ /** The tier a subscription's price buys: the first of `prices` listing one of
166
+ * its items' prices, else the first of `kept` listing one, else the first of
167
+ * `prices`. */
168
+ export let tierFor = (
169
+ sub: Sub,
170
+ { prices = {}, kept = {} }: Pricing = {},
171
+ ): string => {
172
+ let bought = (sub.items?.data ?? []).map((i) => idOf(i.price))
173
+ let buys = (ids: (string | undefined)[] = []) =>
174
+ ids.some((p) => !!p && bought.includes(p))
175
+ let found =
176
+ Object.entries(prices).find(([, by]) => buys(Object.values(by))) ??
177
+ Object.entries(kept).find(([, ids]) => buys(ids))
178
+ return found?.[0] ?? Object.keys(prices)[0] ?? ''
179
+ }
180
+
181
+ /** When a subscription with this status stops, set only when it will not
182
+ * renew, so "cancelled, but paid through the 14th" is one row to read: an
183
+ * explicit `cancel_at`, else the period end it is riding out, else, for one
184
+ * already over, when it ended. */
185
+ export let ending = (sub: Sub, status: string): string | null => {
186
+ let end = periodEnd(sub)
187
+ return when(
188
+ sub.cancel_at ??
189
+ (sub.cancel_at_period_end ? end : null) ??
190
+ (standing(status) == 'ended'
191
+ ? sub.ended_at ?? sub.canceled_at ?? end
192
+ : null),
193
+ )
194
+ }
195
+
196
+ let cadence = (sub: Sub, tier: string, pricing?: Pricing): Per | undefined => {
197
+ let prices = pricing?.prices?.[tier]
198
+ let items = sub.items?.data ?? []
199
+ let known = items.find(({ price }) =>
200
+ idOf(price) == prices?.month || idOf(price) == prices?.year
201
+ )
202
+ let id = idOf(known?.price)
203
+ if (id && id == prices?.year) return 'year'
204
+ if (id && id == prices?.month) return 'month'
205
+ let [only] = items
206
+ let interval = items.length == 1 && typeof only.price == 'object'
207
+ ? only.price?.recurring?.interval
208
+ : undefined
209
+ if (interval == 'month' || interval == 'year') return interval
210
+ }
211
+
212
+ /** A Stripe subscription in the host's words. */
213
+ export let read = (sub: Sub, pricing?: Pricing): Subscription => {
214
+ let status = statusOf(sub)
215
+ let tier = tierFor(sub, pricing)
216
+ let per = cadence(sub, tier, pricing)
217
+ return {
218
+ id: sub.id ?? '',
219
+ payer: idOf(sub.customer),
220
+ tier,
221
+ ...per ? { per } : {},
222
+ status,
223
+ until: when(periodEnd(sub)),
224
+ ending: ending(sub, status),
225
+ tags: { ...sub.metadata },
226
+ }
227
+ }
228
+
229
+ /** The trial a subscription bought while time given free runs starts with,
230
+ * so the free time is kept and the first charge falls when it ends. Stripe
231
+ * takes a trial ending no sooner than two days away, so one ending sooner is
232
+ * two days. */
233
+ export let trialFor = (
234
+ free: string | null | undefined,
235
+ now: number,
236
+ ): { trial_end?: number } =>
237
+ free
238
+ ? {
239
+ trial_end: Math.floor(
240
+ Math.max(Date.parse(free), now + 49 * 60 * 60_000) / 1000,
241
+ ),
242
+ }
243
+ : {}
244
+
245
+ // What a Stripe object was tagged with: its own metadata, over the copy of
246
+ // its subscription's an invoice carries under `parent`.
247
+ let tagsOf = (o: Record<string, unknown>): Tags => {
248
+ let parent = o.parent as
249
+ | { subscription_details?: { metadata?: Tags } }
250
+ | undefined
251
+ return {
252
+ ...parent?.subscription_details?.metadata,
253
+ ...o.metadata as Tags | undefined,
254
+ }
255
+ }
256
+
257
+ type Address = {
258
+ city?: string | null
259
+ state?: string | null
260
+ country?: string | null
261
+ }
262
+
263
+ type Event = {
264
+ type?: string
265
+ created?: number
266
+ livemode?: boolean
267
+ data?: { object?: Record<string, unknown> }
268
+ }
269
+
270
+ /** The tax code a one-off purchase is sold under: artificial intelligence as
271
+ * a service, cloud based, for business use, which Managed Payments takes
272
+ * (its eligibility page). A product made inline carries its own. */
273
+ export let ONCE_TAX = 'txcd_10105002'
274
+
275
+ let path = (subscription: string) =>
276
+ `/v1/subscriptions/${encodeURIComponent(subscription)}`
277
+
278
+ // A subscription with its latest invoice, which an invoiced one is read by.
279
+ let EXPAND = { expand: ['latest_invoice'] }
280
+ let expanded = (subscription: string) =>
281
+ `${path(subscription)}?expand[]=latest_invoice`
282
+
283
+ /** Stripe's plans, every call made with `options` as they read at the
284
+ * time. */
285
+ export let plans = (options: Options): Plans => {
286
+ let now = () => options.clock?.now() ?? Date.now()
287
+ let invoicing = (): Keyed => ({
288
+ key: options.invoiceKey,
289
+ clock: options.clock,
290
+ })
291
+ let price = (tier: string, per: Per) => options.prices?.[tier]?.[per]
292
+ let subscription = async (id: string) => {
293
+ let sub = await found(options, expanded(id)) as Sub | null
294
+ return sub && read(sub, options)
295
+ }
296
+ let charges = async (id: string) => {
297
+ let sub = await ask(options, path(id)) as Sub
298
+ let end = Math.max(sub.trial_end ?? 0, periodEnd(sub) ?? 0)
299
+ return end ? new Date(end * 1000).toISOString() : null
300
+ }
301
+ return {
302
+ on: () => !!options.key,
303
+ offers: (tier, per) => !!options.key && !!price(tier, per),
304
+ standing,
305
+ payer: async ({ email, name, tags, key }) => {
306
+ let made = await ask(
307
+ options,
308
+ '/v1/customers',
309
+ {
310
+ email,
311
+ name,
312
+ metadata: tags,
313
+ },
314
+ undefined,
315
+ 'POST',
316
+ key,
317
+ )
318
+ let customer = String(made.id ?? '')
319
+ if (!customer) throw new Error('stripe made a customer with no id')
320
+ return customer
321
+ },
322
+ billed: async (payer) => {
323
+ let c = await ask(options, `/v1/customers/${encodeURIComponent(payer)}`)
324
+ return c.deleted
325
+ ? null
326
+ : { email: String(c.email ?? ''), name: String(c.name ?? '') }
327
+ },
328
+ checkout: async (asked) => {
329
+ let bought = price(asked.tier, asked.per)
330
+ if (!bought) {
331
+ throw new Error(
332
+ `stripe has no price for ${asked.tier} by the ${asked.per}`,
333
+ )
334
+ }
335
+ // Everything here survives Managed Payments, verified against the
336
+ // account rather than assumed: the reference rides
337
+ // `client_reference_id` for the session and the tags ride
338
+ // `subscription_data[metadata]` for the subscription, which every later
339
+ // `customer.subscription.*` event is read by. `allow_promotion_codes`
340
+ // puts the code box on Stripe's page, the only place one belongs, since
341
+ // Stripe is the seller and owns the price it charges.
342
+ return await checkout(options, asked, {
343
+ mode: 'subscription',
344
+ customer: asked.payer,
345
+ line_items: { 0: { price: bought, quantity: 1 } },
346
+ success_url: asked.done,
347
+ cancel_url: asked.cancel,
348
+ client_reference_id: asked.reference,
349
+ metadata: asked.tags,
350
+ subscription_data: {
351
+ metadata: asked.tags,
352
+ ...trialFor(asked.trial, now()),
353
+ },
354
+ managed_payments: { enabled: true },
355
+ allow_promotion_codes: true,
356
+ })
357
+ },
358
+ // A subscription sent its invoices rather than charged, made here and not
359
+ // at Checkout: the invoices go to the customer's email, so the address
360
+ // asked for becomes the customer's, and its name the organization's
361
+ // where one is given. No payment method is named, so the invoice offers
362
+ // what the account's invoice settings do. Stripe finalizes the first
363
+ // invoice within the hour and emails it; each renewal's is sent the day
364
+ // the period turns, due `due` days on. It is answered with its first
365
+ // invoice, unpaid, so it reads as awaiting it (`statusOf`).
366
+ invoice: async (asked) => {
367
+ let bought = price(asked.tier, asked.per)
368
+ if (!bought) {
369
+ throw new Error(
370
+ `stripe has no price for ${asked.tier} by the ${asked.per}`,
371
+ )
372
+ }
373
+ await ask(options, `/v1/customers/${encodeURIComponent(asked.payer)}`, {
374
+ email: asked.to.email,
375
+ name: asked.to.name || undefined,
376
+ })
377
+ let addOn = asked.addOn
378
+ let start = addOn && Date.parse(addOn.start) / 1000
379
+ let renewal = addOn && Date.parse(addOn.renewal) / 1000
380
+ let future = start != null && start > now() / 1000
381
+ let contract = addOn
382
+ ? {
383
+ payment_settings: invoiceMethods,
384
+ billing_cycle_anchor: renewal,
385
+ ...(future ? { trial_end: start } : { backdate_start_date: start }),
386
+ }
387
+ : trialFor(asked.trial, now())
388
+ let made = await ask(
389
+ options,
390
+ '/v1/subscriptions',
391
+ {
392
+ customer: asked.payer,
393
+ items: [
394
+ { price: bought, quantity: 1 },
395
+ ...addOn ? [await addOnPrice(invoicing(), addOn)] : [],
396
+ ],
397
+ collection_method: 'send_invoice',
398
+ days_until_due: asked.due,
399
+ metadata: asked.tags,
400
+ ...contract,
401
+ ...EXPAND,
402
+ },
403
+ undefined,
404
+ 'POST',
405
+ asked.key,
406
+ ) as Sub
407
+ if (!made.id) throw new Error('stripe made a subscription with no id')
408
+ return {
409
+ subscription: read(made, options),
410
+ at: when(made.created) ?? new Date(now()).toISOString(),
411
+ }
412
+ },
413
+ invoicingOn: () => !!options.key && !!options.invoiceKey,
414
+ addOn: async (id, item) => {
415
+ let sub = await ask(options, path(id)) as Sub
416
+ let items = sub.items?.data ?? []
417
+ let held = items.find((it) => it.metadata?.yaks_add_on == item.key)
418
+ let tier = tierFor(sub, options)
419
+ if (
420
+ sub.collection_method != 'send_invoice' ||
421
+ cadence(sub, tier, options) != 'year' ||
422
+ sub.status == 'canceled' || sub.status == 'incomplete_expired'
423
+ ) {
424
+ return 'Support contracts require a yearly plan paid by invoice.'
425
+ }
426
+ let end = when(periodEnd(sub))?.slice(0, 10)
427
+ if (end != item.renewal) {
428
+ return `The yearly plan renews on ${
429
+ end ?? 'an unknown date'
430
+ }. Use the plan renewal date.`
431
+ }
432
+ if (
433
+ typeof held?.price == 'object' && held.price?.unit_amount == item.cents
434
+ ) return null
435
+ let price = await addOnPrice(invoicing(), item)
436
+ await ask(
437
+ options,
438
+ path(id),
439
+ {
440
+ items: [{ ...price, id: held?.id }],
441
+ payment_settings: invoiceMethods,
442
+ proration_behavior: held ? 'none' : 'create_prorations',
443
+ },
444
+ undefined,
445
+ 'POST',
446
+ `add-on|${id}|${item.key}|${idOf(held?.price)}|${item.cents}`,
447
+ )
448
+ return null
449
+ },
450
+ invoiceOnce: (asked) => invoiceOnce(invoicing(), asked),
451
+ minimum,
452
+ // Payment mode under Managed Payments, the price made inline with its
453
+ // tax code and tax included, as every price here is: no dashboard price
454
+ // to keep in step. The tags ride the session's own metadata, which the
455
+ // event saying it was paid carries back whole.
456
+ once: async (asked) => {
457
+ let made = await ask(options, '/v1/checkout/sessions', {
458
+ mode: 'payment',
459
+ customer: asked.payer,
460
+ line_items: {
461
+ 0: {
462
+ price_data: {
463
+ currency: asked.currency.toLowerCase(),
464
+ unit_amount: asked.cents,
465
+ tax_behavior: 'inclusive',
466
+ product_data: { name: asked.name, tax_code: ONCE_TAX },
467
+ },
468
+ quantity: 1,
469
+ },
470
+ },
471
+ success_url: asked.done,
472
+ cancel_url: asked.cancel,
473
+ client_reference_id: asked.reference,
474
+ metadata: asked.tags,
475
+ payment_intent_data: { metadata: asked.tags },
476
+ managed_payments: { enabled: true },
477
+ })
478
+ let url = String(made.url ?? '')
479
+ if (!url) throw new Error('stripe made a checkout session with no url')
480
+ return url
481
+ },
482
+ // The session names the payment it made and what it took, and the
483
+ // refund is made on the platform's own account.
484
+ refunded: async ({ key, checkout, tags, cents }) => {
485
+ let session = await ask(
486
+ options,
487
+ `/v1/checkout/sessions/${encodeURIComponent(checkout)}`,
488
+ )
489
+ let payment = idOf(
490
+ session.payment_intent as string | { id?: string } | undefined,
491
+ )
492
+ if (!payment) throw new Error(`stripe holds no payment for ${checkout}`)
493
+ return await refund(options, undefined, {
494
+ key,
495
+ payment,
496
+ amount: cents ?? Number(session.amount_total ?? 0),
497
+ tags,
498
+ })
499
+ },
500
+ // The portal needs a configuration on the account; without one Stripe
501
+ // refuses, and the refusal throws.
502
+ portal: async (payer, back) => {
503
+ let made = await ask(options, '/v1/billing_portal/sessions', {
504
+ customer: payer,
505
+ return_url: back,
506
+ })
507
+ let url = String(made.url ?? '')
508
+ if (!url) throw new Error('stripe made a portal session with no url')
509
+ return url
510
+ },
511
+ subscription,
512
+ subscriptions: async (payer) => {
513
+ let out: Subscription[] = []
514
+ for await (
515
+ let sub of list<Sub & { id: string }>(options, '/v1/subscriptions', {
516
+ customer: payer,
517
+ status: 'all',
518
+ 'expand[]': 'data.latest_invoice',
519
+ })
520
+ ) out.push(read(sub, options))
521
+ return out
522
+ },
523
+ charges,
524
+ // The trial set to end then, prorating nothing.
525
+ postpone: async (id, until) => {
526
+ let next = await charges(id)
527
+ if (next && Date.parse(next) >= Date.parse(until)) return
528
+ await ask(options, path(id), {
529
+ trial_end: Math.floor(Date.parse(until) / 1000),
530
+ proration_behavior: 'none',
531
+ })
532
+ },
533
+ }
534
+ }
535
+
536
+ /** A verified event Stripe posted to the platform's own endpoint, read: a
537
+ * `customer.subscription.*` event carries its subscription whole, save an
538
+ * invoiced one's latest invoice, so that one is asked for with it, and a
539
+ * checkout session or an invoice names it, which one GET answers. An
540
+ * invoice's name for it moved under `parent` in API 2025-03-31.basil, and the
541
+ * old field is read too, for the reason `periodEnd` reads both. A checkout
542
+ * session in payment mode is a purchase: completed, its money there or on
543
+ * its way, and `checkout.session.async_payment_succeeded` when what was on
544
+ * its way arrives. */
545
+ export let changed =
546
+ (options: Options) => (event: unknown): Changed | Bought => {
547
+ let e = (event ?? {}) as Event
548
+ let o = e.data?.object ?? {}
549
+ let reference = o.client_reference_id
550
+ let now = options.clock?.now() ?? Date.now()
551
+ let at = new Date((e.created ?? Math.floor(now / 1000)) * 1000)
552
+ .toISOString()
553
+ let live = e.livemode !== false
554
+ let referred = typeof reference == 'string' && reference
555
+ ? { reference }
556
+ : {}
557
+ let details = e.type == 'checkout.session.completed'
558
+ ? o.customer_details as
559
+ | { name?: string; email?: string; address?: Address }
560
+ | undefined
561
+ : undefined
562
+ let payer = typeof details?.name == 'string' && details.name.trim()
563
+ ? {
564
+ payerName: {
565
+ name: details.name,
566
+ ...typeof details.email == 'string' ? { email: details.email } : {},
567
+ },
568
+ }
569
+ : {}
570
+ if ((e.type ?? '').startsWith('checkout.session.') && o.mode == 'payment') {
571
+ return {
572
+ about: 'purchase',
573
+ at,
574
+ live,
575
+ checkout: String(o.id ?? ''),
576
+ paid: o.payment_status == 'paid',
577
+ tags: tagsOf(o),
578
+ ...referred,
579
+ ...payer,
580
+ }
581
+ }
582
+ let parent = (o.parent ?? {}) as {
583
+ subscription_details?: { subscription?: string | { id?: string } }
584
+ }
585
+ let itself = (e.type ?? '').startsWith('customer.subscription.')
586
+ let whole = itself && o.collection_method != 'send_invoice'
587
+ let named = idOf(
588
+ itself
589
+ ? o.id as string | undefined
590
+ : (o.subscription as string | { id?: string } | undefined) ??
591
+ parent.subscription_details?.subscription,
592
+ )
593
+ // A completed checkout says where its payer is billed, when Stripe asked
594
+ // (under Managed Payments, what tax needs: at least the country). Only
595
+ // the town, state and country are read of it.
596
+ let address = details?.address
597
+ let billed = address && Object.fromEntries(
598
+ (['city', 'state', 'country'] as const).flatMap((k) =>
599
+ address[k] ? [[k, String(address[k])]] : []
600
+ ),
601
+ )
602
+ return {
603
+ about: 'subscription',
604
+ at,
605
+ live,
606
+ tags: tagsOf(o),
607
+ ...referred,
608
+ ...payer,
609
+ ...billed && Object.keys(billed).length ? { billed } : {},
610
+ subscription: () =>
611
+ whole
612
+ ? Promise.resolve(read(o as Sub, options))
613
+ : named
614
+ ? plans(options).subscription(named)
615
+ : Promise.resolve(undefined),
616
+ }
617
+ }
package/refunds.js ADDED
@@ -0,0 +1,65 @@
1
+ // A refund made once, on the platform's own account or a seller's (`on`):
2
+ // its request key rides the refund's metadata as well as the idempotency
3
+ // header, so a request asked again after Stripe forgot the header still
4
+ // finds the refund it made.
5
+ import { ask, idOf } from "./mod.js";
6
+ /** A refund read from Stripe's create response or its verified event. */ export let refundedOf = (o)=>({
7
+ id: String(o.id ?? ''),
8
+ payment: idOf(o.payment_intent),
9
+ amount: Number(o.amount ?? 0),
10
+ status: o.status == 'succeeded' ? 'succeeded' : o.status == 'failed' ? 'failed' : o.status == 'canceled' ? 'canceled' : 'pending',
11
+ tags: {
12
+ ...o.metadata ?? {}
13
+ }
14
+ });
15
+ // Stripe retains idempotency keys for a day. The refund's own metadata keeps
16
+ // recovery safe after that window, including a lost create response.
17
+ let priorRefund = async (options, on, request)=>{
18
+ let after = '';
19
+ for(;;){
20
+ let query = new URLSearchParams({
21
+ payment_intent: request.payment,
22
+ limit: '100',
23
+ ...after ? {
24
+ starting_after: after
25
+ } : {}
26
+ });
27
+ let page = await ask(options, `/v1/refunds?${query}`, undefined, on);
28
+ if (!Array.isArray(page.data) || typeof page.has_more != 'boolean') {
29
+ throw new Error('stripe returned an invalid refund list');
30
+ }
31
+ let rows = page.data;
32
+ let old = rows.find((r)=>r.metadata?.request == request.key);
33
+ if (old) {
34
+ let refund = refundedOf(old);
35
+ if (refund.amount != request.amount || refund.payment != request.payment) throw new Error('stripe refund request identity was reused');
36
+ return refund;
37
+ }
38
+ if (!page.has_more) return null;
39
+ let next = String(rows?.at(-1)?.id ?? '');
40
+ if (!next || next == after) {
41
+ throw new Error('stripe refund list did not advance');
42
+ }
43
+ after = next;
44
+ }
45
+ };
46
+ /** Refund `request` on the account `on` (the platform's own where none),
47
+ * returning the application fee in proportion where it says `fee`. Asked
48
+ * again with the same key and request, it refunds nothing twice. */ export let refund = async (options, on, request)=>{
49
+ let old = await priorRefund(options, on, request);
50
+ if (old) return old;
51
+ let made = refundedOf(await ask(options, '/v1/refunds', {
52
+ payment_intent: request.payment,
53
+ amount: request.amount,
54
+ ...request.fee ? {
55
+ refund_application_fee: true
56
+ } : {},
57
+ metadata: {
58
+ ...request.tags,
59
+ request: request.key
60
+ }
61
+ }, on, 'POST', request.key));
62
+ if (!made.id) throw new Error('stripe made a refund with no id');
63
+ return made;
64
+ };
65
+ //# sourceMappingURL=refunds.js.map
package/refunds.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"refunds.js","sources":["./refunds.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,yEAA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